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