The solution I found The goal is to create elements programmatically that were previously styled somewhere else.
First, I created a new XML file in the res/layout folder. I named it template.xml and inserted the following code in it:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
style="@style/rootElement"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/firstChildId"
style="@style/firstChild" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/secondChild" />
</LinearLayout>
And then I styled then the way I wanted in styles.xml file
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="rootElement">
<!-- style -->
</style>
<style name="firstChild">
<!-- style -->
</style>
</resources>
Now, in my Activity class I added:
LinearLayout rootElement = (LinearLayout) getLayoutInflater().inflate(R.layout.template, null);
someOtherView.addView(rootElement);
The inflater will load the template we created in res/layout/template.xml (all the elements in that file and its attributes) and assign it to rootElement
that is then used in my code for anything else. Example
TextView firstChild = (TextView) rootElement.getChildAt(0);
firstChild.setText("It is the firstChild element");
or
TextView firstChild = (TextView) rootElement.findViewById(R.id.firstChildId);
...
Quite easy, isn't it?! I hope that helps