RadioButtons Don't Properly Select/Deselect in Dynamically Created RadioGroup

孤街浪徒 提交于 2019-12-12 16:18:12

问题


When I create a RadioGroup in an XML layout file everything's fine, but when I create it dynamically the RadioButtons don't deselect when another is selected:

Here's the code:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);

    RadioButton radioButtonView = new RadioButton(this);
    radioButtonView.setText("RadioButton");
    radioGroup.addView(radioButtonView);

    RadioButton radioButtonView2 = new RadioButton(this);
    radioButtonView2.setText("RadioButton2");
    radioGroup.addView(radioButtonView2);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
}

And the layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<RadioGroup
    android:id="@+id/radioGroup1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true" >
</RadioGroup>
</RelativeLayout>

回答1:


You need to set some sort of ID for your radio button, as such:

int idRadio = <some number>;
radioButtonView.setId(idRadio++);
radioButtonView2.setId(idRadio++);

Once they have distinct IDs, it should work. Just make sure the IDs don't collide with any existing graphical element, and is not zero (go to your "gen" folder and look at R.java for the other element IDs).




回答2:


Related question how to uncheck the radio button in android. Try radioButtonView.setChecked(false);



来源:https://stackoverflow.com/questions/13558045/radiobuttons-dont-properly-select-deselect-in-dynamically-created-radiogroup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!