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