Skip to content

Commit

Permalink
[MaterialToolbar] Fixed centering logic when title and subtitle are t…
Browse files Browse the repository at this point in the history
…he same

Resolves #2303

PiperOrigin-RevId: 435348290
  • Loading branch information
dsn5ft committed Mar 17, 2022
1 parent 8363cde commit f69e3a0
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions lib/java/com/google/android/material/internal/ToolbarUtils.java
Expand Up @@ -16,6 +16,9 @@

package com.google.android.material.internal;

import static java.util.Collections.max;
import static java.util.Collections.min;

import android.graphics.drawable.Drawable;
import androidx.appcompat.view.menu.ActionMenuItemView;
import androidx.appcompat.widget.ActionMenuView;
Expand All @@ -30,6 +33,9 @@
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.annotation.RestrictTo.Scope;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
* Utility methods for {@link Toolbar}s.
Expand All @@ -39,32 +45,42 @@
@RestrictTo(Scope.LIBRARY)
public class ToolbarUtils {

private static final Comparator<View> VIEW_TOP_COMPARATOR =
new Comparator<View>() {
@Override
public int compare(View view1, View view2) {
return view1.getTop() - view2.getTop();
}
};

private ToolbarUtils() {
// Private constructor to prevent unwanted construction.
}

@Nullable
public static TextView getTitleTextView(@NonNull Toolbar toolbar) {
return getTextView(toolbar, toolbar.getTitle());
List<TextView> textViews = getTextViewsWithText(toolbar, toolbar.getTitle());
return textViews.isEmpty() ? null : min(textViews, VIEW_TOP_COMPARATOR);
}

@Nullable
public static TextView getSubtitleTextView(@NonNull Toolbar toolbar) {
return getTextView(toolbar, toolbar.getSubtitle());
List<TextView> textViews = getTextViewsWithText(toolbar, toolbar.getSubtitle());
return textViews.isEmpty() ? null : max(textViews, VIEW_TOP_COMPARATOR);
}

@Nullable
private static TextView getTextView(@NonNull Toolbar toolbar, CharSequence text) {
private static List<TextView> getTextViewsWithText(@NonNull Toolbar toolbar, CharSequence text) {
List<TextView> textViews = new ArrayList<>();
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;
textViews.add(textView);
}
}
}
return null;
return textViews;
}

@Nullable
Expand All @@ -79,8 +95,7 @@ private static ImageView getImageView(@NonNull Toolbar toolbar, @Nullable Drawab
if (child instanceof ImageView) {
ImageView imageView = (ImageView) child;
if (content != null
&& imageView.getDrawable().getConstantState().equals(content.getConstantState())
) {
&& imageView.getDrawable().getConstantState().equals(content.getConstantState())) {
return imageView;
}
}
Expand Down

0 comments on commit f69e3a0

Please sign in to comment.