android - setBackgroundTintList 不直接应用

标签 android android-appcompat

我在 AppCompatButton 类上应用 setBackgroundTintList() 方法,如下所示:

applyTintColor(this.appCompatButton, R.drawable.button_orange_color_state);

方法applyTintColor:

public void applyTintColor(@NonNull View view, @DrawableRes int color) {

    ColorStateList colorStateList = ContextCompat.getColorStateList(view.getContext(), color);
    ViewCompat.setBackgroundTintList(view, colorStateList);
}

我的button_orange_color_state.xml 文件。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Disable background -->
    <item android:color="@color/brand_secondary"
          android:state_enabled="false"/>
    <!-- Default background -->
    <item android:color="@color/orange"/>
</selector>

问题: 应用 applyTintColor 方法后,按钮采用默认的白色透明颜色而不是我的橙色颜色的形状。 但我注意到,当我按下按钮时,按钮正确地采用禁用状态的颜色,然后再次启用按钮后,颜色变为橙色。 到目前为止,我发现的唯一但肮脏的方法是在 applyTintColor 的末尾添加以下代码:

    view.setEnabled(!view.isEnabled());
    view.setEnabled(!view.isEnabled());

这样按钮就直接考虑好了橙色。

所以我想知道是否有人有更好的主意来让这里的事情变得更好?

最佳答案

供以后引用,如果 View 已经布局,在 view.setBackgroundTintList(tint) 之后,您可以调用 view.refreshDrawableState()

关于android - setBackgroundTintList 不直接应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36114388/

相关文章:

android - 将 SQLite 转换为 JSON

c# - Imgproc.FindContours 返回空轮廓

android - 错误 : Attribute 'SrcCompat' has already been defined

android - 最佳实践 : Navigation Drawer

android - Recyclerview - 无法在滚动回调中调用此方法

java - 计算直线的斜率(如果它是无穷大)

android - Widget.AppCompat.Button colorButtonNormal 显示灰色

android - Lollipop 上的工具栏高度太大

Android AppCompat v21 提供SwitchCompat 不提供SwitchCompatPreference

Android Studio 找不到与 com.android.support :appcompat-v7:23. + 匹配的任何版本