簡體   English   中英

如何動態擴充布局?

[英]How to inflate a layout dynamically?

我在XML中定義了以下布局:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/streamRelativeLayout">
        <ListView android:layout_height="fill_parent" android:layout_width="fill_parent" android:id="@+id/streamListView"></ListView>
        <ProgressBar android:layout_centerInParent="true" android:layout_height="wrap_content" android:id="@+id/streamProgressBar" android:layout_width="wrap_content"></ProgressBar>
    </RelativeLayout>

如何使用LayoutInflater來獲取ListView和ProgressBar並在代碼中分配它?

通過這種方式:

View v = getLayoutInflater().inflate(R.layout.YOUR_LAYOUT_ID, null);
ListView listview = (ListView) v.findViewById(R.id.streamListView);
ProgressBar progress = (ProgressBar) v.findViewById(R.id.streamProgressBar);

您只需要活動參考並致電:

RelativeLayout relativeLayout = (RelativeLayout)activity.getLayoutInflater().inflate(R.layout.your_layout, null);

然后你可以使用它們的id獲取兩個視圖

relativeLayout.findViewById(R.id.anId);

試試這個

RelativeLayout myLayout = (RelativeLayout)getLayoutInflater().inflate(
                R.layout.you_xml_id, null);

        ListView list = (ListView)myLayout.findViewById(R.id.streamListView);
        ProgressBar bar = (ProgressBar)myLayout.findViewById(R.id.streamProgressBar);
private LayoutInflater mInflater;
View convertView;
mInflater = LayoutInflater.from(context);
convertView = mInflater.inflate(R.xml.yourxmlname, null);

現在你可以通過訪問這些項目了

convertView.findViewById

或者如果你有很多實例,你可以定義一個視圖

static class CalViewHolder {
    ListView con_list;
    Progressbar con_progress;
}
holder = new CalViewHolder();
convertView.setTag(holder);

暫無
暫無

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

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