2011-05-20 115 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);