簡體   English   中英

Android-在布局之間切換

[英]Android - Switch between layouts

我有兩種布局,當用戶單擊按鈕時,在兩種布局之間切換的最佳方法是什么?

您可以在ButtonClick上調用setContentView(R.layout.layout2)

最好的方法是使用android.widget.ViewFlipper 有了它,您可以創建與xml不同的布局,然后使用如下所示的簡單方法在它們之間切換:

   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示例:

     <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>

使用ViewSwitcher。

  1. 制作一個包含兩個布局的布局文件。 您的兩個布局應放置在viewswitcher中。

  2. 關聯一個onclick偵聽器,該按鈕將兩個布局切換到一個按鈕。

如果您將兩個布局分別放在不同的文件中,則可以在布局xml文件中使用標記。

創建片段並在運行時將其放入布局后,請使用“片段管理器”,或者使用“查看尋呼機”,因為它也可以增加交換效果。 不要在不清除先前布局的情況下使用setContentView(R.layout.your_layout)(使用“ gone”或“ clear”)更改運行時的布局,因為這會降低您的應用程序的速度(因為現在有兩個布局在運行)甚至創建應用程序的混亂。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM