Peter
Peter

Reputation: 161

Android - Adding layouts to a parent layout

I have 2 layout xml files: "highlights.xml" and "highlights_cell.xml".

Here is a simplified version of each. I've removed the width/height/etc and just kept the important attributes...

highlights.xml

<LinearLayout>
  <uk.co.jasonfry.android.tools.ui.SwipeView android:id="@+id/swipe_view" />
  <uk.co.jasonfry.android.tools.ui.PageControl android:id="@+id/page_control" />
</LinearLayout>

highlights_cell.xml

<LinearLayout android:orientation="vertical">
  <LinearLayout android:id="@+id/linear_layout1" android:orientation="horizontal">
    <ImageView android:id="@+id/logo" />
    <LinearLayout android:id="@+id/linear_layout2" android:orientation="vertical">
      <TextView android:id="@+id/title" />
      <TextView android:id="@+id/subtitle" />
    </LinearLayout>
  </LinearLayout>

  <ScrollView android:id="@+id/scroll_view">
    <TextView android:id="@+id/description" />
  </ScrollView>
</LinearLayout>

The idea is that I want to add several "highlights_cell" to "highlights" through a loop.

I've thrown together some test code as follows but, as it's not working, I suspect that I'm not adding the cell layouts correctly, or perhaps I shouldn't be using "inflater"...

/** Declare shared variables */
SwipeView mSwipeView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){

    //Initialise layout and variables
    super.onCreate(savedInstanceState);
    setContentView(R.layout.highlights);

    //Setup controls
    mSwipeView = (SwipeView) findViewById(R.id.swipe_view);

    LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);

    //Loop through collection and add views
    for(int i=0; i<7;i++)
    {
        //Create the itemView to use layout xml for each cell  
        View itemView = inflater.inflate(R.layout.highlights_cell, null);

        //Set values within cell
        TextView title = (TextView) itemView.findViewById(R.id.title);
        title.setText("HELLO WORLD_" + i);

        //add the itemView to main view
        mSwipeView.addView(itemView);
    }
}

Is this the correct way to add layouts dynamically to a parent layout? Thanks!

Upvotes: 2

Views: 5470

Answers (1)

skynet
skynet

Reputation: 9908

It looks good except for a few things.

Because you are adding views to your custom ViewGroup, you will have to be sure that it correctly lays out and displays its children.

Also, when you add a View to a ViewGroup, you specify the LayoutParams that views can have in that ViewGroup.

Some more info about creating a custom ViewGroup

Upvotes: 2

Related Questions