material-components / material-components-android

Modular and customizable Material Design UI components for Android
Apache License 2.0
16.38k stars 3.07k forks source link

[MaterialToolbar] Error of subtitle alignment #2303

Closed zsemen closed 2 years ago

zsemen commented 3 years ago

Issue:

The subtitle is aligned to the left if text strings of the title and the subtitle are identical.

Steps: 1) Use MaterialToolbar for toolbar.. 2) Set both titleCentered and subTitleCentered to true 3) Set both tile and subTitle to the same vale, for example "aaa".

Example:

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.appbar.MaterialToolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:titleCentered="true"
        app:subtitleCentered="true"
        app:subtitle="aaa"
        app:title="aaa" />

</com.google.android.material.appbar.AppBarLayout>

Root cause is in the code line if (TextUtils.equals(textView.getText(), text)) that results in always returning the TextView of the title and the subTitle is not centered:

private void maybeCenterTitleViews() {
    ...
    TextView subtitleTextView = ToolbarUtils.getSubtitleTextView(this);
    ...
}

public class ToolbarUtils {
...
@Nullable
  public static TextView getSubtitleTextView(@NonNull Toolbar toolbar) {
    return getTextView(toolbar, toolbar.getSubtitle());
  }

  @Nullable
  private static TextView getTextView(@NonNull Toolbar toolbar, CharSequence text) {
    for (int i = 0; i < toolbar.getChildCount(); i++) {
      View child = toolbar.getChildAt(i);
      if (child instanceof TextView) {
        TextView textView = (TextView) child;
        if (TextUtils.equals(textView.getText(), text)) {
          return textView;
        }
      }
    }
    return null;
  }
}

Error_subtitle_alignment

matpag commented 3 years ago

@dsn5ft I could work on this but what should be the proper way to fix this? MaterialToolbar has 2 hidden methods for grabbing the correct TextView

Most reliable option could be to try to call those hidden methods with reflection and fallback to the current logic if methods are missing, what do you think?