I am building a widget for my Android application that will have several buttons on it. Based on the size of the widget, I want the amount of buttons on the widget to grow and s
Like they already said. You can use onAppWidgetOptionsChanged
So my proposition is to
1) Make different layouts. With 3 and 4 buttons.
2) Change the layout base on widget column count.
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
// See the dimensions and
Bundle options = appWidgetManager.getAppWidgetOptions(appWidgetId);
// Get min width and height.
int minWidth = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
int minHeight = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
// Obtain appropriate widget and update it.
appWidgetManager.updateAppWidget(appWidgetId, getRemoteViews(context, minWidth, minHeight));
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
}
/**
* Determine appropriate view based on row or column provided.
*
* @param minWidth
* @param minHeight
* @return
*/
private RemoteViews getRemoteViews(Context context, int minWidth, int minHeight) {
// First find out rows and columns based on width provided.
int rows = getCellsForSize(minHeight);
int columns = getCellsForSize(minWidth);
// Now you changing layout base on you column count
// In this code from 1 column to 4
// you can make code for more columns on your own.
switch (columns) {
case 1: return new RemoteViews(context.getPackageName(), R.layout.activity_layout_widget_1column);
case 2: return new RemoteViews(context.getPackageName(), R.layout.activity_layout_widget_2column);
case 3: return new RemoteViews(context.getPackageName(), R.layout.activity_layout_widget_3column);
case 4: return new RemoteViews(context.getPackageName(), R.layout.activity_layout_widget_4column);
default: return new RemoteViews(context.getPackageName(), R.layout.activity_layout_widget_4column);
}
}
/**
* Returns number of cells needed for given size of the widget.
*
* @param size Widget size in dp.
* @return Size in number of cells.
*/
private static int getCellsForSize(int size) {
int n = 2;
while (70 * n - 30 < size) {
++n;
}
return n - 1;
}