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