Android自带了丰富的基础组件,这次我们要介绍的CheckBox。
先看本次实例代码的运行效果:
首先我们在strings.xml中定义CheckBox和显示的TextView中字符串,代码如下:
<string name="app_name">AndroidWithCheckBox</string>
<string name="hobby">你的爱好是:</string>
<string name="basketball">篮球</string>
<string name="football">足球</string>
而后在main.xml中定义我们的组件,两个CheckBox和一个TextView
<TextView
android:id ="@+id/showText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hobby"
/>
<CheckBox
android:id="@+id/basketballCheckBox"
android:text="@string/basketball"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<CheckBox
android:id="@+id/footballCheckBox"
android:text="@string/football"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
在Activity子类中, 先获取到在main.xml中定义的三个组件,而后给CheckBox添加上OnCheckedChangeListener
,具体代码如下:
public class Test extends Activity {
/** Called when the activity is first created. */
private TextView view ;
private CheckBox basketballCheckBox ;
private CheckBox footballCheckBox ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = (TextView)findViewById(R.id.showText);
basketballCheckBox = (CheckBox)findViewById(R.id.basketballCheckBox);
footballCheckBox = (CheckBox)findViewById(R.id.footballCheckBox);
basketballCheckBox.setOnCheckedChangeListener(cbListener);
footballCheckBox.setOnCheckedChangeListener(cbListener);
}
private CheckBox.OnCheckedChangeListener cbListener =
new CheckBox.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
String hobby = getString(R.string.hobby);
String basketball = getString(R.string.basketball);
String football = getString(R.string.football);
String showText = "";
if(basketballCheckBox.isChecked()&&footballCheckBox.isChecked()){
view.setText(showText = hobby+basketball+","+football);
}
else if(basketballCheckBox.isChecked()&&!footballCheckBox.isChecked()){
view.setText(showText = hobby+basketball);
}
else if(!basketballCheckBox.isChecked()&&footballCheckBox.isChecked()){
view.setText(showText = hobby+football);
}
else{
view.setText(showText = hobby+"不是下面的两项");
}
Toast.makeText(Test.this, showText, Toast.LENGTH_SHORT).show();
}};
}