Created
October 8, 2018 14:23
-
-
Save mkrupal09/f92853181b383fd5c7617d13574fb654 to your computer and use it in GitHub Desktop.
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
<declare-styleable name="SelectorImageView"> | |
<attr name="selectedDrawable" format="reference" /> | |
<attr name="unselectedDrawable" format="reference" /> | |
</declare-styleable> |
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
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