4

I have this android.support.v7.widget.Toolbarand the setTitle() text I want to show sometimes does not show completely. I look for some sort of auto-resize like the android-autofittextview to use for the toolbar but of course that one dont work in toolbar Then I read about the CollapsingToolbarLayout but I dont want that advanced toolbar. Actually I tried it but text was not resized to show all letters. maybe i did something wrong but anyway:)

Can anybody advice me what to do?

Community
  • 1
  • 1
Tord Larsen
  • 2,670
  • 8
  • 33
  • 76

3 Answers3

1

you can add this line to your toolbar

app:titleTextAppearance="@style/styleX"

your toolbar gonna be like this

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:gravity="center"
app:titleTextAppearance="@style/styleX"
android:minHeight="?attr/actionBarSize"
app:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

here is the style

<style name="styleX" parent="@style/Base.TextAppearance.AppCompat.Title">
       <item name="android:textSize">20sp</item>
</style>

you can change 20sp dynamically if you want using dimens.xml

Yassine BELDI
  • 562
  • 5
  • 16
  • But how can I know programmatically during runtime that the `20sp` value is correct so that all text is resized and fully showend? – Tord Larsen Dec 15 '16 at 18:48
  • 1
    test and change in dimens.xml for different size, because programmatically getting the device density and change it sometimes doesn't work for some devices – Yassine BELDI Dec 15 '16 at 18:52
  • 1
    yes what you say I can do but I was looking for some widget or hack like the wonderful [autofittextview](https://github.com/grantland/android-autofittextview). – Tord Larsen Dec 15 '16 at 18:59
0
val toolbarText = binding.toolbar.getChildAt(1) as TextView
toolbarText.setHorizontallyScrolling(false)
toolbarText.gravity = Gravity.START or Gravity.CENTER_VERTICAL
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(toolbarText, 1, 20, 1, TypedValue.COMPLEX_UNIT_SP)

The child index may differ if you have (not) up action.

hrach
  • 2,443
  • 2
  • 26
  • 37
0

Set AutoSize for all Toolbar TextViews (title & subtitle)

 public static void setToolbarTextAutoSize(Toolbar toolbar) {
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            View view = toolbar.getChildAt(i);
            if (view instanceof TextView) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    ((TextView) view).setHorizontallyScrolling(false);
                    ((TextView) view).setAutoSizeTextTypeWithDefaults(TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM);
                }
            }
        }
    }
wiz
  • 321
  • 2
  • 4