Android 复选框CheckBox的使用
package com.radiodemo;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends Activity {
/*************************************
* 复选框CheckBox的使用
*
* 1.定义见布局文件 2.事件的添加方法 3.事件的处理步骤
*
***********************************/
private TextView textView;
private CheckBox checkBox1, checkBox2, checkBox3;
private String TAG = "CheckBoxDemo";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 关联布局中的控件
textView = (TextView) findViewById(R.id.textView);// 用来显示选择
checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
checkBox3 = (CheckBox) findViewById(R.id.checkBox3);
checkBox1.setOnCheckedChangeListener(mCheckBoxChanged);
checkBox2.setOnCheckedChangeListener(mCheckBoxChanged);
checkBox3.setOnCheckedChangeListener(mCheckBoxChanged);
}
// 响应事件的函数。
private CheckBox.OnCheckedChangeListener mCheckBoxChanged = new CheckBox.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
Log.i(TAG, "buttonView:" + buttonView + ",isChecked:" + isChecked
+ "\ntext:" + buttonView.getText());
String string = new String("你所选的是:");
if (checkBox1.isChecked())
string += " " + checkBox1.getText();
if (checkBox2.isChecked())
string += " " + checkBox2.getText();
if (checkBox3.isChecked())
string += " " + checkBox3.getText();
textView.setText(string);
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
资源文件main.xml
<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:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="你所选的是:" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AA"/>
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BB" />
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CC" />
</LinearLayout>