如何在Android中以编程方式设置radiobutton的(已检查)状态?

时间:2018-02-05 22:33:33

标签: android android-radiobutton

我有一个无线设备,其阀门通过蓝牙LE连接到Android应用程序。在App中我有一个活动布局,在radioGroup中有2个radioButtons。启动时,我需要查询外部设备以确定阀门的当前状态,并相应地在应用程序中设置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中的Widget。如果我在onCreate()中执行它,我可以设置radioButton的状态。我想我的实际问题是......你如何在onCreate()之外的例程中设置radioButton?

3 个答案:

答案 0 :(得分:0)

valveOnRadioButton.setChecked(真);

答案 1 :(得分:0)

感谢Muthukrishnan Rajendran的答案......

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

答案 2 :(得分:0)

最后一个答案,但这对我有用:

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

致谢