Here in our example we will consider two Layouts and we will display only one which ever is necessary.
Let us add textView in first Layout which has the text Internet Connection is Available, when Internet Connection is Available. The other Layout has a textView which has the text Internet Connection is Unavailable.
Designing View Switcher in xml file
The Layout begins with View Switcher and two different Layouts inside it.
- <ViewSwitcher xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/ViewSwitcher1"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <TextView
- android:id="@+id/textView1"
- android:text="Internet Connection is Available"
- ....
- android:textStyle="bold" />
- </LinearLayout>
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <TextView
- android:id="@+id/textView2"
- android:text="Internet Connection is Unavailable"
- ....
- android:textStyle="bold" />
- </LinearLayout>
- </ViewSwitcher>
How to switch between Layouts.
showNext and showPrevious can help you switch between Layouts.
- switcher.showNext(); /* Displays second Layout */
- switcher.showPrevious(); /* Displays First Layout when Second Layout is in Display*/
How can we use it in the Program.
In my example i have a method isOnline which returns true when the Internet connection is Available and returns false when the Internet connection is Unavailable. Using this we will show first Layout when isOnline returns true and display second Layout when isOnline returns false.
- import android.net.ConnectivityManager;
- ....
- import android.widget.ViewSwitcher;
- public class MainActivity extends Activity {
- private ViewSwitcher switcher; /* declaring switcher */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- switcher = (ViewSwitcher) findViewById(R.id.ViewSwitcher1); /* ViewSwitcher1 is Switcher in xml layout */
- if(isOnline()){ /* Checks Condition, if true */
- /* Displays Default Layout */
- }else{ /* when the method 'isOnline' returns false Next Layout will be displayed */
- switcher.showNext();
- }
- }
- /* A Method to identify weather Internet Connection is Active or not */
- /* This will return true if Connection is Available else will return false */
- public boolean isOnline() {
- ConnectivityManager cm =
- (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo netInfo = cm.getActiveNetworkInfo();
- if (netInfo != null && netInfo.isConnectedOrConnecting()) {
- return true;
- }
- return false;
- } /* Method Ends */
- }
No comments:
Post a Comment