我使用此样式来更改Button
的背景色
<style name="AccentButton" parent="Widget.AppCompat.Button.Colored">
<item name="colorButtonNormal">@color/colorAccent</item>
<item name="android:textColor">@color/white</item>
</style>
在布局中:
<Button
android:id="@+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/fragment_login_login_button"
app:theme="@style/AccentButton"/>
它起作用了。但是当我在这个Button
上调用setEnabled(false)
时,它保持相同的颜色。我该如何处理此案例?
发布于 2016-03-05 14:58:01
您没有正确使用Widget.AppCompat.Button.Colored
样式。您正在使用父样式(Widget.AppCompat.Button.Colored
),但将其应用为主题。这实际上意味着Widget.AppCompat.Button.Colored
部件将被完全忽略,而您只需更改按钮的默认颜色(可以工作,但不能处理禁用的情况)。
相反,您应该使用ThemeOverlay
并单独应用Colored
样式:
<style name="AccentButton" parent="ThemeOverlay.AppCompat.Dark">
<!-- customize colorButtonNormal for the disable color -->
<!-- customize colorAccent for the enabled color -->
</style>
<Button
android:id="@+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/fragment_login_login_button"
android:theme="@style/AccentButton"
style="@style/Widget.AppCompat.Button.Colored"/>
如this answer on using the Widget.AppCompat.Button.Colored
style中所述,禁用的颜色由colorButtonNormal
控制,启用的颜色由colorAccent
控制。通过使用ThemeOverlay.AppCompat.Dark
,textColor
会自动更改为深色,这意味着您可能根本不需要自定义ThemeOverlay
。
发布于 2016-03-05 14:02:54
您应该使用带有选择器的背景,而不是对按钮使用颜色。以下是演示代码
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true">
<shape android:shape="rectangle">
<solid android:color="@color/yourEnabledColor" />
</shape>
</item>
<item android:state_enabled="false">
<shape android:shape="rectangle">
<solid android:color="@color/yourDisabledColor" />
</shape>
</item>
</selector>
发布于 2016-05-18 20:15:40
将接受的解决方案与自定义小部件相结合,我们可以通过设置alpha来显示禁用的按钮。这应该适用于任何按钮和文本颜色组合:
public class ButtonWidget extends AppCompatButton {
public ButtonWidget(Context context) {
super(context);
}
public ButtonWidget(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ButtonWidget(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setEnabled(boolean enabled) {
setAlpha(enabled ? 1 : 0.5f);
super.setEnabled(enabled);
}
}
https://stackoverflow.com/questions/35810614
复制相似问题