Thursday, June 9, 2011

ViewSwitcher in Android - switching layouts for activity

Let us say you want to change the layout in same activity e.g. you want to show a list of urls and when one of them is clicked, you want to show webview on the entire screen. One solution could be to use a dialog, but a dialog will not use the screen area effectively.
In such cases you can use ViewSwitcher.  A viewswitcher can have two child views and only one of them is shown at a time.
The two views you want to use must be wrapped in the viewswitcher  as shown in the xml file below.
<?xml version="1.0" encoding="utf-8"?>
<ViewSwitcher
   xmlns:android="http://schemas.android.com/apk/res/android"
       android:id = "@+id/viewswitcher"
   ---
   -----
>
 <LinearLayout
    android:layout_width="fill_parent"
    ------->
   
    <GridView 
        android:layout_width="fill_parent"
         -------------------
        ------------------->
    </GridView>     
</LinearLayout>
<LinearLayout
    android:layout_width="fill_parent"
     ------------------>
   
    <WebView
    android:layout_width="fill_parent"
   ---------------------->
    </WebView>
 </LinearLayout>
 
</ViewSwitcher>

In this xml file, the two linear layouts are child views of view switcher. One of them has a gridview and the other has a webview.

Add this line in your onCreate function of the activity to get the viewSwitcher from xml

mViewSwitcher = (ViewSwitcher)findViewById(R.id.viewSwitcher1);

To start with, first child view will be shown. Now you can display the other child view, in this case webview by calling viewswitcher.showNext() and viewswitcher.showPrevious()

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
            -------
            mViewSwitcher.showNext();
                               -------
        }
@Override
    public void onBackPressed(){
        if(mWebView.isShown()){
             mViewSwitcher.showPrevious();
           ---------
        }
    }


No comments:

Post a Comment