Android控件系列之RadioButton与RadioGroup的基本使用

RadioButton即单选框,是一种基础的UI控件。RadioGroup为我们提供了RadioButton单选按钮的容器,RadioButton通常放于RadioGroup容器中进行使用。RadioButton的选中状态,在xml文件中可以使用android:checked=""来进行设置,选中就设置为true,没选中就设置为false。


这里先贴上XML的代码:






























这边我介绍两种获取RadioButton的监听事件处理方法:

方法一:通过获取点击的id来实例化并获取选中状态的RadioButton控件

// 实例化控件
		sex = (RadioGroup) findViewById(R.id.sex);

		// 方法一监听事件,通过获取点击的id来实例化并获取选中状态的RadioButton控件
		sex.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// 获取选中的RadioButton的id
				int id = group.getCheckedRadioButtonId();
				// 通过id实例化选中的这个RadioButton
				RadioButton choise = (RadioButton) findViewById(id);
				// 获取这个RadioButton的text内容
				String output = choise.getText().toString();
				Toast.makeText(MainActivity.this, "你的性别为:" + output, Toast.LENGTH_SHORT).show();
			}
		});

效果图:

Android控件系列之RadioButton与RadioGroup的基本使用_第1张图片

方法二:通过if的方法来对获取的id与实例化的xml中的RadioButton的ID进行判断,找出选中状态的RadioButton控件
hobby = (RadioGroup) findViewById(R.id.hobby);
		baskeball = (RadioButton) findViewById(R.id.basketball);
		table_tennis = (RadioButton) findViewById(R.id.table_tenis);
		badminton = (RadioButton) findViewById(R.id.badminton);
		// 方法二,通过if的方法来对获取的id与实例化的xml中的RadioButton的ID进行判断,找出选中状态的RadioButton控件
		hobby.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {

				if (baskeball.getId() == checkedId) {
					shuchu = baskeball.getText().toString();
				}
				if (table_tennis.getId() == checkedId) {
					shuchu = table_tennis.getText().toString();
				}
				if (badminton.getId() == checkedId) {
					shuchu = badminton.getText().toString();
				}
				Toast.makeText(MainActivity.this, "你喜欢的体育运动为:" + shuchu, Toast.LENGTH_SHORT).show();

			}
		});
效果图:

Android控件系列之RadioButton与RadioGroup的基本使用_第2张图片


点击下载


有话要说:这是博主第一次写博客,有些的不好的地方希望可以见谅,如果感觉还可以的,希望多多支持!!


你可能感兴趣的:(Android,基础UI)