Looked through every question, can't get it working.
I wanna set an AppWidgets layout with the value of a string (So the layout can be switched to another one by just changing the string).
String NoteString = "R.layout.widget_blue".toString();
int resID = context.getResources().getIdentifier(NoteString, "layout", context.getPackageName());
RemoteViews views = new RemoteViews(context.getPackageName(), resID);
don't know why it doesn't work, widget just says: "problem loading widget"..
This works fine:
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_blue);
Thanks
In order to construct a resource ID from string components, you must pass the individual components into getIdentifier()
, not the fully qualified ID as a single parameter:
//Get the ID for R.layout.widget_blue
int resID = context.getResources().getIdentifier("widget_blue", "layout", context.getPackageName());
Then just change the first parameter name to get a different layout resource.
Why are you using getIdentifier for this? Since you're including the hard-coded string in there anyway, why not just use the resource identifier included anyway, as you've done in the second example. That's much more efficient, as stated in the documentation on the getIdentifier() method:
Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With