How Do You Declare Part Of A Page Programmaticaly
If I have a page whose layout is designated by XML code, but I want to possibly create a few radio buttons, say, in the middle, but decide that at runtime, how would I do it? I'm n
Solution 1:
This is not an efficient way to build dynamic UI. You would be better off defining the optional layout in an XML file and then inflate it when you want to use it:
publicvoidsetupRadioButtons() {
finalLayoutInflaterinflater=
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayoutbuttons=
(LinearLayout) inflater.inflate(R.layout.LinLayBut, null);
LinearLayoutmainLayout= (LinearLayout) findViewById(R.id.main);
mainLayout.addView(buttons);
}
The above code assumes that the radio group and buttons are defined inside the LinearLayout
with id LinLayBut
and you main layout id is main
.
Solution 2:
OK, thanks to unluddite, I got it to work. For those tortured souls following the thread, here's the code. The XML doesn't have a layout around it. And if I don't call the method, the radio group takes no vertical space:
<RadioGroup android:id="@+id/radButGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" />
and here's the method:
publicvoidsetupRadioButtons(){
RadioGroup radGroup;
radGroup = (RadioGroup) findViewById(R.id.radButGroup);
RadioButtonradBut0=newRadioButton(this);
radGroup.addView(radBut0, 0); //2nd arg must match order of buttons
radBut0.setText("one Button");
RadioButtonradBut1=newRadioButton(this);
radGroup.addView(radBut1, 1);
radBut1.setText("Two Button");
radBut1.setChecked(true); //which button is set
Post a Comment for "How Do You Declare Part Of A Page Programmaticaly"