用CheckedTextView这货创建开关按钮SwitchButton

254 阅读1分钟
原文链接: mp.weixin.qq.com

一、说明

1、CheckedTextView 类似checkbox,单选-多选。 但它支持文字,名字可以看出它继承TextView ,多了一个选择勾选框。

使用,选中未选中:

checkedTextView.toggle();
这个是一个判断源码:  public void toggle() {
        setChecked(!mChecked);
    }
点击事件需要我们代码捕获,代码设置,切换状态,控件本身不支持自动切换,应该2、没有自动捕获点击事件。

2、设置选着框的样式:selector必须要使用drawable,不能使用color,否者会报xml错误

3、设置背景的selector一定要在代码里面设置,不能再xml中设置:

二、上代码

import android.content.Context;import android.util.AttributeSet;import android.widget.CheckedTextView;import android.widget.RelativeLayout;import com.ytg.jzy.p_common.R;public class SwitchButton extends RelativeLayout {    CheckedTextView mCheckedTextView;    public SwitchButton(Context context, AttributeSet attrs) {        super(context, attrs);        mCheckedTextView = new CheckedTextView(context);        addView(mCheckedTextView);        initView();    }    void initView() {        mCheckedTextView.setCheckMarkDrawable(getContext().getResources().getDrawable(R.drawable.switch_style));        mCheckedTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);    }    public void toggle() {        mCheckedTextView.toggle();    }    /**     * 是否处于选中状态     *     * @return     */    public boolean isChecked() {        return mCheckedTextView.isChecked();    }    /**     * 设置状态     *     * @param checked     */    public void setChecked(boolean checked) {        mCheckedTextView.setChecked(checked);    }}

switch_styles.xml

三、使用:

喜欢就关注吧!或者投稿。更多精彩敬请期待!