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