Skip to content

Instantly share code, notes, and snippets.

@mkrupal09
Created October 8, 2018 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkrupal09/f92853181b383fd5c7617d13574fb654 to your computer and use it in GitHub Desktop.
Save mkrupal09/f92853181b383fd5c7617d13574fb654 to your computer and use it in GitHub Desktop.
<declare-styleable name="SelectorImageView">
<attr name="selectedDrawable" format="reference" />
<attr name="unselectedDrawable" format="reference" />
</declare-styleable>
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.util.StateSet;
public class SelectorImageView extends android.support.v7.widget.AppCompatImageView {
public SelectorImageView(Context context) {
super(context);
init(null);
}
public SelectorImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
private void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.SelectorImageView);
Drawable selectedDrawable = a.getDrawable(R.styleable.SelectorImageView_selectedDrawable);
Drawable unselectedDrawable = a.getDrawable(R.styleable.SelectorImageView_unselectedDrawable);
setImageDrawable(getStateList(selectedDrawable, unselectedDrawable));
a.recycle();
}
}
public SelectorImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
public Drawable getStateList(Drawable selected, Drawable unselected) {
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{android.R.attr.state_selected}, selected);
stateListDrawable.addState(new int[]{-android.R.attr.state_selected}, unselected);
stateListDrawable.addState(StateSet.WILD_CARD, unselected);
return stateListDrawable;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment