RadioButton

作者: 酥酥肉 | 来源:发表于2018-09-13 16:34 被阅读0次
  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;
        }
    }

相关文章

网友评论

    本文标题:RadioButton

    本文链接:https://www.haomeiwen.com/subject/yqwwgftx.html