Tech tip of this week

Android: Autosizing TextViews

Android O introduced new feature to autosize the Textview based on its layout. This setting makes it easier to optimize the text size on different screens with dynamic content.

The Support Library 26.0 Beta provides full support to the autosizing TextView feature on devices running Android versions prior to Android O. The library provides support to Android 4.0 (API level 14) and higher. The android.support.v4.widget package contains the TextViewCompat class to access features in a backward-compatible fashion

There are three ways you can set up the autosizing of TextView:

  • Default
  • Granularity
  • Preset Sizes
Default:

To define the default setting in XML, use the android namespace and set the autoSizeTextType attribute to none or uniform.

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:autoSizeTextType="uniform"
  />
Granularity:

You can define a range of minimum and maximum text sizes and a dimension that specifies the size of each step. The TextView scales uniformly in a range between the minimum and maximum size attributes. Each increment occurs as per the step size set in the granularity attribute.

<TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:autoSizeTextType="uniform"
  android:autoSizeMinTextSize="12sp"
  android:autoSizeMaxTextSize="100sp"
  android:autoSizeStepGranularity="2sp"
/>

Preset Sizes:

Preset sizes lets you specify all the values that the TextView picks when automatically auto-sizing text.

To use preset sizes to set up the autosizing of TextView in XML, use the android namespace and set the following attributes:
  • Set the autoSizeText attribute to either none or uniform. none is a default value and uniform lets TextView scale uniformly on horizontal and vertical axes.
  • Set the autoSizePresetSizes attribute to an array of preset sizes. To access the array as a resource, define the array in the res/values/arrays.xml file.

    <resources>
      <array
        name="autosize_text_sizes">
        <item>10sp</item>
        <item>12sp</item>
        <item>20sp</item>
        <item>40sp</item>
        <item>100sp</item>
      </array>
    </resources>
    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:autoSizeTextType="uniform"
      android:autoSizePresetSizes="@array/autosize_text_sizes"
    />

More information will be available in official Android developer documentation:
https://developer.android.com/preview/features/autosizing-textview.html#setting-textview-autosize

No comments:

Post a Comment