8

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?

Sheehan Alam
  • 60,111
  • 124
  • 355
  • 556

4 Answers4

31

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);
BFil
  • 12,966
  • 3
  • 44
  • 48
7

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);
martiall
  • 981
  • 6
  • 7
  • I am having the dynamically created linaerlayout that is LinearLayout ll=new LinearLayout(context); this layout having some subviews like framelayout, webview. Now, how can I inflate this linearlayout.? – Karthick Apr 18 '13 at 05:54
  • 1
    Avoid passing null as the view root (needed to resolve layout parameters on the inflated layout's root element) because When inflating a layout, avoid passing in null as the parent view, since otherwise any layout parameters on the root of the inflated layout will be ignored. – AMI CHARADAVA Apr 04 '17 at 10:42
1
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);
2red13
  • 11,197
  • 8
  • 40
  • 52
0

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);
Niranj Patel
  • 32,980
  • 10
  • 97
  • 133