How to inflate a layout dynamically?

巧了我就是萌 提交于 2019-12-19 03:14:06

问题


I have the following layout defined in 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>

How can I use the LayoutInflater to grab the ListView and the ProgressBar and assign it in code?


回答1:


In this way:

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:


You just need the activity reference and call :

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

Then you can grab the two view using their ids

relativeLayout.findViewById(R.id.anId);



回答3:


try this

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



回答4:


private LayoutInflater mInflater;
View convertView;
mInflater = LayoutInflater.from(context);
convertView = mInflater.inflate(R.xml.yourxmlname, null);

now you can access the items by

convertView.findViewById

or if you hav lots of Instances, you may define a viewholder

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


来源:https://stackoverflow.com/questions/6070527/how-to-inflate-a-layout-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!