Android自定义状态的按钮

时间:2023-01-07 00:33:42

拿button来举例,常用的状态有是否启用,是否按下,是否拥有焦点等,我们可以在资源文件里根据按钮不同的状态来定义背景,系统默认按钮的背景如下:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_window_focused="false" android:state_enabled="true" android:drawable="@drawable/btn_default_normal" />
    <item android:state_window_focused="false" android:state_enabled="false" android:drawable="@drawable/btn_default_normal_disable" />
    <item android:state_pressed="true" android:drawable="@drawable/btn_default_pressed" />
    <item android:state_focused="true" android:state_enabled="true" android:drawable="@drawable/btn_default_selected" />
    <item android:state_enabled="true" android:drawable="@drawable/btn_default_normal" />
    <item android:state_focused="true" android:drawable="@drawable/btn_default_normal_disable_focused" />
    <item android:drawable="@drawable/btn_default_normal_disable" />
</selector>
如果我们想要加入自己定义的状态也很简单,只需要下面几步

1.首先创建文件“res/values /attrs.xml”,并声明新的风格

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomState">
        <attr name="state_first" format="boolean" />
    </declare-styleable>
</resources>

2.创建自定义类继承于button,并加入第一步定义的新状态

public class CustomStateButton extends AppCompatButton {

    public final String TAG = CustomStateButton.class.getSimpleName();
    private static final int[] STATE_FIRST = {R.attr.state_first};
    private boolean firstState = false;

    public CustomStateButton(Context context) {
        this(context, null);
    }

    public CustomStateButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomStateButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setFirstState(boolean firstState) {
        this.firstState = firstState;
        refreshDrawableState();
    }

    public boolean isFirstState() {
        return firstState;
    }


    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (firstState) {
            mergeDrawableStates(drawableState, STATE_FIRST);
        }
        return drawableState;
    }
}
3.制作按钮背景

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:drawable="@color/colorPrimary" app:state_first="true" />
    <item android:drawable="@color/colorAccent" />
</selector>
4.调用CustomStateButton的setFirstState(true)方法即可显示按钮在自定义状态下的背景