RadioGroup、RadioButton、CheckBox、Toast用法

本文详细解析了Android应用中XML布局文件的使用,重点介绍了如何通过监听器实现用户交互,如性别选择与兴趣爱好的确认。具体展示了RadioGroup与CheckBox的配置与事件响应,提供了一个实用的开发技巧。

  xml布局文件如下:

  <RadioGroup
    android:id="@+id/sex"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/number2"
    android:orientation="vertical">
    <RadioButton
      android:id="@+id/female"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="女"/>
    <RadioButton
      android:id="@+id/male"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="男"/>
  </RadioGroup>
  <CheckBox
    android:id="@+id/swim"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/sex"
    android:text="游泳"/>
  <CheckBox
    android:id="@+id/football"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/swim"
    android:text="足球"/>

     MainActivity.java的OnCreate方法中相应的代码如下:

    genderGroup = (RadioGroup)findViewById(R.id.sex);
    femaleButton = (RadioButton)findViewById(R.id.female);
    maleButton = (RadioButton)findViewById(R.id.male);
    genderGroup.setOnCheckedChangeListener(new GenderGroupListener());
    swimBox = (CheckBox)findViewById(R.id.swim);
    footBallBox = (CheckBox)findViewById(R.id.football);
    swimBox.setOnCheckedChangeListener(new HobbykBoxListener());
    footBallBox.setOnCheckedChangeListener(new HobbykBoxListener());

  定义genderGroup、CheckBox的监听器,注意二者的监听器的参数不同:

  class GenderGroupListener implements OnCheckedChangeListener{

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
      // TODO Auto-generated method stub
      //group点击的组的对象,checkedId组中的RadioButton对象的ID
      if(femaleButton.getId() == checkedId){
        Toast.makeText(MainActivity.this, "女", Toast.LENGTH_SHORT).show();
      }
      else if(maleButton.getId() == checkedId){
        Toast.makeText(MainActivity.this, "男", Toast.LENGTH_SHORT).show();
      }
    }
  }

  class HobbykBoxListener implements android.widget.CompoundButton.OnCheckedChangeListener{

    @Override
    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
      // TODO Auto-generated method stub
      //isChecked是否选中,如果选中则传入真,否则传入假
      if(isChecked){
        Toast.makeText(MainActivity.this, buttonView.getText().toString(), Toast.LENGTH_SHORT).show();
      }
    }
  }

转载于:https://www.cnblogs.com/zhanglei93/p/4657879.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值