Tuesday, 25 November 2014

Add multiple custom views to layout programmatically



If I for example have empty layout like this:


layout1.xml



<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

</LinearLayout>


And some other Layout like this:


layout2.xml



<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >

<TextView
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView 1" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2" />

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3"
android:layout_weight="1"/>

</LinearLayout>


I would like to add layout2.xml to layout1.xml programmatically. I would need to have multiple different version layout2.xml which I would add when I want. Each one would have different text on TextView and Buttons.


In case of regular Android View I would usually do it similarly like this with addView:



public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

TextView tv1 = new TextView(this);
tv1.setText("HELLO");
my_linear_layout.addView(tv1);

Button btn2 = new Button(this);
bt2.setText("WORLD");
my_linear_layout.addView(btn2);
}


How can I do it if I don't have something simple like TextView or Button, and if I have my own xml defined View?


Would it be possible to somehow put all the views inside adapter like for a ListView and then get it when needed and just call addView on those Views?


No comments:

Post a Comment