2011-05-20 114 views
3

我在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控件和進度,並在代碼分配呢?

回答

19

這樣搶兩個視圖

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

你只需要在活動參考,並調用:

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); 
+0

我有動態創建的linaerlayout是的LinearLayout ll =新的LinearLayout(上下文);這個佈局有一些子視圖,比如framelayout,webview。現在,我怎樣才能使這個線性佈局膨脹? – Karthick 2013-04-18 05:54:30

+1

由於 避免傳遞null作爲視圖根(需要解析膨脹佈局的根元素上的佈局參數),因此在膨脹佈局時,請避免在父視圖中傳入null,因爲否則在膨脹佈局的根上的任何佈局參數都會被忽略。 – 2017-04-04 10:42:00

0

試試這個:

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

然後你就可以使用它們的ID

relativeLayout.findViewById(R.id.anId); 
0
private LayoutInflater mInflater; 
View convertView; 
mInflater = LayoutInflater.from(context); 
convertView = mInflater.inflate(R.xml.yourxmlname, null); 

現在你可以通過

convertView.findViewById 

訪問的項目,或者如果你甲肝大量的實例,你可以定義viewholder

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