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