Android的控件很多,我们从最常用的一些控件学起,今天我们学习CheckBox和RadioButton。
首先,我们要在main.xml文件中添加控件:
这里的RadioButton是在RadioGroup下的两个单选项,我们知道在应用中,单选按钮通常都是只能选一个,所以你可以设置一个RadioGroup中有几个单选按钮,况且在运行的时候在该组下你只能选择一项。
对应的string.xml文件:
Hello World, CheckBox_RadioButtonActivity!
CheckBox_RadioButton
女
男
汽车
剩下我们所要做的事情就是在Activity文件中为单选和多选按钮添加监听了,源码如下:
public class CheckBox_RadioButtonActivity extends Activity implementsOnCheckedChangeListener {privateRadioButton female;privateRadioButton male;privateCheckBox cb;/**Called when the activity is first created.*/@Overridepublic voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.main);//获取CheckBox对象
cb =(CheckBox) findViewById(R.id.checkbox);//获取两个RadioButton对象
female =(RadioButton) findViewById(R.id.female);
male=(RadioButton) findViewById(R.id.male);//为CheckBox添加监听
cb.setOnCheckedChangeListener(this);//为RadioButton添加监听
female.setOnClickListener(radio_listener);
male.setOnClickListener(radio_listener);
}
@Overridepublic void onCheckedChanged(CompoundButton buttonView, booleanisChecked) {//对CheckBox的选中状态进行判断并且作出相应的操作
if (isChecked == true) {
Toast.makeText(getApplicationContext(), cb.getText(),
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"you choose cancel",
Toast.LENGTH_LONG).show();
}
}private OnClickListener radio_listener = newOnClickListener() {
@Overridepublic voidonClick(View v) {//在RadionButton选中时所要做的操作
RadioButton rb =(RadioButton) v;
Toast.makeText(getApplicationContext(), rb.getText(),
Toast.LENGTH_SHORT).show();
}
};
}
这里要实现OnCheckedChangeListener这个接口,因为CheckBox的监听器是从CompoundButton继承下来的,所以这里不同于其它控件可以使用回调函数为自身添加监听。
PS:有的时候我们用Eclipse的Alt+?提示功能出不来OnCheckedChangeListener的提示,大家可以在文件头部手动导入下面两个包:
importandroid.widget.CompoundButton;import android.widget.CompoundButton.OnCheckedChangeListener;
之后就会有相应的提示了。
下面我们看运行结果:
1.初始化效果:
2.点击RadionButton男或者女时:
3.选中CheckBox时:
4.取消选中时:
关于点击后Toast的提示我们以后会进行深入的学习。