Set android shape color programmatically -
i editing make question simpler, hoping helps towards accurate answer.
say have following oval
shape:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <solid android:angle="270" android:color="#ffff0000"/> <stroke android:width="3dp" android:color="#ffaa0055"/> </shape>
how set color programmatically, within activity class?
note: answer has been updated cover scenario background
instance of colordrawable
. tyler pfaff, pointing out.
the drawable oval , background of imageview
get drawable
imageview
using getbackground()
:
drawable background = imageview.getbackground();
check against usual suspects:
if (background instanceof shapedrawable) { // cast 'shapedrawable' shapedrawable shapedrawable = (shapedrawable) background; shapedrawable.getpaint().setcolor(contextcompat.getcolor(mcontext,r.color.colortoset)); } else if (background instanceof gradientdrawable) { // cast 'gradientdrawable' gradientdrawable gradientdrawable = (gradientdrawable) background; gradientdrawable.setcolor(contextcompat.getcolor(mcontext,r.color.colortoset)); } else if (background instanceof colordrawable) { // alpha value may need set again after call colordrawable colordrawable = (colordrawable) background; colordrawable.setcolor(contextcompat.getcolor(mcontext,r.color.colortoset)); }
compact version:
drawable background = imageview.getbackground(); if (background instanceof shapedrawable) { ((shapedrawable)background).getpaint().setcolor(contextcompat.getcolor(mcontext,r.color.colortoset)); } else if (background instanceof gradientdrawable) { ((gradientdrawable)background).setcolor(contextcompat.getcolor(mcontext,r.color.colortoset)); } else if (background instanceof colordrawable) { ((colordrawable)background).setcolor(contextcompat.getcolor(mcontext,r.color.colortoset)); }
note null-checking not required.
however, should use mutate()
on drawables before modifying them if used elsewhere. (by default, drawables loaded xml share same state.)
Comments
Post a Comment