I have some styles defined in my res/values/styles.xml file:
<style name="calculatorButton">
<item name="android:textSize">25sp</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">@color/black100</item>
<item name="android:gravity">center</item>
<item name="android:clickable">true</item>
<item name="android:layout_width">0dp</item>
<item name="android:layout_height">match_parent</item>
<item name="android:layout_weight">1</item>
</style>
Now i want to extract the whole list of attributes programmatically, but without the need of naming them all one by one. Means the described approach of using the "obtainStyledAttributes()" function doesn't fit my needs.
I do not need to get an "exact" representation or object of the attribute values (or their Classes), like "int", "String" or "Color".
For me it would be absolutely enough when i get (let's say) a simple mapping of key - value pairs in the form of some strings.
"android:textColor" -> "@color/black100"
"android:gravity" -> "center"
It would be also fine, when their is a possibility to just get the "raw" format of the content of the style or the whole file. Then i would parse it on my own with the help of some DocumentBuilder etc.
But like i have learned this seems to be not possible for resources below the res/values folder because of pre-compilation etc. And i do not want to simply copy+paste the file to the assets folder, the res/raw folder or somewhere else, because of code duplication.
Now if you're all wondering why I need this. We get different XML-strings from some JNI-calls that are representing specific layouts that we are currently parsing on our own and than creating the related view objects programmatically and setting all the specific configurations.
Button bt = new Button(activityMain);
bt.setTag(tag);
bt.setLayoutParams(params);
bt.setTextColor(color);
The challenge that we now have is, that we want to use the styles that we have defined on java side. Therefore we extract the value of the "style" attribute from the given XML-string and are searching for the related resource id and than use it as the 4-th argument in the constructor.
int styleID = activityMain.getResources().getIdentifier(
styleName,
"style",
activityMain.getPackageName()
);
Button bt = new Button(activityMain, null, 0, styleID);
The problem here is, that sadly not all views (that we have currently implemented in our own parser) are supporting the 4-argument constructor, like MaterialButton or AppCompatTextView and many more.
Also the other constructor variants with AttributeSet or defStyleAttr are not working, either it fails because of some ClassCastException or some specific style attributes are skipped.
That's why it's maybe now my last approach to somehow extract all the values from the wished style and than feed (like before) our own parser and let him execute the needed function calls to modify our views.
If you have other ideas how to reach my goal please let me know.