Android:如何从资源中获取ColorStateList?

Ers*_*man 9 android

我正在制作一个导航抽屉,其中图标根据文本的颜色着色.

这是我在res/drawable中声明的选择器

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:color="@color/emerald"/>
    <item android:state_selected="true" android:color="@color/emerald"/>
    <item android:state_pressed="true" android:color="@color/emerald"/>
    <item android:color="@android:color/white"/>
</selector>
Run Code Online (Sandbox Code Playgroud)

这是我的ViewHolder

        Drawable drawable = ContextCompat.getDrawable(mContext,iconResourceId);
        drawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTintList(drawable.mutate(),mContext.gerResouces.getColorStateList());
         mItemIcon.setImageDrawable(drawable);
Run Code Online (Sandbox Code Playgroud)

正如你可以看到我遇到的问题是在这一行,我在getColorStateList中传递了什么?doucmentation没有帮助我.

DrawableCompat.setTintList(drawable.mutate(),mContext.gerResouces.getColorStateList());
Run Code Online (Sandbox Code Playgroud)

peu*_*hse 12

ColorStateList colorStateList = ContextCompat.getColorStateList(this, R.color.your_color_selector);
snackBar.setActionTextColor(colorStateList);
Run Code Online (Sandbox Code Playgroud)


Kar*_*uri 11

传递颜色状态列表资源的id,例如R.color.my_color_state_list.颜色状态列表属于res/color,而不是res/drawable.

DrawableCompat.setTintList(drawable.mutate(),
    mContext.getResources().getColorStateList(R.color.my_color_state_list));
Run Code Online (Sandbox Code Playgroud)

  • 现在已弃用,请使用“ContextCompat.getColorStateList()”。请参阅@peuhse 的回答。 (4认同)