4

XML レイアウト ファイルで RadioGroup を作成するとすべて問題ありませんが、動的に作成すると、別のものが選択されているときに RadioButtons の選択が解除されません。

ここに画像の説明を入力

コードは次のとおりです。

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;
}
}

そしてレイアウトファイル:

<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>
4

2 に答える 2

8

ラジオボタンには、次のようなIDを設定する必要があります。

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

個別のIDを取得すると、機能するはずです。IDが既存のグラフィック要素と衝突せず、ゼロでないことを確認してください(「gen」フォルダーに移動し、R.javaで他の要素IDを確認してください)。

于 2012-11-26T03:08:42.010 に答える
0

関連する質問how to uncheck the radio button in android。試すradioButtonView.setChecked(false);

于 2012-11-26T03:06:48.953 に答える