如何动态膨胀布局?

Posted

技术标签:

【中文标题】如何动态膨胀布局?【英文标题】:How to inflate a layout dynamically? 【发布时间】:2011-08-29 13:21:36 【问题描述】:

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

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

如何使用 LayoutInflater 抓取 ListView 和 ProgressBar 并在代码中分配?

【问题讨论】:

【参考方案1】:

这样:

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

【讨论】:

【参考方案2】:

您只需要活动引用并调用:

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

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

relativeLayout.findViewById(R.id.anId);

【讨论】:

我有动态创建的 linaerlayout,即 LinearLayout ll=new LinearLayout(context);这个布局有一些子视图,如 framelayout、webview。现在,我怎样才能膨胀这个线性布局? 避免将 null 作为视图根传递(需要解析膨胀布局的根元素上的布局参数),因为当膨胀布局时,避免将 null 作为父视图传递,否则在膨胀布局的根将被忽略。【参考方案3】:
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);

【讨论】:

【参考方案4】:

试试这个

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

【讨论】:

以上是关于如何动态膨胀布局?的主要内容,如果未能解决你的问题,请参考以下文章

如何动态地将按钮添加到视图以使布局宽度正常工作?

Android片段布局完成膨胀

你如何在片段中膨胀动态创建的对象?

无法在 Android 中的 XML 中设置膨胀视图的布局宽度、高度和重量

动态添加视图并设置参数和规则无法正常工作(android)

创建新视图时动态隐藏视图