结合上面的答案和来自https://stackoverflow.com/a/7875656/6364860的可爱代码片段,我得到了它的工作方式:
*注意我有一个带文本的圆形按钮,所以我只需要最小的尺寸。
@Override
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions){
super.onAppWidgetOptionsChanged(context,appWidgetManager,appWidgetId,newOptions);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
int maxWidth = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH);
int maxHeight = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT);
int size = Math.min(maxHeight,maxWidth);
int pxSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,size,context.getResources().getDisplayMetrics());
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_button);
float newSize = refitText(context.getString(R.string.button_text),pxSize);
remoteViews.setTextViewTextSize(R.id.widget_text, TypedValue.COMPLEX_UNIT_PX,newSize);
appWidgetManager.updateAppWidget(appWidgetId,remoteViews);
}
}
private float refitText(String text, int textWidth)
{
if (textWidth <= 0)
return 0;
float hi = 100;
float lo = 2;
final float threshold = 0.5f; // How close we have to be
Paint testPaint = new Paint();
while((hi - lo) > threshold) {
float size = (hi+lo)/2;
testPaint.setTextSize(size);
if(testPaint.measureText(text) >= textWidth)
hi = size; // too big
else
lo = size; // too small
}
// Use lo so that we undershoot rather than overshoot
return lo;
}