开发者

Android - Switch between layouts

开发者 https://www.devze.com 2023-04-04 09:25 出处:网络
I have two layouts, what开发者_运维知识库 is the best way to switch between the two layouts when a user clicks on a button?You could call setContentView(R.layout.layout2) on ButtonClickThe best way is

I have two layouts, what开发者_运维知识库 is the best way to switch between the two layouts when a user clicks on a button?


You could call setContentView(R.layout.layout2) on ButtonClick


The best way is to use android.widget.ViewFlipper. With it you can create different layout from xml and then switch among them with simple method like this:

   ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.myViewFlipper);

   // you can switch between next and previous layout and display it
   viewFlipper.showNext();
   viewFlipper.showPrevious();

  // or you can switch selecting the layout that you want to display
  viewFlipper.setDisplayedChild(1);
  viewFlipper.setDisplayedChild(viewFlipper.indexOfChild(findViewById(R.id.secondLayout)

Xml example with tree layouts:

     <ViewFlipper
            android:id="@+id/myViewFlipper"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <LinearLayout
                android:id="@+id/firstLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical" >
               [...]
            </LinearLayout>

            <LinearLayout
                android:id="@+id/secondLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical" >
               [...]
            </LinearLayout>

            <LinearLayout
                android:id="@+id/thirdLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical" >
              [...]
            </LinearLayout>
      </ViewFlipper>


Use ViewSwitcher.

  1. make one layout file that includes two layouts. your two layouts should be place in viewswitcher.

  2. associate an onclick listener that switch two layout with a button.

if you separate two layouts in different file, you can use tag in layout xml file.


Use "fragment manager" after creating fragments and putting your layouts into it on run time or "view pager" as it can also add swapping effect. Do not use setContentView(R.layout.your_layout) without clearing the previous layout (use "gone" or "clear") for changing layout on run time as it slows down your app (because now there are two layout running) and even creates confusion for the app.

0

精彩评论

暂无评论...
验证码 换一张
取 消