舉個例子,設置男女的RadioButton。
<RadioGroup //先設置RadioGroup把一組Radio放在一起
android:id="@+id/sex"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton //在裏面加入Radio
android:id="@+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男" />
<RadioButton
android:id="@+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"
android:layout_marginLeft="20dp"/>
</RadioGroup>
上面我們已經講過關於兩種對於Button監聽器的使用操作了,今天會再加一種,正好放在一起整理。
//對於button的點擊監聽
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "OK!", Toast.LENGTH_SHORT).show();
}
});
//對於button的選擇情況進行監聽
btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
//對於radio的button組的選擇情況進行監聽
btn.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId){ //區分按鈕
}
}
});