Search code examples
javaandroidxmllayoutviewgroup

Is it possible to set content view of a single view group within the code?


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..


Solution

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