tags:

views:

489

answers:

2

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

+2  A: 

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);

}
Yoni Samlan
so is it the layoutID that I need? I noticed the updateAppWidget method doesn't use it.
Eclipsed4utoo
sorry - i missed a line; fixed that. What you need is to make a new RemoteViews with the package name and layout id to pass to updateAppWidget.
Yoni Samlan
A: 

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);
Eclipsed4utoo
right. sorry, i accidentally nuked a few lines when copying from my code. fixed that up.
Yoni Samlan