Last active
August 29, 2015 14:01
-
-
Save TheLittleNaruto/82bfee0992e12ce1bb61 to your computer and use it in GitHub Desktop.
Dynamically assign colors in StateListDrawable
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
/*I am sharing if you want to assign dynamically colors of buttons from the users for normal as well as pressed state. then you can just call this function :*/ | |
public static StateListDrawable convertColorIntoBitmap(String pressedColor, String normalColor){ | |
/*Creating bitmap for color which will be used at pressed state*/ | |
Rect rectPressed = new Rect(0, 0, 1, 1); | |
Bitmap imagePressed = Bitmap.createBitmap(rectPressed.width(), rectPressed.height(), Config.ARGB_8888); | |
Canvas canvas = new Canvas(imagePressed); | |
int colorPressed = Color.parseColor(pressedColor); | |
Paint paintPressed = new Paint(); | |
paintPressed.setColor(colorPressed); | |
canvas.drawRect(rectPressed, paintPressed); | |
RectF bounds = new RectF(); | |
bounds.round(rectPressed); | |
/*Creating bitmap for color which will be used at normal state*/ | |
Rect rectNormal = new Rect(0, 0, 1, 1); | |
Bitmap imageNormal = Bitmap.createBitmap(rectNormal.width(), rectNormal.height(), Config.ARGB_8888); | |
Canvas canvasNormal = new Canvas(imageNormal); | |
int colorNormal = Color.parseColor(normalColor); | |
Paint paintNormal = new Paint(); | |
paintNormal.setColor(colorNormal); | |
canvasNormal.drawRect(rectNormal, paintNormal); | |
/*Now assigning states to StateListDrawable*/ | |
StateListDrawable stateListDrawable= new StateListDrawable(); | |
stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, new BitmapDrawable(imagePressed)); | |
stateListDrawable.addState(StateSet.WILD_CARD, new BitmapDrawable(imageNormal)); | |
return stateListDrawable; | |
} | |
/*Now all you need is to set it as your textview or button background like below :*/ | |
if(android.os.Build.VERSION.SDK_INT>=16){ | |
yourbutton.setBackground(convertColorIntoBitmap("#CEF6CE00","#4C9D32")); | |
}else{ | |
yourbutton.setBackgroundDrawable(convertColorIntoBitmap("#CEF6CE00","#4C9D32")); | |
} | |
/*Here you can see all you need to pass the colors dynamically and we're done. hope this will help someone :)*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment