1616
1717package com .google .android .material .internal ;
1818
19+ import static java .util .Collections .max ;
20+ import static java .util .Collections .min ;
21+
1922import android .graphics .drawable .Drawable ;
2023import androidx .appcompat .view .menu .ActionMenuItemView ;
2124import androidx .appcompat .widget .ActionMenuView ;
3033import androidx .annotation .Nullable ;
3134import androidx .annotation .RestrictTo ;
3235import androidx .annotation .RestrictTo .Scope ;
36+ import java .util .ArrayList ;
37+ import java .util .Comparator ;
38+ import java .util .List ;
3339
3440/**
3541 * Utility methods for {@link Toolbar}s.
3945@ RestrictTo (Scope .LIBRARY )
4046public class ToolbarUtils {
4147
48+ private static final Comparator <View > VIEW_TOP_COMPARATOR =
49+ new Comparator <View >() {
50+ @ Override
51+ public int compare (View view1 , View view2 ) {
52+ return view1 .getTop () - view2 .getTop ();
53+ }
54+ };
55+
4256 private ToolbarUtils () {
4357 // Private constructor to prevent unwanted construction.
4458 }
4559
4660 @ Nullable
4761 public static TextView getTitleTextView (@ NonNull Toolbar toolbar ) {
48- return getTextView (toolbar , toolbar .getTitle ());
62+ List <TextView > textViews = getTextViewsWithText (toolbar , toolbar .getTitle ());
63+ return textViews .isEmpty () ? null : min (textViews , VIEW_TOP_COMPARATOR );
4964 }
5065
5166 @ Nullable
5267 public static TextView getSubtitleTextView (@ NonNull Toolbar toolbar ) {
53- return getTextView (toolbar , toolbar .getSubtitle ());
68+ List <TextView > textViews = getTextViewsWithText (toolbar , toolbar .getSubtitle ());
69+ return textViews .isEmpty () ? null : max (textViews , VIEW_TOP_COMPARATOR );
5470 }
5571
56- @ Nullable
57- private static TextView getTextView ( @ NonNull Toolbar toolbar , CharSequence text ) {
72+ private static List < TextView > getTextViewsWithText ( @ NonNull Toolbar toolbar , CharSequence text ) {
73+ List < TextView > textViews = new ArrayList <>();
5874 for (int i = 0 ; i < toolbar .getChildCount (); i ++) {
5975 View child = toolbar .getChildAt (i );
6076 if (child instanceof TextView ) {
6177 TextView textView = (TextView ) child ;
6278 if (TextUtils .equals (textView .getText (), text )) {
63- return textView ;
79+ textViews . add ( textView ) ;
6480 }
6581 }
6682 }
67- return null ;
83+ return textViews ;
6884 }
6985
7086 @ Nullable
@@ -79,8 +95,7 @@ private static ImageView getImageView(@NonNull Toolbar toolbar, @Nullable Drawab
7995 if (child instanceof ImageView ) {
8096 ImageView imageView = (ImageView ) child ;
8197 if (content != null
82- && imageView .getDrawable ().getConstantState ().equals (content .getConstantState ())
83- ) {
98+ && imageView .getDrawable ().getConstantState ().equals (content .getConstantState ())) {
8499 return imageView ;
85100 }
86101 }
0 commit comments