Issue
Currently I am having four themes in my styles.xml file. (theme1, theme2, theme3, theme4).
I am having a test_image.xml in both drawable & drawable-theme1 folders.
What I need is, for theme1 alone, I need resources from drawable-theme1, and for other themes (theme2, theme3, theme4), I need resources from normal drawable folder.
Finally, while setting the image view programmatically, I will be calling imageView.setResource(R.drawable.test_image). The resource file must be retrieved based on my selected theme.
Whether this is possible?
I could not get any questions or similar relevant to this. If anyone has provided a solution already, please help me finding that. Thanks
Solution
You can't use <themeName>
as a qualifier.
It means that you can't use a drawable-themeName
folder.
However you can define a custom attribute in the attrs.xml
file:
<resources>
<attr name="myDrawable" format="reference" />
</resources>
Then in styles.xml
in the app theme you can define it:
<style name="AppTheme1" parent="Theme.MaterialComponents.DayNight">
<!-- ..... -->
<item name="myDrawable">@drawable/ic_add_24px</item>
</style>
Finally in a layout you can use something like:
<com.google.android.material.button.MaterialButton
....
app:icon="?attr/myDrawable"/>
or programmatically:
MaterialButton button = findViewById(R.id.button);
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.myDrawable, typedValue, true);
button.setIcon(ContextCompat.getDrawable(this,typedValue.resourceId));
Answered By - Gabriele Mariotti
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.