Let's say that I have two layouts for a widget: Layout1 and Layout2. The default for the widget is Layout1, but I allow the user to choose which layout they want the widget to be. So if the user changes to Layout2, how do I programmatically change the layout to Layout2?
There isn't a setContentView method for widgets like there is for Activities.
Thanks
You have to choose the layout when you're building your remoteView. In my widget code:
public static RemoteViews buildUpdate(Context context, String action) {
RemoteViews updateViews;
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
String typeface = prefs.getString("typeface", "sans");
int layoutId = R.layout.widget_sans;
if ("monospace".equals(typeface)){
layoutId = R.layout.widget_mono;
} else if ("serif".equals(typeface)){
layoutId = R.layout.widget_serif;
}
updateViews = new RemoteViews(context.getPackageName(),
layoutId);
//actually do things here
//then finally, return our remoteView
AppWidgetManager.getInstance(context).updateAppWidget(
new ComponentName(context, FuzzyWidget.class), updateViews);
}
Thanks Yoni.
Just wanted to add to your code. When getting the RemoteViews object, you specify the Context and the Layout ID. This is where you set which layout you want to show.
For example...
RemoteViews views = null;
if (1 == 1)
views = new RemoteViews(m_context.getPackageName(), R.layout.Layout1);
else
views = new RemoteViews(m_context.getPackageName(), R.layout.Layout2);
AppWidgetManager.getInstance(context).updateAppWidget(
new ComponentName(context, FuzzyWidget.class), views);
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