【问题标题】:RadioButtons Don't Properly Select/Deselect in Dynamically Created RadioGroup单选按钮在动态创建的 RadioGroup 中没有正确选择/取消选择
【发布时间】:2012-11-13 12:40:37
【问题描述】:

当我在XML布局文件中创建一个放射组时,一切都很好,但是当我动态创建它时,radiobuton在另一种选择时不要取消选择:

代码如下:

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>

【问题讨论】:

    标签: java android radio-button radio-group


    【解决方案1】:

    相关问题how to uncheck the radio button in android。 试试radioButtonView.setChecked(false);

    【讨论】:

      【解决方案2】:

      您需要为单选按钮设置某种 ID,例如:

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

      一旦他们有不同的 ID,它应该可以工作。只需确保 ID 不与任何现有的图形元素冲突,并且不为零(转到您的“gen”文件夹并查看 R.java 以获取其他元素 ID)。

      【讨论】:

      • 操作系统可以跟踪资产以及资产的所有者。此外,当您正在查找用户选择的确切对象时,通常查询返回的 ID 比浏览所有单选按钮并找出选中的对象更容易。此外,如果这是您接受的答案,请通过单击答案旁边的复选标记来标记它。 :-)
      • 有用,当然,但是 UI 正常运行的先决条件?无论如何,感谢您的修复。
      猜你喜欢
      • 2023-03-11
      • 2018-07-15
      • 2011-07-17
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 2020-03-26
      相关资源
      最近更新 更多