Example usage for android.graphics.drawable Drawable mutate

List of usage examples for android.graphics.drawable Drawable mutate

Introduction

In this page you can find the example usage for android.graphics.drawable Drawable mutate.

Prototype

public @NonNull Drawable mutate() 

Source Link

Document

Make this drawable mutable.

Usage

From source file:com.guerinet.formgenerator.TextViewFormItem.java

/**
 * Builds the view and adds it to the container
 *
 * @return The {@link TextViewFormItem} instance
 *///from www  . java  2s .  c  o  m
@CallSuper
public TextViewFormItem build() {
    Drawable[] drawables = new Drawable[4];
    // Get all of the icons
    drawables[0] = getDrawable(icons[0]);
    drawables[1] = getDrawable(icons[1]);
    drawables[2] = getDrawable(icons[2]);
    drawables[3] = getDrawable(icons[3]);

    // Set the compound drawable padding
    if (fg.builder.defaultDrawablePaddingSize != -1) {
        textView.setCompoundDrawablePadding(fg.builder.defaultDrawablePaddingSize);
    }

    // Set the correct tinting and alpha
    for (int i = 0; i < 4; i++) {
        Icon icon = icons[i];
        Drawable drawable = drawables[i];
        if (drawable != null) {
            // Wrap it in the design support library
            drawable = DrawableCompat.wrap(drawable.mutate());
            if (!icon.visible) {
                drawable.setAlpha(0);
            } else if (icon.color != -1) {
                DrawableCompat.setTint(drawable, icon.color);
            }
        }
    }

    // Set the drawables on the view
    textView.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], drawables[2], drawables[3]);

    // Add the view to the container
    fg.container.addView(view);
    return this;
}

From source file:xyz.berial.textinputlayout.TintManager.java

public Drawable getDrawable(int resId, boolean failIfNotKnown) {
    final Context context = mContextRef.get();
    if (context == null)
        return null;

    Drawable drawable = ContextCompat.getDrawable(context, resId);

    if (drawable != null) {
        if (Build.VERSION.SDK_INT >= 8) {
            // Mutate can cause NPEs on 2.1
            drawable = drawable.mutate();
        }/*from  w  w w  .  j a v  a2s  .  com*/

        final ColorStateList tintList = getTintList(resId);
        if (tintList != null) {
            // First wrap the Drawable and set the tint list
            drawable = DrawableCompat.wrap(drawable);
            DrawableCompat.setTintList(drawable, tintList);

            // If there is a blending mode specified for the drawable, use it
            final PorterDuff.Mode tintMode = getTintMode(resId);
            if (tintMode != null) {
                DrawableCompat.setTintMode(drawable, tintMode);
            }
        } else if (resId == R.drawable.abc_cab_background_top_material) {
            return new LayerDrawable(new Drawable[] { getDrawable(R.drawable.abc_cab_background_internal_bg),
                    getDrawable(R.drawable.abc_cab_background_top_mtrl_alpha) });
        } else {
            final boolean usedColorFilter = tintDrawableUsingColorFilter(resId, drawable);
            if (!usedColorFilter && failIfNotKnown) {
                // If we didn't tint using a ColorFilter, and we're set to fail if we don't
                // know the id, return null
                drawable = null;
            }
        }
    }
    return drawable;
}

From source file:org.ciasaboark.tacere.manager.NotificationManagerWrapper.java

