簡體   English   中英

有效地使用布局充氣機

[英]Effectively using Layout-inflator

假設我想要一個帶有2個復選框的自定義視圖。 我會開始創建一個這樣的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="CheckBox" />

<CheckBox
    android:id="@+id/checkBox2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="CheckBox" />

</LinearLayout>

然后創建一個擴展FrameLayout的View,使用layout-inflator添加布局:

mInflate.inflate(R.layout.foo, this, true);

這種方法的問題在於我嵌套2個布局只是為了擁有一個帶有2個復選框的非常基本的視圖。 由於我目前正在開發一個非常復雜的布局,我正在尋找一種方法來避免在使用布局充氣器時不必要的布局嵌套。

動態創建CheckBox:

CheckBox checkBox1 = new CheckBox(this); // or getActivity() depending on code context
CheckBox checkBox2 = new CheckBox(this);
checkBox1.setText("CheckBox");
etc.
frameLayout.addView(child1);
frameLayout.addView(child2);

您可以在xml布局中使用merge標記,然后對其進行充氣:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">

<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="CheckBox" />

<CheckBox
    android:id="@+id/checkBox2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="CheckBox" />

</merge>

FrameLayout可能不是您布局的最佳解決方案,因為它會將視圖疊加在另一個上面。

暫無
暫無

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

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