Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Widget Layout Programmatically

Tags:

android

widget

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

like image 605
Ryan Alford Avatar asked Dec 07 '09 15:12

Ryan Alford


2 Answers

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

}
like image 124
Yoni Samlan Avatar answered Nov 07 '22 03:11

Yoni Samlan


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);
like image 23
Ryan Alford Avatar answered Nov 07 '22 03:11

Ryan Alford