Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting SupportActionBar subtitle multiline

I have the following setup:

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:subtitleTextAppearance="@style/TitleTextStyle"
        app:theme="@style/ActionBarStyle.Light"/>

and

<style name="TitleTextStyle">
    <item name="android:maxLines">2</item>
    <item name="android:textAllCaps">false</item>
</style>

and

getSupportActionBar().setSubtitle( targetString );

the @textAllCaps is applied, but @maxLines is ignored (I tried also `@minLines).

How to enable multiline text in subtitle?

TIA

UPDATE:

I added the code into the onStart:

@Override
public void onStart() {
    super.onStart();
    try{
      Field field = Toolbar.class.getDeclaredField( "mSubtitleTextView" );
      field.setAccessible( true );
      subtitleTextView = (TextView)field.get( toolbar );
      subtitleTextView.setSingleLine( false );
      subtitleTextView.setMaxLines( 2 );
      subtitleTextView.setEllipsize( TruncateAt.END );
    }catch( Exception e ) {
      Logg.e( this, "", e );
    }
}

the problem is now, that the ellipsize values are applied, but setMaxLines() call is ignored...

UPD2:

setSingleLine( false ) did the trick.

like image 413
injecteer Avatar asked Jul 20 '15 11:07

injecteer


1 Answers

Unfortunately, maxLines is not a part of TextAppearance so changing it will not affect the subtitle appearance. Moreover, there's no legal way to access Toolbar.mSubtitleTextView, but after setting a subtitle text you can access it via reflection and change its appearance as you wish.

UPDATE:

That's how you can access mSubtitleTextView via reflection.

public class SubtitleAccessor {
    private static final Field sSubtitleTextViewField = getSubtitleTextViewField();

    private static Field getSubtitleTextViewField() {
        try {
            Field field = Toolbar.class.getDeclaredField("mSubtitleTextView");
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException exception) {
            return null;
        }
    }

    public static TextView getSubtitleTextView(Toolbar toolbar) {
        if (sSubtitleTextViewField == null) {
            return null;
        }

        try {
            return (TextView) sSubtitleTextViewField.get(toolbar);
        } catch (IllegalAccessException exception) {
            return null;
        }
    }
}
like image 199
Michael Avatar answered Oct 26 '22 09:10

Michael