MainActivity.java:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private CheckBox basketball,football,baseball,pingpang;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
basketball = (CheckBox) findViewById(R.id.basketball);
baseball = (CheckBox) findViewById(R.id.baseball);
football = (CheckBox) findViewById(R.id.football);
pingpang = (CheckBox) findViewById(R.id.pingpang);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s = "";
boolean flag = false;
if (basketball.isChecked()){
s += basketball.getText().toString();
flag = true;
}
if (baseball.isChecked()){
s += baseball.getText().toString();
flag = true;
}
if (football.isChecked()){
s += football.getText().toString();
flag = true;
}
if (pingpang.isChecked()){
s += pingpang.getText().toString();
flag = true;
}
if (flag == false){
Toast.makeText(MainActivity.this, "没有任何选项", 0).show();
}else {
Toast.makeText(MainActivity.this, s, 0).show();
}
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.checkboxdemo2.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择爱好" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<CheckBox
android:id="@+id/basketball"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="篮球" />
<CheckBox
android:id="@+id/football"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="足球" />
<CheckBox
android:id="@+id/baseball"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="网球" />
<CheckBox
android:id="@+id/pingpang"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="乒乓球" />
</LinearLayout>
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="确定" />
</LinearLayout>
原文:http://blog.csdn.net/u013476556/article/details/45115893