/**
 * Builds and displays a notification for the given CalEvent. This method uses the new
 * Notification API to place an action button in the notification.
 *
 * @param event the CalEvent that is currently active
 *///w w  w  .  ja  va  2 s.co  m
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void displayNewEventNotification(EventInstance event) {
    // clicking the notification should take the user to the app
    Intent notificationIntent = new Intent(context, MainActivity.class);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // FLAG_CANCEL_CURRENT is required to make sure that the extras are including in
    // the new pending intent
    PendingIntent pendIntent = PendingIntent.getActivity(context, REQUEST_CODES.EVENT_OPEN_MAIN,
            notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    Notification.Builder notBuilder = new Notification.Builder(context)
            .setContentTitle(context.getString(R.string.notification_event_active_title))
            .setContentText(event.toString()).setAutoCancel(false).setOnlyAlertOnce(true).setOngoing(true)
            .setContentIntent(pendIntent);

    EventManager eventManager = new EventManager(context, event);
    switch (eventManager.getBestRinger()) {
    case SILENT:
        notBuilder.setSmallIcon(R.drawable.not_silence);
        break;
    case VIBRATE:
        notBuilder.setSmallIcon(R.drawable.not_vibrate);
        break;
    case NORMAL:
        notBuilder.setSmallIcon(R.drawable.not_normal);
        break;
    }

    // this intent will be attached to the button on the notification
    Intent skipEventIntent = new Intent(context, SkipEventService.class);
    skipEventIntent.putExtra(SkipEventService.EVENT_ID_TAG, event.getId());
    PendingIntent skipEventPendIntent = PendingIntent.getService(context, REQUEST_CODES.EVENT_IGNORE,
            skipEventIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    notBuilder.addAction(R.drawable.not_ignore, context.getString(R.string.notification_event_skip),
            skipEventPendIntent);

    //an intent to add an additional 15 minutes of silencing for an event
    Intent addSilencingIntent = new Intent(context, ExtendEventService.class);
    addSilencingIntent.putExtra(ExtendEventService.INSTANCE_ID, event.getId());
    addSilencingIntent.putExtra(ExtendEventService.NEW_EXTEND_LENGTH, event.getExtendMinutes() + 15); //TODO use minutes stored in prefs
    PendingIntent addSilenceingPendIntent = PendingIntent.getService(context, REQUEST_CODES.EVENT_ADD_TIME,
            addSilencingIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    Authenticator authenticator = new Authenticator(context);
    if (authenticator.isAuthenticated()) {
        notBuilder.addAction(R.drawable.not_clock, "+15", addSilenceingPendIntent);
    }

    // the ticker text should only be shown the first time the notification is
    // created, not on each update
    notBuilder
            .setTicker(context.getString(R.string.notification_event_active_starting) + " " + event.toString());

    if (Build.VERSION.SDK_INT >= 21) {
        notBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
        Notification.Builder publicNotification = getBaseEventNotificationBuilder();
        publicNotification.setContentTitle(context.getString(R.string.notification_event_active_title_public));
        publicNotification.setContentIntent(pendIntent);
        notBuilder.setPublicVersion(publicNotification.build());
        notBuilder.setColor(context.getResources().getColor(R.color.accent));

        Drawable d = context.getResources().getDrawable(R.drawable.shape_circle);
        int height = (int) context.getResources().getDimension(android.R.dimen.notification_large_icon_height);
        int width = (int) context.getResources().getDimension(android.R.dimen.notification_large_icon_width);
        d.setBounds(0, 0, width, height);
        d.mutate().setColorFilter(event.getDisplayColor(), PorterDuff.Mode.MULTIPLY);
        DatabaseInterface databaseInterface = DatabaseInterface.getInstance(context);
        String calendarTitle = databaseInterface.getCalendarNameForId(event.getCalendarId());
        String c = "";
        if (calendarTitle != null && calendarTitle != "") {
            c = ((Character) calendarTitle.charAt(0)).toString().toUpperCase();
        }

        Bitmap largeIcon = createMarkerIcon(d, c, width, height);
        //            Bitmap largeIcon = combineDrawablesToBitmap(d, getRingerIconForEvent(event), width, height);
        notBuilder.setLargeIcon(largeIcon);
    }

    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(NOTIFICATION_ID, notBuilder.build());
}

From source file:org.namelessrom.devicecontrol.modules.cpu.CpuSettingsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedState) {
    final Activity activity = getActivity();
    setHasOptionsMenu(true);/* www .j a  v a  2 s.co  m*/

    // inflate the parent layout
    final View view = super.onCreateView(inflater, root, savedState);
    // we know it because we return it, silence android studio
    assert view != null;

    final CardView cardView = (CardView) view.findViewById(R.id.card_core_stats_root);
    cardView.setCardBackgroundColor(AppResources.get().getCardBackgroundColor());

    mCpuInfo = (LinearLayout) view.findViewById(R.id.cpu_info);

    final DeviceConfig deviceConfig = DeviceConfig.get();
    mStatusHide = (SwitchCompat) view.findViewById(R.id.cpu_info_hide);
    mStatusHide.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(final CompoundButton button, final boolean b) {
            if (b) {
                mCpuInfo.setVisibility(View.VISIBLE);
                CpuCoreMonitor.getInstance(activity).start(CpuSettingsFragment.this, 1000);
            } else {
                CpuCoreMonitor.getInstance(activity).stop();
                mCpuInfo.setVisibility(View.GONE);
            }
            deviceConfig.perfCpuInfo = b;
            deviceConfig.save();
        }
    });
    mStatusHide.setChecked(deviceConfig.perfCpuInfo);
    if (mStatusHide.isChecked()) {
        mCpuInfo.setVisibility(View.VISIBLE);
    } else {
        mCpuInfo.setVisibility(View.GONE);
    }

    CpuCore tmpCore;
    final int mCpuNum = CpuUtils.get().getNumOfCpus();
    final String format = getString(R.string.core) + " %s:";
    for (int i = 0; i < mCpuNum; i++) {
        tmpCore = new CpuCore(String.format(format, String.valueOf(i)), "0", "0", "0");
        generateRow(i, tmpCore);
    }

    Drawable refreshDrawable = ContextCompat.getDrawable(activity, R.drawable.ic_refresh);
    refreshDrawable = DrawableHelper.applyAccentColorFilter(refreshDrawable.mutate());

    final CustomPreferenceCategoryMaterial coreLimits = (CustomPreferenceCategoryMaterial) view
            .findViewById(R.id.core_limits);

    final ImageView imageViewCpu = new ImageView(activity);
    imageViewCpu.setImageDrawable(refreshDrawable);
    imageViewCpu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // animate, just to make it look cool...
            rotateView(v);
            CpuUtils.get().getCpuFreq(CpuSettingsFragment.this);
        }
    });
    coreLimits.addToWidgetFrame(imageViewCpu);

    mMax = (MaterialListPreference) view.findViewById(R.id.cpu_pref_max);
    mMax.setSpinnerTextViewColor(AppResources.get().getAccentColor());
    mMax.setOnPreferenceChangeListener(this);

    mMin = (MaterialListPreference) view.findViewById(R.id.cpu_pref_min);
    mMin.setSpinnerTextViewColor(AppResources.get().getAccentColor());
    mMin.setOnPreferenceChangeListener(this);

    mCpuLock = (MaterialSwitchPreference) view.findViewById(R.id.cpu_pref_cpu_lock);
    mCpuLock.getSwitch().setChecked(deviceConfig.perfCpuLock);
    mCpuLock.setOnPreferenceChangeListener(this);

    final CustomPreferenceCategoryMaterial governor = (CustomPreferenceCategoryMaterial) view
            .findViewById(R.id.cpu_cat_gov);
    final ImageView imageViewGov = new ImageView(activity);
    imageViewGov.setImageDrawable(refreshDrawable);
    imageViewGov.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // animate, just to make it look cool...
            rotateView(v);
            GovernorUtils.get().getGovernor(CpuSettingsFragment.this);
        }
    });
    governor.addToWidgetFrame(imageViewGov);

    mGovernor = (MaterialListPreference) view.findViewById(R.id.cpu_pref_governor);
    mGovernor.setSpinnerTextViewColor(AppResources.get().getAccentColor());
    mGovernor.setOnPreferenceChangeListener(this);

    mGovernorTuning = (MaterialPreference) view.findViewById(R.id.cpu_pref_governor_tuning);
    mGovernorTuning.setOnPreferenceClickListener(this);

    mCpuGovLock = (MaterialSwitchPreference) view.findViewById(R.id.cpu_pref_gov_lock);
    mCpuGovLock.getSwitch().setChecked(deviceConfig.perfCpuGovLock);
    mCpuGovLock.setOnPreferenceChangeListener(this);

    if (Utils.fileExists(getResources().getStringArray(R.array.directories_intelli_plug))
            || Utils.fileExists(getString(R.string.directory_mako_hotplug))
            || Utils.fileExists(getString(R.string.file_cpu_quiet_base))
            || Utils.fileExists(MpDecisionAction.MPDECISION_PATH)) {
        setupHotpluggingPreferences();
    }

    // compensate mpdecision's madness
    mMax.postDelayed(new Runnable() {
        @Override
        public void run() {
            rotateView(imageViewCpu);
            CpuUtils.get().getCpuFreq(CpuSettingsFragment.this);
            mMin.postDelayed(new Runnable() {
                @Override
                public void run() {
                    rotateView(imageViewCpu);
                    CpuUtils.get().getCpuFreq(CpuSettingsFragment.this);
                }
            }, 300);
        }
    }, 300);
    mGovernor.postDelayed(new Runnable() {
        @Override
        public void run() {
            rotateView(imageViewGov);
            GovernorUtils.get().getGovernor(CpuSettingsFragment.this);
        }
    }, 300);

    return view;
}

