View.java revision 7fdf367d7ad63c90c13ddf553d05f58030454191
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.view; 18 19import android.content.ClipData; 20import android.content.Context; 21import android.content.res.Configuration; 22import android.content.res.Resources; 23import android.content.res.TypedArray; 24import android.graphics.Bitmap; 25import android.graphics.Camera; 26import android.graphics.Canvas; 27import android.graphics.Insets; 28import android.graphics.Interpolator; 29import android.graphics.LinearGradient; 30import android.graphics.Matrix; 31import android.graphics.Paint; 32import android.graphics.PixelFormat; 33import android.graphics.Point; 34import android.graphics.PorterDuff; 35import android.graphics.PorterDuffXfermode; 36import android.graphics.Rect; 37import android.graphics.RectF; 38import android.graphics.Region; 39import android.graphics.Shader; 40import android.graphics.drawable.ColorDrawable; 41import android.graphics.drawable.Drawable; 42import android.hardware.display.DisplayManagerGlobal; 43import android.os.Bundle; 44import android.os.Handler; 45import android.os.IBinder; 46import android.os.Parcel; 47import android.os.Parcelable; 48import android.os.RemoteException; 49import android.os.SystemClock; 50import android.os.SystemProperties; 51import android.text.TextUtils; 52import android.util.AttributeSet; 53import android.util.FloatProperty; 54import android.util.Log; 55import android.util.Pool; 56import android.util.Poolable; 57import android.util.PoolableManager; 58import android.util.Pools; 59import android.util.Property; 60import android.util.SparseArray; 61import android.util.TypedValue; 62import android.view.ContextMenu.ContextMenuInfo; 63import android.view.AccessibilityIterators.TextSegmentIterator; 64import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 65import android.view.AccessibilityIterators.WordTextSegmentIterator; 66import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 67import android.view.accessibility.AccessibilityEvent; 68import android.view.accessibility.AccessibilityEventSource; 69import android.view.accessibility.AccessibilityManager; 70import android.view.accessibility.AccessibilityNodeInfo; 71import android.view.accessibility.AccessibilityNodeProvider; 72import android.view.animation.Animation; 73import android.view.animation.AnimationUtils; 74import android.view.animation.Transformation; 75import android.view.inputmethod.EditorInfo; 76import android.view.inputmethod.InputConnection; 77import android.view.inputmethod.InputMethodManager; 78import android.widget.ScrollBarDrawable; 79 80import static android.os.Build.VERSION_CODES.*; 81import static java.lang.Math.max; 82 83import com.android.internal.R; 84import com.android.internal.util.Predicate; 85import com.android.internal.view.menu.MenuBuilder; 86import com.google.android.collect.Lists; 87import com.google.android.collect.Maps; 88 89import java.lang.ref.WeakReference; 90import java.lang.reflect.Field; 91import java.lang.reflect.InvocationTargetException; 92import java.lang.reflect.Method; 93import java.lang.reflect.Modifier; 94import java.util.ArrayList; 95import java.util.Arrays; 96import java.util.Collections; 97import java.util.HashMap; 98import java.util.Locale; 99import java.util.concurrent.CopyOnWriteArrayList; 100import java.util.concurrent.atomic.AtomicInteger; 101 102/** 103 * <p> 104 * This class represents the basic building block for user interface components. A View 105 * occupies a rectangular area on the screen and is responsible for drawing and 106 * event handling. View is the base class for <em>widgets</em>, which are 107 * used to create interactive UI components (buttons, text fields, etc.). The 108 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 109 * are invisible containers that hold other Views (or other ViewGroups) and define 110 * their layout properties. 111 * </p> 112 * 113 * <div class="special reference"> 114 * <h3>Developer Guides</h3> 115 * <p>For information about using this class to develop your application's user interface, 116 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 117 * </div> 118 * 119 * <a name="Using"></a> 120 * <h3>Using Views</h3> 121 * <p> 122 * All of the views in a window are arranged in a single tree. You can add views 123 * either from code or by specifying a tree of views in one or more XML layout 124 * files. There are many specialized subclasses of views that act as controls or 125 * are capable of displaying text, images, or other content. 126 * </p> 127 * <p> 128 * Once you have created a tree of views, there are typically a few types of 129 * common operations you may wish to perform: 130 * <ul> 131 * <li><strong>Set properties:</strong> for example setting the text of a 132 * {@link android.widget.TextView}. The available properties and the methods 133 * that set them will vary among the different subclasses of views. Note that 134 * properties that are known at build time can be set in the XML layout 135 * files.</li> 136 * <li><strong>Set focus:</strong> The framework will handled moving focus in 137 * response to user input. To force focus to a specific view, call 138 * {@link #requestFocus}.</li> 139 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 140 * that will be notified when something interesting happens to the view. For 141 * example, all views will let you set a listener to be notified when the view 142 * gains or loses focus. You can register such a listener using 143 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 144 * Other view subclasses offer more specialized listeners. For example, a Button 145 * exposes a listener to notify clients when the button is clicked.</li> 146 * <li><strong>Set visibility:</strong> You can hide or show views using 147 * {@link #setVisibility(int)}.</li> 148 * </ul> 149 * </p> 150 * <p><em> 151 * Note: The Android framework is responsible for measuring, laying out and 152 * drawing views. You should not call methods that perform these actions on 153 * views yourself unless you are actually implementing a 154 * {@link android.view.ViewGroup}. 155 * </em></p> 156 * 157 * <a name="Lifecycle"></a> 158 * <h3>Implementing a Custom View</h3> 159 * 160 * <p> 161 * To implement a custom view, you will usually begin by providing overrides for 162 * some of the standard methods that the framework calls on all views. You do 163 * not need to override all of these methods. In fact, you can start by just 164 * overriding {@link #onDraw(android.graphics.Canvas)}. 165 * <table border="2" width="85%" align="center" cellpadding="5"> 166 * <thead> 167 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 168 * </thead> 169 * 170 * <tbody> 171 * <tr> 172 * <td rowspan="2">Creation</td> 173 * <td>Constructors</td> 174 * <td>There is a form of the constructor that are called when the view 175 * is created from code and a form that is called when the view is 176 * inflated from a layout file. The second form should parse and apply 177 * any attributes defined in the layout file. 178 * </td> 179 * </tr> 180 * <tr> 181 * <td><code>{@link #onFinishInflate()}</code></td> 182 * <td>Called after a view and all of its children has been inflated 183 * from XML.</td> 184 * </tr> 185 * 186 * <tr> 187 * <td rowspan="3">Layout</td> 188 * <td><code>{@link #onMeasure(int, int)}</code></td> 189 * <td>Called to determine the size requirements for this view and all 190 * of its children. 191 * </td> 192 * </tr> 193 * <tr> 194 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 195 * <td>Called when this view should assign a size and position to all 196 * of its children. 197 * </td> 198 * </tr> 199 * <tr> 200 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 201 * <td>Called when the size of this view has changed. 202 * </td> 203 * </tr> 204 * 205 * <tr> 206 * <td>Drawing</td> 207 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 208 * <td>Called when the view should render its content. 209 * </td> 210 * </tr> 211 * 212 * <tr> 213 * <td rowspan="4">Event processing</td> 214 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 215 * <td>Called when a new hardware key event occurs. 216 * </td> 217 * </tr> 218 * <tr> 219 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 220 * <td>Called when a hardware key up event occurs. 221 * </td> 222 * </tr> 223 * <tr> 224 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 225 * <td>Called when a trackball motion event occurs. 226 * </td> 227 * </tr> 228 * <tr> 229 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 230 * <td>Called when a touch screen motion event occurs. 231 * </td> 232 * </tr> 233 * 234 * <tr> 235 * <td rowspan="2">Focus</td> 236 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 237 * <td>Called when the view gains or loses focus. 238 * </td> 239 * </tr> 240 * 241 * <tr> 242 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 243 * <td>Called when the window containing the view gains or loses focus. 244 * </td> 245 * </tr> 246 * 247 * <tr> 248 * <td rowspan="3">Attaching</td> 249 * <td><code>{@link #onAttachedToWindow()}</code></td> 250 * <td>Called when the view is attached to a window. 251 * </td> 252 * </tr> 253 * 254 * <tr> 255 * <td><code>{@link #onDetachedFromWindow}</code></td> 256 * <td>Called when the view is detached from its window. 257 * </td> 258 * </tr> 259 * 260 * <tr> 261 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 262 * <td>Called when the visibility of the window containing the view 263 * has changed. 264 * </td> 265 * </tr> 266 * </tbody> 267 * 268 * </table> 269 * </p> 270 * 271 * <a name="IDs"></a> 272 * <h3>IDs</h3> 273 * Views may have an integer id associated with them. These ids are typically 274 * assigned in the layout XML files, and are used to find specific views within 275 * the view tree. A common pattern is to: 276 * <ul> 277 * <li>Define a Button in the layout file and assign it a unique ID. 278 * <pre> 279 * <Button 280 * android:id="@+id/my_button" 281 * android:layout_width="wrap_content" 282 * android:layout_height="wrap_content" 283 * android:text="@string/my_button_text"/> 284 * </pre></li> 285 * <li>From the onCreate method of an Activity, find the Button 286 * <pre class="prettyprint"> 287 * Button myButton = (Button) findViewById(R.id.my_button); 288 * </pre></li> 289 * </ul> 290 * <p> 291 * View IDs need not be unique throughout the tree, but it is good practice to 292 * ensure that they are at least unique within the part of the tree you are 293 * searching. 294 * </p> 295 * 296 * <a name="Position"></a> 297 * <h3>Position</h3> 298 * <p> 299 * The geometry of a view is that of a rectangle. A view has a location, 300 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 301 * two dimensions, expressed as a width and a height. The unit for location 302 * and dimensions is the pixel. 303 * </p> 304 * 305 * <p> 306 * It is possible to retrieve the location of a view by invoking the methods 307 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 308 * coordinate of the rectangle representing the view. The latter returns the 309 * top, or Y, coordinate of the rectangle representing the view. These methods 310 * both return the location of the view relative to its parent. For instance, 311 * when getLeft() returns 20, that means the view is located 20 pixels to the 312 * right of the left edge of its direct parent. 313 * </p> 314 * 315 * <p> 316 * In addition, several convenience methods are offered to avoid unnecessary 317 * computations, namely {@link #getRight()} and {@link #getBottom()}. 318 * These methods return the coordinates of the right and bottom edges of the 319 * rectangle representing the view. For instance, calling {@link #getRight()} 320 * is similar to the following computation: <code>getLeft() + getWidth()</code> 321 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 322 * </p> 323 * 324 * <a name="SizePaddingMargins"></a> 325 * <h3>Size, padding and margins</h3> 326 * <p> 327 * The size of a view is expressed with a width and a height. A view actually 328 * possess two pairs of width and height values. 329 * </p> 330 * 331 * <p> 332 * The first pair is known as <em>measured width</em> and 333 * <em>measured height</em>. These dimensions define how big a view wants to be 334 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 335 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 336 * and {@link #getMeasuredHeight()}. 337 * </p> 338 * 339 * <p> 340 * The second pair is simply known as <em>width</em> and <em>height</em>, or 341 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 342 * dimensions define the actual size of the view on screen, at drawing time and 343 * after layout. These values may, but do not have to, be different from the 344 * measured width and height. The width and height can be obtained by calling 345 * {@link #getWidth()} and {@link #getHeight()}. 346 * </p> 347 * 348 * <p> 349 * To measure its dimensions, a view takes into account its padding. The padding 350 * is expressed in pixels for the left, top, right and bottom parts of the view. 351 * Padding can be used to offset the content of the view by a specific amount of 352 * pixels. For instance, a left padding of 2 will push the view's content by 353 * 2 pixels to the right of the left edge. Padding can be set using the 354 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 355 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 356 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 357 * {@link #getPaddingEnd()}. 358 * </p> 359 * 360 * <p> 361 * Even though a view can define a padding, it does not provide any support for 362 * margins. However, view groups provide such a support. Refer to 363 * {@link android.view.ViewGroup} and 364 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 365 * </p> 366 * 367 * <a name="Layout"></a> 368 * <h3>Layout</h3> 369 * <p> 370 * Layout is a two pass process: a measure pass and a layout pass. The measuring 371 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 372 * of the view tree. Each view pushes dimension specifications down the tree 373 * during the recursion. At the end of the measure pass, every view has stored 374 * its measurements. The second pass happens in 375 * {@link #layout(int,int,int,int)} and is also top-down. During 376 * this pass each parent is responsible for positioning all of its children 377 * using the sizes computed in the measure pass. 378 * </p> 379 * 380 * <p> 381 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 382 * {@link #getMeasuredHeight()} values must be set, along with those for all of 383 * that view's descendants. A view's measured width and measured height values 384 * must respect the constraints imposed by the view's parents. This guarantees 385 * that at the end of the measure pass, all parents accept all of their 386 * children's measurements. A parent view may call measure() more than once on 387 * its children. For example, the parent may measure each child once with 388 * unspecified dimensions to find out how big they want to be, then call 389 * measure() on them again with actual numbers if the sum of all the children's 390 * unconstrained sizes is too big or too small. 391 * </p> 392 * 393 * <p> 394 * The measure pass uses two classes to communicate dimensions. The 395 * {@link MeasureSpec} class is used by views to tell their parents how they 396 * want to be measured and positioned. The base LayoutParams class just 397 * describes how big the view wants to be for both width and height. For each 398 * dimension, it can specify one of: 399 * <ul> 400 * <li> an exact number 401 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 402 * (minus padding) 403 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 404 * enclose its content (plus padding). 405 * </ul> 406 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 407 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 408 * an X and Y value. 409 * </p> 410 * 411 * <p> 412 * MeasureSpecs are used to push requirements down the tree from parent to 413 * child. A MeasureSpec can be in one of three modes: 414 * <ul> 415 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 416 * of a child view. For example, a LinearLayout may call measure() on its child 417 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 418 * tall the child view wants to be given a width of 240 pixels. 419 * <li>EXACTLY: This is used by the parent to impose an exact size on the 420 * child. The child must use this size, and guarantee that all of its 421 * descendants will fit within this size. 422 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 423 * child. The child must gurantee that it and all of its descendants will fit 424 * within this size. 425 * </ul> 426 * </p> 427 * 428 * <p> 429 * To intiate a layout, call {@link #requestLayout}. This method is typically 430 * called by a view on itself when it believes that is can no longer fit within 431 * its current bounds. 432 * </p> 433 * 434 * <a name="Drawing"></a> 435 * <h3>Drawing</h3> 436 * <p> 437 * Drawing is handled by walking the tree and rendering each view that 438 * intersects the invalid region. Because the tree is traversed in-order, 439 * this means that parents will draw before (i.e., behind) their children, with 440 * siblings drawn in the order they appear in the tree. 441 * If you set a background drawable for a View, then the View will draw it for you 442 * before calling back to its <code>onDraw()</code> method. 443 * </p> 444 * 445 * <p> 446 * Note that the framework will not draw views that are not in the invalid region. 447 * </p> 448 * 449 * <p> 450 * To force a view to draw, call {@link #invalidate()}. 451 * </p> 452 * 453 * <a name="EventHandlingThreading"></a> 454 * <h3>Event Handling and Threading</h3> 455 * <p> 456 * The basic cycle of a view is as follows: 457 * <ol> 458 * <li>An event comes in and is dispatched to the appropriate view. The view 459 * handles the event and notifies any listeners.</li> 460 * <li>If in the course of processing the event, the view's bounds may need 461 * to be changed, the view will call {@link #requestLayout()}.</li> 462 * <li>Similarly, if in the course of processing the event the view's appearance 463 * may need to be changed, the view will call {@link #invalidate()}.</li> 464 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 465 * the framework will take care of measuring, laying out, and drawing the tree 466 * as appropriate.</li> 467 * </ol> 468 * </p> 469 * 470 * <p><em>Note: The entire view tree is single threaded. You must always be on 471 * the UI thread when calling any method on any view.</em> 472 * If you are doing work on other threads and want to update the state of a view 473 * from that thread, you should use a {@link Handler}. 474 * </p> 475 * 476 * <a name="FocusHandling"></a> 477 * <h3>Focus Handling</h3> 478 * <p> 479 * The framework will handle routine focus movement in response to user input. 480 * This includes changing the focus as views are removed or hidden, or as new 481 * views become available. Views indicate their willingness to take focus 482 * through the {@link #isFocusable} method. To change whether a view can take 483 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 484 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 485 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 486 * </p> 487 * <p> 488 * Focus movement is based on an algorithm which finds the nearest neighbor in a 489 * given direction. In rare cases, the default algorithm may not match the 490 * intended behavior of the developer. In these situations, you can provide 491 * explicit overrides by using these XML attributes in the layout file: 492 * <pre> 493 * nextFocusDown 494 * nextFocusLeft 495 * nextFocusRight 496 * nextFocusUp 497 * </pre> 498 * </p> 499 * 500 * 501 * <p> 502 * To get a particular view to take focus, call {@link #requestFocus()}. 503 * </p> 504 * 505 * <a name="TouchMode"></a> 506 * <h3>Touch Mode</h3> 507 * <p> 508 * When a user is navigating a user interface via directional keys such as a D-pad, it is 509 * necessary to give focus to actionable items such as buttons so the user can see 510 * what will take input. If the device has touch capabilities, however, and the user 511 * begins interacting with the interface by touching it, it is no longer necessary to 512 * always highlight, or give focus to, a particular view. This motivates a mode 513 * for interaction named 'touch mode'. 514 * </p> 515 * <p> 516 * For a touch capable device, once the user touches the screen, the device 517 * will enter touch mode. From this point onward, only views for which 518 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 519 * Other views that are touchable, like buttons, will not take focus when touched; they will 520 * only fire the on click listeners. 521 * </p> 522 * <p> 523 * Any time a user hits a directional key, such as a D-pad direction, the view device will 524 * exit touch mode, and find a view to take focus, so that the user may resume interacting 525 * with the user interface without touching the screen again. 526 * </p> 527 * <p> 528 * The touch mode state is maintained across {@link android.app.Activity}s. Call 529 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 530 * </p> 531 * 532 * <a name="Scrolling"></a> 533 * <h3>Scrolling</h3> 534 * <p> 535 * The framework provides basic support for views that wish to internally 536 * scroll their content. This includes keeping track of the X and Y scroll 537 * offset as well as mechanisms for drawing scrollbars. See 538 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 539 * {@link #awakenScrollBars()} for more details. 540 * </p> 541 * 542 * <a name="Tags"></a> 543 * <h3>Tags</h3> 544 * <p> 545 * Unlike IDs, tags are not used to identify views. Tags are essentially an 546 * extra piece of information that can be associated with a view. They are most 547 * often used as a convenience to store data related to views in the views 548 * themselves rather than by putting them in a separate structure. 549 * </p> 550 * 551 * <a name="Properties"></a> 552 * <h3>Properties</h3> 553 * <p> 554 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 555 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 556 * available both in the {@link Property} form as well as in similarly-named setter/getter 557 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 558 * be used to set persistent state associated with these rendering-related properties on the view. 559 * The properties and methods can also be used in conjunction with 560 * {@link android.animation.Animator Animator}-based animations, described more in the 561 * <a href="#Animation">Animation</a> section. 562 * </p> 563 * 564 * <a name="Animation"></a> 565 * <h3>Animation</h3> 566 * <p> 567 * Starting with Android 3.0, the preferred way of animating views is to use the 568 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 569 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 570 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 571 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 572 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 573 * makes animating these View properties particularly easy and efficient. 574 * </p> 575 * <p> 576 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 577 * You can attach an {@link Animation} object to a view using 578 * {@link #setAnimation(Animation)} or 579 * {@link #startAnimation(Animation)}. The animation can alter the scale, 580 * rotation, translation and alpha of a view over time. If the animation is 581 * attached to a view that has children, the animation will affect the entire 582 * subtree rooted by that node. When an animation is started, the framework will 583 * take care of redrawing the appropriate views until the animation completes. 584 * </p> 585 * 586 * <a name="Security"></a> 587 * <h3>Security</h3> 588 * <p> 589 * Sometimes it is essential that an application be able to verify that an action 590 * is being performed with the full knowledge and consent of the user, such as 591 * granting a permission request, making a purchase or clicking on an advertisement. 592 * Unfortunately, a malicious application could try to spoof the user into 593 * performing these actions, unaware, by concealing the intended purpose of the view. 594 * As a remedy, the framework offers a touch filtering mechanism that can be used to 595 * improve the security of views that provide access to sensitive functionality. 596 * </p><p> 597 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 598 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 599 * will discard touches that are received whenever the view's window is obscured by 600 * another visible window. As a result, the view will not receive touches whenever a 601 * toast, dialog or other window appears above the view's window. 602 * </p><p> 603 * For more fine-grained control over security, consider overriding the 604 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 605 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 606 * </p> 607 * 608 * @attr ref android.R.styleable#View_alpha 609 * @attr ref android.R.styleable#View_background 610 * @attr ref android.R.styleable#View_clickable 611 * @attr ref android.R.styleable#View_contentDescription 612 * @attr ref android.R.styleable#View_drawingCacheQuality 613 * @attr ref android.R.styleable#View_duplicateParentState 614 * @attr ref android.R.styleable#View_id 615 * @attr ref android.R.styleable#View_requiresFadingEdge 616 * @attr ref android.R.styleable#View_fadeScrollbars 617 * @attr ref android.R.styleable#View_fadingEdgeLength 618 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 619 * @attr ref android.R.styleable#View_fitsSystemWindows 620 * @attr ref android.R.styleable#View_isScrollContainer 621 * @attr ref android.R.styleable#View_focusable 622 * @attr ref android.R.styleable#View_focusableInTouchMode 623 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 624 * @attr ref android.R.styleable#View_keepScreenOn 625 * @attr ref android.R.styleable#View_layerType 626 * @attr ref android.R.styleable#View_longClickable 627 * @attr ref android.R.styleable#View_minHeight 628 * @attr ref android.R.styleable#View_minWidth 629 * @attr ref android.R.styleable#View_nextFocusDown 630 * @attr ref android.R.styleable#View_nextFocusLeft 631 * @attr ref android.R.styleable#View_nextFocusRight 632 * @attr ref android.R.styleable#View_nextFocusUp 633 * @attr ref android.R.styleable#View_onClick 634 * @attr ref android.R.styleable#View_padding 635 * @attr ref android.R.styleable#View_paddingBottom 636 * @attr ref android.R.styleable#View_paddingLeft 637 * @attr ref android.R.styleable#View_paddingRight 638 * @attr ref android.R.styleable#View_paddingTop 639 * @attr ref android.R.styleable#View_paddingStart 640 * @attr ref android.R.styleable#View_paddingEnd 641 * @attr ref android.R.styleable#View_saveEnabled 642 * @attr ref android.R.styleable#View_rotation 643 * @attr ref android.R.styleable#View_rotationX 644 * @attr ref android.R.styleable#View_rotationY 645 * @attr ref android.R.styleable#View_scaleX 646 * @attr ref android.R.styleable#View_scaleY 647 * @attr ref android.R.styleable#View_scrollX 648 * @attr ref android.R.styleable#View_scrollY 649 * @attr ref android.R.styleable#View_scrollbarSize 650 * @attr ref android.R.styleable#View_scrollbarStyle 651 * @attr ref android.R.styleable#View_scrollbars 652 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 653 * @attr ref android.R.styleable#View_scrollbarFadeDuration 654 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 655 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 656 * @attr ref android.R.styleable#View_scrollbarThumbVertical 657 * @attr ref android.R.styleable#View_scrollbarTrackVertical 658 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 660 * @attr ref android.R.styleable#View_soundEffectsEnabled 661 * @attr ref android.R.styleable#View_tag 662 * @attr ref android.R.styleable#View_textAlignment 663 * @attr ref android.R.styleable#View_transformPivotX 664 * @attr ref android.R.styleable#View_transformPivotY 665 * @attr ref android.R.styleable#View_translationX 666 * @attr ref android.R.styleable#View_translationY 667 * @attr ref android.R.styleable#View_visibility 668 * 669 * @see android.view.ViewGroup 670 */ 671public class View implements Drawable.Callback, KeyEvent.Callback, 672 AccessibilityEventSource { 673 private static final boolean DBG = false; 674 675 /** 676 * The logging tag used by this class with android.util.Log. 677 */ 678 protected static final String VIEW_LOG_TAG = "View"; 679 680 /** 681 * When set to true, apps will draw debugging information about their layouts. 682 * 683 * @hide 684 */ 685 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 686 687 /** 688 * Used to mark a View that has no ID. 689 */ 690 public static final int NO_ID = -1; 691 692 /** 693 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 694 * calling setFlags. 695 */ 696 private static final int NOT_FOCUSABLE = 0x00000000; 697 698 /** 699 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 700 * setFlags. 701 */ 702 private static final int FOCUSABLE = 0x00000001; 703 704 /** 705 * Mask for use with setFlags indicating bits used for focus. 706 */ 707 private static final int FOCUSABLE_MASK = 0x00000001; 708 709 /** 710 * This view will adjust its padding to fit sytem windows (e.g. status bar) 711 */ 712 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 713 714 /** 715 * This view is visible. 716 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 717 * android:visibility}. 718 */ 719 public static final int VISIBLE = 0x00000000; 720 721 /** 722 * This view is invisible, but it still takes up space for layout purposes. 723 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 724 * android:visibility}. 725 */ 726 public static final int INVISIBLE = 0x00000004; 727 728 /** 729 * This view is invisible, and it doesn't take any space for layout 730 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 731 * android:visibility}. 732 */ 733 public static final int GONE = 0x00000008; 734 735 /** 736 * Mask for use with setFlags indicating bits used for visibility. 737 * {@hide} 738 */ 739 static final int VISIBILITY_MASK = 0x0000000C; 740 741 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 742 743 /** 744 * This view is enabled. Interpretation varies by subclass. 745 * Use with ENABLED_MASK when calling setFlags. 746 * {@hide} 747 */ 748 static final int ENABLED = 0x00000000; 749 750 /** 751 * This view is disabled. Interpretation varies by subclass. 752 * Use with ENABLED_MASK when calling setFlags. 753 * {@hide} 754 */ 755 static final int DISABLED = 0x00000020; 756 757 /** 758 * Mask for use with setFlags indicating bits used for indicating whether 759 * this view is enabled 760 * {@hide} 761 */ 762 static final int ENABLED_MASK = 0x00000020; 763 764 /** 765 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 766 * called and further optimizations will be performed. It is okay to have 767 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 768 * {@hide} 769 */ 770 static final int WILL_NOT_DRAW = 0x00000080; 771 772 /** 773 * Mask for use with setFlags indicating bits used for indicating whether 774 * this view is will draw 775 * {@hide} 776 */ 777 static final int DRAW_MASK = 0x00000080; 778 779 /** 780 * <p>This view doesn't show scrollbars.</p> 781 * {@hide} 782 */ 783 static final int SCROLLBARS_NONE = 0x00000000; 784 785 /** 786 * <p>This view shows horizontal scrollbars.</p> 787 * {@hide} 788 */ 789 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 790 791 /** 792 * <p>This view shows vertical scrollbars.</p> 793 * {@hide} 794 */ 795 static final int SCROLLBARS_VERTICAL = 0x00000200; 796 797 /** 798 * <p>Mask for use with setFlags indicating bits used for indicating which 799 * scrollbars are enabled.</p> 800 * {@hide} 801 */ 802 static final int SCROLLBARS_MASK = 0x00000300; 803 804 /** 805 * Indicates that the view should filter touches when its window is obscured. 806 * Refer to the class comments for more information about this security feature. 807 * {@hide} 808 */ 809 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 810 811 /** 812 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 813 * that they are optional and should be skipped if the window has 814 * requested system UI flags that ignore those insets for layout. 815 */ 816 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 817 818 /** 819 * <p>This view doesn't show fading edges.</p> 820 * {@hide} 821 */ 822 static final int FADING_EDGE_NONE = 0x00000000; 823 824 /** 825 * <p>This view shows horizontal fading edges.</p> 826 * {@hide} 827 */ 828 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 829 830 /** 831 * <p>This view shows vertical fading edges.</p> 832 * {@hide} 833 */ 834 static final int FADING_EDGE_VERTICAL = 0x00002000; 835 836 /** 837 * <p>Mask for use with setFlags indicating bits used for indicating which 838 * fading edges are enabled.</p> 839 * {@hide} 840 */ 841 static final int FADING_EDGE_MASK = 0x00003000; 842 843 /** 844 * <p>Indicates this view can be clicked. When clickable, a View reacts 845 * to clicks by notifying the OnClickListener.<p> 846 * {@hide} 847 */ 848 static final int CLICKABLE = 0x00004000; 849 850 /** 851 * <p>Indicates this view is caching its drawing into a bitmap.</p> 852 * {@hide} 853 */ 854 static final int DRAWING_CACHE_ENABLED = 0x00008000; 855 856 /** 857 * <p>Indicates that no icicle should be saved for this view.<p> 858 * {@hide} 859 */ 860 static final int SAVE_DISABLED = 0x000010000; 861 862 /** 863 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 864 * property.</p> 865 * {@hide} 866 */ 867 static final int SAVE_DISABLED_MASK = 0x000010000; 868 869 /** 870 * <p>Indicates that no drawing cache should ever be created for this view.<p> 871 * {@hide} 872 */ 873 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 874 875 /** 876 * <p>Indicates this view can take / keep focus when int touch mode.</p> 877 * {@hide} 878 */ 879 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 880 881 /** 882 * <p>Enables low quality mode for the drawing cache.</p> 883 */ 884 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 885 886 /** 887 * <p>Enables high quality mode for the drawing cache.</p> 888 */ 889 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 890 891 /** 892 * <p>Enables automatic quality mode for the drawing cache.</p> 893 */ 894 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 895 896 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 897 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 898 }; 899 900 /** 901 * <p>Mask for use with setFlags indicating bits used for the cache 902 * quality property.</p> 903 * {@hide} 904 */ 905 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 906 907 /** 908 * <p> 909 * Indicates this view can be long clicked. When long clickable, a View 910 * reacts to long clicks by notifying the OnLongClickListener or showing a 911 * context menu. 912 * </p> 913 * {@hide} 914 */ 915 static final int LONG_CLICKABLE = 0x00200000; 916 917 /** 918 * <p>Indicates that this view gets its drawable states from its direct parent 919 * and ignores its original internal states.</p> 920 * 921 * @hide 922 */ 923 static final int DUPLICATE_PARENT_STATE = 0x00400000; 924 925 /** 926 * The scrollbar style to display the scrollbars inside the content area, 927 * without increasing the padding. The scrollbars will be overlaid with 928 * translucency on the view's content. 929 */ 930 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 931 932 /** 933 * The scrollbar style to display the scrollbars inside the padded area, 934 * increasing the padding of the view. The scrollbars will not overlap the 935 * content area of the view. 936 */ 937 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 938 939 /** 940 * The scrollbar style to display the scrollbars at the edge of the view, 941 * without increasing the padding. The scrollbars will be overlaid with 942 * translucency. 943 */ 944 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 945 946 /** 947 * The scrollbar style to display the scrollbars at the edge of the view, 948 * increasing the padding of the view. The scrollbars will only overlap the 949 * background, if any. 950 */ 951 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 952 953 /** 954 * Mask to check if the scrollbar style is overlay or inset. 955 * {@hide} 956 */ 957 static final int SCROLLBARS_INSET_MASK = 0x01000000; 958 959 /** 960 * Mask to check if the scrollbar style is inside or outside. 961 * {@hide} 962 */ 963 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 964 965 /** 966 * Mask for scrollbar style. 967 * {@hide} 968 */ 969 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 970 971 /** 972 * View flag indicating that the screen should remain on while the 973 * window containing this view is visible to the user. This effectively 974 * takes care of automatically setting the WindowManager's 975 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 976 */ 977 public static final int KEEP_SCREEN_ON = 0x04000000; 978 979 /** 980 * View flag indicating whether this view should have sound effects enabled 981 * for events such as clicking and touching. 982 */ 983 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 984 985 /** 986 * View flag indicating whether this view should have haptic feedback 987 * enabled for events such as long presses. 988 */ 989 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 990 991 /** 992 * <p>Indicates that the view hierarchy should stop saving state when 993 * it reaches this view. If state saving is initiated immediately at 994 * the view, it will be allowed. 995 * {@hide} 996 */ 997 static final int PARENT_SAVE_DISABLED = 0x20000000; 998 999 /** 1000 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1001 * {@hide} 1002 */ 1003 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1004 1005 /** 1006 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1007 * should add all focusable Views regardless if they are focusable in touch mode. 1008 */ 1009 public static final int FOCUSABLES_ALL = 0x00000000; 1010 1011 /** 1012 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1013 * should add only Views focusable in touch mode. 1014 */ 1015 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1016 1017 /** 1018 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1019 * item. 1020 */ 1021 public static final int FOCUS_BACKWARD = 0x00000001; 1022 1023 /** 1024 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1025 * item. 1026 */ 1027 public static final int FOCUS_FORWARD = 0x00000002; 1028 1029 /** 1030 * Use with {@link #focusSearch(int)}. Move focus to the left. 1031 */ 1032 public static final int FOCUS_LEFT = 0x00000011; 1033 1034 /** 1035 * Use with {@link #focusSearch(int)}. Move focus up. 1036 */ 1037 public static final int FOCUS_UP = 0x00000021; 1038 1039 /** 1040 * Use with {@link #focusSearch(int)}. Move focus to the right. 1041 */ 1042 public static final int FOCUS_RIGHT = 0x00000042; 1043 1044 /** 1045 * Use with {@link #focusSearch(int)}. Move focus down. 1046 */ 1047 public static final int FOCUS_DOWN = 0x00000082; 1048 1049 /** 1050 * Bits of {@link #getMeasuredWidthAndState()} and 1051 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1052 */ 1053 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1054 1055 /** 1056 * Bits of {@link #getMeasuredWidthAndState()} and 1057 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1058 */ 1059 public static final int MEASURED_STATE_MASK = 0xff000000; 1060 1061 /** 1062 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1063 * for functions that combine both width and height into a single int, 1064 * such as {@link #getMeasuredState()} and the childState argument of 1065 * {@link #resolveSizeAndState(int, int, int)}. 1066 */ 1067 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1068 1069 /** 1070 * Bit of {@link #getMeasuredWidthAndState()} and 1071 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1072 * is smaller that the space the view would like to have. 1073 */ 1074 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1075 1076 /** 1077 * Base View state sets 1078 */ 1079 // Singles 1080 /** 1081 * Indicates the view has no states set. States are used with 1082 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1083 * view depending on its state. 1084 * 1085 * @see android.graphics.drawable.Drawable 1086 * @see #getDrawableState() 1087 */ 1088 protected static final int[] EMPTY_STATE_SET; 1089 /** 1090 * Indicates the view is enabled. States are used with 1091 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1092 * view depending on its state. 1093 * 1094 * @see android.graphics.drawable.Drawable 1095 * @see #getDrawableState() 1096 */ 1097 protected static final int[] ENABLED_STATE_SET; 1098 /** 1099 * Indicates the view is focused. States are used with 1100 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1101 * view depending on its state. 1102 * 1103 * @see android.graphics.drawable.Drawable 1104 * @see #getDrawableState() 1105 */ 1106 protected static final int[] FOCUSED_STATE_SET; 1107 /** 1108 * Indicates the view is selected. States are used with 1109 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1110 * view depending on its state. 1111 * 1112 * @see android.graphics.drawable.Drawable 1113 * @see #getDrawableState() 1114 */ 1115 protected static final int[] SELECTED_STATE_SET; 1116 /** 1117 * Indicates the view is pressed. States are used with 1118 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1119 * view depending on its state. 1120 * 1121 * @see android.graphics.drawable.Drawable 1122 * @see #getDrawableState() 1123 * @hide 1124 */ 1125 protected static final int[] PRESSED_STATE_SET; 1126 /** 1127 * Indicates the view's window has focus. States are used with 1128 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1129 * view depending on its state. 1130 * 1131 * @see android.graphics.drawable.Drawable 1132 * @see #getDrawableState() 1133 */ 1134 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1135 // Doubles 1136 /** 1137 * Indicates the view is enabled and has the focus. 1138 * 1139 * @see #ENABLED_STATE_SET 1140 * @see #FOCUSED_STATE_SET 1141 */ 1142 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1143 /** 1144 * Indicates the view is enabled and selected. 1145 * 1146 * @see #ENABLED_STATE_SET 1147 * @see #SELECTED_STATE_SET 1148 */ 1149 protected static final int[] ENABLED_SELECTED_STATE_SET; 1150 /** 1151 * Indicates the view is enabled and that its window has focus. 1152 * 1153 * @see #ENABLED_STATE_SET 1154 * @see #WINDOW_FOCUSED_STATE_SET 1155 */ 1156 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1157 /** 1158 * Indicates the view is focused and selected. 1159 * 1160 * @see #FOCUSED_STATE_SET 1161 * @see #SELECTED_STATE_SET 1162 */ 1163 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1164 /** 1165 * Indicates the view has the focus and that its window has the focus. 1166 * 1167 * @see #FOCUSED_STATE_SET 1168 * @see #WINDOW_FOCUSED_STATE_SET 1169 */ 1170 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1171 /** 1172 * Indicates the view is selected and that its window has the focus. 1173 * 1174 * @see #SELECTED_STATE_SET 1175 * @see #WINDOW_FOCUSED_STATE_SET 1176 */ 1177 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1178 // Triples 1179 /** 1180 * Indicates the view is enabled, focused and selected. 1181 * 1182 * @see #ENABLED_STATE_SET 1183 * @see #FOCUSED_STATE_SET 1184 * @see #SELECTED_STATE_SET 1185 */ 1186 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1187 /** 1188 * Indicates the view is enabled, focused and its window has the focus. 1189 * 1190 * @see #ENABLED_STATE_SET 1191 * @see #FOCUSED_STATE_SET 1192 * @see #WINDOW_FOCUSED_STATE_SET 1193 */ 1194 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1195 /** 1196 * Indicates the view is enabled, selected and its window has the focus. 1197 * 1198 * @see #ENABLED_STATE_SET 1199 * @see #SELECTED_STATE_SET 1200 * @see #WINDOW_FOCUSED_STATE_SET 1201 */ 1202 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1203 /** 1204 * Indicates the view is focused, selected and its window has the focus. 1205 * 1206 * @see #FOCUSED_STATE_SET 1207 * @see #SELECTED_STATE_SET 1208 * @see #WINDOW_FOCUSED_STATE_SET 1209 */ 1210 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1211 /** 1212 * Indicates the view is enabled, focused, selected and its window 1213 * has the focus. 1214 * 1215 * @see #ENABLED_STATE_SET 1216 * @see #FOCUSED_STATE_SET 1217 * @see #SELECTED_STATE_SET 1218 * @see #WINDOW_FOCUSED_STATE_SET 1219 */ 1220 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1221 /** 1222 * Indicates the view is pressed and its window has the focus. 1223 * 1224 * @see #PRESSED_STATE_SET 1225 * @see #WINDOW_FOCUSED_STATE_SET 1226 */ 1227 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1228 /** 1229 * Indicates the view is pressed and selected. 1230 * 1231 * @see #PRESSED_STATE_SET 1232 * @see #SELECTED_STATE_SET 1233 */ 1234 protected static final int[] PRESSED_SELECTED_STATE_SET; 1235 /** 1236 * Indicates the view is pressed, selected and its window has the focus. 1237 * 1238 * @see #PRESSED_STATE_SET 1239 * @see #SELECTED_STATE_SET 1240 * @see #WINDOW_FOCUSED_STATE_SET 1241 */ 1242 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1243 /** 1244 * Indicates the view is pressed and focused. 1245 * 1246 * @see #PRESSED_STATE_SET 1247 * @see #FOCUSED_STATE_SET 1248 */ 1249 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1250 /** 1251 * Indicates the view is pressed, focused and its window has the focus. 1252 * 1253 * @see #PRESSED_STATE_SET 1254 * @see #FOCUSED_STATE_SET 1255 * @see #WINDOW_FOCUSED_STATE_SET 1256 */ 1257 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1258 /** 1259 * Indicates the view is pressed, focused and selected. 1260 * 1261 * @see #PRESSED_STATE_SET 1262 * @see #SELECTED_STATE_SET 1263 * @see #FOCUSED_STATE_SET 1264 */ 1265 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1266 /** 1267 * Indicates the view is pressed, focused, selected and its window has the focus. 1268 * 1269 * @see #PRESSED_STATE_SET 1270 * @see #FOCUSED_STATE_SET 1271 * @see #SELECTED_STATE_SET 1272 * @see #WINDOW_FOCUSED_STATE_SET 1273 */ 1274 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1275 /** 1276 * Indicates the view is pressed and enabled. 1277 * 1278 * @see #PRESSED_STATE_SET 1279 * @see #ENABLED_STATE_SET 1280 */ 1281 protected static final int[] PRESSED_ENABLED_STATE_SET; 1282 /** 1283 * Indicates the view is pressed, enabled and its window has the focus. 1284 * 1285 * @see #PRESSED_STATE_SET 1286 * @see #ENABLED_STATE_SET 1287 * @see #WINDOW_FOCUSED_STATE_SET 1288 */ 1289 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1290 /** 1291 * Indicates the view is pressed, enabled and selected. 1292 * 1293 * @see #PRESSED_STATE_SET 1294 * @see #ENABLED_STATE_SET 1295 * @see #SELECTED_STATE_SET 1296 */ 1297 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1298 /** 1299 * Indicates the view is pressed, enabled, selected and its window has the 1300 * focus. 1301 * 1302 * @see #PRESSED_STATE_SET 1303 * @see #ENABLED_STATE_SET 1304 * @see #SELECTED_STATE_SET 1305 * @see #WINDOW_FOCUSED_STATE_SET 1306 */ 1307 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1308 /** 1309 * Indicates the view is pressed, enabled and focused. 1310 * 1311 * @see #PRESSED_STATE_SET 1312 * @see #ENABLED_STATE_SET 1313 * @see #FOCUSED_STATE_SET 1314 */ 1315 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1316 /** 1317 * Indicates the view is pressed, enabled, focused and its window has the 1318 * focus. 1319 * 1320 * @see #PRESSED_STATE_SET 1321 * @see #ENABLED_STATE_SET 1322 * @see #FOCUSED_STATE_SET 1323 * @see #WINDOW_FOCUSED_STATE_SET 1324 */ 1325 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1326 /** 1327 * Indicates the view is pressed, enabled, focused and selected. 1328 * 1329 * @see #PRESSED_STATE_SET 1330 * @see #ENABLED_STATE_SET 1331 * @see #SELECTED_STATE_SET 1332 * @see #FOCUSED_STATE_SET 1333 */ 1334 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1335 /** 1336 * Indicates the view is pressed, enabled, focused, selected and its window 1337 * has the focus. 1338 * 1339 * @see #PRESSED_STATE_SET 1340 * @see #ENABLED_STATE_SET 1341 * @see #SELECTED_STATE_SET 1342 * @see #FOCUSED_STATE_SET 1343 * @see #WINDOW_FOCUSED_STATE_SET 1344 */ 1345 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1346 1347 /** 1348 * The order here is very important to {@link #getDrawableState()} 1349 */ 1350 private static final int[][] VIEW_STATE_SETS; 1351 1352 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1353 static final int VIEW_STATE_SELECTED = 1 << 1; 1354 static final int VIEW_STATE_FOCUSED = 1 << 2; 1355 static final int VIEW_STATE_ENABLED = 1 << 3; 1356 static final int VIEW_STATE_PRESSED = 1 << 4; 1357 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1358 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1359 static final int VIEW_STATE_HOVERED = 1 << 7; 1360 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1361 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1362 1363 static final int[] VIEW_STATE_IDS = new int[] { 1364 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1365 R.attr.state_selected, VIEW_STATE_SELECTED, 1366 R.attr.state_focused, VIEW_STATE_FOCUSED, 1367 R.attr.state_enabled, VIEW_STATE_ENABLED, 1368 R.attr.state_pressed, VIEW_STATE_PRESSED, 1369 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1370 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1371 R.attr.state_hovered, VIEW_STATE_HOVERED, 1372 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1373 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1374 }; 1375 1376 static { 1377 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1378 throw new IllegalStateException( 1379 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1380 } 1381 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1382 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1383 int viewState = R.styleable.ViewDrawableStates[i]; 1384 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1385 if (VIEW_STATE_IDS[j] == viewState) { 1386 orderedIds[i * 2] = viewState; 1387 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1388 } 1389 } 1390 } 1391 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1392 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1393 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1394 int numBits = Integer.bitCount(i); 1395 int[] set = new int[numBits]; 1396 int pos = 0; 1397 for (int j = 0; j < orderedIds.length; j += 2) { 1398 if ((i & orderedIds[j+1]) != 0) { 1399 set[pos++] = orderedIds[j]; 1400 } 1401 } 1402 VIEW_STATE_SETS[i] = set; 1403 } 1404 1405 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1406 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1407 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1408 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1409 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1410 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1411 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1412 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1413 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1414 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1415 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1416 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1417 | VIEW_STATE_FOCUSED]; 1418 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1419 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1420 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1421 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1422 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1423 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1424 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1425 | VIEW_STATE_ENABLED]; 1426 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1427 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1428 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1429 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1430 | VIEW_STATE_ENABLED]; 1431 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1432 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1433 | VIEW_STATE_ENABLED]; 1434 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1435 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1436 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1437 1438 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1439 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1440 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1441 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1442 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1443 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1444 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1445 | VIEW_STATE_PRESSED]; 1446 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1447 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1448 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1449 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1450 | VIEW_STATE_PRESSED]; 1451 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1452 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1453 | VIEW_STATE_PRESSED]; 1454 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1455 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1456 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1457 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1458 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1459 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1460 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1461 | VIEW_STATE_PRESSED]; 1462 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1463 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1464 | VIEW_STATE_PRESSED]; 1465 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1466 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1467 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1468 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1469 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1470 | VIEW_STATE_PRESSED]; 1471 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1472 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1473 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1474 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1475 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1476 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1477 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1478 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1479 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1480 | VIEW_STATE_PRESSED]; 1481 } 1482 1483 /** 1484 * Accessibility event types that are dispatched for text population. 1485 */ 1486 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1487 AccessibilityEvent.TYPE_VIEW_CLICKED 1488 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1489 | AccessibilityEvent.TYPE_VIEW_SELECTED 1490 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1491 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1492 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1493 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1494 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1495 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1496 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1497 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1498 1499 /** 1500 * Temporary Rect currently for use in setBackground(). This will probably 1501 * be extended in the future to hold our own class with more than just 1502 * a Rect. :) 1503 */ 1504 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1505 1506 /** 1507 * Map used to store views' tags. 1508 */ 1509 private SparseArray<Object> mKeyedTags; 1510 1511 /** 1512 * The next available accessibility id. 1513 */ 1514 private static int sNextAccessibilityViewId; 1515 1516 /** 1517 * The animation currently associated with this view. 1518 * @hide 1519 */ 1520 protected Animation mCurrentAnimation = null; 1521 1522 /** 1523 * Width as measured during measure pass. 1524 * {@hide} 1525 */ 1526 @ViewDebug.ExportedProperty(category = "measurement") 1527 int mMeasuredWidth; 1528 1529 /** 1530 * Height as measured during measure pass. 1531 * {@hide} 1532 */ 1533 @ViewDebug.ExportedProperty(category = "measurement") 1534 int mMeasuredHeight; 1535 1536 /** 1537 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1538 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1539 * its display list. This flag, used only when hw accelerated, allows us to clear the 1540 * flag while retaining this information until it's needed (at getDisplayList() time and 1541 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1542 * 1543 * {@hide} 1544 */ 1545 boolean mRecreateDisplayList = false; 1546 1547 /** 1548 * The view's identifier. 1549 * {@hide} 1550 * 1551 * @see #setId(int) 1552 * @see #getId() 1553 */ 1554 @ViewDebug.ExportedProperty(resolveId = true) 1555 int mID = NO_ID; 1556 1557 /** 1558 * The stable ID of this view for accessibility purposes. 1559 */ 1560 int mAccessibilityViewId = NO_ID; 1561 1562 /** 1563 * @hide 1564 */ 1565 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1566 1567 /** 1568 * The view's tag. 1569 * {@hide} 1570 * 1571 * @see #setTag(Object) 1572 * @see #getTag() 1573 */ 1574 protected Object mTag; 1575 1576 // for mPrivateFlags: 1577 /** {@hide} */ 1578 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1579 /** {@hide} */ 1580 static final int PFLAG_FOCUSED = 0x00000002; 1581 /** {@hide} */ 1582 static final int PFLAG_SELECTED = 0x00000004; 1583 /** {@hide} */ 1584 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1585 /** {@hide} */ 1586 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1587 /** {@hide} */ 1588 static final int PFLAG_DRAWN = 0x00000020; 1589 /** 1590 * When this flag is set, this view is running an animation on behalf of its 1591 * children and should therefore not cancel invalidate requests, even if they 1592 * lie outside of this view's bounds. 1593 * 1594 * {@hide} 1595 */ 1596 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1597 /** {@hide} */ 1598 static final int PFLAG_SKIP_DRAW = 0x00000080; 1599 /** {@hide} */ 1600 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1601 /** {@hide} */ 1602 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1603 /** {@hide} */ 1604 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1605 /** {@hide} */ 1606 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1607 /** {@hide} */ 1608 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1609 /** {@hide} */ 1610 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1611 1612 private static final int PFLAG_PRESSED = 0x00004000; 1613 1614 /** {@hide} */ 1615 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1616 /** 1617 * Flag used to indicate that this view should be drawn once more (and only once 1618 * more) after its animation has completed. 1619 * {@hide} 1620 */ 1621 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1622 1623 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1624 1625 /** 1626 * Indicates that the View returned true when onSetAlpha() was called and that 1627 * the alpha must be restored. 1628 * {@hide} 1629 */ 1630 static final int PFLAG_ALPHA_SET = 0x00040000; 1631 1632 /** 1633 * Set by {@link #setScrollContainer(boolean)}. 1634 */ 1635 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1636 1637 /** 1638 * Set by {@link #setScrollContainer(boolean)}. 1639 */ 1640 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1641 1642 /** 1643 * View flag indicating whether this view was invalidated (fully or partially.) 1644 * 1645 * @hide 1646 */ 1647 static final int PFLAG_DIRTY = 0x00200000; 1648 1649 /** 1650 * View flag indicating whether this view was invalidated by an opaque 1651 * invalidate request. 1652 * 1653 * @hide 1654 */ 1655 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1656 1657 /** 1658 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1659 * 1660 * @hide 1661 */ 1662 static final int PFLAG_DIRTY_MASK = 0x00600000; 1663 1664 /** 1665 * Indicates whether the background is opaque. 1666 * 1667 * @hide 1668 */ 1669 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1670 1671 /** 1672 * Indicates whether the scrollbars are opaque. 1673 * 1674 * @hide 1675 */ 1676 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1677 1678 /** 1679 * Indicates whether the view is opaque. 1680 * 1681 * @hide 1682 */ 1683 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1684 1685 /** 1686 * Indicates a prepressed state; 1687 * the short time between ACTION_DOWN and recognizing 1688 * a 'real' press. Prepressed is used to recognize quick taps 1689 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1690 * 1691 * @hide 1692 */ 1693 private static final int PFLAG_PREPRESSED = 0x02000000; 1694 1695 /** 1696 * Indicates whether the view is temporarily detached. 1697 * 1698 * @hide 1699 */ 1700 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1701 1702 /** 1703 * Indicates that we should awaken scroll bars once attached 1704 * 1705 * @hide 1706 */ 1707 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1708 1709 /** 1710 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1711 * @hide 1712 */ 1713 private static final int PFLAG_HOVERED = 0x10000000; 1714 1715 /** 1716 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1717 * for transform operations 1718 * 1719 * @hide 1720 */ 1721 private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000; 1722 1723 /** {@hide} */ 1724 static final int PFLAG_ACTIVATED = 0x40000000; 1725 1726 /** 1727 * Indicates that this view was specifically invalidated, not just dirtied because some 1728 * child view was invalidated. The flag is used to determine when we need to recreate 1729 * a view's display list (as opposed to just returning a reference to its existing 1730 * display list). 1731 * 1732 * @hide 1733 */ 1734 static final int PFLAG_INVALIDATED = 0x80000000; 1735 1736 /** 1737 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1738 * 1739 * -------|-------|-------|-------| 1740 * PFLAG2_TEXT_ALIGNMENT_FLAGS[0] 1741 * PFLAG2_TEXT_DIRECTION_FLAGS[0] 1742 * 1 PFLAG2_DRAG_CAN_ACCEPT 1743 * 1 PFLAG2_DRAG_HOVERED 1744 * 1 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT 1745 * 11 PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1746 * 1 1 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT 1747 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1748 * 11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 1749 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1750 * 1 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT 1751 * 1 1 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT 1752 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1753 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1754 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1755 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1756 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1757 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1758 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1759 * 111 PFLAG2_TEXT_DIRECTION_MASK 1760 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1761 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1762 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1763 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1764 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1765 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1766 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1767 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1768 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1769 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1770 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1771 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1772 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1773 * 11 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1774 * 1 PFLAG2_HAS_TRANSIENT_STATE 1775 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1776 * 1 PFLAG2_ACCESSIBILITY_STATE_CHANGED 1777 * 1 PFLAG2_VIEW_QUICK_REJECTED 1778 * 1 PFLAG2_PADDING_RESOLVED 1779 * -------|-------|-------|-------| 1780 */ 1781 1782 /** 1783 * Indicates that this view has reported that it can accept the current drag's content. 1784 * Cleared when the drag operation concludes. 1785 * @hide 1786 */ 1787 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1788 1789 /** 1790 * Indicates that this view is currently directly under the drag location in a 1791 * drag-and-drop operation involving content that it can accept. Cleared when 1792 * the drag exits the view, or when the drag operation concludes. 1793 * @hide 1794 */ 1795 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1796 1797 /** 1798 * Horizontal layout direction of this view is from Left to Right. 1799 * Use with {@link #setLayoutDirection}. 1800 */ 1801 public static final int LAYOUT_DIRECTION_LTR = 0; 1802 1803 /** 1804 * Horizontal layout direction of this view is from Right to Left. 1805 * Use with {@link #setLayoutDirection}. 1806 */ 1807 public static final int LAYOUT_DIRECTION_RTL = 1; 1808 1809 /** 1810 * Horizontal layout direction of this view is inherited from its parent. 1811 * Use with {@link #setLayoutDirection}. 1812 */ 1813 public static final int LAYOUT_DIRECTION_INHERIT = 2; 1814 1815 /** 1816 * Horizontal layout direction of this view is from deduced from the default language 1817 * script for the locale. Use with {@link #setLayoutDirection}. 1818 */ 1819 public static final int LAYOUT_DIRECTION_LOCALE = 3; 1820 1821 /** 1822 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1823 * @hide 1824 */ 1825 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1826 1827 /** 1828 * Mask for use with private flags indicating bits used for horizontal layout direction. 1829 * @hide 1830 */ 1831 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1832 1833 /** 1834 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1835 * right-to-left direction. 1836 * @hide 1837 */ 1838 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1839 1840 /** 1841 * Indicates whether the view horizontal layout direction has been resolved. 1842 * @hide 1843 */ 1844 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1845 1846 /** 1847 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1848 * @hide 1849 */ 1850 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1851 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1852 1853 /* 1854 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1855 * flag value. 1856 * @hide 1857 */ 1858 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1859 LAYOUT_DIRECTION_LTR, 1860 LAYOUT_DIRECTION_RTL, 1861 LAYOUT_DIRECTION_INHERIT, 1862 LAYOUT_DIRECTION_LOCALE 1863 }; 1864 1865 /** 1866 * Default horizontal layout direction. 1867 * @hide 1868 */ 1869 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1870 1871 /** 1872 * Indicates that the view is tracking some sort of transient state 1873 * that the app should not need to be aware of, but that the framework 1874 * should take special care to preserve. 1875 * 1876 * @hide 1877 */ 1878 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22; 1879 1880 /** 1881 * Text direction is inherited thru {@link ViewGroup} 1882 */ 1883 public static final int TEXT_DIRECTION_INHERIT = 0; 1884 1885 /** 1886 * Text direction is using "first strong algorithm". The first strong directional character 1887 * determines the paragraph direction. If there is no strong directional character, the 1888 * paragraph direction is the view's resolved layout direction. 1889 */ 1890 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1891 1892 /** 1893 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1894 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1895 * If there are neither, the paragraph direction is the view's resolved layout direction. 1896 */ 1897 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1898 1899 /** 1900 * Text direction is forced to LTR. 1901 */ 1902 public static final int TEXT_DIRECTION_LTR = 3; 1903 1904 /** 1905 * Text direction is forced to RTL. 1906 */ 1907 public static final int TEXT_DIRECTION_RTL = 4; 1908 1909 /** 1910 * Text direction is coming from the system Locale. 1911 */ 1912 public static final int TEXT_DIRECTION_LOCALE = 5; 1913 1914 /** 1915 * Default text direction is inherited 1916 */ 1917 public static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 1918 1919 /** 1920 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 1921 * @hide 1922 */ 1923 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 1924 1925 /** 1926 * Mask for use with private flags indicating bits used for text direction. 1927 * @hide 1928 */ 1929 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 1930 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1931 1932 /** 1933 * Array of text direction flags for mapping attribute "textDirection" to correct 1934 * flag value. 1935 * @hide 1936 */ 1937 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 1938 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1939 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1940 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1941 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1942 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1943 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1944 }; 1945 1946 /** 1947 * Indicates whether the view text direction has been resolved. 1948 * @hide 1949 */ 1950 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 1951 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1952 1953 /** 1954 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1955 * @hide 1956 */ 1957 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 1958 1959 /** 1960 * Mask for use with private flags indicating bits used for resolved text direction. 1961 * @hide 1962 */ 1963 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 1964 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1965 1966 /** 1967 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 1968 * @hide 1969 */ 1970 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 1971 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1972 1973 /* 1974 * Default text alignment. The text alignment of this View is inherited from its parent. 1975 * Use with {@link #setTextAlignment(int)} 1976 */ 1977 public static final int TEXT_ALIGNMENT_INHERIT = 0; 1978 1979 /** 1980 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 1981 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 1982 * 1983 * Use with {@link #setTextAlignment(int)} 1984 */ 1985 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 1986 1987 /** 1988 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 1989 * 1990 * Use with {@link #setTextAlignment(int)} 1991 */ 1992 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 1993 1994 /** 1995 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 1996 * 1997 * Use with {@link #setTextAlignment(int)} 1998 */ 1999 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2000 2001 /** 2002 * Center the paragraph, e.g. ALIGN_CENTER. 2003 * 2004 * Use with {@link #setTextAlignment(int)} 2005 */ 2006 public static final int TEXT_ALIGNMENT_CENTER = 4; 2007 2008 /** 2009 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2010 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2011 * 2012 * Use with {@link #setTextAlignment(int)} 2013 */ 2014 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2015 2016 /** 2017 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2018 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2019 * 2020 * Use with {@link #setTextAlignment(int)} 2021 */ 2022 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2023 2024 /** 2025 * Default text alignment is inherited 2026 */ 2027 public static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2028 2029 /** 2030 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2031 * @hide 2032 */ 2033 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2034 2035 /** 2036 * Mask for use with private flags indicating bits used for text alignment. 2037 * @hide 2038 */ 2039 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2040 2041 /** 2042 * Array of text direction flags for mapping attribute "textAlignment" to correct 2043 * flag value. 2044 * @hide 2045 */ 2046 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2047 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2048 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2049 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2050 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2051 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2052 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2053 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2054 }; 2055 2056 /** 2057 * Indicates whether the view text alignment has been resolved. 2058 * @hide 2059 */ 2060 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2061 2062 /** 2063 * Bit shift to get the resolved text alignment. 2064 * @hide 2065 */ 2066 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2067 2068 /** 2069 * Mask for use with private flags indicating bits used for text alignment. 2070 * @hide 2071 */ 2072 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2073 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2074 2075 /** 2076 * Indicates whether if the view text alignment has been resolved to gravity 2077 */ 2078 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2079 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2080 2081 // Accessiblity constants for mPrivateFlags2 2082 2083 /** 2084 * Shift for the bits in {@link #mPrivateFlags2} related to the 2085 * "importantForAccessibility" attribute. 2086 */ 2087 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2088 2089 /** 2090 * Automatically determine whether a view is important for accessibility. 2091 */ 2092 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2093 2094 /** 2095 * The view is important for accessibility. 2096 */ 2097 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2098 2099 /** 2100 * The view is not important for accessibility. 2101 */ 2102 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2103 2104 /** 2105 * The default whether the view is important for accessibility. 2106 */ 2107 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2108 2109 /** 2110 * Mask for obtainig the bits which specify how to determine 2111 * whether a view is important for accessibility. 2112 */ 2113 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2114 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO) 2115 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2116 2117 /** 2118 * Flag indicating whether a view has accessibility focus. 2119 */ 2120 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x00000040 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2121 2122 /** 2123 * Flag indicating whether a view state for accessibility has changed. 2124 */ 2125 static final int PFLAG2_ACCESSIBILITY_STATE_CHANGED = 0x00000080 2126 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2127 2128 /** 2129 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2130 * is used to check whether later changes to the view's transform should invalidate the 2131 * view to force the quickReject test to run again. 2132 */ 2133 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2134 2135 /** 2136 * Flag indicating that start/end padding has been resolved into left/right padding 2137 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2138 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2139 * during measurement. In some special cases this is required such as when an adapter-based 2140 * view measures prospective children without attaching them to a window. 2141 */ 2142 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2143 2144 // There are a couple of flags left in mPrivateFlags2 2145 2146 /* End of masks for mPrivateFlags2 */ 2147 2148 /* Masks for mPrivateFlags3 */ 2149 2150 /** 2151 * Flag indicating that view has a transform animation set on it. This is used to track whether 2152 * an animation is cleared between successive frames, in order to tell the associated 2153 * DisplayList to clear its animation matrix. 2154 */ 2155 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2156 2157 /** 2158 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2159 * animation is cleared between successive frames, in order to tell the associated 2160 * DisplayList to restore its alpha value. 2161 */ 2162 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2163 2164 2165 /* End of masks for mPrivateFlags3 */ 2166 2167 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2168 2169 /** 2170 * Always allow a user to over-scroll this view, provided it is a 2171 * view that can scroll. 2172 * 2173 * @see #getOverScrollMode() 2174 * @see #setOverScrollMode(int) 2175 */ 2176 public static final int OVER_SCROLL_ALWAYS = 0; 2177 2178 /** 2179 * Allow a user to over-scroll this view only if the content is large 2180 * enough to meaningfully scroll, provided it is a view that can scroll. 2181 * 2182 * @see #getOverScrollMode() 2183 * @see #setOverScrollMode(int) 2184 */ 2185 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2186 2187 /** 2188 * Never allow a user to over-scroll this view. 2189 * 2190 * @see #getOverScrollMode() 2191 * @see #setOverScrollMode(int) 2192 */ 2193 public static final int OVER_SCROLL_NEVER = 2; 2194 2195 /** 2196 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2197 * requested the system UI (status bar) to be visible (the default). 2198 * 2199 * @see #setSystemUiVisibility(int) 2200 */ 2201 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2202 2203 /** 2204 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2205 * system UI to enter an unobtrusive "low profile" mode. 2206 * 2207 * <p>This is for use in games, book readers, video players, or any other 2208 * "immersive" application where the usual system chrome is deemed too distracting. 2209 * 2210 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2211 * 2212 * @see #setSystemUiVisibility(int) 2213 */ 2214 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2215 2216 /** 2217 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2218 * system navigation be temporarily hidden. 2219 * 2220 * <p>This is an even less obtrusive state than that called for by 2221 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2222 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2223 * those to disappear. This is useful (in conjunction with the 2224 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2225 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2226 * window flags) for displaying content using every last pixel on the display. 2227 * 2228 * <p>There is a limitation: because navigation controls are so important, the least user 2229 * interaction will cause them to reappear immediately. When this happens, both 2230 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2231 * so that both elements reappear at the same time. 2232 * 2233 * @see #setSystemUiVisibility(int) 2234 */ 2235 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2236 2237 /** 2238 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2239 * into the normal fullscreen mode so that its content can take over the screen 2240 * while still allowing the user to interact with the application. 2241 * 2242 * <p>This has the same visual effect as 2243 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2244 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2245 * meaning that non-critical screen decorations (such as the status bar) will be 2246 * hidden while the user is in the View's window, focusing the experience on 2247 * that content. Unlike the window flag, if you are using ActionBar in 2248 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2249 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2250 * hide the action bar. 2251 * 2252 * <p>This approach to going fullscreen is best used over the window flag when 2253 * it is a transient state -- that is, the application does this at certain 2254 * points in its user interaction where it wants to allow the user to focus 2255 * on content, but not as a continuous state. For situations where the application 2256 * would like to simply stay full screen the entire time (such as a game that 2257 * wants to take over the screen), the 2258 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2259 * is usually a better approach. The state set here will be removed by the system 2260 * in various situations (such as the user moving to another application) like 2261 * the other system UI states. 2262 * 2263 * <p>When using this flag, the application should provide some easy facility 2264 * for the user to go out of it. A common example would be in an e-book 2265 * reader, where tapping on the screen brings back whatever screen and UI 2266 * decorations that had been hidden while the user was immersed in reading 2267 * the book. 2268 * 2269 * @see #setSystemUiVisibility(int) 2270 */ 2271 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2272 2273 /** 2274 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2275 * flags, we would like a stable view of the content insets given to 2276 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2277 * will always represent the worst case that the application can expect 2278 * as a continuous state. In the stock Android UI this is the space for 2279 * the system bar, nav bar, and status bar, but not more transient elements 2280 * such as an input method. 2281 * 2282 * The stable layout your UI sees is based on the system UI modes you can 2283 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2284 * then you will get a stable layout for changes of the 2285 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2286 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2287 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2288 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2289 * with a stable layout. (Note that you should avoid using 2290 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2291 * 2292 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2293 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2294 * then a hidden status bar will be considered a "stable" state for purposes 2295 * here. This allows your UI to continually hide the status bar, while still 2296 * using the system UI flags to hide the action bar while still retaining 2297 * a stable layout. Note that changing the window fullscreen flag will never 2298 * provide a stable layout for a clean transition. 2299 * 2300 * <p>If you are using ActionBar in 2301 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2302 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2303 * insets it adds to those given to the application. 2304 */ 2305 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2306 2307 /** 2308 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2309 * to be layed out as if it has requested 2310 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2311 * allows it to avoid artifacts when switching in and out of that mode, at 2312 * the expense that some of its user interface may be covered by screen 2313 * decorations when they are shown. You can perform layout of your inner 2314 * UI elements to account for the navagation system UI through the 2315 * {@link #fitSystemWindows(Rect)} method. 2316 */ 2317 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2318 2319 /** 2320 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2321 * to be layed out as if it has requested 2322 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2323 * allows it to avoid artifacts when switching in and out of that mode, at 2324 * the expense that some of its user interface may be covered by screen 2325 * decorations when they are shown. You can perform layout of your inner 2326 * UI elements to account for non-fullscreen system UI through the 2327 * {@link #fitSystemWindows(Rect)} method. 2328 */ 2329 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2330 2331 /** 2332 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2333 */ 2334 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2335 2336 /** 2337 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2338 */ 2339 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2340 2341 /** 2342 * @hide 2343 * 2344 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2345 * out of the public fields to keep the undefined bits out of the developer's way. 2346 * 2347 * Flag to make the status bar not expandable. Unless you also 2348 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2349 */ 2350 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2351 2352 /** 2353 * @hide 2354 * 2355 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2356 * out of the public fields to keep the undefined bits out of the developer's way. 2357 * 2358 * Flag to hide notification icons and scrolling ticker text. 2359 */ 2360 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2361 2362 /** 2363 * @hide 2364 * 2365 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2366 * out of the public fields to keep the undefined bits out of the developer's way. 2367 * 2368 * Flag to disable incoming notification alerts. This will not block 2369 * icons, but it will block sound, vibrating and other visual or aural notifications. 2370 */ 2371 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2372 2373 /** 2374 * @hide 2375 * 2376 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2377 * out of the public fields to keep the undefined bits out of the developer's way. 2378 * 2379 * Flag to hide only the scrolling ticker. Note that 2380 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2381 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2382 */ 2383 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2384 2385 /** 2386 * @hide 2387 * 2388 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2389 * out of the public fields to keep the undefined bits out of the developer's way. 2390 * 2391 * Flag to hide the center system info area. 2392 */ 2393 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2394 2395 /** 2396 * @hide 2397 * 2398 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2399 * out of the public fields to keep the undefined bits out of the developer's way. 2400 * 2401 * Flag to hide only the home button. Don't use this 2402 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2403 */ 2404 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2405 2406 /** 2407 * @hide 2408 * 2409 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2410 * out of the public fields to keep the undefined bits out of the developer's way. 2411 * 2412 * Flag to hide only the back button. Don't use this 2413 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2414 */ 2415 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2416 2417 /** 2418 * @hide 2419 * 2420 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2421 * out of the public fields to keep the undefined bits out of the developer's way. 2422 * 2423 * Flag to hide only the clock. You might use this if your activity has 2424 * its own clock making the status bar's clock redundant. 2425 */ 2426 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2427 2428 /** 2429 * @hide 2430 * 2431 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2432 * out of the public fields to keep the undefined bits out of the developer's way. 2433 * 2434 * Flag to hide only the recent apps button. Don't use this 2435 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2436 */ 2437 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2438 2439 /** 2440 * @hide 2441 */ 2442 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2443 2444 /** 2445 * These are the system UI flags that can be cleared by events outside 2446 * of an application. Currently this is just the ability to tap on the 2447 * screen while hiding the navigation bar to have it return. 2448 * @hide 2449 */ 2450 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2451 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2452 | SYSTEM_UI_FLAG_FULLSCREEN; 2453 2454 /** 2455 * Flags that can impact the layout in relation to system UI. 2456 */ 2457 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2458 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2459 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2460 2461 /** 2462 * Find views that render the specified text. 2463 * 2464 * @see #findViewsWithText(ArrayList, CharSequence, int) 2465 */ 2466 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2467 2468 /** 2469 * Find find views that contain the specified content description. 2470 * 2471 * @see #findViewsWithText(ArrayList, CharSequence, int) 2472 */ 2473 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2474 2475 /** 2476 * Find views that contain {@link AccessibilityNodeProvider}. Such 2477 * a View is a root of virtual view hierarchy and may contain the searched 2478 * text. If this flag is set Views with providers are automatically 2479 * added and it is a responsibility of the client to call the APIs of 2480 * the provider to determine whether the virtual tree rooted at this View 2481 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2482 * represeting the virtual views with this text. 2483 * 2484 * @see #findViewsWithText(ArrayList, CharSequence, int) 2485 * 2486 * @hide 2487 */ 2488 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2489 2490 /** 2491 * The undefined cursor position. 2492 */ 2493 private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2494 2495 /** 2496 * Indicates that the screen has changed state and is now off. 2497 * 2498 * @see #onScreenStateChanged(int) 2499 */ 2500 public static final int SCREEN_STATE_OFF = 0x0; 2501 2502 /** 2503 * Indicates that the screen has changed state and is now on. 2504 * 2505 * @see #onScreenStateChanged(int) 2506 */ 2507 public static final int SCREEN_STATE_ON = 0x1; 2508 2509 /** 2510 * Controls the over-scroll mode for this view. 2511 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2512 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2513 * and {@link #OVER_SCROLL_NEVER}. 2514 */ 2515 private int mOverScrollMode; 2516 2517 /** 2518 * The parent this view is attached to. 2519 * {@hide} 2520 * 2521 * @see #getParent() 2522 */ 2523 protected ViewParent mParent; 2524 2525 /** 2526 * {@hide} 2527 */ 2528 AttachInfo mAttachInfo; 2529 2530 /** 2531 * {@hide} 2532 */ 2533 @ViewDebug.ExportedProperty(flagMapping = { 2534 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2535 name = "FORCE_LAYOUT"), 2536 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2537 name = "LAYOUT_REQUIRED"), 2538 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2539 name = "DRAWING_CACHE_INVALID", outputIf = false), 2540 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2541 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2542 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2543 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2544 }) 2545 int mPrivateFlags; 2546 int mPrivateFlags2; 2547 int mPrivateFlags3; 2548 2549 /** 2550 * This view's request for the visibility of the status bar. 2551 * @hide 2552 */ 2553 @ViewDebug.ExportedProperty(flagMapping = { 2554 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2555 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2556 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2557 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2558 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2559 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2560 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2561 equals = SYSTEM_UI_FLAG_VISIBLE, 2562 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2563 }) 2564 int mSystemUiVisibility; 2565 2566 /** 2567 * Reference count for transient state. 2568 * @see #setHasTransientState(boolean) 2569 */ 2570 int mTransientStateCount = 0; 2571 2572 /** 2573 * Count of how many windows this view has been attached to. 2574 */ 2575 int mWindowAttachCount; 2576 2577 /** 2578 * The layout parameters associated with this view and used by the parent 2579 * {@link android.view.ViewGroup} to determine how this view should be 2580 * laid out. 2581 * {@hide} 2582 */ 2583 protected ViewGroup.LayoutParams mLayoutParams; 2584 2585 /** 2586 * The view flags hold various views states. 2587 * {@hide} 2588 */ 2589 @ViewDebug.ExportedProperty 2590 int mViewFlags; 2591 2592 static class TransformationInfo { 2593 /** 2594 * The transform matrix for the View. This transform is calculated internally 2595 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2596 * is used by default. Do *not* use this variable directly; instead call 2597 * getMatrix(), which will automatically recalculate the matrix if necessary 2598 * to get the correct matrix based on the latest rotation and scale properties. 2599 */ 2600 private final Matrix mMatrix = new Matrix(); 2601 2602 /** 2603 * The transform matrix for the View. This transform is calculated internally 2604 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2605 * is used by default. Do *not* use this variable directly; instead call 2606 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2607 * to get the correct matrix based on the latest rotation and scale properties. 2608 */ 2609 private Matrix mInverseMatrix; 2610 2611 /** 2612 * An internal variable that tracks whether we need to recalculate the 2613 * transform matrix, based on whether the rotation or scaleX/Y properties 2614 * have changed since the matrix was last calculated. 2615 */ 2616 boolean mMatrixDirty = false; 2617 2618 /** 2619 * An internal variable that tracks whether we need to recalculate the 2620 * transform matrix, based on whether the rotation or scaleX/Y properties 2621 * have changed since the matrix was last calculated. 2622 */ 2623 private boolean mInverseMatrixDirty = true; 2624 2625 /** 2626 * A variable that tracks whether we need to recalculate the 2627 * transform matrix, based on whether the rotation or scaleX/Y properties 2628 * have changed since the matrix was last calculated. This variable 2629 * is only valid after a call to updateMatrix() or to a function that 2630 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2631 */ 2632 private boolean mMatrixIsIdentity = true; 2633 2634 /** 2635 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2636 */ 2637 private Camera mCamera = null; 2638 2639 /** 2640 * This matrix is used when computing the matrix for 3D rotations. 2641 */ 2642 private Matrix matrix3D = null; 2643 2644 /** 2645 * These prev values are used to recalculate a centered pivot point when necessary. The 2646 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2647 * set), so thes values are only used then as well. 2648 */ 2649 private int mPrevWidth = -1; 2650 private int mPrevHeight = -1; 2651 2652 /** 2653 * The degrees rotation around the vertical axis through the pivot point. 2654 */ 2655 @ViewDebug.ExportedProperty 2656 float mRotationY = 0f; 2657 2658 /** 2659 * The degrees rotation around the horizontal axis through the pivot point. 2660 */ 2661 @ViewDebug.ExportedProperty 2662 float mRotationX = 0f; 2663 2664 /** 2665 * The degrees rotation around the pivot point. 2666 */ 2667 @ViewDebug.ExportedProperty 2668 float mRotation = 0f; 2669 2670 /** 2671 * The amount of translation of the object away from its left property (post-layout). 2672 */ 2673 @ViewDebug.ExportedProperty 2674 float mTranslationX = 0f; 2675 2676 /** 2677 * The amount of translation of the object away from its top property (post-layout). 2678 */ 2679 @ViewDebug.ExportedProperty 2680 float mTranslationY = 0f; 2681 2682 /** 2683 * The amount of scale in the x direction around the pivot point. A 2684 * value of 1 means no scaling is applied. 2685 */ 2686 @ViewDebug.ExportedProperty 2687 float mScaleX = 1f; 2688 2689 /** 2690 * The amount of scale in the y direction around the pivot point. A 2691 * value of 1 means no scaling is applied. 2692 */ 2693 @ViewDebug.ExportedProperty 2694 float mScaleY = 1f; 2695 2696 /** 2697 * The x location of the point around which the view is rotated and scaled. 2698 */ 2699 @ViewDebug.ExportedProperty 2700 float mPivotX = 0f; 2701 2702 /** 2703 * The y location of the point around which the view is rotated and scaled. 2704 */ 2705 @ViewDebug.ExportedProperty 2706 float mPivotY = 0f; 2707 2708 /** 2709 * The opacity of the View. This is a value from 0 to 1, where 0 means 2710 * completely transparent and 1 means completely opaque. 2711 */ 2712 @ViewDebug.ExportedProperty 2713 float mAlpha = 1f; 2714 } 2715 2716 TransformationInfo mTransformationInfo; 2717 2718 private boolean mLastIsOpaque; 2719 2720 /** 2721 * Convenience value to check for float values that are close enough to zero to be considered 2722 * zero. 2723 */ 2724 private static final float NONZERO_EPSILON = .001f; 2725 2726 /** 2727 * The distance in pixels from the left edge of this view's parent 2728 * to the left edge of this view. 2729 * {@hide} 2730 */ 2731 @ViewDebug.ExportedProperty(category = "layout") 2732 protected int mLeft; 2733 /** 2734 * The distance in pixels from the left edge of this view's parent 2735 * to the right edge of this view. 2736 * {@hide} 2737 */ 2738 @ViewDebug.ExportedProperty(category = "layout") 2739 protected int mRight; 2740 /** 2741 * The distance in pixels from the top edge of this view's parent 2742 * to the top edge of this view. 2743 * {@hide} 2744 */ 2745 @ViewDebug.ExportedProperty(category = "layout") 2746 protected int mTop; 2747 /** 2748 * The distance in pixels from the top edge of this view's parent 2749 * to the bottom edge of this view. 2750 * {@hide} 2751 */ 2752 @ViewDebug.ExportedProperty(category = "layout") 2753 protected int mBottom; 2754 2755 /** 2756 * The offset, in pixels, by which the content of this view is scrolled 2757 * horizontally. 2758 * {@hide} 2759 */ 2760 @ViewDebug.ExportedProperty(category = "scrolling") 2761 protected int mScrollX; 2762 /** 2763 * The offset, in pixels, by which the content of this view is scrolled 2764 * vertically. 2765 * {@hide} 2766 */ 2767 @ViewDebug.ExportedProperty(category = "scrolling") 2768 protected int mScrollY; 2769 2770 /** 2771 * The left padding in pixels, that is the distance in pixels between the 2772 * left edge of this view and the left edge of its content. 2773 * {@hide} 2774 */ 2775 @ViewDebug.ExportedProperty(category = "padding") 2776 protected int mPaddingLeft = UNDEFINED_PADDING; 2777 /** 2778 * The right padding in pixels, that is the distance in pixels between the 2779 * right edge of this view and the right edge of its content. 2780 * {@hide} 2781 */ 2782 @ViewDebug.ExportedProperty(category = "padding") 2783 protected int mPaddingRight = UNDEFINED_PADDING; 2784 /** 2785 * The top padding in pixels, that is the distance in pixels between the 2786 * top edge of this view and the top edge of its content. 2787 * {@hide} 2788 */ 2789 @ViewDebug.ExportedProperty(category = "padding") 2790 protected int mPaddingTop; 2791 /** 2792 * The bottom padding in pixels, that is the distance in pixels between the 2793 * bottom edge of this view and the bottom edge of its content. 2794 * {@hide} 2795 */ 2796 @ViewDebug.ExportedProperty(category = "padding") 2797 protected int mPaddingBottom; 2798 2799 /** 2800 * The layout insets in pixels, that is the distance in pixels between the 2801 * visible edges of this view its bounds. 2802 */ 2803 private Insets mLayoutInsets; 2804 2805 /** 2806 * Briefly describes the view and is primarily used for accessibility support. 2807 */ 2808 private CharSequence mContentDescription; 2809 2810 /** 2811 * Specifies the id of a view for which this view serves as a label for 2812 * accessibility purposes. 2813 */ 2814 private int mLabelForId = View.NO_ID; 2815 2816 /** 2817 * Predicate for matching labeled view id with its label for 2818 * accessibility purposes. 2819 */ 2820 private MatchLabelForPredicate mMatchLabelForPredicate; 2821 2822 /** 2823 * Predicate for matching a view by its id. 2824 */ 2825 private MatchIdPredicate mMatchIdPredicate; 2826 2827 /** 2828 * Cache the paddingRight set by the user to append to the scrollbar's size. 2829 * 2830 * @hide 2831 */ 2832 @ViewDebug.ExportedProperty(category = "padding") 2833 protected int mUserPaddingRight; 2834 2835 /** 2836 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2837 * 2838 * @hide 2839 */ 2840 @ViewDebug.ExportedProperty(category = "padding") 2841 protected int mUserPaddingBottom; 2842 2843 /** 2844 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2845 * 2846 * @hide 2847 */ 2848 @ViewDebug.ExportedProperty(category = "padding") 2849 protected int mUserPaddingLeft; 2850 2851 /** 2852 * Cache the paddingStart set by the user to append to the scrollbar's size. 2853 * 2854 */ 2855 @ViewDebug.ExportedProperty(category = "padding") 2856 int mUserPaddingStart; 2857 2858 /** 2859 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2860 * 2861 */ 2862 @ViewDebug.ExportedProperty(category = "padding") 2863 int mUserPaddingEnd; 2864 2865 /** 2866 * Cache initial left padding. 2867 * 2868 * @hide 2869 */ 2870 int mUserPaddingLeftInitial = UNDEFINED_PADDING; 2871 2872 /** 2873 * Cache initial right padding. 2874 * 2875 * @hide 2876 */ 2877 int mUserPaddingRightInitial = UNDEFINED_PADDING; 2878 2879 /** 2880 * Default undefined padding 2881 */ 2882 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 2883 2884 /** 2885 * @hide 2886 */ 2887 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2888 /** 2889 * @hide 2890 */ 2891 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2892 2893 private Drawable mBackground; 2894 2895 private int mBackgroundResource; 2896 private boolean mBackgroundSizeChanged; 2897 2898 static class ListenerInfo { 2899 /** 2900 * Listener used to dispatch focus change events. 2901 * This field should be made private, so it is hidden from the SDK. 2902 * {@hide} 2903 */ 2904 protected OnFocusChangeListener mOnFocusChangeListener; 2905 2906 /** 2907 * Listeners for layout change events. 2908 */ 2909 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2910 2911 /** 2912 * Listeners for attach events. 2913 */ 2914 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2915 2916 /** 2917 * Listener used to dispatch click events. 2918 * This field should be made private, so it is hidden from the SDK. 2919 * {@hide} 2920 */ 2921 public OnClickListener mOnClickListener; 2922 2923 /** 2924 * Listener used to dispatch long click events. 2925 * This field should be made private, so it is hidden from the SDK. 2926 * {@hide} 2927 */ 2928 protected OnLongClickListener mOnLongClickListener; 2929 2930 /** 2931 * Listener used to build the context menu. 2932 * This field should be made private, so it is hidden from the SDK. 2933 * {@hide} 2934 */ 2935 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2936 2937 private OnKeyListener mOnKeyListener; 2938 2939 private OnTouchListener mOnTouchListener; 2940 2941 private OnHoverListener mOnHoverListener; 2942 2943 private OnGenericMotionListener mOnGenericMotionListener; 2944 2945 private OnDragListener mOnDragListener; 2946 2947 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2948 } 2949 2950 ListenerInfo mListenerInfo; 2951 2952 /** 2953 * The application environment this view lives in. 2954 * This field should be made private, so it is hidden from the SDK. 2955 * {@hide} 2956 */ 2957 protected Context mContext; 2958 2959 private final Resources mResources; 2960 2961 private ScrollabilityCache mScrollCache; 2962 2963 private int[] mDrawableState = null; 2964 2965 /** 2966 * Set to true when drawing cache is enabled and cannot be created. 2967 * 2968 * @hide 2969 */ 2970 public boolean mCachingFailed; 2971 2972 private Bitmap mDrawingCache; 2973 private Bitmap mUnscaledDrawingCache; 2974 private HardwareLayer mHardwareLayer; 2975 DisplayList mDisplayList; 2976 2977 /** 2978 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2979 * the user may specify which view to go to next. 2980 */ 2981 private int mNextFocusLeftId = View.NO_ID; 2982 2983 /** 2984 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2985 * the user may specify which view to go to next. 2986 */ 2987 private int mNextFocusRightId = View.NO_ID; 2988 2989 /** 2990 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2991 * the user may specify which view to go to next. 2992 */ 2993 private int mNextFocusUpId = View.NO_ID; 2994 2995 /** 2996 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2997 * the user may specify which view to go to next. 2998 */ 2999 private int mNextFocusDownId = View.NO_ID; 3000 3001 /** 3002 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3003 * the user may specify which view to go to next. 3004 */ 3005 int mNextFocusForwardId = View.NO_ID; 3006 3007 private CheckForLongPress mPendingCheckForLongPress; 3008 private CheckForTap mPendingCheckForTap = null; 3009 private PerformClick mPerformClick; 3010 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3011 3012 private UnsetPressedState mUnsetPressedState; 3013 3014 /** 3015 * Whether the long press's action has been invoked. The tap's action is invoked on the 3016 * up event while a long press is invoked as soon as the long press duration is reached, so 3017 * a long press could be performed before the tap is checked, in which case the tap's action 3018 * should not be invoked. 3019 */ 3020 private boolean mHasPerformedLongPress; 3021 3022 /** 3023 * The minimum height of the view. We'll try our best to have the height 3024 * of this view to at least this amount. 3025 */ 3026 @ViewDebug.ExportedProperty(category = "measurement") 3027 private int mMinHeight; 3028 3029 /** 3030 * The minimum width of the view. We'll try our best to have the width 3031 * of this view to at least this amount. 3032 */ 3033 @ViewDebug.ExportedProperty(category = "measurement") 3034 private int mMinWidth; 3035 3036 /** 3037 * The delegate to handle touch events that are physically in this view 3038 * but should be handled by another view. 3039 */ 3040 private TouchDelegate mTouchDelegate = null; 3041 3042 /** 3043 * Solid color to use as a background when creating the drawing cache. Enables 3044 * the cache to use 16 bit bitmaps instead of 32 bit. 3045 */ 3046 private int mDrawingCacheBackgroundColor = 0; 3047 3048 /** 3049 * Special tree observer used when mAttachInfo is null. 3050 */ 3051 private ViewTreeObserver mFloatingTreeObserver; 3052 3053 /** 3054 * Cache the touch slop from the context that created the view. 3055 */ 3056 private int mTouchSlop; 3057 3058 /** 3059 * Object that handles automatic animation of view properties. 3060 */ 3061 private ViewPropertyAnimator mAnimator = null; 3062 3063 /** 3064 * Flag indicating that a drag can cross window boundaries. When 3065 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3066 * with this flag set, all visible applications will be able to participate 3067 * in the drag operation and receive the dragged content. 3068 * 3069 * @hide 3070 */ 3071 public static final int DRAG_FLAG_GLOBAL = 1; 3072 3073 /** 3074 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3075 */ 3076 private float mVerticalScrollFactor; 3077 3078 /** 3079 * Position of the vertical scroll bar. 3080 */ 3081 private int mVerticalScrollbarPosition; 3082 3083 /** 3084 * Position the scroll bar at the default position as determined by the system. 3085 */ 3086 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3087 3088 /** 3089 * Position the scroll bar along the left edge. 3090 */ 3091 public static final int SCROLLBAR_POSITION_LEFT = 1; 3092 3093 /** 3094 * Position the scroll bar along the right edge. 3095 */ 3096 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3097 3098 /** 3099 * Indicates that the view does not have a layer. 3100 * 3101 * @see #getLayerType() 3102 * @see #setLayerType(int, android.graphics.Paint) 3103 * @see #LAYER_TYPE_SOFTWARE 3104 * @see #LAYER_TYPE_HARDWARE 3105 */ 3106 public static final int LAYER_TYPE_NONE = 0; 3107 3108 /** 3109 * <p>Indicates that the view has a software layer. A software layer is backed 3110 * by a bitmap and causes the view to be rendered using Android's software 3111 * rendering pipeline, even if hardware acceleration is enabled.</p> 3112 * 3113 * <p>Software layers have various usages:</p> 3114 * <p>When the application is not using hardware acceleration, a software layer 3115 * is useful to apply a specific color filter and/or blending mode and/or 3116 * translucency to a view and all its children.</p> 3117 * <p>When the application is using hardware acceleration, a software layer 3118 * is useful to render drawing primitives not supported by the hardware 3119 * accelerated pipeline. It can also be used to cache a complex view tree 3120 * into a texture and reduce the complexity of drawing operations. For instance, 3121 * when animating a complex view tree with a translation, a software layer can 3122 * be used to render the view tree only once.</p> 3123 * <p>Software layers should be avoided when the affected view tree updates 3124 * often. Every update will require to re-render the software layer, which can 3125 * potentially be slow (particularly when hardware acceleration is turned on 3126 * since the layer will have to be uploaded into a hardware texture after every 3127 * update.)</p> 3128 * 3129 * @see #getLayerType() 3130 * @see #setLayerType(int, android.graphics.Paint) 3131 * @see #LAYER_TYPE_NONE 3132 * @see #LAYER_TYPE_HARDWARE 3133 */ 3134 public static final int LAYER_TYPE_SOFTWARE = 1; 3135 3136 /** 3137 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3138 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3139 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3140 * rendering pipeline, but only if hardware acceleration is turned on for the 3141 * view hierarchy. When hardware acceleration is turned off, hardware layers 3142 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3143 * 3144 * <p>A hardware layer is useful to apply a specific color filter and/or 3145 * blending mode and/or translucency to a view and all its children.</p> 3146 * <p>A hardware layer can be used to cache a complex view tree into a 3147 * texture and reduce the complexity of drawing operations. For instance, 3148 * when animating a complex view tree with a translation, a hardware layer can 3149 * be used to render the view tree only once.</p> 3150 * <p>A hardware layer can also be used to increase the rendering quality when 3151 * rotation transformations are applied on a view. It can also be used to 3152 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3153 * 3154 * @see #getLayerType() 3155 * @see #setLayerType(int, android.graphics.Paint) 3156 * @see #LAYER_TYPE_NONE 3157 * @see #LAYER_TYPE_SOFTWARE 3158 */ 3159 public static final int LAYER_TYPE_HARDWARE = 2; 3160 3161 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3162 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3163 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3164 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3165 }) 3166 int mLayerType = LAYER_TYPE_NONE; 3167 Paint mLayerPaint; 3168 Rect mLocalDirtyRect; 3169 3170 /** 3171 * Set to true when the view is sending hover accessibility events because it 3172 * is the innermost hovered view. 3173 */ 3174 private boolean mSendingHoverAccessibilityEvents; 3175 3176 /** 3177 * Delegate for injecting accessibility functionality. 3178 */ 3179 AccessibilityDelegate mAccessibilityDelegate; 3180 3181 /** 3182 * Consistency verifier for debugging purposes. 3183 * @hide 3184 */ 3185 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3186 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3187 new InputEventConsistencyVerifier(this, 0) : null; 3188 3189 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3190 3191 /** 3192 * Simple constructor to use when creating a view from code. 3193 * 3194 * @param context The Context the view is running in, through which it can 3195 * access the current theme, resources, etc. 3196 */ 3197 public View(Context context) { 3198 mContext = context; 3199 mResources = context != null ? context.getResources() : null; 3200 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3201 // Set layout and text direction defaults 3202 mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3203 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3204 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3205 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3206 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3207 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3208 mUserPaddingStart = UNDEFINED_PADDING; 3209 mUserPaddingEnd = UNDEFINED_PADDING; 3210 } 3211 3212 /** 3213 * Constructor that is called when inflating a view from XML. This is called 3214 * when a view is being constructed from an XML file, supplying attributes 3215 * that were specified in the XML file. This version uses a default style of 3216 * 0, so the only attribute values applied are those in the Context's Theme 3217 * and the given AttributeSet. 3218 * 3219 * <p> 3220 * The method onFinishInflate() will be called after all children have been 3221 * added. 3222 * 3223 * @param context The Context the view is running in, through which it can 3224 * access the current theme, resources, etc. 3225 * @param attrs The attributes of the XML tag that is inflating the view. 3226 * @see #View(Context, AttributeSet, int) 3227 */ 3228 public View(Context context, AttributeSet attrs) { 3229 this(context, attrs, 0); 3230 } 3231 3232 /** 3233 * Perform inflation from XML and apply a class-specific base style. This 3234 * constructor of View allows subclasses to use their own base style when 3235 * they are inflating. For example, a Button class's constructor would call 3236 * this version of the super class constructor and supply 3237 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 3238 * the theme's button style to modify all of the base view attributes (in 3239 * particular its background) as well as the Button class's attributes. 3240 * 3241 * @param context The Context the view is running in, through which it can 3242 * access the current theme, resources, etc. 3243 * @param attrs The attributes of the XML tag that is inflating the view. 3244 * @param defStyle The default style to apply to this view. If 0, no style 3245 * will be applied (beyond what is included in the theme). This may 3246 * either be an attribute resource, whose value will be retrieved 3247 * from the current theme, or an explicit style resource. 3248 * @see #View(Context, AttributeSet) 3249 */ 3250 public View(Context context, AttributeSet attrs, int defStyle) { 3251 this(context); 3252 3253 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 3254 defStyle, 0); 3255 3256 Drawable background = null; 3257 3258 int leftPadding = -1; 3259 int topPadding = -1; 3260 int rightPadding = -1; 3261 int bottomPadding = -1; 3262 int startPadding = UNDEFINED_PADDING; 3263 int endPadding = UNDEFINED_PADDING; 3264 3265 int padding = -1; 3266 3267 int viewFlagValues = 0; 3268 int viewFlagMasks = 0; 3269 3270 boolean setScrollContainer = false; 3271 3272 int x = 0; 3273 int y = 0; 3274 3275 float tx = 0; 3276 float ty = 0; 3277 float rotation = 0; 3278 float rotationX = 0; 3279 float rotationY = 0; 3280 float sx = 1f; 3281 float sy = 1f; 3282 boolean transformSet = false; 3283 3284 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3285 int overScrollMode = mOverScrollMode; 3286 boolean initializeScrollbars = false; 3287 3288 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3289 3290 final int N = a.getIndexCount(); 3291 for (int i = 0; i < N; i++) { 3292 int attr = a.getIndex(i); 3293 switch (attr) { 3294 case com.android.internal.R.styleable.View_background: 3295 background = a.getDrawable(attr); 3296 break; 3297 case com.android.internal.R.styleable.View_padding: 3298 padding = a.getDimensionPixelSize(attr, -1); 3299 mUserPaddingLeftInitial = padding; 3300 mUserPaddingRightInitial = padding; 3301 break; 3302 case com.android.internal.R.styleable.View_paddingLeft: 3303 leftPadding = a.getDimensionPixelSize(attr, -1); 3304 mUserPaddingLeftInitial = leftPadding; 3305 break; 3306 case com.android.internal.R.styleable.View_paddingTop: 3307 topPadding = a.getDimensionPixelSize(attr, -1); 3308 break; 3309 case com.android.internal.R.styleable.View_paddingRight: 3310 rightPadding = a.getDimensionPixelSize(attr, -1); 3311 mUserPaddingRightInitial = rightPadding; 3312 break; 3313 case com.android.internal.R.styleable.View_paddingBottom: 3314 bottomPadding = a.getDimensionPixelSize(attr, -1); 3315 break; 3316 case com.android.internal.R.styleable.View_paddingStart: 3317 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3318 break; 3319 case com.android.internal.R.styleable.View_paddingEnd: 3320 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3321 break; 3322 case com.android.internal.R.styleable.View_scrollX: 3323 x = a.getDimensionPixelOffset(attr, 0); 3324 break; 3325 case com.android.internal.R.styleable.View_scrollY: 3326 y = a.getDimensionPixelOffset(attr, 0); 3327 break; 3328 case com.android.internal.R.styleable.View_alpha: 3329 setAlpha(a.getFloat(attr, 1f)); 3330 break; 3331 case com.android.internal.R.styleable.View_transformPivotX: 3332 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3333 break; 3334 case com.android.internal.R.styleable.View_transformPivotY: 3335 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3336 break; 3337 case com.android.internal.R.styleable.View_translationX: 3338 tx = a.getDimensionPixelOffset(attr, 0); 3339 transformSet = true; 3340 break; 3341 case com.android.internal.R.styleable.View_translationY: 3342 ty = a.getDimensionPixelOffset(attr, 0); 3343 transformSet = true; 3344 break; 3345 case com.android.internal.R.styleable.View_rotation: 3346 rotation = a.getFloat(attr, 0); 3347 transformSet = true; 3348 break; 3349 case com.android.internal.R.styleable.View_rotationX: 3350 rotationX = a.getFloat(attr, 0); 3351 transformSet = true; 3352 break; 3353 case com.android.internal.R.styleable.View_rotationY: 3354 rotationY = a.getFloat(attr, 0); 3355 transformSet = true; 3356 break; 3357 case com.android.internal.R.styleable.View_scaleX: 3358 sx = a.getFloat(attr, 1f); 3359 transformSet = true; 3360 break; 3361 case com.android.internal.R.styleable.View_scaleY: 3362 sy = a.getFloat(attr, 1f); 3363 transformSet = true; 3364 break; 3365 case com.android.internal.R.styleable.View_id: 3366 mID = a.getResourceId(attr, NO_ID); 3367 break; 3368 case com.android.internal.R.styleable.View_tag: 3369 mTag = a.getText(attr); 3370 break; 3371 case com.android.internal.R.styleable.View_fitsSystemWindows: 3372 if (a.getBoolean(attr, false)) { 3373 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3374 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3375 } 3376 break; 3377 case com.android.internal.R.styleable.View_focusable: 3378 if (a.getBoolean(attr, false)) { 3379 viewFlagValues |= FOCUSABLE; 3380 viewFlagMasks |= FOCUSABLE_MASK; 3381 } 3382 break; 3383 case com.android.internal.R.styleable.View_focusableInTouchMode: 3384 if (a.getBoolean(attr, false)) { 3385 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3386 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3387 } 3388 break; 3389 case com.android.internal.R.styleable.View_clickable: 3390 if (a.getBoolean(attr, false)) { 3391 viewFlagValues |= CLICKABLE; 3392 viewFlagMasks |= CLICKABLE; 3393 } 3394 break; 3395 case com.android.internal.R.styleable.View_longClickable: 3396 if (a.getBoolean(attr, false)) { 3397 viewFlagValues |= LONG_CLICKABLE; 3398 viewFlagMasks |= LONG_CLICKABLE; 3399 } 3400 break; 3401 case com.android.internal.R.styleable.View_saveEnabled: 3402 if (!a.getBoolean(attr, true)) { 3403 viewFlagValues |= SAVE_DISABLED; 3404 viewFlagMasks |= SAVE_DISABLED_MASK; 3405 } 3406 break; 3407 case com.android.internal.R.styleable.View_duplicateParentState: 3408 if (a.getBoolean(attr, false)) { 3409 viewFlagValues |= DUPLICATE_PARENT_STATE; 3410 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3411 } 3412 break; 3413 case com.android.internal.R.styleable.View_visibility: 3414 final int visibility = a.getInt(attr, 0); 3415 if (visibility != 0) { 3416 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3417 viewFlagMasks |= VISIBILITY_MASK; 3418 } 3419 break; 3420 case com.android.internal.R.styleable.View_layoutDirection: 3421 // Clear any layout direction flags (included resolved bits) already set 3422 mPrivateFlags2 &= ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3423 // Set the layout direction flags depending on the value of the attribute 3424 final int layoutDirection = a.getInt(attr, -1); 3425 final int value = (layoutDirection != -1) ? 3426 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3427 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3428 break; 3429 case com.android.internal.R.styleable.View_drawingCacheQuality: 3430 final int cacheQuality = a.getInt(attr, 0); 3431 if (cacheQuality != 0) { 3432 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3433 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3434 } 3435 break; 3436 case com.android.internal.R.styleable.View_contentDescription: 3437 setContentDescription(a.getString(attr)); 3438 break; 3439 case com.android.internal.R.styleable.View_labelFor: 3440 setLabelFor(a.getResourceId(attr, NO_ID)); 3441 break; 3442 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3443 if (!a.getBoolean(attr, true)) { 3444 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3445 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3446 } 3447 break; 3448 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3449 if (!a.getBoolean(attr, true)) { 3450 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3451 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3452 } 3453 break; 3454 case R.styleable.View_scrollbars: 3455 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3456 if (scrollbars != SCROLLBARS_NONE) { 3457 viewFlagValues |= scrollbars; 3458 viewFlagMasks |= SCROLLBARS_MASK; 3459 initializeScrollbars = true; 3460 } 3461 break; 3462 //noinspection deprecation 3463 case R.styleable.View_fadingEdge: 3464 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3465 // Ignore the attribute starting with ICS 3466 break; 3467 } 3468 // With builds < ICS, fall through and apply fading edges 3469 case R.styleable.View_requiresFadingEdge: 3470 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3471 if (fadingEdge != FADING_EDGE_NONE) { 3472 viewFlagValues |= fadingEdge; 3473 viewFlagMasks |= FADING_EDGE_MASK; 3474 initializeFadingEdge(a); 3475 } 3476 break; 3477 case R.styleable.View_scrollbarStyle: 3478 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3479 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3480 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3481 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3482 } 3483 break; 3484 case R.styleable.View_isScrollContainer: 3485 setScrollContainer = true; 3486 if (a.getBoolean(attr, false)) { 3487 setScrollContainer(true); 3488 } 3489 break; 3490 case com.android.internal.R.styleable.View_keepScreenOn: 3491 if (a.getBoolean(attr, false)) { 3492 viewFlagValues |= KEEP_SCREEN_ON; 3493 viewFlagMasks |= KEEP_SCREEN_ON; 3494 } 3495 break; 3496 case R.styleable.View_filterTouchesWhenObscured: 3497 if (a.getBoolean(attr, false)) { 3498 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3499 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3500 } 3501 break; 3502 case R.styleable.View_nextFocusLeft: 3503 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3504 break; 3505 case R.styleable.View_nextFocusRight: 3506 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3507 break; 3508 case R.styleable.View_nextFocusUp: 3509 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3510 break; 3511 case R.styleable.View_nextFocusDown: 3512 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3513 break; 3514 case R.styleable.View_nextFocusForward: 3515 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3516 break; 3517 case R.styleable.View_minWidth: 3518 mMinWidth = a.getDimensionPixelSize(attr, 0); 3519 break; 3520 case R.styleable.View_minHeight: 3521 mMinHeight = a.getDimensionPixelSize(attr, 0); 3522 break; 3523 case R.styleable.View_onClick: 3524 if (context.isRestricted()) { 3525 throw new IllegalStateException("The android:onClick attribute cannot " 3526 + "be used within a restricted context"); 3527 } 3528 3529 final String handlerName = a.getString(attr); 3530 if (handlerName != null) { 3531 setOnClickListener(new OnClickListener() { 3532 private Method mHandler; 3533 3534 public void onClick(View v) { 3535 if (mHandler == null) { 3536 try { 3537 mHandler = getContext().getClass().getMethod(handlerName, 3538 View.class); 3539 } catch (NoSuchMethodException e) { 3540 int id = getId(); 3541 String idText = id == NO_ID ? "" : " with id '" 3542 + getContext().getResources().getResourceEntryName( 3543 id) + "'"; 3544 throw new IllegalStateException("Could not find a method " + 3545 handlerName + "(View) in the activity " 3546 + getContext().getClass() + " for onClick handler" 3547 + " on view " + View.this.getClass() + idText, e); 3548 } 3549 } 3550 3551 try { 3552 mHandler.invoke(getContext(), View.this); 3553 } catch (IllegalAccessException e) { 3554 throw new IllegalStateException("Could not execute non " 3555 + "public method of the activity", e); 3556 } catch (InvocationTargetException e) { 3557 throw new IllegalStateException("Could not execute " 3558 + "method of the activity", e); 3559 } 3560 } 3561 }); 3562 } 3563 break; 3564 case R.styleable.View_overScrollMode: 3565 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3566 break; 3567 case R.styleable.View_verticalScrollbarPosition: 3568 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3569 break; 3570 case R.styleable.View_layerType: 3571 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3572 break; 3573 case R.styleable.View_textDirection: 3574 // Clear any text direction flag already set 3575 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3576 // Set the text direction flags depending on the value of the attribute 3577 final int textDirection = a.getInt(attr, -1); 3578 if (textDirection != -1) { 3579 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3580 } 3581 break; 3582 case R.styleable.View_textAlignment: 3583 // Clear any text alignment flag already set 3584 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3585 // Set the text alignment flag depending on the value of the attribute 3586 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3587 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 3588 break; 3589 case R.styleable.View_importantForAccessibility: 3590 setImportantForAccessibility(a.getInt(attr, 3591 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 3592 break; 3593 } 3594 } 3595 3596 setOverScrollMode(overScrollMode); 3597 3598 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 3599 // the resolved layout direction). Those cached values will be used later during padding 3600 // resolution. 3601 mUserPaddingStart = startPadding; 3602 mUserPaddingEnd = endPadding; 3603 3604 if (background != null) { 3605 setBackground(background); 3606 } 3607 3608 if (padding >= 0) { 3609 leftPadding = padding; 3610 topPadding = padding; 3611 rightPadding = padding; 3612 bottomPadding = padding; 3613 mUserPaddingLeftInitial = padding; 3614 mUserPaddingRightInitial = padding; 3615 } 3616 3617 // If the user specified the padding (either with android:padding or 3618 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 3619 // use the default padding or the padding from the background drawable 3620 // (stored at this point in mPadding*) 3621 mUserPaddingLeftInitial = leftPadding >= 0 ? leftPadding : mPaddingLeft; 3622 mUserPaddingRightInitial = rightPadding >= 0 ? rightPadding : mPaddingRight; 3623 internalSetPadding( 3624 mUserPaddingLeftInitial != UNDEFINED_PADDING ? mUserPaddingLeftInitial : 0, 3625 topPadding >= 0 ? topPadding : mPaddingTop, 3626 mUserPaddingRightInitial != UNDEFINED_PADDING ? mUserPaddingRightInitial : 0, 3627 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3628 3629 if (viewFlagMasks != 0) { 3630 setFlags(viewFlagValues, viewFlagMasks); 3631 } 3632 3633 if (initializeScrollbars) { 3634 initializeScrollbars(a); 3635 } 3636 3637 a.recycle(); 3638 3639 // Needs to be called after mViewFlags is set 3640 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3641 recomputePadding(); 3642 } 3643 3644 if (x != 0 || y != 0) { 3645 scrollTo(x, y); 3646 } 3647 3648 if (transformSet) { 3649 setTranslationX(tx); 3650 setTranslationY(ty); 3651 setRotation(rotation); 3652 setRotationX(rotationX); 3653 setRotationY(rotationY); 3654 setScaleX(sx); 3655 setScaleY(sy); 3656 } 3657 3658 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3659 setScrollContainer(true); 3660 } 3661 3662 computeOpaqueFlags(); 3663 } 3664 3665 /** 3666 * Non-public constructor for use in testing 3667 */ 3668 View() { 3669 mResources = null; 3670 } 3671 3672 public String toString() { 3673 StringBuilder out = new StringBuilder(128); 3674 out.append(getClass().getName()); 3675 out.append('{'); 3676 out.append(Integer.toHexString(System.identityHashCode(this))); 3677 out.append(' '); 3678 switch (mViewFlags&VISIBILITY_MASK) { 3679 case VISIBLE: out.append('V'); break; 3680 case INVISIBLE: out.append('I'); break; 3681 case GONE: out.append('G'); break; 3682 default: out.append('.'); break; 3683 } 3684 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 3685 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 3686 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 3687 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 3688 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 3689 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 3690 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 3691 out.append(' '); 3692 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 3693 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 3694 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 3695 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 3696 out.append('p'); 3697 } else { 3698 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 3699 } 3700 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 3701 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 3702 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 3703 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 3704 out.append(' '); 3705 out.append(mLeft); 3706 out.append(','); 3707 out.append(mTop); 3708 out.append('-'); 3709 out.append(mRight); 3710 out.append(','); 3711 out.append(mBottom); 3712 final int id = getId(); 3713 if (id != NO_ID) { 3714 out.append(" #"); 3715 out.append(Integer.toHexString(id)); 3716 final Resources r = mResources; 3717 if (id != 0 && r != null) { 3718 try { 3719 String pkgname; 3720 switch (id&0xff000000) { 3721 case 0x7f000000: 3722 pkgname="app"; 3723 break; 3724 case 0x01000000: 3725 pkgname="android"; 3726 break; 3727 default: 3728 pkgname = r.getResourcePackageName(id); 3729 break; 3730 } 3731 String typename = r.getResourceTypeName(id); 3732 String entryname = r.getResourceEntryName(id); 3733 out.append(" "); 3734 out.append(pkgname); 3735 out.append(":"); 3736 out.append(typename); 3737 out.append("/"); 3738 out.append(entryname); 3739 } catch (Resources.NotFoundException e) { 3740 } 3741 } 3742 } 3743 out.append("}"); 3744 return out.toString(); 3745 } 3746 3747 /** 3748 * <p> 3749 * Initializes the fading edges from a given set of styled attributes. This 3750 * method should be called by subclasses that need fading edges and when an 3751 * instance of these subclasses is created programmatically rather than 3752 * being inflated from XML. This method is automatically called when the XML 3753 * is inflated. 3754 * </p> 3755 * 3756 * @param a the styled attributes set to initialize the fading edges from 3757 */ 3758 protected void initializeFadingEdge(TypedArray a) { 3759 initScrollCache(); 3760 3761 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3762 R.styleable.View_fadingEdgeLength, 3763 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3764 } 3765 3766 /** 3767 * Returns the size of the vertical faded edges used to indicate that more 3768 * content in this view is visible. 3769 * 3770 * @return The size in pixels of the vertical faded edge or 0 if vertical 3771 * faded edges are not enabled for this view. 3772 * @attr ref android.R.styleable#View_fadingEdgeLength 3773 */ 3774 public int getVerticalFadingEdgeLength() { 3775 if (isVerticalFadingEdgeEnabled()) { 3776 ScrollabilityCache cache = mScrollCache; 3777 if (cache != null) { 3778 return cache.fadingEdgeLength; 3779 } 3780 } 3781 return 0; 3782 } 3783 3784 /** 3785 * Set the size of the faded edge used to indicate that more content in this 3786 * view is available. Will not change whether the fading edge is enabled; use 3787 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3788 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3789 * for the vertical or horizontal fading edges. 3790 * 3791 * @param length The size in pixels of the faded edge used to indicate that more 3792 * content in this view is visible. 3793 */ 3794 public void setFadingEdgeLength(int length) { 3795 initScrollCache(); 3796 mScrollCache.fadingEdgeLength = length; 3797 } 3798 3799 /** 3800 * Returns the size of the horizontal faded edges used to indicate that more 3801 * content in this view is visible. 3802 * 3803 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3804 * faded edges are not enabled for this view. 3805 * @attr ref android.R.styleable#View_fadingEdgeLength 3806 */ 3807 public int getHorizontalFadingEdgeLength() { 3808 if (isHorizontalFadingEdgeEnabled()) { 3809 ScrollabilityCache cache = mScrollCache; 3810 if (cache != null) { 3811 return cache.fadingEdgeLength; 3812 } 3813 } 3814 return 0; 3815 } 3816 3817 /** 3818 * Returns the width of the vertical scrollbar. 3819 * 3820 * @return The width in pixels of the vertical scrollbar or 0 if there 3821 * is no vertical scrollbar. 3822 */ 3823 public int getVerticalScrollbarWidth() { 3824 ScrollabilityCache cache = mScrollCache; 3825 if (cache != null) { 3826 ScrollBarDrawable scrollBar = cache.scrollBar; 3827 if (scrollBar != null) { 3828 int size = scrollBar.getSize(true); 3829 if (size <= 0) { 3830 size = cache.scrollBarSize; 3831 } 3832 return size; 3833 } 3834 return 0; 3835 } 3836 return 0; 3837 } 3838 3839 /** 3840 * Returns the height of the horizontal scrollbar. 3841 * 3842 * @return The height in pixels of the horizontal scrollbar or 0 if 3843 * there is no horizontal scrollbar. 3844 */ 3845 protected int getHorizontalScrollbarHeight() { 3846 ScrollabilityCache cache = mScrollCache; 3847 if (cache != null) { 3848 ScrollBarDrawable scrollBar = cache.scrollBar; 3849 if (scrollBar != null) { 3850 int size = scrollBar.getSize(false); 3851 if (size <= 0) { 3852 size = cache.scrollBarSize; 3853 } 3854 return size; 3855 } 3856 return 0; 3857 } 3858 return 0; 3859 } 3860 3861 /** 3862 * <p> 3863 * Initializes the scrollbars from a given set of styled attributes. This 3864 * method should be called by subclasses that need scrollbars and when an 3865 * instance of these subclasses is created programmatically rather than 3866 * being inflated from XML. This method is automatically called when the XML 3867 * is inflated. 3868 * </p> 3869 * 3870 * @param a the styled attributes set to initialize the scrollbars from 3871 */ 3872 protected void initializeScrollbars(TypedArray a) { 3873 initScrollCache(); 3874 3875 final ScrollabilityCache scrollabilityCache = mScrollCache; 3876 3877 if (scrollabilityCache.scrollBar == null) { 3878 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3879 } 3880 3881 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3882 3883 if (!fadeScrollbars) { 3884 scrollabilityCache.state = ScrollabilityCache.ON; 3885 } 3886 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3887 3888 3889 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3890 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3891 .getScrollBarFadeDuration()); 3892 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3893 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3894 ViewConfiguration.getScrollDefaultDelay()); 3895 3896 3897 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3898 com.android.internal.R.styleable.View_scrollbarSize, 3899 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3900 3901 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3902 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3903 3904 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3905 if (thumb != null) { 3906 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3907 } 3908 3909 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3910 false); 3911 if (alwaysDraw) { 3912 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3913 } 3914 3915 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3916 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3917 3918 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3919 if (thumb != null) { 3920 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3921 } 3922 3923 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3924 false); 3925 if (alwaysDraw) { 3926 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3927 } 3928 3929 // Apply layout direction to the new Drawables if needed 3930 final int layoutDirection = getResolvedLayoutDirection(); 3931 if (track != null) { 3932 track.setLayoutDirection(layoutDirection); 3933 } 3934 if (thumb != null) { 3935 thumb.setLayoutDirection(layoutDirection); 3936 } 3937 3938 // Re-apply user/background padding so that scrollbar(s) get added 3939 resolvePadding(); 3940 } 3941 3942 /** 3943 * <p> 3944 * Initalizes the scrollability cache if necessary. 3945 * </p> 3946 */ 3947 private void initScrollCache() { 3948 if (mScrollCache == null) { 3949 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3950 } 3951 } 3952 3953 private ScrollabilityCache getScrollCache() { 3954 initScrollCache(); 3955 return mScrollCache; 3956 } 3957 3958 /** 3959 * Set the position of the vertical scroll bar. Should be one of 3960 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3961 * {@link #SCROLLBAR_POSITION_RIGHT}. 3962 * 3963 * @param position Where the vertical scroll bar should be positioned. 3964 */ 3965 public void setVerticalScrollbarPosition(int position) { 3966 if (mVerticalScrollbarPosition != position) { 3967 mVerticalScrollbarPosition = position; 3968 computeOpaqueFlags(); 3969 resolvePadding(); 3970 } 3971 } 3972 3973 /** 3974 * @return The position where the vertical scroll bar will show, if applicable. 3975 * @see #setVerticalScrollbarPosition(int) 3976 */ 3977 public int getVerticalScrollbarPosition() { 3978 return mVerticalScrollbarPosition; 3979 } 3980 3981 ListenerInfo getListenerInfo() { 3982 if (mListenerInfo != null) { 3983 return mListenerInfo; 3984 } 3985 mListenerInfo = new ListenerInfo(); 3986 return mListenerInfo; 3987 } 3988 3989 /** 3990 * Register a callback to be invoked when focus of this view changed. 3991 * 3992 * @param l The callback that will run. 3993 */ 3994 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3995 getListenerInfo().mOnFocusChangeListener = l; 3996 } 3997 3998 /** 3999 * Add a listener that will be called when the bounds of the view change due to 4000 * layout processing. 4001 * 4002 * @param listener The listener that will be called when layout bounds change. 4003 */ 4004 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4005 ListenerInfo li = getListenerInfo(); 4006 if (li.mOnLayoutChangeListeners == null) { 4007 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4008 } 4009 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4010 li.mOnLayoutChangeListeners.add(listener); 4011 } 4012 } 4013 4014 /** 4015 * Remove a listener for layout changes. 4016 * 4017 * @param listener The listener for layout bounds change. 4018 */ 4019 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4020 ListenerInfo li = mListenerInfo; 4021 if (li == null || li.mOnLayoutChangeListeners == null) { 4022 return; 4023 } 4024 li.mOnLayoutChangeListeners.remove(listener); 4025 } 4026 4027 /** 4028 * Add a listener for attach state changes. 4029 * 4030 * This listener will be called whenever this view is attached or detached 4031 * from a window. Remove the listener using 4032 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4033 * 4034 * @param listener Listener to attach 4035 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4036 */ 4037 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4038 ListenerInfo li = getListenerInfo(); 4039 if (li.mOnAttachStateChangeListeners == null) { 4040 li.mOnAttachStateChangeListeners 4041 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4042 } 4043 li.mOnAttachStateChangeListeners.add(listener); 4044 } 4045 4046 /** 4047 * Remove a listener for attach state changes. The listener will receive no further 4048 * notification of window attach/detach events. 4049 * 4050 * @param listener Listener to remove 4051 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4052 */ 4053 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4054 ListenerInfo li = mListenerInfo; 4055 if (li == null || li.mOnAttachStateChangeListeners == null) { 4056 return; 4057 } 4058 li.mOnAttachStateChangeListeners.remove(listener); 4059 } 4060 4061 /** 4062 * Returns the focus-change callback registered for this view. 4063 * 4064 * @return The callback, or null if one is not registered. 4065 */ 4066 public OnFocusChangeListener getOnFocusChangeListener() { 4067 ListenerInfo li = mListenerInfo; 4068 return li != null ? li.mOnFocusChangeListener : null; 4069 } 4070 4071 /** 4072 * Register a callback to be invoked when this view is clicked. If this view is not 4073 * clickable, it becomes clickable. 4074 * 4075 * @param l The callback that will run 4076 * 4077 * @see #setClickable(boolean) 4078 */ 4079 public void setOnClickListener(OnClickListener l) { 4080 if (!isClickable()) { 4081 setClickable(true); 4082 } 4083 getListenerInfo().mOnClickListener = l; 4084 } 4085 4086 /** 4087 * Return whether this view has an attached OnClickListener. Returns 4088 * true if there is a listener, false if there is none. 4089 */ 4090 public boolean hasOnClickListeners() { 4091 ListenerInfo li = mListenerInfo; 4092 return (li != null && li.mOnClickListener != null); 4093 } 4094 4095 /** 4096 * Register a callback to be invoked when this view is clicked and held. If this view is not 4097 * long clickable, it becomes long clickable. 4098 * 4099 * @param l The callback that will run 4100 * 4101 * @see #setLongClickable(boolean) 4102 */ 4103 public void setOnLongClickListener(OnLongClickListener l) { 4104 if (!isLongClickable()) { 4105 setLongClickable(true); 4106 } 4107 getListenerInfo().mOnLongClickListener = l; 4108 } 4109 4110 /** 4111 * Register a callback to be invoked when the context menu for this view is 4112 * being built. If this view is not long clickable, it becomes long clickable. 4113 * 4114 * @param l The callback that will run 4115 * 4116 */ 4117 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4118 if (!isLongClickable()) { 4119 setLongClickable(true); 4120 } 4121 getListenerInfo().mOnCreateContextMenuListener = l; 4122 } 4123 4124 /** 4125 * Call this view's OnClickListener, if it is defined. Performs all normal 4126 * actions associated with clicking: reporting accessibility event, playing 4127 * a sound, etc. 4128 * 4129 * @return True there was an assigned OnClickListener that was called, false 4130 * otherwise is returned. 4131 */ 4132 public boolean performClick() { 4133 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4134 4135 ListenerInfo li = mListenerInfo; 4136 if (li != null && li.mOnClickListener != null) { 4137 playSoundEffect(SoundEffectConstants.CLICK); 4138 li.mOnClickListener.onClick(this); 4139 return true; 4140 } 4141 4142 return false; 4143 } 4144 4145 /** 4146 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4147 * this only calls the listener, and does not do any associated clicking 4148 * actions like reporting an accessibility event. 4149 * 4150 * @return True there was an assigned OnClickListener that was called, false 4151 * otherwise is returned. 4152 */ 4153 public boolean callOnClick() { 4154 ListenerInfo li = mListenerInfo; 4155 if (li != null && li.mOnClickListener != null) { 4156 li.mOnClickListener.onClick(this); 4157 return true; 4158 } 4159 return false; 4160 } 4161 4162 /** 4163 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4164 * OnLongClickListener did not consume the event. 4165 * 4166 * @return True if one of the above receivers consumed the event, false otherwise. 4167 */ 4168 public boolean performLongClick() { 4169 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4170 4171 boolean handled = false; 4172 ListenerInfo li = mListenerInfo; 4173 if (li != null && li.mOnLongClickListener != null) { 4174 handled = li.mOnLongClickListener.onLongClick(View.this); 4175 } 4176 if (!handled) { 4177 handled = showContextMenu(); 4178 } 4179 if (handled) { 4180 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4181 } 4182 return handled; 4183 } 4184 4185 /** 4186 * Performs button-related actions during a touch down event. 4187 * 4188 * @param event The event. 4189 * @return True if the down was consumed. 4190 * 4191 * @hide 4192 */ 4193 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4194 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4195 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4196 return true; 4197 } 4198 } 4199 return false; 4200 } 4201 4202 /** 4203 * Bring up the context menu for this view. 4204 * 4205 * @return Whether a context menu was displayed. 4206 */ 4207 public boolean showContextMenu() { 4208 return getParent().showContextMenuForChild(this); 4209 } 4210 4211 /** 4212 * Bring up the context menu for this view, referring to the item under the specified point. 4213 * 4214 * @param x The referenced x coordinate. 4215 * @param y The referenced y coordinate. 4216 * @param metaState The keyboard modifiers that were pressed. 4217 * @return Whether a context menu was displayed. 4218 * 4219 * @hide 4220 */ 4221 public boolean showContextMenu(float x, float y, int metaState) { 4222 return showContextMenu(); 4223 } 4224 4225 /** 4226 * Start an action mode. 4227 * 4228 * @param callback Callback that will control the lifecycle of the action mode 4229 * @return The new action mode if it is started, null otherwise 4230 * 4231 * @see ActionMode 4232 */ 4233 public ActionMode startActionMode(ActionMode.Callback callback) { 4234 ViewParent parent = getParent(); 4235 if (parent == null) return null; 4236 return parent.startActionModeForChild(this, callback); 4237 } 4238 4239 /** 4240 * Register a callback to be invoked when a hardware key is pressed in this view. 4241 * Key presses in software input methods will generally not trigger the methods of 4242 * this listener. 4243 * @param l the key listener to attach to this view 4244 */ 4245 public void setOnKeyListener(OnKeyListener l) { 4246 getListenerInfo().mOnKeyListener = l; 4247 } 4248 4249 /** 4250 * Register a callback to be invoked when a touch event is sent to this view. 4251 * @param l the touch listener to attach to this view 4252 */ 4253 public void setOnTouchListener(OnTouchListener l) { 4254 getListenerInfo().mOnTouchListener = l; 4255 } 4256 4257 /** 4258 * Register a callback to be invoked when a generic motion event is sent to this view. 4259 * @param l the generic motion listener to attach to this view 4260 */ 4261 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4262 getListenerInfo().mOnGenericMotionListener = l; 4263 } 4264 4265 /** 4266 * Register a callback to be invoked when a hover event is sent to this view. 4267 * @param l the hover listener to attach to this view 4268 */ 4269 public void setOnHoverListener(OnHoverListener l) { 4270 getListenerInfo().mOnHoverListener = l; 4271 } 4272 4273 /** 4274 * Register a drag event listener callback object for this View. The parameter is 4275 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4276 * View, the system calls the 4277 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4278 * @param l An implementation of {@link android.view.View.OnDragListener}. 4279 */ 4280 public void setOnDragListener(OnDragListener l) { 4281 getListenerInfo().mOnDragListener = l; 4282 } 4283 4284 /** 4285 * Give this view focus. This will cause 4286 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4287 * 4288 * Note: this does not check whether this {@link View} should get focus, it just 4289 * gives it focus no matter what. It should only be called internally by framework 4290 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4291 * 4292 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4293 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4294 * focus moved when requestFocus() is called. It may not always 4295 * apply, in which case use the default View.FOCUS_DOWN. 4296 * @param previouslyFocusedRect The rectangle of the view that had focus 4297 * prior in this View's coordinate system. 4298 */ 4299 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 4300 if (DBG) { 4301 System.out.println(this + " requestFocus()"); 4302 } 4303 4304 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4305 mPrivateFlags |= PFLAG_FOCUSED; 4306 4307 if (mParent != null) { 4308 mParent.requestChildFocus(this, this); 4309 } 4310 4311 onFocusChanged(true, direction, previouslyFocusedRect); 4312 refreshDrawableState(); 4313 4314 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4315 notifyAccessibilityStateChanged(); 4316 } 4317 } 4318 } 4319 4320 /** 4321 * Request that a rectangle of this view be visible on the screen, 4322 * scrolling if necessary just enough. 4323 * 4324 * <p>A View should call this if it maintains some notion of which part 4325 * of its content is interesting. For example, a text editing view 4326 * should call this when its cursor moves. 4327 * 4328 * @param rectangle The rectangle. 4329 * @return Whether any parent scrolled. 4330 */ 4331 public boolean requestRectangleOnScreen(Rect rectangle) { 4332 return requestRectangleOnScreen(rectangle, false); 4333 } 4334 4335 /** 4336 * Request that a rectangle of this view be visible on the screen, 4337 * scrolling if necessary just enough. 4338 * 4339 * <p>A View should call this if it maintains some notion of which part 4340 * of its content is interesting. For example, a text editing view 4341 * should call this when its cursor moves. 4342 * 4343 * <p>When <code>immediate</code> is set to true, scrolling will not be 4344 * animated. 4345 * 4346 * @param rectangle The rectangle. 4347 * @param immediate True to forbid animated scrolling, false otherwise 4348 * @return Whether any parent scrolled. 4349 */ 4350 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4351 if (mAttachInfo == null) { 4352 return false; 4353 } 4354 4355 View child = this; 4356 4357 RectF position = mAttachInfo.mTmpTransformRect; 4358 position.set(rectangle); 4359 4360 ViewParent parent = mParent; 4361 boolean scrolled = false; 4362 while (parent != null) { 4363 rectangle.set((int) position.left, (int) position.top, 4364 (int) position.right, (int) position.bottom); 4365 4366 scrolled |= parent.requestChildRectangleOnScreen(child, 4367 rectangle, immediate); 4368 4369 if (!child.hasIdentityMatrix()) { 4370 child.getMatrix().mapRect(position); 4371 } 4372 4373 position.offset(child.mLeft, child.mTop); 4374 4375 if (!(parent instanceof View)) { 4376 break; 4377 } 4378 4379 View parentView = (View) parent; 4380 4381 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4382 4383 child = parentView; 4384 parent = child.getParent(); 4385 } 4386 4387 return scrolled; 4388 } 4389 4390 /** 4391 * Called when this view wants to give up focus. If focus is cleared 4392 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4393 * <p> 4394 * <strong>Note:</strong> When a View clears focus the framework is trying 4395 * to give focus to the first focusable View from the top. Hence, if this 4396 * View is the first from the top that can take focus, then all callbacks 4397 * related to clearing focus will be invoked after wich the framework will 4398 * give focus to this view. 4399 * </p> 4400 */ 4401 public void clearFocus() { 4402 if (DBG) { 4403 System.out.println(this + " clearFocus()"); 4404 } 4405 4406 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4407 mPrivateFlags &= ~PFLAG_FOCUSED; 4408 4409 if (mParent != null) { 4410 mParent.clearChildFocus(this); 4411 } 4412 4413 onFocusChanged(false, 0, null); 4414 4415 refreshDrawableState(); 4416 4417 ensureInputFocusOnFirstFocusable(); 4418 4419 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4420 notifyAccessibilityStateChanged(); 4421 } 4422 } 4423 } 4424 4425 void ensureInputFocusOnFirstFocusable() { 4426 View root = getRootView(); 4427 if (root != null) { 4428 root.requestFocus(); 4429 } 4430 } 4431 4432 /** 4433 * Called internally by the view system when a new view is getting focus. 4434 * This is what clears the old focus. 4435 */ 4436 void unFocus() { 4437 if (DBG) { 4438 System.out.println(this + " unFocus()"); 4439 } 4440 4441 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4442 mPrivateFlags &= ~PFLAG_FOCUSED; 4443 4444 onFocusChanged(false, 0, null); 4445 refreshDrawableState(); 4446 4447 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4448 notifyAccessibilityStateChanged(); 4449 } 4450 } 4451 } 4452 4453 /** 4454 * Returns true if this view has focus iteself, or is the ancestor of the 4455 * view that has focus. 4456 * 4457 * @return True if this view has or contains focus, false otherwise. 4458 */ 4459 @ViewDebug.ExportedProperty(category = "focus") 4460 public boolean hasFocus() { 4461 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4462 } 4463 4464 /** 4465 * Returns true if this view is focusable or if it contains a reachable View 4466 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4467 * is a View whose parents do not block descendants focus. 4468 * 4469 * Only {@link #VISIBLE} views are considered focusable. 4470 * 4471 * @return True if the view is focusable or if the view contains a focusable 4472 * View, false otherwise. 4473 * 4474 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4475 */ 4476 public boolean hasFocusable() { 4477 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4478 } 4479 4480 /** 4481 * Called by the view system when the focus state of this view changes. 4482 * When the focus change event is caused by directional navigation, direction 4483 * and previouslyFocusedRect provide insight into where the focus is coming from. 4484 * When overriding, be sure to call up through to the super class so that 4485 * the standard focus handling will occur. 4486 * 4487 * @param gainFocus True if the View has focus; false otherwise. 4488 * @param direction The direction focus has moved when requestFocus() 4489 * is called to give this view focus. Values are 4490 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4491 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4492 * It may not always apply, in which case use the default. 4493 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4494 * system, of the previously focused view. If applicable, this will be 4495 * passed in as finer grained information about where the focus is coming 4496 * from (in addition to direction). Will be <code>null</code> otherwise. 4497 */ 4498 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 4499 if (gainFocus) { 4500 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4501 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4502 } 4503 } 4504 4505 InputMethodManager imm = InputMethodManager.peekInstance(); 4506 if (!gainFocus) { 4507 if (isPressed()) { 4508 setPressed(false); 4509 } 4510 if (imm != null && mAttachInfo != null 4511 && mAttachInfo.mHasWindowFocus) { 4512 imm.focusOut(this); 4513 } 4514 onFocusLost(); 4515 } else if (imm != null && mAttachInfo != null 4516 && mAttachInfo.mHasWindowFocus) { 4517 imm.focusIn(this); 4518 } 4519 4520 invalidate(true); 4521 ListenerInfo li = mListenerInfo; 4522 if (li != null && li.mOnFocusChangeListener != null) { 4523 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 4524 } 4525 4526 if (mAttachInfo != null) { 4527 mAttachInfo.mKeyDispatchState.reset(this); 4528 } 4529 } 4530 4531 /** 4532 * Sends an accessibility event of the given type. If accessibility is 4533 * not enabled this method has no effect. The default implementation calls 4534 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 4535 * to populate information about the event source (this View), then calls 4536 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 4537 * populate the text content of the event source including its descendants, 4538 * and last calls 4539 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 4540 * on its parent to resuest sending of the event to interested parties. 4541 * <p> 4542 * If an {@link AccessibilityDelegate} has been specified via calling 4543 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4544 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 4545 * responsible for handling this call. 4546 * </p> 4547 * 4548 * @param eventType The type of the event to send, as defined by several types from 4549 * {@link android.view.accessibility.AccessibilityEvent}, such as 4550 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 4551 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 4552 * 4553 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4554 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4555 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 4556 * @see AccessibilityDelegate 4557 */ 4558 public void sendAccessibilityEvent(int eventType) { 4559 if (mAccessibilityDelegate != null) { 4560 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 4561 } else { 4562 sendAccessibilityEventInternal(eventType); 4563 } 4564 } 4565 4566 /** 4567 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 4568 * {@link AccessibilityEvent} to make an announcement which is related to some 4569 * sort of a context change for which none of the events representing UI transitions 4570 * is a good fit. For example, announcing a new page in a book. If accessibility 4571 * is not enabled this method does nothing. 4572 * 4573 * @param text The announcement text. 4574 */ 4575 public void announceForAccessibility(CharSequence text) { 4576 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 4577 AccessibilityEvent event = AccessibilityEvent.obtain( 4578 AccessibilityEvent.TYPE_ANNOUNCEMENT); 4579 onInitializeAccessibilityEvent(event); 4580 event.getText().add(text); 4581 event.setContentDescription(null); 4582 mParent.requestSendAccessibilityEvent(this, event); 4583 } 4584 } 4585 4586 /** 4587 * @see #sendAccessibilityEvent(int) 4588 * 4589 * Note: Called from the default {@link AccessibilityDelegate}. 4590 */ 4591 void sendAccessibilityEventInternal(int eventType) { 4592 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4593 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 4594 } 4595 } 4596 4597 /** 4598 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 4599 * takes as an argument an empty {@link AccessibilityEvent} and does not 4600 * perform a check whether accessibility is enabled. 4601 * <p> 4602 * If an {@link AccessibilityDelegate} has been specified via calling 4603 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4604 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 4605 * is responsible for handling this call. 4606 * </p> 4607 * 4608 * @param event The event to send. 4609 * 4610 * @see #sendAccessibilityEvent(int) 4611 */ 4612 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 4613 if (mAccessibilityDelegate != null) { 4614 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 4615 } else { 4616 sendAccessibilityEventUncheckedInternal(event); 4617 } 4618 } 4619 4620 /** 4621 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 4622 * 4623 * Note: Called from the default {@link AccessibilityDelegate}. 4624 */ 4625 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 4626 if (!isShown()) { 4627 return; 4628 } 4629 onInitializeAccessibilityEvent(event); 4630 // Only a subset of accessibility events populates text content. 4631 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4632 dispatchPopulateAccessibilityEvent(event); 4633 } 4634 // In the beginning we called #isShown(), so we know that getParent() is not null. 4635 getParent().requestSendAccessibilityEvent(this, event); 4636 } 4637 4638 /** 4639 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4640 * to its children for adding their text content to the event. Note that the 4641 * event text is populated in a separate dispatch path since we add to the 4642 * event not only the text of the source but also the text of all its descendants. 4643 * A typical implementation will call 4644 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4645 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4646 * on each child. Override this method if custom population of the event text 4647 * content is required. 4648 * <p> 4649 * If an {@link AccessibilityDelegate} has been specified via calling 4650 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4651 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4652 * is responsible for handling this call. 4653 * </p> 4654 * <p> 4655 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4656 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4657 * </p> 4658 * 4659 * @param event The event. 4660 * 4661 * @return True if the event population was completed. 4662 */ 4663 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4664 if (mAccessibilityDelegate != null) { 4665 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4666 } else { 4667 return dispatchPopulateAccessibilityEventInternal(event); 4668 } 4669 } 4670 4671 /** 4672 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4673 * 4674 * Note: Called from the default {@link AccessibilityDelegate}. 4675 */ 4676 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4677 onPopulateAccessibilityEvent(event); 4678 return false; 4679 } 4680 4681 /** 4682 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4683 * giving a chance to this View to populate the accessibility event with its 4684 * text content. While this method is free to modify event 4685 * attributes other than text content, doing so should normally be performed in 4686 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4687 * <p> 4688 * Example: Adding formatted date string to an accessibility event in addition 4689 * to the text added by the super implementation: 4690 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4691 * super.onPopulateAccessibilityEvent(event); 4692 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4693 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4694 * mCurrentDate.getTimeInMillis(), flags); 4695 * event.getText().add(selectedDateUtterance); 4696 * }</pre> 4697 * <p> 4698 * If an {@link AccessibilityDelegate} has been specified via calling 4699 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4700 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 4701 * is responsible for handling this call. 4702 * </p> 4703 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4704 * information to the event, in case the default implementation has basic information to add. 4705 * </p> 4706 * 4707 * @param event The accessibility event which to populate. 4708 * 4709 * @see #sendAccessibilityEvent(int) 4710 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4711 */ 4712 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4713 if (mAccessibilityDelegate != null) { 4714 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 4715 } else { 4716 onPopulateAccessibilityEventInternal(event); 4717 } 4718 } 4719 4720 /** 4721 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 4722 * 4723 * Note: Called from the default {@link AccessibilityDelegate}. 4724 */ 4725 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4726 4727 } 4728 4729 /** 4730 * Initializes an {@link AccessibilityEvent} with information about 4731 * this View which is the event source. In other words, the source of 4732 * an accessibility event is the view whose state change triggered firing 4733 * the event. 4734 * <p> 4735 * Example: Setting the password property of an event in addition 4736 * to properties set by the super implementation: 4737 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4738 * super.onInitializeAccessibilityEvent(event); 4739 * event.setPassword(true); 4740 * }</pre> 4741 * <p> 4742 * If an {@link AccessibilityDelegate} has been specified via calling 4743 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4744 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4745 * is responsible for handling this call. 4746 * </p> 4747 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4748 * information to the event, in case the default implementation has basic information to add. 4749 * </p> 4750 * @param event The event to initialize. 4751 * 4752 * @see #sendAccessibilityEvent(int) 4753 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4754 */ 4755 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4756 if (mAccessibilityDelegate != null) { 4757 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 4758 } else { 4759 onInitializeAccessibilityEventInternal(event); 4760 } 4761 } 4762 4763 /** 4764 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4765 * 4766 * Note: Called from the default {@link AccessibilityDelegate}. 4767 */ 4768 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 4769 event.setSource(this); 4770 event.setClassName(View.class.getName()); 4771 event.setPackageName(getContext().getPackageName()); 4772 event.setEnabled(isEnabled()); 4773 event.setContentDescription(mContentDescription); 4774 4775 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 4776 ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList; 4777 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 4778 FOCUSABLES_ALL); 4779 event.setItemCount(focusablesTempList.size()); 4780 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4781 focusablesTempList.clear(); 4782 } 4783 } 4784 4785 /** 4786 * Returns an {@link AccessibilityNodeInfo} representing this view from the 4787 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 4788 * This method is responsible for obtaining an accessibility node info from a 4789 * pool of reusable instances and calling 4790 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 4791 * initialize the former. 4792 * <p> 4793 * Note: The client is responsible for recycling the obtained instance by calling 4794 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4795 * </p> 4796 * 4797 * @return A populated {@link AccessibilityNodeInfo}. 4798 * 4799 * @see AccessibilityNodeInfo 4800 */ 4801 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4802 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 4803 if (provider != null) { 4804 return provider.createAccessibilityNodeInfo(View.NO_ID); 4805 } else { 4806 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4807 onInitializeAccessibilityNodeInfo(info); 4808 return info; 4809 } 4810 } 4811 4812 /** 4813 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4814 * The base implementation sets: 4815 * <ul> 4816 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4817 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4818 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4819 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4820 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4821 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4822 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4823 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4824 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4825 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4826 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4827 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4828 * </ul> 4829 * <p> 4830 * Subclasses should override this method, call the super implementation, 4831 * and set additional attributes. 4832 * </p> 4833 * <p> 4834 * If an {@link AccessibilityDelegate} has been specified via calling 4835 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4836 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 4837 * is responsible for handling this call. 4838 * </p> 4839 * 4840 * @param info The instance to initialize. 4841 */ 4842 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 4843 if (mAccessibilityDelegate != null) { 4844 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 4845 } else { 4846 onInitializeAccessibilityNodeInfoInternal(info); 4847 } 4848 } 4849 4850 /** 4851 * Gets the location of this view in screen coordintates. 4852 * 4853 * @param outRect The output location 4854 */ 4855 private void getBoundsOnScreen(Rect outRect) { 4856 if (mAttachInfo == null) { 4857 return; 4858 } 4859 4860 RectF position = mAttachInfo.mTmpTransformRect; 4861 position.set(0, 0, mRight - mLeft, mBottom - mTop); 4862 4863 if (!hasIdentityMatrix()) { 4864 getMatrix().mapRect(position); 4865 } 4866 4867 position.offset(mLeft, mTop); 4868 4869 ViewParent parent = mParent; 4870 while (parent instanceof View) { 4871 View parentView = (View) parent; 4872 4873 position.offset(-parentView.mScrollX, -parentView.mScrollY); 4874 4875 if (!parentView.hasIdentityMatrix()) { 4876 parentView.getMatrix().mapRect(position); 4877 } 4878 4879 position.offset(parentView.mLeft, parentView.mTop); 4880 4881 parent = parentView.mParent; 4882 } 4883 4884 if (parent instanceof ViewRootImpl) { 4885 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 4886 position.offset(0, -viewRootImpl.mCurScrollY); 4887 } 4888 4889 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 4890 4891 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 4892 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 4893 } 4894 4895 /** 4896 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 4897 * 4898 * Note: Called from the default {@link AccessibilityDelegate}. 4899 */ 4900 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 4901 Rect bounds = mAttachInfo.mTmpInvalRect; 4902 4903 getDrawingRect(bounds); 4904 info.setBoundsInParent(bounds); 4905 4906 getBoundsOnScreen(bounds); 4907 info.setBoundsInScreen(bounds); 4908 4909 ViewParent parent = getParentForAccessibility(); 4910 if (parent instanceof View) { 4911 info.setParent((View) parent); 4912 } 4913 4914 if (mID != View.NO_ID) { 4915 View rootView = getRootView(); 4916 if (rootView == null) { 4917 rootView = this; 4918 } 4919 View label = rootView.findLabelForView(this, mID); 4920 if (label != null) { 4921 info.setLabeledBy(label); 4922 } 4923 } 4924 4925 if (mLabelForId != View.NO_ID) { 4926 View rootView = getRootView(); 4927 if (rootView == null) { 4928 rootView = this; 4929 } 4930 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 4931 if (labeled != null) { 4932 info.setLabelFor(labeled); 4933 } 4934 } 4935 4936 info.setVisibleToUser(isVisibleToUser()); 4937 4938 info.setPackageName(mContext.getPackageName()); 4939 info.setClassName(View.class.getName()); 4940 info.setContentDescription(getContentDescription()); 4941 4942 info.setEnabled(isEnabled()); 4943 info.setClickable(isClickable()); 4944 info.setFocusable(isFocusable()); 4945 info.setFocused(isFocused()); 4946 info.setAccessibilityFocused(isAccessibilityFocused()); 4947 info.setSelected(isSelected()); 4948 info.setLongClickable(isLongClickable()); 4949 4950 // TODO: These make sense only if we are in an AdapterView but all 4951 // views can be selected. Maybe from accessibility perspective 4952 // we should report as selectable view in an AdapterView. 4953 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 4954 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 4955 4956 if (isFocusable()) { 4957 if (isFocused()) { 4958 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 4959 } else { 4960 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 4961 } 4962 } 4963 4964 if (!isAccessibilityFocused()) { 4965 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 4966 } else { 4967 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 4968 } 4969 4970 if (isClickable() && isEnabled()) { 4971 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 4972 } 4973 4974 if (isLongClickable() && isEnabled()) { 4975 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 4976 } 4977 4978 if (mContentDescription != null && mContentDescription.length() > 0) { 4979 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 4980 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 4981 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 4982 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 4983 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 4984 } 4985 } 4986 4987 private View findLabelForView(View view, int labeledId) { 4988 if (mMatchLabelForPredicate == null) { 4989 mMatchLabelForPredicate = new MatchLabelForPredicate(); 4990 } 4991 mMatchLabelForPredicate.mLabeledId = labeledId; 4992 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 4993 } 4994 4995 /** 4996 * Computes whether this view is visible to the user. Such a view is 4997 * attached, visible, all its predecessors are visible, it is not clipped 4998 * entirely by its predecessors, and has an alpha greater than zero. 4999 * 5000 * @return Whether the view is visible on the screen. 5001 * 5002 * @hide 5003 */ 5004 protected boolean isVisibleToUser() { 5005 return isVisibleToUser(null); 5006 } 5007 5008 /** 5009 * Computes whether the given portion of this view is visible to the user. 5010 * Such a view is attached, visible, all its predecessors are visible, 5011 * has an alpha greater than zero, and the specified portion is not 5012 * clipped entirely by its predecessors. 5013 * 5014 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5015 * <code>null</code>, and the entire view will be tested in this case. 5016 * When <code>true</code> is returned by the function, the actual visible 5017 * region will be stored in this parameter; that is, if boundInView is fully 5018 * contained within the view, no modification will be made, otherwise regions 5019 * outside of the visible area of the view will be clipped. 5020 * 5021 * @return Whether the specified portion of the view is visible on the screen. 5022 * 5023 * @hide 5024 */ 5025 protected boolean isVisibleToUser(Rect boundInView) { 5026 if (mAttachInfo != null) { 5027 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5028 Point offset = mAttachInfo.mPoint; 5029 // The first two checks are made also made by isShown() which 5030 // however traverses the tree up to the parent to catch that. 5031 // Therefore, we do some fail fast check to minimize the up 5032 // tree traversal. 5033 boolean isVisible = mAttachInfo.mWindowVisibility == View.VISIBLE 5034 && getAlpha() > 0 5035 && isShown() 5036 && getGlobalVisibleRect(visibleRect, offset); 5037 if (isVisible && boundInView != null) { 5038 visibleRect.offset(-offset.x, -offset.y); 5039 // isVisible is always true here, use a simple assignment 5040 isVisible = boundInView.intersect(visibleRect); 5041 } 5042 return isVisible; 5043 } 5044 5045 return false; 5046 } 5047 5048 /** 5049 * Returns the delegate for implementing accessibility support via 5050 * composition. For more details see {@link AccessibilityDelegate}. 5051 * 5052 * @return The delegate, or null if none set. 5053 * 5054 * @hide 5055 */ 5056 public AccessibilityDelegate getAccessibilityDelegate() { 5057 return mAccessibilityDelegate; 5058 } 5059 5060 /** 5061 * Sets a delegate for implementing accessibility support via composition as 5062 * opposed to inheritance. The delegate's primary use is for implementing 5063 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5064 * 5065 * @param delegate The delegate instance. 5066 * 5067 * @see AccessibilityDelegate 5068 */ 5069 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5070 mAccessibilityDelegate = delegate; 5071 } 5072 5073 /** 5074 * Gets the provider for managing a virtual view hierarchy rooted at this View 5075 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5076 * that explore the window content. 5077 * <p> 5078 * If this method returns an instance, this instance is responsible for managing 5079 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5080 * View including the one representing the View itself. Similarly the returned 5081 * instance is responsible for performing accessibility actions on any virtual 5082 * view or the root view itself. 5083 * </p> 5084 * <p> 5085 * If an {@link AccessibilityDelegate} has been specified via calling 5086 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5087 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5088 * is responsible for handling this call. 5089 * </p> 5090 * 5091 * @return The provider. 5092 * 5093 * @see AccessibilityNodeProvider 5094 */ 5095 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5096 if (mAccessibilityDelegate != null) { 5097 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5098 } else { 5099 return null; 5100 } 5101 } 5102 5103 /** 5104 * Gets the unique identifier of this view on the screen for accessibility purposes. 5105 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5106 * 5107 * @return The view accessibility id. 5108 * 5109 * @hide 5110 */ 5111 public int getAccessibilityViewId() { 5112 if (mAccessibilityViewId == NO_ID) { 5113 mAccessibilityViewId = sNextAccessibilityViewId++; 5114 } 5115 return mAccessibilityViewId; 5116 } 5117 5118 /** 5119 * Gets the unique identifier of the window in which this View reseides. 5120 * 5121 * @return The window accessibility id. 5122 * 5123 * @hide 5124 */ 5125 public int getAccessibilityWindowId() { 5126 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 5127 } 5128 5129 /** 5130 * Gets the {@link View} description. It briefly describes the view and is 5131 * primarily used for accessibility support. Set this property to enable 5132 * better accessibility support for your application. This is especially 5133 * true for views that do not have textual representation (For example, 5134 * ImageButton). 5135 * 5136 * @return The content description. 5137 * 5138 * @attr ref android.R.styleable#View_contentDescription 5139 */ 5140 @ViewDebug.ExportedProperty(category = "accessibility") 5141 public CharSequence getContentDescription() { 5142 return mContentDescription; 5143 } 5144 5145 /** 5146 * Sets the {@link View} description. It briefly describes the view and is 5147 * primarily used for accessibility support. Set this property to enable 5148 * better accessibility support for your application. This is especially 5149 * true for views that do not have textual representation (For example, 5150 * ImageButton). 5151 * 5152 * @param contentDescription The content description. 5153 * 5154 * @attr ref android.R.styleable#View_contentDescription 5155 */ 5156 @RemotableViewMethod 5157 public void setContentDescription(CharSequence contentDescription) { 5158 mContentDescription = contentDescription; 5159 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5160 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5161 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5162 } 5163 } 5164 5165 /** 5166 * Gets the id of a view for which this view serves as a label for 5167 * accessibility purposes. 5168 * 5169 * @return The labeled view id. 5170 */ 5171 @ViewDebug.ExportedProperty(category = "accessibility") 5172 public int getLabelFor() { 5173 return mLabelForId; 5174 } 5175 5176 /** 5177 * Sets the id of a view for which this view serves as a label for 5178 * accessibility purposes. 5179 * 5180 * @param id The labeled view id. 5181 */ 5182 @RemotableViewMethod 5183 public void setLabelFor(int id) { 5184 mLabelForId = id; 5185 if (mLabelForId != View.NO_ID 5186 && mID == View.NO_ID) { 5187 mID = generateViewId(); 5188 } 5189 } 5190 5191 /** 5192 * Invoked whenever this view loses focus, either by losing window focus or by losing 5193 * focus within its window. This method can be used to clear any state tied to the 5194 * focus. For instance, if a button is held pressed with the trackball and the window 5195 * loses focus, this method can be used to cancel the press. 5196 * 5197 * Subclasses of View overriding this method should always call super.onFocusLost(). 5198 * 5199 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5200 * @see #onWindowFocusChanged(boolean) 5201 * 5202 * @hide pending API council approval 5203 */ 5204 protected void onFocusLost() { 5205 resetPressedState(); 5206 } 5207 5208 private void resetPressedState() { 5209 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5210 return; 5211 } 5212 5213 if (isPressed()) { 5214 setPressed(false); 5215 5216 if (!mHasPerformedLongPress) { 5217 removeLongPressCallback(); 5218 } 5219 } 5220 } 5221 5222 /** 5223 * Returns true if this view has focus 5224 * 5225 * @return True if this view has focus, false otherwise. 5226 */ 5227 @ViewDebug.ExportedProperty(category = "focus") 5228 public boolean isFocused() { 5229 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5230 } 5231 5232 /** 5233 * Find the view in the hierarchy rooted at this view that currently has 5234 * focus. 5235 * 5236 * @return The view that currently has focus, or null if no focused view can 5237 * be found. 5238 */ 5239 public View findFocus() { 5240 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5241 } 5242 5243 /** 5244 * Indicates whether this view is one of the set of scrollable containers in 5245 * its window. 5246 * 5247 * @return whether this view is one of the set of scrollable containers in 5248 * its window 5249 * 5250 * @attr ref android.R.styleable#View_isScrollContainer 5251 */ 5252 public boolean isScrollContainer() { 5253 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5254 } 5255 5256 /** 5257 * Change whether this view is one of the set of scrollable containers in 5258 * its window. This will be used to determine whether the window can 5259 * resize or must pan when a soft input area is open -- scrollable 5260 * containers allow the window to use resize mode since the container 5261 * will appropriately shrink. 5262 * 5263 * @attr ref android.R.styleable#View_isScrollContainer 5264 */ 5265 public void setScrollContainer(boolean isScrollContainer) { 5266 if (isScrollContainer) { 5267 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5268 mAttachInfo.mScrollContainers.add(this); 5269 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5270 } 5271 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5272 } else { 5273 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5274 mAttachInfo.mScrollContainers.remove(this); 5275 } 5276 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5277 } 5278 } 5279 5280 /** 5281 * Returns the quality of the drawing cache. 5282 * 5283 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5284 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5285 * 5286 * @see #setDrawingCacheQuality(int) 5287 * @see #setDrawingCacheEnabled(boolean) 5288 * @see #isDrawingCacheEnabled() 5289 * 5290 * @attr ref android.R.styleable#View_drawingCacheQuality 5291 */ 5292 public int getDrawingCacheQuality() { 5293 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5294 } 5295 5296 /** 5297 * Set the drawing cache quality of this view. This value is used only when the 5298 * drawing cache is enabled 5299 * 5300 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5301 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5302 * 5303 * @see #getDrawingCacheQuality() 5304 * @see #setDrawingCacheEnabled(boolean) 5305 * @see #isDrawingCacheEnabled() 5306 * 5307 * @attr ref android.R.styleable#View_drawingCacheQuality 5308 */ 5309 public void setDrawingCacheQuality(int quality) { 5310 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5311 } 5312 5313 /** 5314 * Returns whether the screen should remain on, corresponding to the current 5315 * value of {@link #KEEP_SCREEN_ON}. 5316 * 5317 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5318 * 5319 * @see #setKeepScreenOn(boolean) 5320 * 5321 * @attr ref android.R.styleable#View_keepScreenOn 5322 */ 5323 public boolean getKeepScreenOn() { 5324 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5325 } 5326 5327 /** 5328 * Controls whether the screen should remain on, modifying the 5329 * value of {@link #KEEP_SCREEN_ON}. 5330 * 5331 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5332 * 5333 * @see #getKeepScreenOn() 5334 * 5335 * @attr ref android.R.styleable#View_keepScreenOn 5336 */ 5337 public void setKeepScreenOn(boolean keepScreenOn) { 5338 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5339 } 5340 5341 /** 5342 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5343 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5344 * 5345 * @attr ref android.R.styleable#View_nextFocusLeft 5346 */ 5347 public int getNextFocusLeftId() { 5348 return mNextFocusLeftId; 5349 } 5350 5351 /** 5352 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5353 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5354 * decide automatically. 5355 * 5356 * @attr ref android.R.styleable#View_nextFocusLeft 5357 */ 5358 public void setNextFocusLeftId(int nextFocusLeftId) { 5359 mNextFocusLeftId = nextFocusLeftId; 5360 } 5361 5362 /** 5363 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5364 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5365 * 5366 * @attr ref android.R.styleable#View_nextFocusRight 5367 */ 5368 public int getNextFocusRightId() { 5369 return mNextFocusRightId; 5370 } 5371 5372 /** 5373 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5374 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5375 * decide automatically. 5376 * 5377 * @attr ref android.R.styleable#View_nextFocusRight 5378 */ 5379 public void setNextFocusRightId(int nextFocusRightId) { 5380 mNextFocusRightId = nextFocusRightId; 5381 } 5382 5383 /** 5384 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5385 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5386 * 5387 * @attr ref android.R.styleable#View_nextFocusUp 5388 */ 5389 public int getNextFocusUpId() { 5390 return mNextFocusUpId; 5391 } 5392 5393 /** 5394 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5395 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5396 * decide automatically. 5397 * 5398 * @attr ref android.R.styleable#View_nextFocusUp 5399 */ 5400 public void setNextFocusUpId(int nextFocusUpId) { 5401 mNextFocusUpId = nextFocusUpId; 5402 } 5403 5404 /** 5405 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5406 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5407 * 5408 * @attr ref android.R.styleable#View_nextFocusDown 5409 */ 5410 public int getNextFocusDownId() { 5411 return mNextFocusDownId; 5412 } 5413 5414 /** 5415 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5416 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5417 * decide automatically. 5418 * 5419 * @attr ref android.R.styleable#View_nextFocusDown 5420 */ 5421 public void setNextFocusDownId(int nextFocusDownId) { 5422 mNextFocusDownId = nextFocusDownId; 5423 } 5424 5425 /** 5426 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5427 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5428 * 5429 * @attr ref android.R.styleable#View_nextFocusForward 5430 */ 5431 public int getNextFocusForwardId() { 5432 return mNextFocusForwardId; 5433 } 5434 5435 /** 5436 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5437 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 5438 * decide automatically. 5439 * 5440 * @attr ref android.R.styleable#View_nextFocusForward 5441 */ 5442 public void setNextFocusForwardId(int nextFocusForwardId) { 5443 mNextFocusForwardId = nextFocusForwardId; 5444 } 5445 5446 /** 5447 * Returns the visibility of this view and all of its ancestors 5448 * 5449 * @return True if this view and all of its ancestors are {@link #VISIBLE} 5450 */ 5451 public boolean isShown() { 5452 View current = this; 5453 //noinspection ConstantConditions 5454 do { 5455 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5456 return false; 5457 } 5458 ViewParent parent = current.mParent; 5459 if (parent == null) { 5460 return false; // We are not attached to the view root 5461 } 5462 if (!(parent instanceof View)) { 5463 return true; 5464 } 5465 current = (View) parent; 5466 } while (current != null); 5467 5468 return false; 5469 } 5470 5471 /** 5472 * Called by the view hierarchy when the content insets for a window have 5473 * changed, to allow it to adjust its content to fit within those windows. 5474 * The content insets tell you the space that the status bar, input method, 5475 * and other system windows infringe on the application's window. 5476 * 5477 * <p>You do not normally need to deal with this function, since the default 5478 * window decoration given to applications takes care of applying it to the 5479 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 5480 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 5481 * and your content can be placed under those system elements. You can then 5482 * use this method within your view hierarchy if you have parts of your UI 5483 * which you would like to ensure are not being covered. 5484 * 5485 * <p>The default implementation of this method simply applies the content 5486 * inset's to the view's padding, consuming that content (modifying the 5487 * insets to be 0), and returning true. This behavior is off by default, but can 5488 * be enabled through {@link #setFitsSystemWindows(boolean)}. 5489 * 5490 * <p>This function's traversal down the hierarchy is depth-first. The same content 5491 * insets object is propagated down the hierarchy, so any changes made to it will 5492 * be seen by all following views (including potentially ones above in 5493 * the hierarchy since this is a depth-first traversal). The first view 5494 * that returns true will abort the entire traversal. 5495 * 5496 * <p>The default implementation works well for a situation where it is 5497 * used with a container that covers the entire window, allowing it to 5498 * apply the appropriate insets to its content on all edges. If you need 5499 * a more complicated layout (such as two different views fitting system 5500 * windows, one on the top of the window, and one on the bottom), 5501 * you can override the method and handle the insets however you would like. 5502 * Note that the insets provided by the framework are always relative to the 5503 * far edges of the window, not accounting for the location of the called view 5504 * within that window. (In fact when this method is called you do not yet know 5505 * where the layout will place the view, as it is done before layout happens.) 5506 * 5507 * <p>Note: unlike many View methods, there is no dispatch phase to this 5508 * call. If you are overriding it in a ViewGroup and want to allow the 5509 * call to continue to your children, you must be sure to call the super 5510 * implementation. 5511 * 5512 * <p>Here is a sample layout that makes use of fitting system windows 5513 * to have controls for a video view placed inside of the window decorations 5514 * that it hides and shows. This can be used with code like the second 5515 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 5516 * 5517 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 5518 * 5519 * @param insets Current content insets of the window. Prior to 5520 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 5521 * the insets or else you and Android will be unhappy. 5522 * 5523 * @return Return true if this view applied the insets and it should not 5524 * continue propagating further down the hierarchy, false otherwise. 5525 * @see #getFitsSystemWindows() 5526 * @see #setFitsSystemWindows(boolean) 5527 * @see #setSystemUiVisibility(int) 5528 */ 5529 protected boolean fitSystemWindows(Rect insets) { 5530 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 5531 mUserPaddingStart = UNDEFINED_PADDING; 5532 mUserPaddingEnd = UNDEFINED_PADDING; 5533 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 5534 || mAttachInfo == null 5535 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 5536 internalSetPadding(insets.left, insets.top, insets.right, insets.bottom); 5537 return true; 5538 } else { 5539 internalSetPadding(0, 0, 0, 0); 5540 return false; 5541 } 5542 } 5543 return false; 5544 } 5545 5546 /** 5547 * Sets whether or not this view should account for system screen decorations 5548 * such as the status bar and inset its content; that is, controlling whether 5549 * the default implementation of {@link #fitSystemWindows(Rect)} will be 5550 * executed. See that method for more details. 5551 * 5552 * <p>Note that if you are providing your own implementation of 5553 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 5554 * flag to true -- your implementation will be overriding the default 5555 * implementation that checks this flag. 5556 * 5557 * @param fitSystemWindows If true, then the default implementation of 5558 * {@link #fitSystemWindows(Rect)} will be executed. 5559 * 5560 * @attr ref android.R.styleable#View_fitsSystemWindows 5561 * @see #getFitsSystemWindows() 5562 * @see #fitSystemWindows(Rect) 5563 * @see #setSystemUiVisibility(int) 5564 */ 5565 public void setFitsSystemWindows(boolean fitSystemWindows) { 5566 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 5567 } 5568 5569 /** 5570 * Check for state of {@link #setFitsSystemWindows(boolean). If this method 5571 * returns true, the default implementation of {@link #fitSystemWindows(Rect)} 5572 * will be executed. 5573 * 5574 * @return Returns true if the default implementation of 5575 * {@link #fitSystemWindows(Rect)} will be executed. 5576 * 5577 * @attr ref android.R.styleable#View_fitsSystemWindows 5578 * @see #setFitsSystemWindows() 5579 * @see #fitSystemWindows(Rect) 5580 * @see #setSystemUiVisibility(int) 5581 */ 5582 public boolean getFitsSystemWindows() { 5583 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 5584 } 5585 5586 /** @hide */ 5587 public boolean fitsSystemWindows() { 5588 return getFitsSystemWindows(); 5589 } 5590 5591 /** 5592 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 5593 */ 5594 public void requestFitSystemWindows() { 5595 if (mParent != null) { 5596 mParent.requestFitSystemWindows(); 5597 } 5598 } 5599 5600 /** 5601 * For use by PhoneWindow to make its own system window fitting optional. 5602 * @hide 5603 */ 5604 public void makeOptionalFitsSystemWindows() { 5605 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 5606 } 5607 5608 /** 5609 * Returns the visibility status for this view. 5610 * 5611 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5612 * @attr ref android.R.styleable#View_visibility 5613 */ 5614 @ViewDebug.ExportedProperty(mapping = { 5615 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 5616 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 5617 @ViewDebug.IntToString(from = GONE, to = "GONE") 5618 }) 5619 public int getVisibility() { 5620 return mViewFlags & VISIBILITY_MASK; 5621 } 5622 5623 /** 5624 * Set the enabled state of this view. 5625 * 5626 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5627 * @attr ref android.R.styleable#View_visibility 5628 */ 5629 @RemotableViewMethod 5630 public void setVisibility(int visibility) { 5631 setFlags(visibility, VISIBILITY_MASK); 5632 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 5633 } 5634 5635 /** 5636 * Returns the enabled status for this view. The interpretation of the 5637 * enabled state varies by subclass. 5638 * 5639 * @return True if this view is enabled, false otherwise. 5640 */ 5641 @ViewDebug.ExportedProperty 5642 public boolean isEnabled() { 5643 return (mViewFlags & ENABLED_MASK) == ENABLED; 5644 } 5645 5646 /** 5647 * Set the enabled state of this view. The interpretation of the enabled 5648 * state varies by subclass. 5649 * 5650 * @param enabled True if this view is enabled, false otherwise. 5651 */ 5652 @RemotableViewMethod 5653 public void setEnabled(boolean enabled) { 5654 if (enabled == isEnabled()) return; 5655 5656 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 5657 5658 /* 5659 * The View most likely has to change its appearance, so refresh 5660 * the drawable state. 5661 */ 5662 refreshDrawableState(); 5663 5664 // Invalidate too, since the default behavior for views is to be 5665 // be drawn at 50% alpha rather than to change the drawable. 5666 invalidate(true); 5667 } 5668 5669 /** 5670 * Set whether this view can receive the focus. 5671 * 5672 * Setting this to false will also ensure that this view is not focusable 5673 * in touch mode. 5674 * 5675 * @param focusable If true, this view can receive the focus. 5676 * 5677 * @see #setFocusableInTouchMode(boolean) 5678 * @attr ref android.R.styleable#View_focusable 5679 */ 5680 public void setFocusable(boolean focusable) { 5681 if (!focusable) { 5682 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 5683 } 5684 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 5685 } 5686 5687 /** 5688 * Set whether this view can receive focus while in touch mode. 5689 * 5690 * Setting this to true will also ensure that this view is focusable. 5691 * 5692 * @param focusableInTouchMode If true, this view can receive the focus while 5693 * in touch mode. 5694 * 5695 * @see #setFocusable(boolean) 5696 * @attr ref android.R.styleable#View_focusableInTouchMode 5697 */ 5698 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 5699 // Focusable in touch mode should always be set before the focusable flag 5700 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 5701 // which, in touch mode, will not successfully request focus on this view 5702 // because the focusable in touch mode flag is not set 5703 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 5704 if (focusableInTouchMode) { 5705 setFlags(FOCUSABLE, FOCUSABLE_MASK); 5706 } 5707 } 5708 5709 /** 5710 * Set whether this view should have sound effects enabled for events such as 5711 * clicking and touching. 5712 * 5713 * <p>You may wish to disable sound effects for a view if you already play sounds, 5714 * for instance, a dial key that plays dtmf tones. 5715 * 5716 * @param soundEffectsEnabled whether sound effects are enabled for this view. 5717 * @see #isSoundEffectsEnabled() 5718 * @see #playSoundEffect(int) 5719 * @attr ref android.R.styleable#View_soundEffectsEnabled 5720 */ 5721 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 5722 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 5723 } 5724 5725 /** 5726 * @return whether this view should have sound effects enabled for events such as 5727 * clicking and touching. 5728 * 5729 * @see #setSoundEffectsEnabled(boolean) 5730 * @see #playSoundEffect(int) 5731 * @attr ref android.R.styleable#View_soundEffectsEnabled 5732 */ 5733 @ViewDebug.ExportedProperty 5734 public boolean isSoundEffectsEnabled() { 5735 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 5736 } 5737 5738 /** 5739 * Set whether this view should have haptic feedback for events such as 5740 * long presses. 5741 * 5742 * <p>You may wish to disable haptic feedback if your view already controls 5743 * its own haptic feedback. 5744 * 5745 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 5746 * @see #isHapticFeedbackEnabled() 5747 * @see #performHapticFeedback(int) 5748 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5749 */ 5750 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 5751 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 5752 } 5753 5754 /** 5755 * @return whether this view should have haptic feedback enabled for events 5756 * long presses. 5757 * 5758 * @see #setHapticFeedbackEnabled(boolean) 5759 * @see #performHapticFeedback(int) 5760 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5761 */ 5762 @ViewDebug.ExportedProperty 5763 public boolean isHapticFeedbackEnabled() { 5764 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 5765 } 5766 5767 /** 5768 * Returns the layout direction for this view. 5769 * 5770 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 5771 * {@link #LAYOUT_DIRECTION_RTL}, 5772 * {@link #LAYOUT_DIRECTION_INHERIT} or 5773 * {@link #LAYOUT_DIRECTION_LOCALE}. 5774 * @attr ref android.R.styleable#View_layoutDirection 5775 */ 5776 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5777 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 5778 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 5779 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 5780 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 5781 }) 5782 public int getLayoutDirection() { 5783 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 5784 } 5785 5786 /** 5787 * Set the layout direction for this view. This will propagate a reset of layout direction 5788 * resolution to the view's children and resolve layout direction for this view. 5789 * 5790 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 5791 * {@link #LAYOUT_DIRECTION_RTL}, 5792 * {@link #LAYOUT_DIRECTION_INHERIT} or 5793 * {@link #LAYOUT_DIRECTION_LOCALE}. 5794 * 5795 * @attr ref android.R.styleable#View_layoutDirection 5796 */ 5797 @RemotableViewMethod 5798 public void setLayoutDirection(int layoutDirection) { 5799 if (getLayoutDirection() != layoutDirection) { 5800 // Reset the current layout direction and the resolved one 5801 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 5802 resetResolvedLayoutDirection(); 5803 // Reset padding resolution 5804 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 5805 // Set the new layout direction (filtered) 5806 mPrivateFlags2 |= 5807 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 5808 resolveRtlProperties(); 5809 // ... and ask for a layout pass 5810 requestLayout(); 5811 } 5812 } 5813 5814 /** 5815 * Returns the resolved layout direction for this view. 5816 * 5817 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 5818 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 5819 */ 5820 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5821 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 5822 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 5823 }) 5824 public int getResolvedLayoutDirection() { 5825 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 5826 if (targetSdkVersion < JELLY_BEAN_MR1) { 5827 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 5828 return LAYOUT_DIRECTION_LTR; 5829 } 5830 // The layout direction will be resolved only if needed 5831 if ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) != PFLAG2_LAYOUT_DIRECTION_RESOLVED) { 5832 resolveLayoutDirection(); 5833 } 5834 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? 5835 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 5836 } 5837 5838 /** 5839 * Indicates whether or not this view's layout is right-to-left. This is resolved from 5840 * layout attribute and/or the inherited value from the parent 5841 * 5842 * @return true if the layout is right-to-left. 5843 */ 5844 @ViewDebug.ExportedProperty(category = "layout") 5845 public boolean isLayoutRtl() { 5846 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 5847 } 5848 5849 /** 5850 * Indicates whether the view is currently tracking transient state that the 5851 * app should not need to concern itself with saving and restoring, but that 5852 * the framework should take special note to preserve when possible. 5853 * 5854 * <p>A view with transient state cannot be trivially rebound from an external 5855 * data source, such as an adapter binding item views in a list. This may be 5856 * because the view is performing an animation, tracking user selection 5857 * of content, or similar.</p> 5858 * 5859 * @return true if the view has transient state 5860 */ 5861 @ViewDebug.ExportedProperty(category = "layout") 5862 public boolean hasTransientState() { 5863 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 5864 } 5865 5866 /** 5867 * Set whether this view is currently tracking transient state that the 5868 * framework should attempt to preserve when possible. This flag is reference counted, 5869 * so every call to setHasTransientState(true) should be paired with a later call 5870 * to setHasTransientState(false). 5871 * 5872 * <p>A view with transient state cannot be trivially rebound from an external 5873 * data source, such as an adapter binding item views in a list. This may be 5874 * because the view is performing an animation, tracking user selection 5875 * of content, or similar.</p> 5876 * 5877 * @param hasTransientState true if this view has transient state 5878 */ 5879 public void setHasTransientState(boolean hasTransientState) { 5880 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 5881 mTransientStateCount - 1; 5882 if (mTransientStateCount < 0) { 5883 mTransientStateCount = 0; 5884 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 5885 "unmatched pair of setHasTransientState calls"); 5886 } 5887 if ((hasTransientState && mTransientStateCount == 1) || 5888 (!hasTransientState && mTransientStateCount == 0)) { 5889 // update flag if we've just incremented up from 0 or decremented down to 0 5890 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 5891 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 5892 if (mParent != null) { 5893 try { 5894 mParent.childHasTransientStateChanged(this, hasTransientState); 5895 } catch (AbstractMethodError e) { 5896 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 5897 " does not fully implement ViewParent", e); 5898 } 5899 } 5900 } 5901 } 5902 5903 /** 5904 * If this view doesn't do any drawing on its own, set this flag to 5905 * allow further optimizations. By default, this flag is not set on 5906 * View, but could be set on some View subclasses such as ViewGroup. 5907 * 5908 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 5909 * you should clear this flag. 5910 * 5911 * @param willNotDraw whether or not this View draw on its own 5912 */ 5913 public void setWillNotDraw(boolean willNotDraw) { 5914 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 5915 } 5916 5917 /** 5918 * Returns whether or not this View draws on its own. 5919 * 5920 * @return true if this view has nothing to draw, false otherwise 5921 */ 5922 @ViewDebug.ExportedProperty(category = "drawing") 5923 public boolean willNotDraw() { 5924 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 5925 } 5926 5927 /** 5928 * When a View's drawing cache is enabled, drawing is redirected to an 5929 * offscreen bitmap. Some views, like an ImageView, must be able to 5930 * bypass this mechanism if they already draw a single bitmap, to avoid 5931 * unnecessary usage of the memory. 5932 * 5933 * @param willNotCacheDrawing true if this view does not cache its 5934 * drawing, false otherwise 5935 */ 5936 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 5937 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 5938 } 5939 5940 /** 5941 * Returns whether or not this View can cache its drawing or not. 5942 * 5943 * @return true if this view does not cache its drawing, false otherwise 5944 */ 5945 @ViewDebug.ExportedProperty(category = "drawing") 5946 public boolean willNotCacheDrawing() { 5947 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 5948 } 5949 5950 /** 5951 * Indicates whether this view reacts to click events or not. 5952 * 5953 * @return true if the view is clickable, false otherwise 5954 * 5955 * @see #setClickable(boolean) 5956 * @attr ref android.R.styleable#View_clickable 5957 */ 5958 @ViewDebug.ExportedProperty 5959 public boolean isClickable() { 5960 return (mViewFlags & CLICKABLE) == CLICKABLE; 5961 } 5962 5963 /** 5964 * Enables or disables click events for this view. When a view 5965 * is clickable it will change its state to "pressed" on every click. 5966 * Subclasses should set the view clickable to visually react to 5967 * user's clicks. 5968 * 5969 * @param clickable true to make the view clickable, false otherwise 5970 * 5971 * @see #isClickable() 5972 * @attr ref android.R.styleable#View_clickable 5973 */ 5974 public void setClickable(boolean clickable) { 5975 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 5976 } 5977 5978 /** 5979 * Indicates whether this view reacts to long click events or not. 5980 * 5981 * @return true if the view is long clickable, false otherwise 5982 * 5983 * @see #setLongClickable(boolean) 5984 * @attr ref android.R.styleable#View_longClickable 5985 */ 5986 public boolean isLongClickable() { 5987 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 5988 } 5989 5990 /** 5991 * Enables or disables long click events for this view. When a view is long 5992 * clickable it reacts to the user holding down the button for a longer 5993 * duration than a tap. This event can either launch the listener or a 5994 * context menu. 5995 * 5996 * @param longClickable true to make the view long clickable, false otherwise 5997 * @see #isLongClickable() 5998 * @attr ref android.R.styleable#View_longClickable 5999 */ 6000 public void setLongClickable(boolean longClickable) { 6001 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6002 } 6003 6004 /** 6005 * Sets the pressed state for this view. 6006 * 6007 * @see #isClickable() 6008 * @see #setClickable(boolean) 6009 * 6010 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6011 * the View's internal state from a previously set "pressed" state. 6012 */ 6013 public void setPressed(boolean pressed) { 6014 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6015 6016 if (pressed) { 6017 mPrivateFlags |= PFLAG_PRESSED; 6018 } else { 6019 mPrivateFlags &= ~PFLAG_PRESSED; 6020 } 6021 6022 if (needsRefresh) { 6023 refreshDrawableState(); 6024 } 6025 dispatchSetPressed(pressed); 6026 } 6027 6028 /** 6029 * Dispatch setPressed to all of this View's children. 6030 * 6031 * @see #setPressed(boolean) 6032 * 6033 * @param pressed The new pressed state 6034 */ 6035 protected void dispatchSetPressed(boolean pressed) { 6036 } 6037 6038 /** 6039 * Indicates whether the view is currently in pressed state. Unless 6040 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6041 * the pressed state. 6042 * 6043 * @see #setPressed(boolean) 6044 * @see #isClickable() 6045 * @see #setClickable(boolean) 6046 * 6047 * @return true if the view is currently pressed, false otherwise 6048 */ 6049 public boolean isPressed() { 6050 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6051 } 6052 6053 /** 6054 * Indicates whether this view will save its state (that is, 6055 * whether its {@link #onSaveInstanceState} method will be called). 6056 * 6057 * @return Returns true if the view state saving is enabled, else false. 6058 * 6059 * @see #setSaveEnabled(boolean) 6060 * @attr ref android.R.styleable#View_saveEnabled 6061 */ 6062 public boolean isSaveEnabled() { 6063 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6064 } 6065 6066 /** 6067 * Controls whether the saving of this view's state is 6068 * enabled (that is, whether its {@link #onSaveInstanceState} method 6069 * will be called). Note that even if freezing is enabled, the 6070 * view still must have an id assigned to it (via {@link #setId(int)}) 6071 * for its state to be saved. This flag can only disable the 6072 * saving of this view; any child views may still have their state saved. 6073 * 6074 * @param enabled Set to false to <em>disable</em> state saving, or true 6075 * (the default) to allow it. 6076 * 6077 * @see #isSaveEnabled() 6078 * @see #setId(int) 6079 * @see #onSaveInstanceState() 6080 * @attr ref android.R.styleable#View_saveEnabled 6081 */ 6082 public void setSaveEnabled(boolean enabled) { 6083 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6084 } 6085 6086 /** 6087 * Gets whether the framework should discard touches when the view's 6088 * window is obscured by another visible window. 6089 * Refer to the {@link View} security documentation for more details. 6090 * 6091 * @return True if touch filtering is enabled. 6092 * 6093 * @see #setFilterTouchesWhenObscured(boolean) 6094 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6095 */ 6096 @ViewDebug.ExportedProperty 6097 public boolean getFilterTouchesWhenObscured() { 6098 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6099 } 6100 6101 /** 6102 * Sets whether the framework should discard touches when the view's 6103 * window is obscured by another visible window. 6104 * Refer to the {@link View} security documentation for more details. 6105 * 6106 * @param enabled True if touch filtering should be enabled. 6107 * 6108 * @see #getFilterTouchesWhenObscured 6109 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6110 */ 6111 public void setFilterTouchesWhenObscured(boolean enabled) { 6112 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 6113 FILTER_TOUCHES_WHEN_OBSCURED); 6114 } 6115 6116 /** 6117 * Indicates whether the entire hierarchy under this view will save its 6118 * state when a state saving traversal occurs from its parent. The default 6119 * is true; if false, these views will not be saved unless 6120 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6121 * 6122 * @return Returns true if the view state saving from parent is enabled, else false. 6123 * 6124 * @see #setSaveFromParentEnabled(boolean) 6125 */ 6126 public boolean isSaveFromParentEnabled() { 6127 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6128 } 6129 6130 /** 6131 * Controls whether the entire hierarchy under this view will save its 6132 * state when a state saving traversal occurs from its parent. The default 6133 * is true; if false, these views will not be saved unless 6134 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6135 * 6136 * @param enabled Set to false to <em>disable</em> state saving, or true 6137 * (the default) to allow it. 6138 * 6139 * @see #isSaveFromParentEnabled() 6140 * @see #setId(int) 6141 * @see #onSaveInstanceState() 6142 */ 6143 public void setSaveFromParentEnabled(boolean enabled) { 6144 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6145 } 6146 6147 6148 /** 6149 * Returns whether this View is able to take focus. 6150 * 6151 * @return True if this view can take focus, or false otherwise. 6152 * @attr ref android.R.styleable#View_focusable 6153 */ 6154 @ViewDebug.ExportedProperty(category = "focus") 6155 public final boolean isFocusable() { 6156 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6157 } 6158 6159 /** 6160 * When a view is focusable, it may not want to take focus when in touch mode. 6161 * For example, a button would like focus when the user is navigating via a D-pad 6162 * so that the user can click on it, but once the user starts touching the screen, 6163 * the button shouldn't take focus 6164 * @return Whether the view is focusable in touch mode. 6165 * @attr ref android.R.styleable#View_focusableInTouchMode 6166 */ 6167 @ViewDebug.ExportedProperty 6168 public final boolean isFocusableInTouchMode() { 6169 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6170 } 6171 6172 /** 6173 * Find the nearest view in the specified direction that can take focus. 6174 * This does not actually give focus to that view. 6175 * 6176 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6177 * 6178 * @return The nearest focusable in the specified direction, or null if none 6179 * can be found. 6180 */ 6181 public View focusSearch(int direction) { 6182 if (mParent != null) { 6183 return mParent.focusSearch(this, direction); 6184 } else { 6185 return null; 6186 } 6187 } 6188 6189 /** 6190 * This method is the last chance for the focused view and its ancestors to 6191 * respond to an arrow key. This is called when the focused view did not 6192 * consume the key internally, nor could the view system find a new view in 6193 * the requested direction to give focus to. 6194 * 6195 * @param focused The currently focused view. 6196 * @param direction The direction focus wants to move. One of FOCUS_UP, 6197 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6198 * @return True if the this view consumed this unhandled move. 6199 */ 6200 public boolean dispatchUnhandledMove(View focused, int direction) { 6201 return false; 6202 } 6203 6204 /** 6205 * If a user manually specified the next view id for a particular direction, 6206 * use the root to look up the view. 6207 * @param root The root view of the hierarchy containing this view. 6208 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6209 * or FOCUS_BACKWARD. 6210 * @return The user specified next view, or null if there is none. 6211 */ 6212 View findUserSetNextFocus(View root, int direction) { 6213 switch (direction) { 6214 case FOCUS_LEFT: 6215 if (mNextFocusLeftId == View.NO_ID) return null; 6216 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6217 case FOCUS_RIGHT: 6218 if (mNextFocusRightId == View.NO_ID) return null; 6219 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6220 case FOCUS_UP: 6221 if (mNextFocusUpId == View.NO_ID) return null; 6222 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6223 case FOCUS_DOWN: 6224 if (mNextFocusDownId == View.NO_ID) return null; 6225 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6226 case FOCUS_FORWARD: 6227 if (mNextFocusForwardId == View.NO_ID) return null; 6228 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6229 case FOCUS_BACKWARD: { 6230 if (mID == View.NO_ID) return null; 6231 final int id = mID; 6232 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6233 @Override 6234 public boolean apply(View t) { 6235 return t.mNextFocusForwardId == id; 6236 } 6237 }); 6238 } 6239 } 6240 return null; 6241 } 6242 6243 private View findViewInsideOutShouldExist(View root, int id) { 6244 if (mMatchIdPredicate == null) { 6245 mMatchIdPredicate = new MatchIdPredicate(); 6246 } 6247 mMatchIdPredicate.mId = id; 6248 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6249 if (result == null) { 6250 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6251 } 6252 return result; 6253 } 6254 6255 /** 6256 * Find and return all focusable views that are descendants of this view, 6257 * possibly including this view if it is focusable itself. 6258 * 6259 * @param direction The direction of the focus 6260 * @return A list of focusable views 6261 */ 6262 public ArrayList<View> getFocusables(int direction) { 6263 ArrayList<View> result = new ArrayList<View>(24); 6264 addFocusables(result, direction); 6265 return result; 6266 } 6267 6268 /** 6269 * Add any focusable views that are descendants of this view (possibly 6270 * including this view if it is focusable itself) to views. If we are in touch mode, 6271 * only add views that are also focusable in touch mode. 6272 * 6273 * @param views Focusable views found so far 6274 * @param direction The direction of the focus 6275 */ 6276 public void addFocusables(ArrayList<View> views, int direction) { 6277 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6278 } 6279 6280 /** 6281 * Adds any focusable views that are descendants of this view (possibly 6282 * including this view if it is focusable itself) to views. This method 6283 * adds all focusable views regardless if we are in touch mode or 6284 * only views focusable in touch mode if we are in touch mode or 6285 * only views that can take accessibility focus if accessibility is enabeld 6286 * depending on the focusable mode paramater. 6287 * 6288 * @param views Focusable views found so far or null if all we are interested is 6289 * the number of focusables. 6290 * @param direction The direction of the focus. 6291 * @param focusableMode The type of focusables to be added. 6292 * 6293 * @see #FOCUSABLES_ALL 6294 * @see #FOCUSABLES_TOUCH_MODE 6295 */ 6296 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 6297 if (views == null) { 6298 return; 6299 } 6300 if (!isFocusable()) { 6301 return; 6302 } 6303 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6304 && isInTouchMode() && !isFocusableInTouchMode()) { 6305 return; 6306 } 6307 views.add(this); 6308 } 6309 6310 /** 6311 * Finds the Views that contain given text. The containment is case insensitive. 6312 * The search is performed by either the text that the View renders or the content 6313 * description that describes the view for accessibility purposes and the view does 6314 * not render or both. Clients can specify how the search is to be performed via 6315 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 6316 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 6317 * 6318 * @param outViews The output list of matching Views. 6319 * @param searched The text to match against. 6320 * 6321 * @see #FIND_VIEWS_WITH_TEXT 6322 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 6323 * @see #setContentDescription(CharSequence) 6324 */ 6325 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 6326 if (getAccessibilityNodeProvider() != null) { 6327 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 6328 outViews.add(this); 6329 } 6330 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 6331 && (searched != null && searched.length() > 0) 6332 && (mContentDescription != null && mContentDescription.length() > 0)) { 6333 String searchedLowerCase = searched.toString().toLowerCase(); 6334 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 6335 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 6336 outViews.add(this); 6337 } 6338 } 6339 } 6340 6341 /** 6342 * Find and return all touchable views that are descendants of this view, 6343 * possibly including this view if it is touchable itself. 6344 * 6345 * @return A list of touchable views 6346 */ 6347 public ArrayList<View> getTouchables() { 6348 ArrayList<View> result = new ArrayList<View>(); 6349 addTouchables(result); 6350 return result; 6351 } 6352 6353 /** 6354 * Add any touchable views that are descendants of this view (possibly 6355 * including this view if it is touchable itself) to views. 6356 * 6357 * @param views Touchable views found so far 6358 */ 6359 public void addTouchables(ArrayList<View> views) { 6360 final int viewFlags = mViewFlags; 6361 6362 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 6363 && (viewFlags & ENABLED_MASK) == ENABLED) { 6364 views.add(this); 6365 } 6366 } 6367 6368 /** 6369 * Returns whether this View is accessibility focused. 6370 * 6371 * @return True if this View is accessibility focused. 6372 */ 6373 boolean isAccessibilityFocused() { 6374 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 6375 } 6376 6377 /** 6378 * Call this to try to give accessibility focus to this view. 6379 * 6380 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 6381 * returns false or the view is no visible or the view already has accessibility 6382 * focus. 6383 * 6384 * See also {@link #focusSearch(int)}, which is what you call to say that you 6385 * have focus, and you want your parent to look for the next one. 6386 * 6387 * @return Whether this view actually took accessibility focus. 6388 * 6389 * @hide 6390 */ 6391 public boolean requestAccessibilityFocus() { 6392 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 6393 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 6394 return false; 6395 } 6396 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6397 return false; 6398 } 6399 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 6400 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 6401 ViewRootImpl viewRootImpl = getViewRootImpl(); 6402 if (viewRootImpl != null) { 6403 viewRootImpl.setAccessibilityFocus(this, null); 6404 } 6405 if (mAttachInfo != null) { 6406 Rect rectangle = mAttachInfo.mTmpInvalRect; 6407 getDrawingRect(rectangle); 6408 requestRectangleOnScreen(rectangle); 6409 } 6410 invalidate(); 6411 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 6412 notifyAccessibilityStateChanged(); 6413 return true; 6414 } 6415 return false; 6416 } 6417 6418 /** 6419 * Call this to try to clear accessibility focus of this view. 6420 * 6421 * See also {@link #focusSearch(int)}, which is what you call to say that you 6422 * have focus, and you want your parent to look for the next one. 6423 * 6424 * @hide 6425 */ 6426 public void clearAccessibilityFocus() { 6427 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6428 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6429 invalidate(); 6430 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 6431 notifyAccessibilityStateChanged(); 6432 } 6433 // Clear the global reference of accessibility focus if this 6434 // view or any of its descendants had accessibility focus. 6435 ViewRootImpl viewRootImpl = getViewRootImpl(); 6436 if (viewRootImpl != null) { 6437 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 6438 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 6439 viewRootImpl.setAccessibilityFocus(null, null); 6440 } 6441 } 6442 } 6443 6444 private void sendAccessibilityHoverEvent(int eventType) { 6445 // Since we are not delivering to a client accessibility events from not 6446 // important views (unless the clinet request that) we need to fire the 6447 // event from the deepest view exposed to the client. As a consequence if 6448 // the user crosses a not exposed view the client will see enter and exit 6449 // of the exposed predecessor followed by and enter and exit of that same 6450 // predecessor when entering and exiting the not exposed descendant. This 6451 // is fine since the client has a clear idea which view is hovered at the 6452 // price of a couple more events being sent. This is a simple and 6453 // working solution. 6454 View source = this; 6455 while (true) { 6456 if (source.includeForAccessibility()) { 6457 source.sendAccessibilityEvent(eventType); 6458 return; 6459 } 6460 ViewParent parent = source.getParent(); 6461 if (parent instanceof View) { 6462 source = (View) parent; 6463 } else { 6464 return; 6465 } 6466 } 6467 } 6468 6469 /** 6470 * Clears accessibility focus without calling any callback methods 6471 * normally invoked in {@link #clearAccessibilityFocus()}. This method 6472 * is used for clearing accessibility focus when giving this focus to 6473 * another view. 6474 */ 6475 void clearAccessibilityFocusNoCallbacks() { 6476 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6477 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6478 invalidate(); 6479 } 6480 } 6481 6482 /** 6483 * Call this to try to give focus to a specific view or to one of its 6484 * descendants. 6485 * 6486 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6487 * false), or if it is focusable and it is not focusable in touch mode 6488 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6489 * 6490 * See also {@link #focusSearch(int)}, which is what you call to say that you 6491 * have focus, and you want your parent to look for the next one. 6492 * 6493 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 6494 * {@link #FOCUS_DOWN} and <code>null</code>. 6495 * 6496 * @return Whether this view or one of its descendants actually took focus. 6497 */ 6498 public final boolean requestFocus() { 6499 return requestFocus(View.FOCUS_DOWN); 6500 } 6501 6502 /** 6503 * Call this to try to give focus to a specific view or to one of its 6504 * descendants and give it a hint about what direction focus is heading. 6505 * 6506 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6507 * false), or if it is focusable and it is not focusable in touch mode 6508 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6509 * 6510 * See also {@link #focusSearch(int)}, which is what you call to say that you 6511 * have focus, and you want your parent to look for the next one. 6512 * 6513 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 6514 * <code>null</code> set for the previously focused rectangle. 6515 * 6516 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6517 * @return Whether this view or one of its descendants actually took focus. 6518 */ 6519 public final boolean requestFocus(int direction) { 6520 return requestFocus(direction, null); 6521 } 6522 6523 /** 6524 * Call this to try to give focus to a specific view or to one of its descendants 6525 * and give it hints about the direction and a specific rectangle that the focus 6526 * is coming from. The rectangle can help give larger views a finer grained hint 6527 * about where focus is coming from, and therefore, where to show selection, or 6528 * forward focus change internally. 6529 * 6530 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6531 * false), or if it is focusable and it is not focusable in touch mode 6532 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6533 * 6534 * A View will not take focus if it is not visible. 6535 * 6536 * A View will not take focus if one of its parents has 6537 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 6538 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 6539 * 6540 * See also {@link #focusSearch(int)}, which is what you call to say that you 6541 * have focus, and you want your parent to look for the next one. 6542 * 6543 * You may wish to override this method if your custom {@link View} has an internal 6544 * {@link View} that it wishes to forward the request to. 6545 * 6546 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6547 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 6548 * to give a finer grained hint about where focus is coming from. May be null 6549 * if there is no hint. 6550 * @return Whether this view or one of its descendants actually took focus. 6551 */ 6552 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 6553 return requestFocusNoSearch(direction, previouslyFocusedRect); 6554 } 6555 6556 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 6557 // need to be focusable 6558 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 6559 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6560 return false; 6561 } 6562 6563 // need to be focusable in touch mode if in touch mode 6564 if (isInTouchMode() && 6565 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 6566 return false; 6567 } 6568 6569 // need to not have any parents blocking us 6570 if (hasAncestorThatBlocksDescendantFocus()) { 6571 return false; 6572 } 6573 6574 handleFocusGainInternal(direction, previouslyFocusedRect); 6575 return true; 6576 } 6577 6578 /** 6579 * Call this to try to give focus to a specific view or to one of its descendants. This is a 6580 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 6581 * touch mode to request focus when they are touched. 6582 * 6583 * @return Whether this view or one of its descendants actually took focus. 6584 * 6585 * @see #isInTouchMode() 6586 * 6587 */ 6588 public final boolean requestFocusFromTouch() { 6589 // Leave touch mode if we need to 6590 if (isInTouchMode()) { 6591 ViewRootImpl viewRoot = getViewRootImpl(); 6592 if (viewRoot != null) { 6593 viewRoot.ensureTouchMode(false); 6594 } 6595 } 6596 return requestFocus(View.FOCUS_DOWN); 6597 } 6598 6599 /** 6600 * @return Whether any ancestor of this view blocks descendant focus. 6601 */ 6602 private boolean hasAncestorThatBlocksDescendantFocus() { 6603 ViewParent ancestor = mParent; 6604 while (ancestor instanceof ViewGroup) { 6605 final ViewGroup vgAncestor = (ViewGroup) ancestor; 6606 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 6607 return true; 6608 } else { 6609 ancestor = vgAncestor.getParent(); 6610 } 6611 } 6612 return false; 6613 } 6614 6615 /** 6616 * Gets the mode for determining whether this View is important for accessibility 6617 * which is if it fires accessibility events and if it is reported to 6618 * accessibility services that query the screen. 6619 * 6620 * @return The mode for determining whether a View is important for accessibility. 6621 * 6622 * @attr ref android.R.styleable#View_importantForAccessibility 6623 * 6624 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6625 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6626 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6627 */ 6628 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 6629 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 6630 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 6631 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no") 6632 }) 6633 public int getImportantForAccessibility() { 6634 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6635 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6636 } 6637 6638 /** 6639 * Sets how to determine whether this view is important for accessibility 6640 * which is if it fires accessibility events and if it is reported to 6641 * accessibility services that query the screen. 6642 * 6643 * @param mode How to determine whether this view is important for accessibility. 6644 * 6645 * @attr ref android.R.styleable#View_importantForAccessibility 6646 * 6647 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6648 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6649 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6650 */ 6651 public void setImportantForAccessibility(int mode) { 6652 if (mode != getImportantForAccessibility()) { 6653 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6654 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 6655 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6656 notifyAccessibilityStateChanged(); 6657 } 6658 } 6659 6660 /** 6661 * Gets whether this view should be exposed for accessibility. 6662 * 6663 * @return Whether the view is exposed for accessibility. 6664 * 6665 * @hide 6666 */ 6667 public boolean isImportantForAccessibility() { 6668 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6669 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6670 switch (mode) { 6671 case IMPORTANT_FOR_ACCESSIBILITY_YES: 6672 return true; 6673 case IMPORTANT_FOR_ACCESSIBILITY_NO: 6674 return false; 6675 case IMPORTANT_FOR_ACCESSIBILITY_AUTO: 6676 return isActionableForAccessibility() || hasListenersForAccessibility() 6677 || getAccessibilityNodeProvider() != null; 6678 default: 6679 throw new IllegalArgumentException("Unknow important for accessibility mode: " 6680 + mode); 6681 } 6682 } 6683 6684 /** 6685 * Gets the parent for accessibility purposes. Note that the parent for 6686 * accessibility is not necessary the immediate parent. It is the first 6687 * predecessor that is important for accessibility. 6688 * 6689 * @return The parent for accessibility purposes. 6690 */ 6691 public ViewParent getParentForAccessibility() { 6692 if (mParent instanceof View) { 6693 View parentView = (View) mParent; 6694 if (parentView.includeForAccessibility()) { 6695 return mParent; 6696 } else { 6697 return mParent.getParentForAccessibility(); 6698 } 6699 } 6700 return null; 6701 } 6702 6703 /** 6704 * Adds the children of a given View for accessibility. Since some Views are 6705 * not important for accessibility the children for accessibility are not 6706 * necessarily direct children of the riew, rather they are the first level of 6707 * descendants important for accessibility. 6708 * 6709 * @param children The list of children for accessibility. 6710 */ 6711 public void addChildrenForAccessibility(ArrayList<View> children) { 6712 if (includeForAccessibility()) { 6713 children.add(this); 6714 } 6715 } 6716 6717 /** 6718 * Whether to regard this view for accessibility. A view is regarded for 6719 * accessibility if it is important for accessibility or the querying 6720 * accessibility service has explicitly requested that view not 6721 * important for accessibility are regarded. 6722 * 6723 * @return Whether to regard the view for accessibility. 6724 * 6725 * @hide 6726 */ 6727 public boolean includeForAccessibility() { 6728 if (mAttachInfo != null) { 6729 return mAttachInfo.mIncludeNotImportantViews || isImportantForAccessibility(); 6730 } 6731 return false; 6732 } 6733 6734 /** 6735 * Returns whether the View is considered actionable from 6736 * accessibility perspective. Such view are important for 6737 * accessibility. 6738 * 6739 * @return True if the view is actionable for accessibility. 6740 * 6741 * @hide 6742 */ 6743 public boolean isActionableForAccessibility() { 6744 return (isClickable() || isLongClickable() || isFocusable()); 6745 } 6746 6747 /** 6748 * Returns whether the View has registered callbacks wich makes it 6749 * important for accessibility. 6750 * 6751 * @return True if the view is actionable for accessibility. 6752 */ 6753 private boolean hasListenersForAccessibility() { 6754 ListenerInfo info = getListenerInfo(); 6755 return mTouchDelegate != null || info.mOnKeyListener != null 6756 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 6757 || info.mOnHoverListener != null || info.mOnDragListener != null; 6758 } 6759 6760 /** 6761 * Notifies accessibility services that some view's important for 6762 * accessibility state has changed. Note that such notifications 6763 * are made at most once every 6764 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 6765 * to avoid unnecessary load to the system. Also once a view has 6766 * made a notifucation this method is a NOP until the notification has 6767 * been sent to clients. 6768 * 6769 * @hide 6770 * 6771 * TODO: Makse sure this method is called for any view state change 6772 * that is interesting for accessilility purposes. 6773 */ 6774 public void notifyAccessibilityStateChanged() { 6775 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 6776 return; 6777 } 6778 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) { 6779 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED; 6780 if (mParent != null) { 6781 mParent.childAccessibilityStateChanged(this); 6782 } 6783 } 6784 } 6785 6786 /** 6787 * Reset the state indicating the this view has requested clients 6788 * interested in its accessibility state to be notified. 6789 * 6790 * @hide 6791 */ 6792 public void resetAccessibilityStateChanged() { 6793 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED; 6794 } 6795 6796 /** 6797 * Performs the specified accessibility action on the view. For 6798 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 6799 * <p> 6800 * If an {@link AccessibilityDelegate} has been specified via calling 6801 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6802 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 6803 * is responsible for handling this call. 6804 * </p> 6805 * 6806 * @param action The action to perform. 6807 * @param arguments Optional action arguments. 6808 * @return Whether the action was performed. 6809 */ 6810 public boolean performAccessibilityAction(int action, Bundle arguments) { 6811 if (mAccessibilityDelegate != null) { 6812 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 6813 } else { 6814 return performAccessibilityActionInternal(action, arguments); 6815 } 6816 } 6817 6818 /** 6819 * @see #performAccessibilityAction(int, Bundle) 6820 * 6821 * Note: Called from the default {@link AccessibilityDelegate}. 6822 */ 6823 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 6824 switch (action) { 6825 case AccessibilityNodeInfo.ACTION_CLICK: { 6826 if (isClickable()) { 6827 return performClick(); 6828 } 6829 } break; 6830 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 6831 if (isLongClickable()) { 6832 return performLongClick(); 6833 } 6834 } break; 6835 case AccessibilityNodeInfo.ACTION_FOCUS: { 6836 if (!hasFocus()) { 6837 // Get out of touch mode since accessibility 6838 // wants to move focus around. 6839 getViewRootImpl().ensureTouchMode(false); 6840 return requestFocus(); 6841 } 6842 } break; 6843 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 6844 if (hasFocus()) { 6845 clearFocus(); 6846 return !isFocused(); 6847 } 6848 } break; 6849 case AccessibilityNodeInfo.ACTION_SELECT: { 6850 if (!isSelected()) { 6851 setSelected(true); 6852 return isSelected(); 6853 } 6854 } break; 6855 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 6856 if (isSelected()) { 6857 setSelected(false); 6858 return !isSelected(); 6859 } 6860 } break; 6861 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 6862 if (!isAccessibilityFocused()) { 6863 return requestAccessibilityFocus(); 6864 } 6865 } break; 6866 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 6867 if (isAccessibilityFocused()) { 6868 clearAccessibilityFocus(); 6869 return true; 6870 } 6871 } break; 6872 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 6873 if (arguments != null) { 6874 final int granularity = arguments.getInt( 6875 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 6876 return nextAtGranularity(granularity); 6877 } 6878 } break; 6879 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 6880 if (arguments != null) { 6881 final int granularity = arguments.getInt( 6882 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 6883 return previousAtGranularity(granularity); 6884 } 6885 } break; 6886 } 6887 return false; 6888 } 6889 6890 private boolean nextAtGranularity(int granularity) { 6891 CharSequence text = getIterableTextForAccessibility(); 6892 if (text == null || text.length() == 0) { 6893 return false; 6894 } 6895 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 6896 if (iterator == null) { 6897 return false; 6898 } 6899 final int current = getAccessibilityCursorPosition(); 6900 final int[] range = iterator.following(current); 6901 if (range == null) { 6902 return false; 6903 } 6904 final int start = range[0]; 6905 final int end = range[1]; 6906 setAccessibilityCursorPosition(end); 6907 sendViewTextTraversedAtGranularityEvent( 6908 AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, 6909 granularity, start, end); 6910 return true; 6911 } 6912 6913 private boolean previousAtGranularity(int granularity) { 6914 CharSequence text = getIterableTextForAccessibility(); 6915 if (text == null || text.length() == 0) { 6916 return false; 6917 } 6918 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 6919 if (iterator == null) { 6920 return false; 6921 } 6922 int current = getAccessibilityCursorPosition(); 6923 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 6924 current = text.length(); 6925 } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) { 6926 // When traversing by character we always put the cursor after the character 6927 // to ease edit and have to compensate before asking the for previous segment. 6928 current--; 6929 } 6930 final int[] range = iterator.preceding(current); 6931 if (range == null) { 6932 return false; 6933 } 6934 final int start = range[0]; 6935 final int end = range[1]; 6936 // Always put the cursor after the character to ease edit. 6937 if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) { 6938 setAccessibilityCursorPosition(end); 6939 } else { 6940 setAccessibilityCursorPosition(start); 6941 } 6942 sendViewTextTraversedAtGranularityEvent( 6943 AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, 6944 granularity, start, end); 6945 return true; 6946 } 6947 6948 /** 6949 * Gets the text reported for accessibility purposes. 6950 * 6951 * @return The accessibility text. 6952 * 6953 * @hide 6954 */ 6955 public CharSequence getIterableTextForAccessibility() { 6956 return getContentDescription(); 6957 } 6958 6959 /** 6960 * @hide 6961 */ 6962 public int getAccessibilityCursorPosition() { 6963 return mAccessibilityCursorPosition; 6964 } 6965 6966 /** 6967 * @hide 6968 */ 6969 public void setAccessibilityCursorPosition(int position) { 6970 mAccessibilityCursorPosition = position; 6971 } 6972 6973 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 6974 int fromIndex, int toIndex) { 6975 if (mParent == null) { 6976 return; 6977 } 6978 AccessibilityEvent event = AccessibilityEvent.obtain( 6979 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 6980 onInitializeAccessibilityEvent(event); 6981 onPopulateAccessibilityEvent(event); 6982 event.setFromIndex(fromIndex); 6983 event.setToIndex(toIndex); 6984 event.setAction(action); 6985 event.setMovementGranularity(granularity); 6986 mParent.requestSendAccessibilityEvent(this, event); 6987 } 6988 6989 /** 6990 * @hide 6991 */ 6992 public TextSegmentIterator getIteratorForGranularity(int granularity) { 6993 switch (granularity) { 6994 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 6995 CharSequence text = getIterableTextForAccessibility(); 6996 if (text != null && text.length() > 0) { 6997 CharacterTextSegmentIterator iterator = 6998 CharacterTextSegmentIterator.getInstance( 6999 mContext.getResources().getConfiguration().locale); 7000 iterator.initialize(text.toString()); 7001 return iterator; 7002 } 7003 } break; 7004 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7005 CharSequence text = getIterableTextForAccessibility(); 7006 if (text != null && text.length() > 0) { 7007 WordTextSegmentIterator iterator = 7008 WordTextSegmentIterator.getInstance( 7009 mContext.getResources().getConfiguration().locale); 7010 iterator.initialize(text.toString()); 7011 return iterator; 7012 } 7013 } break; 7014 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7015 CharSequence text = getIterableTextForAccessibility(); 7016 if (text != null && text.length() > 0) { 7017 ParagraphTextSegmentIterator iterator = 7018 ParagraphTextSegmentIterator.getInstance(); 7019 iterator.initialize(text.toString()); 7020 return iterator; 7021 } 7022 } break; 7023 } 7024 return null; 7025 } 7026 7027 /** 7028 * @hide 7029 */ 7030 public void dispatchStartTemporaryDetach() { 7031 clearAccessibilityFocus(); 7032 clearDisplayList(); 7033 7034 onStartTemporaryDetach(); 7035 } 7036 7037 /** 7038 * This is called when a container is going to temporarily detach a child, with 7039 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7040 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7041 * {@link #onDetachedFromWindow()} when the container is done. 7042 */ 7043 public void onStartTemporaryDetach() { 7044 removeUnsetPressCallback(); 7045 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7046 } 7047 7048 /** 7049 * @hide 7050 */ 7051 public void dispatchFinishTemporaryDetach() { 7052 onFinishTemporaryDetach(); 7053 } 7054 7055 /** 7056 * Called after {@link #onStartTemporaryDetach} when the container is done 7057 * changing the view. 7058 */ 7059 public void onFinishTemporaryDetach() { 7060 } 7061 7062 /** 7063 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7064 * for this view's window. Returns null if the view is not currently attached 7065 * to the window. Normally you will not need to use this directly, but 7066 * just use the standard high-level event callbacks like 7067 * {@link #onKeyDown(int, KeyEvent)}. 7068 */ 7069 public KeyEvent.DispatcherState getKeyDispatcherState() { 7070 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7071 } 7072 7073 /** 7074 * Dispatch a key event before it is processed by any input method 7075 * associated with the view hierarchy. This can be used to intercept 7076 * key events in special situations before the IME consumes them; a 7077 * typical example would be handling the BACK key to update the application's 7078 * UI instead of allowing the IME to see it and close itself. 7079 * 7080 * @param event The key event to be dispatched. 7081 * @return True if the event was handled, false otherwise. 7082 */ 7083 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7084 return onKeyPreIme(event.getKeyCode(), event); 7085 } 7086 7087 /** 7088 * Dispatch a key event to the next view on the focus path. This path runs 7089 * from the top of the view tree down to the currently focused view. If this 7090 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7091 * the next node down the focus path. This method also fires any key 7092 * listeners. 7093 * 7094 * @param event The key event to be dispatched. 7095 * @return True if the event was handled, false otherwise. 7096 */ 7097 public boolean dispatchKeyEvent(KeyEvent event) { 7098 if (mInputEventConsistencyVerifier != null) { 7099 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7100 } 7101 7102 // Give any attached key listener a first crack at the event. 7103 //noinspection SimplifiableIfStatement 7104 ListenerInfo li = mListenerInfo; 7105 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7106 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7107 return true; 7108 } 7109 7110 if (event.dispatch(this, mAttachInfo != null 7111 ? mAttachInfo.mKeyDispatchState : null, this)) { 7112 return true; 7113 } 7114 7115 if (mInputEventConsistencyVerifier != null) { 7116 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7117 } 7118 return false; 7119 } 7120 7121 /** 7122 * Dispatches a key shortcut event. 7123 * 7124 * @param event The key event to be dispatched. 7125 * @return True if the event was handled by the view, false otherwise. 7126 */ 7127 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 7128 return onKeyShortcut(event.getKeyCode(), event); 7129 } 7130 7131 /** 7132 * Pass the touch screen motion event down to the target view, or this 7133 * view if it is the target. 7134 * 7135 * @param event The motion event to be dispatched. 7136 * @return True if the event was handled by the view, false otherwise. 7137 */ 7138 public boolean dispatchTouchEvent(MotionEvent event) { 7139 if (mInputEventConsistencyVerifier != null) { 7140 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 7141 } 7142 7143 if (onFilterTouchEventForSecurity(event)) { 7144 //noinspection SimplifiableIfStatement 7145 ListenerInfo li = mListenerInfo; 7146 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7147 && li.mOnTouchListener.onTouch(this, event)) { 7148 return true; 7149 } 7150 7151 if (onTouchEvent(event)) { 7152 return true; 7153 } 7154 } 7155 7156 if (mInputEventConsistencyVerifier != null) { 7157 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7158 } 7159 return false; 7160 } 7161 7162 /** 7163 * Filter the touch event to apply security policies. 7164 * 7165 * @param event The motion event to be filtered. 7166 * @return True if the event should be dispatched, false if the event should be dropped. 7167 * 7168 * @see #getFilterTouchesWhenObscured 7169 */ 7170 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 7171 //noinspection RedundantIfStatement 7172 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 7173 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 7174 // Window is obscured, drop this touch. 7175 return false; 7176 } 7177 return true; 7178 } 7179 7180 /** 7181 * Pass a trackball motion event down to the focused view. 7182 * 7183 * @param event The motion event to be dispatched. 7184 * @return True if the event was handled by the view, false otherwise. 7185 */ 7186 public boolean dispatchTrackballEvent(MotionEvent event) { 7187 if (mInputEventConsistencyVerifier != null) { 7188 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 7189 } 7190 7191 return onTrackballEvent(event); 7192 } 7193 7194 /** 7195 * Dispatch a generic motion event. 7196 * <p> 7197 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7198 * are delivered to the view under the pointer. All other generic motion events are 7199 * delivered to the focused view. Hover events are handled specially and are delivered 7200 * to {@link #onHoverEvent(MotionEvent)}. 7201 * </p> 7202 * 7203 * @param event The motion event to be dispatched. 7204 * @return True if the event was handled by the view, false otherwise. 7205 */ 7206 public boolean dispatchGenericMotionEvent(MotionEvent event) { 7207 if (mInputEventConsistencyVerifier != null) { 7208 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 7209 } 7210 7211 final int source = event.getSource(); 7212 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7213 final int action = event.getAction(); 7214 if (action == MotionEvent.ACTION_HOVER_ENTER 7215 || action == MotionEvent.ACTION_HOVER_MOVE 7216 || action == MotionEvent.ACTION_HOVER_EXIT) { 7217 if (dispatchHoverEvent(event)) { 7218 return true; 7219 } 7220 } else if (dispatchGenericPointerEvent(event)) { 7221 return true; 7222 } 7223 } else if (dispatchGenericFocusedEvent(event)) { 7224 return true; 7225 } 7226 7227 if (dispatchGenericMotionEventInternal(event)) { 7228 return true; 7229 } 7230 7231 if (mInputEventConsistencyVerifier != null) { 7232 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7233 } 7234 return false; 7235 } 7236 7237 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 7238 //noinspection SimplifiableIfStatement 7239 ListenerInfo li = mListenerInfo; 7240 if (li != null && li.mOnGenericMotionListener != null 7241 && (mViewFlags & ENABLED_MASK) == ENABLED 7242 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 7243 return true; 7244 } 7245 7246 if (onGenericMotionEvent(event)) { 7247 return true; 7248 } 7249 7250 if (mInputEventConsistencyVerifier != null) { 7251 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7252 } 7253 return false; 7254 } 7255 7256 /** 7257 * Dispatch a hover event. 7258 * <p> 7259 * Do not call this method directly. 7260 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7261 * </p> 7262 * 7263 * @param event The motion event to be dispatched. 7264 * @return True if the event was handled by the view, false otherwise. 7265 */ 7266 protected boolean dispatchHoverEvent(MotionEvent event) { 7267 //noinspection SimplifiableIfStatement 7268 ListenerInfo li = mListenerInfo; 7269 if (li != null && li.mOnHoverListener != null 7270 && (mViewFlags & ENABLED_MASK) == ENABLED 7271 && li.mOnHoverListener.onHover(this, event)) { 7272 return true; 7273 } 7274 7275 return onHoverEvent(event); 7276 } 7277 7278 /** 7279 * Returns true if the view has a child to which it has recently sent 7280 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 7281 * it does not have a hovered child, then it must be the innermost hovered view. 7282 * @hide 7283 */ 7284 protected boolean hasHoveredChild() { 7285 return false; 7286 } 7287 7288 /** 7289 * Dispatch a generic motion event to the view under the first pointer. 7290 * <p> 7291 * Do not call this method directly. 7292 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7293 * </p> 7294 * 7295 * @param event The motion event to be dispatched. 7296 * @return True if the event was handled by the view, false otherwise. 7297 */ 7298 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 7299 return false; 7300 } 7301 7302 /** 7303 * Dispatch a generic motion event to the currently focused view. 7304 * <p> 7305 * Do not call this method directly. 7306 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7307 * </p> 7308 * 7309 * @param event The motion event to be dispatched. 7310 * @return True if the event was handled by the view, false otherwise. 7311 */ 7312 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 7313 return false; 7314 } 7315 7316 /** 7317 * Dispatch a pointer event. 7318 * <p> 7319 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 7320 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 7321 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 7322 * and should not be expected to handle other pointing device features. 7323 * </p> 7324 * 7325 * @param event The motion event to be dispatched. 7326 * @return True if the event was handled by the view, false otherwise. 7327 * @hide 7328 */ 7329 public final boolean dispatchPointerEvent(MotionEvent event) { 7330 if (event.isTouchEvent()) { 7331 return dispatchTouchEvent(event); 7332 } else { 7333 return dispatchGenericMotionEvent(event); 7334 } 7335 } 7336 7337 /** 7338 * Called when the window containing this view gains or loses window focus. 7339 * ViewGroups should override to route to their children. 7340 * 7341 * @param hasFocus True if the window containing this view now has focus, 7342 * false otherwise. 7343 */ 7344 public void dispatchWindowFocusChanged(boolean hasFocus) { 7345 onWindowFocusChanged(hasFocus); 7346 } 7347 7348 /** 7349 * Called when the window containing this view gains or loses focus. Note 7350 * that this is separate from view focus: to receive key events, both 7351 * your view and its window must have focus. If a window is displayed 7352 * on top of yours that takes input focus, then your own window will lose 7353 * focus but the view focus will remain unchanged. 7354 * 7355 * @param hasWindowFocus True if the window containing this view now has 7356 * focus, false otherwise. 7357 */ 7358 public void onWindowFocusChanged(boolean hasWindowFocus) { 7359 InputMethodManager imm = InputMethodManager.peekInstance(); 7360 if (!hasWindowFocus) { 7361 if (isPressed()) { 7362 setPressed(false); 7363 } 7364 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7365 imm.focusOut(this); 7366 } 7367 removeLongPressCallback(); 7368 removeTapCallback(); 7369 onFocusLost(); 7370 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7371 imm.focusIn(this); 7372 } 7373 refreshDrawableState(); 7374 } 7375 7376 /** 7377 * Returns true if this view is in a window that currently has window focus. 7378 * Note that this is not the same as the view itself having focus. 7379 * 7380 * @return True if this view is in a window that currently has window focus. 7381 */ 7382 public boolean hasWindowFocus() { 7383 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 7384 } 7385 7386 /** 7387 * Dispatch a view visibility change down the view hierarchy. 7388 * ViewGroups should override to route to their children. 7389 * @param changedView The view whose visibility changed. Could be 'this' or 7390 * an ancestor view. 7391 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7392 * {@link #INVISIBLE} or {@link #GONE}. 7393 */ 7394 protected void dispatchVisibilityChanged(View changedView, int visibility) { 7395 onVisibilityChanged(changedView, visibility); 7396 } 7397 7398 /** 7399 * Called when the visibility of the view or an ancestor of the view is changed. 7400 * @param changedView The view whose visibility changed. Could be 'this' or 7401 * an ancestor view. 7402 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7403 * {@link #INVISIBLE} or {@link #GONE}. 7404 */ 7405 protected void onVisibilityChanged(View changedView, int visibility) { 7406 if (visibility == VISIBLE) { 7407 if (mAttachInfo != null) { 7408 initialAwakenScrollBars(); 7409 } else { 7410 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 7411 } 7412 } 7413 } 7414 7415 /** 7416 * Dispatch a hint about whether this view is displayed. For instance, when 7417 * a View moves out of the screen, it might receives a display hint indicating 7418 * the view is not displayed. Applications should not <em>rely</em> on this hint 7419 * as there is no guarantee that they will receive one. 7420 * 7421 * @param hint A hint about whether or not this view is displayed: 7422 * {@link #VISIBLE} or {@link #INVISIBLE}. 7423 */ 7424 public void dispatchDisplayHint(int hint) { 7425 onDisplayHint(hint); 7426 } 7427 7428 /** 7429 * Gives this view a hint about whether is displayed or not. For instance, when 7430 * a View moves out of the screen, it might receives a display hint indicating 7431 * the view is not displayed. Applications should not <em>rely</em> on this hint 7432 * as there is no guarantee that they will receive one. 7433 * 7434 * @param hint A hint about whether or not this view is displayed: 7435 * {@link #VISIBLE} or {@link #INVISIBLE}. 7436 */ 7437 protected void onDisplayHint(int hint) { 7438 } 7439 7440 /** 7441 * Dispatch a window visibility change down the view hierarchy. 7442 * ViewGroups should override to route to their children. 7443 * 7444 * @param visibility The new visibility of the window. 7445 * 7446 * @see #onWindowVisibilityChanged(int) 7447 */ 7448 public void dispatchWindowVisibilityChanged(int visibility) { 7449 onWindowVisibilityChanged(visibility); 7450 } 7451 7452 /** 7453 * Called when the window containing has change its visibility 7454 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 7455 * that this tells you whether or not your window is being made visible 7456 * to the window manager; this does <em>not</em> tell you whether or not 7457 * your window is obscured by other windows on the screen, even if it 7458 * is itself visible. 7459 * 7460 * @param visibility The new visibility of the window. 7461 */ 7462 protected void onWindowVisibilityChanged(int visibility) { 7463 if (visibility == VISIBLE) { 7464 initialAwakenScrollBars(); 7465 } 7466 } 7467 7468 /** 7469 * Returns the current visibility of the window this view is attached to 7470 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 7471 * 7472 * @return Returns the current visibility of the view's window. 7473 */ 7474 public int getWindowVisibility() { 7475 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 7476 } 7477 7478 /** 7479 * Retrieve the overall visible display size in which the window this view is 7480 * attached to has been positioned in. This takes into account screen 7481 * decorations above the window, for both cases where the window itself 7482 * is being position inside of them or the window is being placed under 7483 * then and covered insets are used for the window to position its content 7484 * inside. In effect, this tells you the available area where content can 7485 * be placed and remain visible to users. 7486 * 7487 * <p>This function requires an IPC back to the window manager to retrieve 7488 * the requested information, so should not be used in performance critical 7489 * code like drawing. 7490 * 7491 * @param outRect Filled in with the visible display frame. If the view 7492 * is not attached to a window, this is simply the raw display size. 7493 */ 7494 public void getWindowVisibleDisplayFrame(Rect outRect) { 7495 if (mAttachInfo != null) { 7496 try { 7497 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 7498 } catch (RemoteException e) { 7499 return; 7500 } 7501 // XXX This is really broken, and probably all needs to be done 7502 // in the window manager, and we need to know more about whether 7503 // we want the area behind or in front of the IME. 7504 final Rect insets = mAttachInfo.mVisibleInsets; 7505 outRect.left += insets.left; 7506 outRect.top += insets.top; 7507 outRect.right -= insets.right; 7508 outRect.bottom -= insets.bottom; 7509 return; 7510 } 7511 // The view is not attached to a display so we don't have a context. 7512 // Make a best guess about the display size. 7513 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 7514 d.getRectSize(outRect); 7515 } 7516 7517 /** 7518 * Dispatch a notification about a resource configuration change down 7519 * the view hierarchy. 7520 * ViewGroups should override to route to their children. 7521 * 7522 * @param newConfig The new resource configuration. 7523 * 7524 * @see #onConfigurationChanged(android.content.res.Configuration) 7525 */ 7526 public void dispatchConfigurationChanged(Configuration newConfig) { 7527 onConfigurationChanged(newConfig); 7528 } 7529 7530 /** 7531 * Called when the current configuration of the resources being used 7532 * by the application have changed. You can use this to decide when 7533 * to reload resources that can changed based on orientation and other 7534 * configuration characterstics. You only need to use this if you are 7535 * not relying on the normal {@link android.app.Activity} mechanism of 7536 * recreating the activity instance upon a configuration change. 7537 * 7538 * @param newConfig The new resource configuration. 7539 */ 7540 protected void onConfigurationChanged(Configuration newConfig) { 7541 } 7542 7543 /** 7544 * Private function to aggregate all per-view attributes in to the view 7545 * root. 7546 */ 7547 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7548 performCollectViewAttributes(attachInfo, visibility); 7549 } 7550 7551 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7552 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 7553 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 7554 attachInfo.mKeepScreenOn = true; 7555 } 7556 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 7557 ListenerInfo li = mListenerInfo; 7558 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 7559 attachInfo.mHasSystemUiListeners = true; 7560 } 7561 } 7562 } 7563 7564 void needGlobalAttributesUpdate(boolean force) { 7565 final AttachInfo ai = mAttachInfo; 7566 if (ai != null && !ai.mRecomputeGlobalAttributes) { 7567 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 7568 || ai.mHasSystemUiListeners) { 7569 ai.mRecomputeGlobalAttributes = true; 7570 } 7571 } 7572 } 7573 7574 /** 7575 * Returns whether the device is currently in touch mode. Touch mode is entered 7576 * once the user begins interacting with the device by touch, and affects various 7577 * things like whether focus is always visible to the user. 7578 * 7579 * @return Whether the device is in touch mode. 7580 */ 7581 @ViewDebug.ExportedProperty 7582 public boolean isInTouchMode() { 7583 if (mAttachInfo != null) { 7584 return mAttachInfo.mInTouchMode; 7585 } else { 7586 return ViewRootImpl.isInTouchMode(); 7587 } 7588 } 7589 7590 /** 7591 * Returns the context the view is running in, through which it can 7592 * access the current theme, resources, etc. 7593 * 7594 * @return The view's Context. 7595 */ 7596 @ViewDebug.CapturedViewProperty 7597 public final Context getContext() { 7598 return mContext; 7599 } 7600 7601 /** 7602 * Handle a key event before it is processed by any input method 7603 * associated with the view hierarchy. This can be used to intercept 7604 * key events in special situations before the IME consumes them; a 7605 * typical example would be handling the BACK key to update the application's 7606 * UI instead of allowing the IME to see it and close itself. 7607 * 7608 * @param keyCode The value in event.getKeyCode(). 7609 * @param event Description of the key event. 7610 * @return If you handled the event, return true. If you want to allow the 7611 * event to be handled by the next receiver, return false. 7612 */ 7613 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 7614 return false; 7615 } 7616 7617 /** 7618 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 7619 * KeyEvent.Callback.onKeyDown()}: perform press of the view 7620 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 7621 * is released, if the view is enabled and clickable. 7622 * 7623 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7624 * although some may elect to do so in some situations. Do not rely on this to 7625 * catch software key presses. 7626 * 7627 * @param keyCode A key code that represents the button pressed, from 7628 * {@link android.view.KeyEvent}. 7629 * @param event The KeyEvent object that defines the button action. 7630 */ 7631 public boolean onKeyDown(int keyCode, KeyEvent event) { 7632 boolean result = false; 7633 7634 switch (keyCode) { 7635 case KeyEvent.KEYCODE_DPAD_CENTER: 7636 case KeyEvent.KEYCODE_ENTER: { 7637 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7638 return true; 7639 } 7640 // Long clickable items don't necessarily have to be clickable 7641 if (((mViewFlags & CLICKABLE) == CLICKABLE || 7642 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 7643 (event.getRepeatCount() == 0)) { 7644 setPressed(true); 7645 checkForLongClick(0); 7646 return true; 7647 } 7648 break; 7649 } 7650 } 7651 return result; 7652 } 7653 7654 /** 7655 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 7656 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 7657 * the event). 7658 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7659 * although some may elect to do so in some situations. Do not rely on this to 7660 * catch software key presses. 7661 */ 7662 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 7663 return false; 7664 } 7665 7666 /** 7667 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 7668 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 7669 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 7670 * {@link KeyEvent#KEYCODE_ENTER} is released. 7671 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7672 * although some may elect to do so in some situations. Do not rely on this to 7673 * catch software key presses. 7674 * 7675 * @param keyCode A key code that represents the button pressed, from 7676 * {@link android.view.KeyEvent}. 7677 * @param event The KeyEvent object that defines the button action. 7678 */ 7679 public boolean onKeyUp(int keyCode, KeyEvent event) { 7680 boolean result = false; 7681 7682 switch (keyCode) { 7683 case KeyEvent.KEYCODE_DPAD_CENTER: 7684 case KeyEvent.KEYCODE_ENTER: { 7685 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7686 return true; 7687 } 7688 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 7689 setPressed(false); 7690 7691 if (!mHasPerformedLongPress) { 7692 // This is a tap, so remove the longpress check 7693 removeLongPressCallback(); 7694 7695 result = performClick(); 7696 } 7697 } 7698 break; 7699 } 7700 } 7701 return result; 7702 } 7703 7704 /** 7705 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 7706 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 7707 * the event). 7708 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7709 * although some may elect to do so in some situations. Do not rely on this to 7710 * catch software key presses. 7711 * 7712 * @param keyCode A key code that represents the button pressed, from 7713 * {@link android.view.KeyEvent}. 7714 * @param repeatCount The number of times the action was made. 7715 * @param event The KeyEvent object that defines the button action. 7716 */ 7717 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 7718 return false; 7719 } 7720 7721 /** 7722 * Called on the focused view when a key shortcut event is not handled. 7723 * Override this method to implement local key shortcuts for the View. 7724 * Key shortcuts can also be implemented by setting the 7725 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 7726 * 7727 * @param keyCode The value in event.getKeyCode(). 7728 * @param event Description of the key event. 7729 * @return If you handled the event, return true. If you want to allow the 7730 * event to be handled by the next receiver, return false. 7731 */ 7732 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 7733 return false; 7734 } 7735 7736 /** 7737 * Check whether the called view is a text editor, in which case it 7738 * would make sense to automatically display a soft input window for 7739 * it. Subclasses should override this if they implement 7740 * {@link #onCreateInputConnection(EditorInfo)} to return true if 7741 * a call on that method would return a non-null InputConnection, and 7742 * they are really a first-class editor that the user would normally 7743 * start typing on when the go into a window containing your view. 7744 * 7745 * <p>The default implementation always returns false. This does 7746 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 7747 * will not be called or the user can not otherwise perform edits on your 7748 * view; it is just a hint to the system that this is not the primary 7749 * purpose of this view. 7750 * 7751 * @return Returns true if this view is a text editor, else false. 7752 */ 7753 public boolean onCheckIsTextEditor() { 7754 return false; 7755 } 7756 7757 /** 7758 * Create a new InputConnection for an InputMethod to interact 7759 * with the view. The default implementation returns null, since it doesn't 7760 * support input methods. You can override this to implement such support. 7761 * This is only needed for views that take focus and text input. 7762 * 7763 * <p>When implementing this, you probably also want to implement 7764 * {@link #onCheckIsTextEditor()} to indicate you will return a 7765 * non-null InputConnection. 7766 * 7767 * @param outAttrs Fill in with attribute information about the connection. 7768 */ 7769 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 7770 return null; 7771 } 7772 7773 /** 7774 * Called by the {@link android.view.inputmethod.InputMethodManager} 7775 * when a view who is not the current 7776 * input connection target is trying to make a call on the manager. The 7777 * default implementation returns false; you can override this to return 7778 * true for certain views if you are performing InputConnection proxying 7779 * to them. 7780 * @param view The View that is making the InputMethodManager call. 7781 * @return Return true to allow the call, false to reject. 7782 */ 7783 public boolean checkInputConnectionProxy(View view) { 7784 return false; 7785 } 7786 7787 /** 7788 * Show the context menu for this view. It is not safe to hold on to the 7789 * menu after returning from this method. 7790 * 7791 * You should normally not overload this method. Overload 7792 * {@link #onCreateContextMenu(ContextMenu)} or define an 7793 * {@link OnCreateContextMenuListener} to add items to the context menu. 7794 * 7795 * @param menu The context menu to populate 7796 */ 7797 public void createContextMenu(ContextMenu menu) { 7798 ContextMenuInfo menuInfo = getContextMenuInfo(); 7799 7800 // Sets the current menu info so all items added to menu will have 7801 // my extra info set. 7802 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 7803 7804 onCreateContextMenu(menu); 7805 ListenerInfo li = mListenerInfo; 7806 if (li != null && li.mOnCreateContextMenuListener != null) { 7807 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 7808 } 7809 7810 // Clear the extra information so subsequent items that aren't mine don't 7811 // have my extra info. 7812 ((MenuBuilder)menu).setCurrentMenuInfo(null); 7813 7814 if (mParent != null) { 7815 mParent.createContextMenu(menu); 7816 } 7817 } 7818 7819 /** 7820 * Views should implement this if they have extra information to associate 7821 * with the context menu. The return result is supplied as a parameter to 7822 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 7823 * callback. 7824 * 7825 * @return Extra information about the item for which the context menu 7826 * should be shown. This information will vary across different 7827 * subclasses of View. 7828 */ 7829 protected ContextMenuInfo getContextMenuInfo() { 7830 return null; 7831 } 7832 7833 /** 7834 * Views should implement this if the view itself is going to add items to 7835 * the context menu. 7836 * 7837 * @param menu the context menu to populate 7838 */ 7839 protected void onCreateContextMenu(ContextMenu menu) { 7840 } 7841 7842 /** 7843 * Implement this method to handle trackball motion events. The 7844 * <em>relative</em> movement of the trackball since the last event 7845 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 7846 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 7847 * that a movement of 1 corresponds to the user pressing one DPAD key (so 7848 * they will often be fractional values, representing the more fine-grained 7849 * movement information available from a trackball). 7850 * 7851 * @param event The motion event. 7852 * @return True if the event was handled, false otherwise. 7853 */ 7854 public boolean onTrackballEvent(MotionEvent event) { 7855 return false; 7856 } 7857 7858 /** 7859 * Implement this method to handle generic motion events. 7860 * <p> 7861 * Generic motion events describe joystick movements, mouse hovers, track pad 7862 * touches, scroll wheel movements and other input events. The 7863 * {@link MotionEvent#getSource() source} of the motion event specifies 7864 * the class of input that was received. Implementations of this method 7865 * must examine the bits in the source before processing the event. 7866 * The following code example shows how this is done. 7867 * </p><p> 7868 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7869 * are delivered to the view under the pointer. All other generic motion events are 7870 * delivered to the focused view. 7871 * </p> 7872 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 7873 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 7874 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 7875 * // process the joystick movement... 7876 * return true; 7877 * } 7878 * } 7879 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7880 * switch (event.getAction()) { 7881 * case MotionEvent.ACTION_HOVER_MOVE: 7882 * // process the mouse hover movement... 7883 * return true; 7884 * case MotionEvent.ACTION_SCROLL: 7885 * // process the scroll wheel movement... 7886 * return true; 7887 * } 7888 * } 7889 * return super.onGenericMotionEvent(event); 7890 * }</pre> 7891 * 7892 * @param event The generic motion event being processed. 7893 * @return True if the event was handled, false otherwise. 7894 */ 7895 public boolean onGenericMotionEvent(MotionEvent event) { 7896 return false; 7897 } 7898 7899 /** 7900 * Implement this method to handle hover events. 7901 * <p> 7902 * This method is called whenever a pointer is hovering into, over, or out of the 7903 * bounds of a view and the view is not currently being touched. 7904 * Hover events are represented as pointer events with action 7905 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 7906 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 7907 * </p> 7908 * <ul> 7909 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 7910 * when the pointer enters the bounds of the view.</li> 7911 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 7912 * when the pointer has already entered the bounds of the view and has moved.</li> 7913 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 7914 * when the pointer has exited the bounds of the view or when the pointer is 7915 * about to go down due to a button click, tap, or similar user action that 7916 * causes the view to be touched.</li> 7917 * </ul> 7918 * <p> 7919 * The view should implement this method to return true to indicate that it is 7920 * handling the hover event, such as by changing its drawable state. 7921 * </p><p> 7922 * The default implementation calls {@link #setHovered} to update the hovered state 7923 * of the view when a hover enter or hover exit event is received, if the view 7924 * is enabled and is clickable. The default implementation also sends hover 7925 * accessibility events. 7926 * </p> 7927 * 7928 * @param event The motion event that describes the hover. 7929 * @return True if the view handled the hover event. 7930 * 7931 * @see #isHovered 7932 * @see #setHovered 7933 * @see #onHoverChanged 7934 */ 7935 public boolean onHoverEvent(MotionEvent event) { 7936 // The root view may receive hover (or touch) events that are outside the bounds of 7937 // the window. This code ensures that we only send accessibility events for 7938 // hovers that are actually within the bounds of the root view. 7939 final int action = event.getActionMasked(); 7940 if (!mSendingHoverAccessibilityEvents) { 7941 if ((action == MotionEvent.ACTION_HOVER_ENTER 7942 || action == MotionEvent.ACTION_HOVER_MOVE) 7943 && !hasHoveredChild() 7944 && pointInView(event.getX(), event.getY())) { 7945 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 7946 mSendingHoverAccessibilityEvents = true; 7947 } 7948 } else { 7949 if (action == MotionEvent.ACTION_HOVER_EXIT 7950 || (action == MotionEvent.ACTION_MOVE 7951 && !pointInView(event.getX(), event.getY()))) { 7952 mSendingHoverAccessibilityEvents = false; 7953 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 7954 // If the window does not have input focus we take away accessibility 7955 // focus as soon as the user stop hovering over the view. 7956 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 7957 getViewRootImpl().setAccessibilityFocus(null, null); 7958 } 7959 } 7960 } 7961 7962 if (isHoverable()) { 7963 switch (action) { 7964 case MotionEvent.ACTION_HOVER_ENTER: 7965 setHovered(true); 7966 break; 7967 case MotionEvent.ACTION_HOVER_EXIT: 7968 setHovered(false); 7969 break; 7970 } 7971 7972 // Dispatch the event to onGenericMotionEvent before returning true. 7973 // This is to provide compatibility with existing applications that 7974 // handled HOVER_MOVE events in onGenericMotionEvent and that would 7975 // break because of the new default handling for hoverable views 7976 // in onHoverEvent. 7977 // Note that onGenericMotionEvent will be called by default when 7978 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 7979 dispatchGenericMotionEventInternal(event); 7980 return true; 7981 } 7982 7983 return false; 7984 } 7985 7986 /** 7987 * Returns true if the view should handle {@link #onHoverEvent} 7988 * by calling {@link #setHovered} to change its hovered state. 7989 * 7990 * @return True if the view is hoverable. 7991 */ 7992 private boolean isHoverable() { 7993 final int viewFlags = mViewFlags; 7994 if ((viewFlags & ENABLED_MASK) == DISABLED) { 7995 return false; 7996 } 7997 7998 return (viewFlags & CLICKABLE) == CLICKABLE 7999 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8000 } 8001 8002 /** 8003 * Returns true if the view is currently hovered. 8004 * 8005 * @return True if the view is currently hovered. 8006 * 8007 * @see #setHovered 8008 * @see #onHoverChanged 8009 */ 8010 @ViewDebug.ExportedProperty 8011 public boolean isHovered() { 8012 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8013 } 8014 8015 /** 8016 * Sets whether the view is currently hovered. 8017 * <p> 8018 * Calling this method also changes the drawable state of the view. This 8019 * enables the view to react to hover by using different drawable resources 8020 * to change its appearance. 8021 * </p><p> 8022 * The {@link #onHoverChanged} method is called when the hovered state changes. 8023 * </p> 8024 * 8025 * @param hovered True if the view is hovered. 8026 * 8027 * @see #isHovered 8028 * @see #onHoverChanged 8029 */ 8030 public void setHovered(boolean hovered) { 8031 if (hovered) { 8032 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8033 mPrivateFlags |= PFLAG_HOVERED; 8034 refreshDrawableState(); 8035 onHoverChanged(true); 8036 } 8037 } else { 8038 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8039 mPrivateFlags &= ~PFLAG_HOVERED; 8040 refreshDrawableState(); 8041 onHoverChanged(false); 8042 } 8043 } 8044 } 8045 8046 /** 8047 * Implement this method to handle hover state changes. 8048 * <p> 8049 * This method is called whenever the hover state changes as a result of a 8050 * call to {@link #setHovered}. 8051 * </p> 8052 * 8053 * @param hovered The current hover state, as returned by {@link #isHovered}. 8054 * 8055 * @see #isHovered 8056 * @see #setHovered 8057 */ 8058 public void onHoverChanged(boolean hovered) { 8059 } 8060 8061 /** 8062 * Implement this method to handle touch screen motion events. 8063 * 8064 * @param event The motion event. 8065 * @return True if the event was handled, false otherwise. 8066 */ 8067 public boolean onTouchEvent(MotionEvent event) { 8068 final int viewFlags = mViewFlags; 8069 8070 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8071 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8072 setPressed(false); 8073 } 8074 // A disabled view that is clickable still consumes the touch 8075 // events, it just doesn't respond to them. 8076 return (((viewFlags & CLICKABLE) == CLICKABLE || 8077 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8078 } 8079 8080 if (mTouchDelegate != null) { 8081 if (mTouchDelegate.onTouchEvent(event)) { 8082 return true; 8083 } 8084 } 8085 8086 if (((viewFlags & CLICKABLE) == CLICKABLE || 8087 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8088 switch (event.getAction()) { 8089 case MotionEvent.ACTION_UP: 8090 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8091 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8092 // take focus if we don't have it already and we should in 8093 // touch mode. 8094 boolean focusTaken = false; 8095 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8096 focusTaken = requestFocus(); 8097 } 8098 8099 if (prepressed) { 8100 // The button is being released before we actually 8101 // showed it as pressed. Make it show the pressed 8102 // state now (before scheduling the click) to ensure 8103 // the user sees it. 8104 setPressed(true); 8105 } 8106 8107 if (!mHasPerformedLongPress) { 8108 // This is a tap, so remove the longpress check 8109 removeLongPressCallback(); 8110 8111 // Only perform take click actions if we were in the pressed state 8112 if (!focusTaken) { 8113 // Use a Runnable and post this rather than calling 8114 // performClick directly. This lets other visual state 8115 // of the view update before click actions start. 8116 if (mPerformClick == null) { 8117 mPerformClick = new PerformClick(); 8118 } 8119 if (!post(mPerformClick)) { 8120 performClick(); 8121 } 8122 } 8123 } 8124 8125 if (mUnsetPressedState == null) { 8126 mUnsetPressedState = new UnsetPressedState(); 8127 } 8128 8129 if (prepressed) { 8130 postDelayed(mUnsetPressedState, 8131 ViewConfiguration.getPressedStateDuration()); 8132 } else if (!post(mUnsetPressedState)) { 8133 // If the post failed, unpress right now 8134 mUnsetPressedState.run(); 8135 } 8136 removeTapCallback(); 8137 } 8138 break; 8139 8140 case MotionEvent.ACTION_DOWN: 8141 mHasPerformedLongPress = false; 8142 8143 if (performButtonActionOnTouchDown(event)) { 8144 break; 8145 } 8146 8147 // Walk up the hierarchy to determine if we're inside a scrolling container. 8148 boolean isInScrollingContainer = isInScrollingContainer(); 8149 8150 // For views inside a scrolling container, delay the pressed feedback for 8151 // a short period in case this is a scroll. 8152 if (isInScrollingContainer) { 8153 mPrivateFlags |= PFLAG_PREPRESSED; 8154 if (mPendingCheckForTap == null) { 8155 mPendingCheckForTap = new CheckForTap(); 8156 } 8157 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 8158 } else { 8159 // Not inside a scrolling container, so show the feedback right away 8160 setPressed(true); 8161 checkForLongClick(0); 8162 } 8163 break; 8164 8165 case MotionEvent.ACTION_CANCEL: 8166 setPressed(false); 8167 removeTapCallback(); 8168 break; 8169 8170 case MotionEvent.ACTION_MOVE: 8171 final int x = (int) event.getX(); 8172 final int y = (int) event.getY(); 8173 8174 // Be lenient about moving outside of buttons 8175 if (!pointInView(x, y, mTouchSlop)) { 8176 // Outside button 8177 removeTapCallback(); 8178 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 8179 // Remove any future long press/tap checks 8180 removeLongPressCallback(); 8181 8182 setPressed(false); 8183 } 8184 } 8185 break; 8186 } 8187 return true; 8188 } 8189 8190 return false; 8191 } 8192 8193 /** 8194 * @hide 8195 */ 8196 public boolean isInScrollingContainer() { 8197 ViewParent p = getParent(); 8198 while (p != null && p instanceof ViewGroup) { 8199 if (((ViewGroup) p).shouldDelayChildPressedState()) { 8200 return true; 8201 } 8202 p = p.getParent(); 8203 } 8204 return false; 8205 } 8206 8207 /** 8208 * Remove the longpress detection timer. 8209 */ 8210 private void removeLongPressCallback() { 8211 if (mPendingCheckForLongPress != null) { 8212 removeCallbacks(mPendingCheckForLongPress); 8213 } 8214 } 8215 8216 /** 8217 * Remove the pending click action 8218 */ 8219 private void removePerformClickCallback() { 8220 if (mPerformClick != null) { 8221 removeCallbacks(mPerformClick); 8222 } 8223 } 8224 8225 /** 8226 * Remove the prepress detection timer. 8227 */ 8228 private void removeUnsetPressCallback() { 8229 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 8230 setPressed(false); 8231 removeCallbacks(mUnsetPressedState); 8232 } 8233 } 8234 8235 /** 8236 * Remove the tap detection timer. 8237 */ 8238 private void removeTapCallback() { 8239 if (mPendingCheckForTap != null) { 8240 mPrivateFlags &= ~PFLAG_PREPRESSED; 8241 removeCallbacks(mPendingCheckForTap); 8242 } 8243 } 8244 8245 /** 8246 * Cancels a pending long press. Your subclass can use this if you 8247 * want the context menu to come up if the user presses and holds 8248 * at the same place, but you don't want it to come up if they press 8249 * and then move around enough to cause scrolling. 8250 */ 8251 public void cancelLongPress() { 8252 removeLongPressCallback(); 8253 8254 /* 8255 * The prepressed state handled by the tap callback is a display 8256 * construct, but the tap callback will post a long press callback 8257 * less its own timeout. Remove it here. 8258 */ 8259 removeTapCallback(); 8260 } 8261 8262 /** 8263 * Remove the pending callback for sending a 8264 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 8265 */ 8266 private void removeSendViewScrolledAccessibilityEventCallback() { 8267 if (mSendViewScrolledAccessibilityEvent != null) { 8268 removeCallbacks(mSendViewScrolledAccessibilityEvent); 8269 mSendViewScrolledAccessibilityEvent.mIsPending = false; 8270 } 8271 } 8272 8273 /** 8274 * Sets the TouchDelegate for this View. 8275 */ 8276 public void setTouchDelegate(TouchDelegate delegate) { 8277 mTouchDelegate = delegate; 8278 } 8279 8280 /** 8281 * Gets the TouchDelegate for this View. 8282 */ 8283 public TouchDelegate getTouchDelegate() { 8284 return mTouchDelegate; 8285 } 8286 8287 /** 8288 * Set flags controlling behavior of this view. 8289 * 8290 * @param flags Constant indicating the value which should be set 8291 * @param mask Constant indicating the bit range that should be changed 8292 */ 8293 void setFlags(int flags, int mask) { 8294 int old = mViewFlags; 8295 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 8296 8297 int changed = mViewFlags ^ old; 8298 if (changed == 0) { 8299 return; 8300 } 8301 int privateFlags = mPrivateFlags; 8302 8303 /* Check if the FOCUSABLE bit has changed */ 8304 if (((changed & FOCUSABLE_MASK) != 0) && 8305 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 8306 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 8307 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 8308 /* Give up focus if we are no longer focusable */ 8309 clearFocus(); 8310 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 8311 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 8312 /* 8313 * Tell the view system that we are now available to take focus 8314 * if no one else already has it. 8315 */ 8316 if (mParent != null) mParent.focusableViewAvailable(this); 8317 } 8318 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8319 notifyAccessibilityStateChanged(); 8320 } 8321 } 8322 8323 if ((flags & VISIBILITY_MASK) == VISIBLE) { 8324 if ((changed & VISIBILITY_MASK) != 0) { 8325 /* 8326 * If this view is becoming visible, invalidate it in case it changed while 8327 * it was not visible. Marking it drawn ensures that the invalidation will 8328 * go through. 8329 */ 8330 mPrivateFlags |= PFLAG_DRAWN; 8331 invalidate(true); 8332 8333 needGlobalAttributesUpdate(true); 8334 8335 // a view becoming visible is worth notifying the parent 8336 // about in case nothing has focus. even if this specific view 8337 // isn't focusable, it may contain something that is, so let 8338 // the root view try to give this focus if nothing else does. 8339 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 8340 mParent.focusableViewAvailable(this); 8341 } 8342 } 8343 } 8344 8345 /* Check if the GONE bit has changed */ 8346 if ((changed & GONE) != 0) { 8347 needGlobalAttributesUpdate(false); 8348 requestLayout(); 8349 8350 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 8351 if (hasFocus()) clearFocus(); 8352 clearAccessibilityFocus(); 8353 destroyDrawingCache(); 8354 if (mParent instanceof View) { 8355 // GONE views noop invalidation, so invalidate the parent 8356 ((View) mParent).invalidate(true); 8357 } 8358 // Mark the view drawn to ensure that it gets invalidated properly the next 8359 // time it is visible and gets invalidated 8360 mPrivateFlags |= PFLAG_DRAWN; 8361 } 8362 if (mAttachInfo != null) { 8363 mAttachInfo.mViewVisibilityChanged = true; 8364 } 8365 } 8366 8367 /* Check if the VISIBLE bit has changed */ 8368 if ((changed & INVISIBLE) != 0) { 8369 needGlobalAttributesUpdate(false); 8370 /* 8371 * If this view is becoming invisible, set the DRAWN flag so that 8372 * the next invalidate() will not be skipped. 8373 */ 8374 mPrivateFlags |= PFLAG_DRAWN; 8375 8376 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 8377 // root view becoming invisible shouldn't clear focus and accessibility focus 8378 if (getRootView() != this) { 8379 clearFocus(); 8380 clearAccessibilityFocus(); 8381 } 8382 } 8383 if (mAttachInfo != null) { 8384 mAttachInfo.mViewVisibilityChanged = true; 8385 } 8386 } 8387 8388 if ((changed & VISIBILITY_MASK) != 0) { 8389 if (mParent instanceof ViewGroup) { 8390 ((ViewGroup) mParent).onChildVisibilityChanged(this, 8391 (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK)); 8392 ((View) mParent).invalidate(true); 8393 } else if (mParent != null) { 8394 mParent.invalidateChild(this, null); 8395 } 8396 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 8397 } 8398 8399 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 8400 destroyDrawingCache(); 8401 } 8402 8403 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 8404 destroyDrawingCache(); 8405 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8406 invalidateParentCaches(); 8407 } 8408 8409 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 8410 destroyDrawingCache(); 8411 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8412 } 8413 8414 if ((changed & DRAW_MASK) != 0) { 8415 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 8416 if (mBackground != null) { 8417 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8418 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 8419 } else { 8420 mPrivateFlags |= PFLAG_SKIP_DRAW; 8421 } 8422 } else { 8423 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8424 } 8425 requestLayout(); 8426 invalidate(true); 8427 } 8428 8429 if ((changed & KEEP_SCREEN_ON) != 0) { 8430 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 8431 mParent.recomputeViewAttributes(this); 8432 } 8433 } 8434 8435 if (AccessibilityManager.getInstance(mContext).isEnabled() 8436 && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0 8437 || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) { 8438 notifyAccessibilityStateChanged(); 8439 } 8440 } 8441 8442 /** 8443 * Change the view's z order in the tree, so it's on top of other sibling 8444 * views 8445 */ 8446 public void bringToFront() { 8447 if (mParent != null) { 8448 mParent.bringChildToFront(this); 8449 } 8450 } 8451 8452 /** 8453 * This is called in response to an internal scroll in this view (i.e., the 8454 * view scrolled its own contents). This is typically as a result of 8455 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 8456 * called. 8457 * 8458 * @param l Current horizontal scroll origin. 8459 * @param t Current vertical scroll origin. 8460 * @param oldl Previous horizontal scroll origin. 8461 * @param oldt Previous vertical scroll origin. 8462 */ 8463 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 8464 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8465 postSendViewScrolledAccessibilityEventCallback(); 8466 } 8467 8468 mBackgroundSizeChanged = true; 8469 8470 final AttachInfo ai = mAttachInfo; 8471 if (ai != null) { 8472 ai.mViewScrollChanged = true; 8473 } 8474 } 8475 8476 /** 8477 * Interface definition for a callback to be invoked when the layout bounds of a view 8478 * changes due to layout processing. 8479 */ 8480 public interface OnLayoutChangeListener { 8481 /** 8482 * Called when the focus state of a view has changed. 8483 * 8484 * @param v The view whose state has changed. 8485 * @param left The new value of the view's left property. 8486 * @param top The new value of the view's top property. 8487 * @param right The new value of the view's right property. 8488 * @param bottom The new value of the view's bottom property. 8489 * @param oldLeft The previous value of the view's left property. 8490 * @param oldTop The previous value of the view's top property. 8491 * @param oldRight The previous value of the view's right property. 8492 * @param oldBottom The previous value of the view's bottom property. 8493 */ 8494 void onLayoutChange(View v, int left, int top, int right, int bottom, 8495 int oldLeft, int oldTop, int oldRight, int oldBottom); 8496 } 8497 8498 /** 8499 * This is called during layout when the size of this view has changed. If 8500 * you were just added to the view hierarchy, you're called with the old 8501 * values of 0. 8502 * 8503 * @param w Current width of this view. 8504 * @param h Current height of this view. 8505 * @param oldw Old width of this view. 8506 * @param oldh Old height of this view. 8507 */ 8508 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 8509 } 8510 8511 /** 8512 * Called by draw to draw the child views. This may be overridden 8513 * by derived classes to gain control just before its children are drawn 8514 * (but after its own view has been drawn). 8515 * @param canvas the canvas on which to draw the view 8516 */ 8517 protected void dispatchDraw(Canvas canvas) { 8518 8519 } 8520 8521 /** 8522 * Gets the parent of this view. Note that the parent is a 8523 * ViewParent and not necessarily a View. 8524 * 8525 * @return Parent of this view. 8526 */ 8527 public final ViewParent getParent() { 8528 return mParent; 8529 } 8530 8531 /** 8532 * Set the horizontal scrolled position of your view. This will cause a call to 8533 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8534 * invalidated. 8535 * @param value the x position to scroll to 8536 */ 8537 public void setScrollX(int value) { 8538 scrollTo(value, mScrollY); 8539 } 8540 8541 /** 8542 * Set the vertical scrolled position of your view. This will cause a call to 8543 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8544 * invalidated. 8545 * @param value the y position to scroll to 8546 */ 8547 public void setScrollY(int value) { 8548 scrollTo(mScrollX, value); 8549 } 8550 8551 /** 8552 * Return the scrolled left position of this view. This is the left edge of 8553 * the displayed part of your view. You do not need to draw any pixels 8554 * farther left, since those are outside of the frame of your view on 8555 * screen. 8556 * 8557 * @return The left edge of the displayed part of your view, in pixels. 8558 */ 8559 public final int getScrollX() { 8560 return mScrollX; 8561 } 8562 8563 /** 8564 * Return the scrolled top position of this view. This is the top edge of 8565 * the displayed part of your view. You do not need to draw any pixels above 8566 * it, since those are outside of the frame of your view on screen. 8567 * 8568 * @return The top edge of the displayed part of your view, in pixels. 8569 */ 8570 public final int getScrollY() { 8571 return mScrollY; 8572 } 8573 8574 /** 8575 * Return the width of the your view. 8576 * 8577 * @return The width of your view, in pixels. 8578 */ 8579 @ViewDebug.ExportedProperty(category = "layout") 8580 public final int getWidth() { 8581 return mRight - mLeft; 8582 } 8583 8584 /** 8585 * Return the height of your view. 8586 * 8587 * @return The height of your view, in pixels. 8588 */ 8589 @ViewDebug.ExportedProperty(category = "layout") 8590 public final int getHeight() { 8591 return mBottom - mTop; 8592 } 8593 8594 /** 8595 * Return the visible drawing bounds of your view. Fills in the output 8596 * rectangle with the values from getScrollX(), getScrollY(), 8597 * getWidth(), and getHeight(). 8598 * 8599 * @param outRect The (scrolled) drawing bounds of the view. 8600 */ 8601 public void getDrawingRect(Rect outRect) { 8602 outRect.left = mScrollX; 8603 outRect.top = mScrollY; 8604 outRect.right = mScrollX + (mRight - mLeft); 8605 outRect.bottom = mScrollY + (mBottom - mTop); 8606 } 8607 8608 /** 8609 * Like {@link #getMeasuredWidthAndState()}, but only returns the 8610 * raw width component (that is the result is masked by 8611 * {@link #MEASURED_SIZE_MASK}). 8612 * 8613 * @return The raw measured width of this view. 8614 */ 8615 public final int getMeasuredWidth() { 8616 return mMeasuredWidth & MEASURED_SIZE_MASK; 8617 } 8618 8619 /** 8620 * Return the full width measurement information for this view as computed 8621 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8622 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8623 * This should be used during measurement and layout calculations only. Use 8624 * {@link #getWidth()} to see how wide a view is after layout. 8625 * 8626 * @return The measured width of this view as a bit mask. 8627 */ 8628 public final int getMeasuredWidthAndState() { 8629 return mMeasuredWidth; 8630 } 8631 8632 /** 8633 * Like {@link #getMeasuredHeightAndState()}, but only returns the 8634 * raw width component (that is the result is masked by 8635 * {@link #MEASURED_SIZE_MASK}). 8636 * 8637 * @return The raw measured height of this view. 8638 */ 8639 public final int getMeasuredHeight() { 8640 return mMeasuredHeight & MEASURED_SIZE_MASK; 8641 } 8642 8643 /** 8644 * Return the full height measurement information for this view as computed 8645 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8646 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8647 * This should be used during measurement and layout calculations only. Use 8648 * {@link #getHeight()} to see how wide a view is after layout. 8649 * 8650 * @return The measured width of this view as a bit mask. 8651 */ 8652 public final int getMeasuredHeightAndState() { 8653 return mMeasuredHeight; 8654 } 8655 8656 /** 8657 * Return only the state bits of {@link #getMeasuredWidthAndState()} 8658 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 8659 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 8660 * and the height component is at the shifted bits 8661 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 8662 */ 8663 public final int getMeasuredState() { 8664 return (mMeasuredWidth&MEASURED_STATE_MASK) 8665 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 8666 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 8667 } 8668 8669 /** 8670 * The transform matrix of this view, which is calculated based on the current 8671 * roation, scale, and pivot properties. 8672 * 8673 * @see #getRotation() 8674 * @see #getScaleX() 8675 * @see #getScaleY() 8676 * @see #getPivotX() 8677 * @see #getPivotY() 8678 * @return The current transform matrix for the view 8679 */ 8680 public Matrix getMatrix() { 8681 if (mTransformationInfo != null) { 8682 updateMatrix(); 8683 return mTransformationInfo.mMatrix; 8684 } 8685 return Matrix.IDENTITY_MATRIX; 8686 } 8687 8688 /** 8689 * Utility function to determine if the value is far enough away from zero to be 8690 * considered non-zero. 8691 * @param value A floating point value to check for zero-ness 8692 * @return whether the passed-in value is far enough away from zero to be considered non-zero 8693 */ 8694 private static boolean nonzero(float value) { 8695 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 8696 } 8697 8698 /** 8699 * Returns true if the transform matrix is the identity matrix. 8700 * Recomputes the matrix if necessary. 8701 * 8702 * @return True if the transform matrix is the identity matrix, false otherwise. 8703 */ 8704 final boolean hasIdentityMatrix() { 8705 if (mTransformationInfo != null) { 8706 updateMatrix(); 8707 return mTransformationInfo.mMatrixIsIdentity; 8708 } 8709 return true; 8710 } 8711 8712 void ensureTransformationInfo() { 8713 if (mTransformationInfo == null) { 8714 mTransformationInfo = new TransformationInfo(); 8715 } 8716 } 8717 8718 /** 8719 * Recomputes the transform matrix if necessary. 8720 */ 8721 private void updateMatrix() { 8722 final TransformationInfo info = mTransformationInfo; 8723 if (info == null) { 8724 return; 8725 } 8726 if (info.mMatrixDirty) { 8727 // transform-related properties have changed since the last time someone 8728 // asked for the matrix; recalculate it with the current values 8729 8730 // Figure out if we need to update the pivot point 8731 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 8732 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 8733 info.mPrevWidth = mRight - mLeft; 8734 info.mPrevHeight = mBottom - mTop; 8735 info.mPivotX = info.mPrevWidth / 2f; 8736 info.mPivotY = info.mPrevHeight / 2f; 8737 } 8738 } 8739 info.mMatrix.reset(); 8740 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 8741 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 8742 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 8743 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 8744 } else { 8745 if (info.mCamera == null) { 8746 info.mCamera = new Camera(); 8747 info.matrix3D = new Matrix(); 8748 } 8749 info.mCamera.save(); 8750 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 8751 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 8752 info.mCamera.getMatrix(info.matrix3D); 8753 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 8754 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 8755 info.mPivotY + info.mTranslationY); 8756 info.mMatrix.postConcat(info.matrix3D); 8757 info.mCamera.restore(); 8758 } 8759 info.mMatrixDirty = false; 8760 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 8761 info.mInverseMatrixDirty = true; 8762 } 8763 } 8764 8765 /** 8766 * Utility method to retrieve the inverse of the current mMatrix property. 8767 * We cache the matrix to avoid recalculating it when transform properties 8768 * have not changed. 8769 * 8770 * @return The inverse of the current matrix of this view. 8771 */ 8772 final Matrix getInverseMatrix() { 8773 final TransformationInfo info = mTransformationInfo; 8774 if (info != null) { 8775 updateMatrix(); 8776 if (info.mInverseMatrixDirty) { 8777 if (info.mInverseMatrix == null) { 8778 info.mInverseMatrix = new Matrix(); 8779 } 8780 info.mMatrix.invert(info.mInverseMatrix); 8781 info.mInverseMatrixDirty = false; 8782 } 8783 return info.mInverseMatrix; 8784 } 8785 return Matrix.IDENTITY_MATRIX; 8786 } 8787 8788 /** 8789 * Gets the distance along the Z axis from the camera to this view. 8790 * 8791 * @see #setCameraDistance(float) 8792 * 8793 * @return The distance along the Z axis. 8794 */ 8795 public float getCameraDistance() { 8796 ensureTransformationInfo(); 8797 final float dpi = mResources.getDisplayMetrics().densityDpi; 8798 final TransformationInfo info = mTransformationInfo; 8799 if (info.mCamera == null) { 8800 info.mCamera = new Camera(); 8801 info.matrix3D = new Matrix(); 8802 } 8803 return -(info.mCamera.getLocationZ() * dpi); 8804 } 8805 8806 /** 8807 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 8808 * views are drawn) from the camera to this view. The camera's distance 8809 * affects 3D transformations, for instance rotations around the X and Y 8810 * axis. If the rotationX or rotationY properties are changed and this view is 8811 * large (more than half the size of the screen), it is recommended to always 8812 * use a camera distance that's greater than the height (X axis rotation) or 8813 * the width (Y axis rotation) of this view.</p> 8814 * 8815 * <p>The distance of the camera from the view plane can have an affect on the 8816 * perspective distortion of the view when it is rotated around the x or y axis. 8817 * For example, a large distance will result in a large viewing angle, and there 8818 * will not be much perspective distortion of the view as it rotates. A short 8819 * distance may cause much more perspective distortion upon rotation, and can 8820 * also result in some drawing artifacts if the rotated view ends up partially 8821 * behind the camera (which is why the recommendation is to use a distance at 8822 * least as far as the size of the view, if the view is to be rotated.)</p> 8823 * 8824 * <p>The distance is expressed in "depth pixels." The default distance depends 8825 * on the screen density. For instance, on a medium density display, the 8826 * default distance is 1280. On a high density display, the default distance 8827 * is 1920.</p> 8828 * 8829 * <p>If you want to specify a distance that leads to visually consistent 8830 * results across various densities, use the following formula:</p> 8831 * <pre> 8832 * float scale = context.getResources().getDisplayMetrics().density; 8833 * view.setCameraDistance(distance * scale); 8834 * </pre> 8835 * 8836 * <p>The density scale factor of a high density display is 1.5, 8837 * and 1920 = 1280 * 1.5.</p> 8838 * 8839 * @param distance The distance in "depth pixels", if negative the opposite 8840 * value is used 8841 * 8842 * @see #setRotationX(float) 8843 * @see #setRotationY(float) 8844 */ 8845 public void setCameraDistance(float distance) { 8846 invalidateViewProperty(true, false); 8847 8848 ensureTransformationInfo(); 8849 final float dpi = mResources.getDisplayMetrics().densityDpi; 8850 final TransformationInfo info = mTransformationInfo; 8851 if (info.mCamera == null) { 8852 info.mCamera = new Camera(); 8853 info.matrix3D = new Matrix(); 8854 } 8855 8856 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 8857 info.mMatrixDirty = true; 8858 8859 invalidateViewProperty(false, false); 8860 if (mDisplayList != null) { 8861 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 8862 } 8863 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 8864 // View was rejected last time it was drawn by its parent; this may have changed 8865 invalidateParentIfNeeded(); 8866 } 8867 } 8868 8869 /** 8870 * The degrees that the view is rotated around the pivot point. 8871 * 8872 * @see #setRotation(float) 8873 * @see #getPivotX() 8874 * @see #getPivotY() 8875 * 8876 * @return The degrees of rotation. 8877 */ 8878 @ViewDebug.ExportedProperty(category = "drawing") 8879 public float getRotation() { 8880 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 8881 } 8882 8883 /** 8884 * Sets the degrees that the view is rotated around the pivot point. Increasing values 8885 * result in clockwise rotation. 8886 * 8887 * @param rotation The degrees of rotation. 8888 * 8889 * @see #getRotation() 8890 * @see #getPivotX() 8891 * @see #getPivotY() 8892 * @see #setRotationX(float) 8893 * @see #setRotationY(float) 8894 * 8895 * @attr ref android.R.styleable#View_rotation 8896 */ 8897 public void setRotation(float rotation) { 8898 ensureTransformationInfo(); 8899 final TransformationInfo info = mTransformationInfo; 8900 if (info.mRotation != rotation) { 8901 // Double-invalidation is necessary to capture view's old and new areas 8902 invalidateViewProperty(true, false); 8903 info.mRotation = rotation; 8904 info.mMatrixDirty = true; 8905 invalidateViewProperty(false, true); 8906 if (mDisplayList != null) { 8907 mDisplayList.setRotation(rotation); 8908 } 8909 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 8910 // View was rejected last time it was drawn by its parent; this may have changed 8911 invalidateParentIfNeeded(); 8912 } 8913 } 8914 } 8915 8916 /** 8917 * The degrees that the view is rotated around the vertical axis through the pivot point. 8918 * 8919 * @see #getPivotX() 8920 * @see #getPivotY() 8921 * @see #setRotationY(float) 8922 * 8923 * @return The degrees of Y rotation. 8924 */ 8925 @ViewDebug.ExportedProperty(category = "drawing") 8926 public float getRotationY() { 8927 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 8928 } 8929 8930 /** 8931 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 8932 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 8933 * down the y axis. 8934 * 8935 * When rotating large views, it is recommended to adjust the camera distance 8936 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 8937 * 8938 * @param rotationY The degrees of Y rotation. 8939 * 8940 * @see #getRotationY() 8941 * @see #getPivotX() 8942 * @see #getPivotY() 8943 * @see #setRotation(float) 8944 * @see #setRotationX(float) 8945 * @see #setCameraDistance(float) 8946 * 8947 * @attr ref android.R.styleable#View_rotationY 8948 */ 8949 public void setRotationY(float rotationY) { 8950 ensureTransformationInfo(); 8951 final TransformationInfo info = mTransformationInfo; 8952 if (info.mRotationY != rotationY) { 8953 invalidateViewProperty(true, false); 8954 info.mRotationY = rotationY; 8955 info.mMatrixDirty = true; 8956 invalidateViewProperty(false, true); 8957 if (mDisplayList != null) { 8958 mDisplayList.setRotationY(rotationY); 8959 } 8960 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 8961 // View was rejected last time it was drawn by its parent; this may have changed 8962 invalidateParentIfNeeded(); 8963 } 8964 } 8965 } 8966 8967 /** 8968 * The degrees that the view is rotated around the horizontal axis through the pivot point. 8969 * 8970 * @see #getPivotX() 8971 * @see #getPivotY() 8972 * @see #setRotationX(float) 8973 * 8974 * @return The degrees of X rotation. 8975 */ 8976 @ViewDebug.ExportedProperty(category = "drawing") 8977 public float getRotationX() { 8978 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 8979 } 8980 8981 /** 8982 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 8983 * Increasing values result in clockwise rotation from the viewpoint of looking down the 8984 * x axis. 8985 * 8986 * When rotating large views, it is recommended to adjust the camera distance 8987 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 8988 * 8989 * @param rotationX The degrees of X rotation. 8990 * 8991 * @see #getRotationX() 8992 * @see #getPivotX() 8993 * @see #getPivotY() 8994 * @see #setRotation(float) 8995 * @see #setRotationY(float) 8996 * @see #setCameraDistance(float) 8997 * 8998 * @attr ref android.R.styleable#View_rotationX 8999 */ 9000 public void setRotationX(float rotationX) { 9001 ensureTransformationInfo(); 9002 final TransformationInfo info = mTransformationInfo; 9003 if (info.mRotationX != rotationX) { 9004 invalidateViewProperty(true, false); 9005 info.mRotationX = rotationX; 9006 info.mMatrixDirty = true; 9007 invalidateViewProperty(false, true); 9008 if (mDisplayList != null) { 9009 mDisplayList.setRotationX(rotationX); 9010 } 9011 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9012 // View was rejected last time it was drawn by its parent; this may have changed 9013 invalidateParentIfNeeded(); 9014 } 9015 } 9016 } 9017 9018 /** 9019 * The amount that the view is scaled in x around the pivot point, as a proportion of 9020 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9021 * 9022 * <p>By default, this is 1.0f. 9023 * 9024 * @see #getPivotX() 9025 * @see #getPivotY() 9026 * @return The scaling factor. 9027 */ 9028 @ViewDebug.ExportedProperty(category = "drawing") 9029 public float getScaleX() { 9030 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 9031 } 9032 9033 /** 9034 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9035 * the view's unscaled width. A value of 1 means that no scaling is applied. 9036 * 9037 * @param scaleX The scaling factor. 9038 * @see #getPivotX() 9039 * @see #getPivotY() 9040 * 9041 * @attr ref android.R.styleable#View_scaleX 9042 */ 9043 public void setScaleX(float scaleX) { 9044 ensureTransformationInfo(); 9045 final TransformationInfo info = mTransformationInfo; 9046 if (info.mScaleX != scaleX) { 9047 invalidateViewProperty(true, false); 9048 info.mScaleX = scaleX; 9049 info.mMatrixDirty = true; 9050 invalidateViewProperty(false, true); 9051 if (mDisplayList != null) { 9052 mDisplayList.setScaleX(scaleX); 9053 } 9054 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9055 // View was rejected last time it was drawn by its parent; this may have changed 9056 invalidateParentIfNeeded(); 9057 } 9058 } 9059 } 9060 9061 /** 9062 * The amount that the view is scaled in y around the pivot point, as a proportion of 9063 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9064 * 9065 * <p>By default, this is 1.0f. 9066 * 9067 * @see #getPivotX() 9068 * @see #getPivotY() 9069 * @return The scaling factor. 9070 */ 9071 @ViewDebug.ExportedProperty(category = "drawing") 9072 public float getScaleY() { 9073 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 9074 } 9075 9076 /** 9077 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9078 * the view's unscaled width. A value of 1 means that no scaling is applied. 9079 * 9080 * @param scaleY The scaling factor. 9081 * @see #getPivotX() 9082 * @see #getPivotY() 9083 * 9084 * @attr ref android.R.styleable#View_scaleY 9085 */ 9086 public void setScaleY(float scaleY) { 9087 ensureTransformationInfo(); 9088 final TransformationInfo info = mTransformationInfo; 9089 if (info.mScaleY != scaleY) { 9090 invalidateViewProperty(true, false); 9091 info.mScaleY = scaleY; 9092 info.mMatrixDirty = true; 9093 invalidateViewProperty(false, true); 9094 if (mDisplayList != null) { 9095 mDisplayList.setScaleY(scaleY); 9096 } 9097 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9098 // View was rejected last time it was drawn by its parent; this may have changed 9099 invalidateParentIfNeeded(); 9100 } 9101 } 9102 } 9103 9104 /** 9105 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9106 * and {@link #setScaleX(float) scaled}. 9107 * 9108 * @see #getRotation() 9109 * @see #getScaleX() 9110 * @see #getScaleY() 9111 * @see #getPivotY() 9112 * @return The x location of the pivot point. 9113 * 9114 * @attr ref android.R.styleable#View_transformPivotX 9115 */ 9116 @ViewDebug.ExportedProperty(category = "drawing") 9117 public float getPivotX() { 9118 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 9119 } 9120 9121 /** 9122 * Sets the x location of the point around which the view is 9123 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9124 * By default, the pivot point is centered on the object. 9125 * Setting this property disables this behavior and causes the view to use only the 9126 * explicitly set pivotX and pivotY values. 9127 * 9128 * @param pivotX The x location of the pivot point. 9129 * @see #getRotation() 9130 * @see #getScaleX() 9131 * @see #getScaleY() 9132 * @see #getPivotY() 9133 * 9134 * @attr ref android.R.styleable#View_transformPivotX 9135 */ 9136 public void setPivotX(float pivotX) { 9137 ensureTransformationInfo(); 9138 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9139 final TransformationInfo info = mTransformationInfo; 9140 if (info.mPivotX != pivotX) { 9141 invalidateViewProperty(true, false); 9142 info.mPivotX = pivotX; 9143 info.mMatrixDirty = true; 9144 invalidateViewProperty(false, true); 9145 if (mDisplayList != null) { 9146 mDisplayList.setPivotX(pivotX); 9147 } 9148 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9149 // View was rejected last time it was drawn by its parent; this may have changed 9150 invalidateParentIfNeeded(); 9151 } 9152 } 9153 } 9154 9155 /** 9156 * The y location of the point around which the view is {@link #setRotation(float) rotated} 9157 * and {@link #setScaleY(float) scaled}. 9158 * 9159 * @see #getRotation() 9160 * @see #getScaleX() 9161 * @see #getScaleY() 9162 * @see #getPivotY() 9163 * @return The y location of the pivot point. 9164 * 9165 * @attr ref android.R.styleable#View_transformPivotY 9166 */ 9167 @ViewDebug.ExportedProperty(category = "drawing") 9168 public float getPivotY() { 9169 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 9170 } 9171 9172 /** 9173 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 9174 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 9175 * Setting this property disables this behavior and causes the view to use only the 9176 * explicitly set pivotX and pivotY values. 9177 * 9178 * @param pivotY The y location of the pivot point. 9179 * @see #getRotation() 9180 * @see #getScaleX() 9181 * @see #getScaleY() 9182 * @see #getPivotY() 9183 * 9184 * @attr ref android.R.styleable#View_transformPivotY 9185 */ 9186 public void setPivotY(float pivotY) { 9187 ensureTransformationInfo(); 9188 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9189 final TransformationInfo info = mTransformationInfo; 9190 if (info.mPivotY != pivotY) { 9191 invalidateViewProperty(true, false); 9192 info.mPivotY = pivotY; 9193 info.mMatrixDirty = true; 9194 invalidateViewProperty(false, true); 9195 if (mDisplayList != null) { 9196 mDisplayList.setPivotY(pivotY); 9197 } 9198 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9199 // View was rejected last time it was drawn by its parent; this may have changed 9200 invalidateParentIfNeeded(); 9201 } 9202 } 9203 } 9204 9205 /** 9206 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 9207 * completely transparent and 1 means the view is completely opaque. 9208 * 9209 * <p>By default this is 1.0f. 9210 * @return The opacity of the view. 9211 */ 9212 @ViewDebug.ExportedProperty(category = "drawing") 9213 public float getAlpha() { 9214 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 9215 } 9216 9217 /** 9218 * Returns whether this View has content which overlaps. This function, intended to be 9219 * overridden by specific View types, is an optimization when alpha is set on a view. If 9220 * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer 9221 * and then composited it into place, which can be expensive. If the view has no overlapping 9222 * rendering, the view can draw each primitive with the appropriate alpha value directly. 9223 * An example of overlapping rendering is a TextView with a background image, such as a 9224 * Button. An example of non-overlapping rendering is a TextView with no background, or 9225 * an ImageView with only the foreground image. The default implementation returns true; 9226 * subclasses should override if they have cases which can be optimized. 9227 * 9228 * @return true if the content in this view might overlap, false otherwise. 9229 */ 9230 public boolean hasOverlappingRendering() { 9231 return true; 9232 } 9233 9234 /** 9235 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 9236 * completely transparent and 1 means the view is completely opaque.</p> 9237 * 9238 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 9239 * responsible for applying the opacity itself. Otherwise, calling this method is 9240 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 9241 * setting a hardware layer.</p> 9242 * 9243 * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have 9244 * performance implications. It is generally best to use the alpha property sparingly and 9245 * transiently, as in the case of fading animations.</p> 9246 * 9247 * @param alpha The opacity of the view. 9248 * 9249 * @see #setLayerType(int, android.graphics.Paint) 9250 * 9251 * @attr ref android.R.styleable#View_alpha 9252 */ 9253 public void setAlpha(float alpha) { 9254 ensureTransformationInfo(); 9255 if (mTransformationInfo.mAlpha != alpha) { 9256 mTransformationInfo.mAlpha = alpha; 9257 if (onSetAlpha((int) (alpha * 255))) { 9258 mPrivateFlags |= PFLAG_ALPHA_SET; 9259 // subclass is handling alpha - don't optimize rendering cache invalidation 9260 invalidateParentCaches(); 9261 invalidate(true); 9262 } else { 9263 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9264 invalidateViewProperty(true, false); 9265 if (mDisplayList != null) { 9266 mDisplayList.setAlpha(alpha); 9267 } 9268 } 9269 } 9270 } 9271 9272 /** 9273 * Faster version of setAlpha() which performs the same steps except there are 9274 * no calls to invalidate(). The caller of this function should perform proper invalidation 9275 * on the parent and this object. The return value indicates whether the subclass handles 9276 * alpha (the return value for onSetAlpha()). 9277 * 9278 * @param alpha The new value for the alpha property 9279 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 9280 * the new value for the alpha property is different from the old value 9281 */ 9282 boolean setAlphaNoInvalidation(float alpha) { 9283 ensureTransformationInfo(); 9284 if (mTransformationInfo.mAlpha != alpha) { 9285 mTransformationInfo.mAlpha = alpha; 9286 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 9287 if (subclassHandlesAlpha) { 9288 mPrivateFlags |= PFLAG_ALPHA_SET; 9289 return true; 9290 } else { 9291 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9292 if (mDisplayList != null) { 9293 mDisplayList.setAlpha(alpha); 9294 } 9295 } 9296 } 9297 return false; 9298 } 9299 9300 /** 9301 * Top position of this view relative to its parent. 9302 * 9303 * @return The top of this view, in pixels. 9304 */ 9305 @ViewDebug.CapturedViewProperty 9306 public final int getTop() { 9307 return mTop; 9308 } 9309 9310 /** 9311 * Sets the top position of this view relative to its parent. This method is meant to be called 9312 * by the layout system and should not generally be called otherwise, because the property 9313 * may be changed at any time by the layout. 9314 * 9315 * @param top The top of this view, in pixels. 9316 */ 9317 public final void setTop(int top) { 9318 if (top != mTop) { 9319 updateMatrix(); 9320 final boolean matrixIsIdentity = mTransformationInfo == null 9321 || mTransformationInfo.mMatrixIsIdentity; 9322 if (matrixIsIdentity) { 9323 if (mAttachInfo != null) { 9324 int minTop; 9325 int yLoc; 9326 if (top < mTop) { 9327 minTop = top; 9328 yLoc = top - mTop; 9329 } else { 9330 minTop = mTop; 9331 yLoc = 0; 9332 } 9333 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 9334 } 9335 } else { 9336 // Double-invalidation is necessary to capture view's old and new areas 9337 invalidate(true); 9338 } 9339 9340 int width = mRight - mLeft; 9341 int oldHeight = mBottom - mTop; 9342 9343 mTop = top; 9344 if (mDisplayList != null) { 9345 mDisplayList.setTop(mTop); 9346 } 9347 9348 onSizeChanged(width, mBottom - mTop, width, oldHeight); 9349 9350 if (!matrixIsIdentity) { 9351 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9352 // A change in dimension means an auto-centered pivot point changes, too 9353 mTransformationInfo.mMatrixDirty = true; 9354 } 9355 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9356 invalidate(true); 9357 } 9358 mBackgroundSizeChanged = true; 9359 invalidateParentIfNeeded(); 9360 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9361 // View was rejected last time it was drawn by its parent; this may have changed 9362 invalidateParentIfNeeded(); 9363 } 9364 } 9365 } 9366 9367 /** 9368 * Bottom position of this view relative to its parent. 9369 * 9370 * @return The bottom of this view, in pixels. 9371 */ 9372 @ViewDebug.CapturedViewProperty 9373 public final int getBottom() { 9374 return mBottom; 9375 } 9376 9377 /** 9378 * True if this view has changed since the last time being drawn. 9379 * 9380 * @return The dirty state of this view. 9381 */ 9382 public boolean isDirty() { 9383 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 9384 } 9385 9386 /** 9387 * Sets the bottom position of this view relative to its parent. This method is meant to be 9388 * called by the layout system and should not generally be called otherwise, because the 9389 * property may be changed at any time by the layout. 9390 * 9391 * @param bottom The bottom of this view, in pixels. 9392 */ 9393 public final void setBottom(int bottom) { 9394 if (bottom != mBottom) { 9395 updateMatrix(); 9396 final boolean matrixIsIdentity = mTransformationInfo == null 9397 || mTransformationInfo.mMatrixIsIdentity; 9398 if (matrixIsIdentity) { 9399 if (mAttachInfo != null) { 9400 int maxBottom; 9401 if (bottom < mBottom) { 9402 maxBottom = mBottom; 9403 } else { 9404 maxBottom = bottom; 9405 } 9406 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 9407 } 9408 } else { 9409 // Double-invalidation is necessary to capture view's old and new areas 9410 invalidate(true); 9411 } 9412 9413 int width = mRight - mLeft; 9414 int oldHeight = mBottom - mTop; 9415 9416 mBottom = bottom; 9417 if (mDisplayList != null) { 9418 mDisplayList.setBottom(mBottom); 9419 } 9420 9421 onSizeChanged(width, mBottom - mTop, width, oldHeight); 9422 9423 if (!matrixIsIdentity) { 9424 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9425 // A change in dimension means an auto-centered pivot point changes, too 9426 mTransformationInfo.mMatrixDirty = true; 9427 } 9428 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9429 invalidate(true); 9430 } 9431 mBackgroundSizeChanged = true; 9432 invalidateParentIfNeeded(); 9433 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9434 // View was rejected last time it was drawn by its parent; this may have changed 9435 invalidateParentIfNeeded(); 9436 } 9437 } 9438 } 9439 9440 /** 9441 * Left position of this view relative to its parent. 9442 * 9443 * @return The left edge of this view, in pixels. 9444 */ 9445 @ViewDebug.CapturedViewProperty 9446 public final int getLeft() { 9447 return mLeft; 9448 } 9449 9450 /** 9451 * Sets the left position of this view relative to its parent. This method is meant to be called 9452 * by the layout system and should not generally be called otherwise, because the property 9453 * may be changed at any time by the layout. 9454 * 9455 * @param left The bottom of this view, in pixels. 9456 */ 9457 public final void setLeft(int left) { 9458 if (left != mLeft) { 9459 updateMatrix(); 9460 final boolean matrixIsIdentity = mTransformationInfo == null 9461 || mTransformationInfo.mMatrixIsIdentity; 9462 if (matrixIsIdentity) { 9463 if (mAttachInfo != null) { 9464 int minLeft; 9465 int xLoc; 9466 if (left < mLeft) { 9467 minLeft = left; 9468 xLoc = left - mLeft; 9469 } else { 9470 minLeft = mLeft; 9471 xLoc = 0; 9472 } 9473 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 9474 } 9475 } else { 9476 // Double-invalidation is necessary to capture view's old and new areas 9477 invalidate(true); 9478 } 9479 9480 int oldWidth = mRight - mLeft; 9481 int height = mBottom - mTop; 9482 9483 mLeft = left; 9484 if (mDisplayList != null) { 9485 mDisplayList.setLeft(left); 9486 } 9487 9488 onSizeChanged(mRight - mLeft, height, oldWidth, height); 9489 9490 if (!matrixIsIdentity) { 9491 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9492 // A change in dimension means an auto-centered pivot point changes, too 9493 mTransformationInfo.mMatrixDirty = true; 9494 } 9495 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9496 invalidate(true); 9497 } 9498 mBackgroundSizeChanged = true; 9499 invalidateParentIfNeeded(); 9500 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9501 // View was rejected last time it was drawn by its parent; this may have changed 9502 invalidateParentIfNeeded(); 9503 } 9504 } 9505 } 9506 9507 /** 9508 * Right position of this view relative to its parent. 9509 * 9510 * @return The right edge of this view, in pixels. 9511 */ 9512 @ViewDebug.CapturedViewProperty 9513 public final int getRight() { 9514 return mRight; 9515 } 9516 9517 /** 9518 * Sets the right position of this view relative to its parent. This method is meant to be called 9519 * by the layout system and should not generally be called otherwise, because the property 9520 * may be changed at any time by the layout. 9521 * 9522 * @param right The bottom of this view, in pixels. 9523 */ 9524 public final void setRight(int right) { 9525 if (right != mRight) { 9526 updateMatrix(); 9527 final boolean matrixIsIdentity = mTransformationInfo == null 9528 || mTransformationInfo.mMatrixIsIdentity; 9529 if (matrixIsIdentity) { 9530 if (mAttachInfo != null) { 9531 int maxRight; 9532 if (right < mRight) { 9533 maxRight = mRight; 9534 } else { 9535 maxRight = right; 9536 } 9537 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 9538 } 9539 } else { 9540 // Double-invalidation is necessary to capture view's old and new areas 9541 invalidate(true); 9542 } 9543 9544 int oldWidth = mRight - mLeft; 9545 int height = mBottom - mTop; 9546 9547 mRight = right; 9548 if (mDisplayList != null) { 9549 mDisplayList.setRight(mRight); 9550 } 9551 9552 onSizeChanged(mRight - mLeft, height, oldWidth, height); 9553 9554 if (!matrixIsIdentity) { 9555 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9556 // A change in dimension means an auto-centered pivot point changes, too 9557 mTransformationInfo.mMatrixDirty = true; 9558 } 9559 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9560 invalidate(true); 9561 } 9562 mBackgroundSizeChanged = true; 9563 invalidateParentIfNeeded(); 9564 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9565 // View was rejected last time it was drawn by its parent; this may have changed 9566 invalidateParentIfNeeded(); 9567 } 9568 } 9569 } 9570 9571 /** 9572 * The visual x position of this view, in pixels. This is equivalent to the 9573 * {@link #setTranslationX(float) translationX} property plus the current 9574 * {@link #getLeft() left} property. 9575 * 9576 * @return The visual x position of this view, in pixels. 9577 */ 9578 @ViewDebug.ExportedProperty(category = "drawing") 9579 public float getX() { 9580 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 9581 } 9582 9583 /** 9584 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 9585 * {@link #setTranslationX(float) translationX} property to be the difference between 9586 * the x value passed in and the current {@link #getLeft() left} property. 9587 * 9588 * @param x The visual x position of this view, in pixels. 9589 */ 9590 public void setX(float x) { 9591 setTranslationX(x - mLeft); 9592 } 9593 9594 /** 9595 * The visual y position of this view, in pixels. This is equivalent to the 9596 * {@link #setTranslationY(float) translationY} property plus the current 9597 * {@link #getTop() top} property. 9598 * 9599 * @return The visual y position of this view, in pixels. 9600 */ 9601 @ViewDebug.ExportedProperty(category = "drawing") 9602 public float getY() { 9603 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 9604 } 9605 9606 /** 9607 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 9608 * {@link #setTranslationY(float) translationY} property to be the difference between 9609 * the y value passed in and the current {@link #getTop() top} property. 9610 * 9611 * @param y The visual y position of this view, in pixels. 9612 */ 9613 public void setY(float y) { 9614 setTranslationY(y - mTop); 9615 } 9616 9617 9618 /** 9619 * The horizontal location of this view relative to its {@link #getLeft() left} position. 9620 * This position is post-layout, in addition to wherever the object's 9621 * layout placed it. 9622 * 9623 * @return The horizontal position of this view relative to its left position, in pixels. 9624 */ 9625 @ViewDebug.ExportedProperty(category = "drawing") 9626 public float getTranslationX() { 9627 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 9628 } 9629 9630 /** 9631 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 9632 * This effectively positions the object post-layout, in addition to wherever the object's 9633 * layout placed it. 9634 * 9635 * @param translationX The horizontal position of this view relative to its left position, 9636 * in pixels. 9637 * 9638 * @attr ref android.R.styleable#View_translationX 9639 */ 9640 public void setTranslationX(float translationX) { 9641 ensureTransformationInfo(); 9642 final TransformationInfo info = mTransformationInfo; 9643 if (info.mTranslationX != translationX) { 9644 // Double-invalidation is necessary to capture view's old and new areas 9645 invalidateViewProperty(true, false); 9646 info.mTranslationX = translationX; 9647 info.mMatrixDirty = true; 9648 invalidateViewProperty(false, true); 9649 if (mDisplayList != null) { 9650 mDisplayList.setTranslationX(translationX); 9651 } 9652 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9653 // View was rejected last time it was drawn by its parent; this may have changed 9654 invalidateParentIfNeeded(); 9655 } 9656 } 9657 } 9658 9659 /** 9660 * The horizontal location of this view relative to its {@link #getTop() top} position. 9661 * This position is post-layout, in addition to wherever the object's 9662 * layout placed it. 9663 * 9664 * @return The vertical position of this view relative to its top position, 9665 * in pixels. 9666 */ 9667 @ViewDebug.ExportedProperty(category = "drawing") 9668 public float getTranslationY() { 9669 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 9670 } 9671 9672 /** 9673 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 9674 * This effectively positions the object post-layout, in addition to wherever the object's 9675 * layout placed it. 9676 * 9677 * @param translationY The vertical position of this view relative to its top position, 9678 * in pixels. 9679 * 9680 * @attr ref android.R.styleable#View_translationY 9681 */ 9682 public void setTranslationY(float translationY) { 9683 ensureTransformationInfo(); 9684 final TransformationInfo info = mTransformationInfo; 9685 if (info.mTranslationY != translationY) { 9686 invalidateViewProperty(true, false); 9687 info.mTranslationY = translationY; 9688 info.mMatrixDirty = true; 9689 invalidateViewProperty(false, true); 9690 if (mDisplayList != null) { 9691 mDisplayList.setTranslationY(translationY); 9692 } 9693 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9694 // View was rejected last time it was drawn by its parent; this may have changed 9695 invalidateParentIfNeeded(); 9696 } 9697 } 9698 } 9699 9700 /** 9701 * Hit rectangle in parent's coordinates 9702 * 9703 * @param outRect The hit rectangle of the view. 9704 */ 9705 public void getHitRect(Rect outRect) { 9706 updateMatrix(); 9707 final TransformationInfo info = mTransformationInfo; 9708 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 9709 outRect.set(mLeft, mTop, mRight, mBottom); 9710 } else { 9711 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 9712 tmpRect.set(-info.mPivotX, -info.mPivotY, 9713 getWidth() - info.mPivotX, getHeight() - info.mPivotY); 9714 info.mMatrix.mapRect(tmpRect); 9715 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 9716 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 9717 } 9718 } 9719 9720 /** 9721 * Determines whether the given point, in local coordinates is inside the view. 9722 */ 9723 /*package*/ final boolean pointInView(float localX, float localY) { 9724 return localX >= 0 && localX < (mRight - mLeft) 9725 && localY >= 0 && localY < (mBottom - mTop); 9726 } 9727 9728 /** 9729 * Utility method to determine whether the given point, in local coordinates, 9730 * is inside the view, where the area of the view is expanded by the slop factor. 9731 * This method is called while processing touch-move events to determine if the event 9732 * is still within the view. 9733 */ 9734 private boolean pointInView(float localX, float localY, float slop) { 9735 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 9736 localY < ((mBottom - mTop) + slop); 9737 } 9738 9739 /** 9740 * When a view has focus and the user navigates away from it, the next view is searched for 9741 * starting from the rectangle filled in by this method. 9742 * 9743 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 9744 * of the view. However, if your view maintains some idea of internal selection, 9745 * such as a cursor, or a selected row or column, you should override this method and 9746 * fill in a more specific rectangle. 9747 * 9748 * @param r The rectangle to fill in, in this view's coordinates. 9749 */ 9750 public void getFocusedRect(Rect r) { 9751 getDrawingRect(r); 9752 } 9753 9754 /** 9755 * If some part of this view is not clipped by any of its parents, then 9756 * return that area in r in global (root) coordinates. To convert r to local 9757 * coordinates (without taking possible View rotations into account), offset 9758 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 9759 * If the view is completely clipped or translated out, return false. 9760 * 9761 * @param r If true is returned, r holds the global coordinates of the 9762 * visible portion of this view. 9763 * @param globalOffset If true is returned, globalOffset holds the dx,dy 9764 * between this view and its root. globalOffet may be null. 9765 * @return true if r is non-empty (i.e. part of the view is visible at the 9766 * root level. 9767 */ 9768 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 9769 int width = mRight - mLeft; 9770 int height = mBottom - mTop; 9771 if (width > 0 && height > 0) { 9772 r.set(0, 0, width, height); 9773 if (globalOffset != null) { 9774 globalOffset.set(-mScrollX, -mScrollY); 9775 } 9776 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 9777 } 9778 return false; 9779 } 9780 9781 public final boolean getGlobalVisibleRect(Rect r) { 9782 return getGlobalVisibleRect(r, null); 9783 } 9784 9785 public final boolean getLocalVisibleRect(Rect r) { 9786 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 9787 if (getGlobalVisibleRect(r, offset)) { 9788 r.offset(-offset.x, -offset.y); // make r local 9789 return true; 9790 } 9791 return false; 9792 } 9793 9794 /** 9795 * Offset this view's vertical location by the specified number of pixels. 9796 * 9797 * @param offset the number of pixels to offset the view by 9798 */ 9799 public void offsetTopAndBottom(int offset) { 9800 if (offset != 0) { 9801 updateMatrix(); 9802 final boolean matrixIsIdentity = mTransformationInfo == null 9803 || mTransformationInfo.mMatrixIsIdentity; 9804 if (matrixIsIdentity) { 9805 if (mDisplayList != null) { 9806 invalidateViewProperty(false, false); 9807 } else { 9808 final ViewParent p = mParent; 9809 if (p != null && mAttachInfo != null) { 9810 final Rect r = mAttachInfo.mTmpInvalRect; 9811 int minTop; 9812 int maxBottom; 9813 int yLoc; 9814 if (offset < 0) { 9815 minTop = mTop + offset; 9816 maxBottom = mBottom; 9817 yLoc = offset; 9818 } else { 9819 minTop = mTop; 9820 maxBottom = mBottom + offset; 9821 yLoc = 0; 9822 } 9823 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 9824 p.invalidateChild(this, r); 9825 } 9826 } 9827 } else { 9828 invalidateViewProperty(false, false); 9829 } 9830 9831 mTop += offset; 9832 mBottom += offset; 9833 if (mDisplayList != null) { 9834 mDisplayList.offsetTopBottom(offset); 9835 invalidateViewProperty(false, false); 9836 } else { 9837 if (!matrixIsIdentity) { 9838 invalidateViewProperty(false, true); 9839 } 9840 invalidateParentIfNeeded(); 9841 } 9842 } 9843 } 9844 9845 /** 9846 * Offset this view's horizontal location by the specified amount of pixels. 9847 * 9848 * @param offset the numer of pixels to offset the view by 9849 */ 9850 public void offsetLeftAndRight(int offset) { 9851 if (offset != 0) { 9852 updateMatrix(); 9853 final boolean matrixIsIdentity = mTransformationInfo == null 9854 || mTransformationInfo.mMatrixIsIdentity; 9855 if (matrixIsIdentity) { 9856 if (mDisplayList != null) { 9857 invalidateViewProperty(false, false); 9858 } else { 9859 final ViewParent p = mParent; 9860 if (p != null && mAttachInfo != null) { 9861 final Rect r = mAttachInfo.mTmpInvalRect; 9862 int minLeft; 9863 int maxRight; 9864 if (offset < 0) { 9865 minLeft = mLeft + offset; 9866 maxRight = mRight; 9867 } else { 9868 minLeft = mLeft; 9869 maxRight = mRight + offset; 9870 } 9871 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 9872 p.invalidateChild(this, r); 9873 } 9874 } 9875 } else { 9876 invalidateViewProperty(false, false); 9877 } 9878 9879 mLeft += offset; 9880 mRight += offset; 9881 if (mDisplayList != null) { 9882 mDisplayList.offsetLeftRight(offset); 9883 invalidateViewProperty(false, false); 9884 } else { 9885 if (!matrixIsIdentity) { 9886 invalidateViewProperty(false, true); 9887 } 9888 invalidateParentIfNeeded(); 9889 } 9890 } 9891 } 9892 9893 /** 9894 * Get the LayoutParams associated with this view. All views should have 9895 * layout parameters. These supply parameters to the <i>parent</i> of this 9896 * view specifying how it should be arranged. There are many subclasses of 9897 * ViewGroup.LayoutParams, and these correspond to the different subclasses 9898 * of ViewGroup that are responsible for arranging their children. 9899 * 9900 * This method may return null if this View is not attached to a parent 9901 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 9902 * was not invoked successfully. When a View is attached to a parent 9903 * ViewGroup, this method must not return null. 9904 * 9905 * @return The LayoutParams associated with this view, or null if no 9906 * parameters have been set yet 9907 */ 9908 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 9909 public ViewGroup.LayoutParams getLayoutParams() { 9910 return mLayoutParams; 9911 } 9912 9913 /** 9914 * Set the layout parameters associated with this view. These supply 9915 * parameters to the <i>parent</i> of this view specifying how it should be 9916 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 9917 * correspond to the different subclasses of ViewGroup that are responsible 9918 * for arranging their children. 9919 * 9920 * @param params The layout parameters for this view, cannot be null 9921 */ 9922 public void setLayoutParams(ViewGroup.LayoutParams params) { 9923 if (params == null) { 9924 throw new NullPointerException("Layout parameters cannot be null"); 9925 } 9926 mLayoutParams = params; 9927 resolveLayoutParams(); 9928 if (mParent instanceof ViewGroup) { 9929 ((ViewGroup) mParent).onSetLayoutParams(this, params); 9930 } 9931 requestLayout(); 9932 } 9933 9934 /** 9935 * Resolve the layout parameters depending on the resolved layout direction 9936 */ 9937 private void resolveLayoutParams() { 9938 if (mLayoutParams != null) { 9939 mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection()); 9940 } 9941 } 9942 9943 /** 9944 * Set the scrolled position of your view. This will cause a call to 9945 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9946 * invalidated. 9947 * @param x the x position to scroll to 9948 * @param y the y position to scroll to 9949 */ 9950 public void scrollTo(int x, int y) { 9951 if (mScrollX != x || mScrollY != y) { 9952 int oldX = mScrollX; 9953 int oldY = mScrollY; 9954 mScrollX = x; 9955 mScrollY = y; 9956 invalidateParentCaches(); 9957 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 9958 if (!awakenScrollBars()) { 9959 postInvalidateOnAnimation(); 9960 } 9961 } 9962 } 9963 9964 /** 9965 * Move the scrolled position of your view. This will cause a call to 9966 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9967 * invalidated. 9968 * @param x the amount of pixels to scroll by horizontally 9969 * @param y the amount of pixels to scroll by vertically 9970 */ 9971 public void scrollBy(int x, int y) { 9972 scrollTo(mScrollX + x, mScrollY + y); 9973 } 9974 9975 /** 9976 * <p>Trigger the scrollbars to draw. When invoked this method starts an 9977 * animation to fade the scrollbars out after a default delay. If a subclass 9978 * provides animated scrolling, the start delay should equal the duration 9979 * of the scrolling animation.</p> 9980 * 9981 * <p>The animation starts only if at least one of the scrollbars is 9982 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 9983 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 9984 * this method returns true, and false otherwise. If the animation is 9985 * started, this method calls {@link #invalidate()}; in that case the 9986 * caller should not call {@link #invalidate()}.</p> 9987 * 9988 * <p>This method should be invoked every time a subclass directly updates 9989 * the scroll parameters.</p> 9990 * 9991 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 9992 * and {@link #scrollTo(int, int)}.</p> 9993 * 9994 * @return true if the animation is played, false otherwise 9995 * 9996 * @see #awakenScrollBars(int) 9997 * @see #scrollBy(int, int) 9998 * @see #scrollTo(int, int) 9999 * @see #isHorizontalScrollBarEnabled() 10000 * @see #isVerticalScrollBarEnabled() 10001 * @see #setHorizontalScrollBarEnabled(boolean) 10002 * @see #setVerticalScrollBarEnabled(boolean) 10003 */ 10004 protected boolean awakenScrollBars() { 10005 return mScrollCache != null && 10006 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 10007 } 10008 10009 /** 10010 * Trigger the scrollbars to draw. 10011 * This method differs from awakenScrollBars() only in its default duration. 10012 * initialAwakenScrollBars() will show the scroll bars for longer than 10013 * usual to give the user more of a chance to notice them. 10014 * 10015 * @return true if the animation is played, false otherwise. 10016 */ 10017 private boolean initialAwakenScrollBars() { 10018 return mScrollCache != null && 10019 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 10020 } 10021 10022 /** 10023 * <p> 10024 * Trigger the scrollbars to draw. When invoked this method starts an 10025 * animation to fade the scrollbars out after a fixed delay. If a subclass 10026 * provides animated scrolling, the start delay should equal the duration of 10027 * the scrolling animation. 10028 * </p> 10029 * 10030 * <p> 10031 * The animation starts only if at least one of the scrollbars is enabled, 10032 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10033 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10034 * this method returns true, and false otherwise. If the animation is 10035 * started, this method calls {@link #invalidate()}; in that case the caller 10036 * should not call {@link #invalidate()}. 10037 * </p> 10038 * 10039 * <p> 10040 * This method should be invoked everytime a subclass directly updates the 10041 * scroll parameters. 10042 * </p> 10043 * 10044 * @param startDelay the delay, in milliseconds, after which the animation 10045 * should start; when the delay is 0, the animation starts 10046 * immediately 10047 * @return true if the animation is played, false otherwise 10048 * 10049 * @see #scrollBy(int, int) 10050 * @see #scrollTo(int, int) 10051 * @see #isHorizontalScrollBarEnabled() 10052 * @see #isVerticalScrollBarEnabled() 10053 * @see #setHorizontalScrollBarEnabled(boolean) 10054 * @see #setVerticalScrollBarEnabled(boolean) 10055 */ 10056 protected boolean awakenScrollBars(int startDelay) { 10057 return awakenScrollBars(startDelay, true); 10058 } 10059 10060 /** 10061 * <p> 10062 * Trigger the scrollbars to draw. When invoked this method starts an 10063 * animation to fade the scrollbars out after a fixed delay. If a subclass 10064 * provides animated scrolling, the start delay should equal the duration of 10065 * the scrolling animation. 10066 * </p> 10067 * 10068 * <p> 10069 * The animation starts only if at least one of the scrollbars is enabled, 10070 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10071 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10072 * this method returns true, and false otherwise. If the animation is 10073 * started, this method calls {@link #invalidate()} if the invalidate parameter 10074 * is set to true; in that case the caller 10075 * should not call {@link #invalidate()}. 10076 * </p> 10077 * 10078 * <p> 10079 * This method should be invoked everytime a subclass directly updates the 10080 * scroll parameters. 10081 * </p> 10082 * 10083 * @param startDelay the delay, in milliseconds, after which the animation 10084 * should start; when the delay is 0, the animation starts 10085 * immediately 10086 * 10087 * @param invalidate Wheter this method should call invalidate 10088 * 10089 * @return true if the animation is played, false otherwise 10090 * 10091 * @see #scrollBy(int, int) 10092 * @see #scrollTo(int, int) 10093 * @see #isHorizontalScrollBarEnabled() 10094 * @see #isVerticalScrollBarEnabled() 10095 * @see #setHorizontalScrollBarEnabled(boolean) 10096 * @see #setVerticalScrollBarEnabled(boolean) 10097 */ 10098 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 10099 final ScrollabilityCache scrollCache = mScrollCache; 10100 10101 if (scrollCache == null || !scrollCache.fadeScrollBars) { 10102 return false; 10103 } 10104 10105 if (scrollCache.scrollBar == null) { 10106 scrollCache.scrollBar = new ScrollBarDrawable(); 10107 } 10108 10109 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 10110 10111 if (invalidate) { 10112 // Invalidate to show the scrollbars 10113 postInvalidateOnAnimation(); 10114 } 10115 10116 if (scrollCache.state == ScrollabilityCache.OFF) { 10117 // FIXME: this is copied from WindowManagerService. 10118 // We should get this value from the system when it 10119 // is possible to do so. 10120 final int KEY_REPEAT_FIRST_DELAY = 750; 10121 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 10122 } 10123 10124 // Tell mScrollCache when we should start fading. This may 10125 // extend the fade start time if one was already scheduled 10126 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 10127 scrollCache.fadeStartTime = fadeStartTime; 10128 scrollCache.state = ScrollabilityCache.ON; 10129 10130 // Schedule our fader to run, unscheduling any old ones first 10131 if (mAttachInfo != null) { 10132 mAttachInfo.mHandler.removeCallbacks(scrollCache); 10133 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 10134 } 10135 10136 return true; 10137 } 10138 10139 return false; 10140 } 10141 10142 /** 10143 * Do not invalidate views which are not visible and which are not running an animation. They 10144 * will not get drawn and they should not set dirty flags as if they will be drawn 10145 */ 10146 private boolean skipInvalidate() { 10147 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 10148 (!(mParent instanceof ViewGroup) || 10149 !((ViewGroup) mParent).isViewTransitioning(this)); 10150 } 10151 /** 10152 * Mark the area defined by dirty as needing to be drawn. If the view is 10153 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 10154 * in the future. This must be called from a UI thread. To call from a non-UI 10155 * thread, call {@link #postInvalidate()}. 10156 * 10157 * WARNING: This method is destructive to dirty. 10158 * @param dirty the rectangle representing the bounds of the dirty region 10159 */ 10160 public void invalidate(Rect dirty) { 10161 if (skipInvalidate()) { 10162 return; 10163 } 10164 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10165 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10166 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10167 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10168 mPrivateFlags |= PFLAG_INVALIDATED; 10169 mPrivateFlags |= PFLAG_DIRTY; 10170 final ViewParent p = mParent; 10171 final AttachInfo ai = mAttachInfo; 10172 //noinspection PointlessBooleanExpression,ConstantConditions 10173 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10174 if (p != null && ai != null && ai.mHardwareAccelerated) { 10175 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10176 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10177 p.invalidateChild(this, null); 10178 return; 10179 } 10180 } 10181 if (p != null && ai != null) { 10182 final int scrollX = mScrollX; 10183 final int scrollY = mScrollY; 10184 final Rect r = ai.mTmpInvalRect; 10185 r.set(dirty.left - scrollX, dirty.top - scrollY, 10186 dirty.right - scrollX, dirty.bottom - scrollY); 10187 mParent.invalidateChild(this, r); 10188 } 10189 } 10190 } 10191 10192 /** 10193 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 10194 * The coordinates of the dirty rect are relative to the view. 10195 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 10196 * will be called at some point in the future. This must be called from 10197 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 10198 * @param l the left position of the dirty region 10199 * @param t the top position of the dirty region 10200 * @param r the right position of the dirty region 10201 * @param b the bottom position of the dirty region 10202 */ 10203 public void invalidate(int l, int t, int r, int b) { 10204 if (skipInvalidate()) { 10205 return; 10206 } 10207 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10208 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10209 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10210 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10211 mPrivateFlags |= PFLAG_INVALIDATED; 10212 mPrivateFlags |= PFLAG_DIRTY; 10213 final ViewParent p = mParent; 10214 final AttachInfo ai = mAttachInfo; 10215 //noinspection PointlessBooleanExpression,ConstantConditions 10216 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10217 if (p != null && ai != null && ai.mHardwareAccelerated) { 10218 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10219 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10220 p.invalidateChild(this, null); 10221 return; 10222 } 10223 } 10224 if (p != null && ai != null && l < r && t < b) { 10225 final int scrollX = mScrollX; 10226 final int scrollY = mScrollY; 10227 final Rect tmpr = ai.mTmpInvalRect; 10228 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 10229 p.invalidateChild(this, tmpr); 10230 } 10231 } 10232 } 10233 10234 /** 10235 * Invalidate the whole view. If the view is visible, 10236 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 10237 * the future. This must be called from a UI thread. To call from a non-UI thread, 10238 * call {@link #postInvalidate()}. 10239 */ 10240 public void invalidate() { 10241 invalidate(true); 10242 } 10243 10244 /** 10245 * This is where the invalidate() work actually happens. A full invalidate() 10246 * causes the drawing cache to be invalidated, but this function can be called with 10247 * invalidateCache set to false to skip that invalidation step for cases that do not 10248 * need it (for example, a component that remains at the same dimensions with the same 10249 * content). 10250 * 10251 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 10252 * well. This is usually true for a full invalidate, but may be set to false if the 10253 * View's contents or dimensions have not changed. 10254 */ 10255 void invalidate(boolean invalidateCache) { 10256 if (skipInvalidate()) { 10257 return; 10258 } 10259 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10260 (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) || 10261 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) { 10262 mLastIsOpaque = isOpaque(); 10263 mPrivateFlags &= ~PFLAG_DRAWN; 10264 mPrivateFlags |= PFLAG_DIRTY; 10265 if (invalidateCache) { 10266 mPrivateFlags |= PFLAG_INVALIDATED; 10267 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10268 } 10269 final AttachInfo ai = mAttachInfo; 10270 final ViewParent p = mParent; 10271 //noinspection PointlessBooleanExpression,ConstantConditions 10272 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10273 if (p != null && ai != null && ai.mHardwareAccelerated) { 10274 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10275 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10276 p.invalidateChild(this, null); 10277 return; 10278 } 10279 } 10280 10281 if (p != null && ai != null) { 10282 final Rect r = ai.mTmpInvalRect; 10283 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10284 // Don't call invalidate -- we don't want to internally scroll 10285 // our own bounds 10286 p.invalidateChild(this, r); 10287 } 10288 } 10289 } 10290 10291 /** 10292 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 10293 * set any flags or handle all of the cases handled by the default invalidation methods. 10294 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 10295 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 10296 * walk up the hierarchy, transforming the dirty rect as necessary. 10297 * 10298 * The method also handles normal invalidation logic if display list properties are not 10299 * being used in this view. The invalidateParent and forceRedraw flags are used by that 10300 * backup approach, to handle these cases used in the various property-setting methods. 10301 * 10302 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 10303 * are not being used in this view 10304 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 10305 * list properties are not being used in this view 10306 */ 10307 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 10308 if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) { 10309 if (invalidateParent) { 10310 invalidateParentCaches(); 10311 } 10312 if (forceRedraw) { 10313 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10314 } 10315 invalidate(false); 10316 } else { 10317 final AttachInfo ai = mAttachInfo; 10318 final ViewParent p = mParent; 10319 if (p != null && ai != null) { 10320 final Rect r = ai.mTmpInvalRect; 10321 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10322 if (mParent instanceof ViewGroup) { 10323 ((ViewGroup) mParent).invalidateChildFast(this, r); 10324 } else { 10325 mParent.invalidateChild(this, r); 10326 } 10327 } 10328 } 10329 } 10330 10331 /** 10332 * Utility method to transform a given Rect by the current matrix of this view. 10333 */ 10334 void transformRect(final Rect rect) { 10335 if (!getMatrix().isIdentity()) { 10336 RectF boundingRect = mAttachInfo.mTmpTransformRect; 10337 boundingRect.set(rect); 10338 getMatrix().mapRect(boundingRect); 10339 rect.set((int) (boundingRect.left - 0.5f), 10340 (int) (boundingRect.top - 0.5f), 10341 (int) (boundingRect.right + 0.5f), 10342 (int) (boundingRect.bottom + 0.5f)); 10343 } 10344 } 10345 10346 /** 10347 * Used to indicate that the parent of this view should clear its caches. This functionality 10348 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10349 * which is necessary when various parent-managed properties of the view change, such as 10350 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 10351 * clears the parent caches and does not causes an invalidate event. 10352 * 10353 * @hide 10354 */ 10355 protected void invalidateParentCaches() { 10356 if (mParent instanceof View) { 10357 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 10358 } 10359 } 10360 10361 /** 10362 * Used to indicate that the parent of this view should be invalidated. This functionality 10363 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10364 * which is necessary when various parent-managed properties of the view change, such as 10365 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 10366 * an invalidation event to the parent. 10367 * 10368 * @hide 10369 */ 10370 protected void invalidateParentIfNeeded() { 10371 if (isHardwareAccelerated() && mParent instanceof View) { 10372 ((View) mParent).invalidate(true); 10373 } 10374 } 10375 10376 /** 10377 * Indicates whether this View is opaque. An opaque View guarantees that it will 10378 * draw all the pixels overlapping its bounds using a fully opaque color. 10379 * 10380 * Subclasses of View should override this method whenever possible to indicate 10381 * whether an instance is opaque. Opaque Views are treated in a special way by 10382 * the View hierarchy, possibly allowing it to perform optimizations during 10383 * invalidate/draw passes. 10384 * 10385 * @return True if this View is guaranteed to be fully opaque, false otherwise. 10386 */ 10387 @ViewDebug.ExportedProperty(category = "drawing") 10388 public boolean isOpaque() { 10389 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 10390 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f); 10391 } 10392 10393 /** 10394 * @hide 10395 */ 10396 protected void computeOpaqueFlags() { 10397 // Opaque if: 10398 // - Has a background 10399 // - Background is opaque 10400 // - Doesn't have scrollbars or scrollbars are inside overlay 10401 10402 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 10403 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 10404 } else { 10405 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 10406 } 10407 10408 final int flags = mViewFlags; 10409 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 10410 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 10411 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 10412 } else { 10413 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 10414 } 10415 } 10416 10417 /** 10418 * @hide 10419 */ 10420 protected boolean hasOpaqueScrollbars() { 10421 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 10422 } 10423 10424 /** 10425 * @return A handler associated with the thread running the View. This 10426 * handler can be used to pump events in the UI events queue. 10427 */ 10428 public Handler getHandler() { 10429 if (mAttachInfo != null) { 10430 return mAttachInfo.mHandler; 10431 } 10432 return null; 10433 } 10434 10435 /** 10436 * Gets the view root associated with the View. 10437 * @return The view root, or null if none. 10438 * @hide 10439 */ 10440 public ViewRootImpl getViewRootImpl() { 10441 if (mAttachInfo != null) { 10442 return mAttachInfo.mViewRootImpl; 10443 } 10444 return null; 10445 } 10446 10447 /** 10448 * <p>Causes the Runnable to be added to the message queue. 10449 * The runnable will be run on the user interface thread.</p> 10450 * 10451 * <p>This method can be invoked from outside of the UI thread 10452 * only when this View is attached to a window.</p> 10453 * 10454 * @param action The Runnable that will be executed. 10455 * 10456 * @return Returns true if the Runnable was successfully placed in to the 10457 * message queue. Returns false on failure, usually because the 10458 * looper processing the message queue is exiting. 10459 * 10460 * @see #postDelayed 10461 * @see #removeCallbacks 10462 */ 10463 public boolean post(Runnable action) { 10464 final AttachInfo attachInfo = mAttachInfo; 10465 if (attachInfo != null) { 10466 return attachInfo.mHandler.post(action); 10467 } 10468 // Assume that post will succeed later 10469 ViewRootImpl.getRunQueue().post(action); 10470 return true; 10471 } 10472 10473 /** 10474 * <p>Causes the Runnable to be added to the message queue, to be run 10475 * after the specified amount of time elapses. 10476 * The runnable will be run on the user interface thread.</p> 10477 * 10478 * <p>This method can be invoked from outside of the UI thread 10479 * only when this View is attached to a window.</p> 10480 * 10481 * @param action The Runnable that will be executed. 10482 * @param delayMillis The delay (in milliseconds) until the Runnable 10483 * will be executed. 10484 * 10485 * @return true if the Runnable was successfully placed in to the 10486 * message queue. Returns false on failure, usually because the 10487 * looper processing the message queue is exiting. Note that a 10488 * result of true does not mean the Runnable will be processed -- 10489 * if the looper is quit before the delivery time of the message 10490 * occurs then the message will be dropped. 10491 * 10492 * @see #post 10493 * @see #removeCallbacks 10494 */ 10495 public boolean postDelayed(Runnable action, long delayMillis) { 10496 final AttachInfo attachInfo = mAttachInfo; 10497 if (attachInfo != null) { 10498 return attachInfo.mHandler.postDelayed(action, delayMillis); 10499 } 10500 // Assume that post will succeed later 10501 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10502 return true; 10503 } 10504 10505 /** 10506 * <p>Causes the Runnable to execute on the next animation time step. 10507 * The runnable will be run on the user interface thread.</p> 10508 * 10509 * <p>This method can be invoked from outside of the UI thread 10510 * only when this View is attached to a window.</p> 10511 * 10512 * @param action The Runnable that will be executed. 10513 * 10514 * @see #postOnAnimationDelayed 10515 * @see #removeCallbacks 10516 */ 10517 public void postOnAnimation(Runnable action) { 10518 final AttachInfo attachInfo = mAttachInfo; 10519 if (attachInfo != null) { 10520 attachInfo.mViewRootImpl.mChoreographer.postCallback( 10521 Choreographer.CALLBACK_ANIMATION, action, null); 10522 } else { 10523 // Assume that post will succeed later 10524 ViewRootImpl.getRunQueue().post(action); 10525 } 10526 } 10527 10528 /** 10529 * <p>Causes the Runnable to execute on the next animation time step, 10530 * after the specified amount of time elapses. 10531 * The runnable will be run on the user interface thread.</p> 10532 * 10533 * <p>This method can be invoked from outside of the UI thread 10534 * only when this View is attached to a window.</p> 10535 * 10536 * @param action The Runnable that will be executed. 10537 * @param delayMillis The delay (in milliseconds) until the Runnable 10538 * will be executed. 10539 * 10540 * @see #postOnAnimation 10541 * @see #removeCallbacks 10542 */ 10543 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 10544 final AttachInfo attachInfo = mAttachInfo; 10545 if (attachInfo != null) { 10546 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 10547 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 10548 } else { 10549 // Assume that post will succeed later 10550 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10551 } 10552 } 10553 10554 /** 10555 * <p>Removes the specified Runnable from the message queue.</p> 10556 * 10557 * <p>This method can be invoked from outside of the UI thread 10558 * only when this View is attached to a window.</p> 10559 * 10560 * @param action The Runnable to remove from the message handling queue 10561 * 10562 * @return true if this view could ask the Handler to remove the Runnable, 10563 * false otherwise. When the returned value is true, the Runnable 10564 * may or may not have been actually removed from the message queue 10565 * (for instance, if the Runnable was not in the queue already.) 10566 * 10567 * @see #post 10568 * @see #postDelayed 10569 * @see #postOnAnimation 10570 * @see #postOnAnimationDelayed 10571 */ 10572 public boolean removeCallbacks(Runnable action) { 10573 if (action != null) { 10574 final AttachInfo attachInfo = mAttachInfo; 10575 if (attachInfo != null) { 10576 attachInfo.mHandler.removeCallbacks(action); 10577 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 10578 Choreographer.CALLBACK_ANIMATION, action, null); 10579 } else { 10580 // Assume that post will succeed later 10581 ViewRootImpl.getRunQueue().removeCallbacks(action); 10582 } 10583 } 10584 return true; 10585 } 10586 10587 /** 10588 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 10589 * Use this to invalidate the View from a non-UI thread.</p> 10590 * 10591 * <p>This method can be invoked from outside of the UI thread 10592 * only when this View is attached to a window.</p> 10593 * 10594 * @see #invalidate() 10595 * @see #postInvalidateDelayed(long) 10596 */ 10597 public void postInvalidate() { 10598 postInvalidateDelayed(0); 10599 } 10600 10601 /** 10602 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10603 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 10604 * 10605 * <p>This method can be invoked from outside of the UI thread 10606 * only when this View is attached to a window.</p> 10607 * 10608 * @param left The left coordinate of the rectangle to invalidate. 10609 * @param top The top coordinate of the rectangle to invalidate. 10610 * @param right The right coordinate of the rectangle to invalidate. 10611 * @param bottom The bottom coordinate of the rectangle to invalidate. 10612 * 10613 * @see #invalidate(int, int, int, int) 10614 * @see #invalidate(Rect) 10615 * @see #postInvalidateDelayed(long, int, int, int, int) 10616 */ 10617 public void postInvalidate(int left, int top, int right, int bottom) { 10618 postInvalidateDelayed(0, left, top, right, bottom); 10619 } 10620 10621 /** 10622 * <p>Cause an invalidate to happen on a subsequent cycle through the event 10623 * loop. Waits for the specified amount of time.</p> 10624 * 10625 * <p>This method can be invoked from outside of the UI thread 10626 * only when this View is attached to a window.</p> 10627 * 10628 * @param delayMilliseconds the duration in milliseconds to delay the 10629 * invalidation by 10630 * 10631 * @see #invalidate() 10632 * @see #postInvalidate() 10633 */ 10634 public void postInvalidateDelayed(long delayMilliseconds) { 10635 // We try only with the AttachInfo because there's no point in invalidating 10636 // if we are not attached to our window 10637 final AttachInfo attachInfo = mAttachInfo; 10638 if (attachInfo != null) { 10639 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 10640 } 10641 } 10642 10643 /** 10644 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10645 * through the event loop. Waits for the specified amount of time.</p> 10646 * 10647 * <p>This method can be invoked from outside of the UI thread 10648 * only when this View is attached to a window.</p> 10649 * 10650 * @param delayMilliseconds the duration in milliseconds to delay the 10651 * invalidation by 10652 * @param left The left coordinate of the rectangle to invalidate. 10653 * @param top The top coordinate of the rectangle to invalidate. 10654 * @param right The right coordinate of the rectangle to invalidate. 10655 * @param bottom The bottom coordinate of the rectangle to invalidate. 10656 * 10657 * @see #invalidate(int, int, int, int) 10658 * @see #invalidate(Rect) 10659 * @see #postInvalidate(int, int, int, int) 10660 */ 10661 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 10662 int right, int bottom) { 10663 10664 // We try only with the AttachInfo because there's no point in invalidating 10665 // if we are not attached to our window 10666 final AttachInfo attachInfo = mAttachInfo; 10667 if (attachInfo != null) { 10668 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 10669 info.target = this; 10670 info.left = left; 10671 info.top = top; 10672 info.right = right; 10673 info.bottom = bottom; 10674 10675 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 10676 } 10677 } 10678 10679 /** 10680 * <p>Cause an invalidate to happen on the next animation time step, typically the 10681 * next display frame.</p> 10682 * 10683 * <p>This method can be invoked from outside of the UI thread 10684 * only when this View is attached to a window.</p> 10685 * 10686 * @see #invalidate() 10687 */ 10688 public void postInvalidateOnAnimation() { 10689 // We try only with the AttachInfo because there's no point in invalidating 10690 // if we are not attached to our window 10691 final AttachInfo attachInfo = mAttachInfo; 10692 if (attachInfo != null) { 10693 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 10694 } 10695 } 10696 10697 /** 10698 * <p>Cause an invalidate of the specified area to happen on the next animation 10699 * time step, typically the next display frame.</p> 10700 * 10701 * <p>This method can be invoked from outside of the UI thread 10702 * only when this View is attached to a window.</p> 10703 * 10704 * @param left The left coordinate of the rectangle to invalidate. 10705 * @param top The top coordinate of the rectangle to invalidate. 10706 * @param right The right coordinate of the rectangle to invalidate. 10707 * @param bottom The bottom coordinate of the rectangle to invalidate. 10708 * 10709 * @see #invalidate(int, int, int, int) 10710 * @see #invalidate(Rect) 10711 */ 10712 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 10713 // We try only with the AttachInfo because there's no point in invalidating 10714 // if we are not attached to our window 10715 final AttachInfo attachInfo = mAttachInfo; 10716 if (attachInfo != null) { 10717 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 10718 info.target = this; 10719 info.left = left; 10720 info.top = top; 10721 info.right = right; 10722 info.bottom = bottom; 10723 10724 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 10725 } 10726 } 10727 10728 /** 10729 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 10730 * This event is sent at most once every 10731 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 10732 */ 10733 private void postSendViewScrolledAccessibilityEventCallback() { 10734 if (mSendViewScrolledAccessibilityEvent == null) { 10735 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 10736 } 10737 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 10738 mSendViewScrolledAccessibilityEvent.mIsPending = true; 10739 postDelayed(mSendViewScrolledAccessibilityEvent, 10740 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 10741 } 10742 } 10743 10744 /** 10745 * Called by a parent to request that a child update its values for mScrollX 10746 * and mScrollY if necessary. This will typically be done if the child is 10747 * animating a scroll using a {@link android.widget.Scroller Scroller} 10748 * object. 10749 */ 10750 public void computeScroll() { 10751 } 10752 10753 /** 10754 * <p>Indicate whether the horizontal edges are faded when the view is 10755 * scrolled horizontally.</p> 10756 * 10757 * @return true if the horizontal edges should are faded on scroll, false 10758 * otherwise 10759 * 10760 * @see #setHorizontalFadingEdgeEnabled(boolean) 10761 * 10762 * @attr ref android.R.styleable#View_requiresFadingEdge 10763 */ 10764 public boolean isHorizontalFadingEdgeEnabled() { 10765 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 10766 } 10767 10768 /** 10769 * <p>Define whether the horizontal edges should be faded when this view 10770 * is scrolled horizontally.</p> 10771 * 10772 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 10773 * be faded when the view is scrolled 10774 * horizontally 10775 * 10776 * @see #isHorizontalFadingEdgeEnabled() 10777 * 10778 * @attr ref android.R.styleable#View_requiresFadingEdge 10779 */ 10780 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 10781 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 10782 if (horizontalFadingEdgeEnabled) { 10783 initScrollCache(); 10784 } 10785 10786 mViewFlags ^= FADING_EDGE_HORIZONTAL; 10787 } 10788 } 10789 10790 /** 10791 * <p>Indicate whether the vertical edges are faded when the view is 10792 * scrolled horizontally.</p> 10793 * 10794 * @return true if the vertical edges should are faded on scroll, false 10795 * otherwise 10796 * 10797 * @see #setVerticalFadingEdgeEnabled(boolean) 10798 * 10799 * @attr ref android.R.styleable#View_requiresFadingEdge 10800 */ 10801 public boolean isVerticalFadingEdgeEnabled() { 10802 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 10803 } 10804 10805 /** 10806 * <p>Define whether the vertical edges should be faded when this view 10807 * is scrolled vertically.</p> 10808 * 10809 * @param verticalFadingEdgeEnabled true if the vertical edges should 10810 * be faded when the view is scrolled 10811 * vertically 10812 * 10813 * @see #isVerticalFadingEdgeEnabled() 10814 * 10815 * @attr ref android.R.styleable#View_requiresFadingEdge 10816 */ 10817 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 10818 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 10819 if (verticalFadingEdgeEnabled) { 10820 initScrollCache(); 10821 } 10822 10823 mViewFlags ^= FADING_EDGE_VERTICAL; 10824 } 10825 } 10826 10827 /** 10828 * Returns the strength, or intensity, of the top faded edge. The strength is 10829 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10830 * returns 0.0 or 1.0 but no value in between. 10831 * 10832 * Subclasses should override this method to provide a smoother fade transition 10833 * when scrolling occurs. 10834 * 10835 * @return the intensity of the top fade as a float between 0.0f and 1.0f 10836 */ 10837 protected float getTopFadingEdgeStrength() { 10838 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 10839 } 10840 10841 /** 10842 * Returns the strength, or intensity, of the bottom faded edge. The strength is 10843 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10844 * returns 0.0 or 1.0 but no value in between. 10845 * 10846 * Subclasses should override this method to provide a smoother fade transition 10847 * when scrolling occurs. 10848 * 10849 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 10850 */ 10851 protected float getBottomFadingEdgeStrength() { 10852 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 10853 computeVerticalScrollRange() ? 1.0f : 0.0f; 10854 } 10855 10856 /** 10857 * Returns the strength, or intensity, of the left faded edge. The strength is 10858 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10859 * returns 0.0 or 1.0 but no value in between. 10860 * 10861 * Subclasses should override this method to provide a smoother fade transition 10862 * when scrolling occurs. 10863 * 10864 * @return the intensity of the left fade as a float between 0.0f and 1.0f 10865 */ 10866 protected float getLeftFadingEdgeStrength() { 10867 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 10868 } 10869 10870 /** 10871 * Returns the strength, or intensity, of the right faded edge. The strength is 10872 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10873 * returns 0.0 or 1.0 but no value in between. 10874 * 10875 * Subclasses should override this method to provide a smoother fade transition 10876 * when scrolling occurs. 10877 * 10878 * @return the intensity of the right fade as a float between 0.0f and 1.0f 10879 */ 10880 protected float getRightFadingEdgeStrength() { 10881 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 10882 computeHorizontalScrollRange() ? 1.0f : 0.0f; 10883 } 10884 10885 /** 10886 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 10887 * scrollbar is not drawn by default.</p> 10888 * 10889 * @return true if the horizontal scrollbar should be painted, false 10890 * otherwise 10891 * 10892 * @see #setHorizontalScrollBarEnabled(boolean) 10893 */ 10894 public boolean isHorizontalScrollBarEnabled() { 10895 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 10896 } 10897 10898 /** 10899 * <p>Define whether the horizontal scrollbar should be drawn or not. The 10900 * scrollbar is not drawn by default.</p> 10901 * 10902 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 10903 * be painted 10904 * 10905 * @see #isHorizontalScrollBarEnabled() 10906 */ 10907 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 10908 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 10909 mViewFlags ^= SCROLLBARS_HORIZONTAL; 10910 computeOpaqueFlags(); 10911 resolvePadding(); 10912 } 10913 } 10914 10915 /** 10916 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 10917 * scrollbar is not drawn by default.</p> 10918 * 10919 * @return true if the vertical scrollbar should be painted, false 10920 * otherwise 10921 * 10922 * @see #setVerticalScrollBarEnabled(boolean) 10923 */ 10924 public boolean isVerticalScrollBarEnabled() { 10925 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 10926 } 10927 10928 /** 10929 * <p>Define whether the vertical scrollbar should be drawn or not. The 10930 * scrollbar is not drawn by default.</p> 10931 * 10932 * @param verticalScrollBarEnabled true if the vertical scrollbar should 10933 * be painted 10934 * 10935 * @see #isVerticalScrollBarEnabled() 10936 */ 10937 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 10938 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 10939 mViewFlags ^= SCROLLBARS_VERTICAL; 10940 computeOpaqueFlags(); 10941 resolvePadding(); 10942 } 10943 } 10944 10945 /** 10946 * @hide 10947 */ 10948 protected void recomputePadding() { 10949 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 10950 } 10951 10952 /** 10953 * Define whether scrollbars will fade when the view is not scrolling. 10954 * 10955 * @param fadeScrollbars wheter to enable fading 10956 * 10957 * @attr ref android.R.styleable#View_fadeScrollbars 10958 */ 10959 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 10960 initScrollCache(); 10961 final ScrollabilityCache scrollabilityCache = mScrollCache; 10962 scrollabilityCache.fadeScrollBars = fadeScrollbars; 10963 if (fadeScrollbars) { 10964 scrollabilityCache.state = ScrollabilityCache.OFF; 10965 } else { 10966 scrollabilityCache.state = ScrollabilityCache.ON; 10967 } 10968 } 10969 10970 /** 10971 * 10972 * Returns true if scrollbars will fade when this view is not scrolling 10973 * 10974 * @return true if scrollbar fading is enabled 10975 * 10976 * @attr ref android.R.styleable#View_fadeScrollbars 10977 */ 10978 public boolean isScrollbarFadingEnabled() { 10979 return mScrollCache != null && mScrollCache.fadeScrollBars; 10980 } 10981 10982 /** 10983 * 10984 * Returns the delay before scrollbars fade. 10985 * 10986 * @return the delay before scrollbars fade 10987 * 10988 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 10989 */ 10990 public int getScrollBarDefaultDelayBeforeFade() { 10991 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 10992 mScrollCache.scrollBarDefaultDelayBeforeFade; 10993 } 10994 10995 /** 10996 * Define the delay before scrollbars fade. 10997 * 10998 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 10999 * 11000 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11001 */ 11002 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 11003 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 11004 } 11005 11006 /** 11007 * 11008 * Returns the scrollbar fade duration. 11009 * 11010 * @return the scrollbar fade duration 11011 * 11012 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11013 */ 11014 public int getScrollBarFadeDuration() { 11015 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 11016 mScrollCache.scrollBarFadeDuration; 11017 } 11018 11019 /** 11020 * Define the scrollbar fade duration. 11021 * 11022 * @param scrollBarFadeDuration - the scrollbar fade duration 11023 * 11024 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11025 */ 11026 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 11027 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 11028 } 11029 11030 /** 11031 * 11032 * Returns the scrollbar size. 11033 * 11034 * @return the scrollbar size 11035 * 11036 * @attr ref android.R.styleable#View_scrollbarSize 11037 */ 11038 public int getScrollBarSize() { 11039 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 11040 mScrollCache.scrollBarSize; 11041 } 11042 11043 /** 11044 * Define the scrollbar size. 11045 * 11046 * @param scrollBarSize - the scrollbar size 11047 * 11048 * @attr ref android.R.styleable#View_scrollbarSize 11049 */ 11050 public void setScrollBarSize(int scrollBarSize) { 11051 getScrollCache().scrollBarSize = scrollBarSize; 11052 } 11053 11054 /** 11055 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 11056 * inset. When inset, they add to the padding of the view. And the scrollbars 11057 * can be drawn inside the padding area or on the edge of the view. For example, 11058 * if a view has a background drawable and you want to draw the scrollbars 11059 * inside the padding specified by the drawable, you can use 11060 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 11061 * appear at the edge of the view, ignoring the padding, then you can use 11062 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 11063 * @param style the style of the scrollbars. Should be one of 11064 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 11065 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 11066 * @see #SCROLLBARS_INSIDE_OVERLAY 11067 * @see #SCROLLBARS_INSIDE_INSET 11068 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11069 * @see #SCROLLBARS_OUTSIDE_INSET 11070 * 11071 * @attr ref android.R.styleable#View_scrollbarStyle 11072 */ 11073 public void setScrollBarStyle(int style) { 11074 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 11075 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 11076 computeOpaqueFlags(); 11077 resolvePadding(); 11078 } 11079 } 11080 11081 /** 11082 * <p>Returns the current scrollbar style.</p> 11083 * @return the current scrollbar style 11084 * @see #SCROLLBARS_INSIDE_OVERLAY 11085 * @see #SCROLLBARS_INSIDE_INSET 11086 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11087 * @see #SCROLLBARS_OUTSIDE_INSET 11088 * 11089 * @attr ref android.R.styleable#View_scrollbarStyle 11090 */ 11091 @ViewDebug.ExportedProperty(mapping = { 11092 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 11093 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 11094 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 11095 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 11096 }) 11097 public int getScrollBarStyle() { 11098 return mViewFlags & SCROLLBARS_STYLE_MASK; 11099 } 11100 11101 /** 11102 * <p>Compute the horizontal range that the horizontal scrollbar 11103 * represents.</p> 11104 * 11105 * <p>The range is expressed in arbitrary units that must be the same as the 11106 * units used by {@link #computeHorizontalScrollExtent()} and 11107 * {@link #computeHorizontalScrollOffset()}.</p> 11108 * 11109 * <p>The default range is the drawing width of this view.</p> 11110 * 11111 * @return the total horizontal range represented by the horizontal 11112 * scrollbar 11113 * 11114 * @see #computeHorizontalScrollExtent() 11115 * @see #computeHorizontalScrollOffset() 11116 * @see android.widget.ScrollBarDrawable 11117 */ 11118 protected int computeHorizontalScrollRange() { 11119 return getWidth(); 11120 } 11121 11122 /** 11123 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 11124 * within the horizontal range. This value is used to compute the position 11125 * of the thumb within the scrollbar's track.</p> 11126 * 11127 * <p>The range is expressed in arbitrary units that must be the same as the 11128 * units used by {@link #computeHorizontalScrollRange()} and 11129 * {@link #computeHorizontalScrollExtent()}.</p> 11130 * 11131 * <p>The default offset is the scroll offset of this view.</p> 11132 * 11133 * @return the horizontal offset of the scrollbar's thumb 11134 * 11135 * @see #computeHorizontalScrollRange() 11136 * @see #computeHorizontalScrollExtent() 11137 * @see android.widget.ScrollBarDrawable 11138 */ 11139 protected int computeHorizontalScrollOffset() { 11140 return mScrollX; 11141 } 11142 11143 /** 11144 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 11145 * within the horizontal range. This value is used to compute the length 11146 * of the thumb within the scrollbar's track.</p> 11147 * 11148 * <p>The range is expressed in arbitrary units that must be the same as the 11149 * units used by {@link #computeHorizontalScrollRange()} and 11150 * {@link #computeHorizontalScrollOffset()}.</p> 11151 * 11152 * <p>The default extent is the drawing width of this view.</p> 11153 * 11154 * @return the horizontal extent of the scrollbar's thumb 11155 * 11156 * @see #computeHorizontalScrollRange() 11157 * @see #computeHorizontalScrollOffset() 11158 * @see android.widget.ScrollBarDrawable 11159 */ 11160 protected int computeHorizontalScrollExtent() { 11161 return getWidth(); 11162 } 11163 11164 /** 11165 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 11166 * 11167 * <p>The range is expressed in arbitrary units that must be the same as the 11168 * units used by {@link #computeVerticalScrollExtent()} and 11169 * {@link #computeVerticalScrollOffset()}.</p> 11170 * 11171 * @return the total vertical range represented by the vertical scrollbar 11172 * 11173 * <p>The default range is the drawing height of this view.</p> 11174 * 11175 * @see #computeVerticalScrollExtent() 11176 * @see #computeVerticalScrollOffset() 11177 * @see android.widget.ScrollBarDrawable 11178 */ 11179 protected int computeVerticalScrollRange() { 11180 return getHeight(); 11181 } 11182 11183 /** 11184 * <p>Compute the vertical offset of the vertical scrollbar's thumb 11185 * within the horizontal range. This value is used to compute the position 11186 * of the thumb within the scrollbar's track.</p> 11187 * 11188 * <p>The range is expressed in arbitrary units that must be the same as the 11189 * units used by {@link #computeVerticalScrollRange()} and 11190 * {@link #computeVerticalScrollExtent()}.</p> 11191 * 11192 * <p>The default offset is the scroll offset of this view.</p> 11193 * 11194 * @return the vertical offset of the scrollbar's thumb 11195 * 11196 * @see #computeVerticalScrollRange() 11197 * @see #computeVerticalScrollExtent() 11198 * @see android.widget.ScrollBarDrawable 11199 */ 11200 protected int computeVerticalScrollOffset() { 11201 return mScrollY; 11202 } 11203 11204 /** 11205 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 11206 * within the vertical range. This value is used to compute the length 11207 * of the thumb within the scrollbar's track.</p> 11208 * 11209 * <p>The range is expressed in arbitrary units that must be the same as the 11210 * units used by {@link #computeVerticalScrollRange()} and 11211 * {@link #computeVerticalScrollOffset()}.</p> 11212 * 11213 * <p>The default extent is the drawing height of this view.</p> 11214 * 11215 * @return the vertical extent of the scrollbar's thumb 11216 * 11217 * @see #computeVerticalScrollRange() 11218 * @see #computeVerticalScrollOffset() 11219 * @see android.widget.ScrollBarDrawable 11220 */ 11221 protected int computeVerticalScrollExtent() { 11222 return getHeight(); 11223 } 11224 11225 /** 11226 * Check if this view can be scrolled horizontally in a certain direction. 11227 * 11228 * @param direction Negative to check scrolling left, positive to check scrolling right. 11229 * @return true if this view can be scrolled in the specified direction, false otherwise. 11230 */ 11231 public boolean canScrollHorizontally(int direction) { 11232 final int offset = computeHorizontalScrollOffset(); 11233 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 11234 if (range == 0) return false; 11235 if (direction < 0) { 11236 return offset > 0; 11237 } else { 11238 return offset < range - 1; 11239 } 11240 } 11241 11242 /** 11243 * Check if this view can be scrolled vertically in a certain direction. 11244 * 11245 * @param direction Negative to check scrolling up, positive to check scrolling down. 11246 * @return true if this view can be scrolled in the specified direction, false otherwise. 11247 */ 11248 public boolean canScrollVertically(int direction) { 11249 final int offset = computeVerticalScrollOffset(); 11250 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 11251 if (range == 0) return false; 11252 if (direction < 0) { 11253 return offset > 0; 11254 } else { 11255 return offset < range - 1; 11256 } 11257 } 11258 11259 /** 11260 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 11261 * scrollbars are painted only if they have been awakened first.</p> 11262 * 11263 * @param canvas the canvas on which to draw the scrollbars 11264 * 11265 * @see #awakenScrollBars(int) 11266 */ 11267 protected final void onDrawScrollBars(Canvas canvas) { 11268 // scrollbars are drawn only when the animation is running 11269 final ScrollabilityCache cache = mScrollCache; 11270 if (cache != null) { 11271 11272 int state = cache.state; 11273 11274 if (state == ScrollabilityCache.OFF) { 11275 return; 11276 } 11277 11278 boolean invalidate = false; 11279 11280 if (state == ScrollabilityCache.FADING) { 11281 // We're fading -- get our fade interpolation 11282 if (cache.interpolatorValues == null) { 11283 cache.interpolatorValues = new float[1]; 11284 } 11285 11286 float[] values = cache.interpolatorValues; 11287 11288 // Stops the animation if we're done 11289 if (cache.scrollBarInterpolator.timeToValues(values) == 11290 Interpolator.Result.FREEZE_END) { 11291 cache.state = ScrollabilityCache.OFF; 11292 } else { 11293 cache.scrollBar.setAlpha(Math.round(values[0])); 11294 } 11295 11296 // This will make the scroll bars inval themselves after 11297 // drawing. We only want this when we're fading so that 11298 // we prevent excessive redraws 11299 invalidate = true; 11300 } else { 11301 // We're just on -- but we may have been fading before so 11302 // reset alpha 11303 cache.scrollBar.setAlpha(255); 11304 } 11305 11306 11307 final int viewFlags = mViewFlags; 11308 11309 final boolean drawHorizontalScrollBar = 11310 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11311 final boolean drawVerticalScrollBar = 11312 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 11313 && !isVerticalScrollBarHidden(); 11314 11315 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 11316 final int width = mRight - mLeft; 11317 final int height = mBottom - mTop; 11318 11319 final ScrollBarDrawable scrollBar = cache.scrollBar; 11320 11321 final int scrollX = mScrollX; 11322 final int scrollY = mScrollY; 11323 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 11324 11325 int left, top, right, bottom; 11326 11327 if (drawHorizontalScrollBar) { 11328 int size = scrollBar.getSize(false); 11329 if (size <= 0) { 11330 size = cache.scrollBarSize; 11331 } 11332 11333 scrollBar.setParameters(computeHorizontalScrollRange(), 11334 computeHorizontalScrollOffset(), 11335 computeHorizontalScrollExtent(), false); 11336 final int verticalScrollBarGap = drawVerticalScrollBar ? 11337 getVerticalScrollbarWidth() : 0; 11338 top = scrollY + height - size - (mUserPaddingBottom & inside); 11339 left = scrollX + (mPaddingLeft & inside); 11340 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 11341 bottom = top + size; 11342 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 11343 if (invalidate) { 11344 invalidate(left, top, right, bottom); 11345 } 11346 } 11347 11348 if (drawVerticalScrollBar) { 11349 int size = scrollBar.getSize(true); 11350 if (size <= 0) { 11351 size = cache.scrollBarSize; 11352 } 11353 11354 scrollBar.setParameters(computeVerticalScrollRange(), 11355 computeVerticalScrollOffset(), 11356 computeVerticalScrollExtent(), true); 11357 int verticalScrollbarPosition = mVerticalScrollbarPosition; 11358 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 11359 verticalScrollbarPosition = isLayoutRtl() ? 11360 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 11361 } 11362 switch (verticalScrollbarPosition) { 11363 default: 11364 case SCROLLBAR_POSITION_RIGHT: 11365 left = scrollX + width - size - (mUserPaddingRight & inside); 11366 break; 11367 case SCROLLBAR_POSITION_LEFT: 11368 left = scrollX + (mUserPaddingLeft & inside); 11369 break; 11370 } 11371 top = scrollY + (mPaddingTop & inside); 11372 right = left + size; 11373 bottom = scrollY + height - (mUserPaddingBottom & inside); 11374 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 11375 if (invalidate) { 11376 invalidate(left, top, right, bottom); 11377 } 11378 } 11379 } 11380 } 11381 } 11382 11383 /** 11384 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 11385 * FastScroller is visible. 11386 * @return whether to temporarily hide the vertical scrollbar 11387 * @hide 11388 */ 11389 protected boolean isVerticalScrollBarHidden() { 11390 return false; 11391 } 11392 11393 /** 11394 * <p>Draw the horizontal scrollbar if 11395 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 11396 * 11397 * @param canvas the canvas on which to draw the scrollbar 11398 * @param scrollBar the scrollbar's drawable 11399 * 11400 * @see #isHorizontalScrollBarEnabled() 11401 * @see #computeHorizontalScrollRange() 11402 * @see #computeHorizontalScrollExtent() 11403 * @see #computeHorizontalScrollOffset() 11404 * @see android.widget.ScrollBarDrawable 11405 * @hide 11406 */ 11407 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 11408 int l, int t, int r, int b) { 11409 scrollBar.setBounds(l, t, r, b); 11410 scrollBar.draw(canvas); 11411 } 11412 11413 /** 11414 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 11415 * returns true.</p> 11416 * 11417 * @param canvas the canvas on which to draw the scrollbar 11418 * @param scrollBar the scrollbar's drawable 11419 * 11420 * @see #isVerticalScrollBarEnabled() 11421 * @see #computeVerticalScrollRange() 11422 * @see #computeVerticalScrollExtent() 11423 * @see #computeVerticalScrollOffset() 11424 * @see android.widget.ScrollBarDrawable 11425 * @hide 11426 */ 11427 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 11428 int l, int t, int r, int b) { 11429 scrollBar.setBounds(l, t, r, b); 11430 scrollBar.draw(canvas); 11431 } 11432 11433 /** 11434 * Implement this to do your drawing. 11435 * 11436 * @param canvas the canvas on which the background will be drawn 11437 */ 11438 protected void onDraw(Canvas canvas) { 11439 } 11440 11441 /* 11442 * Caller is responsible for calling requestLayout if necessary. 11443 * (This allows addViewInLayout to not request a new layout.) 11444 */ 11445 void assignParent(ViewParent parent) { 11446 if (mParent == null) { 11447 mParent = parent; 11448 } else if (parent == null) { 11449 mParent = null; 11450 } else { 11451 throw new RuntimeException("view " + this + " being added, but" 11452 + " it already has a parent"); 11453 } 11454 } 11455 11456 /** 11457 * This is called when the view is attached to a window. At this point it 11458 * has a Surface and will start drawing. Note that this function is 11459 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 11460 * however it may be called any time before the first onDraw -- including 11461 * before or after {@link #onMeasure(int, int)}. 11462 * 11463 * @see #onDetachedFromWindow() 11464 */ 11465 protected void onAttachedToWindow() { 11466 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 11467 mParent.requestTransparentRegion(this); 11468 } 11469 11470 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 11471 initialAwakenScrollBars(); 11472 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 11473 } 11474 11475 jumpDrawablesToCurrentState(); 11476 11477 resolveRtlProperties(); 11478 11479 clearAccessibilityFocus(); 11480 if (isFocused()) { 11481 InputMethodManager imm = InputMethodManager.peekInstance(); 11482 imm.focusIn(this); 11483 } 11484 11485 if (mAttachInfo != null && mDisplayList != null) { 11486 mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList); 11487 } 11488 } 11489 11490 void resolveRtlProperties() { 11491 // Order is important here: LayoutDirection MUST be resolved first... 11492 resolveLayoutDirection(); 11493 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 11494 resolvePadding(); 11495 resolveLayoutParams(); 11496 resolveTextDirection(); 11497 resolveTextAlignment(); 11498 resolveDrawables(); 11499 } 11500 11501 /** 11502 * @see #onScreenStateChanged(int) 11503 */ 11504 void dispatchScreenStateChanged(int screenState) { 11505 onScreenStateChanged(screenState); 11506 } 11507 11508 /** 11509 * This method is called whenever the state of the screen this view is 11510 * attached to changes. A state change will usually occurs when the screen 11511 * turns on or off (whether it happens automatically or the user does it 11512 * manually.) 11513 * 11514 * @param screenState The new state of the screen. Can be either 11515 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 11516 */ 11517 public void onScreenStateChanged(int screenState) { 11518 } 11519 11520 /** 11521 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 11522 */ 11523 private boolean hasRtlSupport() { 11524 return mContext.getApplicationInfo().hasRtlSupport(); 11525 } 11526 11527 /** 11528 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 11529 * that the parent directionality can and will be resolved before its children. 11530 * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done. 11531 */ 11532 public void resolveLayoutDirection() { 11533 // Clear any previous layout direction resolution 11534 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 11535 11536 if (hasRtlSupport()) { 11537 // Set resolved depending on layout direction 11538 switch (getLayoutDirection()) { 11539 case LAYOUT_DIRECTION_INHERIT: 11540 // We cannot resolve yet. LTR is by default and let the resolution happen again 11541 // later to get the correct resolved value 11542 if (!canResolveLayoutDirection()) return; 11543 11544 ViewGroup viewGroup = ((ViewGroup) mParent); 11545 11546 // We cannot resolve yet on the parent too. LTR is by default and let the 11547 // resolution happen again later 11548 if (!viewGroup.canResolveLayoutDirection()) return; 11549 11550 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11551 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11552 } 11553 break; 11554 case LAYOUT_DIRECTION_RTL: 11555 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11556 break; 11557 case LAYOUT_DIRECTION_LOCALE: 11558 if(isLayoutDirectionRtl(Locale.getDefault())) { 11559 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11560 } 11561 break; 11562 default: 11563 // Nothing to do, LTR by default 11564 } 11565 } 11566 11567 // Set to resolved 11568 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 11569 onResolvedLayoutDirectionChanged(); 11570 } 11571 11572 /** 11573 * Called when layout direction has been resolved. 11574 * 11575 * The default implementation does nothing. 11576 */ 11577 public void onResolvedLayoutDirectionChanged() { 11578 } 11579 11580 /** 11581 * Return if padding has been resolved 11582 */ 11583 boolean isPaddingResolved() { 11584 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) != 0; 11585 } 11586 11587 /** 11588 * Resolve padding depending on layout direction. 11589 */ 11590 public void resolvePadding() { 11591 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 11592 if (targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport()) { 11593 // Pre Jelly Bean MR1 case (compatibility mode) OR no RTL support case: 11594 // left / right padding are used if defined. If they are not defined and start / end 11595 // padding are defined (e.g. in Frameworks resources), then we use start / end and 11596 // resolve them as left / right (layout direction is not taken into account). 11597 if (mUserPaddingLeftInitial == UNDEFINED_PADDING && 11598 mUserPaddingStart != UNDEFINED_PADDING) { 11599 mUserPaddingLeft = mUserPaddingStart; 11600 } 11601 if (mUserPaddingRightInitial == UNDEFINED_PADDING && 11602 mUserPaddingEnd != UNDEFINED_PADDING) { 11603 mUserPaddingRight = mUserPaddingEnd; 11604 } 11605 11606 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 11607 11608 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, 11609 mUserPaddingBottom); 11610 } else { 11611 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 11612 // If start / end padding are defined, they will be resolved (hence overriding) to 11613 // left / right or right / left depending on the resolved layout direction. 11614 // If start / end padding are not defined, use the left / right ones. 11615 int resolvedLayoutDirection = getResolvedLayoutDirection(); 11616 // Set user padding to initial values ... 11617 mUserPaddingLeft = (mUserPaddingLeftInitial == UNDEFINED_PADDING) ? 11618 0 : mUserPaddingLeftInitial; 11619 mUserPaddingRight = (mUserPaddingRightInitial == UNDEFINED_PADDING) ? 11620 0 : mUserPaddingRightInitial; 11621 // ... then resolve it. 11622 switch (resolvedLayoutDirection) { 11623 case LAYOUT_DIRECTION_RTL: 11624 if (mUserPaddingStart != UNDEFINED_PADDING) { 11625 mUserPaddingRight = mUserPaddingStart; 11626 } 11627 if (mUserPaddingEnd != UNDEFINED_PADDING) { 11628 mUserPaddingLeft = mUserPaddingEnd; 11629 } 11630 break; 11631 case LAYOUT_DIRECTION_LTR: 11632 default: 11633 if (mUserPaddingStart != UNDEFINED_PADDING) { 11634 mUserPaddingLeft = mUserPaddingStart; 11635 } 11636 if (mUserPaddingEnd != UNDEFINED_PADDING) { 11637 mUserPaddingRight = mUserPaddingEnd; 11638 } 11639 } 11640 11641 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 11642 11643 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, 11644 mUserPaddingBottom); 11645 onPaddingChanged(resolvedLayoutDirection); 11646 } 11647 11648 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 11649 } 11650 11651 /** 11652 * Resolve padding depending on the layout direction. Subclasses that care about 11653 * padding resolution should override this method. The default implementation does 11654 * nothing. 11655 * 11656 * @param layoutDirection the direction of the layout 11657 * 11658 * @see #LAYOUT_DIRECTION_LTR 11659 * @see #LAYOUT_DIRECTION_RTL 11660 */ 11661 public void onPaddingChanged(int layoutDirection) { 11662 } 11663 11664 /** 11665 * Check if layout direction resolution can be done. 11666 * 11667 * @return true if layout direction resolution can be done otherwise return false. 11668 */ 11669 public boolean canResolveLayoutDirection() { 11670 switch (getLayoutDirection()) { 11671 case LAYOUT_DIRECTION_INHERIT: 11672 return (mParent != null) && (mParent instanceof ViewGroup); 11673 default: 11674 return true; 11675 } 11676 } 11677 11678 /** 11679 * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset} 11680 * when reset is done. 11681 */ 11682 public void resetResolvedLayoutDirection() { 11683 // Reset the current resolved bits 11684 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 11685 onResolvedLayoutDirectionReset(); 11686 // Reset also the text direction 11687 resetResolvedTextDirection(); 11688 } 11689 11690 /** 11691 * Called during reset of resolved layout direction. 11692 * 11693 * Subclasses need to override this method to clear cached information that depends on the 11694 * resolved layout direction, or to inform child views that inherit their layout direction. 11695 * 11696 * The default implementation does nothing. 11697 */ 11698 public void onResolvedLayoutDirectionReset() { 11699 } 11700 11701 /** 11702 * Check if a Locale uses an RTL script. 11703 * 11704 * @param locale Locale to check 11705 * @return true if the Locale uses an RTL script. 11706 */ 11707 protected static boolean isLayoutDirectionRtl(Locale locale) { 11708 return (LAYOUT_DIRECTION_RTL == TextUtils.getLayoutDirectionFromLocale(locale)); 11709 } 11710 11711 /** 11712 * This is called when the view is detached from a window. At this point it 11713 * no longer has a surface for drawing. 11714 * 11715 * @see #onAttachedToWindow() 11716 */ 11717 protected void onDetachedFromWindow() { 11718 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 11719 11720 removeUnsetPressCallback(); 11721 removeLongPressCallback(); 11722 removePerformClickCallback(); 11723 removeSendViewScrolledAccessibilityEventCallback(); 11724 11725 destroyDrawingCache(); 11726 11727 destroyLayer(false); 11728 11729 if (mAttachInfo != null) { 11730 if (mDisplayList != null) { 11731 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList); 11732 } 11733 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 11734 } else { 11735 // Should never happen 11736 clearDisplayList(); 11737 } 11738 11739 mCurrentAnimation = null; 11740 11741 resetResolvedLayoutDirection(); 11742 resetResolvedTextAlignment(); 11743 resetAccessibilityStateChanged(); 11744 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 11745 } 11746 11747 /** 11748 * @return The number of times this view has been attached to a window 11749 */ 11750 protected int getWindowAttachCount() { 11751 return mWindowAttachCount; 11752 } 11753 11754 /** 11755 * Retrieve a unique token identifying the window this view is attached to. 11756 * @return Return the window's token for use in 11757 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 11758 */ 11759 public IBinder getWindowToken() { 11760 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 11761 } 11762 11763 /** 11764 * Retrieve a unique token identifying the top-level "real" window of 11765 * the window that this view is attached to. That is, this is like 11766 * {@link #getWindowToken}, except if the window this view in is a panel 11767 * window (attached to another containing window), then the token of 11768 * the containing window is returned instead. 11769 * 11770 * @return Returns the associated window token, either 11771 * {@link #getWindowToken()} or the containing window's token. 11772 */ 11773 public IBinder getApplicationWindowToken() { 11774 AttachInfo ai = mAttachInfo; 11775 if (ai != null) { 11776 IBinder appWindowToken = ai.mPanelParentWindowToken; 11777 if (appWindowToken == null) { 11778 appWindowToken = ai.mWindowToken; 11779 } 11780 return appWindowToken; 11781 } 11782 return null; 11783 } 11784 11785 /** 11786 * Gets the logical display to which the view's window has been attached. 11787 * 11788 * @return The logical display, or null if the view is not currently attached to a window. 11789 */ 11790 public Display getDisplay() { 11791 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 11792 } 11793 11794 /** 11795 * Retrieve private session object this view hierarchy is using to 11796 * communicate with the window manager. 11797 * @return the session object to communicate with the window manager 11798 */ 11799 /*package*/ IWindowSession getWindowSession() { 11800 return mAttachInfo != null ? mAttachInfo.mSession : null; 11801 } 11802 11803 /** 11804 * @param info the {@link android.view.View.AttachInfo} to associated with 11805 * this view 11806 */ 11807 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 11808 //System.out.println("Attached! " + this); 11809 mAttachInfo = info; 11810 mWindowAttachCount++; 11811 // We will need to evaluate the drawable state at least once. 11812 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 11813 if (mFloatingTreeObserver != null) { 11814 info.mTreeObserver.merge(mFloatingTreeObserver); 11815 mFloatingTreeObserver = null; 11816 } 11817 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 11818 mAttachInfo.mScrollContainers.add(this); 11819 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 11820 } 11821 performCollectViewAttributes(mAttachInfo, visibility); 11822 onAttachedToWindow(); 11823 11824 ListenerInfo li = mListenerInfo; 11825 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 11826 li != null ? li.mOnAttachStateChangeListeners : null; 11827 if (listeners != null && listeners.size() > 0) { 11828 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 11829 // perform the dispatching. The iterator is a safe guard against listeners that 11830 // could mutate the list by calling the various add/remove methods. This prevents 11831 // the array from being modified while we iterate it. 11832 for (OnAttachStateChangeListener listener : listeners) { 11833 listener.onViewAttachedToWindow(this); 11834 } 11835 } 11836 11837 int vis = info.mWindowVisibility; 11838 if (vis != GONE) { 11839 onWindowVisibilityChanged(vis); 11840 } 11841 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 11842 // If nobody has evaluated the drawable state yet, then do it now. 11843 refreshDrawableState(); 11844 } 11845 needGlobalAttributesUpdate(false); 11846 } 11847 11848 void dispatchDetachedFromWindow() { 11849 AttachInfo info = mAttachInfo; 11850 if (info != null) { 11851 int vis = info.mWindowVisibility; 11852 if (vis != GONE) { 11853 onWindowVisibilityChanged(GONE); 11854 } 11855 } 11856 11857 onDetachedFromWindow(); 11858 11859 ListenerInfo li = mListenerInfo; 11860 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 11861 li != null ? li.mOnAttachStateChangeListeners : null; 11862 if (listeners != null && listeners.size() > 0) { 11863 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 11864 // perform the dispatching. The iterator is a safe guard against listeners that 11865 // could mutate the list by calling the various add/remove methods. This prevents 11866 // the array from being modified while we iterate it. 11867 for (OnAttachStateChangeListener listener : listeners) { 11868 listener.onViewDetachedFromWindow(this); 11869 } 11870 } 11871 11872 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 11873 mAttachInfo.mScrollContainers.remove(this); 11874 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 11875 } 11876 11877 mAttachInfo = null; 11878 } 11879 11880 /** 11881 * Store this view hierarchy's frozen state into the given container. 11882 * 11883 * @param container The SparseArray in which to save the view's state. 11884 * 11885 * @see #restoreHierarchyState(android.util.SparseArray) 11886 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11887 * @see #onSaveInstanceState() 11888 */ 11889 public void saveHierarchyState(SparseArray<Parcelable> container) { 11890 dispatchSaveInstanceState(container); 11891 } 11892 11893 /** 11894 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 11895 * this view and its children. May be overridden to modify how freezing happens to a 11896 * view's children; for example, some views may want to not store state for their children. 11897 * 11898 * @param container The SparseArray in which to save the view's state. 11899 * 11900 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 11901 * @see #saveHierarchyState(android.util.SparseArray) 11902 * @see #onSaveInstanceState() 11903 */ 11904 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 11905 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 11906 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 11907 Parcelable state = onSaveInstanceState(); 11908 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 11909 throw new IllegalStateException( 11910 "Derived class did not call super.onSaveInstanceState()"); 11911 } 11912 if (state != null) { 11913 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 11914 // + ": " + state); 11915 container.put(mID, state); 11916 } 11917 } 11918 } 11919 11920 /** 11921 * Hook allowing a view to generate a representation of its internal state 11922 * that can later be used to create a new instance with that same state. 11923 * This state should only contain information that is not persistent or can 11924 * not be reconstructed later. For example, you will never store your 11925 * current position on screen because that will be computed again when a 11926 * new instance of the view is placed in its view hierarchy. 11927 * <p> 11928 * Some examples of things you may store here: the current cursor position 11929 * in a text view (but usually not the text itself since that is stored in a 11930 * content provider or other persistent storage), the currently selected 11931 * item in a list view. 11932 * 11933 * @return Returns a Parcelable object containing the view's current dynamic 11934 * state, or null if there is nothing interesting to save. The 11935 * default implementation returns null. 11936 * @see #onRestoreInstanceState(android.os.Parcelable) 11937 * @see #saveHierarchyState(android.util.SparseArray) 11938 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11939 * @see #setSaveEnabled(boolean) 11940 */ 11941 protected Parcelable onSaveInstanceState() { 11942 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 11943 return BaseSavedState.EMPTY_STATE; 11944 } 11945 11946 /** 11947 * Restore this view hierarchy's frozen state from the given container. 11948 * 11949 * @param container The SparseArray which holds previously frozen states. 11950 * 11951 * @see #saveHierarchyState(android.util.SparseArray) 11952 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 11953 * @see #onRestoreInstanceState(android.os.Parcelable) 11954 */ 11955 public void restoreHierarchyState(SparseArray<Parcelable> container) { 11956 dispatchRestoreInstanceState(container); 11957 } 11958 11959 /** 11960 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 11961 * state for this view and its children. May be overridden to modify how restoring 11962 * happens to a view's children; for example, some views may want to not store state 11963 * for their children. 11964 * 11965 * @param container The SparseArray which holds previously saved state. 11966 * 11967 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11968 * @see #restoreHierarchyState(android.util.SparseArray) 11969 * @see #onRestoreInstanceState(android.os.Parcelable) 11970 */ 11971 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 11972 if (mID != NO_ID) { 11973 Parcelable state = container.get(mID); 11974 if (state != null) { 11975 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 11976 // + ": " + state); 11977 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 11978 onRestoreInstanceState(state); 11979 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 11980 throw new IllegalStateException( 11981 "Derived class did not call super.onRestoreInstanceState()"); 11982 } 11983 } 11984 } 11985 } 11986 11987 /** 11988 * Hook allowing a view to re-apply a representation of its internal state that had previously 11989 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 11990 * null state. 11991 * 11992 * @param state The frozen state that had previously been returned by 11993 * {@link #onSaveInstanceState}. 11994 * 11995 * @see #onSaveInstanceState() 11996 * @see #restoreHierarchyState(android.util.SparseArray) 11997 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 11998 */ 11999 protected void onRestoreInstanceState(Parcelable state) { 12000 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12001 if (state != BaseSavedState.EMPTY_STATE && state != null) { 12002 throw new IllegalArgumentException("Wrong state class, expecting View State but " 12003 + "received " + state.getClass().toString() + " instead. This usually happens " 12004 + "when two views of different type have the same id in the same hierarchy. " 12005 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 12006 + "other views do not use the same id."); 12007 } 12008 } 12009 12010 /** 12011 * <p>Return the time at which the drawing of the view hierarchy started.</p> 12012 * 12013 * @return the drawing start time in milliseconds 12014 */ 12015 public long getDrawingTime() { 12016 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 12017 } 12018 12019 /** 12020 * <p>Enables or disables the duplication of the parent's state into this view. When 12021 * duplication is enabled, this view gets its drawable state from its parent rather 12022 * than from its own internal properties.</p> 12023 * 12024 * <p>Note: in the current implementation, setting this property to true after the 12025 * view was added to a ViewGroup might have no effect at all. This property should 12026 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 12027 * 12028 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 12029 * property is enabled, an exception will be thrown.</p> 12030 * 12031 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 12032 * parent, these states should not be affected by this method.</p> 12033 * 12034 * @param enabled True to enable duplication of the parent's drawable state, false 12035 * to disable it. 12036 * 12037 * @see #getDrawableState() 12038 * @see #isDuplicateParentStateEnabled() 12039 */ 12040 public void setDuplicateParentStateEnabled(boolean enabled) { 12041 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 12042 } 12043 12044 /** 12045 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 12046 * 12047 * @return True if this view's drawable state is duplicated from the parent, 12048 * false otherwise 12049 * 12050 * @see #getDrawableState() 12051 * @see #setDuplicateParentStateEnabled(boolean) 12052 */ 12053 public boolean isDuplicateParentStateEnabled() { 12054 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 12055 } 12056 12057 /** 12058 * <p>Specifies the type of layer backing this view. The layer can be 12059 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 12060 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 12061 * 12062 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12063 * instance that controls how the layer is composed on screen. The following 12064 * properties of the paint are taken into account when composing the layer:</p> 12065 * <ul> 12066 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12067 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12068 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12069 * </ul> 12070 * 12071 * <p>If this view has an alpha value set to < 1.0 by calling 12072 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 12073 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 12074 * equivalent to setting a hardware layer on this view and providing a paint with 12075 * the desired alpha value.</p> 12076 * 12077 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 12078 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 12079 * for more information on when and how to use layers.</p> 12080 * 12081 * @param layerType The type of layer to use with this view, must be one of 12082 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12083 * {@link #LAYER_TYPE_HARDWARE} 12084 * @param paint The paint used to compose the layer. This argument is optional 12085 * and can be null. It is ignored when the layer type is 12086 * {@link #LAYER_TYPE_NONE} 12087 * 12088 * @see #getLayerType() 12089 * @see #LAYER_TYPE_NONE 12090 * @see #LAYER_TYPE_SOFTWARE 12091 * @see #LAYER_TYPE_HARDWARE 12092 * @see #setAlpha(float) 12093 * 12094 * @attr ref android.R.styleable#View_layerType 12095 */ 12096 public void setLayerType(int layerType, Paint paint) { 12097 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 12098 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 12099 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 12100 } 12101 12102 if (layerType == mLayerType) { 12103 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 12104 mLayerPaint = paint == null ? new Paint() : paint; 12105 invalidateParentCaches(); 12106 invalidate(true); 12107 } 12108 return; 12109 } 12110 12111 // Destroy any previous software drawing cache if needed 12112 switch (mLayerType) { 12113 case LAYER_TYPE_HARDWARE: 12114 destroyLayer(false); 12115 // fall through - non-accelerated views may use software layer mechanism instead 12116 case LAYER_TYPE_SOFTWARE: 12117 destroyDrawingCache(); 12118 break; 12119 default: 12120 break; 12121 } 12122 12123 mLayerType = layerType; 12124 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 12125 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 12126 mLocalDirtyRect = layerDisabled ? null : new Rect(); 12127 12128 invalidateParentCaches(); 12129 invalidate(true); 12130 } 12131 12132 /** 12133 * Updates the {@link Paint} object used with the current layer (used only if the current 12134 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 12135 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 12136 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 12137 * ensure that the view gets redrawn immediately. 12138 * 12139 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12140 * instance that controls how the layer is composed on screen. The following 12141 * properties of the paint are taken into account when composing the layer:</p> 12142 * <ul> 12143 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12144 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12145 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12146 * </ul> 12147 * 12148 * <p>If this view has an alpha value set to < 1.0 by calling 12149 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 12150 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 12151 * equivalent to setting a hardware layer on this view and providing a paint with 12152 * the desired alpha value.</p> 12153 * 12154 * @param paint The paint used to compose the layer. This argument is optional 12155 * and can be null. It is ignored when the layer type is 12156 * {@link #LAYER_TYPE_NONE} 12157 * 12158 * @see #setLayerType(int, android.graphics.Paint) 12159 */ 12160 public void setLayerPaint(Paint paint) { 12161 int layerType = getLayerType(); 12162 if (layerType != LAYER_TYPE_NONE) { 12163 mLayerPaint = paint == null ? new Paint() : paint; 12164 if (layerType == LAYER_TYPE_HARDWARE) { 12165 HardwareLayer layer = getHardwareLayer(); 12166 if (layer != null) { 12167 layer.setLayerPaint(paint); 12168 } 12169 invalidateViewProperty(false, false); 12170 } else { 12171 invalidate(); 12172 } 12173 } 12174 } 12175 12176 /** 12177 * Indicates whether this view has a static layer. A view with layer type 12178 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 12179 * dynamic. 12180 */ 12181 boolean hasStaticLayer() { 12182 return true; 12183 } 12184 12185 /** 12186 * Indicates what type of layer is currently associated with this view. By default 12187 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 12188 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 12189 * for more information on the different types of layers. 12190 * 12191 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12192 * {@link #LAYER_TYPE_HARDWARE} 12193 * 12194 * @see #setLayerType(int, android.graphics.Paint) 12195 * @see #buildLayer() 12196 * @see #LAYER_TYPE_NONE 12197 * @see #LAYER_TYPE_SOFTWARE 12198 * @see #LAYER_TYPE_HARDWARE 12199 */ 12200 public int getLayerType() { 12201 return mLayerType; 12202 } 12203 12204 /** 12205 * Forces this view's layer to be created and this view to be rendered 12206 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 12207 * invoking this method will have no effect. 12208 * 12209 * This method can for instance be used to render a view into its layer before 12210 * starting an animation. If this view is complex, rendering into the layer 12211 * before starting the animation will avoid skipping frames. 12212 * 12213 * @throws IllegalStateException If this view is not attached to a window 12214 * 12215 * @see #setLayerType(int, android.graphics.Paint) 12216 */ 12217 public void buildLayer() { 12218 if (mLayerType == LAYER_TYPE_NONE) return; 12219 12220 if (mAttachInfo == null) { 12221 throw new IllegalStateException("This view must be attached to a window first"); 12222 } 12223 12224 switch (mLayerType) { 12225 case LAYER_TYPE_HARDWARE: 12226 if (mAttachInfo.mHardwareRenderer != null && 12227 mAttachInfo.mHardwareRenderer.isEnabled() && 12228 mAttachInfo.mHardwareRenderer.validate()) { 12229 getHardwareLayer(); 12230 } 12231 break; 12232 case LAYER_TYPE_SOFTWARE: 12233 buildDrawingCache(true); 12234 break; 12235 } 12236 } 12237 12238 /** 12239 * <p>Returns a hardware layer that can be used to draw this view again 12240 * without executing its draw method.</p> 12241 * 12242 * @return A HardwareLayer ready to render, or null if an error occurred. 12243 */ 12244 HardwareLayer getHardwareLayer() { 12245 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 12246 !mAttachInfo.mHardwareRenderer.isEnabled()) { 12247 return null; 12248 } 12249 12250 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 12251 12252 final int width = mRight - mLeft; 12253 final int height = mBottom - mTop; 12254 12255 if (width == 0 || height == 0) { 12256 return null; 12257 } 12258 12259 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 12260 if (mHardwareLayer == null) { 12261 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 12262 width, height, isOpaque()); 12263 mLocalDirtyRect.set(0, 0, width, height); 12264 } else { 12265 if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 12266 if (mHardwareLayer.resize(width, height)) { 12267 mLocalDirtyRect.set(0, 0, width, height); 12268 } 12269 } 12270 12271 // This should not be necessary but applications that change 12272 // the parameters of their background drawable without calling 12273 // this.setBackground(Drawable) can leave the view in a bad state 12274 // (for instance isOpaque() returns true, but the background is 12275 // not opaque.) 12276 computeOpaqueFlags(); 12277 12278 final boolean opaque = isOpaque(); 12279 if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) { 12280 mHardwareLayer.setOpaque(opaque); 12281 mLocalDirtyRect.set(0, 0, width, height); 12282 } 12283 } 12284 12285 // The layer is not valid if the underlying GPU resources cannot be allocated 12286 if (!mHardwareLayer.isValid()) { 12287 return null; 12288 } 12289 12290 mHardwareLayer.setLayerPaint(mLayerPaint); 12291 mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 12292 ViewRootImpl viewRoot = getViewRootImpl(); 12293 if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer); 12294 12295 mLocalDirtyRect.setEmpty(); 12296 } 12297 12298 return mHardwareLayer; 12299 } 12300 12301 /** 12302 * Destroys this View's hardware layer if possible. 12303 * 12304 * @return True if the layer was destroyed, false otherwise. 12305 * 12306 * @see #setLayerType(int, android.graphics.Paint) 12307 * @see #LAYER_TYPE_HARDWARE 12308 */ 12309 boolean destroyLayer(boolean valid) { 12310 if (mHardwareLayer != null) { 12311 AttachInfo info = mAttachInfo; 12312 if (info != null && info.mHardwareRenderer != null && 12313 info.mHardwareRenderer.isEnabled() && 12314 (valid || info.mHardwareRenderer.validate())) { 12315 mHardwareLayer.destroy(); 12316 mHardwareLayer = null; 12317 12318 invalidate(true); 12319 invalidateParentCaches(); 12320 } 12321 return true; 12322 } 12323 return false; 12324 } 12325 12326 /** 12327 * Destroys all hardware rendering resources. This method is invoked 12328 * when the system needs to reclaim resources. Upon execution of this 12329 * method, you should free any OpenGL resources created by the view. 12330 * 12331 * Note: you <strong>must</strong> call 12332 * <code>super.destroyHardwareResources()</code> when overriding 12333 * this method. 12334 * 12335 * @hide 12336 */ 12337 protected void destroyHardwareResources() { 12338 destroyLayer(true); 12339 } 12340 12341 /** 12342 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 12343 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 12344 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 12345 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 12346 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 12347 * null.</p> 12348 * 12349 * <p>Enabling the drawing cache is similar to 12350 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 12351 * acceleration is turned off. When hardware acceleration is turned on, enabling the 12352 * drawing cache has no effect on rendering because the system uses a different mechanism 12353 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 12354 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 12355 * for information on how to enable software and hardware layers.</p> 12356 * 12357 * <p>This API can be used to manually generate 12358 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 12359 * {@link #getDrawingCache()}.</p> 12360 * 12361 * @param enabled true to enable the drawing cache, false otherwise 12362 * 12363 * @see #isDrawingCacheEnabled() 12364 * @see #getDrawingCache() 12365 * @see #buildDrawingCache() 12366 * @see #setLayerType(int, android.graphics.Paint) 12367 */ 12368 public void setDrawingCacheEnabled(boolean enabled) { 12369 mCachingFailed = false; 12370 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 12371 } 12372 12373 /** 12374 * <p>Indicates whether the drawing cache is enabled for this view.</p> 12375 * 12376 * @return true if the drawing cache is enabled 12377 * 12378 * @see #setDrawingCacheEnabled(boolean) 12379 * @see #getDrawingCache() 12380 */ 12381 @ViewDebug.ExportedProperty(category = "drawing") 12382 public boolean isDrawingCacheEnabled() { 12383 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 12384 } 12385 12386 /** 12387 * Debugging utility which recursively outputs the dirty state of a view and its 12388 * descendants. 12389 * 12390 * @hide 12391 */ 12392 @SuppressWarnings({"UnusedDeclaration"}) 12393 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 12394 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 12395 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 12396 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 12397 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 12398 if (clear) { 12399 mPrivateFlags &= clearMask; 12400 } 12401 if (this instanceof ViewGroup) { 12402 ViewGroup parent = (ViewGroup) this; 12403 final int count = parent.getChildCount(); 12404 for (int i = 0; i < count; i++) { 12405 final View child = parent.getChildAt(i); 12406 child.outputDirtyFlags(indent + " ", clear, clearMask); 12407 } 12408 } 12409 } 12410 12411 /** 12412 * This method is used by ViewGroup to cause its children to restore or recreate their 12413 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 12414 * to recreate its own display list, which would happen if it went through the normal 12415 * draw/dispatchDraw mechanisms. 12416 * 12417 * @hide 12418 */ 12419 protected void dispatchGetDisplayList() {} 12420 12421 /** 12422 * A view that is not attached or hardware accelerated cannot create a display list. 12423 * This method checks these conditions and returns the appropriate result. 12424 * 12425 * @return true if view has the ability to create a display list, false otherwise. 12426 * 12427 * @hide 12428 */ 12429 public boolean canHaveDisplayList() { 12430 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 12431 } 12432 12433 /** 12434 * @return The HardwareRenderer associated with that view or null if hardware rendering 12435 * is not supported or this this has not been attached to a window. 12436 * 12437 * @hide 12438 */ 12439 public HardwareRenderer getHardwareRenderer() { 12440 if (mAttachInfo != null) { 12441 return mAttachInfo.mHardwareRenderer; 12442 } 12443 return null; 12444 } 12445 12446 /** 12447 * Returns a DisplayList. If the incoming displayList is null, one will be created. 12448 * Otherwise, the same display list will be returned (after having been rendered into 12449 * along the way, depending on the invalidation state of the view). 12450 * 12451 * @param displayList The previous version of this displayList, could be null. 12452 * @param isLayer Whether the requester of the display list is a layer. If so, 12453 * the view will avoid creating a layer inside the resulting display list. 12454 * @return A new or reused DisplayList object. 12455 */ 12456 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 12457 if (!canHaveDisplayList()) { 12458 return null; 12459 } 12460 12461 if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || 12462 displayList == null || !displayList.isValid() || 12463 (!isLayer && mRecreateDisplayList))) { 12464 // Don't need to recreate the display list, just need to tell our 12465 // children to restore/recreate theirs 12466 if (displayList != null && displayList.isValid() && 12467 !isLayer && !mRecreateDisplayList) { 12468 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12469 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12470 dispatchGetDisplayList(); 12471 12472 return displayList; 12473 } 12474 12475 if (!isLayer) { 12476 // If we got here, we're recreating it. Mark it as such to ensure that 12477 // we copy in child display lists into ours in drawChild() 12478 mRecreateDisplayList = true; 12479 } 12480 if (displayList == null) { 12481 final String name = getClass().getSimpleName(); 12482 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name); 12483 // If we're creating a new display list, make sure our parent gets invalidated 12484 // since they will need to recreate their display list to account for this 12485 // new child display list. 12486 invalidateParentCaches(); 12487 } 12488 12489 boolean caching = false; 12490 final HardwareCanvas canvas = displayList.start(); 12491 int width = mRight - mLeft; 12492 int height = mBottom - mTop; 12493 12494 try { 12495 canvas.setViewport(width, height); 12496 // The dirty rect should always be null for a display list 12497 canvas.onPreDraw(null); 12498 int layerType = getLayerType(); 12499 if (!isLayer && layerType != LAYER_TYPE_NONE) { 12500 if (layerType == LAYER_TYPE_HARDWARE) { 12501 final HardwareLayer layer = getHardwareLayer(); 12502 if (layer != null && layer.isValid()) { 12503 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 12504 } else { 12505 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 12506 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 12507 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 12508 } 12509 caching = true; 12510 } else { 12511 buildDrawingCache(true); 12512 Bitmap cache = getDrawingCache(true); 12513 if (cache != null) { 12514 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 12515 caching = true; 12516 } 12517 } 12518 } else { 12519 12520 computeScroll(); 12521 12522 canvas.translate(-mScrollX, -mScrollY); 12523 if (!isLayer) { 12524 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12525 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12526 } 12527 12528 // Fast path for layouts with no backgrounds 12529 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12530 dispatchDraw(canvas); 12531 } else { 12532 draw(canvas); 12533 } 12534 } 12535 } finally { 12536 canvas.onPostDraw(); 12537 12538 displayList.end(); 12539 displayList.setCaching(caching); 12540 if (isLayer) { 12541 displayList.setLeftTopRightBottom(0, 0, width, height); 12542 } else { 12543 setDisplayListProperties(displayList); 12544 } 12545 } 12546 } else if (!isLayer) { 12547 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12548 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12549 } 12550 12551 return displayList; 12552 } 12553 12554 /** 12555 * Get the DisplayList for the HardwareLayer 12556 * 12557 * @param layer The HardwareLayer whose DisplayList we want 12558 * @return A DisplayList fopr the specified HardwareLayer 12559 */ 12560 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 12561 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 12562 layer.setDisplayList(displayList); 12563 return displayList; 12564 } 12565 12566 12567 /** 12568 * <p>Returns a display list that can be used to draw this view again 12569 * without executing its draw method.</p> 12570 * 12571 * @return A DisplayList ready to replay, or null if caching is not enabled. 12572 * 12573 * @hide 12574 */ 12575 public DisplayList getDisplayList() { 12576 mDisplayList = getDisplayList(mDisplayList, false); 12577 return mDisplayList; 12578 } 12579 12580 private void clearDisplayList() { 12581 if (mDisplayList != null) { 12582 mDisplayList.invalidate(); 12583 mDisplayList.clear(); 12584 } 12585 } 12586 12587 /** 12588 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 12589 * 12590 * @return A non-scaled bitmap representing this view or null if cache is disabled. 12591 * 12592 * @see #getDrawingCache(boolean) 12593 */ 12594 public Bitmap getDrawingCache() { 12595 return getDrawingCache(false); 12596 } 12597 12598 /** 12599 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 12600 * is null when caching is disabled. If caching is enabled and the cache is not ready, 12601 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 12602 * draw from the cache when the cache is enabled. To benefit from the cache, you must 12603 * request the drawing cache by calling this method and draw it on screen if the 12604 * returned bitmap is not null.</p> 12605 * 12606 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 12607 * this method will create a bitmap of the same size as this view. Because this bitmap 12608 * will be drawn scaled by the parent ViewGroup, the result on screen might show 12609 * scaling artifacts. To avoid such artifacts, you should call this method by setting 12610 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 12611 * size than the view. This implies that your application must be able to handle this 12612 * size.</p> 12613 * 12614 * @param autoScale Indicates whether the generated bitmap should be scaled based on 12615 * the current density of the screen when the application is in compatibility 12616 * mode. 12617 * 12618 * @return A bitmap representing this view or null if cache is disabled. 12619 * 12620 * @see #setDrawingCacheEnabled(boolean) 12621 * @see #isDrawingCacheEnabled() 12622 * @see #buildDrawingCache(boolean) 12623 * @see #destroyDrawingCache() 12624 */ 12625 public Bitmap getDrawingCache(boolean autoScale) { 12626 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 12627 return null; 12628 } 12629 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 12630 buildDrawingCache(autoScale); 12631 } 12632 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 12633 } 12634 12635 /** 12636 * <p>Frees the resources used by the drawing cache. If you call 12637 * {@link #buildDrawingCache()} manually without calling 12638 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 12639 * should cleanup the cache with this method afterwards.</p> 12640 * 12641 * @see #setDrawingCacheEnabled(boolean) 12642 * @see #buildDrawingCache() 12643 * @see #getDrawingCache() 12644 */ 12645 public void destroyDrawingCache() { 12646 if (mDrawingCache != null) { 12647 mDrawingCache.recycle(); 12648 mDrawingCache = null; 12649 } 12650 if (mUnscaledDrawingCache != null) { 12651 mUnscaledDrawingCache.recycle(); 12652 mUnscaledDrawingCache = null; 12653 } 12654 } 12655 12656 /** 12657 * Setting a solid background color for the drawing cache's bitmaps will improve 12658 * performance and memory usage. Note, though that this should only be used if this 12659 * view will always be drawn on top of a solid color. 12660 * 12661 * @param color The background color to use for the drawing cache's bitmap 12662 * 12663 * @see #setDrawingCacheEnabled(boolean) 12664 * @see #buildDrawingCache() 12665 * @see #getDrawingCache() 12666 */ 12667 public void setDrawingCacheBackgroundColor(int color) { 12668 if (color != mDrawingCacheBackgroundColor) { 12669 mDrawingCacheBackgroundColor = color; 12670 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 12671 } 12672 } 12673 12674 /** 12675 * @see #setDrawingCacheBackgroundColor(int) 12676 * 12677 * @return The background color to used for the drawing cache's bitmap 12678 */ 12679 public int getDrawingCacheBackgroundColor() { 12680 return mDrawingCacheBackgroundColor; 12681 } 12682 12683 /** 12684 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 12685 * 12686 * @see #buildDrawingCache(boolean) 12687 */ 12688 public void buildDrawingCache() { 12689 buildDrawingCache(false); 12690 } 12691 12692 /** 12693 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 12694 * 12695 * <p>If you call {@link #buildDrawingCache()} manually without calling 12696 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 12697 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 12698 * 12699 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 12700 * this method will create a bitmap of the same size as this view. Because this bitmap 12701 * will be drawn scaled by the parent ViewGroup, the result on screen might show 12702 * scaling artifacts. To avoid such artifacts, you should call this method by setting 12703 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 12704 * size than the view. This implies that your application must be able to handle this 12705 * size.</p> 12706 * 12707 * <p>You should avoid calling this method when hardware acceleration is enabled. If 12708 * you do not need the drawing cache bitmap, calling this method will increase memory 12709 * usage and cause the view to be rendered in software once, thus negatively impacting 12710 * performance.</p> 12711 * 12712 * @see #getDrawingCache() 12713 * @see #destroyDrawingCache() 12714 */ 12715 public void buildDrawingCache(boolean autoScale) { 12716 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 12717 mDrawingCache == null : mUnscaledDrawingCache == null)) { 12718 mCachingFailed = false; 12719 12720 int width = mRight - mLeft; 12721 int height = mBottom - mTop; 12722 12723 final AttachInfo attachInfo = mAttachInfo; 12724 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 12725 12726 if (autoScale && scalingRequired) { 12727 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 12728 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 12729 } 12730 12731 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 12732 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 12733 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 12734 12735 final int projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 12736 final int drawingCacheSize = 12737 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 12738 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 12739 if (width > 0 && height > 0) { 12740 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 12741 + projectedBitmapSize + " bytes, only " 12742 + drawingCacheSize + " available"); 12743 } 12744 destroyDrawingCache(); 12745 mCachingFailed = true; 12746 return; 12747 } 12748 12749 boolean clear = true; 12750 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 12751 12752 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 12753 Bitmap.Config quality; 12754 if (!opaque) { 12755 // Never pick ARGB_4444 because it looks awful 12756 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 12757 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 12758 case DRAWING_CACHE_QUALITY_AUTO: 12759 quality = Bitmap.Config.ARGB_8888; 12760 break; 12761 case DRAWING_CACHE_QUALITY_LOW: 12762 quality = Bitmap.Config.ARGB_8888; 12763 break; 12764 case DRAWING_CACHE_QUALITY_HIGH: 12765 quality = Bitmap.Config.ARGB_8888; 12766 break; 12767 default: 12768 quality = Bitmap.Config.ARGB_8888; 12769 break; 12770 } 12771 } else { 12772 // Optimization for translucent windows 12773 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 12774 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 12775 } 12776 12777 // Try to cleanup memory 12778 if (bitmap != null) bitmap.recycle(); 12779 12780 try { 12781 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 12782 width, height, quality); 12783 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 12784 if (autoScale) { 12785 mDrawingCache = bitmap; 12786 } else { 12787 mUnscaledDrawingCache = bitmap; 12788 } 12789 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 12790 } catch (OutOfMemoryError e) { 12791 // If there is not enough memory to create the bitmap cache, just 12792 // ignore the issue as bitmap caches are not required to draw the 12793 // view hierarchy 12794 if (autoScale) { 12795 mDrawingCache = null; 12796 } else { 12797 mUnscaledDrawingCache = null; 12798 } 12799 mCachingFailed = true; 12800 return; 12801 } 12802 12803 clear = drawingCacheBackgroundColor != 0; 12804 } 12805 12806 Canvas canvas; 12807 if (attachInfo != null) { 12808 canvas = attachInfo.mCanvas; 12809 if (canvas == null) { 12810 canvas = new Canvas(); 12811 } 12812 canvas.setBitmap(bitmap); 12813 // Temporarily clobber the cached Canvas in case one of our children 12814 // is also using a drawing cache. Without this, the children would 12815 // steal the canvas by attaching their own bitmap to it and bad, bad 12816 // thing would happen (invisible views, corrupted drawings, etc.) 12817 attachInfo.mCanvas = null; 12818 } else { 12819 // This case should hopefully never or seldom happen 12820 canvas = new Canvas(bitmap); 12821 } 12822 12823 if (clear) { 12824 bitmap.eraseColor(drawingCacheBackgroundColor); 12825 } 12826 12827 computeScroll(); 12828 final int restoreCount = canvas.save(); 12829 12830 if (autoScale && scalingRequired) { 12831 final float scale = attachInfo.mApplicationScale; 12832 canvas.scale(scale, scale); 12833 } 12834 12835 canvas.translate(-mScrollX, -mScrollY); 12836 12837 mPrivateFlags |= PFLAG_DRAWN; 12838 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 12839 mLayerType != LAYER_TYPE_NONE) { 12840 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 12841 } 12842 12843 // Fast path for layouts with no backgrounds 12844 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12845 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12846 dispatchDraw(canvas); 12847 } else { 12848 draw(canvas); 12849 } 12850 12851 canvas.restoreToCount(restoreCount); 12852 canvas.setBitmap(null); 12853 12854 if (attachInfo != null) { 12855 // Restore the cached Canvas for our siblings 12856 attachInfo.mCanvas = canvas; 12857 } 12858 } 12859 } 12860 12861 /** 12862 * Create a snapshot of the view into a bitmap. We should probably make 12863 * some form of this public, but should think about the API. 12864 */ 12865 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 12866 int width = mRight - mLeft; 12867 int height = mBottom - mTop; 12868 12869 final AttachInfo attachInfo = mAttachInfo; 12870 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 12871 width = (int) ((width * scale) + 0.5f); 12872 height = (int) ((height * scale) + 0.5f); 12873 12874 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 12875 width > 0 ? width : 1, height > 0 ? height : 1, quality); 12876 if (bitmap == null) { 12877 throw new OutOfMemoryError(); 12878 } 12879 12880 Resources resources = getResources(); 12881 if (resources != null) { 12882 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 12883 } 12884 12885 Canvas canvas; 12886 if (attachInfo != null) { 12887 canvas = attachInfo.mCanvas; 12888 if (canvas == null) { 12889 canvas = new Canvas(); 12890 } 12891 canvas.setBitmap(bitmap); 12892 // Temporarily clobber the cached Canvas in case one of our children 12893 // is also using a drawing cache. Without this, the children would 12894 // steal the canvas by attaching their own bitmap to it and bad, bad 12895 // things would happen (invisible views, corrupted drawings, etc.) 12896 attachInfo.mCanvas = null; 12897 } else { 12898 // This case should hopefully never or seldom happen 12899 canvas = new Canvas(bitmap); 12900 } 12901 12902 if ((backgroundColor & 0xff000000) != 0) { 12903 bitmap.eraseColor(backgroundColor); 12904 } 12905 12906 computeScroll(); 12907 final int restoreCount = canvas.save(); 12908 canvas.scale(scale, scale); 12909 canvas.translate(-mScrollX, -mScrollY); 12910 12911 // Temporarily remove the dirty mask 12912 int flags = mPrivateFlags; 12913 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12914 12915 // Fast path for layouts with no backgrounds 12916 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12917 dispatchDraw(canvas); 12918 } else { 12919 draw(canvas); 12920 } 12921 12922 mPrivateFlags = flags; 12923 12924 canvas.restoreToCount(restoreCount); 12925 canvas.setBitmap(null); 12926 12927 if (attachInfo != null) { 12928 // Restore the cached Canvas for our siblings 12929 attachInfo.mCanvas = canvas; 12930 } 12931 12932 return bitmap; 12933 } 12934 12935 /** 12936 * Indicates whether this View is currently in edit mode. A View is usually 12937 * in edit mode when displayed within a developer tool. For instance, if 12938 * this View is being drawn by a visual user interface builder, this method 12939 * should return true. 12940 * 12941 * Subclasses should check the return value of this method to provide 12942 * different behaviors if their normal behavior might interfere with the 12943 * host environment. For instance: the class spawns a thread in its 12944 * constructor, the drawing code relies on device-specific features, etc. 12945 * 12946 * This method is usually checked in the drawing code of custom widgets. 12947 * 12948 * @return True if this View is in edit mode, false otherwise. 12949 */ 12950 public boolean isInEditMode() { 12951 return false; 12952 } 12953 12954 /** 12955 * If the View draws content inside its padding and enables fading edges, 12956 * it needs to support padding offsets. Padding offsets are added to the 12957 * fading edges to extend the length of the fade so that it covers pixels 12958 * drawn inside the padding. 12959 * 12960 * Subclasses of this class should override this method if they need 12961 * to draw content inside the padding. 12962 * 12963 * @return True if padding offset must be applied, false otherwise. 12964 * 12965 * @see #getLeftPaddingOffset() 12966 * @see #getRightPaddingOffset() 12967 * @see #getTopPaddingOffset() 12968 * @see #getBottomPaddingOffset() 12969 * 12970 * @since CURRENT 12971 */ 12972 protected boolean isPaddingOffsetRequired() { 12973 return false; 12974 } 12975 12976 /** 12977 * Amount by which to extend the left fading region. Called only when 12978 * {@link #isPaddingOffsetRequired()} returns true. 12979 * 12980 * @return The left padding offset in pixels. 12981 * 12982 * @see #isPaddingOffsetRequired() 12983 * 12984 * @since CURRENT 12985 */ 12986 protected int getLeftPaddingOffset() { 12987 return 0; 12988 } 12989 12990 /** 12991 * Amount by which to extend the right fading region. Called only when 12992 * {@link #isPaddingOffsetRequired()} returns true. 12993 * 12994 * @return The right padding offset in pixels. 12995 * 12996 * @see #isPaddingOffsetRequired() 12997 * 12998 * @since CURRENT 12999 */ 13000 protected int getRightPaddingOffset() { 13001 return 0; 13002 } 13003 13004 /** 13005 * Amount by which to extend the top fading region. Called only when 13006 * {@link #isPaddingOffsetRequired()} returns true. 13007 * 13008 * @return The top padding offset in pixels. 13009 * 13010 * @see #isPaddingOffsetRequired() 13011 * 13012 * @since CURRENT 13013 */ 13014 protected int getTopPaddingOffset() { 13015 return 0; 13016 } 13017 13018 /** 13019 * Amount by which to extend the bottom fading region. Called only when 13020 * {@link #isPaddingOffsetRequired()} returns true. 13021 * 13022 * @return The bottom padding offset in pixels. 13023 * 13024 * @see #isPaddingOffsetRequired() 13025 * 13026 * @since CURRENT 13027 */ 13028 protected int getBottomPaddingOffset() { 13029 return 0; 13030 } 13031 13032 /** 13033 * @hide 13034 * @param offsetRequired 13035 */ 13036 protected int getFadeTop(boolean offsetRequired) { 13037 int top = mPaddingTop; 13038 if (offsetRequired) top += getTopPaddingOffset(); 13039 return top; 13040 } 13041 13042 /** 13043 * @hide 13044 * @param offsetRequired 13045 */ 13046 protected int getFadeHeight(boolean offsetRequired) { 13047 int padding = mPaddingTop; 13048 if (offsetRequired) padding += getTopPaddingOffset(); 13049 return mBottom - mTop - mPaddingBottom - padding; 13050 } 13051 13052 /** 13053 * <p>Indicates whether this view is attached to a hardware accelerated 13054 * window or not.</p> 13055 * 13056 * <p>Even if this method returns true, it does not mean that every call 13057 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 13058 * accelerated {@link android.graphics.Canvas}. For instance, if this view 13059 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 13060 * window is hardware accelerated, 13061 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 13062 * return false, and this method will return true.</p> 13063 * 13064 * @return True if the view is attached to a window and the window is 13065 * hardware accelerated; false in any other case. 13066 */ 13067 public boolean isHardwareAccelerated() { 13068 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13069 } 13070 13071 /** 13072 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 13073 * case of an active Animation being run on the view. 13074 */ 13075 private boolean drawAnimation(ViewGroup parent, long drawingTime, 13076 Animation a, boolean scalingRequired) { 13077 Transformation invalidationTransform; 13078 final int flags = parent.mGroupFlags; 13079 final boolean initialized = a.isInitialized(); 13080 if (!initialized) { 13081 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 13082 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 13083 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 13084 onAnimationStart(); 13085 } 13086 13087 boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f); 13088 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 13089 if (parent.mInvalidationTransformation == null) { 13090 parent.mInvalidationTransformation = new Transformation(); 13091 } 13092 invalidationTransform = parent.mInvalidationTransformation; 13093 a.getTransformation(drawingTime, invalidationTransform, 1f); 13094 } else { 13095 invalidationTransform = parent.mChildTransformation; 13096 } 13097 13098 if (more) { 13099 if (!a.willChangeBounds()) { 13100 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 13101 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 13102 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 13103 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 13104 // The child need to draw an animation, potentially offscreen, so 13105 // make sure we do not cancel invalidate requests 13106 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13107 parent.invalidate(mLeft, mTop, mRight, mBottom); 13108 } 13109 } else { 13110 if (parent.mInvalidateRegion == null) { 13111 parent.mInvalidateRegion = new RectF(); 13112 } 13113 final RectF region = parent.mInvalidateRegion; 13114 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 13115 invalidationTransform); 13116 13117 // The child need to draw an animation, potentially offscreen, so 13118 // make sure we do not cancel invalidate requests 13119 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13120 13121 final int left = mLeft + (int) region.left; 13122 final int top = mTop + (int) region.top; 13123 parent.invalidate(left, top, left + (int) (region.width() + .5f), 13124 top + (int) (region.height() + .5f)); 13125 } 13126 } 13127 return more; 13128 } 13129 13130 /** 13131 * This method is called by getDisplayList() when a display list is created or re-rendered. 13132 * It sets or resets the current value of all properties on that display list (resetting is 13133 * necessary when a display list is being re-created, because we need to make sure that 13134 * previously-set transform values 13135 */ 13136 void setDisplayListProperties(DisplayList displayList) { 13137 if (displayList != null) { 13138 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 13139 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 13140 if (mParent instanceof ViewGroup) { 13141 displayList.setClipChildren( 13142 (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 13143 } 13144 float alpha = 1; 13145 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 13146 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13147 ViewGroup parentVG = (ViewGroup) mParent; 13148 final boolean hasTransform = 13149 parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation); 13150 if (hasTransform) { 13151 Transformation transform = parentVG.mChildTransformation; 13152 final int transformType = parentVG.mChildTransformation.getTransformationType(); 13153 if (transformType != Transformation.TYPE_IDENTITY) { 13154 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 13155 alpha = transform.getAlpha(); 13156 } 13157 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 13158 displayList.setStaticMatrix(transform.getMatrix()); 13159 } 13160 } 13161 } 13162 } 13163 if (mTransformationInfo != null) { 13164 alpha *= mTransformationInfo.mAlpha; 13165 if (alpha < 1) { 13166 final int multipliedAlpha = (int) (255 * alpha); 13167 if (onSetAlpha(multipliedAlpha)) { 13168 alpha = 1; 13169 } 13170 } 13171 displayList.setTransformationInfo(alpha, 13172 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 13173 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 13174 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 13175 mTransformationInfo.mScaleY); 13176 if (mTransformationInfo.mCamera == null) { 13177 mTransformationInfo.mCamera = new Camera(); 13178 mTransformationInfo.matrix3D = new Matrix(); 13179 } 13180 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 13181 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) { 13182 displayList.setPivotX(getPivotX()); 13183 displayList.setPivotY(getPivotY()); 13184 } 13185 } else if (alpha < 1) { 13186 displayList.setAlpha(alpha); 13187 } 13188 } 13189 } 13190 13191 /** 13192 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 13193 * This draw() method is an implementation detail and is not intended to be overridden or 13194 * to be called from anywhere else other than ViewGroup.drawChild(). 13195 */ 13196 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 13197 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13198 boolean more = false; 13199 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 13200 final int flags = parent.mGroupFlags; 13201 13202 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 13203 parent.mChildTransformation.clear(); 13204 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13205 } 13206 13207 Transformation transformToApply = null; 13208 boolean concatMatrix = false; 13209 13210 boolean scalingRequired = false; 13211 boolean caching; 13212 int layerType = getLayerType(); 13213 13214 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 13215 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 13216 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 13217 caching = true; 13218 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 13219 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 13220 } else { 13221 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 13222 } 13223 13224 final Animation a = getAnimation(); 13225 if (a != null) { 13226 more = drawAnimation(parent, drawingTime, a, scalingRequired); 13227 concatMatrix = a.willChangeTransformationMatrix(); 13228 if (concatMatrix) { 13229 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13230 } 13231 transformToApply = parent.mChildTransformation; 13232 } else { 13233 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && 13234 mDisplayList != null) { 13235 // No longer animating: clear out old animation matrix 13236 mDisplayList.setAnimationMatrix(null); 13237 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13238 } 13239 if (!useDisplayListProperties && 13240 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13241 final boolean hasTransform = 13242 parent.getChildStaticTransformation(this, parent.mChildTransformation); 13243 if (hasTransform) { 13244 final int transformType = parent.mChildTransformation.getTransformationType(); 13245 transformToApply = transformType != Transformation.TYPE_IDENTITY ? 13246 parent.mChildTransformation : null; 13247 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 13248 } 13249 } 13250 } 13251 13252 concatMatrix |= !childHasIdentityMatrix; 13253 13254 // Sets the flag as early as possible to allow draw() implementations 13255 // to call invalidate() successfully when doing animations 13256 mPrivateFlags |= PFLAG_DRAWN; 13257 13258 if (!concatMatrix && 13259 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 13260 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 13261 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 13262 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 13263 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 13264 return more; 13265 } 13266 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 13267 13268 if (hardwareAccelerated) { 13269 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 13270 // retain the flag's value temporarily in the mRecreateDisplayList flag 13271 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 13272 mPrivateFlags &= ~PFLAG_INVALIDATED; 13273 } 13274 13275 DisplayList displayList = null; 13276 Bitmap cache = null; 13277 boolean hasDisplayList = false; 13278 if (caching) { 13279 if (!hardwareAccelerated) { 13280 if (layerType != LAYER_TYPE_NONE) { 13281 layerType = LAYER_TYPE_SOFTWARE; 13282 buildDrawingCache(true); 13283 } 13284 cache = getDrawingCache(true); 13285 } else { 13286 switch (layerType) { 13287 case LAYER_TYPE_SOFTWARE: 13288 if (useDisplayListProperties) { 13289 hasDisplayList = canHaveDisplayList(); 13290 } else { 13291 buildDrawingCache(true); 13292 cache = getDrawingCache(true); 13293 } 13294 break; 13295 case LAYER_TYPE_HARDWARE: 13296 if (useDisplayListProperties) { 13297 hasDisplayList = canHaveDisplayList(); 13298 } 13299 break; 13300 case LAYER_TYPE_NONE: 13301 // Delay getting the display list until animation-driven alpha values are 13302 // set up and possibly passed on to the view 13303 hasDisplayList = canHaveDisplayList(); 13304 break; 13305 } 13306 } 13307 } 13308 useDisplayListProperties &= hasDisplayList; 13309 if (useDisplayListProperties) { 13310 displayList = getDisplayList(); 13311 if (!displayList.isValid()) { 13312 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13313 // to getDisplayList(), the display list will be marked invalid and we should not 13314 // try to use it again. 13315 displayList = null; 13316 hasDisplayList = false; 13317 useDisplayListProperties = false; 13318 } 13319 } 13320 13321 int sx = 0; 13322 int sy = 0; 13323 if (!hasDisplayList) { 13324 computeScroll(); 13325 sx = mScrollX; 13326 sy = mScrollY; 13327 } 13328 13329 final boolean hasNoCache = cache == null || hasDisplayList; 13330 final boolean offsetForScroll = cache == null && !hasDisplayList && 13331 layerType != LAYER_TYPE_HARDWARE; 13332 13333 int restoreTo = -1; 13334 if (!useDisplayListProperties || transformToApply != null) { 13335 restoreTo = canvas.save(); 13336 } 13337 if (offsetForScroll) { 13338 canvas.translate(mLeft - sx, mTop - sy); 13339 } else { 13340 if (!useDisplayListProperties) { 13341 canvas.translate(mLeft, mTop); 13342 } 13343 if (scalingRequired) { 13344 if (useDisplayListProperties) { 13345 // TODO: Might not need this if we put everything inside the DL 13346 restoreTo = canvas.save(); 13347 } 13348 // mAttachInfo cannot be null, otherwise scalingRequired == false 13349 final float scale = 1.0f / mAttachInfo.mApplicationScale; 13350 canvas.scale(scale, scale); 13351 } 13352 } 13353 13354 float alpha = useDisplayListProperties ? 1 : getAlpha(); 13355 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 13356 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13357 if (transformToApply != null || !childHasIdentityMatrix) { 13358 int transX = 0; 13359 int transY = 0; 13360 13361 if (offsetForScroll) { 13362 transX = -sx; 13363 transY = -sy; 13364 } 13365 13366 if (transformToApply != null) { 13367 if (concatMatrix) { 13368 if (useDisplayListProperties) { 13369 displayList.setAnimationMatrix(transformToApply.getMatrix()); 13370 } else { 13371 // Undo the scroll translation, apply the transformation matrix, 13372 // then redo the scroll translate to get the correct result. 13373 canvas.translate(-transX, -transY); 13374 canvas.concat(transformToApply.getMatrix()); 13375 canvas.translate(transX, transY); 13376 } 13377 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13378 } 13379 13380 float transformAlpha = transformToApply.getAlpha(); 13381 if (transformAlpha < 1) { 13382 alpha *= transformAlpha; 13383 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13384 } 13385 } 13386 13387 if (!childHasIdentityMatrix && !useDisplayListProperties) { 13388 canvas.translate(-transX, -transY); 13389 canvas.concat(getMatrix()); 13390 canvas.translate(transX, transY); 13391 } 13392 } 13393 13394 // Deal with alpha if it is or used to be <1 13395 if (alpha < 1 || 13396 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13397 if (alpha < 1) { 13398 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13399 } else { 13400 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13401 } 13402 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13403 if (hasNoCache) { 13404 final int multipliedAlpha = (int) (255 * alpha); 13405 if (!onSetAlpha(multipliedAlpha)) { 13406 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13407 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 13408 layerType != LAYER_TYPE_NONE) { 13409 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 13410 } 13411 if (useDisplayListProperties) { 13412 displayList.setAlpha(alpha * getAlpha()); 13413 } else if (layerType == LAYER_TYPE_NONE) { 13414 final int scrollX = hasDisplayList ? 0 : sx; 13415 final int scrollY = hasDisplayList ? 0 : sy; 13416 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 13417 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 13418 } 13419 } else { 13420 // Alpha is handled by the child directly, clobber the layer's alpha 13421 mPrivateFlags |= PFLAG_ALPHA_SET; 13422 } 13423 } 13424 } 13425 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 13426 onSetAlpha(255); 13427 mPrivateFlags &= ~PFLAG_ALPHA_SET; 13428 } 13429 13430 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 13431 !useDisplayListProperties) { 13432 if (offsetForScroll) { 13433 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 13434 } else { 13435 if (!scalingRequired || cache == null) { 13436 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 13437 } else { 13438 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 13439 } 13440 } 13441 } 13442 13443 if (!useDisplayListProperties && hasDisplayList) { 13444 displayList = getDisplayList(); 13445 if (!displayList.isValid()) { 13446 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13447 // to getDisplayList(), the display list will be marked invalid and we should not 13448 // try to use it again. 13449 displayList = null; 13450 hasDisplayList = false; 13451 } 13452 } 13453 13454 if (hasNoCache) { 13455 boolean layerRendered = false; 13456 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 13457 final HardwareLayer layer = getHardwareLayer(); 13458 if (layer != null && layer.isValid()) { 13459 mLayerPaint.setAlpha((int) (alpha * 255)); 13460 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 13461 layerRendered = true; 13462 } else { 13463 final int scrollX = hasDisplayList ? 0 : sx; 13464 final int scrollY = hasDisplayList ? 0 : sy; 13465 canvas.saveLayer(scrollX, scrollY, 13466 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 13467 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13468 } 13469 } 13470 13471 if (!layerRendered) { 13472 if (!hasDisplayList) { 13473 // Fast path for layouts with no backgrounds 13474 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13475 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13476 dispatchDraw(canvas); 13477 } else { 13478 draw(canvas); 13479 } 13480 } else { 13481 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13482 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 13483 } 13484 } 13485 } else if (cache != null) { 13486 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13487 Paint cachePaint; 13488 13489 if (layerType == LAYER_TYPE_NONE) { 13490 cachePaint = parent.mCachePaint; 13491 if (cachePaint == null) { 13492 cachePaint = new Paint(); 13493 cachePaint.setDither(false); 13494 parent.mCachePaint = cachePaint; 13495 } 13496 if (alpha < 1) { 13497 cachePaint.setAlpha((int) (alpha * 255)); 13498 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13499 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 13500 cachePaint.setAlpha(255); 13501 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13502 } 13503 } else { 13504 cachePaint = mLayerPaint; 13505 cachePaint.setAlpha((int) (alpha * 255)); 13506 } 13507 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 13508 } 13509 13510 if (restoreTo >= 0) { 13511 canvas.restoreToCount(restoreTo); 13512 } 13513 13514 if (a != null && !more) { 13515 if (!hardwareAccelerated && !a.getFillAfter()) { 13516 onSetAlpha(255); 13517 } 13518 parent.finishAnimatingView(this, a); 13519 } 13520 13521 if (more && hardwareAccelerated) { 13522 // invalidation is the trigger to recreate display lists, so if we're using 13523 // display lists to render, force an invalidate to allow the animation to 13524 // continue drawing another frame 13525 parent.invalidate(true); 13526 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 13527 // alpha animations should cause the child to recreate its display list 13528 invalidate(true); 13529 } 13530 } 13531 13532 mRecreateDisplayList = false; 13533 13534 return more; 13535 } 13536 13537 /** 13538 * Manually render this view (and all of its children) to the given Canvas. 13539 * The view must have already done a full layout before this function is 13540 * called. When implementing a view, implement 13541 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 13542 * If you do need to override this method, call the superclass version. 13543 * 13544 * @param canvas The Canvas to which the View is rendered. 13545 */ 13546 public void draw(Canvas canvas) { 13547 final int privateFlags = mPrivateFlags; 13548 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 13549 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 13550 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 13551 13552 /* 13553 * Draw traversal performs several drawing steps which must be executed 13554 * in the appropriate order: 13555 * 13556 * 1. Draw the background 13557 * 2. If necessary, save the canvas' layers to prepare for fading 13558 * 3. Draw view's content 13559 * 4. Draw children 13560 * 5. If necessary, draw the fading edges and restore layers 13561 * 6. Draw decorations (scrollbars for instance) 13562 */ 13563 13564 // Step 1, draw the background, if needed 13565 int saveCount; 13566 13567 if (!dirtyOpaque) { 13568 final Drawable background = mBackground; 13569 if (background != null) { 13570 final int scrollX = mScrollX; 13571 final int scrollY = mScrollY; 13572 13573 if (mBackgroundSizeChanged) { 13574 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 13575 mBackgroundSizeChanged = false; 13576 } 13577 13578 if ((scrollX | scrollY) == 0) { 13579 background.draw(canvas); 13580 } else { 13581 canvas.translate(scrollX, scrollY); 13582 background.draw(canvas); 13583 canvas.translate(-scrollX, -scrollY); 13584 } 13585 } 13586 } 13587 13588 // skip step 2 & 5 if possible (common case) 13589 final int viewFlags = mViewFlags; 13590 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 13591 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 13592 if (!verticalEdges && !horizontalEdges) { 13593 // Step 3, draw the content 13594 if (!dirtyOpaque) onDraw(canvas); 13595 13596 // Step 4, draw the children 13597 dispatchDraw(canvas); 13598 13599 // Step 6, draw decorations (scrollbars) 13600 onDrawScrollBars(canvas); 13601 13602 // we're done... 13603 return; 13604 } 13605 13606 /* 13607 * Here we do the full fledged routine... 13608 * (this is an uncommon case where speed matters less, 13609 * this is why we repeat some of the tests that have been 13610 * done above) 13611 */ 13612 13613 boolean drawTop = false; 13614 boolean drawBottom = false; 13615 boolean drawLeft = false; 13616 boolean drawRight = false; 13617 13618 float topFadeStrength = 0.0f; 13619 float bottomFadeStrength = 0.0f; 13620 float leftFadeStrength = 0.0f; 13621 float rightFadeStrength = 0.0f; 13622 13623 // Step 2, save the canvas' layers 13624 int paddingLeft = mPaddingLeft; 13625 13626 final boolean offsetRequired = isPaddingOffsetRequired(); 13627 if (offsetRequired) { 13628 paddingLeft += getLeftPaddingOffset(); 13629 } 13630 13631 int left = mScrollX + paddingLeft; 13632 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 13633 int top = mScrollY + getFadeTop(offsetRequired); 13634 int bottom = top + getFadeHeight(offsetRequired); 13635 13636 if (offsetRequired) { 13637 right += getRightPaddingOffset(); 13638 bottom += getBottomPaddingOffset(); 13639 } 13640 13641 final ScrollabilityCache scrollabilityCache = mScrollCache; 13642 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 13643 int length = (int) fadeHeight; 13644 13645 // clip the fade length if top and bottom fades overlap 13646 // overlapping fades produce odd-looking artifacts 13647 if (verticalEdges && (top + length > bottom - length)) { 13648 length = (bottom - top) / 2; 13649 } 13650 13651 // also clip horizontal fades if necessary 13652 if (horizontalEdges && (left + length > right - length)) { 13653 length = (right - left) / 2; 13654 } 13655 13656 if (verticalEdges) { 13657 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 13658 drawTop = topFadeStrength * fadeHeight > 1.0f; 13659 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 13660 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 13661 } 13662 13663 if (horizontalEdges) { 13664 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 13665 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 13666 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 13667 drawRight = rightFadeStrength * fadeHeight > 1.0f; 13668 } 13669 13670 saveCount = canvas.getSaveCount(); 13671 13672 int solidColor = getSolidColor(); 13673 if (solidColor == 0) { 13674 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13675 13676 if (drawTop) { 13677 canvas.saveLayer(left, top, right, top + length, null, flags); 13678 } 13679 13680 if (drawBottom) { 13681 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 13682 } 13683 13684 if (drawLeft) { 13685 canvas.saveLayer(left, top, left + length, bottom, null, flags); 13686 } 13687 13688 if (drawRight) { 13689 canvas.saveLayer(right - length, top, right, bottom, null, flags); 13690 } 13691 } else { 13692 scrollabilityCache.setFadeColor(solidColor); 13693 } 13694 13695 // Step 3, draw the content 13696 if (!dirtyOpaque) onDraw(canvas); 13697 13698 // Step 4, draw the children 13699 dispatchDraw(canvas); 13700 13701 // Step 5, draw the fade effect and restore layers 13702 final Paint p = scrollabilityCache.paint; 13703 final Matrix matrix = scrollabilityCache.matrix; 13704 final Shader fade = scrollabilityCache.shader; 13705 13706 if (drawTop) { 13707 matrix.setScale(1, fadeHeight * topFadeStrength); 13708 matrix.postTranslate(left, top); 13709 fade.setLocalMatrix(matrix); 13710 canvas.drawRect(left, top, right, top + length, p); 13711 } 13712 13713 if (drawBottom) { 13714 matrix.setScale(1, fadeHeight * bottomFadeStrength); 13715 matrix.postRotate(180); 13716 matrix.postTranslate(left, bottom); 13717 fade.setLocalMatrix(matrix); 13718 canvas.drawRect(left, bottom - length, right, bottom, p); 13719 } 13720 13721 if (drawLeft) { 13722 matrix.setScale(1, fadeHeight * leftFadeStrength); 13723 matrix.postRotate(-90); 13724 matrix.postTranslate(left, top); 13725 fade.setLocalMatrix(matrix); 13726 canvas.drawRect(left, top, left + length, bottom, p); 13727 } 13728 13729 if (drawRight) { 13730 matrix.setScale(1, fadeHeight * rightFadeStrength); 13731 matrix.postRotate(90); 13732 matrix.postTranslate(right, top); 13733 fade.setLocalMatrix(matrix); 13734 canvas.drawRect(right - length, top, right, bottom, p); 13735 } 13736 13737 canvas.restoreToCount(saveCount); 13738 13739 // Step 6, draw decorations (scrollbars) 13740 onDrawScrollBars(canvas); 13741 } 13742 13743 /** 13744 * Override this if your view is known to always be drawn on top of a solid color background, 13745 * and needs to draw fading edges. Returning a non-zero color enables the view system to 13746 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 13747 * should be set to 0xFF. 13748 * 13749 * @see #setVerticalFadingEdgeEnabled(boolean) 13750 * @see #setHorizontalFadingEdgeEnabled(boolean) 13751 * 13752 * @return The known solid color background for this view, or 0 if the color may vary 13753 */ 13754 @ViewDebug.ExportedProperty(category = "drawing") 13755 public int getSolidColor() { 13756 return 0; 13757 } 13758 13759 /** 13760 * Build a human readable string representation of the specified view flags. 13761 * 13762 * @param flags the view flags to convert to a string 13763 * @return a String representing the supplied flags 13764 */ 13765 private static String printFlags(int flags) { 13766 String output = ""; 13767 int numFlags = 0; 13768 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 13769 output += "TAKES_FOCUS"; 13770 numFlags++; 13771 } 13772 13773 switch (flags & VISIBILITY_MASK) { 13774 case INVISIBLE: 13775 if (numFlags > 0) { 13776 output += " "; 13777 } 13778 output += "INVISIBLE"; 13779 // USELESS HERE numFlags++; 13780 break; 13781 case GONE: 13782 if (numFlags > 0) { 13783 output += " "; 13784 } 13785 output += "GONE"; 13786 // USELESS HERE numFlags++; 13787 break; 13788 default: 13789 break; 13790 } 13791 return output; 13792 } 13793 13794 /** 13795 * Build a human readable string representation of the specified private 13796 * view flags. 13797 * 13798 * @param privateFlags the private view flags to convert to a string 13799 * @return a String representing the supplied flags 13800 */ 13801 private static String printPrivateFlags(int privateFlags) { 13802 String output = ""; 13803 int numFlags = 0; 13804 13805 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 13806 output += "WANTS_FOCUS"; 13807 numFlags++; 13808 } 13809 13810 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 13811 if (numFlags > 0) { 13812 output += " "; 13813 } 13814 output += "FOCUSED"; 13815 numFlags++; 13816 } 13817 13818 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 13819 if (numFlags > 0) { 13820 output += " "; 13821 } 13822 output += "SELECTED"; 13823 numFlags++; 13824 } 13825 13826 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 13827 if (numFlags > 0) { 13828 output += " "; 13829 } 13830 output += "IS_ROOT_NAMESPACE"; 13831 numFlags++; 13832 } 13833 13834 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 13835 if (numFlags > 0) { 13836 output += " "; 13837 } 13838 output += "HAS_BOUNDS"; 13839 numFlags++; 13840 } 13841 13842 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 13843 if (numFlags > 0) { 13844 output += " "; 13845 } 13846 output += "DRAWN"; 13847 // USELESS HERE numFlags++; 13848 } 13849 return output; 13850 } 13851 13852 /** 13853 * <p>Indicates whether or not this view's layout will be requested during 13854 * the next hierarchy layout pass.</p> 13855 * 13856 * @return true if the layout will be forced during next layout pass 13857 */ 13858 public boolean isLayoutRequested() { 13859 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 13860 } 13861 13862 /** 13863 * Assign a size and position to a view and all of its 13864 * descendants 13865 * 13866 * <p>This is the second phase of the layout mechanism. 13867 * (The first is measuring). In this phase, each parent calls 13868 * layout on all of its children to position them. 13869 * This is typically done using the child measurements 13870 * that were stored in the measure pass().</p> 13871 * 13872 * <p>Derived classes should not override this method. 13873 * Derived classes with children should override 13874 * onLayout. In that method, they should 13875 * call layout on each of their children.</p> 13876 * 13877 * @param l Left position, relative to parent 13878 * @param t Top position, relative to parent 13879 * @param r Right position, relative to parent 13880 * @param b Bottom position, relative to parent 13881 */ 13882 @SuppressWarnings({"unchecked"}) 13883 public void layout(int l, int t, int r, int b) { 13884 int oldL = mLeft; 13885 int oldT = mTop; 13886 int oldB = mBottom; 13887 int oldR = mRight; 13888 boolean changed = setFrame(l, t, r, b); 13889 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 13890 onLayout(changed, l, t, r, b); 13891 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 13892 13893 ListenerInfo li = mListenerInfo; 13894 if (li != null && li.mOnLayoutChangeListeners != null) { 13895 ArrayList<OnLayoutChangeListener> listenersCopy = 13896 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 13897 int numListeners = listenersCopy.size(); 13898 for (int i = 0; i < numListeners; ++i) { 13899 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 13900 } 13901 } 13902 } 13903 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 13904 } 13905 13906 /** 13907 * Called from layout when this view should 13908 * assign a size and position to each of its children. 13909 * 13910 * Derived classes with children should override 13911 * this method and call layout on each of 13912 * their children. 13913 * @param changed This is a new size or position for this view 13914 * @param left Left position, relative to parent 13915 * @param top Top position, relative to parent 13916 * @param right Right position, relative to parent 13917 * @param bottom Bottom position, relative to parent 13918 */ 13919 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 13920 } 13921 13922 /** 13923 * Assign a size and position to this view. 13924 * 13925 * This is called from layout. 13926 * 13927 * @param left Left position, relative to parent 13928 * @param top Top position, relative to parent 13929 * @param right Right position, relative to parent 13930 * @param bottom Bottom position, relative to parent 13931 * @return true if the new size and position are different than the 13932 * previous ones 13933 * {@hide} 13934 */ 13935 protected boolean setFrame(int left, int top, int right, int bottom) { 13936 boolean changed = false; 13937 13938 if (DBG) { 13939 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 13940 + right + "," + bottom + ")"); 13941 } 13942 13943 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 13944 changed = true; 13945 13946 // Remember our drawn bit 13947 int drawn = mPrivateFlags & PFLAG_DRAWN; 13948 13949 int oldWidth = mRight - mLeft; 13950 int oldHeight = mBottom - mTop; 13951 int newWidth = right - left; 13952 int newHeight = bottom - top; 13953 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 13954 13955 // Invalidate our old position 13956 invalidate(sizeChanged); 13957 13958 mLeft = left; 13959 mTop = top; 13960 mRight = right; 13961 mBottom = bottom; 13962 if (mDisplayList != null) { 13963 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 13964 } 13965 13966 mPrivateFlags |= PFLAG_HAS_BOUNDS; 13967 13968 13969 if (sizeChanged) { 13970 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 13971 // A change in dimension means an auto-centered pivot point changes, too 13972 if (mTransformationInfo != null) { 13973 mTransformationInfo.mMatrixDirty = true; 13974 } 13975 } 13976 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 13977 } 13978 13979 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 13980 // If we are visible, force the DRAWN bit to on so that 13981 // this invalidate will go through (at least to our parent). 13982 // This is because someone may have invalidated this view 13983 // before this call to setFrame came in, thereby clearing 13984 // the DRAWN bit. 13985 mPrivateFlags |= PFLAG_DRAWN; 13986 invalidate(sizeChanged); 13987 // parent display list may need to be recreated based on a change in the bounds 13988 // of any child 13989 invalidateParentCaches(); 13990 } 13991 13992 // Reset drawn bit to original value (invalidate turns it off) 13993 mPrivateFlags |= drawn; 13994 13995 mBackgroundSizeChanged = true; 13996 } 13997 return changed; 13998 } 13999 14000 /** 14001 * Finalize inflating a view from XML. This is called as the last phase 14002 * of inflation, after all child views have been added. 14003 * 14004 * <p>Even if the subclass overrides onFinishInflate, they should always be 14005 * sure to call the super method, so that we get called. 14006 */ 14007 protected void onFinishInflate() { 14008 } 14009 14010 /** 14011 * Returns the resources associated with this view. 14012 * 14013 * @return Resources object. 14014 */ 14015 public Resources getResources() { 14016 return mResources; 14017 } 14018 14019 /** 14020 * Invalidates the specified Drawable. 14021 * 14022 * @param drawable the drawable to invalidate 14023 */ 14024 public void invalidateDrawable(Drawable drawable) { 14025 if (verifyDrawable(drawable)) { 14026 final Rect dirty = drawable.getBounds(); 14027 final int scrollX = mScrollX; 14028 final int scrollY = mScrollY; 14029 14030 invalidate(dirty.left + scrollX, dirty.top + scrollY, 14031 dirty.right + scrollX, dirty.bottom + scrollY); 14032 } 14033 } 14034 14035 /** 14036 * Schedules an action on a drawable to occur at a specified time. 14037 * 14038 * @param who the recipient of the action 14039 * @param what the action to run on the drawable 14040 * @param when the time at which the action must occur. Uses the 14041 * {@link SystemClock#uptimeMillis} timebase. 14042 */ 14043 public void scheduleDrawable(Drawable who, Runnable what, long when) { 14044 if (verifyDrawable(who) && what != null) { 14045 final long delay = when - SystemClock.uptimeMillis(); 14046 if (mAttachInfo != null) { 14047 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 14048 Choreographer.CALLBACK_ANIMATION, what, who, 14049 Choreographer.subtractFrameDelay(delay)); 14050 } else { 14051 ViewRootImpl.getRunQueue().postDelayed(what, delay); 14052 } 14053 } 14054 } 14055 14056 /** 14057 * Cancels a scheduled action on a drawable. 14058 * 14059 * @param who the recipient of the action 14060 * @param what the action to cancel 14061 */ 14062 public void unscheduleDrawable(Drawable who, Runnable what) { 14063 if (verifyDrawable(who) && what != null) { 14064 if (mAttachInfo != null) { 14065 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14066 Choreographer.CALLBACK_ANIMATION, what, who); 14067 } else { 14068 ViewRootImpl.getRunQueue().removeCallbacks(what); 14069 } 14070 } 14071 } 14072 14073 /** 14074 * Unschedule any events associated with the given Drawable. This can be 14075 * used when selecting a new Drawable into a view, so that the previous 14076 * one is completely unscheduled. 14077 * 14078 * @param who The Drawable to unschedule. 14079 * 14080 * @see #drawableStateChanged 14081 */ 14082 public void unscheduleDrawable(Drawable who) { 14083 if (mAttachInfo != null && who != null) { 14084 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14085 Choreographer.CALLBACK_ANIMATION, null, who); 14086 } 14087 } 14088 14089 /** 14090 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 14091 * that the View directionality can and will be resolved before its Drawables. 14092 * 14093 * Will call {@link View#onResolveDrawables} when resolution is done. 14094 */ 14095 public void resolveDrawables() { 14096 if (mBackground != null) { 14097 mBackground.setLayoutDirection(getResolvedLayoutDirection()); 14098 } 14099 onResolveDrawables(getResolvedLayoutDirection()); 14100 } 14101 14102 /** 14103 * Called when layout direction has been resolved. 14104 * 14105 * The default implementation does nothing. 14106 * 14107 * @param layoutDirection The resolved layout direction. 14108 * 14109 * @see #LAYOUT_DIRECTION_LTR 14110 * @see #LAYOUT_DIRECTION_RTL 14111 */ 14112 public void onResolveDrawables(int layoutDirection) { 14113 } 14114 14115 /** 14116 * If your view subclass is displaying its own Drawable objects, it should 14117 * override this function and return true for any Drawable it is 14118 * displaying. This allows animations for those drawables to be 14119 * scheduled. 14120 * 14121 * <p>Be sure to call through to the super class when overriding this 14122 * function. 14123 * 14124 * @param who The Drawable to verify. Return true if it is one you are 14125 * displaying, else return the result of calling through to the 14126 * super class. 14127 * 14128 * @return boolean If true than the Drawable is being displayed in the 14129 * view; else false and it is not allowed to animate. 14130 * 14131 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 14132 * @see #drawableStateChanged() 14133 */ 14134 protected boolean verifyDrawable(Drawable who) { 14135 return who == mBackground; 14136 } 14137 14138 /** 14139 * This function is called whenever the state of the view changes in such 14140 * a way that it impacts the state of drawables being shown. 14141 * 14142 * <p>Be sure to call through to the superclass when overriding this 14143 * function. 14144 * 14145 * @see Drawable#setState(int[]) 14146 */ 14147 protected void drawableStateChanged() { 14148 Drawable d = mBackground; 14149 if (d != null && d.isStateful()) { 14150 d.setState(getDrawableState()); 14151 } 14152 } 14153 14154 /** 14155 * Call this to force a view to update its drawable state. This will cause 14156 * drawableStateChanged to be called on this view. Views that are interested 14157 * in the new state should call getDrawableState. 14158 * 14159 * @see #drawableStateChanged 14160 * @see #getDrawableState 14161 */ 14162 public void refreshDrawableState() { 14163 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 14164 drawableStateChanged(); 14165 14166 ViewParent parent = mParent; 14167 if (parent != null) { 14168 parent.childDrawableStateChanged(this); 14169 } 14170 } 14171 14172 /** 14173 * Return an array of resource IDs of the drawable states representing the 14174 * current state of the view. 14175 * 14176 * @return The current drawable state 14177 * 14178 * @see Drawable#setState(int[]) 14179 * @see #drawableStateChanged() 14180 * @see #onCreateDrawableState(int) 14181 */ 14182 public final int[] getDrawableState() { 14183 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 14184 return mDrawableState; 14185 } else { 14186 mDrawableState = onCreateDrawableState(0); 14187 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 14188 return mDrawableState; 14189 } 14190 } 14191 14192 /** 14193 * Generate the new {@link android.graphics.drawable.Drawable} state for 14194 * this view. This is called by the view 14195 * system when the cached Drawable state is determined to be invalid. To 14196 * retrieve the current state, you should use {@link #getDrawableState}. 14197 * 14198 * @param extraSpace if non-zero, this is the number of extra entries you 14199 * would like in the returned array in which you can place your own 14200 * states. 14201 * 14202 * @return Returns an array holding the current {@link Drawable} state of 14203 * the view. 14204 * 14205 * @see #mergeDrawableStates(int[], int[]) 14206 */ 14207 protected int[] onCreateDrawableState(int extraSpace) { 14208 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 14209 mParent instanceof View) { 14210 return ((View) mParent).onCreateDrawableState(extraSpace); 14211 } 14212 14213 int[] drawableState; 14214 14215 int privateFlags = mPrivateFlags; 14216 14217 int viewStateIndex = 0; 14218 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 14219 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 14220 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 14221 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 14222 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 14223 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 14224 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 14225 HardwareRenderer.isAvailable()) { 14226 // This is set if HW acceleration is requested, even if the current 14227 // process doesn't allow it. This is just to allow app preview 14228 // windows to better match their app. 14229 viewStateIndex |= VIEW_STATE_ACCELERATED; 14230 } 14231 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 14232 14233 final int privateFlags2 = mPrivateFlags2; 14234 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 14235 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 14236 14237 drawableState = VIEW_STATE_SETS[viewStateIndex]; 14238 14239 //noinspection ConstantIfStatement 14240 if (false) { 14241 Log.i("View", "drawableStateIndex=" + viewStateIndex); 14242 Log.i("View", toString() 14243 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 14244 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 14245 + " fo=" + hasFocus() 14246 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 14247 + " wf=" + hasWindowFocus() 14248 + ": " + Arrays.toString(drawableState)); 14249 } 14250 14251 if (extraSpace == 0) { 14252 return drawableState; 14253 } 14254 14255 final int[] fullState; 14256 if (drawableState != null) { 14257 fullState = new int[drawableState.length + extraSpace]; 14258 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 14259 } else { 14260 fullState = new int[extraSpace]; 14261 } 14262 14263 return fullState; 14264 } 14265 14266 /** 14267 * Merge your own state values in <var>additionalState</var> into the base 14268 * state values <var>baseState</var> that were returned by 14269 * {@link #onCreateDrawableState(int)}. 14270 * 14271 * @param baseState The base state values returned by 14272 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 14273 * own additional state values. 14274 * 14275 * @param additionalState The additional state values you would like 14276 * added to <var>baseState</var>; this array is not modified. 14277 * 14278 * @return As a convenience, the <var>baseState</var> array you originally 14279 * passed into the function is returned. 14280 * 14281 * @see #onCreateDrawableState(int) 14282 */ 14283 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 14284 final int N = baseState.length; 14285 int i = N - 1; 14286 while (i >= 0 && baseState[i] == 0) { 14287 i--; 14288 } 14289 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 14290 return baseState; 14291 } 14292 14293 /** 14294 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 14295 * on all Drawable objects associated with this view. 14296 */ 14297 public void jumpDrawablesToCurrentState() { 14298 if (mBackground != null) { 14299 mBackground.jumpToCurrentState(); 14300 } 14301 } 14302 14303 /** 14304 * Sets the background color for this view. 14305 * @param color the color of the background 14306 */ 14307 @RemotableViewMethod 14308 public void setBackgroundColor(int color) { 14309 if (mBackground instanceof ColorDrawable) { 14310 ((ColorDrawable) mBackground.mutate()).setColor(color); 14311 computeOpaqueFlags(); 14312 } else { 14313 setBackground(new ColorDrawable(color)); 14314 } 14315 } 14316 14317 /** 14318 * Set the background to a given resource. The resource should refer to 14319 * a Drawable object or 0 to remove the background. 14320 * @param resid The identifier of the resource. 14321 * 14322 * @attr ref android.R.styleable#View_background 14323 */ 14324 @RemotableViewMethod 14325 public void setBackgroundResource(int resid) { 14326 if (resid != 0 && resid == mBackgroundResource) { 14327 return; 14328 } 14329 14330 Drawable d= null; 14331 if (resid != 0) { 14332 d = mResources.getDrawable(resid); 14333 } 14334 setBackground(d); 14335 14336 mBackgroundResource = resid; 14337 } 14338 14339 /** 14340 * Set the background to a given Drawable, or remove the background. If the 14341 * background has padding, this View's padding is set to the background's 14342 * padding. However, when a background is removed, this View's padding isn't 14343 * touched. If setting the padding is desired, please use 14344 * {@link #setPadding(int, int, int, int)}. 14345 * 14346 * @param background The Drawable to use as the background, or null to remove the 14347 * background 14348 */ 14349 public void setBackground(Drawable background) { 14350 //noinspection deprecation 14351 setBackgroundDrawable(background); 14352 } 14353 14354 /** 14355 * @deprecated use {@link #setBackground(Drawable)} instead 14356 */ 14357 @Deprecated 14358 public void setBackgroundDrawable(Drawable background) { 14359 computeOpaqueFlags(); 14360 14361 if (background == mBackground) { 14362 return; 14363 } 14364 14365 boolean requestLayout = false; 14366 14367 mBackgroundResource = 0; 14368 14369 /* 14370 * Regardless of whether we're setting a new background or not, we want 14371 * to clear the previous drawable. 14372 */ 14373 if (mBackground != null) { 14374 mBackground.setCallback(null); 14375 unscheduleDrawable(mBackground); 14376 } 14377 14378 if (background != null) { 14379 Rect padding = sThreadLocal.get(); 14380 if (padding == null) { 14381 padding = new Rect(); 14382 sThreadLocal.set(padding); 14383 } 14384 background.setLayoutDirection(getResolvedLayoutDirection()); 14385 if (background.getPadding(padding)) { 14386 // Reset padding resolution 14387 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 14388 switch (background.getLayoutDirection()) { 14389 case LAYOUT_DIRECTION_RTL: 14390 mUserPaddingLeftInitial = padding.right; 14391 mUserPaddingRightInitial = padding.left; 14392 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 14393 break; 14394 case LAYOUT_DIRECTION_LTR: 14395 default: 14396 mUserPaddingLeftInitial = padding.left; 14397 mUserPaddingRightInitial = padding.right; 14398 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 14399 } 14400 } 14401 14402 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 14403 // if it has a different minimum size, we should layout again 14404 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 14405 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 14406 requestLayout = true; 14407 } 14408 14409 background.setCallback(this); 14410 if (background.isStateful()) { 14411 background.setState(getDrawableState()); 14412 } 14413 background.setVisible(getVisibility() == VISIBLE, false); 14414 mBackground = background; 14415 14416 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 14417 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 14418 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 14419 requestLayout = true; 14420 } 14421 } else { 14422 /* Remove the background */ 14423 mBackground = null; 14424 14425 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 14426 /* 14427 * This view ONLY drew the background before and we're removing 14428 * the background, so now it won't draw anything 14429 * (hence we SKIP_DRAW) 14430 */ 14431 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 14432 mPrivateFlags |= PFLAG_SKIP_DRAW; 14433 } 14434 14435 /* 14436 * When the background is set, we try to apply its padding to this 14437 * View. When the background is removed, we don't touch this View's 14438 * padding. This is noted in the Javadocs. Hence, we don't need to 14439 * requestLayout(), the invalidate() below is sufficient. 14440 */ 14441 14442 // The old background's minimum size could have affected this 14443 // View's layout, so let's requestLayout 14444 requestLayout = true; 14445 } 14446 14447 computeOpaqueFlags(); 14448 14449 if (requestLayout) { 14450 requestLayout(); 14451 } 14452 14453 mBackgroundSizeChanged = true; 14454 invalidate(true); 14455 } 14456 14457 /** 14458 * Gets the background drawable 14459 * 14460 * @return The drawable used as the background for this view, if any. 14461 * 14462 * @see #setBackground(Drawable) 14463 * 14464 * @attr ref android.R.styleable#View_background 14465 */ 14466 public Drawable getBackground() { 14467 return mBackground; 14468 } 14469 14470 /** 14471 * Sets the padding. The view may add on the space required to display 14472 * the scrollbars, depending on the style and visibility of the scrollbars. 14473 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 14474 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 14475 * from the values set in this call. 14476 * 14477 * @attr ref android.R.styleable#View_padding 14478 * @attr ref android.R.styleable#View_paddingBottom 14479 * @attr ref android.R.styleable#View_paddingLeft 14480 * @attr ref android.R.styleable#View_paddingRight 14481 * @attr ref android.R.styleable#View_paddingTop 14482 * @param left the left padding in pixels 14483 * @param top the top padding in pixels 14484 * @param right the right padding in pixels 14485 * @param bottom the bottom padding in pixels 14486 */ 14487 public void setPadding(int left, int top, int right, int bottom) { 14488 // Reset padding resolution 14489 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 14490 14491 mUserPaddingStart = UNDEFINED_PADDING; 14492 mUserPaddingEnd = UNDEFINED_PADDING; 14493 14494 mUserPaddingLeftInitial = left; 14495 mUserPaddingRightInitial = right; 14496 14497 internalSetPadding(left, top, right, bottom); 14498 } 14499 14500 /** 14501 * @hide 14502 */ 14503 protected void internalSetPadding(int left, int top, int right, int bottom) { 14504 mUserPaddingLeft = left; 14505 mUserPaddingRight = right; 14506 mUserPaddingBottom = bottom; 14507 14508 final int viewFlags = mViewFlags; 14509 boolean changed = false; 14510 14511 // Common case is there are no scroll bars. 14512 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 14513 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 14514 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 14515 ? 0 : getVerticalScrollbarWidth(); 14516 switch (mVerticalScrollbarPosition) { 14517 case SCROLLBAR_POSITION_DEFAULT: 14518 if (isLayoutRtl()) { 14519 left += offset; 14520 } else { 14521 right += offset; 14522 } 14523 break; 14524 case SCROLLBAR_POSITION_RIGHT: 14525 right += offset; 14526 break; 14527 case SCROLLBAR_POSITION_LEFT: 14528 left += offset; 14529 break; 14530 } 14531 } 14532 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 14533 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 14534 ? 0 : getHorizontalScrollbarHeight(); 14535 } 14536 } 14537 14538 if (mPaddingLeft != left) { 14539 changed = true; 14540 mPaddingLeft = left; 14541 } 14542 if (mPaddingTop != top) { 14543 changed = true; 14544 mPaddingTop = top; 14545 } 14546 if (mPaddingRight != right) { 14547 changed = true; 14548 mPaddingRight = right; 14549 } 14550 if (mPaddingBottom != bottom) { 14551 changed = true; 14552 mPaddingBottom = bottom; 14553 } 14554 14555 if (changed) { 14556 requestLayout(); 14557 } 14558 } 14559 14560 /** 14561 * Sets the relative padding. The view may add on the space required to display 14562 * the scrollbars, depending on the style and visibility of the scrollbars. 14563 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 14564 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 14565 * from the values set in this call. 14566 * 14567 * @attr ref android.R.styleable#View_padding 14568 * @attr ref android.R.styleable#View_paddingBottom 14569 * @attr ref android.R.styleable#View_paddingStart 14570 * @attr ref android.R.styleable#View_paddingEnd 14571 * @attr ref android.R.styleable#View_paddingTop 14572 * @param start the start padding in pixels 14573 * @param top the top padding in pixels 14574 * @param end the end padding in pixels 14575 * @param bottom the bottom padding in pixels 14576 */ 14577 public void setPaddingRelative(int start, int top, int end, int bottom) { 14578 // Reset padding resolution 14579 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 14580 14581 mUserPaddingStart = start; 14582 mUserPaddingEnd = end; 14583 14584 switch(getResolvedLayoutDirection()) { 14585 case LAYOUT_DIRECTION_RTL: 14586 mUserPaddingLeftInitial = end; 14587 mUserPaddingRightInitial = start; 14588 internalSetPadding(end, top, start, bottom); 14589 break; 14590 case LAYOUT_DIRECTION_LTR: 14591 default: 14592 mUserPaddingLeftInitial = start; 14593 mUserPaddingRightInitial = end; 14594 internalSetPadding(start, top, end, bottom); 14595 } 14596 } 14597 14598 /** 14599 * Returns the top padding of this view. 14600 * 14601 * @return the top padding in pixels 14602 */ 14603 public int getPaddingTop() { 14604 return mPaddingTop; 14605 } 14606 14607 /** 14608 * Returns the bottom padding of this view. If there are inset and enabled 14609 * scrollbars, this value may include the space required to display the 14610 * scrollbars as well. 14611 * 14612 * @return the bottom padding in pixels 14613 */ 14614 public int getPaddingBottom() { 14615 return mPaddingBottom; 14616 } 14617 14618 /** 14619 * Returns the left padding of this view. If there are inset and enabled 14620 * scrollbars, this value may include the space required to display the 14621 * scrollbars as well. 14622 * 14623 * @return the left padding in pixels 14624 */ 14625 public int getPaddingLeft() { 14626 if (!isPaddingResolved()) { 14627 resolvePadding(); 14628 } 14629 return mPaddingLeft; 14630 } 14631 14632 /** 14633 * Returns the start padding of this view depending on its resolved layout direction. 14634 * If there are inset and enabled scrollbars, this value may include the space 14635 * required to display the scrollbars as well. 14636 * 14637 * @return the start padding in pixels 14638 */ 14639 public int getPaddingStart() { 14640 if (!isPaddingResolved()) { 14641 resolvePadding(); 14642 } 14643 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 14644 mPaddingRight : mPaddingLeft; 14645 } 14646 14647 /** 14648 * Returns the right padding of this view. If there are inset and enabled 14649 * scrollbars, this value may include the space required to display the 14650 * scrollbars as well. 14651 * 14652 * @return the right padding in pixels 14653 */ 14654 public int getPaddingRight() { 14655 if (!isPaddingResolved()) { 14656 resolvePadding(); 14657 } 14658 return mPaddingRight; 14659 } 14660 14661 /** 14662 * Returns the end padding of this view depending on its resolved layout direction. 14663 * If there are inset and enabled scrollbars, this value may include the space 14664 * required to display the scrollbars as well. 14665 * 14666 * @return the end padding in pixels 14667 */ 14668 public int getPaddingEnd() { 14669 if (!isPaddingResolved()) { 14670 resolvePadding(); 14671 } 14672 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 14673 mPaddingLeft : mPaddingRight; 14674 } 14675 14676 /** 14677 * Return if the padding as been set thru relative values 14678 * {@link #setPaddingRelative(int, int, int, int)} or thru 14679 * @attr ref android.R.styleable#View_paddingStart or 14680 * @attr ref android.R.styleable#View_paddingEnd 14681 * 14682 * @return true if the padding is relative or false if it is not. 14683 */ 14684 public boolean isPaddingRelative() { 14685 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 14686 } 14687 14688 /** 14689 * @hide 14690 */ 14691 public Insets getOpticalInsets() { 14692 if (mLayoutInsets == null) { 14693 mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets(); 14694 } 14695 return mLayoutInsets; 14696 } 14697 14698 /** 14699 * @hide 14700 */ 14701 public void setLayoutInsets(Insets layoutInsets) { 14702 mLayoutInsets = layoutInsets; 14703 } 14704 14705 /** 14706 * Changes the selection state of this view. A view can be selected or not. 14707 * Note that selection is not the same as focus. Views are typically 14708 * selected in the context of an AdapterView like ListView or GridView; 14709 * the selected view is the view that is highlighted. 14710 * 14711 * @param selected true if the view must be selected, false otherwise 14712 */ 14713 public void setSelected(boolean selected) { 14714 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 14715 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 14716 if (!selected) resetPressedState(); 14717 invalidate(true); 14718 refreshDrawableState(); 14719 dispatchSetSelected(selected); 14720 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 14721 notifyAccessibilityStateChanged(); 14722 } 14723 } 14724 } 14725 14726 /** 14727 * Dispatch setSelected to all of this View's children. 14728 * 14729 * @see #setSelected(boolean) 14730 * 14731 * @param selected The new selected state 14732 */ 14733 protected void dispatchSetSelected(boolean selected) { 14734 } 14735 14736 /** 14737 * Indicates the selection state of this view. 14738 * 14739 * @return true if the view is selected, false otherwise 14740 */ 14741 @ViewDebug.ExportedProperty 14742 public boolean isSelected() { 14743 return (mPrivateFlags & PFLAG_SELECTED) != 0; 14744 } 14745 14746 /** 14747 * Changes the activated state of this view. A view can be activated or not. 14748 * Note that activation is not the same as selection. Selection is 14749 * a transient property, representing the view (hierarchy) the user is 14750 * currently interacting with. Activation is a longer-term state that the 14751 * user can move views in and out of. For example, in a list view with 14752 * single or multiple selection enabled, the views in the current selection 14753 * set are activated. (Um, yeah, we are deeply sorry about the terminology 14754 * here.) The activated state is propagated down to children of the view it 14755 * is set on. 14756 * 14757 * @param activated true if the view must be activated, false otherwise 14758 */ 14759 public void setActivated(boolean activated) { 14760 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 14761 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 14762 invalidate(true); 14763 refreshDrawableState(); 14764 dispatchSetActivated(activated); 14765 } 14766 } 14767 14768 /** 14769 * Dispatch setActivated to all of this View's children. 14770 * 14771 * @see #setActivated(boolean) 14772 * 14773 * @param activated The new activated state 14774 */ 14775 protected void dispatchSetActivated(boolean activated) { 14776 } 14777 14778 /** 14779 * Indicates the activation state of this view. 14780 * 14781 * @return true if the view is activated, false otherwise 14782 */ 14783 @ViewDebug.ExportedProperty 14784 public boolean isActivated() { 14785 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 14786 } 14787 14788 /** 14789 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 14790 * observer can be used to get notifications when global events, like 14791 * layout, happen. 14792 * 14793 * The returned ViewTreeObserver observer is not guaranteed to remain 14794 * valid for the lifetime of this View. If the caller of this method keeps 14795 * a long-lived reference to ViewTreeObserver, it should always check for 14796 * the return value of {@link ViewTreeObserver#isAlive()}. 14797 * 14798 * @return The ViewTreeObserver for this view's hierarchy. 14799 */ 14800 public ViewTreeObserver getViewTreeObserver() { 14801 if (mAttachInfo != null) { 14802 return mAttachInfo.mTreeObserver; 14803 } 14804 if (mFloatingTreeObserver == null) { 14805 mFloatingTreeObserver = new ViewTreeObserver(); 14806 } 14807 return mFloatingTreeObserver; 14808 } 14809 14810 /** 14811 * <p>Finds the topmost view in the current view hierarchy.</p> 14812 * 14813 * @return the topmost view containing this view 14814 */ 14815 public View getRootView() { 14816 if (mAttachInfo != null) { 14817 final View v = mAttachInfo.mRootView; 14818 if (v != null) { 14819 return v; 14820 } 14821 } 14822 14823 View parent = this; 14824 14825 while (parent.mParent != null && parent.mParent instanceof View) { 14826 parent = (View) parent.mParent; 14827 } 14828 14829 return parent; 14830 } 14831 14832 /** 14833 * <p>Computes the coordinates of this view on the screen. The argument 14834 * must be an array of two integers. After the method returns, the array 14835 * contains the x and y location in that order.</p> 14836 * 14837 * @param location an array of two integers in which to hold the coordinates 14838 */ 14839 public void getLocationOnScreen(int[] location) { 14840 getLocationInWindow(location); 14841 14842 final AttachInfo info = mAttachInfo; 14843 if (info != null) { 14844 location[0] += info.mWindowLeft; 14845 location[1] += info.mWindowTop; 14846 } 14847 } 14848 14849 /** 14850 * <p>Computes the coordinates of this view in its window. The argument 14851 * must be an array of two integers. After the method returns, the array 14852 * contains the x and y location in that order.</p> 14853 * 14854 * @param location an array of two integers in which to hold the coordinates 14855 */ 14856 public void getLocationInWindow(int[] location) { 14857 if (location == null || location.length < 2) { 14858 throw new IllegalArgumentException("location must be an array of two integers"); 14859 } 14860 14861 if (mAttachInfo == null) { 14862 // When the view is not attached to a window, this method does not make sense 14863 location[0] = location[1] = 0; 14864 return; 14865 } 14866 14867 float[] position = mAttachInfo.mTmpTransformLocation; 14868 position[0] = position[1] = 0.0f; 14869 14870 if (!hasIdentityMatrix()) { 14871 getMatrix().mapPoints(position); 14872 } 14873 14874 position[0] += mLeft; 14875 position[1] += mTop; 14876 14877 ViewParent viewParent = mParent; 14878 while (viewParent instanceof View) { 14879 final View view = (View) viewParent; 14880 14881 position[0] -= view.mScrollX; 14882 position[1] -= view.mScrollY; 14883 14884 if (!view.hasIdentityMatrix()) { 14885 view.getMatrix().mapPoints(position); 14886 } 14887 14888 position[0] += view.mLeft; 14889 position[1] += view.mTop; 14890 14891 viewParent = view.mParent; 14892 } 14893 14894 if (viewParent instanceof ViewRootImpl) { 14895 // *cough* 14896 final ViewRootImpl vr = (ViewRootImpl) viewParent; 14897 position[1] -= vr.mCurScrollY; 14898 } 14899 14900 location[0] = (int) (position[0] + 0.5f); 14901 location[1] = (int) (position[1] + 0.5f); 14902 } 14903 14904 /** 14905 * {@hide} 14906 * @param id the id of the view to be found 14907 * @return the view of the specified id, null if cannot be found 14908 */ 14909 protected View findViewTraversal(int id) { 14910 if (id == mID) { 14911 return this; 14912 } 14913 return null; 14914 } 14915 14916 /** 14917 * {@hide} 14918 * @param tag the tag of the view to be found 14919 * @return the view of specified tag, null if cannot be found 14920 */ 14921 protected View findViewWithTagTraversal(Object tag) { 14922 if (tag != null && tag.equals(mTag)) { 14923 return this; 14924 } 14925 return null; 14926 } 14927 14928 /** 14929 * {@hide} 14930 * @param predicate The predicate to evaluate. 14931 * @param childToSkip If not null, ignores this child during the recursive traversal. 14932 * @return The first view that matches the predicate or null. 14933 */ 14934 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 14935 if (predicate.apply(this)) { 14936 return this; 14937 } 14938 return null; 14939 } 14940 14941 /** 14942 * Look for a child view with the given id. If this view has the given 14943 * id, return this view. 14944 * 14945 * @param id The id to search for. 14946 * @return The view that has the given id in the hierarchy or null 14947 */ 14948 public final View findViewById(int id) { 14949 if (id < 0) { 14950 return null; 14951 } 14952 return findViewTraversal(id); 14953 } 14954 14955 /** 14956 * Finds a view by its unuque and stable accessibility id. 14957 * 14958 * @param accessibilityId The searched accessibility id. 14959 * @return The found view. 14960 */ 14961 final View findViewByAccessibilityId(int accessibilityId) { 14962 if (accessibilityId < 0) { 14963 return null; 14964 } 14965 return findViewByAccessibilityIdTraversal(accessibilityId); 14966 } 14967 14968 /** 14969 * Performs the traversal to find a view by its unuque and stable accessibility id. 14970 * 14971 * <strong>Note:</strong>This method does not stop at the root namespace 14972 * boundary since the user can touch the screen at an arbitrary location 14973 * potentially crossing the root namespace bounday which will send an 14974 * accessibility event to accessibility services and they should be able 14975 * to obtain the event source. Also accessibility ids are guaranteed to be 14976 * unique in the window. 14977 * 14978 * @param accessibilityId The accessibility id. 14979 * @return The found view. 14980 */ 14981 View findViewByAccessibilityIdTraversal(int accessibilityId) { 14982 if (getAccessibilityViewId() == accessibilityId) { 14983 return this; 14984 } 14985 return null; 14986 } 14987 14988 /** 14989 * Look for a child view with the given tag. If this view has the given 14990 * tag, return this view. 14991 * 14992 * @param tag The tag to search for, using "tag.equals(getTag())". 14993 * @return The View that has the given tag in the hierarchy or null 14994 */ 14995 public final View findViewWithTag(Object tag) { 14996 if (tag == null) { 14997 return null; 14998 } 14999 return findViewWithTagTraversal(tag); 15000 } 15001 15002 /** 15003 * {@hide} 15004 * Look for a child view that matches the specified predicate. 15005 * If this view matches the predicate, return this view. 15006 * 15007 * @param predicate The predicate to evaluate. 15008 * @return The first view that matches the predicate or null. 15009 */ 15010 public final View findViewByPredicate(Predicate<View> predicate) { 15011 return findViewByPredicateTraversal(predicate, null); 15012 } 15013 15014 /** 15015 * {@hide} 15016 * Look for a child view that matches the specified predicate, 15017 * starting with the specified view and its descendents and then 15018 * recusively searching the ancestors and siblings of that view 15019 * until this view is reached. 15020 * 15021 * This method is useful in cases where the predicate does not match 15022 * a single unique view (perhaps multiple views use the same id) 15023 * and we are trying to find the view that is "closest" in scope to the 15024 * starting view. 15025 * 15026 * @param start The view to start from. 15027 * @param predicate The predicate to evaluate. 15028 * @return The first view that matches the predicate or null. 15029 */ 15030 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 15031 View childToSkip = null; 15032 for (;;) { 15033 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 15034 if (view != null || start == this) { 15035 return view; 15036 } 15037 15038 ViewParent parent = start.getParent(); 15039 if (parent == null || !(parent instanceof View)) { 15040 return null; 15041 } 15042 15043 childToSkip = start; 15044 start = (View) parent; 15045 } 15046 } 15047 15048 /** 15049 * Sets the identifier for this view. The identifier does not have to be 15050 * unique in this view's hierarchy. The identifier should be a positive 15051 * number. 15052 * 15053 * @see #NO_ID 15054 * @see #getId() 15055 * @see #findViewById(int) 15056 * 15057 * @param id a number used to identify the view 15058 * 15059 * @attr ref android.R.styleable#View_id 15060 */ 15061 public void setId(int id) { 15062 mID = id; 15063 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 15064 mID = generateViewId(); 15065 } 15066 } 15067 15068 /** 15069 * {@hide} 15070 * 15071 * @param isRoot true if the view belongs to the root namespace, false 15072 * otherwise 15073 */ 15074 public void setIsRootNamespace(boolean isRoot) { 15075 if (isRoot) { 15076 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 15077 } else { 15078 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 15079 } 15080 } 15081 15082 /** 15083 * {@hide} 15084 * 15085 * @return true if the view belongs to the root namespace, false otherwise 15086 */ 15087 public boolean isRootNamespace() { 15088 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 15089 } 15090 15091 /** 15092 * Returns this view's identifier. 15093 * 15094 * @return a positive integer used to identify the view or {@link #NO_ID} 15095 * if the view has no ID 15096 * 15097 * @see #setId(int) 15098 * @see #findViewById(int) 15099 * @attr ref android.R.styleable#View_id 15100 */ 15101 @ViewDebug.CapturedViewProperty 15102 public int getId() { 15103 return mID; 15104 } 15105 15106 /** 15107 * Returns this view's tag. 15108 * 15109 * @return the Object stored in this view as a tag 15110 * 15111 * @see #setTag(Object) 15112 * @see #getTag(int) 15113 */ 15114 @ViewDebug.ExportedProperty 15115 public Object getTag() { 15116 return mTag; 15117 } 15118 15119 /** 15120 * Sets the tag associated with this view. A tag can be used to mark 15121 * a view in its hierarchy and does not have to be unique within the 15122 * hierarchy. Tags can also be used to store data within a view without 15123 * resorting to another data structure. 15124 * 15125 * @param tag an Object to tag the view with 15126 * 15127 * @see #getTag() 15128 * @see #setTag(int, Object) 15129 */ 15130 public void setTag(final Object tag) { 15131 mTag = tag; 15132 } 15133 15134 /** 15135 * Returns the tag associated with this view and the specified key. 15136 * 15137 * @param key The key identifying the tag 15138 * 15139 * @return the Object stored in this view as a tag 15140 * 15141 * @see #setTag(int, Object) 15142 * @see #getTag() 15143 */ 15144 public Object getTag(int key) { 15145 if (mKeyedTags != null) return mKeyedTags.get(key); 15146 return null; 15147 } 15148 15149 /** 15150 * Sets a tag associated with this view and a key. A tag can be used 15151 * to mark a view in its hierarchy and does not have to be unique within 15152 * the hierarchy. Tags can also be used to store data within a view 15153 * without resorting to another data structure. 15154 * 15155 * The specified key should be an id declared in the resources of the 15156 * application to ensure it is unique (see the <a 15157 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 15158 * Keys identified as belonging to 15159 * the Android framework or not associated with any package will cause 15160 * an {@link IllegalArgumentException} to be thrown. 15161 * 15162 * @param key The key identifying the tag 15163 * @param tag An Object to tag the view with 15164 * 15165 * @throws IllegalArgumentException If they specified key is not valid 15166 * 15167 * @see #setTag(Object) 15168 * @see #getTag(int) 15169 */ 15170 public void setTag(int key, final Object tag) { 15171 // If the package id is 0x00 or 0x01, it's either an undefined package 15172 // or a framework id 15173 if ((key >>> 24) < 2) { 15174 throw new IllegalArgumentException("The key must be an application-specific " 15175 + "resource id."); 15176 } 15177 15178 setKeyedTag(key, tag); 15179 } 15180 15181 /** 15182 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 15183 * framework id. 15184 * 15185 * @hide 15186 */ 15187 public void setTagInternal(int key, Object tag) { 15188 if ((key >>> 24) != 0x1) { 15189 throw new IllegalArgumentException("The key must be a framework-specific " 15190 + "resource id."); 15191 } 15192 15193 setKeyedTag(key, tag); 15194 } 15195 15196 private void setKeyedTag(int key, Object tag) { 15197 if (mKeyedTags == null) { 15198 mKeyedTags = new SparseArray<Object>(); 15199 } 15200 15201 mKeyedTags.put(key, tag); 15202 } 15203 15204 /** 15205 * Prints information about this view in the log output, with the tag 15206 * {@link #VIEW_LOG_TAG}. 15207 * 15208 * @hide 15209 */ 15210 public void debug() { 15211 debug(0); 15212 } 15213 15214 /** 15215 * Prints information about this view in the log output, with the tag 15216 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 15217 * indentation defined by the <code>depth</code>. 15218 * 15219 * @param depth the indentation level 15220 * 15221 * @hide 15222 */ 15223 protected void debug(int depth) { 15224 String output = debugIndent(depth - 1); 15225 15226 output += "+ " + this; 15227 int id = getId(); 15228 if (id != -1) { 15229 output += " (id=" + id + ")"; 15230 } 15231 Object tag = getTag(); 15232 if (tag != null) { 15233 output += " (tag=" + tag + ")"; 15234 } 15235 Log.d(VIEW_LOG_TAG, output); 15236 15237 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 15238 output = debugIndent(depth) + " FOCUSED"; 15239 Log.d(VIEW_LOG_TAG, output); 15240 } 15241 15242 output = debugIndent(depth); 15243 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 15244 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 15245 + "} "; 15246 Log.d(VIEW_LOG_TAG, output); 15247 15248 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 15249 || mPaddingBottom != 0) { 15250 output = debugIndent(depth); 15251 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 15252 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 15253 Log.d(VIEW_LOG_TAG, output); 15254 } 15255 15256 output = debugIndent(depth); 15257 output += "mMeasureWidth=" + mMeasuredWidth + 15258 " mMeasureHeight=" + mMeasuredHeight; 15259 Log.d(VIEW_LOG_TAG, output); 15260 15261 output = debugIndent(depth); 15262 if (mLayoutParams == null) { 15263 output += "BAD! no layout params"; 15264 } else { 15265 output = mLayoutParams.debug(output); 15266 } 15267 Log.d(VIEW_LOG_TAG, output); 15268 15269 output = debugIndent(depth); 15270 output += "flags={"; 15271 output += View.printFlags(mViewFlags); 15272 output += "}"; 15273 Log.d(VIEW_LOG_TAG, output); 15274 15275 output = debugIndent(depth); 15276 output += "privateFlags={"; 15277 output += View.printPrivateFlags(mPrivateFlags); 15278 output += "}"; 15279 Log.d(VIEW_LOG_TAG, output); 15280 } 15281 15282 /** 15283 * Creates a string of whitespaces used for indentation. 15284 * 15285 * @param depth the indentation level 15286 * @return a String containing (depth * 2 + 3) * 2 white spaces 15287 * 15288 * @hide 15289 */ 15290 protected static String debugIndent(int depth) { 15291 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 15292 for (int i = 0; i < (depth * 2) + 3; i++) { 15293 spaces.append(' ').append(' '); 15294 } 15295 return spaces.toString(); 15296 } 15297 15298 /** 15299 * <p>Return the offset of the widget's text baseline from the widget's top 15300 * boundary. If this widget does not support baseline alignment, this 15301 * method returns -1. </p> 15302 * 15303 * @return the offset of the baseline within the widget's bounds or -1 15304 * if baseline alignment is not supported 15305 */ 15306 @ViewDebug.ExportedProperty(category = "layout") 15307 public int getBaseline() { 15308 return -1; 15309 } 15310 15311 /** 15312 * Returns whether the view hierarchy is currently undergoing a layout pass. This 15313 * information is useful to avoid situations such as calling {@link #requestLayout()} during 15314 * a layout pass. 15315 * 15316 * @return whether the view hierarchy is currently undergoing a layout pass 15317 */ 15318 public boolean isInLayout() { 15319 ViewRootImpl viewRoot = getViewRootImpl(); 15320 return (viewRoot != null && viewRoot.isInLayout()); 15321 } 15322 15323 /** 15324 * Call this when something has changed which has invalidated the 15325 * layout of this view. This will schedule a layout pass of the view 15326 * tree. This should not be called while the view hierarchy is currently in a layout 15327 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 15328 * end of the current layout pass (and then layout will run again) or after the current 15329 * frame is drawn and the next layout occurs. 15330 * 15331 * <p>Subclasses which override this method should call the superclass method to 15332 * handle possible request-during-layout errors correctly.</p> 15333 */ 15334 public void requestLayout() { 15335 ViewRootImpl viewRoot = getViewRootImpl(); 15336 if (viewRoot != null && viewRoot.isInLayout()) { 15337 viewRoot.requestLayoutDuringLayout(this); 15338 return; 15339 } 15340 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 15341 mPrivateFlags |= PFLAG_INVALIDATED; 15342 15343 if (mParent != null && !mParent.isLayoutRequested()) { 15344 mParent.requestLayout(); 15345 } 15346 } 15347 15348 /** 15349 * Forces this view to be laid out during the next layout pass. 15350 * This method does not call requestLayout() or forceLayout() 15351 * on the parent. 15352 */ 15353 public void forceLayout() { 15354 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 15355 mPrivateFlags |= PFLAG_INVALIDATED; 15356 } 15357 15358 /** 15359 * <p> 15360 * This is called to find out how big a view should be. The parent 15361 * supplies constraint information in the width and height parameters. 15362 * </p> 15363 * 15364 * <p> 15365 * The actual measurement work of a view is performed in 15366 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 15367 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 15368 * </p> 15369 * 15370 * 15371 * @param widthMeasureSpec Horizontal space requirements as imposed by the 15372 * parent 15373 * @param heightMeasureSpec Vertical space requirements as imposed by the 15374 * parent 15375 * 15376 * @see #onMeasure(int, int) 15377 */ 15378 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 15379 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 15380 widthMeasureSpec != mOldWidthMeasureSpec || 15381 heightMeasureSpec != mOldHeightMeasureSpec) { 15382 15383 // first clears the measured dimension flag 15384 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 15385 15386 if (!isPaddingResolved()) { 15387 resolvePadding(); 15388 } 15389 15390 // measure ourselves, this should set the measured dimension flag back 15391 onMeasure(widthMeasureSpec, heightMeasureSpec); 15392 15393 // flag not set, setMeasuredDimension() was not invoked, we raise 15394 // an exception to warn the developer 15395 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 15396 throw new IllegalStateException("onMeasure() did not set the" 15397 + " measured dimension by calling" 15398 + " setMeasuredDimension()"); 15399 } 15400 15401 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 15402 } 15403 15404 mOldWidthMeasureSpec = widthMeasureSpec; 15405 mOldHeightMeasureSpec = heightMeasureSpec; 15406 } 15407 15408 /** 15409 * <p> 15410 * Measure the view and its content to determine the measured width and the 15411 * measured height. This method is invoked by {@link #measure(int, int)} and 15412 * should be overriden by subclasses to provide accurate and efficient 15413 * measurement of their contents. 15414 * </p> 15415 * 15416 * <p> 15417 * <strong>CONTRACT:</strong> When overriding this method, you 15418 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 15419 * measured width and height of this view. Failure to do so will trigger an 15420 * <code>IllegalStateException</code>, thrown by 15421 * {@link #measure(int, int)}. Calling the superclass' 15422 * {@link #onMeasure(int, int)} is a valid use. 15423 * </p> 15424 * 15425 * <p> 15426 * The base class implementation of measure defaults to the background size, 15427 * unless a larger size is allowed by the MeasureSpec. Subclasses should 15428 * override {@link #onMeasure(int, int)} to provide better measurements of 15429 * their content. 15430 * </p> 15431 * 15432 * <p> 15433 * If this method is overridden, it is the subclass's responsibility to make 15434 * sure the measured height and width are at least the view's minimum height 15435 * and width ({@link #getSuggestedMinimumHeight()} and 15436 * {@link #getSuggestedMinimumWidth()}). 15437 * </p> 15438 * 15439 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 15440 * The requirements are encoded with 15441 * {@link android.view.View.MeasureSpec}. 15442 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 15443 * The requirements are encoded with 15444 * {@link android.view.View.MeasureSpec}. 15445 * 15446 * @see #getMeasuredWidth() 15447 * @see #getMeasuredHeight() 15448 * @see #setMeasuredDimension(int, int) 15449 * @see #getSuggestedMinimumHeight() 15450 * @see #getSuggestedMinimumWidth() 15451 * @see android.view.View.MeasureSpec#getMode(int) 15452 * @see android.view.View.MeasureSpec#getSize(int) 15453 */ 15454 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 15455 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 15456 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 15457 } 15458 15459 /** 15460 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 15461 * measured width and measured height. Failing to do so will trigger an 15462 * exception at measurement time.</p> 15463 * 15464 * @param measuredWidth The measured width of this view. May be a complex 15465 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 15466 * {@link #MEASURED_STATE_TOO_SMALL}. 15467 * @param measuredHeight The measured height of this view. May be a complex 15468 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 15469 * {@link #MEASURED_STATE_TOO_SMALL}. 15470 */ 15471 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 15472 mMeasuredWidth = measuredWidth; 15473 mMeasuredHeight = measuredHeight; 15474 15475 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 15476 } 15477 15478 /** 15479 * Merge two states as returned by {@link #getMeasuredState()}. 15480 * @param curState The current state as returned from a view or the result 15481 * of combining multiple views. 15482 * @param newState The new view state to combine. 15483 * @return Returns a new integer reflecting the combination of the two 15484 * states. 15485 */ 15486 public static int combineMeasuredStates(int curState, int newState) { 15487 return curState | newState; 15488 } 15489 15490 /** 15491 * Version of {@link #resolveSizeAndState(int, int, int)} 15492 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 15493 */ 15494 public static int resolveSize(int size, int measureSpec) { 15495 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 15496 } 15497 15498 /** 15499 * Utility to reconcile a desired size and state, with constraints imposed 15500 * by a MeasureSpec. Will take the desired size, unless a different size 15501 * is imposed by the constraints. The returned value is a compound integer, 15502 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 15503 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 15504 * size is smaller than the size the view wants to be. 15505 * 15506 * @param size How big the view wants to be 15507 * @param measureSpec Constraints imposed by the parent 15508 * @return Size information bit mask as defined by 15509 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 15510 */ 15511 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 15512 int result = size; 15513 int specMode = MeasureSpec.getMode(measureSpec); 15514 int specSize = MeasureSpec.getSize(measureSpec); 15515 switch (specMode) { 15516 case MeasureSpec.UNSPECIFIED: 15517 result = size; 15518 break; 15519 case MeasureSpec.AT_MOST: 15520 if (specSize < size) { 15521 result = specSize | MEASURED_STATE_TOO_SMALL; 15522 } else { 15523 result = size; 15524 } 15525 break; 15526 case MeasureSpec.EXACTLY: 15527 result = specSize; 15528 break; 15529 } 15530 return result | (childMeasuredState&MEASURED_STATE_MASK); 15531 } 15532 15533 /** 15534 * Utility to return a default size. Uses the supplied size if the 15535 * MeasureSpec imposed no constraints. Will get larger if allowed 15536 * by the MeasureSpec. 15537 * 15538 * @param size Default size for this view 15539 * @param measureSpec Constraints imposed by the parent 15540 * @return The size this view should be. 15541 */ 15542 public static int getDefaultSize(int size, int measureSpec) { 15543 int result = size; 15544 int specMode = MeasureSpec.getMode(measureSpec); 15545 int specSize = MeasureSpec.getSize(measureSpec); 15546 15547 switch (specMode) { 15548 case MeasureSpec.UNSPECIFIED: 15549 result = size; 15550 break; 15551 case MeasureSpec.AT_MOST: 15552 case MeasureSpec.EXACTLY: 15553 result = specSize; 15554 break; 15555 } 15556 return result; 15557 } 15558 15559 /** 15560 * Returns the suggested minimum height that the view should use. This 15561 * returns the maximum of the view's minimum height 15562 * and the background's minimum height 15563 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 15564 * <p> 15565 * When being used in {@link #onMeasure(int, int)}, the caller should still 15566 * ensure the returned height is within the requirements of the parent. 15567 * 15568 * @return The suggested minimum height of the view. 15569 */ 15570 protected int getSuggestedMinimumHeight() { 15571 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 15572 15573 } 15574 15575 /** 15576 * Returns the suggested minimum width that the view should use. This 15577 * returns the maximum of the view's minimum width) 15578 * and the background's minimum width 15579 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 15580 * <p> 15581 * When being used in {@link #onMeasure(int, int)}, the caller should still 15582 * ensure the returned width is within the requirements of the parent. 15583 * 15584 * @return The suggested minimum width of the view. 15585 */ 15586 protected int getSuggestedMinimumWidth() { 15587 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 15588 } 15589 15590 /** 15591 * Returns the minimum height of the view. 15592 * 15593 * @return the minimum height the view will try to be. 15594 * 15595 * @see #setMinimumHeight(int) 15596 * 15597 * @attr ref android.R.styleable#View_minHeight 15598 */ 15599 public int getMinimumHeight() { 15600 return mMinHeight; 15601 } 15602 15603 /** 15604 * Sets the minimum height of the view. It is not guaranteed the view will 15605 * be able to achieve this minimum height (for example, if its parent layout 15606 * constrains it with less available height). 15607 * 15608 * @param minHeight The minimum height the view will try to be. 15609 * 15610 * @see #getMinimumHeight() 15611 * 15612 * @attr ref android.R.styleable#View_minHeight 15613 */ 15614 public void setMinimumHeight(int minHeight) { 15615 mMinHeight = minHeight; 15616 requestLayout(); 15617 } 15618 15619 /** 15620 * Returns the minimum width of the view. 15621 * 15622 * @return the minimum width the view will try to be. 15623 * 15624 * @see #setMinimumWidth(int) 15625 * 15626 * @attr ref android.R.styleable#View_minWidth 15627 */ 15628 public int getMinimumWidth() { 15629 return mMinWidth; 15630 } 15631 15632 /** 15633 * Sets the minimum width of the view. It is not guaranteed the view will 15634 * be able to achieve this minimum width (for example, if its parent layout 15635 * constrains it with less available width). 15636 * 15637 * @param minWidth The minimum width the view will try to be. 15638 * 15639 * @see #getMinimumWidth() 15640 * 15641 * @attr ref android.R.styleable#View_minWidth 15642 */ 15643 public void setMinimumWidth(int minWidth) { 15644 mMinWidth = minWidth; 15645 requestLayout(); 15646 15647 } 15648 15649 /** 15650 * Get the animation currently associated with this view. 15651 * 15652 * @return The animation that is currently playing or 15653 * scheduled to play for this view. 15654 */ 15655 public Animation getAnimation() { 15656 return mCurrentAnimation; 15657 } 15658 15659 /** 15660 * Start the specified animation now. 15661 * 15662 * @param animation the animation to start now 15663 */ 15664 public void startAnimation(Animation animation) { 15665 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 15666 setAnimation(animation); 15667 invalidateParentCaches(); 15668 invalidate(true); 15669 } 15670 15671 /** 15672 * Cancels any animations for this view. 15673 */ 15674 public void clearAnimation() { 15675 if (mCurrentAnimation != null) { 15676 mCurrentAnimation.detach(); 15677 } 15678 mCurrentAnimation = null; 15679 invalidateParentIfNeeded(); 15680 } 15681 15682 /** 15683 * Sets the next animation to play for this view. 15684 * If you want the animation to play immediately, use 15685 * {@link #startAnimation(android.view.animation.Animation)} instead. 15686 * This method provides allows fine-grained 15687 * control over the start time and invalidation, but you 15688 * must make sure that 1) the animation has a start time set, and 15689 * 2) the view's parent (which controls animations on its children) 15690 * will be invalidated when the animation is supposed to 15691 * start. 15692 * 15693 * @param animation The next animation, or null. 15694 */ 15695 public void setAnimation(Animation animation) { 15696 mCurrentAnimation = animation; 15697 15698 if (animation != null) { 15699 // If the screen is off assume the animation start time is now instead of 15700 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 15701 // would cause the animation to start when the screen turns back on 15702 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 15703 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 15704 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 15705 } 15706 animation.reset(); 15707 } 15708 } 15709 15710 /** 15711 * Invoked by a parent ViewGroup to notify the start of the animation 15712 * currently associated with this view. If you override this method, 15713 * always call super.onAnimationStart(); 15714 * 15715 * @see #setAnimation(android.view.animation.Animation) 15716 * @see #getAnimation() 15717 */ 15718 protected void onAnimationStart() { 15719 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 15720 } 15721 15722 /** 15723 * Invoked by a parent ViewGroup to notify the end of the animation 15724 * currently associated with this view. If you override this method, 15725 * always call super.onAnimationEnd(); 15726 * 15727 * @see #setAnimation(android.view.animation.Animation) 15728 * @see #getAnimation() 15729 */ 15730 protected void onAnimationEnd() { 15731 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 15732 } 15733 15734 /** 15735 * Invoked if there is a Transform that involves alpha. Subclass that can 15736 * draw themselves with the specified alpha should return true, and then 15737 * respect that alpha when their onDraw() is called. If this returns false 15738 * then the view may be redirected to draw into an offscreen buffer to 15739 * fulfill the request, which will look fine, but may be slower than if the 15740 * subclass handles it internally. The default implementation returns false. 15741 * 15742 * @param alpha The alpha (0..255) to apply to the view's drawing 15743 * @return true if the view can draw with the specified alpha. 15744 */ 15745 protected boolean onSetAlpha(int alpha) { 15746 return false; 15747 } 15748 15749 /** 15750 * This is used by the RootView to perform an optimization when 15751 * the view hierarchy contains one or several SurfaceView. 15752 * SurfaceView is always considered transparent, but its children are not, 15753 * therefore all View objects remove themselves from the global transparent 15754 * region (passed as a parameter to this function). 15755 * 15756 * @param region The transparent region for this ViewAncestor (window). 15757 * 15758 * @return Returns true if the effective visibility of the view at this 15759 * point is opaque, regardless of the transparent region; returns false 15760 * if it is possible for underlying windows to be seen behind the view. 15761 * 15762 * {@hide} 15763 */ 15764 public boolean gatherTransparentRegion(Region region) { 15765 final AttachInfo attachInfo = mAttachInfo; 15766 if (region != null && attachInfo != null) { 15767 final int pflags = mPrivateFlags; 15768 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 15769 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 15770 // remove it from the transparent region. 15771 final int[] location = attachInfo.mTransparentLocation; 15772 getLocationInWindow(location); 15773 region.op(location[0], location[1], location[0] + mRight - mLeft, 15774 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 15775 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 15776 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 15777 // exists, so we remove the background drawable's non-transparent 15778 // parts from this transparent region. 15779 applyDrawableToTransparentRegion(mBackground, region); 15780 } 15781 } 15782 return true; 15783 } 15784 15785 /** 15786 * Play a sound effect for this view. 15787 * 15788 * <p>The framework will play sound effects for some built in actions, such as 15789 * clicking, but you may wish to play these effects in your widget, 15790 * for instance, for internal navigation. 15791 * 15792 * <p>The sound effect will only be played if sound effects are enabled by the user, and 15793 * {@link #isSoundEffectsEnabled()} is true. 15794 * 15795 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 15796 */ 15797 public void playSoundEffect(int soundConstant) { 15798 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 15799 return; 15800 } 15801 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 15802 } 15803 15804 /** 15805 * BZZZTT!!1! 15806 * 15807 * <p>Provide haptic feedback to the user for this view. 15808 * 15809 * <p>The framework will provide haptic feedback for some built in actions, 15810 * such as long presses, but you may wish to provide feedback for your 15811 * own widget. 15812 * 15813 * <p>The feedback will only be performed if 15814 * {@link #isHapticFeedbackEnabled()} is true. 15815 * 15816 * @param feedbackConstant One of the constants defined in 15817 * {@link HapticFeedbackConstants} 15818 */ 15819 public boolean performHapticFeedback(int feedbackConstant) { 15820 return performHapticFeedback(feedbackConstant, 0); 15821 } 15822 15823 /** 15824 * BZZZTT!!1! 15825 * 15826 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 15827 * 15828 * @param feedbackConstant One of the constants defined in 15829 * {@link HapticFeedbackConstants} 15830 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 15831 */ 15832 public boolean performHapticFeedback(int feedbackConstant, int flags) { 15833 if (mAttachInfo == null) { 15834 return false; 15835 } 15836 //noinspection SimplifiableIfStatement 15837 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 15838 && !isHapticFeedbackEnabled()) { 15839 return false; 15840 } 15841 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 15842 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 15843 } 15844 15845 /** 15846 * Request that the visibility of the status bar or other screen/window 15847 * decorations be changed. 15848 * 15849 * <p>This method is used to put the over device UI into temporary modes 15850 * where the user's attention is focused more on the application content, 15851 * by dimming or hiding surrounding system affordances. This is typically 15852 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 15853 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 15854 * to be placed behind the action bar (and with these flags other system 15855 * affordances) so that smooth transitions between hiding and showing them 15856 * can be done. 15857 * 15858 * <p>Two representative examples of the use of system UI visibility is 15859 * implementing a content browsing application (like a magazine reader) 15860 * and a video playing application. 15861 * 15862 * <p>The first code shows a typical implementation of a View in a content 15863 * browsing application. In this implementation, the application goes 15864 * into a content-oriented mode by hiding the status bar and action bar, 15865 * and putting the navigation elements into lights out mode. The user can 15866 * then interact with content while in this mode. Such an application should 15867 * provide an easy way for the user to toggle out of the mode (such as to 15868 * check information in the status bar or access notifications). In the 15869 * implementation here, this is done simply by tapping on the content. 15870 * 15871 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 15872 * content} 15873 * 15874 * <p>This second code sample shows a typical implementation of a View 15875 * in a video playing application. In this situation, while the video is 15876 * playing the application would like to go into a complete full-screen mode, 15877 * to use as much of the display as possible for the video. When in this state 15878 * the user can not interact with the application; the system intercepts 15879 * touching on the screen to pop the UI out of full screen mode. See 15880 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 15881 * 15882 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 15883 * content} 15884 * 15885 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 15886 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 15887 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 15888 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 15889 */ 15890 public void setSystemUiVisibility(int visibility) { 15891 if (visibility != mSystemUiVisibility) { 15892 mSystemUiVisibility = visibility; 15893 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 15894 mParent.recomputeViewAttributes(this); 15895 } 15896 } 15897 } 15898 15899 /** 15900 * Returns the last {@link #setSystemUiVisibility(int) that this view has requested. 15901 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 15902 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 15903 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 15904 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 15905 */ 15906 public int getSystemUiVisibility() { 15907 return mSystemUiVisibility; 15908 } 15909 15910 /** 15911 * Returns the current system UI visibility that is currently set for 15912 * the entire window. This is the combination of the 15913 * {@link #setSystemUiVisibility(int)} values supplied by all of the 15914 * views in the window. 15915 */ 15916 public int getWindowSystemUiVisibility() { 15917 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 15918 } 15919 15920 /** 15921 * Override to find out when the window's requested system UI visibility 15922 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 15923 * This is different from the callbacks recieved through 15924 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 15925 * in that this is only telling you about the local request of the window, 15926 * not the actual values applied by the system. 15927 */ 15928 public void onWindowSystemUiVisibilityChanged(int visible) { 15929 } 15930 15931 /** 15932 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 15933 * the view hierarchy. 15934 */ 15935 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 15936 onWindowSystemUiVisibilityChanged(visible); 15937 } 15938 15939 /** 15940 * Set a listener to receive callbacks when the visibility of the system bar changes. 15941 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 15942 */ 15943 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 15944 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 15945 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 15946 mParent.recomputeViewAttributes(this); 15947 } 15948 } 15949 15950 /** 15951 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 15952 * the view hierarchy. 15953 */ 15954 public void dispatchSystemUiVisibilityChanged(int visibility) { 15955 ListenerInfo li = mListenerInfo; 15956 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 15957 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 15958 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 15959 } 15960 } 15961 15962 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 15963 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 15964 if (val != mSystemUiVisibility) { 15965 setSystemUiVisibility(val); 15966 return true; 15967 } 15968 return false; 15969 } 15970 15971 /** @hide */ 15972 public void setDisabledSystemUiVisibility(int flags) { 15973 if (mAttachInfo != null) { 15974 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 15975 mAttachInfo.mDisabledSystemUiVisibility = flags; 15976 if (mParent != null) { 15977 mParent.recomputeViewAttributes(this); 15978 } 15979 } 15980 } 15981 } 15982 15983 /** 15984 * Creates an image that the system displays during the drag and drop 15985 * operation. This is called a "drag shadow". The default implementation 15986 * for a DragShadowBuilder based on a View returns an image that has exactly the same 15987 * appearance as the given View. The default also positions the center of the drag shadow 15988 * directly under the touch point. If no View is provided (the constructor with no parameters 15989 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 15990 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 15991 * default is an invisible drag shadow. 15992 * <p> 15993 * You are not required to use the View you provide to the constructor as the basis of the 15994 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 15995 * anything you want as the drag shadow. 15996 * </p> 15997 * <p> 15998 * You pass a DragShadowBuilder object to the system when you start the drag. The system 15999 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 16000 * size and position of the drag shadow. It uses this data to construct a 16001 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 16002 * so that your application can draw the shadow image in the Canvas. 16003 * </p> 16004 * 16005 * <div class="special reference"> 16006 * <h3>Developer Guides</h3> 16007 * <p>For a guide to implementing drag and drop features, read the 16008 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 16009 * </div> 16010 */ 16011 public static class DragShadowBuilder { 16012 private final WeakReference<View> mView; 16013 16014 /** 16015 * Constructs a shadow image builder based on a View. By default, the resulting drag 16016 * shadow will have the same appearance and dimensions as the View, with the touch point 16017 * over the center of the View. 16018 * @param view A View. Any View in scope can be used. 16019 */ 16020 public DragShadowBuilder(View view) { 16021 mView = new WeakReference<View>(view); 16022 } 16023 16024 /** 16025 * Construct a shadow builder object with no associated View. This 16026 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 16027 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 16028 * to supply the drag shadow's dimensions and appearance without 16029 * reference to any View object. If they are not overridden, then the result is an 16030 * invisible drag shadow. 16031 */ 16032 public DragShadowBuilder() { 16033 mView = new WeakReference<View>(null); 16034 } 16035 16036 /** 16037 * Returns the View object that had been passed to the 16038 * {@link #View.DragShadowBuilder(View)} 16039 * constructor. If that View parameter was {@code null} or if the 16040 * {@link #View.DragShadowBuilder()} 16041 * constructor was used to instantiate the builder object, this method will return 16042 * null. 16043 * 16044 * @return The View object associate with this builder object. 16045 */ 16046 @SuppressWarnings({"JavadocReference"}) 16047 final public View getView() { 16048 return mView.get(); 16049 } 16050 16051 /** 16052 * Provides the metrics for the shadow image. These include the dimensions of 16053 * the shadow image, and the point within that shadow that should 16054 * be centered under the touch location while dragging. 16055 * <p> 16056 * The default implementation sets the dimensions of the shadow to be the 16057 * same as the dimensions of the View itself and centers the shadow under 16058 * the touch point. 16059 * </p> 16060 * 16061 * @param shadowSize A {@link android.graphics.Point} containing the width and height 16062 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 16063 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 16064 * image. 16065 * 16066 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 16067 * shadow image that should be underneath the touch point during the drag and drop 16068 * operation. Your application must set {@link android.graphics.Point#x} to the 16069 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 16070 */ 16071 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 16072 final View view = mView.get(); 16073 if (view != null) { 16074 shadowSize.set(view.getWidth(), view.getHeight()); 16075 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 16076 } else { 16077 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 16078 } 16079 } 16080 16081 /** 16082 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 16083 * based on the dimensions it received from the 16084 * {@link #onProvideShadowMetrics(Point, Point)} callback. 16085 * 16086 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 16087 */ 16088 public void onDrawShadow(Canvas canvas) { 16089 final View view = mView.get(); 16090 if (view != null) { 16091 view.draw(canvas); 16092 } else { 16093 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 16094 } 16095 } 16096 } 16097 16098 /** 16099 * Starts a drag and drop operation. When your application calls this method, it passes a 16100 * {@link android.view.View.DragShadowBuilder} object to the system. The 16101 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 16102 * to get metrics for the drag shadow, and then calls the object's 16103 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 16104 * <p> 16105 * Once the system has the drag shadow, it begins the drag and drop operation by sending 16106 * drag events to all the View objects in your application that are currently visible. It does 16107 * this either by calling the View object's drag listener (an implementation of 16108 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 16109 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 16110 * Both are passed a {@link android.view.DragEvent} object that has a 16111 * {@link android.view.DragEvent#getAction()} value of 16112 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 16113 * </p> 16114 * <p> 16115 * Your application can invoke startDrag() on any attached View object. The View object does not 16116 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 16117 * be related to the View the user selected for dragging. 16118 * </p> 16119 * @param data A {@link android.content.ClipData} object pointing to the data to be 16120 * transferred by the drag and drop operation. 16121 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 16122 * drag shadow. 16123 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 16124 * drop operation. This Object is put into every DragEvent object sent by the system during the 16125 * current drag. 16126 * <p> 16127 * myLocalState is a lightweight mechanism for the sending information from the dragged View 16128 * to the target Views. For example, it can contain flags that differentiate between a 16129 * a copy operation and a move operation. 16130 * </p> 16131 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 16132 * so the parameter should be set to 0. 16133 * @return {@code true} if the method completes successfully, or 16134 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 16135 * do a drag, and so no drag operation is in progress. 16136 */ 16137 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 16138 Object myLocalState, int flags) { 16139 if (ViewDebug.DEBUG_DRAG) { 16140 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 16141 } 16142 boolean okay = false; 16143 16144 Point shadowSize = new Point(); 16145 Point shadowTouchPoint = new Point(); 16146 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 16147 16148 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 16149 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 16150 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 16151 } 16152 16153 if (ViewDebug.DEBUG_DRAG) { 16154 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 16155 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 16156 } 16157 Surface surface = new Surface(); 16158 try { 16159 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 16160 flags, shadowSize.x, shadowSize.y, surface); 16161 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 16162 + " surface=" + surface); 16163 if (token != null) { 16164 Canvas canvas = surface.lockCanvas(null); 16165 try { 16166 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 16167 shadowBuilder.onDrawShadow(canvas); 16168 } finally { 16169 surface.unlockCanvasAndPost(canvas); 16170 } 16171 16172 final ViewRootImpl root = getViewRootImpl(); 16173 16174 // Cache the local state object for delivery with DragEvents 16175 root.setLocalDragState(myLocalState); 16176 16177 // repurpose 'shadowSize' for the last touch point 16178 root.getLastTouchPoint(shadowSize); 16179 16180 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 16181 shadowSize.x, shadowSize.y, 16182 shadowTouchPoint.x, shadowTouchPoint.y, data); 16183 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 16184 16185 // Off and running! Release our local surface instance; the drag 16186 // shadow surface is now managed by the system process. 16187 surface.release(); 16188 } 16189 } catch (Exception e) { 16190 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 16191 surface.destroy(); 16192 } 16193 16194 return okay; 16195 } 16196 16197 /** 16198 * Handles drag events sent by the system following a call to 16199 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 16200 *<p> 16201 * When the system calls this method, it passes a 16202 * {@link android.view.DragEvent} object. A call to 16203 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 16204 * in DragEvent. The method uses these to determine what is happening in the drag and drop 16205 * operation. 16206 * @param event The {@link android.view.DragEvent} sent by the system. 16207 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 16208 * in DragEvent, indicating the type of drag event represented by this object. 16209 * @return {@code true} if the method was successful, otherwise {@code false}. 16210 * <p> 16211 * The method should return {@code true} in response to an action type of 16212 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 16213 * operation. 16214 * </p> 16215 * <p> 16216 * The method should also return {@code true} in response to an action type of 16217 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 16218 * {@code false} if it didn't. 16219 * </p> 16220 */ 16221 public boolean onDragEvent(DragEvent event) { 16222 return false; 16223 } 16224 16225 /** 16226 * Detects if this View is enabled and has a drag event listener. 16227 * If both are true, then it calls the drag event listener with the 16228 * {@link android.view.DragEvent} it received. If the drag event listener returns 16229 * {@code true}, then dispatchDragEvent() returns {@code true}. 16230 * <p> 16231 * For all other cases, the method calls the 16232 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 16233 * method and returns its result. 16234 * </p> 16235 * <p> 16236 * This ensures that a drag event is always consumed, even if the View does not have a drag 16237 * event listener. However, if the View has a listener and the listener returns true, then 16238 * onDragEvent() is not called. 16239 * </p> 16240 */ 16241 public boolean dispatchDragEvent(DragEvent event) { 16242 //noinspection SimplifiableIfStatement 16243 ListenerInfo li = mListenerInfo; 16244 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 16245 && li.mOnDragListener.onDrag(this, event)) { 16246 return true; 16247 } 16248 return onDragEvent(event); 16249 } 16250 16251 boolean canAcceptDrag() { 16252 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 16253 } 16254 16255 /** 16256 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 16257 * it is ever exposed at all. 16258 * @hide 16259 */ 16260 public void onCloseSystemDialogs(String reason) { 16261 } 16262 16263 /** 16264 * Given a Drawable whose bounds have been set to draw into this view, 16265 * update a Region being computed for 16266 * {@link #gatherTransparentRegion(android.graphics.Region)} so 16267 * that any non-transparent parts of the Drawable are removed from the 16268 * given transparent region. 16269 * 16270 * @param dr The Drawable whose transparency is to be applied to the region. 16271 * @param region A Region holding the current transparency information, 16272 * where any parts of the region that are set are considered to be 16273 * transparent. On return, this region will be modified to have the 16274 * transparency information reduced by the corresponding parts of the 16275 * Drawable that are not transparent. 16276 * {@hide} 16277 */ 16278 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 16279 if (DBG) { 16280 Log.i("View", "Getting transparent region for: " + this); 16281 } 16282 final Region r = dr.getTransparentRegion(); 16283 final Rect db = dr.getBounds(); 16284 final AttachInfo attachInfo = mAttachInfo; 16285 if (r != null && attachInfo != null) { 16286 final int w = getRight()-getLeft(); 16287 final int h = getBottom()-getTop(); 16288 if (db.left > 0) { 16289 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 16290 r.op(0, 0, db.left, h, Region.Op.UNION); 16291 } 16292 if (db.right < w) { 16293 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 16294 r.op(db.right, 0, w, h, Region.Op.UNION); 16295 } 16296 if (db.top > 0) { 16297 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 16298 r.op(0, 0, w, db.top, Region.Op.UNION); 16299 } 16300 if (db.bottom < h) { 16301 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 16302 r.op(0, db.bottom, w, h, Region.Op.UNION); 16303 } 16304 final int[] location = attachInfo.mTransparentLocation; 16305 getLocationInWindow(location); 16306 r.translate(location[0], location[1]); 16307 region.op(r, Region.Op.INTERSECT); 16308 } else { 16309 region.op(db, Region.Op.DIFFERENCE); 16310 } 16311 } 16312 16313 private void checkForLongClick(int delayOffset) { 16314 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 16315 mHasPerformedLongPress = false; 16316 16317 if (mPendingCheckForLongPress == null) { 16318 mPendingCheckForLongPress = new CheckForLongPress(); 16319 } 16320 mPendingCheckForLongPress.rememberWindowAttachCount(); 16321 postDelayed(mPendingCheckForLongPress, 16322 ViewConfiguration.getLongPressTimeout() - delayOffset); 16323 } 16324 } 16325 16326 /** 16327 * Inflate a view from an XML resource. This convenience method wraps the {@link 16328 * LayoutInflater} class, which provides a full range of options for view inflation. 16329 * 16330 * @param context The Context object for your activity or application. 16331 * @param resource The resource ID to inflate 16332 * @param root A view group that will be the parent. Used to properly inflate the 16333 * layout_* parameters. 16334 * @see LayoutInflater 16335 */ 16336 public static View inflate(Context context, int resource, ViewGroup root) { 16337 LayoutInflater factory = LayoutInflater.from(context); 16338 return factory.inflate(resource, root); 16339 } 16340 16341 /** 16342 * Scroll the view with standard behavior for scrolling beyond the normal 16343 * content boundaries. Views that call this method should override 16344 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 16345 * results of an over-scroll operation. 16346 * 16347 * Views can use this method to handle any touch or fling-based scrolling. 16348 * 16349 * @param deltaX Change in X in pixels 16350 * @param deltaY Change in Y in pixels 16351 * @param scrollX Current X scroll value in pixels before applying deltaX 16352 * @param scrollY Current Y scroll value in pixels before applying deltaY 16353 * @param scrollRangeX Maximum content scroll range along the X axis 16354 * @param scrollRangeY Maximum content scroll range along the Y axis 16355 * @param maxOverScrollX Number of pixels to overscroll by in either direction 16356 * along the X axis. 16357 * @param maxOverScrollY Number of pixels to overscroll by in either direction 16358 * along the Y axis. 16359 * @param isTouchEvent true if this scroll operation is the result of a touch event. 16360 * @return true if scrolling was clamped to an over-scroll boundary along either 16361 * axis, false otherwise. 16362 */ 16363 @SuppressWarnings({"UnusedParameters"}) 16364 protected boolean overScrollBy(int deltaX, int deltaY, 16365 int scrollX, int scrollY, 16366 int scrollRangeX, int scrollRangeY, 16367 int maxOverScrollX, int maxOverScrollY, 16368 boolean isTouchEvent) { 16369 final int overScrollMode = mOverScrollMode; 16370 final boolean canScrollHorizontal = 16371 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 16372 final boolean canScrollVertical = 16373 computeVerticalScrollRange() > computeVerticalScrollExtent(); 16374 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 16375 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 16376 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 16377 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 16378 16379 int newScrollX = scrollX + deltaX; 16380 if (!overScrollHorizontal) { 16381 maxOverScrollX = 0; 16382 } 16383 16384 int newScrollY = scrollY + deltaY; 16385 if (!overScrollVertical) { 16386 maxOverScrollY = 0; 16387 } 16388 16389 // Clamp values if at the limits and record 16390 final int left = -maxOverScrollX; 16391 final int right = maxOverScrollX + scrollRangeX; 16392 final int top = -maxOverScrollY; 16393 final int bottom = maxOverScrollY + scrollRangeY; 16394 16395 boolean clampedX = false; 16396 if (newScrollX > right) { 16397 newScrollX = right; 16398 clampedX = true; 16399 } else if (newScrollX < left) { 16400 newScrollX = left; 16401 clampedX = true; 16402 } 16403 16404 boolean clampedY = false; 16405 if (newScrollY > bottom) { 16406 newScrollY = bottom; 16407 clampedY = true; 16408 } else if (newScrollY < top) { 16409 newScrollY = top; 16410 clampedY = true; 16411 } 16412 16413 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 16414 16415 return clampedX || clampedY; 16416 } 16417 16418 /** 16419 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 16420 * respond to the results of an over-scroll operation. 16421 * 16422 * @param scrollX New X scroll value in pixels 16423 * @param scrollY New Y scroll value in pixels 16424 * @param clampedX True if scrollX was clamped to an over-scroll boundary 16425 * @param clampedY True if scrollY was clamped to an over-scroll boundary 16426 */ 16427 protected void onOverScrolled(int scrollX, int scrollY, 16428 boolean clampedX, boolean clampedY) { 16429 // Intentionally empty. 16430 } 16431 16432 /** 16433 * Returns the over-scroll mode for this view. The result will be 16434 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16435 * (allow over-scrolling only if the view content is larger than the container), 16436 * or {@link #OVER_SCROLL_NEVER}. 16437 * 16438 * @return This view's over-scroll mode. 16439 */ 16440 public int getOverScrollMode() { 16441 return mOverScrollMode; 16442 } 16443 16444 /** 16445 * Set the over-scroll mode for this view. Valid over-scroll modes are 16446 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16447 * (allow over-scrolling only if the view content is larger than the container), 16448 * or {@link #OVER_SCROLL_NEVER}. 16449 * 16450 * Setting the over-scroll mode of a view will have an effect only if the 16451 * view is capable of scrolling. 16452 * 16453 * @param overScrollMode The new over-scroll mode for this view. 16454 */ 16455 public void setOverScrollMode(int overScrollMode) { 16456 if (overScrollMode != OVER_SCROLL_ALWAYS && 16457 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 16458 overScrollMode != OVER_SCROLL_NEVER) { 16459 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 16460 } 16461 mOverScrollMode = overScrollMode; 16462 } 16463 16464 /** 16465 * Gets a scale factor that determines the distance the view should scroll 16466 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 16467 * @return The vertical scroll scale factor. 16468 * @hide 16469 */ 16470 protected float getVerticalScrollFactor() { 16471 if (mVerticalScrollFactor == 0) { 16472 TypedValue outValue = new TypedValue(); 16473 if (!mContext.getTheme().resolveAttribute( 16474 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 16475 throw new IllegalStateException( 16476 "Expected theme to define listPreferredItemHeight."); 16477 } 16478 mVerticalScrollFactor = outValue.getDimension( 16479 mContext.getResources().getDisplayMetrics()); 16480 } 16481 return mVerticalScrollFactor; 16482 } 16483 16484 /** 16485 * Gets a scale factor that determines the distance the view should scroll 16486 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 16487 * @return The horizontal scroll scale factor. 16488 * @hide 16489 */ 16490 protected float getHorizontalScrollFactor() { 16491 // TODO: Should use something else. 16492 return getVerticalScrollFactor(); 16493 } 16494 16495 /** 16496 * Return the value specifying the text direction or policy that was set with 16497 * {@link #setTextDirection(int)}. 16498 * 16499 * @return the defined text direction. It can be one of: 16500 * 16501 * {@link #TEXT_DIRECTION_INHERIT}, 16502 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16503 * {@link #TEXT_DIRECTION_ANY_RTL}, 16504 * {@link #TEXT_DIRECTION_LTR}, 16505 * {@link #TEXT_DIRECTION_RTL}, 16506 * {@link #TEXT_DIRECTION_LOCALE} 16507 */ 16508 @ViewDebug.ExportedProperty(category = "text", mapping = { 16509 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 16510 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 16511 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 16512 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 16513 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 16514 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 16515 }) 16516 public int getTextDirection() { 16517 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 16518 } 16519 16520 /** 16521 * Set the text direction. 16522 * 16523 * @param textDirection the direction to set. Should be one of: 16524 * 16525 * {@link #TEXT_DIRECTION_INHERIT}, 16526 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16527 * {@link #TEXT_DIRECTION_ANY_RTL}, 16528 * {@link #TEXT_DIRECTION_LTR}, 16529 * {@link #TEXT_DIRECTION_RTL}, 16530 * {@link #TEXT_DIRECTION_LOCALE} 16531 */ 16532 public void setTextDirection(int textDirection) { 16533 if (getTextDirection() != textDirection) { 16534 // Reset the current text direction and the resolved one 16535 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 16536 resetResolvedTextDirection(); 16537 // Set the new text direction 16538 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 16539 // Refresh 16540 requestLayout(); 16541 invalidate(true); 16542 } 16543 } 16544 16545 /** 16546 * Return the resolved text direction. 16547 * 16548 * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches 16549 * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds 16550 * up the parent chain of the view. if there is no parent, then it will return the default 16551 * {@link #TEXT_DIRECTION_FIRST_STRONG}. 16552 * 16553 * @return the resolved text direction. Returns one of: 16554 * 16555 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16556 * {@link #TEXT_DIRECTION_ANY_RTL}, 16557 * {@link #TEXT_DIRECTION_LTR}, 16558 * {@link #TEXT_DIRECTION_RTL}, 16559 * {@link #TEXT_DIRECTION_LOCALE} 16560 */ 16561 public int getResolvedTextDirection() { 16562 // The text direction will be resolved only if needed 16563 if ((mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) != PFLAG2_TEXT_DIRECTION_RESOLVED) { 16564 resolveTextDirection(); 16565 } 16566 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 16567 } 16568 16569 /** 16570 * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when 16571 * resolution is done. 16572 */ 16573 public void resolveTextDirection() { 16574 // Reset any previous text direction resolution 16575 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 16576 16577 if (hasRtlSupport()) { 16578 // Set resolved text direction flag depending on text direction flag 16579 final int textDirection = getTextDirection(); 16580 switch(textDirection) { 16581 case TEXT_DIRECTION_INHERIT: 16582 if (canResolveTextDirection()) { 16583 ViewGroup viewGroup = ((ViewGroup) mParent); 16584 16585 // Set current resolved direction to the same value as the parent's one 16586 final int parentResolvedDirection = viewGroup.getResolvedTextDirection(); 16587 switch (parentResolvedDirection) { 16588 case TEXT_DIRECTION_FIRST_STRONG: 16589 case TEXT_DIRECTION_ANY_RTL: 16590 case TEXT_DIRECTION_LTR: 16591 case TEXT_DIRECTION_RTL: 16592 case TEXT_DIRECTION_LOCALE: 16593 mPrivateFlags2 |= 16594 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 16595 break; 16596 default: 16597 // Default resolved direction is "first strong" heuristic 16598 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16599 } 16600 } else { 16601 // We cannot do the resolution if there is no parent, so use the default one 16602 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16603 } 16604 break; 16605 case TEXT_DIRECTION_FIRST_STRONG: 16606 case TEXT_DIRECTION_ANY_RTL: 16607 case TEXT_DIRECTION_LTR: 16608 case TEXT_DIRECTION_RTL: 16609 case TEXT_DIRECTION_LOCALE: 16610 // Resolved direction is the same as text direction 16611 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 16612 break; 16613 default: 16614 // Default resolved direction is "first strong" heuristic 16615 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16616 } 16617 } else { 16618 // Default resolved direction is "first strong" heuristic 16619 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16620 } 16621 16622 // Set to resolved 16623 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 16624 onResolvedTextDirectionChanged(); 16625 } 16626 16627 /** 16628 * Called when text direction has been resolved. Subclasses that care about text direction 16629 * resolution should override this method. 16630 * 16631 * The default implementation does nothing. 16632 */ 16633 public void onResolvedTextDirectionChanged() { 16634 } 16635 16636 /** 16637 * Check if text direction resolution can be done. 16638 * 16639 * @return true if text direction resolution can be done otherwise return false. 16640 */ 16641 public boolean canResolveTextDirection() { 16642 switch (getTextDirection()) { 16643 case TEXT_DIRECTION_INHERIT: 16644 return (mParent != null) && (mParent instanceof ViewGroup); 16645 default: 16646 return true; 16647 } 16648 } 16649 16650 /** 16651 * Reset resolved text direction. Text direction can be resolved with a call to 16652 * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when 16653 * reset is done. 16654 */ 16655 public void resetResolvedTextDirection() { 16656 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 16657 onResolvedTextDirectionReset(); 16658 } 16659 16660 /** 16661 * Called when text direction is reset. Subclasses that care about text direction reset should 16662 * override this method and do a reset of the text direction of their children. The default 16663 * implementation does nothing. 16664 */ 16665 public void onResolvedTextDirectionReset() { 16666 } 16667 16668 /** 16669 * Return the value specifying the text alignment or policy that was set with 16670 * {@link #setTextAlignment(int)}. 16671 * 16672 * @return the defined text alignment. It can be one of: 16673 * 16674 * {@link #TEXT_ALIGNMENT_INHERIT}, 16675 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16676 * {@link #TEXT_ALIGNMENT_CENTER}, 16677 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16678 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16679 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16680 * {@link #TEXT_ALIGNMENT_VIEW_END} 16681 */ 16682 @ViewDebug.ExportedProperty(category = "text", mapping = { 16683 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 16684 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 16685 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 16686 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 16687 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 16688 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 16689 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 16690 }) 16691 public int getTextAlignment() { 16692 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 16693 } 16694 16695 /** 16696 * Set the text alignment. 16697 * 16698 * @param textAlignment The text alignment to set. Should be one of 16699 * 16700 * {@link #TEXT_ALIGNMENT_INHERIT}, 16701 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16702 * {@link #TEXT_ALIGNMENT_CENTER}, 16703 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16704 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16705 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16706 * {@link #TEXT_ALIGNMENT_VIEW_END} 16707 * 16708 * @attr ref android.R.styleable#View_textAlignment 16709 */ 16710 public void setTextAlignment(int textAlignment) { 16711 if (textAlignment != getTextAlignment()) { 16712 // Reset the current and resolved text alignment 16713 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 16714 resetResolvedTextAlignment(); 16715 // Set the new text alignment 16716 mPrivateFlags2 |= ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 16717 // Refresh 16718 requestLayout(); 16719 invalidate(true); 16720 } 16721 } 16722 16723 /** 16724 * Return the resolved text alignment. 16725 * 16726 * The resolved text alignment. This needs resolution if the value is 16727 * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)} if it is 16728 * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view. 16729 * 16730 * @return the resolved text alignment. Returns one of: 16731 * 16732 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16733 * {@link #TEXT_ALIGNMENT_CENTER}, 16734 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16735 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16736 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16737 * {@link #TEXT_ALIGNMENT_VIEW_END} 16738 */ 16739 @ViewDebug.ExportedProperty(category = "text", mapping = { 16740 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 16741 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 16742 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 16743 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 16744 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 16745 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 16746 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 16747 }) 16748 public int getResolvedTextAlignment() { 16749 // If text alignment is not resolved, then resolve it 16750 if ((mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) != PFLAG2_TEXT_ALIGNMENT_RESOLVED) { 16751 resolveTextAlignment(); 16752 } 16753 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 16754 } 16755 16756 /** 16757 * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when 16758 * resolution is done. 16759 */ 16760 public void resolveTextAlignment() { 16761 // Reset any previous text alignment resolution 16762 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 16763 16764 if (hasRtlSupport()) { 16765 // Set resolved text alignment flag depending on text alignment flag 16766 final int textAlignment = getTextAlignment(); 16767 switch (textAlignment) { 16768 case TEXT_ALIGNMENT_INHERIT: 16769 // Check if we can resolve the text alignment 16770 if (canResolveLayoutDirection() && mParent instanceof View) { 16771 View view = (View) mParent; 16772 16773 final int parentResolvedTextAlignment = view.getResolvedTextAlignment(); 16774 switch (parentResolvedTextAlignment) { 16775 case TEXT_ALIGNMENT_GRAVITY: 16776 case TEXT_ALIGNMENT_TEXT_START: 16777 case TEXT_ALIGNMENT_TEXT_END: 16778 case TEXT_ALIGNMENT_CENTER: 16779 case TEXT_ALIGNMENT_VIEW_START: 16780 case TEXT_ALIGNMENT_VIEW_END: 16781 // Resolved text alignment is the same as the parent resolved 16782 // text alignment 16783 mPrivateFlags2 |= 16784 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 16785 break; 16786 default: 16787 // Use default resolved text alignment 16788 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16789 } 16790 } 16791 else { 16792 // We cannot do the resolution if there is no parent so use the default 16793 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16794 } 16795 break; 16796 case TEXT_ALIGNMENT_GRAVITY: 16797 case TEXT_ALIGNMENT_TEXT_START: 16798 case TEXT_ALIGNMENT_TEXT_END: 16799 case TEXT_ALIGNMENT_CENTER: 16800 case TEXT_ALIGNMENT_VIEW_START: 16801 case TEXT_ALIGNMENT_VIEW_END: 16802 // Resolved text alignment is the same as text alignment 16803 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 16804 break; 16805 default: 16806 // Use default resolved text alignment 16807 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16808 } 16809 } else { 16810 // Use default resolved text alignment 16811 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16812 } 16813 16814 // Set the resolved 16815 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 16816 onResolvedTextAlignmentChanged(); 16817 } 16818 16819 /** 16820 * Check if text alignment resolution can be done. 16821 * 16822 * @return true if text alignment resolution can be done otherwise return false. 16823 */ 16824 public boolean canResolveTextAlignment() { 16825 switch (getTextAlignment()) { 16826 case TEXT_DIRECTION_INHERIT: 16827 return (mParent != null); 16828 default: 16829 return true; 16830 } 16831 } 16832 16833 /** 16834 * Called when text alignment has been resolved. Subclasses that care about text alignment 16835 * resolution should override this method. 16836 * 16837 * The default implementation does nothing. 16838 */ 16839 public void onResolvedTextAlignmentChanged() { 16840 } 16841 16842 /** 16843 * Reset resolved text alignment. Text alignment can be resolved with a call to 16844 * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when 16845 * reset is done. 16846 */ 16847 public void resetResolvedTextAlignment() { 16848 // Reset any previous text alignment resolution 16849 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 16850 onResolvedTextAlignmentReset(); 16851 } 16852 16853 /** 16854 * Called when text alignment is reset. Subclasses that care about text alignment reset should 16855 * override this method and do a reset of the text alignment of their children. The default 16856 * implementation does nothing. 16857 */ 16858 public void onResolvedTextAlignmentReset() { 16859 } 16860 16861 /** 16862 * Generate a value suitable for use in {@link #setId(int)}. 16863 * This value will not collide with ID values generated at build time by aapt for R.id. 16864 * 16865 * @return a generated ID value 16866 */ 16867 public static int generateViewId() { 16868 for (;;) { 16869 final int result = sNextGeneratedId.get(); 16870 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 16871 int newValue = result + 1; 16872 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 16873 if (sNextGeneratedId.compareAndSet(result, newValue)) { 16874 return result; 16875 } 16876 } 16877 } 16878 16879 // 16880 // Properties 16881 // 16882 /** 16883 * A Property wrapper around the <code>alpha</code> functionality handled by the 16884 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 16885 */ 16886 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 16887 @Override 16888 public void setValue(View object, float value) { 16889 object.setAlpha(value); 16890 } 16891 16892 @Override 16893 public Float get(View object) { 16894 return object.getAlpha(); 16895 } 16896 }; 16897 16898 /** 16899 * A Property wrapper around the <code>translationX</code> functionality handled by the 16900 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 16901 */ 16902 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 16903 @Override 16904 public void setValue(View object, float value) { 16905 object.setTranslationX(value); 16906 } 16907 16908 @Override 16909 public Float get(View object) { 16910 return object.getTranslationX(); 16911 } 16912 }; 16913 16914 /** 16915 * A Property wrapper around the <code>translationY</code> functionality handled by the 16916 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 16917 */ 16918 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 16919 @Override 16920 public void setValue(View object, float value) { 16921 object.setTranslationY(value); 16922 } 16923 16924 @Override 16925 public Float get(View object) { 16926 return object.getTranslationY(); 16927 } 16928 }; 16929 16930 /** 16931 * A Property wrapper around the <code>x</code> functionality handled by the 16932 * {@link View#setX(float)} and {@link View#getX()} methods. 16933 */ 16934 public static final Property<View, Float> X = new FloatProperty<View>("x") { 16935 @Override 16936 public void setValue(View object, float value) { 16937 object.setX(value); 16938 } 16939 16940 @Override 16941 public Float get(View object) { 16942 return object.getX(); 16943 } 16944 }; 16945 16946 /** 16947 * A Property wrapper around the <code>y</code> functionality handled by the 16948 * {@link View#setY(float)} and {@link View#getY()} methods. 16949 */ 16950 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 16951 @Override 16952 public void setValue(View object, float value) { 16953 object.setY(value); 16954 } 16955 16956 @Override 16957 public Float get(View object) { 16958 return object.getY(); 16959 } 16960 }; 16961 16962 /** 16963 * A Property wrapper around the <code>rotation</code> functionality handled by the 16964 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 16965 */ 16966 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 16967 @Override 16968 public void setValue(View object, float value) { 16969 object.setRotation(value); 16970 } 16971 16972 @Override 16973 public Float get(View object) { 16974 return object.getRotation(); 16975 } 16976 }; 16977 16978 /** 16979 * A Property wrapper around the <code>rotationX</code> functionality handled by the 16980 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 16981 */ 16982 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 16983 @Override 16984 public void setValue(View object, float value) { 16985 object.setRotationX(value); 16986 } 16987 16988 @Override 16989 public Float get(View object) { 16990 return object.getRotationX(); 16991 } 16992 }; 16993 16994 /** 16995 * A Property wrapper around the <code>rotationY</code> functionality handled by the 16996 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 16997 */ 16998 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 16999 @Override 17000 public void setValue(View object, float value) { 17001 object.setRotationY(value); 17002 } 17003 17004 @Override 17005 public Float get(View object) { 17006 return object.getRotationY(); 17007 } 17008 }; 17009 17010 /** 17011 * A Property wrapper around the <code>scaleX</code> functionality handled by the 17012 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 17013 */ 17014 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 17015 @Override 17016 public void setValue(View object, float value) { 17017 object.setScaleX(value); 17018 } 17019 17020 @Override 17021 public Float get(View object) { 17022 return object.getScaleX(); 17023 } 17024 }; 17025 17026 /** 17027 * A Property wrapper around the <code>scaleY</code> functionality handled by the 17028 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 17029 */ 17030 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 17031 @Override 17032 public void setValue(View object, float value) { 17033 object.setScaleY(value); 17034 } 17035 17036 @Override 17037 public Float get(View object) { 17038 return object.getScaleY(); 17039 } 17040 }; 17041 17042 /** 17043 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 17044 * Each MeasureSpec represents a requirement for either the width or the height. 17045 * A MeasureSpec is comprised of a size and a mode. There are three possible 17046 * modes: 17047 * <dl> 17048 * <dt>UNSPECIFIED</dt> 17049 * <dd> 17050 * The parent has not imposed any constraint on the child. It can be whatever size 17051 * it wants. 17052 * </dd> 17053 * 17054 * <dt>EXACTLY</dt> 17055 * <dd> 17056 * The parent has determined an exact size for the child. The child is going to be 17057 * given those bounds regardless of how big it wants to be. 17058 * </dd> 17059 * 17060 * <dt>AT_MOST</dt> 17061 * <dd> 17062 * The child can be as large as it wants up to the specified size. 17063 * </dd> 17064 * </dl> 17065 * 17066 * MeasureSpecs are implemented as ints to reduce object allocation. This class 17067 * is provided to pack and unpack the <size, mode> tuple into the int. 17068 */ 17069 public static class MeasureSpec { 17070 private static final int MODE_SHIFT = 30; 17071 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 17072 17073 /** 17074 * Measure specification mode: The parent has not imposed any constraint 17075 * on the child. It can be whatever size it wants. 17076 */ 17077 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 17078 17079 /** 17080 * Measure specification mode: The parent has determined an exact size 17081 * for the child. The child is going to be given those bounds regardless 17082 * of how big it wants to be. 17083 */ 17084 public static final int EXACTLY = 1 << MODE_SHIFT; 17085 17086 /** 17087 * Measure specification mode: The child can be as large as it wants up 17088 * to the specified size. 17089 */ 17090 public static final int AT_MOST = 2 << MODE_SHIFT; 17091 17092 /** 17093 * Creates a measure specification based on the supplied size and mode. 17094 * 17095 * The mode must always be one of the following: 17096 * <ul> 17097 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 17098 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 17099 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 17100 * </ul> 17101 * 17102 * @param size the size of the measure specification 17103 * @param mode the mode of the measure specification 17104 * @return the measure specification based on size and mode 17105 */ 17106 public static int makeMeasureSpec(int size, int mode) { 17107 return size + mode; 17108 } 17109 17110 /** 17111 * Extracts the mode from the supplied measure specification. 17112 * 17113 * @param measureSpec the measure specification to extract the mode from 17114 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 17115 * {@link android.view.View.MeasureSpec#AT_MOST} or 17116 * {@link android.view.View.MeasureSpec#EXACTLY} 17117 */ 17118 public static int getMode(int measureSpec) { 17119 return (measureSpec & MODE_MASK); 17120 } 17121 17122 /** 17123 * Extracts the size from the supplied measure specification. 17124 * 17125 * @param measureSpec the measure specification to extract the size from 17126 * @return the size in pixels defined in the supplied measure specification 17127 */ 17128 public static int getSize(int measureSpec) { 17129 return (measureSpec & ~MODE_MASK); 17130 } 17131 17132 /** 17133 * Returns a String representation of the specified measure 17134 * specification. 17135 * 17136 * @param measureSpec the measure specification to convert to a String 17137 * @return a String with the following format: "MeasureSpec: MODE SIZE" 17138 */ 17139 public static String toString(int measureSpec) { 17140 int mode = getMode(measureSpec); 17141 int size = getSize(measureSpec); 17142 17143 StringBuilder sb = new StringBuilder("MeasureSpec: "); 17144 17145 if (mode == UNSPECIFIED) 17146 sb.append("UNSPECIFIED "); 17147 else if (mode == EXACTLY) 17148 sb.append("EXACTLY "); 17149 else if (mode == AT_MOST) 17150 sb.append("AT_MOST "); 17151 else 17152 sb.append(mode).append(" "); 17153 17154 sb.append(size); 17155 return sb.toString(); 17156 } 17157 } 17158 17159 class CheckForLongPress implements Runnable { 17160 17161 private int mOriginalWindowAttachCount; 17162 17163 public void run() { 17164 if (isPressed() && (mParent != null) 17165 && mOriginalWindowAttachCount == mWindowAttachCount) { 17166 if (performLongClick()) { 17167 mHasPerformedLongPress = true; 17168 } 17169 } 17170 } 17171 17172 public void rememberWindowAttachCount() { 17173 mOriginalWindowAttachCount = mWindowAttachCount; 17174 } 17175 } 17176 17177 private final class CheckForTap implements Runnable { 17178 public void run() { 17179 mPrivateFlags &= ~PFLAG_PREPRESSED; 17180 setPressed(true); 17181 checkForLongClick(ViewConfiguration.getTapTimeout()); 17182 } 17183 } 17184 17185 private final class PerformClick implements Runnable { 17186 public void run() { 17187 performClick(); 17188 } 17189 } 17190 17191 /** @hide */ 17192 public void hackTurnOffWindowResizeAnim(boolean off) { 17193 mAttachInfo.mTurnOffWindowResizeAnim = off; 17194 } 17195 17196 /** 17197 * This method returns a ViewPropertyAnimator object, which can be used to animate 17198 * specific properties on this View. 17199 * 17200 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 17201 */ 17202 public ViewPropertyAnimator animate() { 17203 if (mAnimator == null) { 17204 mAnimator = new ViewPropertyAnimator(this); 17205 } 17206 return mAnimator; 17207 } 17208 17209 /** 17210 * Interface definition for a callback to be invoked when a hardware key event is 17211 * dispatched to this view. The callback will be invoked before the key event is 17212 * given to the view. This is only useful for hardware keyboards; a software input 17213 * method has no obligation to trigger this listener. 17214 */ 17215 public interface OnKeyListener { 17216 /** 17217 * Called when a hardware key is dispatched to a view. This allows listeners to 17218 * get a chance to respond before the target view. 17219 * <p>Key presses in software keyboards will generally NOT trigger this method, 17220 * although some may elect to do so in some situations. Do not assume a 17221 * software input method has to be key-based; even if it is, it may use key presses 17222 * in a different way than you expect, so there is no way to reliably catch soft 17223 * input key presses. 17224 * 17225 * @param v The view the key has been dispatched to. 17226 * @param keyCode The code for the physical key that was pressed 17227 * @param event The KeyEvent object containing full information about 17228 * the event. 17229 * @return True if the listener has consumed the event, false otherwise. 17230 */ 17231 boolean onKey(View v, int keyCode, KeyEvent event); 17232 } 17233 17234 /** 17235 * Interface definition for a callback to be invoked when a touch event is 17236 * dispatched to this view. The callback will be invoked before the touch 17237 * event is given to the view. 17238 */ 17239 public interface OnTouchListener { 17240 /** 17241 * Called when a touch event is dispatched to a view. This allows listeners to 17242 * get a chance to respond before the target view. 17243 * 17244 * @param v The view the touch event has been dispatched to. 17245 * @param event The MotionEvent object containing full information about 17246 * the event. 17247 * @return True if the listener has consumed the event, false otherwise. 17248 */ 17249 boolean onTouch(View v, MotionEvent event); 17250 } 17251 17252 /** 17253 * Interface definition for a callback to be invoked when a hover event is 17254 * dispatched to this view. The callback will be invoked before the hover 17255 * event is given to the view. 17256 */ 17257 public interface OnHoverListener { 17258 /** 17259 * Called when a hover event is dispatched to a view. This allows listeners to 17260 * get a chance to respond before the target view. 17261 * 17262 * @param v The view the hover event has been dispatched to. 17263 * @param event The MotionEvent object containing full information about 17264 * the event. 17265 * @return True if the listener has consumed the event, false otherwise. 17266 */ 17267 boolean onHover(View v, MotionEvent event); 17268 } 17269 17270 /** 17271 * Interface definition for a callback to be invoked when a generic motion event is 17272 * dispatched to this view. The callback will be invoked before the generic motion 17273 * event is given to the view. 17274 */ 17275 public interface OnGenericMotionListener { 17276 /** 17277 * Called when a generic motion event is dispatched to a view. This allows listeners to 17278 * get a chance to respond before the target view. 17279 * 17280 * @param v The view the generic motion event has been dispatched to. 17281 * @param event The MotionEvent object containing full information about 17282 * the event. 17283 * @return True if the listener has consumed the event, false otherwise. 17284 */ 17285 boolean onGenericMotion(View v, MotionEvent event); 17286 } 17287 17288 /** 17289 * Interface definition for a callback to be invoked when a view has been clicked and held. 17290 */ 17291 public interface OnLongClickListener { 17292 /** 17293 * Called when a view has been clicked and held. 17294 * 17295 * @param v The view that was clicked and held. 17296 * 17297 * @return true if the callback consumed the long click, false otherwise. 17298 */ 17299 boolean onLongClick(View v); 17300 } 17301 17302 /** 17303 * Interface definition for a callback to be invoked when a drag is being dispatched 17304 * to this view. The callback will be invoked before the hosting view's own 17305 * onDrag(event) method. If the listener wants to fall back to the hosting view's 17306 * onDrag(event) behavior, it should return 'false' from this callback. 17307 * 17308 * <div class="special reference"> 17309 * <h3>Developer Guides</h3> 17310 * <p>For a guide to implementing drag and drop features, read the 17311 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17312 * </div> 17313 */ 17314 public interface OnDragListener { 17315 /** 17316 * Called when a drag event is dispatched to a view. This allows listeners 17317 * to get a chance to override base View behavior. 17318 * 17319 * @param v The View that received the drag event. 17320 * @param event The {@link android.view.DragEvent} object for the drag event. 17321 * @return {@code true} if the drag event was handled successfully, or {@code false} 17322 * if the drag event was not handled. Note that {@code false} will trigger the View 17323 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 17324 */ 17325 boolean onDrag(View v, DragEvent event); 17326 } 17327 17328 /** 17329 * Interface definition for a callback to be invoked when the focus state of 17330 * a view changed. 17331 */ 17332 public interface OnFocusChangeListener { 17333 /** 17334 * Called when the focus state of a view has changed. 17335 * 17336 * @param v The view whose state has changed. 17337 * @param hasFocus The new focus state of v. 17338 */ 17339 void onFocusChange(View v, boolean hasFocus); 17340 } 17341 17342 /** 17343 * Interface definition for a callback to be invoked when a view is clicked. 17344 */ 17345 public interface OnClickListener { 17346 /** 17347 * Called when a view has been clicked. 17348 * 17349 * @param v The view that was clicked. 17350 */ 17351 void onClick(View v); 17352 } 17353 17354 /** 17355 * Interface definition for a callback to be invoked when the context menu 17356 * for this view is being built. 17357 */ 17358 public interface OnCreateContextMenuListener { 17359 /** 17360 * Called when the context menu for this view is being built. It is not 17361 * safe to hold onto the menu after this method returns. 17362 * 17363 * @param menu The context menu that is being built 17364 * @param v The view for which the context menu is being built 17365 * @param menuInfo Extra information about the item for which the 17366 * context menu should be shown. This information will vary 17367 * depending on the class of v. 17368 */ 17369 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 17370 } 17371 17372 /** 17373 * Interface definition for a callback to be invoked when the status bar changes 17374 * visibility. This reports <strong>global</strong> changes to the system UI 17375 * state, not what the application is requesting. 17376 * 17377 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 17378 */ 17379 public interface OnSystemUiVisibilityChangeListener { 17380 /** 17381 * Called when the status bar changes visibility because of a call to 17382 * {@link View#setSystemUiVisibility(int)}. 17383 * 17384 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17385 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 17386 * This tells you the <strong>global</strong> state of these UI visibility 17387 * flags, not what your app is currently applying. 17388 */ 17389 public void onSystemUiVisibilityChange(int visibility); 17390 } 17391 17392 /** 17393 * Interface definition for a callback to be invoked when this view is attached 17394 * or detached from its window. 17395 */ 17396 public interface OnAttachStateChangeListener { 17397 /** 17398 * Called when the view is attached to a window. 17399 * @param v The view that was attached 17400 */ 17401 public void onViewAttachedToWindow(View v); 17402 /** 17403 * Called when the view is detached from a window. 17404 * @param v The view that was detached 17405 */ 17406 public void onViewDetachedFromWindow(View v); 17407 } 17408 17409 private final class UnsetPressedState implements Runnable { 17410 public void run() { 17411 setPressed(false); 17412 } 17413 } 17414 17415 /** 17416 * Base class for derived classes that want to save and restore their own 17417 * state in {@link android.view.View#onSaveInstanceState()}. 17418 */ 17419 public static class BaseSavedState extends AbsSavedState { 17420 /** 17421 * Constructor used when reading from a parcel. Reads the state of the superclass. 17422 * 17423 * @param source 17424 */ 17425 public BaseSavedState(Parcel source) { 17426 super(source); 17427 } 17428 17429 /** 17430 * Constructor called by derived classes when creating their SavedState objects 17431 * 17432 * @param superState The state of the superclass of this view 17433 */ 17434 public BaseSavedState(Parcelable superState) { 17435 super(superState); 17436 } 17437 17438 public static final Parcelable.Creator<BaseSavedState> CREATOR = 17439 new Parcelable.Creator<BaseSavedState>() { 17440 public BaseSavedState createFromParcel(Parcel in) { 17441 return new BaseSavedState(in); 17442 } 17443 17444 public BaseSavedState[] newArray(int size) { 17445 return new BaseSavedState[size]; 17446 } 17447 }; 17448 } 17449 17450 /** 17451 * A set of information given to a view when it is attached to its parent 17452 * window. 17453 */ 17454 static class AttachInfo { 17455 interface Callbacks { 17456 void playSoundEffect(int effectId); 17457 boolean performHapticFeedback(int effectId, boolean always); 17458 } 17459 17460 /** 17461 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 17462 * to a Handler. This class contains the target (View) to invalidate and 17463 * the coordinates of the dirty rectangle. 17464 * 17465 * For performance purposes, this class also implements a pool of up to 17466 * POOL_LIMIT objects that get reused. This reduces memory allocations 17467 * whenever possible. 17468 */ 17469 static class InvalidateInfo implements Poolable<InvalidateInfo> { 17470 private static final int POOL_LIMIT = 10; 17471 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 17472 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 17473 public InvalidateInfo newInstance() { 17474 return new InvalidateInfo(); 17475 } 17476 17477 public void onAcquired(InvalidateInfo element) { 17478 } 17479 17480 public void onReleased(InvalidateInfo element) { 17481 element.target = null; 17482 } 17483 }, POOL_LIMIT) 17484 ); 17485 17486 private InvalidateInfo mNext; 17487 private boolean mIsPooled; 17488 17489 View target; 17490 17491 int left; 17492 int top; 17493 int right; 17494 int bottom; 17495 17496 public void setNextPoolable(InvalidateInfo element) { 17497 mNext = element; 17498 } 17499 17500 public InvalidateInfo getNextPoolable() { 17501 return mNext; 17502 } 17503 17504 static InvalidateInfo acquire() { 17505 return sPool.acquire(); 17506 } 17507 17508 void release() { 17509 sPool.release(this); 17510 } 17511 17512 public boolean isPooled() { 17513 return mIsPooled; 17514 } 17515 17516 public void setPooled(boolean isPooled) { 17517 mIsPooled = isPooled; 17518 } 17519 } 17520 17521 final IWindowSession mSession; 17522 17523 final IWindow mWindow; 17524 17525 final IBinder mWindowToken; 17526 17527 final Display mDisplay; 17528 17529 final Callbacks mRootCallbacks; 17530 17531 HardwareCanvas mHardwareCanvas; 17532 17533 /** 17534 * The top view of the hierarchy. 17535 */ 17536 View mRootView; 17537 17538 IBinder mPanelParentWindowToken; 17539 Surface mSurface; 17540 17541 boolean mHardwareAccelerated; 17542 boolean mHardwareAccelerationRequested; 17543 HardwareRenderer mHardwareRenderer; 17544 17545 boolean mScreenOn; 17546 17547 /** 17548 * Scale factor used by the compatibility mode 17549 */ 17550 float mApplicationScale; 17551 17552 /** 17553 * Indicates whether the application is in compatibility mode 17554 */ 17555 boolean mScalingRequired; 17556 17557 /** 17558 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 17559 */ 17560 boolean mTurnOffWindowResizeAnim; 17561 17562 /** 17563 * Left position of this view's window 17564 */ 17565 int mWindowLeft; 17566 17567 /** 17568 * Top position of this view's window 17569 */ 17570 int mWindowTop; 17571 17572 /** 17573 * Indicates whether views need to use 32-bit drawing caches 17574 */ 17575 boolean mUse32BitDrawingCache; 17576 17577 /** 17578 * For windows that are full-screen but using insets to layout inside 17579 * of the screen decorations, these are the current insets for the 17580 * content of the window. 17581 */ 17582 final Rect mContentInsets = new Rect(); 17583 17584 /** 17585 * For windows that are full-screen but using insets to layout inside 17586 * of the screen decorations, these are the current insets for the 17587 * actual visible parts of the window. 17588 */ 17589 final Rect mVisibleInsets = new Rect(); 17590 17591 /** 17592 * The internal insets given by this window. This value is 17593 * supplied by the client (through 17594 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 17595 * be given to the window manager when changed to be used in laying 17596 * out windows behind it. 17597 */ 17598 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 17599 = new ViewTreeObserver.InternalInsetsInfo(); 17600 17601 /** 17602 * All views in the window's hierarchy that serve as scroll containers, 17603 * used to determine if the window can be resized or must be panned 17604 * to adjust for a soft input area. 17605 */ 17606 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 17607 17608 final KeyEvent.DispatcherState mKeyDispatchState 17609 = new KeyEvent.DispatcherState(); 17610 17611 /** 17612 * Indicates whether the view's window currently has the focus. 17613 */ 17614 boolean mHasWindowFocus; 17615 17616 /** 17617 * The current visibility of the window. 17618 */ 17619 int mWindowVisibility; 17620 17621 /** 17622 * Indicates the time at which drawing started to occur. 17623 */ 17624 long mDrawingTime; 17625 17626 /** 17627 * Indicates whether or not ignoring the DIRTY_MASK flags. 17628 */ 17629 boolean mIgnoreDirtyState; 17630 17631 /** 17632 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 17633 * to avoid clearing that flag prematurely. 17634 */ 17635 boolean mSetIgnoreDirtyState = false; 17636 17637 /** 17638 * Indicates whether the view's window is currently in touch mode. 17639 */ 17640 boolean mInTouchMode; 17641 17642 /** 17643 * Indicates that ViewAncestor should trigger a global layout change 17644 * the next time it performs a traversal 17645 */ 17646 boolean mRecomputeGlobalAttributes; 17647 17648 /** 17649 * Always report new attributes at next traversal. 17650 */ 17651 boolean mForceReportNewAttributes; 17652 17653 /** 17654 * Set during a traveral if any views want to keep the screen on. 17655 */ 17656 boolean mKeepScreenOn; 17657 17658 /** 17659 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 17660 */ 17661 int mSystemUiVisibility; 17662 17663 /** 17664 * Hack to force certain system UI visibility flags to be cleared. 17665 */ 17666 int mDisabledSystemUiVisibility; 17667 17668 /** 17669 * Last global system UI visibility reported by the window manager. 17670 */ 17671 int mGlobalSystemUiVisibility; 17672 17673 /** 17674 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 17675 * attached. 17676 */ 17677 boolean mHasSystemUiListeners; 17678 17679 /** 17680 * Set if the visibility of any views has changed. 17681 */ 17682 boolean mViewVisibilityChanged; 17683 17684 /** 17685 * Set to true if a view has been scrolled. 17686 */ 17687 boolean mViewScrollChanged; 17688 17689 /** 17690 * Global to the view hierarchy used as a temporary for dealing with 17691 * x/y points in the transparent region computations. 17692 */ 17693 final int[] mTransparentLocation = new int[2]; 17694 17695 /** 17696 * Global to the view hierarchy used as a temporary for dealing with 17697 * x/y points in the ViewGroup.invalidateChild implementation. 17698 */ 17699 final int[] mInvalidateChildLocation = new int[2]; 17700 17701 17702 /** 17703 * Global to the view hierarchy used as a temporary for dealing with 17704 * x/y location when view is transformed. 17705 */ 17706 final float[] mTmpTransformLocation = new float[2]; 17707 17708 /** 17709 * The view tree observer used to dispatch global events like 17710 * layout, pre-draw, touch mode change, etc. 17711 */ 17712 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 17713 17714 /** 17715 * A Canvas used by the view hierarchy to perform bitmap caching. 17716 */ 17717 Canvas mCanvas; 17718 17719 /** 17720 * The view root impl. 17721 */ 17722 final ViewRootImpl mViewRootImpl; 17723 17724 /** 17725 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 17726 * handler can be used to pump events in the UI events queue. 17727 */ 17728 final Handler mHandler; 17729 17730 /** 17731 * Temporary for use in computing invalidate rectangles while 17732 * calling up the hierarchy. 17733 */ 17734 final Rect mTmpInvalRect = new Rect(); 17735 17736 /** 17737 * Temporary for use in computing hit areas with transformed views 17738 */ 17739 final RectF mTmpTransformRect = new RectF(); 17740 17741 /** 17742 * Temporary for use in transforming invalidation rect 17743 */ 17744 final Matrix mTmpMatrix = new Matrix(); 17745 17746 /** 17747 * Temporary for use in transforming invalidation rect 17748 */ 17749 final Transformation mTmpTransformation = new Transformation(); 17750 17751 /** 17752 * Temporary list for use in collecting focusable descendents of a view. 17753 */ 17754 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 17755 17756 /** 17757 * The id of the window for accessibility purposes. 17758 */ 17759 int mAccessibilityWindowId = View.NO_ID; 17760 17761 /** 17762 * Whether to ingore not exposed for accessibility Views when 17763 * reporting the view tree to accessibility services. 17764 */ 17765 boolean mIncludeNotImportantViews; 17766 17767 /** 17768 * The drawable for highlighting accessibility focus. 17769 */ 17770 Drawable mAccessibilityFocusDrawable; 17771 17772 /** 17773 * Show where the margins, bounds and layout bounds are for each view. 17774 */ 17775 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 17776 17777 /** 17778 * Point used to compute visible regions. 17779 */ 17780 final Point mPoint = new Point(); 17781 17782 /** 17783 * Creates a new set of attachment information with the specified 17784 * events handler and thread. 17785 * 17786 * @param handler the events handler the view must use 17787 */ 17788 AttachInfo(IWindowSession session, IWindow window, Display display, 17789 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 17790 mSession = session; 17791 mWindow = window; 17792 mWindowToken = window.asBinder(); 17793 mDisplay = display; 17794 mViewRootImpl = viewRootImpl; 17795 mHandler = handler; 17796 mRootCallbacks = effectPlayer; 17797 } 17798 } 17799 17800 /** 17801 * <p>ScrollabilityCache holds various fields used by a View when scrolling 17802 * is supported. This avoids keeping too many unused fields in most 17803 * instances of View.</p> 17804 */ 17805 private static class ScrollabilityCache implements Runnable { 17806 17807 /** 17808 * Scrollbars are not visible 17809 */ 17810 public static final int OFF = 0; 17811 17812 /** 17813 * Scrollbars are visible 17814 */ 17815 public static final int ON = 1; 17816 17817 /** 17818 * Scrollbars are fading away 17819 */ 17820 public static final int FADING = 2; 17821 17822 public boolean fadeScrollBars; 17823 17824 public int fadingEdgeLength; 17825 public int scrollBarDefaultDelayBeforeFade; 17826 public int scrollBarFadeDuration; 17827 17828 public int scrollBarSize; 17829 public ScrollBarDrawable scrollBar; 17830 public float[] interpolatorValues; 17831 public View host; 17832 17833 public final Paint paint; 17834 public final Matrix matrix; 17835 public Shader shader; 17836 17837 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 17838 17839 private static final float[] OPAQUE = { 255 }; 17840 private static final float[] TRANSPARENT = { 0.0f }; 17841 17842 /** 17843 * When fading should start. This time moves into the future every time 17844 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 17845 */ 17846 public long fadeStartTime; 17847 17848 17849 /** 17850 * The current state of the scrollbars: ON, OFF, or FADING 17851 */ 17852 public int state = OFF; 17853 17854 private int mLastColor; 17855 17856 public ScrollabilityCache(ViewConfiguration configuration, View host) { 17857 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 17858 scrollBarSize = configuration.getScaledScrollBarSize(); 17859 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 17860 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 17861 17862 paint = new Paint(); 17863 matrix = new Matrix(); 17864 // use use a height of 1, and then wack the matrix each time we 17865 // actually use it. 17866 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 17867 paint.setShader(shader); 17868 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 17869 17870 this.host = host; 17871 } 17872 17873 public void setFadeColor(int color) { 17874 if (color != mLastColor) { 17875 mLastColor = color; 17876 17877 if (color != 0) { 17878 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 17879 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 17880 paint.setShader(shader); 17881 // Restore the default transfer mode (src_over) 17882 paint.setXfermode(null); 17883 } else { 17884 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 17885 paint.setShader(shader); 17886 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 17887 } 17888 } 17889 } 17890 17891 public void run() { 17892 long now = AnimationUtils.currentAnimationTimeMillis(); 17893 if (now >= fadeStartTime) { 17894 17895 // the animation fades the scrollbars out by changing 17896 // the opacity (alpha) from fully opaque to fully 17897 // transparent 17898 int nextFrame = (int) now; 17899 int framesCount = 0; 17900 17901 Interpolator interpolator = scrollBarInterpolator; 17902 17903 // Start opaque 17904 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 17905 17906 // End transparent 17907 nextFrame += scrollBarFadeDuration; 17908 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 17909 17910 state = FADING; 17911 17912 // Kick off the fade animation 17913 host.invalidate(true); 17914 } 17915 } 17916 } 17917 17918 /** 17919 * Resuable callback for sending 17920 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 17921 */ 17922 private class SendViewScrolledAccessibilityEvent implements Runnable { 17923 public volatile boolean mIsPending; 17924 17925 public void run() { 17926 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 17927 mIsPending = false; 17928 } 17929 } 17930 17931 /** 17932 * <p> 17933 * This class represents a delegate that can be registered in a {@link View} 17934 * to enhance accessibility support via composition rather via inheritance. 17935 * It is specifically targeted to widget developers that extend basic View 17936 * classes i.e. classes in package android.view, that would like their 17937 * applications to be backwards compatible. 17938 * </p> 17939 * <div class="special reference"> 17940 * <h3>Developer Guides</h3> 17941 * <p>For more information about making applications accessible, read the 17942 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 17943 * developer guide.</p> 17944 * </div> 17945 * <p> 17946 * A scenario in which a developer would like to use an accessibility delegate 17947 * is overriding a method introduced in a later API version then the minimal API 17948 * version supported by the application. For example, the method 17949 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 17950 * in API version 4 when the accessibility APIs were first introduced. If a 17951 * developer would like his application to run on API version 4 devices (assuming 17952 * all other APIs used by the application are version 4 or lower) and take advantage 17953 * of this method, instead of overriding the method which would break the application's 17954 * backwards compatibility, he can override the corresponding method in this 17955 * delegate and register the delegate in the target View if the API version of 17956 * the system is high enough i.e. the API version is same or higher to the API 17957 * version that introduced 17958 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 17959 * </p> 17960 * <p> 17961 * Here is an example implementation: 17962 * </p> 17963 * <code><pre><p> 17964 * if (Build.VERSION.SDK_INT >= 14) { 17965 * // If the API version is equal of higher than the version in 17966 * // which onInitializeAccessibilityNodeInfo was introduced we 17967 * // register a delegate with a customized implementation. 17968 * View view = findViewById(R.id.view_id); 17969 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 17970 * public void onInitializeAccessibilityNodeInfo(View host, 17971 * AccessibilityNodeInfo info) { 17972 * // Let the default implementation populate the info. 17973 * super.onInitializeAccessibilityNodeInfo(host, info); 17974 * // Set some other information. 17975 * info.setEnabled(host.isEnabled()); 17976 * } 17977 * }); 17978 * } 17979 * </code></pre></p> 17980 * <p> 17981 * This delegate contains methods that correspond to the accessibility methods 17982 * in View. If a delegate has been specified the implementation in View hands 17983 * off handling to the corresponding method in this delegate. The default 17984 * implementation the delegate methods behaves exactly as the corresponding 17985 * method in View for the case of no accessibility delegate been set. Hence, 17986 * to customize the behavior of a View method, clients can override only the 17987 * corresponding delegate method without altering the behavior of the rest 17988 * accessibility related methods of the host view. 17989 * </p> 17990 */ 17991 public static class AccessibilityDelegate { 17992 17993 /** 17994 * Sends an accessibility event of the given type. If accessibility is not 17995 * enabled this method has no effect. 17996 * <p> 17997 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 17998 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 17999 * been set. 18000 * </p> 18001 * 18002 * @param host The View hosting the delegate. 18003 * @param eventType The type of the event to send. 18004 * 18005 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 18006 */ 18007 public void sendAccessibilityEvent(View host, int eventType) { 18008 host.sendAccessibilityEventInternal(eventType); 18009 } 18010 18011 /** 18012 * Performs the specified accessibility action on the view. For 18013 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 18014 * <p> 18015 * The default implementation behaves as 18016 * {@link View#performAccessibilityAction(int, Bundle) 18017 * View#performAccessibilityAction(int, Bundle)} for the case of 18018 * no accessibility delegate been set. 18019 * </p> 18020 * 18021 * @param action The action to perform. 18022 * @return Whether the action was performed. 18023 * 18024 * @see View#performAccessibilityAction(int, Bundle) 18025 * View#performAccessibilityAction(int, Bundle) 18026 */ 18027 public boolean performAccessibilityAction(View host, int action, Bundle args) { 18028 return host.performAccessibilityActionInternal(action, args); 18029 } 18030 18031 /** 18032 * Sends an accessibility event. This method behaves exactly as 18033 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 18034 * empty {@link AccessibilityEvent} and does not perform a check whether 18035 * accessibility is enabled. 18036 * <p> 18037 * The default implementation behaves as 18038 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18039 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 18040 * the case of no accessibility delegate been set. 18041 * </p> 18042 * 18043 * @param host The View hosting the delegate. 18044 * @param event The event to send. 18045 * 18046 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18047 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18048 */ 18049 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 18050 host.sendAccessibilityEventUncheckedInternal(event); 18051 } 18052 18053 /** 18054 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 18055 * to its children for adding their text content to the event. 18056 * <p> 18057 * The default implementation behaves as 18058 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18059 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 18060 * the case of no accessibility delegate been set. 18061 * </p> 18062 * 18063 * @param host The View hosting the delegate. 18064 * @param event The event. 18065 * @return True if the event population was completed. 18066 * 18067 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18068 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18069 */ 18070 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18071 return host.dispatchPopulateAccessibilityEventInternal(event); 18072 } 18073 18074 /** 18075 * Gives a chance to the host View to populate the accessibility event with its 18076 * text content. 18077 * <p> 18078 * The default implementation behaves as 18079 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 18080 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 18081 * the case of no accessibility delegate been set. 18082 * </p> 18083 * 18084 * @param host The View hosting the delegate. 18085 * @param event The accessibility event which to populate. 18086 * 18087 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 18088 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 18089 */ 18090 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18091 host.onPopulateAccessibilityEventInternal(event); 18092 } 18093 18094 /** 18095 * Initializes an {@link AccessibilityEvent} with information about the 18096 * the host View which is the event source. 18097 * <p> 18098 * The default implementation behaves as 18099 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 18100 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 18101 * the case of no accessibility delegate been set. 18102 * </p> 18103 * 18104 * @param host The View hosting the delegate. 18105 * @param event The event to initialize. 18106 * 18107 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 18108 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 18109 */ 18110 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 18111 host.onInitializeAccessibilityEventInternal(event); 18112 } 18113 18114 /** 18115 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 18116 * <p> 18117 * The default implementation behaves as 18118 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18119 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 18120 * the case of no accessibility delegate been set. 18121 * </p> 18122 * 18123 * @param host The View hosting the delegate. 18124 * @param info The instance to initialize. 18125 * 18126 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18127 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18128 */ 18129 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 18130 host.onInitializeAccessibilityNodeInfoInternal(info); 18131 } 18132 18133 /** 18134 * Called when a child of the host View has requested sending an 18135 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 18136 * to augment the event. 18137 * <p> 18138 * The default implementation behaves as 18139 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18140 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 18141 * the case of no accessibility delegate been set. 18142 * </p> 18143 * 18144 * @param host The View hosting the delegate. 18145 * @param child The child which requests sending the event. 18146 * @param event The event to be sent. 18147 * @return True if the event should be sent 18148 * 18149 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18150 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18151 */ 18152 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 18153 AccessibilityEvent event) { 18154 return host.onRequestSendAccessibilityEventInternal(child, event); 18155 } 18156 18157 /** 18158 * Gets the provider for managing a virtual view hierarchy rooted at this View 18159 * and reported to {@link android.accessibilityservice.AccessibilityService}s 18160 * that explore the window content. 18161 * <p> 18162 * The default implementation behaves as 18163 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 18164 * the case of no accessibility delegate been set. 18165 * </p> 18166 * 18167 * @return The provider. 18168 * 18169 * @see AccessibilityNodeProvider 18170 */ 18171 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 18172 return null; 18173 } 18174 } 18175 18176 private class MatchIdPredicate implements Predicate<View> { 18177 public int mId; 18178 18179 @Override 18180 public boolean apply(View view) { 18181 return (view.mID == mId); 18182 } 18183 } 18184 18185 private class MatchLabelForPredicate implements Predicate<View> { 18186 private int mLabeledId; 18187 18188 @Override 18189 public boolean apply(View view) { 18190 return (view.mLabelForId == mLabeledId); 18191 } 18192 } 18193 18194 /** 18195 * Dump all private flags in readable format, useful for documentation and 18196 * sanity checking. 18197 */ 18198 private static void dumpFlags() { 18199 final HashMap<String, String> found = Maps.newHashMap(); 18200 try { 18201 for (Field field : View.class.getDeclaredFields()) { 18202 final int modifiers = field.getModifiers(); 18203 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 18204 if (field.getType().equals(int.class)) { 18205 final int value = field.getInt(null); 18206 dumpFlag(found, field.getName(), value); 18207 } else if (field.getType().equals(int[].class)) { 18208 final int[] values = (int[]) field.get(null); 18209 for (int i = 0; i < values.length; i++) { 18210 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 18211 } 18212 } 18213 } 18214 } 18215 } catch (IllegalAccessException e) { 18216 throw new RuntimeException(e); 18217 } 18218 18219 final ArrayList<String> keys = Lists.newArrayList(); 18220 keys.addAll(found.keySet()); 18221 Collections.sort(keys); 18222 for (String key : keys) { 18223 Log.d(VIEW_LOG_TAG, found.get(key)); 18224 } 18225 } 18226 18227 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 18228 // Sort flags by prefix, then by bits, always keeping unique keys 18229 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 18230 final int prefix = name.indexOf('_'); 18231 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 18232 final String output = bits + " " + name; 18233 found.put(key, output); 18234 } 18235} 18236