CheckBox和RadioButton的区别在于,CheckBox可取消,RadioButton不可以
能实现的方法很多,在这里仅仅展示自己比较常用的一种方法
XML布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<CheckBox
android:id="@+id/cb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"/>
<CheckBox
android:id="@+id/cb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"/>
<CheckBox
android:id="@+id/cb3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"/>
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="确定"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
java代码:
package com.example.administrator.myapplication;
import android.content.BroadcastReceiver;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private CheckBox cb1,cb2,cb3;
private Button btn1;
private Boolean c1=false,c2=false,c3=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initfind();
}
private void initfind(){
btn1=findViewById(R.id.btn1);
cb1=findViewById(R.id.cb1);
cb2=findViewById(R.id.cb2);
cb3=findViewById(R.id.cb3);
btn1.setOnClickListener(onClick);
cb1.setOnClickListener(onClick);
cb2.setOnClickListener(onClick);
cb3.setOnClickListener(onClick);
}
//按钮监听实现方法
private View.OnClickListener onClick=new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.cb1: c1=!c1;break;
case R.id.cb2: c2=!c2;break;
case R.id.cb3: c3=!c3;break;
case R.id.btn1 :Log.d("Button","c1="+c1+"c2="+c2+"c3="+c3);break;
}
}
};
}
效果: