JoachimR
JoachimR

Reputation: 5258

Android home screen widget textsize dynamically

There are applications that offer the ability to change the font size of a text in a home screen widget. One example is https://play.google.com/store/apps/details?id=org.zooper.zwfree

However home screen widgets only can carry RemoteViews so setting the textSize of a TextView dynamically will not work.

As I see it there are two possibilities to change the text size dynamically:

My question is: Is there a third possibility left?

Upvotes: 2

Views: 3132

Answers (1)

TWiStErRob
TWiStErRob

Reputation: 46498

If you're targeting API level 16 or above, you can try the following:

Sadly the whole thing depends on knowing the widget size, which is only possible in API 16+.

  1. Override the AppWidgetProvider.onAppWidgetOptionsChanged callback
    or get the same Bundle later via AppWidgetManager.getAppWidgetOptions
  2. Extract the size of the widget:
    • options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)
    • options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH)
    • options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT)
    • options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT)
  3. Deduce your TextView's width from the widget size
    (best if you have it match_parent to the root of the widget, mind margins/paddings)
  4. If you have complex layout you can alternatively
    • inflate the whole widget in your app space
      widget = LayoutInflater.from(context).inflate(R.layout.widget, null)
    • Simulate a layout based on the framework:
      widget.measure(MeasureSpec.makeMeasureSpec(widgetWidth, MeasureSpec.EXACTLY), ...).
    • Get your TextView's size: widget.findViewById(R.id.myText).getMeasuredWidth()
  5. Use something like refitText here to find your optimal size
  6. Set the calculated size via RemoteViews.setTextViewTextSize

Note: I didn't implement this method, just thought about it.

Try not to do this on every update, cache the results (even in preferences), widget options shouldn't change often.

Upvotes: 2

Related Questions