【发布时间】:2019-02-26 08:37:15
【问题描述】:
我正在创建一个自定义按钮,该按钮将被公开以供使用。 我想根据状态(如果启用或禁用)更改按钮的颜色。以编程方式。
【问题讨论】:
标签: android components
我正在创建一个自定义按钮,该按钮将被公开以供使用。 我想根据状态(如果启用或禁用)更改按钮的颜色。以编程方式。
【问题讨论】:
标签: android components
最简单的方法是将其drawable设置为StateListDrawable,其中嵌入了不同的启用和禁用状态。那你就不用设置了,它会自己设置的。
【讨论】:
如果你想创建一个自定义按钮,你可以这样做:
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
【讨论】: