我正在为我的Android应用程序构建一个小部件,它将有几个按钮。基于小部件的大小,我希望小部件上的按钮数量能够自动增加和缩小。以下是在4x1视图中的外观:
当你将它缩小到3x1时:
是否有任何方法在3x1视图中动态隐藏第四个按钮,以便其他三个按钮不会被挤压?同样适用于2x1或1x1。非常感谢您的任何意见!
谢谢!
![4x1 widget](https://istack.dev59.com/kvWn6.webp)
![3x1](https://istack.dev59.com/PlBMt.webp)
谢谢!
就像他们已经说的一样。您可以使用onAppWidgetOptionsChanged
因此,我的建议是:
1)创建不同的布局。有3个和4个按钮。
2)根据小部件列数更改布局。
@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;
}
getCellsForSize()
做了这样的处理呢?谢谢。 - olfekonAppWidgetOptionsChanged
- 不幸的是,API级别<16的用户将没有此功能。onAppWidgetOptionsChanged
中,使用newOptions Bundle提供的值,必须检测宽度和高度的变化,并按照文档中建议的方式设置大小桶(来自同一设计页面):
真正具有挑战性的是如何确定这些桶。newOptions Bundle具有min_width、min_height、max_width和max_height值,这些值在设备、屏幕密度、启动器等方面有很大的差异。不幸的是,Android团队没有向我们展示如何做到这一点,在网络上也很少有关于实际上,随着用户调整小部件的大小,系统将响应具有dp大小范围的操作,您的小部件可以在其中重新绘制自己。计划跨“大小桶”而不是可变网格尺寸的小部件调整策略将为您带来最可靠的结果。
onAppWidgetOptionsChanged
的代码示例,其中大多数非常简单。