问题
I have RadioGroup in xml. And I am filling it with RadioButton from code. Problem is, in Emulators RadioButtons do not behave w.r.t RadioGroup. I can select all radiobuttons at once. But everything seems to work fine on real device.
Below are screenshots and code for all files:
Screenshot from emulator

Screenshot from device Samsung Galaxy

Source for MainActivity.java
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private RadioGroup rg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LayoutInflater inflater = LayoutInflater.from(getBaseContext());
rg = (RadioGroup)findViewById(R.id.rg);
for (int i = 0; i < 5; i++) {
inflater.inflate(R.layout.myradio, rg,true);
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/llContainer"
tools:context=".MainActivity" >
<RadioGroup
android:id="@+id/rg"
android:background="#0000ff"
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
</RadioGroup>
myradio.xml
<?xml version="1.0" encoding="utf-8"?>
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="RadioButton" />
回答1:
It will be like this
public class example extends Activity {
/** Called when the activity is first created. */
private RadioGroup rgroup;
RadioButton rb;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.example);
rgroup = (RadioGroup)findViewById(R.id.rg);
final RadioButton[] rb = new RadioButton[5];
for (int i = 0; i < 5; i++) {
rb[i]=new RadioButton(this);
rb[i].setText("rdo"+i);
rb[i].setId(i);
rgroup.addView(rb[i]);
}
}
}

来源:https://stackoverflow.com/questions/14436513/android-radiobuttons-misbehaving-on-emulator-only