Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// ...
public static void fixToolbarOverflowButton(final Activity activity) {
if (Build.VERSION.SDK_INT >= 21) {
// the problem occurs only on LOLLIPOP when using native Toolbar and Action Bar
try {
final int abId = activity.getResources().getIdentifier("android:id/action_bar", null, null);
final Toolbar toolbar = (Toolbar) activity.getWindow().getDecorView().findViewById(abId);
final int moreId = activity.getResources().getIdentifier("android:string/action_menu_overflow_description", "string", null);
// copy the drawable from appcompat-v7 library if you don't use it OR use the framework one if it's available
final Drawable d = getDrawableWithColorControlNormal(toolbar.getContext(), R.drawable.abc_ic_menu_moreoverflow_mtrl_alpha);
toolbar.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
final String moreString = activity.getString(moreId);
final ArrayList<View> out = new ArrayList<>();
toolbar.findViewsWithText(out, moreString, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
if (out.isEmpty()) return;
final ImageButton moreButton = (ImageButton) out.get(0);
moreButton.setImageDrawable(d);
Util.View.removeOnGlobalLayoutListener(toolbar, this);
}
});
} catch (Exception ex) {
// this is a pretty hacky solution, anything can go wrong really
ex.printStackTrace();
}
}
}
/**
* Read colorControlNormal (on API < 21) or android:colorControlNormal (on API 21) from theme and apply it to specified drawable.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static Drawable getDrawableWithColorControlNormal(Context context, @DrawableRes int drawableId) {
TypedArray ta = context.obtainStyledAttributes(new int[]{API_21 ? android.R.attr.colorControlNormal : R.attr.colorControlNormal});
int c = ta.getColor(0, Color.BLACK);
ta.recycle();
Drawable d = context.getApplicationContext().getResources().getDrawable(drawableId);
return tintDrawable(d, c);
}
/**
* Paint supplied Drawable with supplied color.
*/
public static Drawable tintDrawable(Drawable d, int c) {
PorterDuffColorFilter cf = new PorterDuffColorFilter(c, PorterDuff.Mode.SRC_IN);
d.mutate().setColorFilter(cf);
return d;
}
// ...
// ...
public void onCreate(Bundle savedInstanceState) {
// ...
if (savedInstanceState == null) {
// since the bug occurs only on first run
// let's apply a fix only in that case
// subsequent runs or screen rotations are ok
MaterialUtils.fixToolbarOverflowButton(this);
}
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.