Search code examples
androidandroid-toolbar

How to change Toolbar height and font size programmatically depending of text length


I have a lot of different titles for Toolbar that I pass from previous activity trough intent:

title = getIntent().getStringExtra("title");

And I set them to my Toolbar of new activity like this:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle(title);

But the font is too large and only covers one line of toolbar: enter image description here

This is one of the example titles: CONVERSION OF RADAR RANGE PROPAGATION KILOMETER INTO MICROSECOND TIME AND VICE-VERSA

I would like to know is there a way to dynamically change Toolbar height and text size to fit this titles? Can this be done programmatically?

Thanks


Solution

  • try this create custom toolbar 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"
         app:popupTheme="@style/AppTheme.PopupOverlay">
    
            <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Did you know"
                android:id="@+id/myTitle"
                android:textColor="@android:color/white" />
        </LinearLayout>
    </android.support.v7.widget.Toolbar>
    

    and use theme of your activity as NoActionBar

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    TextView myTitle = (TextView) toolbar.findViewById(R.id.myTitle);