Android开发总结笔记 RadioButton和CheckBox(按钮) 1-1-10

来源:互联网 发布:mac 卸载自带输入法 编辑:程序博客网 时间:2024/05/18 02:11

从继承结构来看,CheckBox(API)RadioButton(API)都是继承于CompoundButton(API)
根据官方文档的描述,这个CompoundButton是拥有两种可以自动切换状态的按钮
这个特性跟CheckBoxRadioButton一样。
也因为CheckBoxRadioButton都是继承于CompoundButton的,所以这两个子类的大部分方法都在CompoundButton

下面就来看一下他们的常用用法

1、RadioButton
mRgGender= (RadioGroup) findViewById(R.id.rg);
mRgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton= (RadioButton) findViewById(checkedId);
Toast.makeText(MainActivity.this,radioButton.getText(),Toast.LENGTH_SHORT).show();
}
});
device-2015-10-09-142812.gif

2、CheckBox
public class MainActivity extends AppCompatActivity implements OnCheckedChangeListener {
private CheckBox mCbBasketBall;
private CheckBox mCbBadminton;
private CheckBox mCbPingpong;
 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCbBasketBall = (CheckBox) findViewById(R.id.basketball);
mCbBadminton = (CheckBox) findViewById(R.id.badminton);
mCbPingpong = (CheckBox) findViewById(R.id.pingpong);
mCbBasketBall.setOnCheckedChangeListener(this);
mCbPingpong.setOnCheckedChangeListener(this);
mCbBadminton.setOnCheckedChangeListener(this);
 
}
 
 
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isChecked()){
Toast.makeText(this,buttonView.getText(),Toast.LENGTH_SHORT).show();
}
}
}


device-2015-10-09-144232.gif



3、自定义样式
有时候默认的样式可以满足不了我们的需求,所以就需要自定义一些样式
<CheckBox
android:background="@drawable/selector_cb_gender"
android:button="@null"
android:layout_margin="10dp"
android:id="@+id/basketball"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

selector_cb_gender.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_sex_female" android:state_checked="true"></item>
<item android:drawable="@drawable/ic_sex_male" android:state_checked="false"></item>
</selector>

device-2015-10-09-145208.gif

0 0