【问题标题】:set radio button position in android在android中设置单选按钮位置
【发布时间】:2021-11-13 22:12:45
【问题描述】:

我想使用 sqlite db 检查单选按钮,但问题是每次我检查按钮并返回时,它都不会保持选中状态。如何保持选中的按钮处于选中状态?这是实现

case R.id.rg:
   RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(
                    RadioGroup.LayoutParams.WRAP_CONTENT,
                    RadioGroup.LayoutParams.WRAP_CONTENT    );

   dialog.show();
   for (int i = 0; i < list.length; i++) {
       rb = new RadioButton(context);
       rb.setText("item" + i);
       rb.setId(i);
       rg.addView(rb, layoutParams);
       rb = (RadioButton) rg.getChildAt(0);
       rb.setChecked(true);
       rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(RadioGroup group, int checkedId) {
               rb = group.findViewById(checkedId);
               View radioButton = group.findViewById(rg.getCheckedRadioButtonId());
               radio_button_position = group.indexOfChild(radioButton);
               boolean success = db.updateButtonPosition(myFiles.get(position).getId()),
                              String.valueOf(radio_button_position));
               if (success){
                    int readButtonPosition = db.readButtonPosition(myFiles.get(position).getId()),
                              String.valueOf(radio_button_position));
                    rb = (RadioButton) rg.getChildAt(readButtonPosition);
                    rb.setChecked(true);
                    Toast.makeText(PlayerActivity.this, "success", Toast.LENGTH_SHORT).show();
                    } else {
                    Toast.makeText(PlayerActivity.this, "failure", Toast.LENGTH_SHORT).show();
                    }    
                }
           }

}

readButtonPosition 给出了正确的值,在我的情况下,当我检查第二个按钮时它返回 1。

默认情况下,我将第一个单选按钮设置为选中状态,并希望保持选中按钮而不是默认选中状态。

【问题讨论】:

    标签: android radio-button


    【解决方案1】:

    在您的 for 循环之外,根据数据库中保存的值设置选中的单选按钮。使用这个外部循环

    int readButtonPosition = db.readButtonPosition(myFiles.get(position).getId()),
                                  String.valueOf(radio_button_position));
    rb = (RadioButton) rg.getChildAt(readButtonPosition);
    rb.setChecked(true);
    

    并且不要多次设置同一个广播组监听器,将您的广播组监听器置于循环之外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-07
      • 2015-06-19
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      • 2016-11-28
      • 1970-01-01
      相关资源
      最近更新 更多