Drawable.java revision 9066cfe9886ac131c34d59ed0e2d287b0e3c0087
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 java.io.InputStream;
20import java.io.IOException;
21import java.util.Arrays;
22
23import org.xmlpull.v1.XmlPullParser;
24import org.xmlpull.v1.XmlPullParserException;
25
26import android.content.res.Resources;
27import android.content.res.TypedArray;
28import android.graphics.*;
29import android.util.AttributeSet;
30import android.util.StateSet;
31import android.util.Xml;
32import android.util.TypedValue;
33
34/**
35 * A Drawable is a general abstraction for "something that can be drawn."  Most
36 * often you will deal with Drawable as the type of resource retrieved for
37 * drawing things to the screen; the Drawable class provides a generic API for
38 * dealing with an underlying visual resource that may take a variety of forms.
39 * Unlike a {@link android.view.View}, a Drawable does not have any facility to
40 * receive events or otherwise interact with the user.
41 *
42 * <p>In addition to simple drawing, Drawable provides a number of generic
43 * mechanisms for its client to interact with what is being drawn:
44 *
45 * <ul>
46 *     <li> The {@link #setBounds} method <var>must</var> be called to tell the
47 *     Drawable where it is drawn and how large it should be.  All Drawables
48 *     should respect the requested size, often simply by scaling their
49 *     imagery.  A client can find the preferred size for some Drawables with
50 *     the {@link #getIntrinsicHeight} and {@link #getIntrinsicWidth} methods.
51 *
52 *     <li> The {@link #getPadding} method can return from some Drawables
53 *     information about how to frame content that is placed inside of them.
54 *     For example, a Drawable that is intended to be the frame for a button
55 *     widget would need to return padding that correctly places the label
56 *     inside of itself.
57 *
58 *     <li> The {@link #setState} method allows the client to tell the Drawable
59 *     in which state it is to be drawn, such as "focused", "selected", etc.
60 *     Some drawables may modify their imagery based on the selected state.
61 *
62 *     <li> The {@link #setLevel} method allows the client to supply a single
63 *     continuous controller that can modify the Drawable is displayed, such as
64 *     a battery level or progress level.  Some drawables may modify their
65 *     imagery based on the current level.
66 *
67 *     <li> A Drawable can perform animations by calling back to its client
68 *     through the {@link Callback} interface.  All clients should support this
69 *     interface (via {@link #setCallback}) so that animations will work.  A
70 *     simple way to do this is through the system facilities such as
71 *     {@link android.view.View#setBackgroundDrawable(Drawable)} and
72 *     {@link android.widget.ImageView}.
73 * </ul>
74 *
75 * Though usually not visible to the application, Drawables may take a variety
76 * of forms:
77 *
78 * <ul>
79 *     <li> <b>Bitmap</b>: the simplest Drawable, a PNG or JPEG image.
80 *     <li> <b>Nine Patch</b>: an extension to the PNG format allows it to
81 *     specify information about how to stretch it and place things inside of
82 *     it.
83 *     <li> <b>Shape</b>: contains simple drawing commands instead of a raw
84 *     bitmap, allowing it to resize better in some cases.
85 *     <li> <b>Layers</b>: a compound drawable, which draws multiple underlying
86 *     drawables on top of each other.
87 *     <li> <b>States</b>: a compound drawable that selects one of a set of
88 *     drawables based on its state.
89 *     <li> <b>Levels</b>: a compound drawable that selects one of a set of
90 *     drawables based on its level.
91 *     <li> <b>Scale</b>: a compound drawable with a single child drawable,
92 *     whose overall size is modified based on the current level.
93 * </ul>
94 * <p>For information and examples of creating drawable resources (XML or bitmap files that
95 * can be loaded in code), see <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources
96 * and Internationalization</a>.
97 */
98public abstract class Drawable {
99
100    private int[] mStateSet = StateSet.WILD_CARD;
101    private int mLevel = 0;
102    private int mChangingConfigurations = 0;
103    private Rect mBounds = new Rect();
104    /*package*/ Callback mCallback = null;
105    private boolean mVisible = true;
106
107    /**
108     * Draw in its bounds (set via setBounds) respecting optional effects such
109     * as alpha (set via setAlpha) and color filter (set via setColorFilter).
110     *
111     * @param canvas The canvas to draw into
112     */
113    public abstract void draw(Canvas canvas);
114
115    /**
116     * Specify a bounding rectangle for the Drawable. This is where the drawable
117     * will draw when its draw() method is called.
118     */
119    public void setBounds(int left, int top, int right, int bottom) {
120        Rect oldBounds = mBounds;
121
122        if (oldBounds.left != left || oldBounds.top != top ||
123                oldBounds.right != right || oldBounds.bottom != bottom) {
124            mBounds.set(left, top, right, bottom);
125            onBoundsChange(mBounds);
126        }
127    }
128
129    /**
130     * Specify a bounding rectangle for the Drawable. This is where the drawable
131     * will draw when its draw() method is called.
132     */
133    public void setBounds(Rect bounds) {
134        setBounds(bounds.left, bounds.top, bounds.right, bounds.bottom);
135    }
136
137    /**
138     * Return a copy of the drawable's bounds in the specified Rect (allocated
139     * by the caller). The bounds specify where this will draw when its draw()
140     * method is called.
141     *
142     * @param bounds Rect to receive the drawable's bounds (allocated by the
143     *               caller).
144     */
145    public final void copyBounds(Rect bounds) {
146        bounds.set(mBounds);
147    }
148
149    /**
150     * Return a copy of the drawable's bounds in a new Rect. This returns the
151     * same values as getBounds(), but the returned object is guaranteed to not
152     * be changed later by the drawable (i.e. it retains no reference to this
153     * rect). If the caller already has a Rect allocated, call copyBounds(rect)
154     *
155     * @return A copy of the drawable's bounds
156     */
157    public final Rect copyBounds() {
158        return new Rect(mBounds);
159    }
160
161    /**
162     * Return the drawable's bounds Rect. Note: for efficiency, the returned
163     * object may be the same object stored in the drawable (though this is not
164     * guaranteed), so if a persistent copy of the bounds is needed, call
165     * copyBounds(rect) instead.
166     *
167     * @return The bounds of the drawable (which may change later, so caller
168     *         beware).
169     */
170    public final Rect getBounds() {
171        return mBounds;
172    }
173
174    /**
175     * Set a mask of the configuration parameters for which this drawable
176     * may change, requiring that it be re-created.
177     *
178     * @param configs A mask of the changing configuration parameters, as
179     * defined by {@link android.content.res.Configuration}.
180     *
181     * @see android.content.res.Configuration
182     */
183    public void setChangingConfigurations(int configs) {
184        mChangingConfigurations = configs;
185    }
186
187    /**
188     * Return a mask of the configuration parameters for which this drawable
189     * mau change, requiring that it be re-created.  The default implementation
190     * returns whatever was provided through
191     * {@link #setChangingConfigurations(int)} or 0 by default.  Subclasses
192     * may extend this to or in the changing configurations of any other
193     * drawables they hold.
194     *
195     * @return Returns a mask of the changing configuration parameters, as
196     * defined by {@link android.content.res.Configuration}.
197     *
198     * @see android.content.res.Configuration
199     */
200    public int getChangingConfigurations() {
201        return mChangingConfigurations;
202    }
203
204    /**
205     * Set to true to have the drawable dither its colors when drawn to a device
206     * with fewer than 8-bits per color component. This can improve the look on
207     * those devices, but can also slow down the drawing a little.
208     */
209    public void setDither(boolean dither) {}
210
211    /**
212     * Set to true to have the drawable filter its bitmap when scaled or rotated
213     * (for drawables that use bitmaps). If the drawable does not use bitmaps,
214     * this call is ignored. This can improve the look when scaled or rotated,
215     * but also slows down the drawing.
216     */
217    public void setFilterBitmap(boolean filter) {}
218
219    /**
220     * Implement this interface if you want to create an animated drawable that
221     * extends {@link android.graphics.drawable.Drawable Drawable}.
222     * Upon retrieving a drawable, use
223     * {@link Drawable#setCallback(android.graphics.drawable.Drawable.Callback)}
224     * to supply your implementation of the interface to the drawable; it uses
225     * this interface to schedule and execute animation changes.
226     */
227    public static interface Callback {
228        /**
229         * Called when the drawable needs to be redrawn.  A view at this point
230         * should invalidate itself (or at least the part of itself where the
231         * drawable appears).
232         *
233         * @param who The drawable that is requesting the update.
234         */
235        public void invalidateDrawable(Drawable who);
236
237        /**
238         * A Drawable can call this to schedule the next frame of its
239         * animation.  An implementation can generally simply call
240         * {@link android.os.Handler#postAtTime(Runnable, Object, long)} with
241         * the parameters <var>(what, who, when)</var> to perform the
242         * scheduling.
243         *
244         * @param who The drawable being scheduled.
245         * @param what The action to execute.
246         * @param when The time (in milliseconds) to run.  The timebase is
247         *             {@link android.os.SystemClock#uptimeMillis}
248         */
249        public void scheduleDrawable(Drawable who, Runnable what, long when);
250
251        /**
252         * A Drawable can call this to unschedule an action previously
253         * scheduled with {@link #scheduleDrawable}.  An implementation can
254         * generally simply call
255         * {@link android.os.Handler#removeCallbacks(Runnable, Object)} with
256         * the parameters <var>(what, who)</var> to unschedule the drawable.
257         *
258         * @param who The drawable being unscheduled.
259         * @param what The action being unscheduled.
260         */
261        public void unscheduleDrawable(Drawable who, Runnable what);
262    }
263
264    /**
265     * Bind a {@link Callback} object to this Drawable.  Required for clients
266     * that want to support animated drawables.
267     *
268     * @param cb The client's Callback implementation.
269     */
270    public final void setCallback(Callback cb) {
271        mCallback = cb;
272    }
273
274    /**
275     * Use the current {@link Callback} implementation to have this Drawable
276     * redrawn.  Does nothing if there is no Callback attached to the
277     * Drawable.
278     *
279     * @see Callback#invalidateDrawable
280     */
281    public void invalidateSelf()
282    {
283        if (mCallback != null) {
284            mCallback.invalidateDrawable(this);
285        }
286    }
287
288    /**
289     * Use the current {@link Callback} implementation to have this Drawable
290     * scheduled.  Does nothing if there is no Callback attached to the
291     * Drawable.
292     *
293     * @param what The action being scheduled.
294     * @param when The time (in milliseconds) to run.
295     *
296     * @see Callback#scheduleDrawable
297     */
298    public void scheduleSelf(Runnable what, long when)
299    {
300        if (mCallback != null) {
301            mCallback.scheduleDrawable(this, what, when);
302        }
303    }
304
305    /**
306     * Use the current {@link Callback} implementation to have this Drawable
307     * unscheduled.  Does nothing if there is no Callback attached to the
308     * Drawable.
309     *
310     * @param what The runnable that you no longer want called.
311     *
312     * @see Callback#unscheduleDrawable
313     */
314    public void unscheduleSelf(Runnable what)
315    {
316        if (mCallback != null) {
317            mCallback.unscheduleDrawable(this, what);
318        }
319    }
320
321    /**
322     * Specify an alpha value for the drawable. 0 means fully transparent, and
323     * 255 means fully opaque.
324     */
325    public abstract void setAlpha(int alpha);
326
327    /**
328     * Specify an optional colorFilter for the drawable. Pass null to remove
329     * any filters.
330    */
331    public abstract void setColorFilter(ColorFilter cf);
332
333    /**
334     * Specify a color and porterduff mode to be the colorfilter for this
335     * drawable.
336     */
337    public void setColorFilter(int color, PorterDuff.Mode mode) {
338        setColorFilter(new PorterDuffColorFilter(color, mode));
339    }
340
341    public void clearColorFilter() {
342        setColorFilter(null);
343    }
344
345    /**
346     * Indicates whether this view will change its appearance based on state.
347     * Clients can use this to determine whether it is necessary to calculate
348     * their state and call setState.
349     *
350     * @return True if this view changes its appearance based on state, false
351     *         otherwise.
352     *
353     * @see #setState(int[])
354     */
355    public boolean isStateful() {
356        return false;
357    }
358
359    /**
360     * Specify a set of states for the drawable. These are use-case specific,
361     * so see the relevant documentation. As an example, the background for
362     * widgets like Button understand the following states:
363     * [{@link android.R.attr#state_focused},
364     *  {@link android.R.attr#state_pressed}].
365     *
366     * <p>If the new state you are supplying causes the appearance of the
367     * Drawable to change, then it is responsible for calling
368     * {@link #invalidateSelf} in order to have itself redrawn, <em>and</em>
369     * true will be returned from this function.
370     *
371     * <p>Note: The Drawable holds a reference on to <var>stateSet</var>
372     * until a new state array is given to it, so you must not modify this
373     * array during that time.</p>
374     *
375     * @param stateSet The new set of states to be displayed.
376     *
377     * @return Returns true if this change in state has caused the appearance
378     * of the Drawable to change (hence requiring an invalidate), otherwise
379     * returns false.
380     */
381    public boolean setState(final int[] stateSet) {
382        if (!Arrays.equals(mStateSet, stateSet)) {
383            mStateSet = stateSet;
384            return onStateChange(stateSet);
385        }
386        return false;
387    }
388
389    /**
390     * Describes the current state, as a union of primitve states, such as
391     * {@link android.R.attr#state_focused},
392     * {@link android.R.attr#state_selected}, etc.
393     * Some drawables may modify their imagery based on the selected state.
394     * @return An array of resource Ids describing the current state.
395     */
396    public int[] getState() {
397        return mStateSet;
398    }
399
400    /**
401     * @return The current drawable that will be used by this drawable. For simple drawables, this
402     *         is just the drawable itself. For drawables that change state like
403     *         {@link StateListDrawable} and {@link LevelListDrawable} this will be the child drawable
404     *         currently in use.
405     */
406    public Drawable getCurrent() {
407        return this;
408    }
409
410    /**
411     * Specify the level for the drawable.  This allows a drawable to vary its
412     * imagery based on a continuous controller, for example to show progress
413     * or volume level.
414     *
415     * <p>If the new level you are supplying causes the appearance of the
416     * Drawable to change, then it is responsible for calling
417     * {@link #invalidateSelf} in order to have itself redrawn, <em>and</em>
418     * true will be returned from this function.
419     *
420     * @param level The new level, from 0 (minimum) to 10000 (maximum).
421     *
422     * @return Returns true if this change in level has caused the appearance
423     * of the Drawable to change (hence requiring an invalidate), otherwise
424     * returns false.
425     */
426    public final boolean setLevel(int level) {
427        if (mLevel != level) {
428            mLevel = level;
429            return onLevelChange(level);
430        }
431        return false;
432    }
433
434    /**
435     * Retrieve the current level.
436     *
437     * @return int Current level, from 0 (minimum) to 10000 (maximum).
438     */
439    public final int getLevel() {
440        return mLevel;
441    }
442
443    /**
444     * Set whether this Drawable is visible.  This generally does not impact
445     * the Drawable's behavior, but is a hint that can be used by some
446     * Drawables, for example, to decide whether run animations.
447     *
448     * @param visible Set to true if visible, false if not.
449     * @param restart You can supply true here to force the drawable to behave
450     *                as if it has just become visible, even if it had last
451     *                been set visible.  Used for example to force animations
452     *                to restart.
453     *
454     * @return boolean Returns true if the new visibility is different than
455     *         its previous state.
456     */
457    public boolean setVisible(boolean visible, boolean restart) {
458        boolean changed = mVisible != visible;
459        mVisible = visible;
460        return changed;
461    }
462
463    public final boolean isVisible() {
464        return mVisible;
465    }
466
467    /**
468     * Return the opacity/transparency of this Drawable.  The returned value is
469     * one of the abstract format constants in
470     * {@link android.graphics.PixelFormat}:
471     * {@link android.graphics.PixelFormat#UNKNOWN},
472     * {@link android.graphics.PixelFormat#TRANSLUCENT},
473     * {@link android.graphics.PixelFormat#TRANSPARENT}, or
474     * {@link android.graphics.PixelFormat#OPAQUE}.
475     *
476     * <p>Generally a Drawable should be as conservative as possible with the
477     * value it returns.  For example, if it contains multiple child drawables
478     * and only shows one of them at a time, if only one of the children is
479     * TRANSLUCENT and the others are OPAQUE then TRANSLUCENT should be
480     * returned.  You can use the method {@link #resolveOpacity} to perform a
481     * standard reduction of two opacities to the appropriate single output.
482     *
483     * <p>Note that the returned value does <em>not</em> take into account a
484     * custom alpha or color filter that has been applied by the client through
485     * the {@link #setAlpha} or {@link #setColorFilter} methods.
486     *
487     * @return int The opacity class of the Drawable.
488     *
489     * @see android.graphics.PixelFormat
490     */
491    public abstract int getOpacity();
492
493    /**
494     * Return the appropriate opacity value for two source opacities.  If
495     * either is UNKNOWN, that is returned; else, if either is TRANSLUCENT,
496     * that is returned; else, if either is TRANSPARENT, that is returned;
497     * else, OPAQUE is returned.
498     *
499     * <p>This is to help in implementing {@link #getOpacity}.
500     *
501     * @param op1 One opacity value.
502     * @param op2 Another opacity value.
503     *
504     * @return int The combined opacity value.
505     *
506     * @see #getOpacity
507     */
508    public static int resolveOpacity(int op1, int op2) {
509        if (op1 == op2) {
510            return op1;
511        }
512        if (op1 == PixelFormat.UNKNOWN || op2 == PixelFormat.UNKNOWN) {
513            return PixelFormat.UNKNOWN;
514        }
515        if (op1 == PixelFormat.TRANSLUCENT || op2 == PixelFormat.TRANSLUCENT) {
516            return PixelFormat.TRANSLUCENT;
517        }
518        if (op1 == PixelFormat.TRANSPARENT || op2 == PixelFormat.TRANSPARENT) {
519            return PixelFormat.TRANSPARENT;
520        }
521        return PixelFormat.OPAQUE;
522    }
523
524    /**
525     * Returns a Region representing the part of the Drawable that is completely
526     * transparent.  This can be used to perform drawing operations, identifying
527     * which parts of the target will not change when rendering the Drawable.
528     * The default implementation returns null, indicating no transparent
529     * region; subclasses can optionally override this to return an actual
530     * Region if they want to supply this optimization information, but it is
531     * not required that they do so.
532     *
533     * @return Returns null if the Drawables has no transparent region to
534     * report, else a Region holding the parts of the Drawable's bounds that
535     * are transparent.
536     */
537    public Region getTransparentRegion() {
538        return null;
539    }
540
541    /**
542     * Override this in your subclass to change appearance if you recognize the
543     * specified state.
544     *
545     * @return Returns true if the state change has caused the appearance of
546     * the Drawable to change (that is, it needs to be drawn), else false
547     * if it looks the same and there is no need to redraw it since its
548     * last state.
549     */
550    protected boolean onStateChange(int[] state) { return false; }
551    /** Override this in your subclass to change appearance if you vary based
552     *  on level.
553     * @return Returns true if the level change has caused the appearance of
554     * the Drawable to change (that is, it needs to be drawn), else false
555     * if it looks the same and there is no need to redraw it since its
556     * last level.
557     */
558    protected boolean onLevelChange(int level) { return false; }
559    /**
560     * Override this in your subclass to change appearance if you recognize the
561     * specified state.
562     */
563    protected void onBoundsChange(Rect bounds) {}
564
565    /**
566     * Return the intrinsic width of the underlying drawable object.  Returns
567     * -1 if it has no intrinsic width, such as with a solid color.
568     */
569    public int getIntrinsicWidth() {
570        return -1;
571    }
572
573    /**
574     * Return the intrinsic height of the underlying drawable object. Returns
575     * -1 if it has no intrinsic height, such as with a solid color.
576     */
577    public int getIntrinsicHeight() {
578        return -1;
579    }
580
581    /**
582     * Returns the minimum width suggested by this Drawable. If a View uses this
583     * Drawable as a background, it is suggested that the View use at least this
584     * value for its width. (There will be some scenarios where this will not be
585     * possible.) This value should INCLUDE any padding.
586     *
587     * @return The minimum width suggested by this Drawable. If this Drawable
588     *         doesn't have a suggested minimum width, 0 is returned.
589     */
590    public int getMinimumWidth() {
591        final int intrinsicWidth = getIntrinsicWidth();
592        return intrinsicWidth > 0 ? intrinsicWidth : 0;
593    }
594
595    /**
596     * Returns the minimum height suggested by this Drawable. If a View uses this
597     * Drawable as a background, it is suggested that the View use at least this
598     * value for its height. (There will be some scenarios where this will not be
599     * possible.) This value should INCLUDE any padding.
600     *
601     * @return The minimum height suggested by this Drawable. If this Drawable
602     *         doesn't have a suggested minimum height, 0 is returned.
603     */
604    public int getMinimumHeight() {
605        final int intrinsicHeight = getIntrinsicHeight();
606        return intrinsicHeight > 0 ? intrinsicHeight : 0;
607    }
608
609    /**
610     * Return in padding the insets suggested by this Drawable for placing
611     * content inside the drawable's bounds. Positive values move toward the
612     * center of the Drawable (set Rect.inset). Returns true if this drawable
613     * actually has a padding, else false. When false is returned, the padding
614     * is always set to 0.
615     */
616    public boolean getPadding(Rect padding) {
617        padding.set(0, 0, 0, 0);
618        return false;
619    }
620
621    /**
622     * Make this drawable mutable. This operation cannot be reversed. A mutable
623     * drawable is guaranteed to not share its state with any other drawable.
624     * This is especially useful when you need to modify properties of drawables
625     * loaded from resources. By default, all drawables instances loaded from
626     * the same resource share a common state; if you modify the state of one
627     * instance, all the other instances will receive the same modification.
628     *
629     * Calling this method on a mutable Drawable will have no effect.
630     *
631     * @return This drawable.
632     */
633    public Drawable mutate() {
634        return this;
635    }
636
637    /**
638     * Create a drawable from an inputstream
639     */
640    public static Drawable createFromStream(InputStream is, String srcName) {
641        return createFromResourceStream(null, null, is, srcName);
642    }
643
644    /**
645     * Create a drawable from an inputstream
646     *
647     * @hide pending API council approval
648     */
649    public static Drawable createFromResourceStream(Resources res, TypedValue value,
650            InputStream is, String srcName) {
651
652        if (is == null) {
653            return null;
654        }
655
656        /*  ugh. The decodeStream contract is that we have already allocated
657            the pad rect, but if the bitmap does not had a ninepatch chunk,
658            then the pad will be ignored. If we could change this to lazily
659            alloc/assign the rect, we could avoid the GC churn of making new
660            Rects only to drop them on the floor.
661        */
662        Rect pad = new Rect();
663        Bitmap  bm = BitmapFactory.decodeStream(res, value, is, pad, null);
664        if (bm != null) {
665            byte[] np = bm.getNinePatchChunk();
666            if (np == null || !NinePatch.isNinePatchChunk(np)) {
667                np = null;
668                pad = null;
669            }
670            return drawableFromBitmap(res, bm, np, pad, srcName);
671        }
672        return null;
673    }
674
675    /**
676     * Create a drawable from an XML document. For more information on how to
677     * create resources in XML, see
678     * <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources and
679     * Internationalization</a>.
680     */
681    public static Drawable createFromXml(Resources r, XmlPullParser parser)
682            throws XmlPullParserException, IOException {
683        AttributeSet attrs = Xml.asAttributeSet(parser);
684
685        int type;
686        while ((type=parser.next()) != XmlPullParser.START_TAG &&
687                type != XmlPullParser.END_DOCUMENT) {
688            // Empty loop
689        }
690
691        if (type != XmlPullParser.START_TAG) {
692            throw new XmlPullParserException("No start tag found");
693        }
694
695        Drawable drawable = createFromXmlInner(r, parser, attrs);
696
697        if (drawable == null) {
698            throw new RuntimeException("Unknown initial tag: " + parser.getName());
699        }
700
701        return drawable;
702    }
703
704    /**
705     * Create from inside an XML document.  Called on a parser positioned at
706     * a tag in an XML document, tries to create a Drawable from that tag.
707     * Returns null if the tag is not a valid drawable.
708     */
709    public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs)
710    throws XmlPullParserException, IOException {
711        Drawable drawable;
712
713        final String name = parser.getName();
714
715        if (name.equals("selector")) {
716            drawable = new StateListDrawable();
717        } else if (name.equals("level-list")) {
718            drawable = new LevelListDrawable();
719        } else if (name.equals("layer-list")) {
720            drawable = new LayerDrawable();
721        } else if (name.equals("transition")) {
722            drawable = new TransitionDrawable();
723        } else if (name.equals("color")) {
724            drawable = new ColorDrawable();
725        } else if (name.equals("shape")) {
726            drawable = new GradientDrawable();
727        } else if (name.equals("scale")) {
728            drawable = new ScaleDrawable();
729        } else if (name.equals("clip")) {
730            drawable = new ClipDrawable();
731        } else if (name.equals("rotate")) {
732            drawable = new RotateDrawable();
733        } else if (name.equals("animation-list")) {
734            drawable = new AnimationDrawable();
735        } else if (name.equals("inset")) {
736            drawable = new InsetDrawable();
737        } else if (name.equals("bitmap")) {
738            drawable = new BitmapDrawable();
739            if (r != null) {
740               ((BitmapDrawable) drawable).setDensityScale(r.getDisplayMetrics());
741            }
742        } else if (name.equals("nine-patch")) {
743            drawable = new NinePatchDrawable();
744        } else {
745            throw new XmlPullParserException(parser.getPositionDescription() +
746                    ": invalid drawable tag " + name);
747        }
748
749        drawable.inflate(r, parser, attrs);
750        return drawable;
751    }
752
753
754    /**
755     * Create a drawable from file path name.
756     */
757    public static Drawable createFromPath(String pathName) {
758        if (pathName == null) {
759            return null;
760        }
761
762        Bitmap bm = BitmapFactory.decodeFile(pathName);
763        if (bm != null) {
764            return drawableFromBitmap(null, bm, null, null, pathName);
765        }
766
767        return null;
768    }
769
770    public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs)
771            throws XmlPullParserException, IOException {
772
773        TypedArray a = r.obtainAttributes(attrs, com.android.internal.R.styleable.Drawable);
774        inflateWithAttributes(r, parser, a, com.android.internal.R.styleable.Drawable_visible);
775        a.recycle();
776    }
777
778    void inflateWithAttributes(Resources r, XmlPullParser parser,
779            TypedArray attrs, int visibleAttr)
780            throws XmlPullParserException, IOException {
781
782        mVisible = attrs.getBoolean(visibleAttr, mVisible);
783    }
784
785    public static abstract class ConstantState {
786        public abstract Drawable newDrawable();
787        public abstract int getChangingConfigurations();
788    }
789
790    public ConstantState getConstantState() {
791        return null;
792    }
793
794    private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np,
795            Rect pad, String srcName) {
796
797        if (np != null) {
798            return new NinePatchDrawable(bm, np, pad, srcName);
799        }
800
801        final BitmapDrawable drawable = new BitmapDrawable(bm);
802        if (res != null) {
803            drawable.setDensityScale(res.getDisplayMetrics());
804        }
805
806        return drawable;
807    }
808}
809
810