Android studio CheckBox(复选框)

实现代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener,CompoundButton.OnCheckedChangeListener{

    private CheckBox cb_one;
    private CheckBox cb_two;
    private CheckBox cb_three;
    private Button btn_send;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        cb_one = (CheckBox) findViewById(R.id.cb_one);
        cb_two = (CheckBox) findViewById(R.id.cb_two);
        cb_three = (CheckBox) findViewById(R.id.cb_three);
        btn_send = (Button) findViewById(R.id.btn_send);

        cb_one.setOnCheckedChangeListener(this);
        cb_two.setOnCheckedChangeListener(this);
        cb_three.setOnCheckedChangeListener(this);
        btn_send.setOnClickListener(this);

    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
       if(compoundButton.isChecked()) Toast.makeText(this,compoundButton.getText().toString(),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View view) {
        String choose = "";
        if(cb_one.isChecked())choose += cb_one.getText().toString() + "";
        if(cb_two.isChecked())choose += cb_two.getText().toString() + "";
        if(cb_three.isChecked())choose += cb_three.getText().toString() + "";
        Toast.makeText(this,choose,Toast.LENGTH_SHORT).show();
    }
}

自定义点击效果

PS:这里素材的原因,有点小...

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="true"
        android:state_checked="true"
        android:drawable="@mipmap/ic_checkbox_checked"/>
    <item
        android:state_enabled="true"
        android:state_checked="false"
        android:drawable="@mipmap/ic_checkbox_normal" />
</selector>

写好后,我们有两种方法设置,也可以说一种吧!你看看就知道了~

①android:button属性设置为上述的selctor

android:button="@drawable/rad_btn_selctor"

②在style中定义一个属性,然后通过android style属性设置,先往style添加下述代码:

    <style name="MyCheckBox" parent="@android:style/Widget.CompoundButton.CheckBox">
        <item name="android:button">@drawable/rad_btn_selctor</item>
    </style>

然后布局那里:

style="@style/MyCheckBox"

改变文字与选择框的相对位置

这个实现起来也很简单 要控制选择框的位置,两步即可!设置:

Step 1. android:button="@null"
Step 2. android:drawableTop="@android:drawable/btn_radio"
当然我们可以把drawableXxx替换成自己喜欢的效果!

修改文字与选择框的距离

有时,我们可能需要调节文字与选择框之间的距离,让他们看起来稍微没那么挤,我们可以:
1.在XML代码中控制: 使用android:paddingXxx = "xxx" 来控制距离
2.在Java代码中,稍微好一点,动态计算paddingLeft!

示例代码如下:

rb.setButtonDrawable(R.drawable.rad_btn_selctor);
int rb_paddingLeft = getResources().getDrawable(R.mipmap.ic_checkbox_checked).getIntrinsicWidth()+5; 
rb.setPadding(rb_paddingLeft, 0, 0, 0);
原文地址:https://www.cnblogs.com/1329197745a/p/14905494.html