Drawable.java revision 3da32b768899e7dabe3a16333edf5eca2b9ebe93
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.graphics.drawable;
18
19import android.annotation.ColorInt;
20import android.annotation.NonNull;
21import android.annotation.Nullable;
22import android.content.res.ColorStateList;
23import android.content.res.Resources;
24import android.content.res.Resources.Theme;
25import android.content.res.TypedArray;
26import android.graphics.Bitmap;
27import android.graphics.BitmapFactory;
28import android.graphics.Canvas;
29import android.graphics.Color;
30import android.graphics.ColorFilter;
31import android.graphics.Insets;
32import android.graphics.NinePatch;
33import android.graphics.Outline;
34import android.graphics.PixelFormat;
35import android.graphics.PorterDuff;
36import android.graphics.PorterDuff.Mode;
37import android.graphics.PorterDuffColorFilter;
38import android.graphics.Rect;
39import android.graphics.Region;
40import android.graphics.Xfermode;
41import android.os.Trace;
42import android.util.AttributeSet;
43import android.util.DisplayMetrics;
44import android.util.FloatProperty;
45import android.util.StateSet;
46import android.util.TypedValue;
47import android.util.Xml;
48import android.view.View;
49
50import org.xmlpull.v1.XmlPullParser;
51import org.xmlpull.v1.XmlPullParserException;
52
53import java.io.IOException;
54import java.io.InputStream;
55import java.lang.ref.WeakReference;
56import java.util.Arrays;
57import java.util.Collection;
58
59/**
60 * A Drawable is a general abstraction for "something that can be drawn."  Most
61 * often you will deal with Drawable as the type of resource retrieved for
62 * drawing things to the screen; the Drawable class provides a generic API for
63 * dealing with an underlying visual resource that may take a variety of forms.
64 * Unlike a {@link android.view.View}, a Drawable does not have any facility to
65 * receive events or otherwise interact with the user.
66 *
67 * <p>In addition to simple drawing, Drawable provides a number of generic
68 * mechanisms for its client to interact with what is being drawn:
69 *
70 * <ul>
71 *     <li> The {@link #setBounds} method <var>must</var> be called to tell the
72 *     Drawable where it is drawn and how large it should be.  All Drawables
73 *     should respect the requested size, often simply by scaling their
74 *     imagery.  A client can find the preferred size for some Drawables with
75 *     the {@link #getIntrinsicHeight} and {@link #getIntrinsicWidth} methods.
76 *
77 *     <li> The {@link #getPadding} method can return from some Drawables
78 *     information about how to frame content that is placed inside of them.
79 *     For example, a Drawable that is intended to be the frame for a button
80 *     widget would need to return padding that correctly places the label
81 *     inside of itself.
82 *
83 *     <li> The {@link #setState} method allows the client to tell the Drawable
84 *     in which state it is to be drawn, such as "focused", "selected", etc.
85 *     Some drawables may modify their imagery based on the selected state.
86 *
87 *     <li> The {@link #setLevel} method allows the client to supply a single
88 *     continuous controller that can modify the Drawable is displayed, such as
89 *     a battery level or progress level.  Some drawables may modify their
90 *     imagery based on the current level.
91 *
92 *     <li> A Drawable can perform animations by calling back to its client
93 *     through the {@link Callback} interface.  All clients should support this
94 *     interface (via {@link #setCallback}) so that animations will work.  A
95 *     simple way to do this is through the system facilities such as
96 *     {@link android.view.View#setBackground(Drawable)} and
97 *     {@link android.widget.ImageView}.
98 * </ul>
99 *
100 * Though usually not visible to the application, Drawables may take a variety
101 * of forms:
102 *
103 * <ul>
104 *     <li> <b>Bitmap</b>: the simplest Drawable, a PNG or JPEG image.
105 *     <li> <b>Nine Patch</b>: an extension to the PNG format allows it to
106 *     specify information about how to stretch it and place things inside of
107 *     it.
108 *     <li> <b>Shape</b>: contains simple drawing commands instead of a raw
109 *     bitmap, allowing it to resize better in some cases.
110 *     <li> <b>Layers</b>: a compound drawable, which draws multiple underlying
111 *     drawables on top of each other.
112 *     <li> <b>States</b>: a compound drawable that selects one of a set of
113 *     drawables based on its state.
114 *     <li> <b>Levels</b>: a compound drawable that selects one of a set of
115 *     drawables based on its level.
116 *     <li> <b>Scale</b>: a compound drawable with a single child drawable,
117 *     whose overall size is modified based on the current level.
118 * </ul>
119 *
120 * <div class="special reference">
121 * <h3>Developer Guides</h3>
122 * <p>For more information about how to use drawables, read the
123 * <a href="{@docRoot}guide/topics/graphics/2d-graphics.html">Canvas and Drawables</a> developer
124 * guide. For information and examples of creating drawable resources (XML or bitmap files that
125 * can be loaded in code), read the
126 * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>
127 * document.</p></div>
128 */
129public abstract class Drawable {
130
131    private static final Rect ZERO_BOUNDS_RECT = new Rect();
132
133    static final PorterDuff.Mode DEFAULT_TINT_MODE = PorterDuff.Mode.SRC_IN;
134
135    /** The standard maximum value for calls to {@link #setLevel(int)}. */
136    public static final int MAX_LEVEL = 10000;
137
138    /** The standard maximum value for calls to {@link #setLevel(float)}. */
139    public static final float MAX_LEVEL_FLOAT = 10000.0f;
140
141    private int[] mStateSet = StateSet.WILD_CARD;
142    private float mLevel = 0.0f;
143    private int mChangingConfigurations = 0;
144    private Rect mBounds = ZERO_BOUNDS_RECT;  // lazily becomes a new Rect()
145    private WeakReference<Callback> mCallback = null;
146    private boolean mVisible = true;
147
148    private int mLayoutDirection;
149
150    /**
151     * Draw in its bounds (set via setBounds) respecting optional effects such
152     * as alpha (set via setAlpha) and color filter (set via setColorFilter).
153     *
154     * @param canvas The canvas to draw into
155     */
156    public abstract void draw(Canvas canvas);
157
158    /**
159     * Specify a bounding rectangle for the Drawable. This is where the drawable
160     * will draw when its draw() method is called.
161     */
162    public void setBounds(int left, int top, int right, int bottom) {
163        Rect oldBounds = mBounds;
164
165        if (oldBounds == ZERO_BOUNDS_RECT) {
166            oldBounds = mBounds = new Rect();
167        }
168
169        if (oldBounds.left != left || oldBounds.top != top ||
170                oldBounds.right != right || oldBounds.bottom != bottom) {
171            if (!oldBounds.isEmpty()) {
172                // first invalidate the previous bounds
173                invalidateSelf();
174            }
175            mBounds.set(left, top, right, bottom);
176            onBoundsChange(mBounds);
177        }
178    }
179
180    /**
181     * Specify a bounding rectangle for the Drawable. This is where the drawable
182     * will draw when its draw() method is called.
183     */
184    public void setBounds(Rect bounds) {
185        setBounds(bounds.left, bounds.top, bounds.right, bounds.bottom);
186    }
187
188    /**
189     * Return a copy of the drawable's bounds in the specified Rect (allocated
190     * by the caller). The bounds specify where this will draw when its draw()
191     * method is called.
192     *
193     * @param bounds Rect to receive the drawable's bounds (allocated by the
194     *               caller).
195     */
196    public final void copyBounds(Rect bounds) {
197        bounds.set(mBounds);
198    }
199
200    /**
201     * Return a copy of the drawable's bounds in a new Rect. This returns the
202     * same values as getBounds(), but the returned object is guaranteed to not
203     * be changed later by the drawable (i.e. it retains no reference to this
204     * rect). If the caller already has a Rect allocated, call copyBounds(rect).
205     *
206     * @return A copy of the drawable's bounds
207     */
208    public final Rect copyBounds() {
209        return new Rect(mBounds);
210    }
211
212    /**
213     * Return the drawable's bounds Rect. Note: for efficiency, the returned
214     * object may be the same object stored in the drawable (though this is not
215     * guaranteed), so if a persistent copy of the bounds is needed, call
216     * copyBounds(rect) instead.
217     * You should also not change the object returned by this method as it may
218     * be the same object stored in the drawable.
219     *
220     * @return The bounds of the drawable (which may change later, so caller
221     *         beware). DO NOT ALTER the returned object as it may change the
222     *         stored bounds of this drawable.
223     *
224     * @see #copyBounds()
225     * @see #copyBounds(android.graphics.Rect)
226     */
227    public final Rect getBounds() {
228        if (mBounds == ZERO_BOUNDS_RECT) {
229            mBounds = new Rect();
230        }
231
232        return mBounds;
233    }
234
235    /**
236     * Return the drawable's dirty bounds Rect. Note: for efficiency, the
237     * returned object may be the same object stored in the drawable (though
238     * this is not guaranteed).
239     * <p>
240     * By default, this returns the full drawable bounds. Custom drawables may
241     * override this method to perform more precise invalidation.
242     *
243     * @return The dirty bounds of this drawable
244     */
245    public Rect getDirtyBounds() {
246        return getBounds();
247    }
248
249    /**
250     * Set a mask of the configuration parameters for which this drawable
251     * may change, requiring that it be re-created.
252     *
253     * @param configs A mask of the changing configuration parameters, as
254     * defined by {@link android.content.pm.ActivityInfo}.
255     *
256     * @see android.content.pm.ActivityInfo
257     */
258    public void setChangingConfigurations(int configs) {
259        mChangingConfigurations = configs;
260    }
261
262    /**
263     * Return a mask of the configuration parameters for which this drawable
264     * may change, requiring that it be re-created.  The default implementation
265     * returns whatever was provided through
266     * {@link #setChangingConfigurations(int)} or 0 by default.  Subclasses
267     * may extend this to or in the changing configurations of any other
268     * drawables they hold.
269     *
270     * @return Returns a mask of the changing configuration parameters, as
271     * defined by {@link android.content.pm.ActivityInfo}.
272     *
273     * @see android.content.pm.ActivityInfo
274     */
275    public int getChangingConfigurations() {
276        return mChangingConfigurations;
277    }
278
279    /**
280     * Set to true to have the drawable dither its colors when drawn to a
281     * device with fewer than 8-bits per color component.
282     *
283     * @see android.graphics.Paint#setDither(boolean);
284     * @deprecated This property is ignored.
285     */
286    @Deprecated
287    public void setDither(boolean dither) {}
288
289    /**
290     * Set to true to have the drawable filter its bitmaps with bilinear
291     * sampling when they are scaled or rotated.
292     *
293     * <p>This can improve appearance when bitmaps are rotated. If the drawable
294     * does not use bitmaps, this call is ignored.</p>
295     *
296     * @see #isFilterBitmap()
297     * @see android.graphics.Paint#setFilterBitmap(boolean);
298     */
299    public void setFilterBitmap(boolean filter) {}
300
301    /**
302     * @return whether this drawable filters its bitmaps
303     * @see #setFilterBitmap(boolean)
304     */
305    public boolean isFilterBitmap() {
306        return false;
307    }
308
309    /**
310     * Implement this interface if you want to create an animated drawable that
311     * extends {@link android.graphics.drawable.Drawable Drawable}.
312     * Upon retrieving a drawable, use
313     * {@link Drawable#setCallback(android.graphics.drawable.Drawable.Callback)}
314     * to supply your implementation of the interface to the drawable; it uses
315     * this interface to schedule and execute animation changes.
316     */
317    public static interface Callback {
318        /**
319         * Called when the drawable needs to be redrawn.  A view at this point
320         * should invalidate itself (or at least the part of itself where the
321         * drawable appears).
322         *
323         * @param who The drawable that is requesting the update.
324         */
325        public void invalidateDrawable(Drawable who);
326
327        /**
328         * A Drawable can call this to schedule the next frame of its
329         * animation.  An implementation can generally simply call
330         * {@link android.os.Handler#postAtTime(Runnable, Object, long)} with
331         * the parameters <var>(what, who, when)</var> to perform the
332         * scheduling.
333         *
334         * @param who The drawable being scheduled.
335         * @param what The action to execute.
336         * @param when The time (in milliseconds) to run.  The timebase is
337         *             {@link android.os.SystemClock#uptimeMillis}
338         */
339        public void scheduleDrawable(Drawable who, Runnable what, long when);
340
341        /**
342         * A Drawable can call this to unschedule an action previously
343         * scheduled with {@link #scheduleDrawable}.  An implementation can
344         * generally simply call
345         * {@link android.os.Handler#removeCallbacks(Runnable, Object)} with
346         * the parameters <var>(what, who)</var> to unschedule the drawable.
347         *
348         * @param who The drawable being unscheduled.
349         * @param what The action being unscheduled.
350         */
351        public void unscheduleDrawable(Drawable who, Runnable what);
352    }
353
354    /**
355     * Bind a {@link Callback} object to this Drawable.  Required for clients
356     * that want to support animated drawables.
357     *
358     * @param cb The client's Callback implementation.
359     *
360     * @see #getCallback()
361     */
362    public final void setCallback(Callback cb) {
363        mCallback = new WeakReference<Callback>(cb);
364    }
365
366    /**
367     * Return the current {@link Callback} implementation attached to this
368     * Drawable.
369     *
370     * @return A {@link Callback} instance or null if no callback was set.
371     *
372     * @see #setCallback(android.graphics.drawable.Drawable.Callback)
373     */
374    public Callback getCallback() {
375        if (mCallback != null) {
376            return mCallback.get();
377        }
378        return null;
379    }
380
381    /**
382     * Use the current {@link Callback} implementation to have this Drawable
383     * redrawn.  Does nothing if there is no Callback attached to the
384     * Drawable.
385     *
386     * @see Callback#invalidateDrawable
387     * @see #getCallback()
388     * @see #setCallback(android.graphics.drawable.Drawable.Callback)
389     */
390    public void invalidateSelf() {
391        final Callback callback = getCallback();
392        if (callback != null) {
393            callback.invalidateDrawable(this);
394        }
395    }
396
397    /**
398     * Use the current {@link Callback} implementation to have this Drawable
399     * scheduled.  Does nothing if there is no Callback attached to the
400     * Drawable.
401     *
402     * @param what The action being scheduled.
403     * @param when The time (in milliseconds) to run.
404     *
405     * @see Callback#scheduleDrawable
406     */
407    public void scheduleSelf(Runnable what, long when) {
408        final Callback callback = getCallback();
409        if (callback != null) {
410            callback.scheduleDrawable(this, what, when);
411        }
412    }
413
414    /**
415     * Use the current {@link Callback} implementation to have this Drawable
416     * unscheduled.  Does nothing if there is no Callback attached to the
417     * Drawable.
418     *
419     * @param what The runnable that you no longer want called.
420     *
421     * @see Callback#unscheduleDrawable
422     */
423    public void unscheduleSelf(Runnable what) {
424        final Callback callback = getCallback();
425        if (callback != null) {
426            callback.unscheduleDrawable(this, what);
427        }
428    }
429
430    /**
431     * Returns the resolved layout direction for this Drawable.
432     *
433     * @return One of {@link android.view.View#LAYOUT_DIRECTION_LTR},
434     *         {@link android.view.View#LAYOUT_DIRECTION_RTL}
435     * @see #setLayoutDirection(int)
436     */
437    public int getLayoutDirection() {
438        return mLayoutDirection;
439    }
440
441    /**
442     * Set the layout direction for this drawable. Should be a resolved
443     * layout direction, as the Drawable has no capacity to do the resolution on
444     * its own.
445     *
446     * @param layoutDirection the resolved layout direction for the drawable,
447     *                        either {@link android.view.View#LAYOUT_DIRECTION_LTR}
448     *                        or {@link android.view.View#LAYOUT_DIRECTION_RTL}
449     * @see #getLayoutDirection()
450     */
451    public final boolean setLayoutDirection(@View.ResolvedLayoutDir int layoutDirection) {
452        if (mLayoutDirection != layoutDirection) {
453            mLayoutDirection = layoutDirection;
454            return onLayoutDirectionChanged(layoutDirection);
455        }
456        return false;
457    }
458
459    /**
460     * Called when the drawable's resolved layout direction changes.
461     *
462     * @param layoutDirection the new resolved layout direction
463     * @return true if the layout direction change has caused the appearance of
464     *         the drawable to change and it needs to be re-drawn
465     * @see #setLayoutDirection(int)
466     */
467    public boolean onLayoutDirectionChanged(@View.ResolvedLayoutDir int layoutDirection) {
468        return false;
469    }
470
471    /**
472     * Specify an alpha value for the drawable. 0 means fully transparent, and
473     * 255 means fully opaque.
474     */
475    public abstract void setAlpha(int alpha);
476
477    /**
478     * Gets the current alpha value for the drawable. 0 means fully transparent,
479     * 255 means fully opaque. This method is implemented by
480     * Drawable subclasses and the value returned is specific to how that class treats alpha.
481     * The default return value is 255 if the class does not override this method to return a value
482     * specific to its use of alpha.
483     */
484    public int getAlpha() {
485        return 0xFF;
486    }
487
488    /**
489     * @hide
490     *
491     * Internal-only method for setting xfermode on certain supported drawables.
492     *
493     * Should not be made public since the layers and drawing area with which
494     * Drawables draw is private implementation detail, and not something apps
495     * should rely upon.
496     */
497    public void setXfermode(Xfermode mode) {
498        // Base implementation drops it on the floor for compatibility. Whee!
499    }
500
501    /**
502     * Specify an optional color filter for the drawable.
503     * <p>
504     * If a Drawable has a ColorFilter, each output pixel of the Drawable's
505     * drawing contents will be modified by the color filter before it is
506     * blended onto the render target of a Canvas.
507     * </p>
508     * <p>
509     * Pass {@code null} to remove any existing color filter.
510     * </p>
511     * <p class="note"><strong>Note:</strong> Setting a non-{@code null} color
512     * filter disables {@link #setTintList(ColorStateList) tint}.
513     * </p>
514     *
515     * @param colorFilter The color filter to apply, or {@code null} to remove the
516     *            existing color filter
517     */
518    public abstract void setColorFilter(@Nullable ColorFilter colorFilter);
519
520    /**
521     * Specify a color and Porter-Duff mode to be the color filter for this
522     * drawable.
523     * <p>
524     * Convenience for {@link #setColorFilter(ColorFilter)} which constructs a
525     * {@link PorterDuffColorFilter}.
526     * </p>
527     * <p class="note"><strong>Note:</strong> Setting a color filter disables
528     * {@link #setTintList(ColorStateList) tint}.
529     * </p>
530     */
531    public void setColorFilter(@ColorInt int color, @NonNull PorterDuff.Mode mode) {
532        setColorFilter(new PorterDuffColorFilter(color, mode));
533    }
534
535    /**
536     * Specifies tint color for this drawable.
537     * <p>
538     * A Drawable's drawing content will be blended together with its tint
539     * before it is drawn to the screen. This functions similarly to
540     * {@link #setColorFilter(int, PorterDuff.Mode)}.
541     * </p>
542     * <p>
543     * To clear the tint, pass {@code null} to
544     * {@link #setTintList(ColorStateList)}.
545     * </p>
546     * <p class="note"><strong>Note:</strong> Setting a color filter via
547     * {@link #setColorFilter(ColorFilter)} or
548     * {@link #setColorFilter(int, PorterDuff.Mode)} overrides tint.
549     * </p>
550     *
551     * @param tintColor Color to use for tinting this drawable
552     * @see #setTintList(ColorStateList)
553     * @see #setTintMode(PorterDuff.Mode)
554     */
555    public void setTint(@ColorInt int tintColor) {
556        setTintList(ColorStateList.valueOf(tintColor));
557    }
558
559    /**
560     * Specifies tint color for this drawable as a color state list.
561     * <p>
562     * A Drawable's drawing content will be blended together with its tint
563     * before it is drawn to the screen. This functions similarly to
564     * {@link #setColorFilter(int, PorterDuff.Mode)}.
565     * </p>
566     * <p class="note"><strong>Note:</strong> Setting a color filter via
567     * {@link #setColorFilter(ColorFilter)} or
568     * {@link #setColorFilter(int, PorterDuff.Mode)} overrides tint.
569     * </p>
570     *
571     * @param tint Color state list to use for tinting this drawable, or
572     *            {@code null} to clear the tint
573     * @see #setTint(int)
574     * @see #setTintMode(PorterDuff.Mode)
575     */
576    public void setTintList(@Nullable ColorStateList tint) {}
577
578    /**
579     * Specifies a tint blending mode for this drawable.
580     * <p>
581     * Defines how this drawable's tint color should be blended into the drawable
582     * before it is drawn to screen. Default tint mode is {@link PorterDuff.Mode#SRC_IN}.
583     * </p>
584     * <p class="note"><strong>Note:</strong> Setting a color filter via
585     * {@link #setColorFilter(ColorFilter)} or
586     * {@link #setColorFilter(int, PorterDuff.Mode)} overrides tint.
587     * </p>
588     *
589     * @param tintMode A Porter-Duff blending mode
590     * @see #setTint(int)
591     * @see #setTintList(ColorStateList)
592     */
593    public void setTintMode(@NonNull PorterDuff.Mode tintMode) {}
594
595    /**
596     * Returns the current color filter, or {@code null} if none set.
597     *
598     * @return the current color filter, or {@code null} if none set
599     */
600    public ColorFilter getColorFilter() {
601        return null;
602    }
603
604    /**
605     * Removes the color filter for this drawable.
606     */
607    public void clearColorFilter() {
608        setColorFilter(null);
609    }
610
611    /**
612     * Specifies the hotspot's location within the drawable.
613     *
614     * @param x The X coordinate of the center of the hotspot
615     * @param y The Y coordinate of the center of the hotspot
616     */
617    public void setHotspot(float x, float y) {}
618
619    /**
620     * Sets the bounds to which the hotspot is constrained, if they should be
621     * different from the drawable bounds.
622     *
623     * @param left position in pixels of the left bound
624     * @param top position in pixels of the top bound
625     * @param right position in pixels of the right bound
626     * @param bottom position in pixels of the bottom bound
627     * @see #getHotspotBounds(android.graphics.Rect)
628     */
629    public void setHotspotBounds(int left, int top, int right, int bottom) {}
630
631    /**
632     * Populates {@code outRect} with the hotspot bounds.
633     *
634     * @param outRect the rect to populate with the hotspot bounds
635     * @see #setHotspotBounds(int, int, int, int)
636     */
637    public void getHotspotBounds(Rect outRect) {
638        outRect.set(getBounds());
639    }
640
641    /**
642     * Whether this drawable requests projection.
643     *
644     * @hide magic!
645     */
646    public boolean isProjected() {
647        return false;
648    }
649
650    /**
651     * Indicates whether this drawable will change its appearance based on
652     * state. Clients can use this to determine whether it is necessary to
653     * calculate their state and call setState.
654     *
655     * @return True if this drawable changes its appearance based on state,
656     *         false otherwise.
657     * @see #setState(int[])
658     */
659    public boolean isStateful() {
660        return false;
661    }
662
663    /**
664     * Specify a set of states for the drawable. These are use-case specific,
665     * so see the relevant documentation. As an example, the background for
666     * widgets like Button understand the following states:
667     * [{@link android.R.attr#state_focused},
668     *  {@link android.R.attr#state_pressed}].
669     *
670     * <p>If the new state you are supplying causes the appearance of the
671     * Drawable to change, then it is responsible for calling
672     * {@link #invalidateSelf} in order to have itself redrawn, <em>and</em>
673     * true will be returned from this function.
674     *
675     * <p>Note: The Drawable holds a reference on to <var>stateSet</var>
676     * until a new state array is given to it, so you must not modify this
677     * array during that time.</p>
678     *
679     * @param stateSet The new set of states to be displayed.
680     *
681     * @return Returns true if this change in state has caused the appearance
682     * of the Drawable to change (hence requiring an invalidate), otherwise
683     * returns false.
684     */
685    public boolean setState(final int[] stateSet) {
686        if (!Arrays.equals(mStateSet, stateSet)) {
687            mStateSet = stateSet;
688            return onStateChange(stateSet);
689        }
690        return false;
691    }
692
693    /**
694     * Describes the current state, as a union of primitve states, such as
695     * {@link android.R.attr#state_focused},
696     * {@link android.R.attr#state_selected}, etc.
697     * Some drawables may modify their imagery based on the selected state.
698     * @return An array of resource Ids describing the current state.
699     */
700    public int[] getState() {
701        return mStateSet;
702    }
703
704    /**
705     * If this Drawable does transition animations between states, ask that
706     * it immediately jump to the current state and skip any active animations.
707     */
708    public void jumpToCurrentState() {
709    }
710
711    /**
712     * @return The current drawable that will be used by this drawable. For simple drawables, this
713     *         is just the drawable itself. For drawables that change state like
714     *         {@link StateListDrawable} and {@link LevelListDrawable} this will be the child drawable
715     *         currently in use.
716     */
717    public Drawable getCurrent() {
718        return this;
719    }
720
721    /**
722     * Sets the level for the drawable as an integer value where typically the
723     * minimum level is 0 and the maximum is 10000 {@link #MAX_LEVEL}; however,
724     * the range may vary based on the Drawable implementation and is not
725     * clamped.
726     * <p>
727     * This allows a drawable to vary its imagery based on a continuous
728     * controller. For example, it may be used to show progress or volume
729     * level.
730     * <p>
731     * Use #setLevelFloat(float) to set the level as a high-precision
732     * floating-point value.
733     *
734     * @param level the new level, typically between 0 and 10000
735     * @return {@code true} if this change in level has caused the appearance
736     *         of the drawable to change and will require a subsequent call to
737     *         invalidate, {@code false} otherwise
738     * @see #getLevel()
739     * @see #setLevel(float)
740     * @see #onLevelChange(int)
741     */
742    public final boolean setLevel(int level) {
743        return setLevel((float) level);
744    }
745
746    /**
747     * Returns the current level as a rounded integer value.
748     * <p>
749     * Use #getLevelFloat() to return the level as a high-precision
750     * floating-point value.
751     *
752     * @return the current level, typically between 0 and 10000
753     * @see #setLevel(int)
754     * @see #getLevelFloat()
755     */
756    public final int getLevel() {
757        return Math.round(mLevel);
758    }
759
760    /**
761     * Sets the level for the drawable as a floating-point value where
762     * typically the minimum level is 0.0 and the maximum is 10000.0
763     * {@link #MAX_LEVEL_FLOAT}; however, the range may vary based on the
764     * Drawable implementation and is not clamped.
765     * <p>
766     * This allows a drawable to vary its imagery based on a continuous
767     * controller. For example, it may be used to show progress or volume
768     * level.
769     *
770     * @param level the new level, typically between 0.0 and 10000.0
771     *              ({@link #MAX_LEVEL_FLOAT})
772     * @return {@code true} if this change in level has caused the appearance
773     *         of the drawable to change and will require a subsequent call to
774     *         invalidate, {@code false} otherwise
775     * @see #getLevelFloat()
776     * @see #onLevelChange(float)
777     */
778    public final boolean setLevel(float level) {
779        if (mLevel != level) {
780            mLevel = level;
781            return onLevelChange(level);
782        }
783        return false;
784    }
785
786    /**
787     * Returns the current level as a floating-point value.
788     *
789     * @return the current level, typically between 0.0 and 10000.0
790     *         ({@link #MAX_LEVEL_FLOAT})
791     * @see #setLevel(float)
792     */
793    public final float getLevelFloat() {
794        return mLevel;
795    }
796
797    /**
798     * Set whether this Drawable is visible.  This generally does not impact
799     * the Drawable's behavior, but is a hint that can be used by some
800     * Drawables, for example, to decide whether run animations.
801     *
802     * @param visible Set to true if visible, false if not.
803     * @param restart You can supply true here to force the drawable to behave
804     *                as if it has just become visible, even if it had last
805     *                been set visible.  Used for example to force animations
806     *                to restart.
807     *
808     * @return boolean Returns true if the new visibility is different than
809     *         its previous state.
810     */
811    public boolean setVisible(boolean visible, boolean restart) {
812        boolean changed = mVisible != visible;
813        if (changed) {
814            mVisible = visible;
815            invalidateSelf();
816        }
817        return changed;
818    }
819
820    public final boolean isVisible() {
821        return mVisible;
822    }
823
824    /**
825     * Set whether this Drawable is automatically mirrored when its layout direction is RTL
826     * (right-to left). See {@link android.util.LayoutDirection}.
827     *
828     * @param mirrored Set to true if the Drawable should be mirrored, false if not.
829     */
830    public void setAutoMirrored(boolean mirrored) {
831    }
832
833    /**
834     * Tells if this Drawable will be automatically mirrored  when its layout direction is RTL
835     * right-to-left. See {@link android.util.LayoutDirection}.
836     *
837     * @return boolean Returns true if this Drawable will be automatically mirrored.
838     */
839    public boolean isAutoMirrored() {
840        return false;
841    }
842
843    /**
844     * Applies the specified theme to this Drawable and its children.
845     */
846    public void applyTheme(@SuppressWarnings("unused") Theme t) {
847    }
848
849    public boolean canApplyTheme() {
850        return false;
851    }
852
853    /**
854     * Return the opacity/transparency of this Drawable.  The returned value is
855     * one of the abstract format constants in
856     * {@link android.graphics.PixelFormat}:
857     * {@link android.graphics.PixelFormat#UNKNOWN},
858     * {@link android.graphics.PixelFormat#TRANSLUCENT},
859     * {@link android.graphics.PixelFormat#TRANSPARENT}, or
860     * {@link android.graphics.PixelFormat#OPAQUE}.
861     *
862     * <p>An OPAQUE drawable is one that draws all all content within its bounds, completely
863     * covering anything behind the drawable. A TRANSPARENT drawable is one that draws nothing
864     * within its bounds, allowing everything behind it to show through. A TRANSLUCENT drawable
865     * is a drawable in any other state, where the drawable will draw some, but not all,
866     * of the content within its bounds and at least some content behind the drawable will
867     * be visible. If the visibility of the drawable's contents cannot be determined, the
868     * safest/best return value is TRANSLUCENT.
869     *
870     * <p>Generally a Drawable should be as conservative as possible with the
871     * value it returns.  For example, if it contains multiple child drawables
872     * and only shows one of them at a time, if only one of the children is
873     * TRANSLUCENT and the others are OPAQUE then TRANSLUCENT should be
874     * returned.  You can use the method {@link #resolveOpacity} to perform a
875     * standard reduction of two opacities to the appropriate single output.
876     *
877     * <p>Note that the returned value does not necessarily take into account a
878     * custom alpha or color filter that has been applied by the client through
879     * the {@link #setAlpha} or {@link #setColorFilter} methods. Some subclasses,
880     * such as {@link BitmapDrawable}, {@link ColorDrawable}, and {@link GradientDrawable},
881     * do account for the value of {@link #setAlpha}, but the general behavior is dependent
882     * upon the implementation of the subclass.
883     *
884     * @return int The opacity class of the Drawable.
885     *
886     * @see android.graphics.PixelFormat
887     */
888    public abstract int getOpacity();
889
890    /**
891     * Return the appropriate opacity value for two source opacities.  If
892     * either is UNKNOWN, that is returned; else, if either is TRANSLUCENT,
893     * that is returned; else, if either is TRANSPARENT, that is returned;
894     * else, OPAQUE is returned.
895     *
896     * <p>This is to help in implementing {@link #getOpacity}.
897     *
898     * @param op1 One opacity value.
899     * @param op2 Another opacity value.
900     *
901     * @return int The combined opacity value.
902     *
903     * @see #getOpacity
904     */
905    public static int resolveOpacity(int op1, int op2) {
906        if (op1 == op2) {
907            return op1;
908        }
909        if (op1 == PixelFormat.UNKNOWN || op2 == PixelFormat.UNKNOWN) {
910            return PixelFormat.UNKNOWN;
911        }
912        if (op1 == PixelFormat.TRANSLUCENT || op2 == PixelFormat.TRANSLUCENT) {
913            return PixelFormat.TRANSLUCENT;
914        }
915        if (op1 == PixelFormat.TRANSPARENT || op2 == PixelFormat.TRANSPARENT) {
916            return PixelFormat.TRANSPARENT;
917        }
918        return PixelFormat.OPAQUE;
919    }
920
921    /**
922     * Returns a Region representing the part of the Drawable that is completely
923     * transparent.  This can be used to perform drawing operations, identifying
924     * which parts of the target will not change when rendering the Drawable.
925     * The default implementation returns null, indicating no transparent
926     * region; subclasses can optionally override this to return an actual
927     * Region if they want to supply this optimization information, but it is
928     * not required that they do so.
929     *
930     * @return Returns null if the Drawables has no transparent region to
931     * report, else a Region holding the parts of the Drawable's bounds that
932     * are transparent.
933     */
934    public Region getTransparentRegion() {
935        return null;
936    }
937
938    /**
939     * Override this in your subclass to change appearance if you recognize the
940     * specified state.
941     *
942     * @return Returns true if the state change has caused the appearance of
943     * the Drawable to change (that is, it needs to be drawn), else false
944     * if it looks the same and there is no need to redraw it since its
945     * last state.
946     */
947    protected boolean onStateChange(int[] state) { return false; }
948
949    /**
950     * Called when the drawable level changes.
951     * <p>
952     * Override this in your subclass to change appearance if you vary based on
953     * level and do not need floating-point accuracy. To handle changes with
954     * higher accuracy, override {@link #onLevelChange(float)} instead.
955     * <p>
956     * <strong>Note:</strong> Do not override both this method and
957     * {@link #onLevelChange(float)}. Only override one method.
958     *
959     * @param level the level as an integer value, typically between 0
960     *              (minimum) and 10000 ({@link #MAX_LEVEL})
961     * @return {@code true} if the level change has caused the appearance of
962     *         the drawable to change such that it needs to be redrawn, or
963     *         {@code false} if there is no need to redraw
964     */
965    protected boolean onLevelChange(int level) { return false; }
966
967    /**
968     * Called when the drawable level changes.
969     * <p>
970     * Override this in your subclass to change appearance if you vary based on
971     * level and need floating-point accuracy.
972     * <p>
973     * <strong>Note:</strong> Do not override both this method and
974     * {@link #onLevelChange(int)}. Only override one method. If your app
975     * targets SDK <= 23 ({@link android.os.Build.VERSION_CODES#M M}), you
976     * will need to override {@link #onLevelChange(int)} to receive callbacks
977     * on devices running Android M and below.
978     *
979     * @param level the level as a floating-point value, typically between 0.0
980     *              and 10000.0 ({@link #MAX_LEVEL_FLOAT})
981     * @return {@code true} if the level change has caused the appearance of
982     *         the drawable to change such that it needs to be redrawn, or
983     *         {@code false} if there is no need to redraw
984     */
985    protected boolean onLevelChange(float level) {
986        return onLevelChange(Math.round(level));
987    }
988
989    /**
990     * Override this in your subclass to change appearance if you vary based on
991     * the bounds.
992     */
993    protected void onBoundsChange(Rect bounds) {}
994
995    /**
996     * Return the intrinsic width of the underlying drawable object.  Returns
997     * -1 if it has no intrinsic width, such as with a solid color.
998     */
999    public int getIntrinsicWidth() {
1000        return -1;
1001    }
1002
1003    /**
1004     * Return the intrinsic height of the underlying drawable object. Returns
1005     * -1 if it has no intrinsic height, such as with a solid color.
1006     */
1007    public int getIntrinsicHeight() {
1008        return -1;
1009    }
1010
1011    /**
1012     * Returns the minimum width suggested by this Drawable. If a View uses this
1013     * Drawable as a background, it is suggested that the View use at least this
1014     * value for its width. (There will be some scenarios where this will not be
1015     * possible.) This value should INCLUDE any padding.
1016     *
1017     * @return The minimum width suggested by this Drawable. If this Drawable
1018     *         doesn't have a suggested minimum width, 0 is returned.
1019     */
1020    public int getMinimumWidth() {
1021        final int intrinsicWidth = getIntrinsicWidth();
1022        return intrinsicWidth > 0 ? intrinsicWidth : 0;
1023    }
1024
1025    /**
1026     * Returns the minimum height suggested by this Drawable. If a View uses this
1027     * Drawable as a background, it is suggested that the View use at least this
1028     * value for its height. (There will be some scenarios where this will not be
1029     * possible.) This value should INCLUDE any padding.
1030     *
1031     * @return The minimum height suggested by this Drawable. If this Drawable
1032     *         doesn't have a suggested minimum height, 0 is returned.
1033     */
1034    public int getMinimumHeight() {
1035        final int intrinsicHeight = getIntrinsicHeight();
1036        return intrinsicHeight > 0 ? intrinsicHeight : 0;
1037    }
1038
1039    /**
1040     * Return in padding the insets suggested by this Drawable for placing
1041     * content inside the drawable's bounds. Positive values move toward the
1042     * center of the Drawable (set Rect.inset).
1043     *
1044     * @return true if this drawable actually has a padding, else false. When false is returned,
1045     * the padding is always set to 0.
1046     */
1047    public boolean getPadding(@NonNull Rect padding) {
1048        padding.set(0, 0, 0, 0);
1049        return false;
1050    }
1051
1052    /**
1053     * Return in insets the layout insets suggested by this Drawable for use with alignment
1054     * operations during layout.
1055     *
1056     * @hide
1057     */
1058    public Insets getOpticalInsets() {
1059        return Insets.NONE;
1060    }
1061
1062    /**
1063     * Called to get the drawable to populate the Outline that defines its drawing area.
1064     * <p>
1065     * This method is called by the default {@link android.view.ViewOutlineProvider} to define
1066     * the outline of the View.
1067     * <p>
1068     * The default behavior defines the outline to be the bounding rectangle of 0 alpha.
1069     * Subclasses that wish to convey a different shape or alpha value must override this method.
1070     *
1071     * @see android.view.View#setOutlineProvider(android.view.ViewOutlineProvider)
1072     */
1073    public void getOutline(@NonNull Outline outline) {
1074        outline.setRect(getBounds());
1075        outline.setAlpha(0);
1076    }
1077
1078    /**
1079     * Make this drawable mutable. This operation cannot be reversed. A mutable
1080     * drawable is guaranteed to not share its state with any other drawable.
1081     * This is especially useful when you need to modify properties of drawables
1082     * loaded from resources. By default, all drawables instances loaded from
1083     * the same resource share a common state; if you modify the state of one
1084     * instance, all the other instances will receive the same modification.
1085     *
1086     * Calling this method on a mutable Drawable will have no effect.
1087     *
1088     * @return This drawable.
1089     * @see ConstantState
1090     * @see #getConstantState()
1091     */
1092    public Drawable mutate() {
1093        return this;
1094    }
1095
1096    /**
1097     * Clears the mutated state, allowing this drawable to be cached and
1098     * mutated again.
1099     * <p>
1100     * This is hidden because only framework drawables can be cached, so
1101     * custom drawables don't need to support constant state, mutate(), or
1102     * clearMutated().
1103     *
1104     * @hide
1105     */
1106    public void clearMutated() {
1107        // Default implementation is no-op.
1108    }
1109
1110    /**
1111     * Create a drawable from an inputstream
1112     */
1113    public static Drawable createFromStream(InputStream is, String srcName) {
1114        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable");
1115        try {
1116            return createFromResourceStream(null, null, is, srcName);
1117        } finally {
1118            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1119        }
1120    }
1121
1122    /**
1123     * Create a drawable from an inputstream, using the given resources and
1124     * value to determine density information.
1125     */
1126    public static Drawable createFromResourceStream(Resources res, TypedValue value,
1127            InputStream is, String srcName) {
1128        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable");
1129        try {
1130            return createFromResourceStream(res, value, is, srcName, null);
1131        } finally {
1132            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1133        }
1134    }
1135
1136    /**
1137     * Create a drawable from an inputstream, using the given resources and
1138     * value to determine density information.
1139     */
1140    public static Drawable createFromResourceStream(Resources res, TypedValue value,
1141            InputStream is, String srcName, BitmapFactory.Options opts) {
1142        if (is == null) {
1143            return null;
1144        }
1145
1146        /*  ugh. The decodeStream contract is that we have already allocated
1147            the pad rect, but if the bitmap does not had a ninepatch chunk,
1148            then the pad will be ignored. If we could change this to lazily
1149            alloc/assign the rect, we could avoid the GC churn of making new
1150            Rects only to drop them on the floor.
1151        */
1152        Rect pad = new Rect();
1153
1154        // Special stuff for compatibility mode: if the target density is not
1155        // the same as the display density, but the resource -is- the same as
1156        // the display density, then don't scale it down to the target density.
1157        // This allows us to load the system's density-correct resources into
1158        // an application in compatibility mode, without scaling those down
1159        // to the compatibility density only to have them scaled back up when
1160        // drawn to the screen.
1161        if (opts == null) opts = new BitmapFactory.Options();
1162        opts.inScreenDensity = res != null
1163                ? res.getDisplayMetrics().noncompatDensityDpi : DisplayMetrics.DENSITY_DEVICE;
1164        Bitmap  bm = BitmapFactory.decodeResourceStream(res, value, is, pad, opts);
1165        if (bm != null) {
1166            byte[] np = bm.getNinePatchChunk();
1167            if (np == null || !NinePatch.isNinePatchChunk(np)) {
1168                np = null;
1169                pad = null;
1170            }
1171
1172            final Rect opticalInsets = new Rect();
1173            bm.getOpticalInsets(opticalInsets);
1174            return drawableFromBitmap(res, bm, np, pad, opticalInsets, srcName);
1175        }
1176        return null;
1177    }
1178
1179    /**
1180     * Create a drawable from an XML document. For more information on how to
1181     * create resources in XML, see
1182     * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.
1183     */
1184    public static Drawable createFromXml(Resources r, XmlPullParser parser)
1185            throws XmlPullParserException, IOException {
1186        return createFromXml(r, parser, null);
1187    }
1188
1189    /**
1190     * Create a drawable from an XML document using an optional {@link Theme}.
1191     * For more information on how to create resources in XML, see
1192     * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.
1193     */
1194    public static Drawable createFromXml(Resources r, XmlPullParser parser, Theme theme)
1195            throws XmlPullParserException, IOException {
1196        AttributeSet attrs = Xml.asAttributeSet(parser);
1197
1198        int type;
1199        while ((type=parser.next()) != XmlPullParser.START_TAG &&
1200                type != XmlPullParser.END_DOCUMENT) {
1201            // Empty loop
1202        }
1203
1204        if (type != XmlPullParser.START_TAG) {
1205            throw new XmlPullParserException("No start tag found");
1206        }
1207
1208        Drawable drawable = createFromXmlInner(r, parser, attrs, theme);
1209
1210        if (drawable == null) {
1211            throw new RuntimeException("Unknown initial tag: " + parser.getName());
1212        }
1213
1214        return drawable;
1215    }
1216
1217    /**
1218     * Create from inside an XML document.  Called on a parser positioned at
1219     * a tag in an XML document, tries to create a Drawable from that tag.
1220     * Returns null if the tag is not a valid drawable.
1221     */
1222    public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs)
1223            throws XmlPullParserException, IOException {
1224        return createFromXmlInner(r, parser, attrs, null);
1225    }
1226
1227    /**
1228     * Create a drawable from inside an XML document using an optional
1229     * {@link Theme}. Called on a parser positioned at a tag in an XML
1230     * document, tries to create a Drawable from that tag. Returns {@code null}
1231     * if the tag is not a valid drawable.
1232     */
1233    public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs,
1234            Theme theme) throws XmlPullParserException, IOException {
1235        return r.getDrawableInflater().inflateFromXml(parser.getName(), parser, attrs, theme);
1236    }
1237
1238    /**
1239     * Create a drawable from file path name.
1240     */
1241    public static Drawable createFromPath(String pathName) {
1242        if (pathName == null) {
1243            return null;
1244        }
1245
1246        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, pathName);
1247        try {
1248            Bitmap bm = BitmapFactory.decodeFile(pathName);
1249            if (bm != null) {
1250                return drawableFromBitmap(null, bm, null, null, null, pathName);
1251            }
1252        } finally {
1253            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1254        }
1255
1256        return null;
1257    }
1258
1259    /**
1260     * Inflate this Drawable from an XML resource. Does not apply a theme.
1261     *
1262     * @see #inflate(Resources, XmlPullParser, AttributeSet, Theme)
1263     */
1264    public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs)
1265            throws XmlPullParserException, IOException {
1266        inflate(r, parser, attrs, null);
1267    }
1268
1269    /**
1270     * Inflate this Drawable from an XML resource optionally styled by a theme.
1271     *
1272     * @param r Resources used to resolve attribute values
1273     * @param parser XML parser from which to inflate this Drawable
1274     * @param attrs Base set of attribute values
1275     * @param theme Theme to apply, may be null
1276     * @throws XmlPullParserException
1277     * @throws IOException
1278     */
1279    public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme)
1280            throws XmlPullParserException, IOException {
1281        final TypedArray a;
1282        if (theme != null) {
1283            a = theme.obtainStyledAttributes(
1284                    attrs, com.android.internal.R.styleable.Drawable, 0, 0);
1285        } else {
1286            a = r.obtainAttributes(attrs, com.android.internal.R.styleable.Drawable);
1287        }
1288
1289        inflateWithAttributes(r, parser, a, com.android.internal.R.styleable.Drawable_visible);
1290        a.recycle();
1291    }
1292
1293    /**
1294     * Inflate a Drawable from an XML resource.
1295     *
1296     * @throws XmlPullParserException
1297     * @throws IOException
1298     */
1299    void inflateWithAttributes(Resources r, XmlPullParser parser, TypedArray attrs, int visibleAttr)
1300            throws XmlPullParserException, IOException {
1301        mVisible = attrs.getBoolean(visibleAttr, mVisible);
1302    }
1303
1304    /**
1305     * This abstract class is used by {@link Drawable}s to store shared constant state and data
1306     * between Drawables. {@link BitmapDrawable}s created from the same resource will for instance
1307     * share a unique bitmap stored in their ConstantState.
1308     *
1309     * <p>
1310     * {@link #newDrawable(Resources)} can be used as a factory to create new Drawable instances
1311     * from this ConstantState.
1312     * </p>
1313     *
1314     * Use {@link Drawable#getConstantState()} to retrieve the ConstantState of a Drawable. Calling
1315     * {@link Drawable#mutate()} on a Drawable should typically create a new ConstantState for that
1316     * Drawable.
1317     */
1318    public static abstract class ConstantState {
1319        /**
1320         * Create a new drawable without supplying resources the caller
1321         * is running in.  Note that using this means the density-dependent
1322         * drawables (like bitmaps) will not be able to update their target
1323         * density correctly. One should use {@link #newDrawable(Resources)}
1324         * instead to provide a resource.
1325         */
1326        public abstract Drawable newDrawable();
1327
1328        /**
1329         * Create a new Drawable instance from its constant state.  This
1330         * must be implemented for drawables that change based on the target
1331         * density of their caller (that is depending on whether it is
1332         * in compatibility mode).
1333         */
1334        public Drawable newDrawable(Resources res) {
1335            return newDrawable();
1336        }
1337
1338        /**
1339         * Create a new Drawable instance from its constant state. This must be
1340         * implemented for drawables that can have a theme applied.
1341         */
1342        public Drawable newDrawable(Resources res, Theme theme) {
1343            return newDrawable(null);
1344        }
1345
1346        /**
1347         * Return a bit mask of configuration changes that will impact
1348         * this drawable (and thus require completely reloading it).
1349         */
1350        public abstract int getChangingConfigurations();
1351
1352        /**
1353         * @return Total pixel count
1354         * @hide
1355         */
1356        public int addAtlasableBitmaps(Collection<Bitmap> atlasList) {
1357            return 0;
1358        }
1359
1360        /** @hide */
1361        protected final boolean isAtlasable(Bitmap bitmap) {
1362            return bitmap != null && bitmap.getConfig() == Bitmap.Config.ARGB_8888;
1363        }
1364
1365        /**
1366         * Return whether this constant state can have a theme applied.
1367         */
1368        public boolean canApplyTheme() {
1369            return false;
1370        }
1371    }
1372
1373    /**
1374     * Return a {@link ConstantState} instance that holds the shared state of this Drawable.
1375     *
1376     * @return The ConstantState associated to that Drawable.
1377     * @see ConstantState
1378     * @see Drawable#mutate()
1379     */
1380    public ConstantState getConstantState() {
1381        return null;
1382    }
1383
1384    private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np,
1385            Rect pad, Rect layoutBounds, String srcName) {
1386
1387        if (np != null) {
1388            return new NinePatchDrawable(res, bm, np, pad, layoutBounds, srcName);
1389        }
1390
1391        return new BitmapDrawable(res, bm);
1392    }
1393
1394    /**
1395     * Ensures the tint filter is consistent with the current tint color and
1396     * mode.
1397     */
1398    PorterDuffColorFilter updateTintFilter(PorterDuffColorFilter tintFilter, ColorStateList tint,
1399            PorterDuff.Mode tintMode) {
1400        if (tint == null || tintMode == null) {
1401            return null;
1402        }
1403
1404        final int color = tint.getColorForState(getState(), Color.TRANSPARENT);
1405        if (tintFilter == null) {
1406            return new PorterDuffColorFilter(color, tintMode);
1407        }
1408
1409        tintFilter.setColor(color);
1410        tintFilter.setMode(tintMode);
1411        return tintFilter;
1412    }
1413
1414    /**
1415     * Animatable property for Drawable level.
1416     *
1417     * @hide Until Drawable animations have been cleaned up.
1418     */
1419    public static final FloatProperty<Drawable> LEVEL = new FloatProperty<Drawable>("levelFloat") {
1420        @Override
1421        public Float get(Drawable object) {
1422            return object.getLevelFloat();
1423        }
1424
1425        @Override
1426        public void setValue(Drawable object, float value) {
1427            object.setLevel(value);
1428        }
1429    };
1430
1431    /**
1432     * Obtains styled attributes from the theme, if available, or unstyled
1433     * resources if the theme is null.
1434     */
1435    static TypedArray obtainAttributes(
1436            Resources res, Theme theme, AttributeSet set, int[] attrs) {
1437        if (theme == null) {
1438            return res.obtainAttributes(set, attrs);
1439        }
1440        return theme.obtainStyledAttributes(set, attrs, 0, 0);
1441    }
1442
1443    /**
1444     * Parses a {@link android.graphics.PorterDuff.Mode} from a tintMode
1445     * attribute's enum value.
1446     *
1447     * @hide
1448     */
1449    public static PorterDuff.Mode parseTintMode(int value, Mode defaultMode) {
1450        switch (value) {
1451            case 3: return Mode.SRC_OVER;
1452            case 5: return Mode.SRC_IN;
1453            case 9: return Mode.SRC_ATOP;
1454            case 14: return Mode.MULTIPLY;
1455            case 15: return Mode.SCREEN;
1456            case 16: return Mode.ADD;
1457            default: return defaultMode;
1458        }
1459    }
1460}
1461
1462