RadioButton

  1. Radio buttons are normally used together in a RadioGroup
  2. 在RadioGroup中添加RadioButton(至少两个)
  3. 为对象添加监听器,实现OnCheckedChangeListener接口,(选择RadioGroup包下的那个)

XML 配置

<RadioGroup
        android:id="@+id/rg_sex"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/rb_Male"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="男" />

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

JAVA 使用

  • public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener
    private RadioGroup rg;
    private RadioButton rg_Male, rg_Female;

     rg = (RadioGroup) findViewById(R.id.rg_sex);
        rg_Male = (RadioButton) findViewById(R.id.rb_Male);
        rg_Female = (RadioButton) findViewById(R.id.rb_FeMale);
        rg.setOnCheckedChangeListener(this); //绑定事件

 @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.rb_FeMale:
                // 当用户选择女性时
                Log.e("chao", "onCheckedChanged: ");
                Toast.makeText(this,"当前用户选择 "+ rg_Female.getText().toString(),Toast.LENGTH_SHORT).show();

                break;
            case R.id.rb_Male:
                // 当用户选择男性时
                Toast.makeText(this,"当前用户选择" +rg_Male.getText().toString(),Toast.LENGTH_SHORT).show();
                break;
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容