How to use selector to tint imageview in android

匿名 (未验证) 提交于 2019-12-03 01:55:01

问题:

I want to tint my tabhost's icons using xml, instead of doing it programatically (I wasn't able to do that anyway)... So I found this thread on SO: Android imageview change tint to simulate button click

That seems to be a pretty good solution, but I wasn't able to adapt it correctly in my project... I did the following changes:

public class TintableImageView extends ImageView { private ColorStateList tint;  public TintableImageView(Context context) {     super(context); }  //this is the constructor that causes the exception public TintableImageView(Context context, AttributeSet attrs) {     super(context, attrs);     init(context, attrs, 0); }  public TintableImageView(Context context, AttributeSet attrs, int defStyle) {     super(context, attrs, defStyle);     init(context, attrs, defStyle); }  //here, obtainStyledAttributes was asking for an array private void init(Context context, AttributeSet attrs, int defStyle) {     TypedArray a = context.obtainStyledAttributes(attrs, new int[]{R.styleable.TintableImageView_tint}, defStyle, 0);     tint = a.getColorStateList(R.styleable.TintableImageView_tint);     a.recycle(); }  @Override protected void drawableStateChanged() {     super.drawableStateChanged();     if (tint != null && tint.isStateful())         updateTintColor(); }  public void setColorFilter(ColorStateList tint) {     this.tint = tint;     super.setColorFilter(tint.getColorForState(getDrawableState(), 0)); }  private void updateTintColor() {     int color = tint.getColorForState(getDrawableState(), 0);     setColorFilter(color); }  } 

I also wasn't able to reference @drawable/selector.xml at android:tint, so I did this at colors.xml:

 #2e7cb4@drawable/tab_icon_selector

My selector:

  

My tab layout:

 

Any suggestions? Thanks in advance

[EDIT] I was getting a NumberFormatException for using android:tint, when the correct was app:tint (after setting xmlns:app="http://schemas.android.com/apk/res/com.myapp")... but now I think I'm using my selector in a wrong way, because the icons are all black, no matter the state... I've tried setting @drawable/tab_icon_selector from within colors.xml, didn't work

[/EDIT]

回答1:

In reference to my solution at https://stackoverflow.com/a/18724834/2136792, there are a few things you're missing:

TintableImageView.java

@Override protected void drawableStateChanged() {     super.drawableStateChanged();     if (tint != null && tint.isStateful())         updateTintColor(); }  public void setColorFilter(ColorStateList tint) {     this.tint = tint;     super.setColorFilter(tint.getColorForState(getDrawableState(), 0)); }  private void updateTintColor() {     int color = tint.getColorForState(getDrawableState(), 0);     setColorFi
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!