Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

android - Drawable tinting in RecyclerView for pre-Lollipop

I am trying to use drawable tinting using the following code in my RecyclerView

Drawable likeDrawable = ContextCompat.getDrawable(getActivity(), R.drawable.ic_thumb_up);
Drawable likeWrappedDrawable = DrawableCompat.wrap(likeDrawable);
DrawableCompat.setTint(likeWrappedDrawable,ContextCompat.getColor(getActivity(), android.R.color.white));
holder.ivLike.setImageDrawable(likeWrappedDrawable);

Now all of this is being done in the onBindViewHolder of the RecyclerView Adapter

I change this tint between three colors based on the state of that list item. This works all fine for Lolipop and above but below this version, the color of the list item is unpredictable. Sometimes it shows the right color but on refreshing the list sometimes it changes to some other color.

Anything im doing wrong here or the tinting thing on pre-lollipop is still unusable in this particular case?

Update

Including the code from my onBindViewHolder

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    Drawable likeDrawable =
        ContextCompat.getDrawable(getActivity(), R.drawable.ic_thumb_up);

    Drawable likeWrappedDrawable = DrawableCompat.wrap(likeDrawable);

    holder.tvLikeCount.setTextColor(ResUtil.getColor(R.color.light_font,
        getActivity()));

    DrawableCompat.setTint(likeWrappedDrawable,
        ContextCompat.getColor(getActivity(), android.R.color.white));

    if (tweetModel.isFavorited()) {
        DrawableCompat.setTint(likeWrappedDrawable,
            ContextCompat.getColor(getActivity(), android.R.color.holo_blue_light));
    }

    holder.ivLike.setImageDrawable(likeWrappedDrawable);

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Call mutate() on the Drawable before calling setTint()

Drawable likeDrawable = ContextCompat.getDrawable(getActivity(), R.drawable.ic_thumb_up).mutate();

By default, all drawables instances loaded from the same resource share a common state; if you modify the state of one instance, all the other instances will receive the same modification. http://developer.android.com/reference/android/graphics/drawable/Drawable.html#mutate()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...