Other questions say that the style cannot be set programmatically, but a View
can be initialised with a style such as when it is loaded from XML.
How can I initialise a View
with a particular style programmaticly (not in XML)? I tried using View(Context context, AttributeSet attrs, int defStyle), but I don't know what to parse in for the second argument. Passing in null
results in the View
not being displayed
Best Answer
I'm having the same problem, but haven't found any practical way to directly set a style programmatically, so far. I would like to populate my screen with a lot of widgets, of a given type, let's say buttons. It is impractical to define them all in the layout file. I would like to create them programmatically, but I would also like to define their style in a style xml file.
The solution I have devised consists in defining just one of those widgets in the layout file, create all the others programmatically, and clone the style info from the first one to the other ones.
An example follows.
In the style file, define the style for your buttons. For example:
Then subclass class "Button", by deriving a class "NiceButton". Define the constructor that will be needed by the inflater:
Then define another constructor, which purpose is to clone an existing button:
In your layout file, define just the first one of your buttons. Suppose for example that you want to put your buttons in a table:
Notice that the full qualified name of the widget class is used; obviously, you will have to replace com.mydomain.mypackage with the actual package name.
In your activity, you may want to define an array which is going to hold a reference to all of the buttons, and a common listener to be called when any of the buttons is pressed:
Notice how the view id is used as an index in the array of buttons. So you will need your buttons to have an id from 0 to n-1.
Finally, here is the way you can create your buttons in the onCreate method:
Here's how the screen appears after you have pressed some buttons:
Well, there's some code involved, but in the end you can create as many widgets you want programmatically, and still have their attributes defined as a style.