How to check if “Radiobutton” is checked?

只谈情不闲聊 提交于 2019-12-17 16:28:16

问题


I would like to make a structure with the condition (if-else) RadioButton

I want that when the Radiobutton RB1 is selected, this function is active:

regAuxiliar = ultimoRegistro;

And when the radiobutton RB2 is selected, this function is active:

regAuxiliar = objRegistro;

And sorry for my English, I'm Brazilian.


回答1:


Just as you would with a CheckBox

RadioButton rb;

rb = (RadioButton) findViewById(R.id.rb);

rb.isChecked();



回答2:


        if(jRadioButton1.isSelected()){
            jTextField1.setText("Welcome");
        }
        else if(jRadioButton2.isSelected()){
            jTextField1.setText("Hello");
        }



回答3:


You can also maintain a flag value based on listener,

 radioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {

                //handle the boolean flag here. 
                  if(arg1==true)
                         //Do something

                else 
                    //do something else

            }
        });

Or simply isChecked() can also be used to check the state of your RadioButton.

Here is a link to a sample,

http://www.mkyong.com/android/android-radio-buttons-example/

And then based on the flag you can execute your function.




回答4:


radioButton.isChecked() function returns true if the Radion button is chosen, false otherwise.

Source




回答5:


radiobuttonObj.isChecked() will give you boolean

if(radiobuttonObj1.isChecked()){
//do what you want 
}else if(radiobuttonObj2.isChecked()){
//do what you want 
}



回答6:


If you need for espresso test the solutions is like this :

onView(withId(id)).check(matches(isChecked()));

Bye,




回答7:


You can use switch like this:

XML Layout

<RadioGroup
            android:id="@+id/RG"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <RadioButton
                android:id="@+id/R1"
                android:layout_width="wrap_contnet"
                android:layout_height="wrap_content"
                android:text="R1" />

            <RadioButton
                android:id="@+id/R2"
                android:layout_width="wrap_contnet"
                android:layout_height="wrap_content"
                android:text="R2" />
</RadioGroup>

And JAVA Activity

switch (RG.getCheckedRadioButtonId()) {
        case R.id.R1:
            regAuxiliar = ultimoRegistro;
        case R.id.R2:
            regAuxiliar = objRegistro;
        default:
            regAuxiliar = null; // none selected
    }

You will also need to implement an onClick function with button or setOnCheckedChangeListener function to get required functionality.



来源:https://stackoverflow.com/questions/11050074/how-to-check-if-radiobutton-is-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!