From source file:org.ciasaboark.tacere.view.EventListItem.java

private void drawSidebar() {
    Drawable sidebarDrawable = sidebarImageView.getDrawable();
    int displayColor = event.getDisplayColor();
    if (isFutureEvent()) {
        displayColor = desaturateColor(displayColor, DESATURATE_RATIO);
    }/*  w  w w .  j a va  2  s . c  om*/
    sidebarDrawable.mutate().setColorFilter(displayColor, PorterDuff.Mode.MULTIPLY);
    sidebarImageView.setImageDrawable(sidebarDrawable);
}

From source file:com.android.leanlauncher.WidgetPreviewLoader.java

private Drawable mutateOnMainThread(final Drawable drawable) {
    try {//from  w w w .j  a v  a2s. c o  m
        return mMainThreadExecutor.submit(new Callable<Drawable>() {
            @Override
            public Drawable call() throws Exception {
                return drawable.mutate();
            }
        }).get();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.ciasaboark.tacere.view.EventListItem.java

private void drawRepeatingIcon() {
    if (clockIcon != null) {
        boolean eventRepeats = databaseInterface.doesEventRepeat(event.getEventId());
        Drawable icon;
        if (eventRepeats) {
            icon = context.getResources().getDrawable(R.drawable.history);
        } else {/* ww w  .ja v a2s. c  o m*/
            icon = context.getResources().getDrawable(R.drawable.clock);
        }

        icon.mutate().setColorFilter(iconTintColor, PorterDuff.Mode.MULTIPLY);
        clockIcon.setImageDrawable(icon);
    }
}

From source file:com.teitsmch.hearthmaker.MainActivity.java

@Override
public void onDialogComplete(int type, int deckId, String deckName) {
    String className = dialogClasses[type];
    if (deckName.trim().isEmpty()) {
        SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        deckName = "";
        int count = preferences.getInt(className, 0);
        count++;//from www .java 2 s. co m
        deckName = String.format("%s %d", className, count);
        editor.putInt(className, count);
        editor.apply();
    }
    currentDeckClass = className;

    setNavigationMenuItem(deckId, deckName);

    onNavigationItemSelected(mDrawerList.getMenu().findItem(deckId));

    //set class icon

    switch (className) {
    case "Warrior":
        getNavigationView().getMenu().findItem(deckId).setIcon(R.drawable.warrior_icon);
        break;
    case "Druid":
        getNavigationView().getMenu().findItem(deckId).setIcon(R.drawable.druid_icon);
        break;
    case "Hunter":
        getNavigationView().getMenu().findItem(deckId).setIcon(R.drawable.hunter_icon);
        break;
    case "Mage":
        getNavigationView().getMenu().findItem(deckId).setIcon(R.drawable.mage_icon);
        break;
    case "Paladin":
        getNavigationView().getMenu().findItem(deckId).setIcon(R.drawable.paladin_icon);
        break;
    case "Priest":
        getNavigationView().getMenu().findItem(deckId).setIcon(R.drawable.priest_icon);
        break;
    case "Rogue":
        getNavigationView().getMenu().findItem(deckId).setIcon(R.drawable.rogue_icon);
        break;
    case "Shaman":
        getNavigationView().getMenu().findItem(deckId).setIcon(R.drawable.shaman_icon);
        break;
    case "Warlock":
        getNavigationView().getMenu().findItem(deckId).setIcon(R.drawable.warlock_icon);
        break;
    default:
        break;
    }

    Drawable drawable = getNavigationView().getMenu().findItem(deckId).getIcon();
    drawable.mutate();
    drawable.setColorFilter(0, PorterDuff.Mode.SRC_ATOP);

}

From source file:android.support.v7ox.widget.AppCompatDrawableManager.java

private static boolean tintDrawableUsingColorFilter(@NonNull Context context, @DrawableRes final int resId,
        @NonNull Drawable drawable) {
    PorterDuff.Mode tintMode = DEFAULT_MODE;
    boolean colorAttrSet = false;
    int colorAttr = 0;
    int alpha = -1;

    if (arrayContains(COLORFILTER_TINT_COLOR_CONTROL_NORMAL, resId)) {
        colorAttr = R.attr.colorControlNormal_ox;
        colorAttrSet = true;/*  www. j  a va 2s. c o  m*/
    } else if (arrayContains(COLORFILTER_COLOR_CONTROL_ACTIVATED, resId)) {
        colorAttr = R.attr.colorControlActivated_ox;
        colorAttrSet = true;
    } else if (arrayContains(COLORFILTER_COLOR_BACKGROUND_MULTIPLY, resId)) {
        colorAttr = android.R.attr.colorBackground;
        colorAttrSet = true;
        tintMode = PorterDuff.Mode.MULTIPLY;
    } else {
        colorAttr = android.R.attr.colorForeground;
        colorAttrSet = true;
        alpha = Math.round(0.16f * 255);
    }

    if (colorAttrSet) {
        if (DrawableUtils.canSafelyMutateDrawable(drawable)) {
            drawable = drawable.mutate();
        }

        final int color = ThemeUtils.getThemeAttrColor(context, colorAttr);
        drawable.setColorFilter(getPorterDuffColorFilter(color, tintMode));

        if (alpha != -1) {
            drawable.setAlpha(alpha);
        }

        if (DEBUG) {
            Log.d(TAG, "[tintDrawableUsingColorFilter] Tinted " + context.getResources().getResourceName(resId)
                    + " with color: #" + Integer.toHexString(color));
        }
        return true;
    }
    return false;
}

From source file:com.facebook.react.views.textinput.ReactTextInputManager.java

@ReactProp(name = "underlineColorAndroid", customType = "Color")
public void setUnderlineColor(ReactEditText view, @Nullable Integer underlineColor) {
    // Drawable.mutate() can sometimes crash due to an AOSP bug:
    // See https://code.google.com/p/android/issues/detail?id=191754 for more info
    Drawable background = view.getBackground();
    Drawable drawableToMutate = background.getConstantState() != null ? background.mutate() : background;

    if (underlineColor == null) {
        drawableToMutate.clearColorFilter();
    } else {/*from  w w  w  . j  a  v a2  s.c om*/
        drawableToMutate.setColorFilter(underlineColor, PorterDuff.Mode.SRC_IN);
    }
}