Skip to content

Instantly share code, notes, and snippets.

@alorma
Created February 8, 2017 17:13
Show Gist options
  • Save alorma/a27b827661679fce47b6443275f70cde to your computer and use it in GitHub Desktop.
Save alorma/a27b827661679fce47b6443275f70cde to your computer and use it in GitHub Desktop.
VectorMenuIconHolder
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.widget.AppCompatDrawableManager;
import android.view.MenuItem;
import java.lang.ref.WeakReference;
public class VectorMenuIconHolder {
  private WeakReference<Context> context;
  @DrawableRes private int icon;
  private final int colorDefault;
  public VectorMenuIconHolder(Context context, @DrawableRes int icon, @ColorInt int colorDefault) {
    this.context = new WeakReference<>(context);
    this.icon = icon;
    this.colorDefault = colorDefault;
  }
  public void apply(MenuItem menuItem) {
    if (context != null && context.get() != null && menuItem != null) {
      Drawable drawable = AppCompatDrawableManager.get().getDrawable(context.get(), icon);
      Drawable wrap = DrawableCompat.wrap(drawable);
      DrawableCompat.setTint(wrap, colorDefault);
      menuItem.setIcon(wrap);
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment