一、实现效果
二、布局xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<CheckBox
android:id="@+id/like_shuttlecock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="羽毛球"
android:textSize="18sp"
/>
<CheckBox
android:id="@+id/like_basketball"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="篮球"
android:textSize="18sp"
/>
<CheckBox
android:id="@+id/like_pingpong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="乒乓球"
android:textSize="18sp"
/>
<TextView
android:id="@+id/hobby"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
/>
</LinearLayout>
三、MainActivity.java文件
实现setOnCheckedChangeListener接口,设置3个checkbox控件的监听事件。并重写接口的onCheckedChanged()方法,在该方法中实现点击事件。
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private TextView hobby;
private String hobbys;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckBox shuttlecock=(CheckBox) findViewById(R.id.like_shuttlecock);
CheckBox basketball=(CheckBox)findViewById(R.id.like_basketball);
CheckBox pingpong=(CheckBox)findViewById(R.id.like_pingpong);
shuttlecock.setOnCheckedChangeListener(this);//在此处按住Alt+enter,选择Make 'MainActivity'会自动出现27行
basketball.setOnCheckedChangeListener(this);//设置三个接口,下面再定义方法
pingpong.setOnCheckedChangeListener(this);
hobby=(TextView) findViewById(R.id.hobby);
hobbys= new String();
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String motion=buttonView.getText().toString();
if (isChecked){
if (!hobbys.contains(motion)) {
hobbys = hobbys + motion;
hobby.setText(hobbys);
}
}else{
if (hobbys.contains(motion)){//如果没被选中
hobbys=hobbys.replace(motion,"");//使用空字符串替换
hobby.setText(hobbys);
}
}
}
}