public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final CheckBox like1=(CheckBox)findViewById(R.id.like1); //獲取第1個複選按鈕
final CheckBox like2=(CheckBox)findViewById(R.id.like2); //獲取第2個複選按鈕
final CheckBox like3=(CheckBox)findViewById(R.id.like3); //獲取第3個複選按鈕
like1.setOnCheckedChangeListener(checkBox_listener); //爲like1添加狀態改變監聽
like2.setOnCheckedChangeListener(checkBox_listener); //爲like2添加狀態改變監聽
like3.setOnCheckedChangeListener(checkBox_listener); //爲like3添加狀態改變監聽
Button button = (Button) findViewById(R.id.button1); //獲取提交按鈕
//爲提交按鈕添加單擊事件監聽
button.setOnClickListener(new OnClickListener() { ide
@Override
public void onClick(View v) {
//經過for循環遍歷單選按鈕組
String like=""; //保存選中的值
if(like1.isChecked()) //當第一個複選按鈕被選中
like+=like1.getText().toString()+" ";
if(like2.isChecked()) //當第一個複選按鈕被選中
like+=like2.getText().toString()+" ";
if(like3.isChecked()) //當第一個複選按鈕被選中
like+=like3.getText().toString()+" ";
Toast.makeText(MainActivity.this, like, Toast.LENGTH_SHORT).show(); //顯示被選中的複選按鈕 this
}
});
}
//建立一個狀態改變監聽對象
private OnCheckedChangeListener checkBox_listener=new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){ //判斷複選按鈕是否被選中
Log.i("複選按鈕","選中了["+buttonView.getText().toString()+"]");
}
}
};
} 對象