3

I want to know whether it is possible to use an xml layout file to define the content of a view dynamically from within the code. When we start an activity we pass it the xml layout to use with the method call setContentView(R.layout.main); but is it possible to use an xml layout file to define a dynamically created ViewGroup such as LinearLayout?

I have a layout xml which shows a score table for a game. Each score that is displayed on this screen needs to be dynamically added via code. I know that it is possible within the code to create a ViewGroup for this score and populate it with all the things I need to make a single score, and then do this every time for each score, and then add them all to the existing UI structure, already defined in the xml layout. What I would like to know is if it is possible to use another xml file to do this?

For example, a layout xml file:

<LinearLayout android:id="@+id/top">
  <LinearLayout android:id="@+id/column_heading"/>
</LinearLayout>

In another xml layout file is something like:

<LinearLayout android:id="@+id/row">
  <TextView/>
  <TextView/>
  <TextView/>
  <TextView/>
</LinearLayout>

Within the code I would like to do something like the following:

LinearLayout top = (LinearLayout)findViewById(R.id.top);
for (int i = 0; i < num_of_rows; i++) {
  LinearLayout row = new LinearLayout(this);
  row.setContentView(R.layout.row);  //where R.layout.row is the second layout above
  // ... dynamically change values as needed
  top.addView(row);
}

However .setContentView(...) is not a valid method of LinearLayout. Is there another way to do this? I know I could do it all by code, but that's rather messy and this way would seem to be very tidy and rational..

Caleb
  • 524
  • 5
  • 18

3 Answers3

2

You should use LayoutInflater for this. Here is a short example

LinearLayout top = (LinearLayout)findViewById(R.id.top);
for (int i = 0; i < num_of_rows; i++) {
    LayoutInflater inflater = LayoutInflater.from(this);
    LinearLayout row = (LinearLayout)inflater.inflate(R.layout.row, null);    
    // ... dynamically change values as needed
    top.addView(row);
}
inazaruk
  • 74,247
  • 24
  • 188
  • 156
1
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.row, null);
jamapag
  • 9,290
  • 4
  • 34
  • 28
1

You can use LayoutInflater's inflate method to inflate an arbitrary layout from resources. If you provide a root view parameter to this method, the inflated layout will be contained within it. This way you can inflate the XML view into your row.

Xion
  • 22,400
  • 10
  • 55
  • 79