你們好,咱們這一節將講多選項CheckBox 的綜合應用,咱們的程序主要構造兩個CheckBox 的對象,以及一個TextView對象,並經過setOnCheckedChangeLisener 實現onCheckedChanged ()方法來更新TextView 文字.
首先咱們看一下效果圖:
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
下面是主程序的代碼:
string.xml: android
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="hello">Hello World, CheckboxDemo!</string>
- <string name="app_name">CheckboxDemo</string>
- <string name="hobby">你的愛好是:</string>
- <string name="basketball">籃球</string>
- <string name="football">足球</string>
- </resources>
複製代碼
主程序界面代碼main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:id="@+id/textview1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hobby"
- />
- <CheckBox
- android:id="@+id/checkbox1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/basketball"
- />
- <CheckBox
- android:id="@+id/checkbox2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/football"
- />
- </LinearLayout>
複製代碼
最後是程序的核心代碼CheckBoxDemo:
- package com.android.test;
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.CheckBox;
- import android.widget.CompoundButton;
- import android.widget.TextView;
- public class CheckboxDemo extends Activity {
-
- private TextView tv;
- private CheckBox cb1;
- private CheckBox cb2;
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- tv = (TextView)findViewById(R.id.textview1);
- cb1 = (CheckBox)findViewById(R.id.checkbox1);
- cb2 = (CheckBox)findViewById(R.id.checkbox2);
-
- cb1.setOnCheckedChangeListener(cbListener);
- cb2.setOnCheckedChangeListener(cbListener);
-
-
- }
-
- private CheckBox.OnCheckedChangeListener cbListener =
- new CheckBox.OnCheckedChangeListener(){
-
- public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
- {
- String stv = getString(R.string.hobby);
- String scb1 = getString(R.string.basketball);
- String scb2 = getString(R.string.football);
- //判斷一共有四種狀況
- if(cb1.isChecked()== true && cb2.isChecked()== true)
- {
- tv.setText(stv + scb1 + "," + scb2);
- }
- else if(cb1.isChecked()== true && cb2.isChecked()== false)
- {
- tv.setText(stv+scb1);
- }
- else if(cb1.isChecked() == false && cb2.isChecked() == true)
- {
- tv.setText(stv+scb2);
- }
- else{
- tv.setText(stv);
- }
- }
- };
-
- }
複製代碼