Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 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 Answer

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()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...