RadioButton: android的单选按钮,通常放在RadioGroup标签中。以下是获取RadioButton信息的例子:
public class RadioButtonActivty extends AppCompatActivity {
Button btn;
RadioButton r1, r2;
EditText name;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_button_activty);
textView=findViewById(R.id.text_sex);
name = findViewById(R.id.name);
btn = findViewById(R.id.btn_ok);
r1 = findViewById(R.id.boy);
r2 = findViewById(R.id.girl);
RadioGroup sex = findViewById(R.id.sex);
btn.setOnClickListener(new mClick());
sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton r = findViewById(i);
//get radiobutton value
textView.setText("MSG: sex: " +r.getText());
}
});
}
class mClick implements View.OnClickListener{
@Override
public void onClick(View view) {
CharSequence str = "",name2 = "";
name2 = name.getText();
if (r1.isChecked()){
str = r1.getText();
}
if (r2.isChecked()){
str = r2.getText();
}
textView.setText("MSG: \n name:" +name2 +"\n sex" + str);
}
}
}
xml内容如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".RadioButtonActivty">
<TextView
android:id="@+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:text="please input word"/>
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<RadioGroup
android:id="@+id/sex"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/boy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男"/>
<RadioButton
android:id="@+id/girl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"/>
</RadioGroup>
<Button
android:id="@+id/btn_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@color/gray"
android:text="OK"
android:textColor="@color/black"/>
<TextView
android:id="@+id/text_sex"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:gravity="center"
android:textSize="20sp"/>
</LinearLayout>