Issue
I am able to get resource Id by string name by using the following
fun resIdByName(): Int {
return resources.getIdentifier("apple", "drawable", packageName)
}
but the issue is I have dark/light mood support in my app and this method is returning light image for dark mood and dark image for light mood.
I have search a lot on the internet but only found a way to get res from the name not how to get base on theme, so do not consider this a duplicate question.
Solution
Short answer: Don´t use setImageResource(Int id). Get the themed drawable with getResources().getDrawable(Int id, Resources.Theme theme) and use setImageDrawable(Drawable drawable) instead.
Explanation: Themed resources don´t have a particular id suffix/preffix; is the same ID across all themes, to avoid breaking the app. The theme is supposed to be applied beforehand, allowing all the theme-sensitive values to be replaced by the theme´s version. Usually, a visual context (activity) contains the reference, but depending on how/when you are trying to get the resource, you may get one with a different theming (application context for example will not have theme references), and because that, we have getDrawable(Int id, Resources.Theme theme) since api 22. That´s the root of your problem. When you call setImageDrawable(Int res), the imageView executes this block:
private void resolveUri() {
if (mDrawable != null) {
return;
}
if (getResources() == null) {
return;
}
Drawable d = null;
if (mResource != 0) {
try {
d = mContext.getDrawable(mResource);
} catch (Exception e) {
Log.w(LOG_TAG, "Unable to find resource: " + mResource, e);
// Don't try again.
mResource = 0;
}
} else if (mUri != null) {
d = getDrawableFromUri(mUri);
if (d == null) {
Log.w(LOG_TAG, "resolveUri failed on bad bitmap uri: " + mUri);
// Don't try again.
mUri = null;
}
} else {
return;
}
updateDrawable(d);
}
as you can see, it uses the deprecated Context.getDrawable(Int id) method. So the drawable will, at best, match the theme reference in the context, if any. In your widget, the call likely happens before the rest of the change happens. So, specify the desired theme instead and you´ll be okay.
Answered By - Fco P.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.