功能
複選框用於選擇某幾項內容,經典場景如選課,從語文、數學、英語中選擇1門或者2門。
顯示
在佈局文件中,注意通過checked屬性設置是否默認選中即可,代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="4dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="請選擇課程"/>
<CheckBox
android:id="@+id/checkBoxChinese"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:text="語文"/>
<CheckBox
android:id="@+id/checkBoxMath"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:text="數學"/>
<CheckBox
android:id="@+id/checkBoxEnglish"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:text="英語"/>
<Button
android:id="@+id/buttonOk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="確認"/>
</LinearLayout>
效果如下:
獲取選中項
點擊確認後,後臺獲取選中項,並彈窗顯示選中項。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//獲取按鈕
Button buttonOk = findViewById(R.id.buttonOk);
//設置按鈕點擊監聽器
buttonOk.setOnClickListener(new MyOnClickListener());
}
//定義按鈕點擊監聽器
class MyOnClickListener implements View.OnClickListener {
//按鈕點擊
@Override
public void onClick(View view) {
if (view.getId() == R.id.buttonOk) {//被點擊的是確認按鈕
//獲取選中項
CheckBox checkBoxChinese=findViewById(R.id.checkBoxChinese);
CheckBox checkBoxMath=findViewById(R.id.checkBoxMath);
CheckBox checkBoxEnglish=findViewById(R.id.checkBoxEnglish);
StringBuilder sb=new StringBuilder();
if(checkBoxChinese.isChecked()==true){
sb.append("語文;");
}
if(checkBoxMath.isChecked()==true){
sb.append("數學;");
}
if(checkBoxEnglish.isChecked()==true){
sb.append("英語;");
}
//顯示提示框
Toast.makeText(MainActivity.this, "你選擇了:"+sb.toString() , Toast.LENGTH_SHORT).show();
}
}
}
}
監聽選中項變化
當選中項變化時,提示用戶選擇信息,代碼如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Switch switchMsg = findViewById(R.id.switchMsg);
switchMsg.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
}
//定義按鈕點擊監聽器
class MyOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String str = "";
if (b == true) {
str = "開啓";
} else {
str = "關閉";
}
//顯示提示框
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
}
}