frenziedherring
frenziedherring

Reputation: 2265

Apply Color Filter to Action Overflow Icon at Runtime

Is there any way to get the Action bar overflow icon drawable at runtime to apply a color filter? I'm looking for something similar to menu.findItem(R.id.menu_id).getIcon() except for the 3 dot overflow so that I can do a .setColorFilter.

Thanks!

Upvotes: 0

Views: 606

Answers (2)

michalbrz
michalbrz

Reputation: 3504

Yes, there is a way. You just have to find overflow icon in view hierarchy. One good way is searching in ViewGroup returned by getDecorView(). You can search for it using findViewsWithText with flag FIND_VIEWS_WITH_CONTENT_DESCRIPTION.

Sample code:

public static void setOverflowButtonColor(final Activity activity, final int visibleFontColor) {
    final String overflowDescription = activity.getString(R.string.abc_action_menu_overflow_description);
    final ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
    final ViewTreeObserver viewTreeObserver = decorView.getViewTreeObserver();
    viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            final ArrayList<View> outViews = new ArrayList<View>();
            decorView.findViewsWithText(outViews, overflowDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
            if (outViews.isEmpty()) {
                return;
            }
            TintImageView overflow = (TintImageView) outViews.get(0);
            overflow.setColorFilter(Color.CYAN);
            removeOnGlobalLayoutListener(decorView, this);
        }
    });
}

public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
        v.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
    }
    else {
        v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
    }
}

For more details see my answer in similar question: https://stackoverflow.com/a/27672844/2707179

Upvotes: 1

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

You cant get the OverflowIcon within the onCreateOptionsMenu, but you can still change the appearance of it at runtime so instead of applying a filter on it programatically you can create your own OverflowIcon image instead.

sample:

You can change the overflow icon within the style of your activity

<style name="YOUR_THEME" parent="android:style/Theme.Holo.Light">
 <item name="android:actionOverflowButtonStyle">@style/CustomOverflow</item>
</style>

<style name="CustomOverflow" parent="android:style/Widget.Holo.ActionButton.Overflow">
   <item name="android:src">@drawable/your_custom_overflow_image</item>
</style>

Upvotes: 0

Related Questions