Created
March 17, 2015 16:36
-
-
Save tylerchesley/5d15d859be4f3ce31213 to your computer and use it in GitHub Desktop.
Backwards compatible TintableImageView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<resources> | |
<declare-styleable name="TintableImageView"> | |
<attr name="tint" format="reference|color" /> | |
</declare-styleable> | |
</resources> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<selector xmlns:android="http://schemas.android.com/apk/res/android"> | |
<item android:state_pressed="true" android:color="@color/pressed_color"/> | |
<item android:color="#00000000"/> | |
</selector> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.widgets; | |
import android.content.Context; | |
import android.content.res.ColorStateList; | |
import android.content.res.TypedArray; | |
import android.util.AttributeSet; | |
import android.widget.ImageView; | |
import com.example.R; | |
public class TintableImageView extends ImageView { | |
private ColorStateList tint; | |
public TintableImageView(Context context) { | |
super(context); | |
} | |
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); | |
} | |
private void init(Context context, AttributeSet attrs, int defStyle) { | |
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TintableImageView, 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment