【问题标题】:How to know if the button state has changed from enabled to disabled android?如何知道按钮状态是否已从启用更改为禁用 android?
【发布时间】:2019-02-26 08:37:15
【问题描述】:

我正在创建一个自定义按钮,该按钮将被公开以供使用。 我想根据状态(如果启用或禁用)更改按钮的颜色。以编程方式。

【问题讨论】:

    标签: android components


    【解决方案1】:

    最简单的方法是将其drawable设置为StateListDrawable,其中嵌入了不同的启用和禁用状态。那你就不用设置了,它会自己设置的。

    【讨论】:

    • 是的,我就是这么想的。我看到状态 android.R.attr.state_enabled 但没有禁用状态 attr。
    • 哦,其实我刚刚看到我可以使用 {- R.att.state_enabled} 来表示禁用状态
    【解决方案2】:

    如果你想创建一个自定义按钮,你可以这样做:

    public class CustomBtn extends android.support.v7.widget.AppCompatButton {
        private Context context;
    
        public CustomBtn(Context context) {
            super(context);
            this.context = context;
        }
    
        public CustomBtn(Context context, AttributeSet attrs) {
            super(context, attrs);
            this.context = context;
        }
    
        public CustomBtn(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            this.context = context;
        }
    
        @Override
        public void setEnabled(boolean enabled) {
            super.setEnabled(enabled);
            if (enabled) {
                this.setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary));
            } else {
                this.setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));
            }
        }
    }
    

    并使用如下自定义按钮:

    CustomBtn customBtn = findViewById(R.id.customBtn); //add a CustomBtn like normal widget in layout xml
    customBtn.setEnabled(true);//this button color will be R.color.colorPrimary
    customBtn.setEnabled(false);//this button color will be R.color.colorPrimaryDark
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-03
      • 2013-04-09
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多