Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting layout id from string, won't work

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

like image 525
Jakob Avatar asked Dec 17 '12 21:12

Jakob


2 Answers

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.

like image 56
devunwired Avatar answered Nov 05 '22 00:11

devunwired


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.

like image 31
qzikl Avatar answered Nov 04 '22 23:11

qzikl