一、单选按钮
相互排斥的事件使用该控件,一组相互互斥的事件放到一个组内,及RadioGroup。
<RadioGroup
android:id="@+id/sex"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/girl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="女"/>
<RadioButton
android:id="@+id/boy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男"/>
</RadioGroup>
添加点击事件:
private RadioGroup mSexView;
mSexView = (RadioGroup) findViewById(R.id.sex);
mSexView.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkid) {
if(checkid == R.id.boy){
Toast.makeText(MainActivity.this,"boy",Toast.LENGTH_LONG).show();
}
}
});
注意:单选按钮有一点需要注意的地方,文档里也有相应的说明
若要一开始就默认选中其中的某个RadioButton,应给每个RadioButton设置id,否则会出现异常。
二、复选框
<CheckBox
android:id="@+id/checkbox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="旅游" />
<CheckBox
android:id="@+id/checkbox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="骑马" />
<CheckBox
android:id="@+id/checkbox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="射箭" />
<CheckBox
android:id="@+id/checkbox4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="跑步" />
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private CheckBox checkBox1;
private CheckBox checkBox2;
private CheckBox checkBox3;
private CheckBox checkBox4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBox1 = (CheckBox) findViewById(R.id.checkbox1);
checkBox2 = (CheckBox) findViewById(R.id.checkbox2);
checkBox3 = (CheckBox) findViewById(R.id.checkbox3);
checkBox4 = (CheckBox) findViewById(R.id.checkbox4);
checkBox1.setOnCheckedChangeListener(this);
checkBox2.setOnCheckedChangeListener(this);
checkBox3.setOnCheckedChangeListener(this);
checkBox4.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
switch (compoundButton.getId()) {
case R.id.checkbox1:
Toast.makeText(MainActivity.this,"1",Toast.LENGTH_LONG).show();
break;
case R.id.checkbox2:
Toast.makeText(MainActivity.this,"2",Toast.LENGTH_LONG).show();
break;
case R.id.checkbox3:
Toast.makeText(MainActivity.this,"3",Toast.LENGTH_LONG).show();
break;
case R.id.checkbox4:
Toast.makeText(MainActivity.this,"4",Toast.LENGTH_LONG).show();
break;
}
}
}
三、简单说一点Button吧
button对于我们来说非常常见,但是还是要说两个属性
1、如果不想要button的背景色可以设置为@null
2、有些时候我们需要图片和文字都显示的button,这时我们可以使用drawableLeft及图片在文字的左侧,同理还有右侧,上面下面,嘿嘿