How to set custom attributes of custom components programmatically?

I have a custom component called CircleView and I want to change the custom fillColor attribute defined in attrs.xml :

 <declare-styleable name="CircleView"> <attr name="radius" format="integer" /> <attr name="fillColor" format="color" /> </declare-styleable> 

I initially installed it in my XML layout, which currently looks like this (namespace CircleView is defined as xmlns:circleview="http://schemas.android.com/apk/res-auto" ; it works fine when I I define it in XML, so this should not be a problem)

 <com.mz496.toolkit.CircleView ... circleview:fillColor="#33ffffff"/> 

I can only get the fillColor attribute in my CircleView , which extends the View , but I don't know how to set its value.

I researched things like setBackgroundColor , and searched for other "installed" methods, but I could not find them. I imagined a method like

circle.setAttribute(R.styleable.CircleView_fillColor, "#33ff0000")

+6
source share
1 answer

A CircleView in the layout is nothing more than an instance of the CircleView class, so just add a function to CircleView.java :

 public void setFillColor(int newColor) { fillColor = newColor; } 

And then call it if necessary:

 CircleView circle_view = (CircleView) findViewById(R.id.circle_view); circle_view.setFillColor(0x33ffffff); circle_view.invalidate(); 

Also note that this simply changes the internal variable, but you still need to redraw the user component using the invalidate() method of the View class, since the user component is automatically redrawn automatically if the whole view is redrawn, for example, when switching fragments (see Forcing viewing for redrawing ).

(I realized this at the very end, when I just wanted to ask: “Would I need to determine this myself?” And I tried to determine it myself, and it worked.)

+3
source

All Articles