Android Selector Drawable doesnt work with attributes

天大地大妈咪最大 提交于 2019-11-30 05:19:48
mudit

Finally, found the problem. There is a bug in android [pre-lollipop] OS which doesnt allow you to use attr in drawable. Here is the link to bug:

https://code.google.com/p/android/issues/detail?id=26251

Android dev team has released a fix but it works on android L and above.For workaround to this problem, refer to following solution:

How to reference style attributes from a drawable?

I dunno if it's still relevant to you, but I was struggling with the same thing and I think I have found a workaround (kinda). The direct use of ?attr/ is not working (working on api 21 and up, but even then it's not working with color selectors (only with drawables).

So I did it like this (giving you my own example). Create an atribute in attr.xml

<attr name="nav_item_color_selector" format="reference|color"/>

Then in all the themes you're using, add the attribute like so (f.e. for the Light Theme):

<item name="nav_item_color_selector">@color/text_color_selector_light</item>

or for the dark theme(default):

<item name="nav_item_color_selector">@color/text_color_selector</item>

Now my text_color_selector.xml (both) look like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"
      android:color="@color/myAccentColor" />
<item android:state_selected="false" 
      android:color = "@color/myTextPrimaryColor"/>
<item android:color="@color/myTextPrimaryColor" />

and when I want to use them, f.e in tinting my custom image view, I use:

    <com.yourdomain.yourpackage.NavDrawerIcon
    android:layout_width="24dp"
    android:layout_height="24dp"
    android:layout_gravity="center_vertical"
    android:src="@mipmap/ic_launcher"
    android:id="@+id/nav_item_icon"
    android:layout_margin="24dp"
    android:tint = "?attr/nav_item_color_selector"
    android:tintMode="src_atop"/>

You can also reitieve it programmatically by using TypedValue, like so:

    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = context.getTheme();
    theme.resolveAttribute(R.attr.nav_item_color_selector, typedValue, true);
    XmlResourceParser parser = viewGroup.getContext().getResources().getXml(typedValue.resourceId);
    try {
        ColorStateList sl = ColorStateList.createFromXml(viewGroup.getContext().getResources(), parser);
        viewHolder.textView.setTextColor(sl);

    } catch (Exception e) {  }

I hope this helps :-)

In stead of putting a "?" Change it to "@"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!