7

我在 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 并在代码中分配它?

4

4 回答 4

30

这样:

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);
于 2011-05-20T10:32:16.083 回答
7

您只需要活动参考并调用:

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

然后您可以使用它们的 id 获取两个视图

relativeLayout.findViewById(R.id.anId);
于 2011-05-20T10:29:04.920 回答
1
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);
于 2011-05-20T10:32:43.570 回答
0

试试这个

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);
于 2011-05-20T10:32:20.197 回答