android - setSupportBackgroundTintList 状态不工作

标签 android android-appcompat

我创建了一个扩展 AppCompat 按钮的 MyButton 类。在我的讲师中,我执行了这段代码:

    int[][] states = new int[][]{
            new int[]{android.R.attr.state_enabled}, // enabled
            new int[]{android.R.attr.state_pressed}  // pressed
    };

    int[] colors = new int[]{
            ContextCompat.getColor(context, R.color.tint),
            ContextCompat.getColor(context, R.color.primary),
    };

    setSupportBackgroundTintList(new ColorStateList(states, colors));

不幸的是,这些状态不起作用。该按钮仅显示启用的颜色。我正在使用最新的 appcompat 库,也尝试过旧的

compile 'com.android.support:appcompat-v7:23.1.1'  //also tried 23.0.1
compile 'com.android.support:design:23.1.1'        //also tried 23.0.1

我做错了什么?

最佳答案

状态按照定义的顺序进行匹配。所以,android.R.attr.state_enabled将匹配之前 android.R.attr.state_pressed .

由于启用了按钮,第一个正匹配项将针对 android.R.attr.state_enabled和颜色ContextCompat.getColor(context, R.color.tint)将被选中。由于已找到正匹配项,是否按下按钮并不重要

解决这个问题的最快方法是放置 android.R.attr.state_pressed之前android.R.attr.state_enabled .状态匹配将如下进行:

  • 按钮当前被按下 --> 状态 android.R.attr.state_pressed将进行检查并找到正匹配项 --> 颜色 ContextCompat.getColor(context, R.color.primary)将被使用。

  • 按钮当前按下 --> 状态 android.R.attr.state_pressed将被检查并且检查将失败 --> state android.R.attr.state_enabled将进行检查并找到正匹配项 --> 颜色 ContextCompat.getColor(context, R.color.tint)将被使用。

这应该有效:

int[][] states = new int[][]{
        new int[]{android.R.attr.state_pressed}, // pressed
        new int[]{android.R.attr.state_enabled} // enabled
};

int[] colors = new int[]{
        ContextCompat.getColor(context, R.color.primary),
        ContextCompat.getColor(context, R.color.tint)
};

setSupportBackgroundTintList(new ColorStateList(states, colors));

关于android - setSupportBackgroundTintList 状态不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34040836/

相关文章:

android - 流激活蜂鸣

android - 如何为 firebase 性能监控创建空操作版本

android - SQLBrite 会自动关闭游标吗?

android - ActionBarActivity 和 Fragment Activity 的区别

android - 如何在不使用支持库的情况下创建新的 android 项目?

android - 在 AppCompat 中找不到资源

android - "WindowManager BadTokenException-Unable to add window"为什么我在使用谷歌地图时出现此异常?

java - 从像素数组计算平均值时出现 ArrayIndexOutOfBoundsException

android - AppcompatActivity:OutMemoryException

android - 向 AppCompatActivity 添加抽屉导航