【问题标题】:How to set the (checked) state of a radiobutton programmatically in Android?如何在 Android 中以编程方式设置单选按钮的(选中)状态?
【发布时间】:2018-07-15 21:36:01
【问题描述】:

我有一个带有阀门的无线设备,它通过蓝牙 LE 连接到 Android 应用程序。在应用程序中,我在 radioGroup 中有一个带有 2 个单选按钮的活动布局。在启动时,我需要查询外部设备以确定阀门的当前状态,并相应地在 App 中设置一个 radioButton。我的基本策略如下...

private RadioGroup valveStateRadioGroup;
private RadioButton valveOnRadioButton;
private RadioButton valveOffRadioButton;

static boolean valveOn = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // set view and init Bluetooth stuff here

    valveStateRadioGroup = (RadioGroup) findViewById(R.id.valve_State_Radio_Group);
    valveOnRadioButton = (RadioButton) findViewById(R.id.valve_on_radioButton);
    valveOffRadioButton = (RadioButton) findViewById(R.id.valve_off_radioButton);

    valveStateRadioGroup.clearCheck();

    valveStateRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
        public void onCheckedChanged(RadioGroup group, int checkedId) {
                // do normal radioButton CLICKED stuff here
        }
    });
    queryValveState(); // call coms routine to get initial device status
}

public void queryValveState() {
    // code here that sends out a wireless query to the device
}

@Override
public synchronized void onDataAvailable(BluetoothGattCharacteristic characteristic) {
    //reply received from device, parse packet, determine valve status
    valveOn = false; // based on reply from device
    refeshUi();
}

private void refeshUi() {
    if (valveOn) {
        valveOnRadioButton.setChecked(true);
    }
    else {
        valveOffRadioButton.setChecked(true); // <<<<<<<<<<<< THIS is the problem
}

我遇到的问题是,当 ValveOffRadioButton.setChecked(true) 触发时,它永远不会触发 OnCheckedChangeListener 也不会更新 UI 中的小部件。如果我在 onCreate() 中进行设置,我可以设置 radioButton 的状态。我想我的实际问题是......你如何在 onCreate() 之外的例程中设置一个单选按钮?

【问题讨论】:

  • 似乎您拥有的是 RadioButtonGroup,我认为您需要将状态更改为单选组而不是单个单选按钮。检查这个答案:stackoverflow.com/a/37100605/3792636
  • 问题可能是不同的线程,尝试使用 refeshUi() 中的 runOnUIThread 进行更新。
  • 感谢 Muthukrishnan Rajendran。工作完美!还在学习... ;)

标签: android android-radiobutton


【解决方案1】:

valveOnRadioButton.setChecked(true);

【讨论】:

    【解决方案2】:

    感谢 Muthukrishnan Rajendran 的回答...

    private void refeshUi() {
        runOnUiThread(new Runnable() {
            public void run() {
                if (valveOn) {
                    valveOnRadioButton.setChecked(true);
                }
                else {
                    valveOffRadioButton.setChecked(true);
                }
            }
        });
    }
    

    【讨论】:

      【解决方案3】:

      答案迟到了,但这对我有用:

      ((RadioButton)radioGroup.getChildAt(0)).setChecked(true);

      问候

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-25
        • 2015-02-20
        • 2011-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-18
        • 2014-03-06
        相关资源
        最近更新 更多