Dynamic number of buttons in LinearLayout



In the onCreate method of my Activity I know the number of Buttons which I want in col0. In the following example it are four Buttons. Then my TextView v0 gets the android:layout_weight set to number of buttons minus one (this is because v1 should be of the same height as all the Buttons). Instead of providing for each possible number of buttons an own xml file it would be much nicer, if one could generalize such that dynamic java codes somehow produces the appropriate layout. How is that possible?



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal">

<LinearLayout
android:id="@+id/col0"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1"
android:baselineAligned="false"
android:orientation="vertical">

<Button
android:id="@+id/b0"
style="@style/MyButton" />

<Button
android:id="@+id/b1"
style="@style/MyButton" />

<Button
android:id="@+id/b2"
style="@style/MyButton" />

<Button
android:id="@+id/b3"
style="@style/MyButton" />

</LinearLayout>

<LinearLayout
android:id="@+id/col1"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="6"
android:baselineAligned="false"
android:orientation="vertical">

<TextView
android:id="@+id/v0"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="3" />

<TextView
android:id="@+id/v1"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />

</LinearLayout>

</LinearLayout>

No comments:

Post a Comment