CheckBox複選按鈕是一種有雙狀態按鈕的特殊類型,可以選中或者不選中。可以現在布局檔案中定義多選按鈕,然後對每一個多選按鈕進行事件監setOnCheckedChangeListener,通過isChecked來判斷選項是否被選中
main.xml
<?xml version="1.0" encoding="utf-8"?><br /><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:layout_width="fill_parent"<br /> android:layout_height="fill_parent"<br /> android:orientation="vertical" ></p><p> <TextView<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:text="@string/theme" /><br /> <CheckBox<br /> android:id="@+id/apple"<br /> android:text="@string/apple"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"/><br /> <CheckBox<br /> android:id="@+id/banana"<br /> android:text="@string/banana"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"/></p><p></LinearLayout>
RadioGroupActivity.java
package Android.Activity;</p><p>import android.app.Activity;<br />import android.os.Bundle;<br />import android.widget.CheckBox;<br />import android.widget.CompoundButton;<br />import android.widget.Toast;</p><p>public class RadioGroupActivity extends Activity {<br /> /** Called when the activity is first created. */<br />private CheckBox appleCheck = null;<br />private CheckBox bananaCheck = null;<br /> @Override<br /> public void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> setContentView(R.layout.main);<br /> //通過控制項的ID來得到代表控制項的對象<br /> appleCheck = (CheckBox)findViewById(R.id.apple);<br /> bananaCheck = (CheckBox)findViewById(R.id.banana);<br /> //為RadioGroup設定監聽器,需要注意的是,這裡的監聽器和Button控制項的監聽器有所不同<br /> appleCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {</p><p>public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {<br />// TODO Auto-generated method stub<br />if(isChecked){<br />Toast.makeText(RadioGroupActivity.this,"恭喜你,還剩很多蘋果", Toast.LENGTH_LONG).show();<br />}<br />}<br />});</p><p> bananaCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {</p><p>public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {<br />// TODO Auto-generated method stub<br />if(isChecked){<br />Toast.makeText(RadioGroupActivity.this,"恭喜你,還剩很多香蕉", Toast.LENGTH_LONG).show();<br />}<br />}<br />});<br /> }<br />}