RadioButton单选框并得到选中结果

首先,单选框的控件是RadioButton,需要在XML文件中配置如下代码

<TextView
    android:id="@+id/tv_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="单选"
    android:textSize="33dp"

    />

<RadioGroup
    android:id="@+id/rg_gender"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
<RadioButton
        android:id="@+id/rb_1"
        android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="男"
    android:textSize="22dp"
    ></RadioButton>
<RadioButton
    android:id="@+id/rb_2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="女"
    android:textSize="22dp"
    ></RadioButton>
</RadioGroup>
<Button
    android:id="@+id/bt"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="提交"
    android:textSize="29dp"
    >

</Button>
**其中如果想要实现单选的话需要建立一个RadioGroup,这样就可以只选择一个选项; 然后在MainActivity页面中对RadioGroup和Button进行声明; 然后对其进行可视化;即如下: bt=findViewById(R.id.bt); rg_gender=findViewById(R.id.rg_gender); 具体执行代码如下: public class MainActivity extends AppCompatActivity {
private RadioGroup rg_gender;
private Button bt;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bt=findViewById(R.id.bt);
    rg_gender=findViewById(R.id.rg_gender);
    bt.setOnClickListener(new View.OnClickListener() {					//设置点击事件
        @Override
        public void onClick(View v) {
            int len=rg_gender.getChildCount();					//调用RadioGroup的得到子RadioButton的数量
            for(int i=0;i<=len;i++){
                RadioButton radio=(RadioButton)rg_gender.getChildAt(i);		//得到子下标
                if(radio.isChecked()){								//判断选框有没有被选中
                    Toast.makeText(MainActivity.this,radio.getText(),Toast.LENGTH_SHORT).show();			//用Toast控件对选中信息进行在屏幕上显示
                    break;


                }


            }
        }
    });



}

}

猜你喜欢

转载自blog.csdn.net/Arex_Li/article/details/88774232