Android自定义状态的按钮

本文介绍了如何为Android按钮自定义不同状态,如启用、按下和焦点状态。通过在资源文件中定义背景,然后在'attrs.xml'中声明新风格,最后创建继承自Button的自定义类来应用这些样式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

拿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)方法即可显示按钮在自定义状态下的背景



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值