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 new to Android so I'm taking a stab in the dark. Would something like this work?
In the XML, add a LinearLayout to the middle of the page's XML like this:
<LinearLayout android:id="@+id/LinLayBut"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
And then in the java something like this:
public void setupRadioButt开发者_JS百科ons(){
LinearLayout linLay;
linLay = (LinearLayout) findViewById(R.id.LinLayBut);
RadioGroup radGroup = new RadioGroup(this);
RadioButton radBut = new RadioButton(this);
radGroup.addView(radBut, 0);
radGroup.setText("A button");
}
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:
public void setupRadioButtons() {
final LayoutInflater inflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout buttons =
(LinearLayout) inflater.inflate(R.layout.LinLayBut, null);
LinearLayout mainLayout = (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
.
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:
public void setupRadioButtons(){
RadioGroup radGroup;
radGroup = (RadioGroup) findViewById(R.id.radButGroup);
RadioButton radBut0 = new RadioButton(this);
radGroup.addView(radBut0, 0); //2nd arg must match order of buttons
radBut0.setText("one Button");
RadioButton radBut1 = new RadioButton(this);
radGroup.addView(radBut1, 1);
radBut1.setText("Two Button");
radBut1.setChecked(true); //which button is set
精彩评论