When you’re using different kind of styles in your project, the best way to accomplish this is to use the styles.xml file where you can define different style definitions for your views. These styles can be applied very easily, like:
<TextView android:id="@+id/txtName" android:text="TextView" style="@style/NameText" />
This is all done, using declarative xml syntax. But what if you are forced to create views programmatically?
There is no view.setStyle(“NameText”) method, so how do can we define them in code?
There is a small workaround which might come in handy:
Button b = (Button) getLayoutInflater().inflate(R.layout.template_button, null); b.setText(category.getName());
This code is creating a button, using the layoutinflator method. This method is using xml layout template to use a base for the button.
This layout file is looking like this:
<?xml version="1.0" encoding="utf-8"?> <Button xmlns:android="http://schemas.android.com/apk/res/android" android:text="Date" style="@style/WhiteButton"/>
As you can see, just a definition of a button with style included.
All quit simple but very powerfull. If you’ve to use styling programmatically, this is a option. The downside is that you have to create layouts for each option. But if you’re using just a few options, this surely is the way to go!
Besides that, it’s very maintainable.