View.java revision 26cab31d784c44a2e2605ec3478562f9e6ffd99d
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.animation.AnimatorInflater; 20import android.animation.RevealAnimator; 21import android.animation.StateListAnimator; 22import android.animation.ValueAnimator; 23import android.annotation.IntDef; 24import android.annotation.NonNull; 25import android.annotation.Nullable; 26import android.content.ClipData; 27import android.content.Context; 28import android.content.res.ColorStateList; 29import android.content.res.Configuration; 30import android.content.res.Resources; 31import android.content.res.TypedArray; 32import android.graphics.Bitmap; 33import android.graphics.Canvas; 34import android.graphics.Insets; 35import android.graphics.Interpolator; 36import android.graphics.LinearGradient; 37import android.graphics.Matrix; 38import android.graphics.Outline; 39import android.graphics.Paint; 40import android.graphics.PixelFormat; 41import android.graphics.Point; 42import android.graphics.PorterDuff; 43import android.graphics.PorterDuffXfermode; 44import android.graphics.Rect; 45import android.graphics.RectF; 46import android.graphics.Region; 47import android.graphics.Shader; 48import android.graphics.drawable.ColorDrawable; 49import android.graphics.drawable.Drawable; 50import android.hardware.display.DisplayManagerGlobal; 51import android.os.Bundle; 52import android.os.Handler; 53import android.os.IBinder; 54import android.os.Parcel; 55import android.os.Parcelable; 56import android.os.RemoteException; 57import android.os.SystemClock; 58import android.os.SystemProperties; 59import android.text.TextUtils; 60import android.util.AttributeSet; 61import android.util.FloatProperty; 62import android.util.LayoutDirection; 63import android.util.Log; 64import android.util.LongSparseLongArray; 65import android.util.Pools.SynchronizedPool; 66import android.util.Property; 67import android.util.SparseArray; 68import android.util.SuperNotCalledException; 69import android.util.TypedValue; 70import android.view.ContextMenu.ContextMenuInfo; 71import android.view.AccessibilityIterators.TextSegmentIterator; 72import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 73import android.view.AccessibilityIterators.WordTextSegmentIterator; 74import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 75import android.view.accessibility.AccessibilityEvent; 76import android.view.accessibility.AccessibilityEventSource; 77import android.view.accessibility.AccessibilityManager; 78import android.view.accessibility.AccessibilityNodeInfo; 79import android.view.accessibility.AccessibilityNodeProvider; 80import android.view.animation.Animation; 81import android.view.animation.AnimationUtils; 82import android.view.animation.Transformation; 83import android.view.inputmethod.EditorInfo; 84import android.view.inputmethod.InputConnection; 85import android.view.inputmethod.InputMethodManager; 86import android.widget.ScrollBarDrawable; 87 88import static android.os.Build.VERSION_CODES.*; 89import static java.lang.Math.max; 90 91import com.android.internal.R; 92import com.android.internal.util.Predicate; 93import com.android.internal.view.menu.MenuBuilder; 94 95import com.google.android.collect.Lists; 96import com.google.android.collect.Maps; 97 98import java.lang.annotation.Retention; 99import java.lang.annotation.RetentionPolicy; 100import java.lang.ref.WeakReference; 101import java.lang.reflect.Field; 102import java.lang.reflect.InvocationTargetException; 103import java.lang.reflect.Method; 104import java.lang.reflect.Modifier; 105import java.util.ArrayList; 106import java.util.Arrays; 107import java.util.Collections; 108import java.util.HashMap; 109import java.util.List; 110import java.util.Locale; 111import java.util.Map; 112import java.util.concurrent.CopyOnWriteArrayList; 113import java.util.concurrent.atomic.AtomicInteger; 114 115/** 116 * <p> 117 * This class represents the basic building block for user interface components. A View 118 * occupies a rectangular area on the screen and is responsible for drawing and 119 * event handling. View is the base class for <em>widgets</em>, which are 120 * used to create interactive UI components (buttons, text fields, etc.). The 121 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 122 * are invisible containers that hold other Views (or other ViewGroups) and define 123 * their layout properties. 124 * </p> 125 * 126 * <div class="special reference"> 127 * <h3>Developer Guides</h3> 128 * <p>For information about using this class to develop your application's user interface, 129 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 130 * </div> 131 * 132 * <a name="Using"></a> 133 * <h3>Using Views</h3> 134 * <p> 135 * All of the views in a window are arranged in a single tree. You can add views 136 * either from code or by specifying a tree of views in one or more XML layout 137 * files. There are many specialized subclasses of views that act as controls or 138 * are capable of displaying text, images, or other content. 139 * </p> 140 * <p> 141 * Once you have created a tree of views, there are typically a few types of 142 * common operations you may wish to perform: 143 * <ul> 144 * <li><strong>Set properties:</strong> for example setting the text of a 145 * {@link android.widget.TextView}. The available properties and the methods 146 * that set them will vary among the different subclasses of views. Note that 147 * properties that are known at build time can be set in the XML layout 148 * files.</li> 149 * <li><strong>Set focus:</strong> The framework will handled moving focus in 150 * response to user input. To force focus to a specific view, call 151 * {@link #requestFocus}.</li> 152 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 153 * that will be notified when something interesting happens to the view. For 154 * example, all views will let you set a listener to be notified when the view 155 * gains or loses focus. You can register such a listener using 156 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 157 * Other view subclasses offer more specialized listeners. For example, a Button 158 * exposes a listener to notify clients when the button is clicked.</li> 159 * <li><strong>Set visibility:</strong> You can hide or show views using 160 * {@link #setVisibility(int)}.</li> 161 * </ul> 162 * </p> 163 * <p><em> 164 * Note: The Android framework is responsible for measuring, laying out and 165 * drawing views. You should not call methods that perform these actions on 166 * views yourself unless you are actually implementing a 167 * {@link android.view.ViewGroup}. 168 * </em></p> 169 * 170 * <a name="Lifecycle"></a> 171 * <h3>Implementing a Custom View</h3> 172 * 173 * <p> 174 * To implement a custom view, you will usually begin by providing overrides for 175 * some of the standard methods that the framework calls on all views. You do 176 * not need to override all of these methods. In fact, you can start by just 177 * overriding {@link #onDraw(android.graphics.Canvas)}. 178 * <table border="2" width="85%" align="center" cellpadding="5"> 179 * <thead> 180 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 181 * </thead> 182 * 183 * <tbody> 184 * <tr> 185 * <td rowspan="2">Creation</td> 186 * <td>Constructors</td> 187 * <td>There is a form of the constructor that are called when the view 188 * is created from code and a form that is called when the view is 189 * inflated from a layout file. The second form should parse and apply 190 * any attributes defined in the layout file. 191 * </td> 192 * </tr> 193 * <tr> 194 * <td><code>{@link #onFinishInflate()}</code></td> 195 * <td>Called after a view and all of its children has been inflated 196 * from XML.</td> 197 * </tr> 198 * 199 * <tr> 200 * <td rowspan="3">Layout</td> 201 * <td><code>{@link #onMeasure(int, int)}</code></td> 202 * <td>Called to determine the size requirements for this view and all 203 * of its children. 204 * </td> 205 * </tr> 206 * <tr> 207 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 208 * <td>Called when this view should assign a size and position to all 209 * of its children. 210 * </td> 211 * </tr> 212 * <tr> 213 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 214 * <td>Called when the size of this view has changed. 215 * </td> 216 * </tr> 217 * 218 * <tr> 219 * <td>Drawing</td> 220 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 221 * <td>Called when the view should render its content. 222 * </td> 223 * </tr> 224 * 225 * <tr> 226 * <td rowspan="4">Event processing</td> 227 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 228 * <td>Called when a new hardware key event occurs. 229 * </td> 230 * </tr> 231 * <tr> 232 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 233 * <td>Called when a hardware key up event occurs. 234 * </td> 235 * </tr> 236 * <tr> 237 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 238 * <td>Called when a trackball motion event occurs. 239 * </td> 240 * </tr> 241 * <tr> 242 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 243 * <td>Called when a touch screen motion event occurs. 244 * </td> 245 * </tr> 246 * 247 * <tr> 248 * <td rowspan="2">Focus</td> 249 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 250 * <td>Called when the view gains or loses focus. 251 * </td> 252 * </tr> 253 * 254 * <tr> 255 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 256 * <td>Called when the window containing the view gains or loses focus. 257 * </td> 258 * </tr> 259 * 260 * <tr> 261 * <td rowspan="3">Attaching</td> 262 * <td><code>{@link #onAttachedToWindow()}</code></td> 263 * <td>Called when the view is attached to a window. 264 * </td> 265 * </tr> 266 * 267 * <tr> 268 * <td><code>{@link #onDetachedFromWindow}</code></td> 269 * <td>Called when the view is detached from its window. 270 * </td> 271 * </tr> 272 * 273 * <tr> 274 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 275 * <td>Called when the visibility of the window containing the view 276 * has changed. 277 * </td> 278 * </tr> 279 * </tbody> 280 * 281 * </table> 282 * </p> 283 * 284 * <a name="IDs"></a> 285 * <h3>IDs</h3> 286 * Views may have an integer id associated with them. These ids are typically 287 * assigned in the layout XML files, and are used to find specific views within 288 * the view tree. A common pattern is to: 289 * <ul> 290 * <li>Define a Button in the layout file and assign it a unique ID. 291 * <pre> 292 * <Button 293 * android:id="@+id/my_button" 294 * android:layout_width="wrap_content" 295 * android:layout_height="wrap_content" 296 * android:text="@string/my_button_text"/> 297 * </pre></li> 298 * <li>From the onCreate method of an Activity, find the Button 299 * <pre class="prettyprint"> 300 * Button myButton = (Button) findViewById(R.id.my_button); 301 * </pre></li> 302 * </ul> 303 * <p> 304 * View IDs need not be unique throughout the tree, but it is good practice to 305 * ensure that they are at least unique within the part of the tree you are 306 * searching. 307 * </p> 308 * 309 * <a name="Position"></a> 310 * <h3>Position</h3> 311 * <p> 312 * The geometry of a view is that of a rectangle. A view has a location, 313 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 314 * two dimensions, expressed as a width and a height. The unit for location 315 * and dimensions is the pixel. 316 * </p> 317 * 318 * <p> 319 * It is possible to retrieve the location of a view by invoking the methods 320 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 321 * coordinate of the rectangle representing the view. The latter returns the 322 * top, or Y, coordinate of the rectangle representing the view. These methods 323 * both return the location of the view relative to its parent. For instance, 324 * when getLeft() returns 20, that means the view is located 20 pixels to the 325 * right of the left edge of its direct parent. 326 * </p> 327 * 328 * <p> 329 * In addition, several convenience methods are offered to avoid unnecessary 330 * computations, namely {@link #getRight()} and {@link #getBottom()}. 331 * These methods return the coordinates of the right and bottom edges of the 332 * rectangle representing the view. For instance, calling {@link #getRight()} 333 * is similar to the following computation: <code>getLeft() + getWidth()</code> 334 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 335 * </p> 336 * 337 * <a name="SizePaddingMargins"></a> 338 * <h3>Size, padding and margins</h3> 339 * <p> 340 * The size of a view is expressed with a width and a height. A view actually 341 * possess two pairs of width and height values. 342 * </p> 343 * 344 * <p> 345 * The first pair is known as <em>measured width</em> and 346 * <em>measured height</em>. These dimensions define how big a view wants to be 347 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 348 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 349 * and {@link #getMeasuredHeight()}. 350 * </p> 351 * 352 * <p> 353 * The second pair is simply known as <em>width</em> and <em>height</em>, or 354 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 355 * dimensions define the actual size of the view on screen, at drawing time and 356 * after layout. These values may, but do not have to, be different from the 357 * measured width and height. The width and height can be obtained by calling 358 * {@link #getWidth()} and {@link #getHeight()}. 359 * </p> 360 * 361 * <p> 362 * To measure its dimensions, a view takes into account its padding. The padding 363 * is expressed in pixels for the left, top, right and bottom parts of the view. 364 * Padding can be used to offset the content of the view by a specific amount of 365 * pixels. For instance, a left padding of 2 will push the view's content by 366 * 2 pixels to the right of the left edge. Padding can be set using the 367 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 368 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 369 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 370 * {@link #getPaddingEnd()}. 371 * </p> 372 * 373 * <p> 374 * Even though a view can define a padding, it does not provide any support for 375 * margins. However, view groups provide such a support. Refer to 376 * {@link android.view.ViewGroup} and 377 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 378 * </p> 379 * 380 * <a name="Layout"></a> 381 * <h3>Layout</h3> 382 * <p> 383 * Layout is a two pass process: a measure pass and a layout pass. The measuring 384 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 385 * of the view tree. Each view pushes dimension specifications down the tree 386 * during the recursion. At the end of the measure pass, every view has stored 387 * its measurements. The second pass happens in 388 * {@link #layout(int,int,int,int)} and is also top-down. During 389 * this pass each parent is responsible for positioning all of its children 390 * using the sizes computed in the measure pass. 391 * </p> 392 * 393 * <p> 394 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 395 * {@link #getMeasuredHeight()} values must be set, along with those for all of 396 * that view's descendants. A view's measured width and measured height values 397 * must respect the constraints imposed by the view's parents. This guarantees 398 * that at the end of the measure pass, all parents accept all of their 399 * children's measurements. A parent view may call measure() more than once on 400 * its children. For example, the parent may measure each child once with 401 * unspecified dimensions to find out how big they want to be, then call 402 * measure() on them again with actual numbers if the sum of all the children's 403 * unconstrained sizes is too big or too small. 404 * </p> 405 * 406 * <p> 407 * The measure pass uses two classes to communicate dimensions. The 408 * {@link MeasureSpec} class is used by views to tell their parents how they 409 * want to be measured and positioned. The base LayoutParams class just 410 * describes how big the view wants to be for both width and height. For each 411 * dimension, it can specify one of: 412 * <ul> 413 * <li> an exact number 414 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 415 * (minus padding) 416 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 417 * enclose its content (plus padding). 418 * </ul> 419 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 420 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 421 * an X and Y value. 422 * </p> 423 * 424 * <p> 425 * MeasureSpecs are used to push requirements down the tree from parent to 426 * child. A MeasureSpec can be in one of three modes: 427 * <ul> 428 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 429 * of a child view. For example, a LinearLayout may call measure() on its child 430 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 431 * tall the child view wants to be given a width of 240 pixels. 432 * <li>EXACTLY: This is used by the parent to impose an exact size on the 433 * child. The child must use this size, and guarantee that all of its 434 * descendants will fit within this size. 435 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 436 * child. The child must guarantee that it and all of its descendants will fit 437 * within this size. 438 * </ul> 439 * </p> 440 * 441 * <p> 442 * To intiate a layout, call {@link #requestLayout}. This method is typically 443 * called by a view on itself when it believes that is can no longer fit within 444 * its current bounds. 445 * </p> 446 * 447 * <a name="Drawing"></a> 448 * <h3>Drawing</h3> 449 * <p> 450 * Drawing is handled by walking the tree and rendering each view that 451 * intersects the invalid region. Because the tree is traversed in-order, 452 * this means that parents will draw before (i.e., behind) their children, with 453 * siblings drawn in the order they appear in the tree. 454 * If you set a background drawable for a View, then the View will draw it for you 455 * before calling back to its <code>onDraw()</code> method. 456 * </p> 457 * 458 * <p> 459 * Note that the framework will not draw views that are not in the invalid region. 460 * </p> 461 * 462 * <p> 463 * To force a view to draw, call {@link #invalidate()}. 464 * </p> 465 * 466 * <a name="EventHandlingThreading"></a> 467 * <h3>Event Handling and Threading</h3> 468 * <p> 469 * The basic cycle of a view is as follows: 470 * <ol> 471 * <li>An event comes in and is dispatched to the appropriate view. The view 472 * handles the event and notifies any listeners.</li> 473 * <li>If in the course of processing the event, the view's bounds may need 474 * to be changed, the view will call {@link #requestLayout()}.</li> 475 * <li>Similarly, if in the course of processing the event the view's appearance 476 * may need to be changed, the view will call {@link #invalidate()}.</li> 477 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 478 * the framework will take care of measuring, laying out, and drawing the tree 479 * as appropriate.</li> 480 * </ol> 481 * </p> 482 * 483 * <p><em>Note: The entire view tree is single threaded. You must always be on 484 * the UI thread when calling any method on any view.</em> 485 * If you are doing work on other threads and want to update the state of a view 486 * from that thread, you should use a {@link Handler}. 487 * </p> 488 * 489 * <a name="FocusHandling"></a> 490 * <h3>Focus Handling</h3> 491 * <p> 492 * The framework will handle routine focus movement in response to user input. 493 * This includes changing the focus as views are removed or hidden, or as new 494 * views become available. Views indicate their willingness to take focus 495 * through the {@link #isFocusable} method. To change whether a view can take 496 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 497 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 498 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 499 * </p> 500 * <p> 501 * Focus movement is based on an algorithm which finds the nearest neighbor in a 502 * given direction. In rare cases, the default algorithm may not match the 503 * intended behavior of the developer. In these situations, you can provide 504 * explicit overrides by using these XML attributes in the layout file: 505 * <pre> 506 * nextFocusDown 507 * nextFocusLeft 508 * nextFocusRight 509 * nextFocusUp 510 * </pre> 511 * </p> 512 * 513 * 514 * <p> 515 * To get a particular view to take focus, call {@link #requestFocus()}. 516 * </p> 517 * 518 * <a name="TouchMode"></a> 519 * <h3>Touch Mode</h3> 520 * <p> 521 * When a user is navigating a user interface via directional keys such as a D-pad, it is 522 * necessary to give focus to actionable items such as buttons so the user can see 523 * what will take input. If the device has touch capabilities, however, and the user 524 * begins interacting with the interface by touching it, it is no longer necessary to 525 * always highlight, or give focus to, a particular view. This motivates a mode 526 * for interaction named 'touch mode'. 527 * </p> 528 * <p> 529 * For a touch capable device, once the user touches the screen, the device 530 * will enter touch mode. From this point onward, only views for which 531 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 532 * Other views that are touchable, like buttons, will not take focus when touched; they will 533 * only fire the on click listeners. 534 * </p> 535 * <p> 536 * Any time a user hits a directional key, such as a D-pad direction, the view device will 537 * exit touch mode, and find a view to take focus, so that the user may resume interacting 538 * with the user interface without touching the screen again. 539 * </p> 540 * <p> 541 * The touch mode state is maintained across {@link android.app.Activity}s. Call 542 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 543 * </p> 544 * 545 * <a name="Scrolling"></a> 546 * <h3>Scrolling</h3> 547 * <p> 548 * The framework provides basic support for views that wish to internally 549 * scroll their content. This includes keeping track of the X and Y scroll 550 * offset as well as mechanisms for drawing scrollbars. See 551 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 552 * {@link #awakenScrollBars()} for more details. 553 * </p> 554 * 555 * <a name="Tags"></a> 556 * <h3>Tags</h3> 557 * <p> 558 * Unlike IDs, tags are not used to identify views. Tags are essentially an 559 * extra piece of information that can be associated with a view. They are most 560 * often used as a convenience to store data related to views in the views 561 * themselves rather than by putting them in a separate structure. 562 * </p> 563 * 564 * <a name="Properties"></a> 565 * <h3>Properties</h3> 566 * <p> 567 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 568 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 569 * available both in the {@link Property} form as well as in similarly-named setter/getter 570 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 571 * be used to set persistent state associated with these rendering-related properties on the view. 572 * The properties and methods can also be used in conjunction with 573 * {@link android.animation.Animator Animator}-based animations, described more in the 574 * <a href="#Animation">Animation</a> section. 575 * </p> 576 * 577 * <a name="Animation"></a> 578 * <h3>Animation</h3> 579 * <p> 580 * Starting with Android 3.0, the preferred way of animating views is to use the 581 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 582 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 583 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 584 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 585 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 586 * makes animating these View properties particularly easy and efficient. 587 * </p> 588 * <p> 589 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 590 * You can attach an {@link Animation} object to a view using 591 * {@link #setAnimation(Animation)} or 592 * {@link #startAnimation(Animation)}. The animation can alter the scale, 593 * rotation, translation and alpha of a view over time. If the animation is 594 * attached to a view that has children, the animation will affect the entire 595 * subtree rooted by that node. When an animation is started, the framework will 596 * take care of redrawing the appropriate views until the animation completes. 597 * </p> 598 * 599 * <a name="Security"></a> 600 * <h3>Security</h3> 601 * <p> 602 * Sometimes it is essential that an application be able to verify that an action 603 * is being performed with the full knowledge and consent of the user, such as 604 * granting a permission request, making a purchase or clicking on an advertisement. 605 * Unfortunately, a malicious application could try to spoof the user into 606 * performing these actions, unaware, by concealing the intended purpose of the view. 607 * As a remedy, the framework offers a touch filtering mechanism that can be used to 608 * improve the security of views that provide access to sensitive functionality. 609 * </p><p> 610 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 611 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 612 * will discard touches that are received whenever the view's window is obscured by 613 * another visible window. As a result, the view will not receive touches whenever a 614 * toast, dialog or other window appears above the view's window. 615 * </p><p> 616 * For more fine-grained control over security, consider overriding the 617 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 618 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 619 * </p> 620 * 621 * @attr ref android.R.styleable#View_alpha 622 * @attr ref android.R.styleable#View_background 623 * @attr ref android.R.styleable#View_clickable 624 * @attr ref android.R.styleable#View_contentDescription 625 * @attr ref android.R.styleable#View_drawingCacheQuality 626 * @attr ref android.R.styleable#View_duplicateParentState 627 * @attr ref android.R.styleable#View_id 628 * @attr ref android.R.styleable#View_requiresFadingEdge 629 * @attr ref android.R.styleable#View_fadeScrollbars 630 * @attr ref android.R.styleable#View_fadingEdgeLength 631 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 632 * @attr ref android.R.styleable#View_fitsSystemWindows 633 * @attr ref android.R.styleable#View_isScrollContainer 634 * @attr ref android.R.styleable#View_focusable 635 * @attr ref android.R.styleable#View_focusableInTouchMode 636 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 637 * @attr ref android.R.styleable#View_keepScreenOn 638 * @attr ref android.R.styleable#View_layerType 639 * @attr ref android.R.styleable#View_layoutDirection 640 * @attr ref android.R.styleable#View_longClickable 641 * @attr ref android.R.styleable#View_minHeight 642 * @attr ref android.R.styleable#View_minWidth 643 * @attr ref android.R.styleable#View_nextFocusDown 644 * @attr ref android.R.styleable#View_nextFocusLeft 645 * @attr ref android.R.styleable#View_nextFocusRight 646 * @attr ref android.R.styleable#View_nextFocusUp 647 * @attr ref android.R.styleable#View_onClick 648 * @attr ref android.R.styleable#View_padding 649 * @attr ref android.R.styleable#View_paddingBottom 650 * @attr ref android.R.styleable#View_paddingLeft 651 * @attr ref android.R.styleable#View_paddingRight 652 * @attr ref android.R.styleable#View_paddingTop 653 * @attr ref android.R.styleable#View_paddingStart 654 * @attr ref android.R.styleable#View_paddingEnd 655 * @attr ref android.R.styleable#View_saveEnabled 656 * @attr ref android.R.styleable#View_rotation 657 * @attr ref android.R.styleable#View_rotationX 658 * @attr ref android.R.styleable#View_rotationY 659 * @attr ref android.R.styleable#View_scaleX 660 * @attr ref android.R.styleable#View_scaleY 661 * @attr ref android.R.styleable#View_scrollX 662 * @attr ref android.R.styleable#View_scrollY 663 * @attr ref android.R.styleable#View_scrollbarSize 664 * @attr ref android.R.styleable#View_scrollbarStyle 665 * @attr ref android.R.styleable#View_scrollbars 666 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 667 * @attr ref android.R.styleable#View_scrollbarFadeDuration 668 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 669 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 670 * @attr ref android.R.styleable#View_scrollbarThumbVertical 671 * @attr ref android.R.styleable#View_scrollbarTrackVertical 672 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 673 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 674 * @attr ref android.R.styleable#View_stateListAnimator 675 * @attr ref android.R.styleable#View_transitionName 676 * @attr ref android.R.styleable#View_soundEffectsEnabled 677 * @attr ref android.R.styleable#View_tag 678 * @attr ref android.R.styleable#View_textAlignment 679 * @attr ref android.R.styleable#View_textDirection 680 * @attr ref android.R.styleable#View_transformPivotX 681 * @attr ref android.R.styleable#View_transformPivotY 682 * @attr ref android.R.styleable#View_translationX 683 * @attr ref android.R.styleable#View_translationY 684 * @attr ref android.R.styleable#View_translationZ 685 * @attr ref android.R.styleable#View_visibility 686 * 687 * @see android.view.ViewGroup 688 */ 689public class View implements Drawable.Callback, KeyEvent.Callback, 690 AccessibilityEventSource { 691 private static final boolean DBG = false; 692 693 /** 694 * The logging tag used by this class with android.util.Log. 695 */ 696 protected static final String VIEW_LOG_TAG = "View"; 697 698 /** 699 * When set to true, apps will draw debugging information about their layouts. 700 * 701 * @hide 702 */ 703 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 704 705 /** 706 * Used to mark a View that has no ID. 707 */ 708 public static final int NO_ID = -1; 709 710 /** 711 * Signals that compatibility booleans have been initialized according to 712 * target SDK versions. 713 */ 714 private static boolean sCompatibilityDone = false; 715 716 /** 717 * Use the old (broken) way of building MeasureSpecs. 718 */ 719 private static boolean sUseBrokenMakeMeasureSpec = false; 720 721 /** 722 * Ignore any optimizations using the measure cache. 723 */ 724 private static boolean sIgnoreMeasureCache = false; 725 726 /** 727 * Ignore the clipBounds of this view for the children. 728 */ 729 static boolean sIgnoreClipBoundsForChildren = false; 730 731 /** 732 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 733 * calling setFlags. 734 */ 735 private static final int NOT_FOCUSABLE = 0x00000000; 736 737 /** 738 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 739 * setFlags. 740 */ 741 private static final int FOCUSABLE = 0x00000001; 742 743 /** 744 * Mask for use with setFlags indicating bits used for focus. 745 */ 746 private static final int FOCUSABLE_MASK = 0x00000001; 747 748 /** 749 * This view will adjust its padding to fit sytem windows (e.g. status bar) 750 */ 751 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 752 753 /** @hide */ 754 @IntDef({VISIBLE, INVISIBLE, GONE}) 755 @Retention(RetentionPolicy.SOURCE) 756 public @interface Visibility {} 757 758 /** 759 * This view is visible. 760 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 761 * android:visibility}. 762 */ 763 public static final int VISIBLE = 0x00000000; 764 765 /** 766 * This view is invisible, but it still takes up space for layout purposes. 767 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 768 * android:visibility}. 769 */ 770 public static final int INVISIBLE = 0x00000004; 771 772 /** 773 * This view is invisible, and it doesn't take any space for layout 774 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 775 * android:visibility}. 776 */ 777 public static final int GONE = 0x00000008; 778 779 /** 780 * Mask for use with setFlags indicating bits used for visibility. 781 * {@hide} 782 */ 783 static final int VISIBILITY_MASK = 0x0000000C; 784 785 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 786 787 /** 788 * This view is enabled. Interpretation varies by subclass. 789 * Use with ENABLED_MASK when calling setFlags. 790 * {@hide} 791 */ 792 static final int ENABLED = 0x00000000; 793 794 /** 795 * This view is disabled. Interpretation varies by subclass. 796 * Use with ENABLED_MASK when calling setFlags. 797 * {@hide} 798 */ 799 static final int DISABLED = 0x00000020; 800 801 /** 802 * Mask for use with setFlags indicating bits used for indicating whether 803 * this view is enabled 804 * {@hide} 805 */ 806 static final int ENABLED_MASK = 0x00000020; 807 808 /** 809 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 810 * called and further optimizations will be performed. It is okay to have 811 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 812 * {@hide} 813 */ 814 static final int WILL_NOT_DRAW = 0x00000080; 815 816 /** 817 * Mask for use with setFlags indicating bits used for indicating whether 818 * this view is will draw 819 * {@hide} 820 */ 821 static final int DRAW_MASK = 0x00000080; 822 823 /** 824 * <p>This view doesn't show scrollbars.</p> 825 * {@hide} 826 */ 827 static final int SCROLLBARS_NONE = 0x00000000; 828 829 /** 830 * <p>This view shows horizontal scrollbars.</p> 831 * {@hide} 832 */ 833 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 834 835 /** 836 * <p>This view shows vertical scrollbars.</p> 837 * {@hide} 838 */ 839 static final int SCROLLBARS_VERTICAL = 0x00000200; 840 841 /** 842 * <p>Mask for use with setFlags indicating bits used for indicating which 843 * scrollbars are enabled.</p> 844 * {@hide} 845 */ 846 static final int SCROLLBARS_MASK = 0x00000300; 847 848 /** 849 * Indicates that the view should filter touches when its window is obscured. 850 * Refer to the class comments for more information about this security feature. 851 * {@hide} 852 */ 853 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 854 855 /** 856 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 857 * that they are optional and should be skipped if the window has 858 * requested system UI flags that ignore those insets for layout. 859 */ 860 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 861 862 /** 863 * <p>This view doesn't show fading edges.</p> 864 * {@hide} 865 */ 866 static final int FADING_EDGE_NONE = 0x00000000; 867 868 /** 869 * <p>This view shows horizontal fading edges.</p> 870 * {@hide} 871 */ 872 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 873 874 /** 875 * <p>This view shows vertical fading edges.</p> 876 * {@hide} 877 */ 878 static final int FADING_EDGE_VERTICAL = 0x00002000; 879 880 /** 881 * <p>Mask for use with setFlags indicating bits used for indicating which 882 * fading edges are enabled.</p> 883 * {@hide} 884 */ 885 static final int FADING_EDGE_MASK = 0x00003000; 886 887 /** 888 * <p>Indicates this view can be clicked. When clickable, a View reacts 889 * to clicks by notifying the OnClickListener.<p> 890 * {@hide} 891 */ 892 static final int CLICKABLE = 0x00004000; 893 894 /** 895 * <p>Indicates this view is caching its drawing into a bitmap.</p> 896 * {@hide} 897 */ 898 static final int DRAWING_CACHE_ENABLED = 0x00008000; 899 900 /** 901 * <p>Indicates that no icicle should be saved for this view.<p> 902 * {@hide} 903 */ 904 static final int SAVE_DISABLED = 0x000010000; 905 906 /** 907 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 908 * property.</p> 909 * {@hide} 910 */ 911 static final int SAVE_DISABLED_MASK = 0x000010000; 912 913 /** 914 * <p>Indicates that no drawing cache should ever be created for this view.<p> 915 * {@hide} 916 */ 917 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 918 919 /** 920 * <p>Indicates this view can take / keep focus when int touch mode.</p> 921 * {@hide} 922 */ 923 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 924 925 /** @hide */ 926 @Retention(RetentionPolicy.SOURCE) 927 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 928 public @interface DrawingCacheQuality {} 929 930 /** 931 * <p>Enables low quality mode for the drawing cache.</p> 932 */ 933 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 934 935 /** 936 * <p>Enables high quality mode for the drawing cache.</p> 937 */ 938 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 939 940 /** 941 * <p>Enables automatic quality mode for the drawing cache.</p> 942 */ 943 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 944 945 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 946 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 947 }; 948 949 /** 950 * <p>Mask for use with setFlags indicating bits used for the cache 951 * quality property.</p> 952 * {@hide} 953 */ 954 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 955 956 /** 957 * <p> 958 * Indicates this view can be long clicked. When long clickable, a View 959 * reacts to long clicks by notifying the OnLongClickListener or showing a 960 * context menu. 961 * </p> 962 * {@hide} 963 */ 964 static final int LONG_CLICKABLE = 0x00200000; 965 966 /** 967 * <p>Indicates that this view gets its drawable states from its direct parent 968 * and ignores its original internal states.</p> 969 * 970 * @hide 971 */ 972 static final int DUPLICATE_PARENT_STATE = 0x00400000; 973 974 /** @hide */ 975 @IntDef({ 976 SCROLLBARS_INSIDE_OVERLAY, 977 SCROLLBARS_INSIDE_INSET, 978 SCROLLBARS_OUTSIDE_OVERLAY, 979 SCROLLBARS_OUTSIDE_INSET 980 }) 981 @Retention(RetentionPolicy.SOURCE) 982 public @interface ScrollBarStyle {} 983 984 /** 985 * The scrollbar style to display the scrollbars inside the content area, 986 * without increasing the padding. The scrollbars will be overlaid with 987 * translucency on the view's content. 988 */ 989 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 990 991 /** 992 * The scrollbar style to display the scrollbars inside the padded area, 993 * increasing the padding of the view. The scrollbars will not overlap the 994 * content area of the view. 995 */ 996 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 997 998 /** 999 * The scrollbar style to display the scrollbars at the edge of the view, 1000 * without increasing the padding. The scrollbars will be overlaid with 1001 * translucency. 1002 */ 1003 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1004 1005 /** 1006 * The scrollbar style to display the scrollbars at the edge of the view, 1007 * increasing the padding of the view. The scrollbars will only overlap the 1008 * background, if any. 1009 */ 1010 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1011 1012 /** 1013 * Mask to check if the scrollbar style is overlay or inset. 1014 * {@hide} 1015 */ 1016 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1017 1018 /** 1019 * Mask to check if the scrollbar style is inside or outside. 1020 * {@hide} 1021 */ 1022 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1023 1024 /** 1025 * Mask for scrollbar style. 1026 * {@hide} 1027 */ 1028 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1029 1030 /** 1031 * View flag indicating that the screen should remain on while the 1032 * window containing this view is visible to the user. This effectively 1033 * takes care of automatically setting the WindowManager's 1034 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1035 */ 1036 public static final int KEEP_SCREEN_ON = 0x04000000; 1037 1038 /** 1039 * View flag indicating whether this view should have sound effects enabled 1040 * for events such as clicking and touching. 1041 */ 1042 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1043 1044 /** 1045 * View flag indicating whether this view should have haptic feedback 1046 * enabled for events such as long presses. 1047 */ 1048 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1049 1050 /** 1051 * <p>Indicates that the view hierarchy should stop saving state when 1052 * it reaches this view. If state saving is initiated immediately at 1053 * the view, it will be allowed. 1054 * {@hide} 1055 */ 1056 static final int PARENT_SAVE_DISABLED = 0x20000000; 1057 1058 /** 1059 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1060 * {@hide} 1061 */ 1062 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1063 1064 /** @hide */ 1065 @IntDef(flag = true, 1066 value = { 1067 FOCUSABLES_ALL, 1068 FOCUSABLES_TOUCH_MODE 1069 }) 1070 @Retention(RetentionPolicy.SOURCE) 1071 public @interface FocusableMode {} 1072 1073 /** 1074 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1075 * should add all focusable Views regardless if they are focusable in touch mode. 1076 */ 1077 public static final int FOCUSABLES_ALL = 0x00000000; 1078 1079 /** 1080 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1081 * should add only Views focusable in touch mode. 1082 */ 1083 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1084 1085 /** @hide */ 1086 @IntDef({ 1087 FOCUS_BACKWARD, 1088 FOCUS_FORWARD, 1089 FOCUS_LEFT, 1090 FOCUS_UP, 1091 FOCUS_RIGHT, 1092 FOCUS_DOWN 1093 }) 1094 @Retention(RetentionPolicy.SOURCE) 1095 public @interface FocusDirection {} 1096 1097 /** @hide */ 1098 @IntDef({ 1099 FOCUS_LEFT, 1100 FOCUS_UP, 1101 FOCUS_RIGHT, 1102 FOCUS_DOWN 1103 }) 1104 @Retention(RetentionPolicy.SOURCE) 1105 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1106 1107 /** 1108 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1109 * item. 1110 */ 1111 public static final int FOCUS_BACKWARD = 0x00000001; 1112 1113 /** 1114 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1115 * item. 1116 */ 1117 public static final int FOCUS_FORWARD = 0x00000002; 1118 1119 /** 1120 * Use with {@link #focusSearch(int)}. Move focus to the left. 1121 */ 1122 public static final int FOCUS_LEFT = 0x00000011; 1123 1124 /** 1125 * Use with {@link #focusSearch(int)}. Move focus up. 1126 */ 1127 public static final int FOCUS_UP = 0x00000021; 1128 1129 /** 1130 * Use with {@link #focusSearch(int)}. Move focus to the right. 1131 */ 1132 public static final int FOCUS_RIGHT = 0x00000042; 1133 1134 /** 1135 * Use with {@link #focusSearch(int)}. Move focus down. 1136 */ 1137 public static final int FOCUS_DOWN = 0x00000082; 1138 1139 /** 1140 * Bits of {@link #getMeasuredWidthAndState()} and 1141 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1142 */ 1143 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1144 1145 /** 1146 * Bits of {@link #getMeasuredWidthAndState()} and 1147 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1148 */ 1149 public static final int MEASURED_STATE_MASK = 0xff000000; 1150 1151 /** 1152 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1153 * for functions that combine both width and height into a single int, 1154 * such as {@link #getMeasuredState()} and the childState argument of 1155 * {@link #resolveSizeAndState(int, int, int)}. 1156 */ 1157 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1158 1159 /** 1160 * Bit of {@link #getMeasuredWidthAndState()} and 1161 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1162 * is smaller that the space the view would like to have. 1163 */ 1164 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1165 1166 /** 1167 * Base View state sets 1168 */ 1169 // Singles 1170 /** 1171 * Indicates the view has no states set. States are used with 1172 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1173 * view depending on its state. 1174 * 1175 * @see android.graphics.drawable.Drawable 1176 * @see #getDrawableState() 1177 */ 1178 protected static final int[] EMPTY_STATE_SET; 1179 /** 1180 * Indicates the view is enabled. States are used with 1181 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1182 * view depending on its state. 1183 * 1184 * @see android.graphics.drawable.Drawable 1185 * @see #getDrawableState() 1186 */ 1187 protected static final int[] ENABLED_STATE_SET; 1188 /** 1189 * Indicates the view is focused. States are used with 1190 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1191 * view depending on its state. 1192 * 1193 * @see android.graphics.drawable.Drawable 1194 * @see #getDrawableState() 1195 */ 1196 protected static final int[] FOCUSED_STATE_SET; 1197 /** 1198 * Indicates the view is selected. States are used with 1199 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1200 * view depending on its state. 1201 * 1202 * @see android.graphics.drawable.Drawable 1203 * @see #getDrawableState() 1204 */ 1205 protected static final int[] SELECTED_STATE_SET; 1206 /** 1207 * Indicates the view is pressed. States are used with 1208 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1209 * view depending on its state. 1210 * 1211 * @see android.graphics.drawable.Drawable 1212 * @see #getDrawableState() 1213 */ 1214 protected static final int[] PRESSED_STATE_SET; 1215 /** 1216 * Indicates the view's window has focus. States are used with 1217 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1218 * view depending on its state. 1219 * 1220 * @see android.graphics.drawable.Drawable 1221 * @see #getDrawableState() 1222 */ 1223 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1224 // Doubles 1225 /** 1226 * Indicates the view is enabled and has the focus. 1227 * 1228 * @see #ENABLED_STATE_SET 1229 * @see #FOCUSED_STATE_SET 1230 */ 1231 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1232 /** 1233 * Indicates the view is enabled and selected. 1234 * 1235 * @see #ENABLED_STATE_SET 1236 * @see #SELECTED_STATE_SET 1237 */ 1238 protected static final int[] ENABLED_SELECTED_STATE_SET; 1239 /** 1240 * Indicates the view is enabled and that its window has focus. 1241 * 1242 * @see #ENABLED_STATE_SET 1243 * @see #WINDOW_FOCUSED_STATE_SET 1244 */ 1245 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1246 /** 1247 * Indicates the view is focused and selected. 1248 * 1249 * @see #FOCUSED_STATE_SET 1250 * @see #SELECTED_STATE_SET 1251 */ 1252 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1253 /** 1254 * Indicates the view has the focus and that its window has the focus. 1255 * 1256 * @see #FOCUSED_STATE_SET 1257 * @see #WINDOW_FOCUSED_STATE_SET 1258 */ 1259 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1260 /** 1261 * Indicates the view is selected and that its window has the focus. 1262 * 1263 * @see #SELECTED_STATE_SET 1264 * @see #WINDOW_FOCUSED_STATE_SET 1265 */ 1266 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1267 // Triples 1268 /** 1269 * Indicates the view is enabled, focused and selected. 1270 * 1271 * @see #ENABLED_STATE_SET 1272 * @see #FOCUSED_STATE_SET 1273 * @see #SELECTED_STATE_SET 1274 */ 1275 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1276 /** 1277 * Indicates the view is enabled, focused and its window has the focus. 1278 * 1279 * @see #ENABLED_STATE_SET 1280 * @see #FOCUSED_STATE_SET 1281 * @see #WINDOW_FOCUSED_STATE_SET 1282 */ 1283 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1284 /** 1285 * Indicates the view is enabled, selected and its window has the focus. 1286 * 1287 * @see #ENABLED_STATE_SET 1288 * @see #SELECTED_STATE_SET 1289 * @see #WINDOW_FOCUSED_STATE_SET 1290 */ 1291 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1292 /** 1293 * Indicates the view is focused, selected and its window has the focus. 1294 * 1295 * @see #FOCUSED_STATE_SET 1296 * @see #SELECTED_STATE_SET 1297 * @see #WINDOW_FOCUSED_STATE_SET 1298 */ 1299 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1300 /** 1301 * Indicates the view is enabled, focused, selected and its window 1302 * has the focus. 1303 * 1304 * @see #ENABLED_STATE_SET 1305 * @see #FOCUSED_STATE_SET 1306 * @see #SELECTED_STATE_SET 1307 * @see #WINDOW_FOCUSED_STATE_SET 1308 */ 1309 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1310 /** 1311 * Indicates the view is pressed and its window has the focus. 1312 * 1313 * @see #PRESSED_STATE_SET 1314 * @see #WINDOW_FOCUSED_STATE_SET 1315 */ 1316 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1317 /** 1318 * Indicates the view is pressed and selected. 1319 * 1320 * @see #PRESSED_STATE_SET 1321 * @see #SELECTED_STATE_SET 1322 */ 1323 protected static final int[] PRESSED_SELECTED_STATE_SET; 1324 /** 1325 * Indicates the view is pressed, selected and its window has the focus. 1326 * 1327 * @see #PRESSED_STATE_SET 1328 * @see #SELECTED_STATE_SET 1329 * @see #WINDOW_FOCUSED_STATE_SET 1330 */ 1331 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1332 /** 1333 * Indicates the view is pressed and focused. 1334 * 1335 * @see #PRESSED_STATE_SET 1336 * @see #FOCUSED_STATE_SET 1337 */ 1338 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1339 /** 1340 * Indicates the view is pressed, focused and its window has the focus. 1341 * 1342 * @see #PRESSED_STATE_SET 1343 * @see #FOCUSED_STATE_SET 1344 * @see #WINDOW_FOCUSED_STATE_SET 1345 */ 1346 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1347 /** 1348 * Indicates the view is pressed, focused and selected. 1349 * 1350 * @see #PRESSED_STATE_SET 1351 * @see #SELECTED_STATE_SET 1352 * @see #FOCUSED_STATE_SET 1353 */ 1354 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1355 /** 1356 * Indicates the view is pressed, focused, selected and its window has the focus. 1357 * 1358 * @see #PRESSED_STATE_SET 1359 * @see #FOCUSED_STATE_SET 1360 * @see #SELECTED_STATE_SET 1361 * @see #WINDOW_FOCUSED_STATE_SET 1362 */ 1363 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1364 /** 1365 * Indicates the view is pressed and enabled. 1366 * 1367 * @see #PRESSED_STATE_SET 1368 * @see #ENABLED_STATE_SET 1369 */ 1370 protected static final int[] PRESSED_ENABLED_STATE_SET; 1371 /** 1372 * Indicates the view is pressed, enabled and its window has the focus. 1373 * 1374 * @see #PRESSED_STATE_SET 1375 * @see #ENABLED_STATE_SET 1376 * @see #WINDOW_FOCUSED_STATE_SET 1377 */ 1378 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1379 /** 1380 * Indicates the view is pressed, enabled and selected. 1381 * 1382 * @see #PRESSED_STATE_SET 1383 * @see #ENABLED_STATE_SET 1384 * @see #SELECTED_STATE_SET 1385 */ 1386 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1387 /** 1388 * Indicates the view is pressed, enabled, selected and its window has the 1389 * focus. 1390 * 1391 * @see #PRESSED_STATE_SET 1392 * @see #ENABLED_STATE_SET 1393 * @see #SELECTED_STATE_SET 1394 * @see #WINDOW_FOCUSED_STATE_SET 1395 */ 1396 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1397 /** 1398 * Indicates the view is pressed, enabled and focused. 1399 * 1400 * @see #PRESSED_STATE_SET 1401 * @see #ENABLED_STATE_SET 1402 * @see #FOCUSED_STATE_SET 1403 */ 1404 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1405 /** 1406 * Indicates the view is pressed, enabled, focused and its window has the 1407 * focus. 1408 * 1409 * @see #PRESSED_STATE_SET 1410 * @see #ENABLED_STATE_SET 1411 * @see #FOCUSED_STATE_SET 1412 * @see #WINDOW_FOCUSED_STATE_SET 1413 */ 1414 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1415 /** 1416 * Indicates the view is pressed, enabled, focused and selected. 1417 * 1418 * @see #PRESSED_STATE_SET 1419 * @see #ENABLED_STATE_SET 1420 * @see #SELECTED_STATE_SET 1421 * @see #FOCUSED_STATE_SET 1422 */ 1423 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1424 /** 1425 * Indicates the view is pressed, enabled, focused, selected and its window 1426 * has the focus. 1427 * 1428 * @see #PRESSED_STATE_SET 1429 * @see #ENABLED_STATE_SET 1430 * @see #SELECTED_STATE_SET 1431 * @see #FOCUSED_STATE_SET 1432 * @see #WINDOW_FOCUSED_STATE_SET 1433 */ 1434 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1435 1436 /** 1437 * The order here is very important to {@link #getDrawableState()} 1438 */ 1439 private static final int[][] VIEW_STATE_SETS; 1440 1441 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1442 static final int VIEW_STATE_SELECTED = 1 << 1; 1443 static final int VIEW_STATE_FOCUSED = 1 << 2; 1444 static final int VIEW_STATE_ENABLED = 1 << 3; 1445 static final int VIEW_STATE_PRESSED = 1 << 4; 1446 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1447 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1448 static final int VIEW_STATE_HOVERED = 1 << 7; 1449 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1450 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1451 1452 static final int[] VIEW_STATE_IDS = new int[] { 1453 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1454 R.attr.state_selected, VIEW_STATE_SELECTED, 1455 R.attr.state_focused, VIEW_STATE_FOCUSED, 1456 R.attr.state_enabled, VIEW_STATE_ENABLED, 1457 R.attr.state_pressed, VIEW_STATE_PRESSED, 1458 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1459 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1460 R.attr.state_hovered, VIEW_STATE_HOVERED, 1461 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1462 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1463 }; 1464 1465 static { 1466 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1467 throw new IllegalStateException( 1468 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1469 } 1470 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1471 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1472 int viewState = R.styleable.ViewDrawableStates[i]; 1473 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1474 if (VIEW_STATE_IDS[j] == viewState) { 1475 orderedIds[i * 2] = viewState; 1476 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1477 } 1478 } 1479 } 1480 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1481 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1482 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1483 int numBits = Integer.bitCount(i); 1484 int[] set = new int[numBits]; 1485 int pos = 0; 1486 for (int j = 0; j < orderedIds.length; j += 2) { 1487 if ((i & orderedIds[j+1]) != 0) { 1488 set[pos++] = orderedIds[j]; 1489 } 1490 } 1491 VIEW_STATE_SETS[i] = set; 1492 } 1493 1494 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1495 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1496 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1497 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1498 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1499 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1500 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1501 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1502 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1503 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1504 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1505 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1506 | VIEW_STATE_FOCUSED]; 1507 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1508 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1509 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1510 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1511 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1512 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1513 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1514 | VIEW_STATE_ENABLED]; 1515 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1516 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1517 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1518 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1519 | VIEW_STATE_ENABLED]; 1520 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1521 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1522 | VIEW_STATE_ENABLED]; 1523 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1524 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1525 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1526 1527 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1528 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1529 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1530 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1531 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1532 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1533 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1534 | VIEW_STATE_PRESSED]; 1535 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1536 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1537 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1538 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1539 | VIEW_STATE_PRESSED]; 1540 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1541 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1542 | VIEW_STATE_PRESSED]; 1543 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1544 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1545 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1546 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1547 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1548 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1549 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1550 | VIEW_STATE_PRESSED]; 1551 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1552 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1553 | VIEW_STATE_PRESSED]; 1554 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1555 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1556 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1557 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1558 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1559 | VIEW_STATE_PRESSED]; 1560 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1561 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1562 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1563 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1564 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1565 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1566 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1567 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1568 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1569 | VIEW_STATE_PRESSED]; 1570 } 1571 1572 /** 1573 * Accessibility event types that are dispatched for text population. 1574 */ 1575 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1576 AccessibilityEvent.TYPE_VIEW_CLICKED 1577 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1578 | AccessibilityEvent.TYPE_VIEW_SELECTED 1579 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1580 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1581 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1582 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1583 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1584 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1585 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1586 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1587 1588 /** 1589 * Temporary Rect currently for use in setBackground(). This will probably 1590 * be extended in the future to hold our own class with more than just 1591 * a Rect. :) 1592 */ 1593 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1594 1595 /** 1596 * Map used to store views' tags. 1597 */ 1598 private SparseArray<Object> mKeyedTags; 1599 1600 /** 1601 * The next available accessibility id. 1602 */ 1603 private static int sNextAccessibilityViewId; 1604 1605 /** 1606 * The animation currently associated with this view. 1607 * @hide 1608 */ 1609 protected Animation mCurrentAnimation = null; 1610 1611 /** 1612 * Width as measured during measure pass. 1613 * {@hide} 1614 */ 1615 @ViewDebug.ExportedProperty(category = "measurement") 1616 int mMeasuredWidth; 1617 1618 /** 1619 * Height as measured during measure pass. 1620 * {@hide} 1621 */ 1622 @ViewDebug.ExportedProperty(category = "measurement") 1623 int mMeasuredHeight; 1624 1625 /** 1626 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1627 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1628 * its display list. This flag, used only when hw accelerated, allows us to clear the 1629 * flag while retaining this information until it's needed (at getDisplayList() time and 1630 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1631 * 1632 * {@hide} 1633 */ 1634 boolean mRecreateDisplayList = false; 1635 1636 /** 1637 * The view's identifier. 1638 * {@hide} 1639 * 1640 * @see #setId(int) 1641 * @see #getId() 1642 */ 1643 @ViewDebug.ExportedProperty(resolveId = true) 1644 int mID = NO_ID; 1645 1646 /** 1647 * The stable ID of this view for accessibility purposes. 1648 */ 1649 int mAccessibilityViewId = NO_ID; 1650 1651 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1652 1653 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1654 1655 /** 1656 * The view's tag. 1657 * {@hide} 1658 * 1659 * @see #setTag(Object) 1660 * @see #getTag() 1661 */ 1662 protected Object mTag = null; 1663 1664 // for mPrivateFlags: 1665 /** {@hide} */ 1666 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1667 /** {@hide} */ 1668 static final int PFLAG_FOCUSED = 0x00000002; 1669 /** {@hide} */ 1670 static final int PFLAG_SELECTED = 0x00000004; 1671 /** {@hide} */ 1672 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1673 /** {@hide} */ 1674 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1675 /** {@hide} */ 1676 static final int PFLAG_DRAWN = 0x00000020; 1677 /** 1678 * When this flag is set, this view is running an animation on behalf of its 1679 * children and should therefore not cancel invalidate requests, even if they 1680 * lie outside of this view's bounds. 1681 * 1682 * {@hide} 1683 */ 1684 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1685 /** {@hide} */ 1686 static final int PFLAG_SKIP_DRAW = 0x00000080; 1687 /** {@hide} */ 1688 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1689 /** {@hide} */ 1690 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1691 /** {@hide} */ 1692 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1693 /** {@hide} */ 1694 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1695 /** {@hide} */ 1696 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1697 /** {@hide} */ 1698 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1699 1700 private static final int PFLAG_PRESSED = 0x00004000; 1701 1702 /** {@hide} */ 1703 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1704 /** 1705 * Flag used to indicate that this view should be drawn once more (and only once 1706 * more) after its animation has completed. 1707 * {@hide} 1708 */ 1709 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1710 1711 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1712 1713 /** 1714 * Indicates that the View returned true when onSetAlpha() was called and that 1715 * the alpha must be restored. 1716 * {@hide} 1717 */ 1718 static final int PFLAG_ALPHA_SET = 0x00040000; 1719 1720 /** 1721 * Set by {@link #setScrollContainer(boolean)}. 1722 */ 1723 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1724 1725 /** 1726 * Set by {@link #setScrollContainer(boolean)}. 1727 */ 1728 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1729 1730 /** 1731 * View flag indicating whether this view was invalidated (fully or partially.) 1732 * 1733 * @hide 1734 */ 1735 static final int PFLAG_DIRTY = 0x00200000; 1736 1737 /** 1738 * View flag indicating whether this view was invalidated by an opaque 1739 * invalidate request. 1740 * 1741 * @hide 1742 */ 1743 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1744 1745 /** 1746 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1747 * 1748 * @hide 1749 */ 1750 static final int PFLAG_DIRTY_MASK = 0x00600000; 1751 1752 /** 1753 * Indicates whether the background is opaque. 1754 * 1755 * @hide 1756 */ 1757 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1758 1759 /** 1760 * Indicates whether the scrollbars are opaque. 1761 * 1762 * @hide 1763 */ 1764 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1765 1766 /** 1767 * Indicates whether the view is opaque. 1768 * 1769 * @hide 1770 */ 1771 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1772 1773 /** 1774 * Indicates a prepressed state; 1775 * the short time between ACTION_DOWN and recognizing 1776 * a 'real' press. Prepressed is used to recognize quick taps 1777 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1778 * 1779 * @hide 1780 */ 1781 private static final int PFLAG_PREPRESSED = 0x02000000; 1782 1783 /** 1784 * Indicates whether the view is temporarily detached. 1785 * 1786 * @hide 1787 */ 1788 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1789 1790 /** 1791 * Indicates that we should awaken scroll bars once attached 1792 * 1793 * @hide 1794 */ 1795 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1796 1797 /** 1798 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1799 * @hide 1800 */ 1801 private static final int PFLAG_HOVERED = 0x10000000; 1802 1803 /** 1804 * no longer needed, should be reused 1805 */ 1806 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1807 1808 /** {@hide} */ 1809 static final int PFLAG_ACTIVATED = 0x40000000; 1810 1811 /** 1812 * Indicates that this view was specifically invalidated, not just dirtied because some 1813 * child view was invalidated. The flag is used to determine when we need to recreate 1814 * a view's display list (as opposed to just returning a reference to its existing 1815 * display list). 1816 * 1817 * @hide 1818 */ 1819 static final int PFLAG_INVALIDATED = 0x80000000; 1820 1821 /** 1822 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1823 * 1824 * |-------|-------|-------|-------| 1825 * 1 PFLAG2_DRAG_CAN_ACCEPT 1826 * 1 PFLAG2_DRAG_HOVERED 1827 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1828 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1829 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1830 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1831 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1832 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1833 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1834 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1835 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1836 * 111 PFLAG2_TEXT_DIRECTION_MASK 1837 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1838 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1839 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1840 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1841 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1842 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1843 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1844 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1845 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1846 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1847 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1848 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1849 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1850 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1851 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1852 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1853 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1854 * 1 PFLAG2_VIEW_QUICK_REJECTED 1855 * 1 PFLAG2_PADDING_RESOLVED 1856 * 1 PFLAG2_DRAWABLE_RESOLVED 1857 * 1 PFLAG2_HAS_TRANSIENT_STATE 1858 * |-------|-------|-------|-------| 1859 */ 1860 1861 /** 1862 * Indicates that this view has reported that it can accept the current drag's content. 1863 * Cleared when the drag operation concludes. 1864 * @hide 1865 */ 1866 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1867 1868 /** 1869 * Indicates that this view is currently directly under the drag location in a 1870 * drag-and-drop operation involving content that it can accept. Cleared when 1871 * the drag exits the view, or when the drag operation concludes. 1872 * @hide 1873 */ 1874 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1875 1876 /** @hide */ 1877 @IntDef({ 1878 LAYOUT_DIRECTION_LTR, 1879 LAYOUT_DIRECTION_RTL, 1880 LAYOUT_DIRECTION_INHERIT, 1881 LAYOUT_DIRECTION_LOCALE 1882 }) 1883 @Retention(RetentionPolicy.SOURCE) 1884 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1885 public @interface LayoutDir {} 1886 1887 /** @hide */ 1888 @IntDef({ 1889 LAYOUT_DIRECTION_LTR, 1890 LAYOUT_DIRECTION_RTL 1891 }) 1892 @Retention(RetentionPolicy.SOURCE) 1893 public @interface ResolvedLayoutDir {} 1894 1895 /** 1896 * Horizontal layout direction of this view is from Left to Right. 1897 * Use with {@link #setLayoutDirection}. 1898 */ 1899 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1900 1901 /** 1902 * Horizontal layout direction of this view is from Right to Left. 1903 * Use with {@link #setLayoutDirection}. 1904 */ 1905 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1906 1907 /** 1908 * Horizontal layout direction of this view is inherited from its parent. 1909 * Use with {@link #setLayoutDirection}. 1910 */ 1911 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1912 1913 /** 1914 * Horizontal layout direction of this view is from deduced from the default language 1915 * script for the locale. Use with {@link #setLayoutDirection}. 1916 */ 1917 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1918 1919 /** 1920 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1921 * @hide 1922 */ 1923 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1924 1925 /** 1926 * Mask for use with private flags indicating bits used for horizontal layout direction. 1927 * @hide 1928 */ 1929 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1930 1931 /** 1932 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1933 * right-to-left direction. 1934 * @hide 1935 */ 1936 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1937 1938 /** 1939 * Indicates whether the view horizontal layout direction has been resolved. 1940 * @hide 1941 */ 1942 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1943 1944 /** 1945 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1946 * @hide 1947 */ 1948 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1949 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1950 1951 /* 1952 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1953 * flag value. 1954 * @hide 1955 */ 1956 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1957 LAYOUT_DIRECTION_LTR, 1958 LAYOUT_DIRECTION_RTL, 1959 LAYOUT_DIRECTION_INHERIT, 1960 LAYOUT_DIRECTION_LOCALE 1961 }; 1962 1963 /** 1964 * Default horizontal layout direction. 1965 */ 1966 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1967 1968 /** 1969 * Default horizontal layout direction. 1970 * @hide 1971 */ 1972 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1973 1974 /** 1975 * Text direction is inherited thru {@link ViewGroup} 1976 */ 1977 public static final int TEXT_DIRECTION_INHERIT = 0; 1978 1979 /** 1980 * Text direction is using "first strong algorithm". The first strong directional character 1981 * determines the paragraph direction. If there is no strong directional character, the 1982 * paragraph direction is the view's resolved layout direction. 1983 */ 1984 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1985 1986 /** 1987 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1988 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1989 * If there are neither, the paragraph direction is the view's resolved layout direction. 1990 */ 1991 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1992 1993 /** 1994 * Text direction is forced to LTR. 1995 */ 1996 public static final int TEXT_DIRECTION_LTR = 3; 1997 1998 /** 1999 * Text direction is forced to RTL. 2000 */ 2001 public static final int TEXT_DIRECTION_RTL = 4; 2002 2003 /** 2004 * Text direction is coming from the system Locale. 2005 */ 2006 public static final int TEXT_DIRECTION_LOCALE = 5; 2007 2008 /** 2009 * Default text direction is inherited 2010 */ 2011 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2012 2013 /** 2014 * Default resolved text direction 2015 * @hide 2016 */ 2017 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2018 2019 /** 2020 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2021 * @hide 2022 */ 2023 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2024 2025 /** 2026 * Mask for use with private flags indicating bits used for text direction. 2027 * @hide 2028 */ 2029 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2030 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2031 2032 /** 2033 * Array of text direction flags for mapping attribute "textDirection" to correct 2034 * flag value. 2035 * @hide 2036 */ 2037 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2038 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2039 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2040 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2041 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2042 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2043 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2044 }; 2045 2046 /** 2047 * Indicates whether the view text direction has been resolved. 2048 * @hide 2049 */ 2050 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2051 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2052 2053 /** 2054 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2055 * @hide 2056 */ 2057 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2058 2059 /** 2060 * Mask for use with private flags indicating bits used for resolved text direction. 2061 * @hide 2062 */ 2063 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2064 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2065 2066 /** 2067 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2068 * @hide 2069 */ 2070 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2071 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2072 2073 /** @hide */ 2074 @IntDef({ 2075 TEXT_ALIGNMENT_INHERIT, 2076 TEXT_ALIGNMENT_GRAVITY, 2077 TEXT_ALIGNMENT_CENTER, 2078 TEXT_ALIGNMENT_TEXT_START, 2079 TEXT_ALIGNMENT_TEXT_END, 2080 TEXT_ALIGNMENT_VIEW_START, 2081 TEXT_ALIGNMENT_VIEW_END 2082 }) 2083 @Retention(RetentionPolicy.SOURCE) 2084 public @interface TextAlignment {} 2085 2086 /** 2087 * Default text alignment. The text alignment of this View is inherited from its parent. 2088 * Use with {@link #setTextAlignment(int)} 2089 */ 2090 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2091 2092 /** 2093 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2094 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2095 * 2096 * Use with {@link #setTextAlignment(int)} 2097 */ 2098 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2099 2100 /** 2101 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2102 * 2103 * Use with {@link #setTextAlignment(int)} 2104 */ 2105 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2106 2107 /** 2108 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2109 * 2110 * Use with {@link #setTextAlignment(int)} 2111 */ 2112 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2113 2114 /** 2115 * Center the paragraph, e.g. ALIGN_CENTER. 2116 * 2117 * Use with {@link #setTextAlignment(int)} 2118 */ 2119 public static final int TEXT_ALIGNMENT_CENTER = 4; 2120 2121 /** 2122 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2123 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2124 * 2125 * Use with {@link #setTextAlignment(int)} 2126 */ 2127 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2128 2129 /** 2130 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2131 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2132 * 2133 * Use with {@link #setTextAlignment(int)} 2134 */ 2135 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2136 2137 /** 2138 * Default text alignment is inherited 2139 */ 2140 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2141 2142 /** 2143 * Default resolved text alignment 2144 * @hide 2145 */ 2146 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2147 2148 /** 2149 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2150 * @hide 2151 */ 2152 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2153 2154 /** 2155 * Mask for use with private flags indicating bits used for text alignment. 2156 * @hide 2157 */ 2158 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2159 2160 /** 2161 * Array of text direction flags for mapping attribute "textAlignment" to correct 2162 * flag value. 2163 * @hide 2164 */ 2165 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2166 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2167 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2168 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2169 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2170 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2171 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2172 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2173 }; 2174 2175 /** 2176 * Indicates whether the view text alignment has been resolved. 2177 * @hide 2178 */ 2179 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2180 2181 /** 2182 * Bit shift to get the resolved text alignment. 2183 * @hide 2184 */ 2185 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2186 2187 /** 2188 * Mask for use with private flags indicating bits used for text alignment. 2189 * @hide 2190 */ 2191 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2192 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2193 2194 /** 2195 * Indicates whether if the view text alignment has been resolved to gravity 2196 */ 2197 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2198 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2199 2200 // Accessiblity constants for mPrivateFlags2 2201 2202 /** 2203 * Shift for the bits in {@link #mPrivateFlags2} related to the 2204 * "importantForAccessibility" attribute. 2205 */ 2206 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2207 2208 /** 2209 * Automatically determine whether a view is important for accessibility. 2210 */ 2211 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2212 2213 /** 2214 * The view is important for accessibility. 2215 */ 2216 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2217 2218 /** 2219 * The view is not important for accessibility. 2220 */ 2221 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2222 2223 /** 2224 * The view is not important for accessibility, nor are any of its 2225 * descendant views. 2226 */ 2227 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2228 2229 /** 2230 * The default whether the view is important for accessibility. 2231 */ 2232 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2233 2234 /** 2235 * Mask for obtainig the bits which specify how to determine 2236 * whether a view is important for accessibility. 2237 */ 2238 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2239 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2240 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2241 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2242 2243 /** 2244 * Shift for the bits in {@link #mPrivateFlags2} related to the 2245 * "accessibilityLiveRegion" attribute. 2246 */ 2247 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2248 2249 /** 2250 * Live region mode specifying that accessibility services should not 2251 * automatically announce changes to this view. This is the default live 2252 * region mode for most views. 2253 * <p> 2254 * Use with {@link #setAccessibilityLiveRegion(int)}. 2255 */ 2256 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2257 2258 /** 2259 * Live region mode specifying that accessibility services should announce 2260 * changes to this view. 2261 * <p> 2262 * Use with {@link #setAccessibilityLiveRegion(int)}. 2263 */ 2264 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2265 2266 /** 2267 * Live region mode specifying that accessibility services should interrupt 2268 * ongoing speech to immediately announce changes to this view. 2269 * <p> 2270 * Use with {@link #setAccessibilityLiveRegion(int)}. 2271 */ 2272 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2273 2274 /** 2275 * The default whether the view is important for accessibility. 2276 */ 2277 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2278 2279 /** 2280 * Mask for obtaining the bits which specify a view's accessibility live 2281 * region mode. 2282 */ 2283 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2284 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2285 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2286 2287 /** 2288 * Flag indicating whether a view has accessibility focus. 2289 */ 2290 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2291 2292 /** 2293 * Flag whether the accessibility state of the subtree rooted at this view changed. 2294 */ 2295 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2296 2297 /** 2298 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2299 * is used to check whether later changes to the view's transform should invalidate the 2300 * view to force the quickReject test to run again. 2301 */ 2302 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2303 2304 /** 2305 * Flag indicating that start/end padding has been resolved into left/right padding 2306 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2307 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2308 * during measurement. In some special cases this is required such as when an adapter-based 2309 * view measures prospective children without attaching them to a window. 2310 */ 2311 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2312 2313 /** 2314 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2315 */ 2316 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2317 2318 /** 2319 * Indicates that the view is tracking some sort of transient state 2320 * that the app should not need to be aware of, but that the framework 2321 * should take special care to preserve. 2322 */ 2323 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2324 2325 /** 2326 * Group of bits indicating that RTL properties resolution is done. 2327 */ 2328 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2329 PFLAG2_TEXT_DIRECTION_RESOLVED | 2330 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2331 PFLAG2_PADDING_RESOLVED | 2332 PFLAG2_DRAWABLE_RESOLVED; 2333 2334 // There are a couple of flags left in mPrivateFlags2 2335 2336 /* End of masks for mPrivateFlags2 */ 2337 2338 /** 2339 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2340 * 2341 * |-------|-------|-------|-------| 2342 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2343 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2344 * 1 PFLAG3_IS_LAID_OUT 2345 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2346 * 1 PFLAG3_CALLED_SUPER 2347 * |-------|-------|-------|-------| 2348 */ 2349 2350 /** 2351 * Flag indicating that view has a transform animation set on it. This is used to track whether 2352 * an animation is cleared between successive frames, in order to tell the associated 2353 * DisplayList to clear its animation matrix. 2354 */ 2355 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2356 2357 /** 2358 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2359 * animation is cleared between successive frames, in order to tell the associated 2360 * DisplayList to restore its alpha value. 2361 */ 2362 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2363 2364 /** 2365 * Flag indicating that the view has been through at least one layout since it 2366 * was last attached to a window. 2367 */ 2368 static final int PFLAG3_IS_LAID_OUT = 0x4; 2369 2370 /** 2371 * Flag indicating that a call to measure() was skipped and should be done 2372 * instead when layout() is invoked. 2373 */ 2374 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2375 2376 /** 2377 * Flag indicating that an overridden method correctly called down to 2378 * the superclass implementation as required by the API spec. 2379 */ 2380 static final int PFLAG3_CALLED_SUPER = 0x10; 2381 2382 /** 2383 * Flag indicating that a view's outline has been specifically defined. 2384 */ 2385 static final int PFLAG3_OUTLINE_DEFINED = 0x20; 2386 2387 /** 2388 * Flag indicating that we're in the process of applying window insets. 2389 */ 2390 static final int PFLAG3_APPLYING_INSETS = 0x40; 2391 2392 /** 2393 * Flag indicating that we're in the process of fitting system windows using the old method. 2394 */ 2395 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80; 2396 2397 /** 2398 * Flag indicating that nested scrolling is enabled for this view. 2399 * The view will optionally cooperate with views up its parent chain to allow for 2400 * integrated nested scrolling along the same axis. 2401 */ 2402 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x200; 2403 2404 /* End of masks for mPrivateFlags3 */ 2405 2406 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2407 2408 /** 2409 * Always allow a user to over-scroll this view, provided it is a 2410 * view that can scroll. 2411 * 2412 * @see #getOverScrollMode() 2413 * @see #setOverScrollMode(int) 2414 */ 2415 public static final int OVER_SCROLL_ALWAYS = 0; 2416 2417 /** 2418 * Allow a user to over-scroll this view only if the content is large 2419 * enough to meaningfully scroll, provided it is a view that can scroll. 2420 * 2421 * @see #getOverScrollMode() 2422 * @see #setOverScrollMode(int) 2423 */ 2424 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2425 2426 /** 2427 * Never allow a user to over-scroll this view. 2428 * 2429 * @see #getOverScrollMode() 2430 * @see #setOverScrollMode(int) 2431 */ 2432 public static final int OVER_SCROLL_NEVER = 2; 2433 2434 /** 2435 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2436 * requested the system UI (status bar) to be visible (the default). 2437 * 2438 * @see #setSystemUiVisibility(int) 2439 */ 2440 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2441 2442 /** 2443 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2444 * system UI to enter an unobtrusive "low profile" mode. 2445 * 2446 * <p>This is for use in games, book readers, video players, or any other 2447 * "immersive" application where the usual system chrome is deemed too distracting. 2448 * 2449 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2450 * 2451 * @see #setSystemUiVisibility(int) 2452 */ 2453 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2454 2455 /** 2456 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2457 * system navigation be temporarily hidden. 2458 * 2459 * <p>This is an even less obtrusive state than that called for by 2460 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2461 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2462 * those to disappear. This is useful (in conjunction with the 2463 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2464 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2465 * window flags) for displaying content using every last pixel on the display. 2466 * 2467 * <p>There is a limitation: because navigation controls are so important, the least user 2468 * interaction will cause them to reappear immediately. When this happens, both 2469 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2470 * so that both elements reappear at the same time. 2471 * 2472 * @see #setSystemUiVisibility(int) 2473 */ 2474 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2475 2476 /** 2477 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2478 * into the normal fullscreen mode so that its content can take over the screen 2479 * while still allowing the user to interact with the application. 2480 * 2481 * <p>This has the same visual effect as 2482 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2483 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2484 * meaning that non-critical screen decorations (such as the status bar) will be 2485 * hidden while the user is in the View's window, focusing the experience on 2486 * that content. Unlike the window flag, if you are using ActionBar in 2487 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2488 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2489 * hide the action bar. 2490 * 2491 * <p>This approach to going fullscreen is best used over the window flag when 2492 * it is a transient state -- that is, the application does this at certain 2493 * points in its user interaction where it wants to allow the user to focus 2494 * on content, but not as a continuous state. For situations where the application 2495 * would like to simply stay full screen the entire time (such as a game that 2496 * wants to take over the screen), the 2497 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2498 * is usually a better approach. The state set here will be removed by the system 2499 * in various situations (such as the user moving to another application) like 2500 * the other system UI states. 2501 * 2502 * <p>When using this flag, the application should provide some easy facility 2503 * for the user to go out of it. A common example would be in an e-book 2504 * reader, where tapping on the screen brings back whatever screen and UI 2505 * decorations that had been hidden while the user was immersed in reading 2506 * the book. 2507 * 2508 * @see #setSystemUiVisibility(int) 2509 */ 2510 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2511 2512 /** 2513 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2514 * flags, we would like a stable view of the content insets given to 2515 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2516 * will always represent the worst case that the application can expect 2517 * as a continuous state. In the stock Android UI this is the space for 2518 * the system bar, nav bar, and status bar, but not more transient elements 2519 * such as an input method. 2520 * 2521 * The stable layout your UI sees is based on the system UI modes you can 2522 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2523 * then you will get a stable layout for changes of the 2524 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2525 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2526 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2527 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2528 * with a stable layout. (Note that you should avoid using 2529 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2530 * 2531 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2532 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2533 * then a hidden status bar will be considered a "stable" state for purposes 2534 * here. This allows your UI to continually hide the status bar, while still 2535 * using the system UI flags to hide the action bar while still retaining 2536 * a stable layout. Note that changing the window fullscreen flag will never 2537 * provide a stable layout for a clean transition. 2538 * 2539 * <p>If you are using ActionBar in 2540 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2541 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2542 * insets it adds to those given to the application. 2543 */ 2544 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2545 2546 /** 2547 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2548 * to be layed out as if it has requested 2549 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2550 * allows it to avoid artifacts when switching in and out of that mode, at 2551 * the expense that some of its user interface may be covered by screen 2552 * decorations when they are shown. You can perform layout of your inner 2553 * UI elements to account for the navigation system UI through the 2554 * {@link #fitSystemWindows(Rect)} method. 2555 */ 2556 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2557 2558 /** 2559 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2560 * to be layed out as if it has requested 2561 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2562 * allows it to avoid artifacts when switching in and out of that mode, at 2563 * the expense that some of its user interface may be covered by screen 2564 * decorations when they are shown. You can perform layout of your inner 2565 * UI elements to account for non-fullscreen system UI through the 2566 * {@link #fitSystemWindows(Rect)} method. 2567 */ 2568 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2569 2570 /** 2571 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2572 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2573 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2574 * user interaction. 2575 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2576 * has an effect when used in combination with that flag.</p> 2577 */ 2578 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2579 2580 /** 2581 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2582 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2583 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2584 * experience while also hiding the system bars. If this flag is not set, 2585 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2586 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2587 * if the user swipes from the top of the screen. 2588 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2589 * system gestures, such as swiping from the top of the screen. These transient system bars 2590 * will overlay app’s content, may have some degree of transparency, and will automatically 2591 * hide after a short timeout. 2592 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2593 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2594 * with one or both of those flags.</p> 2595 */ 2596 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2597 2598 /** 2599 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2600 */ 2601 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2602 2603 /** 2604 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2605 */ 2606 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2607 2608 /** 2609 * @hide 2610 * 2611 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2612 * out of the public fields to keep the undefined bits out of the developer's way. 2613 * 2614 * Flag to make the status bar not expandable. Unless you also 2615 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2616 */ 2617 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2618 2619 /** 2620 * @hide 2621 * 2622 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2623 * out of the public fields to keep the undefined bits out of the developer's way. 2624 * 2625 * Flag to hide notification icons and scrolling ticker text. 2626 */ 2627 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2628 2629 /** 2630 * @hide 2631 * 2632 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2633 * out of the public fields to keep the undefined bits out of the developer's way. 2634 * 2635 * Flag to disable incoming notification alerts. This will not block 2636 * icons, but it will block sound, vibrating and other visual or aural notifications. 2637 */ 2638 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2639 2640 /** 2641 * @hide 2642 * 2643 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2644 * out of the public fields to keep the undefined bits out of the developer's way. 2645 * 2646 * Flag to hide only the scrolling ticker. Note that 2647 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2648 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2649 */ 2650 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2651 2652 /** 2653 * @hide 2654 * 2655 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2656 * out of the public fields to keep the undefined bits out of the developer's way. 2657 * 2658 * Flag to hide the center system info area. 2659 */ 2660 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2661 2662 /** 2663 * @hide 2664 * 2665 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2666 * out of the public fields to keep the undefined bits out of the developer's way. 2667 * 2668 * Flag to hide only the home button. Don't use this 2669 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2670 */ 2671 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2672 2673 /** 2674 * @hide 2675 * 2676 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2677 * out of the public fields to keep the undefined bits out of the developer's way. 2678 * 2679 * Flag to hide only the back button. Don't use this 2680 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2681 */ 2682 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2683 2684 /** 2685 * @hide 2686 * 2687 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2688 * out of the public fields to keep the undefined bits out of the developer's way. 2689 * 2690 * Flag to hide only the clock. You might use this if your activity has 2691 * its own clock making the status bar's clock redundant. 2692 */ 2693 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2694 2695 /** 2696 * @hide 2697 * 2698 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2699 * out of the public fields to keep the undefined bits out of the developer's way. 2700 * 2701 * Flag to hide only the recent apps button. Don't use this 2702 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2703 */ 2704 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2705 2706 /** 2707 * @hide 2708 * 2709 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2710 * out of the public fields to keep the undefined bits out of the developer's way. 2711 * 2712 * Flag to disable the global search gesture. Don't use this 2713 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2714 */ 2715 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2716 2717 /** 2718 * @hide 2719 * 2720 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2721 * out of the public fields to keep the undefined bits out of the developer's way. 2722 * 2723 * Flag to specify that the status bar is displayed in transient mode. 2724 */ 2725 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2726 2727 /** 2728 * @hide 2729 * 2730 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2731 * out of the public fields to keep the undefined bits out of the developer's way. 2732 * 2733 * Flag to specify that the navigation bar is displayed in transient mode. 2734 */ 2735 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2736 2737 /** 2738 * @hide 2739 * 2740 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2741 * out of the public fields to keep the undefined bits out of the developer's way. 2742 * 2743 * Flag to specify that the hidden status bar would like to be shown. 2744 */ 2745 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2746 2747 /** 2748 * @hide 2749 * 2750 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2751 * out of the public fields to keep the undefined bits out of the developer's way. 2752 * 2753 * Flag to specify that the hidden navigation bar would like to be shown. 2754 */ 2755 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2756 2757 /** 2758 * @hide 2759 * 2760 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2761 * out of the public fields to keep the undefined bits out of the developer's way. 2762 * 2763 * Flag to specify that the status bar is displayed in translucent mode. 2764 */ 2765 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2766 2767 /** 2768 * @hide 2769 * 2770 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2771 * out of the public fields to keep the undefined bits out of the developer's way. 2772 * 2773 * Flag to specify that the navigation bar is displayed in translucent mode. 2774 */ 2775 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2776 2777 /** 2778 * @hide 2779 * 2780 * Whether Recents is visible or not. 2781 */ 2782 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2783 2784 /** 2785 * @hide 2786 * 2787 * Makes system ui transparent. 2788 */ 2789 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2790 2791 /** 2792 * @hide 2793 */ 2794 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2795 2796 /** 2797 * These are the system UI flags that can be cleared by events outside 2798 * of an application. Currently this is just the ability to tap on the 2799 * screen while hiding the navigation bar to have it return. 2800 * @hide 2801 */ 2802 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2803 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2804 | SYSTEM_UI_FLAG_FULLSCREEN; 2805 2806 /** 2807 * Flags that can impact the layout in relation to system UI. 2808 */ 2809 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2810 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2811 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2812 2813 /** @hide */ 2814 @IntDef(flag = true, 2815 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2816 @Retention(RetentionPolicy.SOURCE) 2817 public @interface FindViewFlags {} 2818 2819 /** 2820 * Find views that render the specified text. 2821 * 2822 * @see #findViewsWithText(ArrayList, CharSequence, int) 2823 */ 2824 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2825 2826 /** 2827 * Find find views that contain the specified content description. 2828 * 2829 * @see #findViewsWithText(ArrayList, CharSequence, int) 2830 */ 2831 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2832 2833 /** 2834 * Find views that contain {@link AccessibilityNodeProvider}. Such 2835 * a View is a root of virtual view hierarchy and may contain the searched 2836 * text. If this flag is set Views with providers are automatically 2837 * added and it is a responsibility of the client to call the APIs of 2838 * the provider to determine whether the virtual tree rooted at this View 2839 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2840 * representing the virtual views with this text. 2841 * 2842 * @see #findViewsWithText(ArrayList, CharSequence, int) 2843 * 2844 * @hide 2845 */ 2846 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2847 2848 /** 2849 * The undefined cursor position. 2850 * 2851 * @hide 2852 */ 2853 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2854 2855 /** 2856 * Indicates that the screen has changed state and is now off. 2857 * 2858 * @see #onScreenStateChanged(int) 2859 */ 2860 public static final int SCREEN_STATE_OFF = 0x0; 2861 2862 /** 2863 * Indicates that the screen has changed state and is now on. 2864 * 2865 * @see #onScreenStateChanged(int) 2866 */ 2867 public static final int SCREEN_STATE_ON = 0x1; 2868 2869 /** 2870 * Indicates no axis of view scrolling. 2871 */ 2872 public static final int SCROLL_AXIS_NONE = 0; 2873 2874 /** 2875 * Indicates scrolling along the horizontal axis. 2876 */ 2877 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2878 2879 /** 2880 * Indicates scrolling along the vertical axis. 2881 */ 2882 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2883 2884 /** 2885 * Controls the over-scroll mode for this view. 2886 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2887 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2888 * and {@link #OVER_SCROLL_NEVER}. 2889 */ 2890 private int mOverScrollMode; 2891 2892 /** 2893 * The parent this view is attached to. 2894 * {@hide} 2895 * 2896 * @see #getParent() 2897 */ 2898 protected ViewParent mParent; 2899 2900 /** 2901 * {@hide} 2902 */ 2903 AttachInfo mAttachInfo; 2904 2905 /** 2906 * {@hide} 2907 */ 2908 @ViewDebug.ExportedProperty(flagMapping = { 2909 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2910 name = "FORCE_LAYOUT"), 2911 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2912 name = "LAYOUT_REQUIRED"), 2913 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2914 name = "DRAWING_CACHE_INVALID", outputIf = false), 2915 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2916 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2917 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2918 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2919 }) 2920 int mPrivateFlags; 2921 int mPrivateFlags2; 2922 int mPrivateFlags3; 2923 2924 /** 2925 * This view's request for the visibility of the status bar. 2926 * @hide 2927 */ 2928 @ViewDebug.ExportedProperty(flagMapping = { 2929 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2930 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2931 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2932 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2933 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2934 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2935 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2936 equals = SYSTEM_UI_FLAG_VISIBLE, 2937 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2938 }) 2939 int mSystemUiVisibility; 2940 2941 /** 2942 * Reference count for transient state. 2943 * @see #setHasTransientState(boolean) 2944 */ 2945 int mTransientStateCount = 0; 2946 2947 /** 2948 * Count of how many windows this view has been attached to. 2949 */ 2950 int mWindowAttachCount; 2951 2952 /** 2953 * The layout parameters associated with this view and used by the parent 2954 * {@link android.view.ViewGroup} to determine how this view should be 2955 * laid out. 2956 * {@hide} 2957 */ 2958 protected ViewGroup.LayoutParams mLayoutParams; 2959 2960 /** 2961 * The view flags hold various views states. 2962 * {@hide} 2963 */ 2964 @ViewDebug.ExportedProperty 2965 int mViewFlags; 2966 2967 static class TransformationInfo { 2968 /** 2969 * The transform matrix for the View. This transform is calculated internally 2970 * based on the translation, rotation, and scale properties. 2971 * 2972 * Do *not* use this variable directly; instead call getMatrix(), which will 2973 * load the value from the View's RenderNode. 2974 */ 2975 private final Matrix mMatrix = new Matrix(); 2976 2977 /** 2978 * The inverse transform matrix for the View. This transform is calculated 2979 * internally based on the translation, rotation, and scale properties. 2980 * 2981 * Do *not* use this variable directly; instead call getInverseMatrix(), 2982 * which will load the value from the View's RenderNode. 2983 */ 2984 private Matrix mInverseMatrix; 2985 2986 /** 2987 * The opacity of the View. This is a value from 0 to 1, where 0 means 2988 * completely transparent and 1 means completely opaque. 2989 */ 2990 @ViewDebug.ExportedProperty 2991 float mAlpha = 1f; 2992 2993 /** 2994 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2995 * property only used by transitions, which is composited with the other alpha 2996 * values to calculate the final visual alpha value. 2997 */ 2998 float mTransitionAlpha = 1f; 2999 } 3000 3001 TransformationInfo mTransformationInfo; 3002 3003 /** 3004 * Current clip bounds. to which all drawing of this view are constrained. 3005 */ 3006 Rect mClipBounds = null; 3007 3008 private boolean mLastIsOpaque; 3009 3010 /** 3011 * The distance in pixels from the left edge of this view's parent 3012 * to the left edge of this view. 3013 * {@hide} 3014 */ 3015 @ViewDebug.ExportedProperty(category = "layout") 3016 protected int mLeft; 3017 /** 3018 * The distance in pixels from the left edge of this view's parent 3019 * to the right edge of this view. 3020 * {@hide} 3021 */ 3022 @ViewDebug.ExportedProperty(category = "layout") 3023 protected int mRight; 3024 /** 3025 * The distance in pixels from the top edge of this view's parent 3026 * to the top edge of this view. 3027 * {@hide} 3028 */ 3029 @ViewDebug.ExportedProperty(category = "layout") 3030 protected int mTop; 3031 /** 3032 * The distance in pixels from the top edge of this view's parent 3033 * to the bottom edge of this view. 3034 * {@hide} 3035 */ 3036 @ViewDebug.ExportedProperty(category = "layout") 3037 protected int mBottom; 3038 3039 /** 3040 * The offset, in pixels, by which the content of this view is scrolled 3041 * horizontally. 3042 * {@hide} 3043 */ 3044 @ViewDebug.ExportedProperty(category = "scrolling") 3045 protected int mScrollX; 3046 /** 3047 * The offset, in pixels, by which the content of this view is scrolled 3048 * vertically. 3049 * {@hide} 3050 */ 3051 @ViewDebug.ExportedProperty(category = "scrolling") 3052 protected int mScrollY; 3053 3054 /** 3055 * The left padding in pixels, that is the distance in pixels between the 3056 * left edge of this view and the left edge of its content. 3057 * {@hide} 3058 */ 3059 @ViewDebug.ExportedProperty(category = "padding") 3060 protected int mPaddingLeft = 0; 3061 /** 3062 * The right padding in pixels, that is the distance in pixels between the 3063 * right edge of this view and the right edge of its content. 3064 * {@hide} 3065 */ 3066 @ViewDebug.ExportedProperty(category = "padding") 3067 protected int mPaddingRight = 0; 3068 /** 3069 * The top padding in pixels, that is the distance in pixels between the 3070 * top edge of this view and the top edge of its content. 3071 * {@hide} 3072 */ 3073 @ViewDebug.ExportedProperty(category = "padding") 3074 protected int mPaddingTop; 3075 /** 3076 * The bottom padding in pixels, that is the distance in pixels between the 3077 * bottom edge of this view and the bottom edge of its content. 3078 * {@hide} 3079 */ 3080 @ViewDebug.ExportedProperty(category = "padding") 3081 protected int mPaddingBottom; 3082 3083 /** 3084 * The layout insets in pixels, that is the distance in pixels between the 3085 * visible edges of this view its bounds. 3086 */ 3087 private Insets mLayoutInsets; 3088 3089 /** 3090 * Briefly describes the view and is primarily used for accessibility support. 3091 */ 3092 private CharSequence mContentDescription; 3093 3094 /** 3095 * Specifies the id of a view for which this view serves as a label for 3096 * accessibility purposes. 3097 */ 3098 private int mLabelForId = View.NO_ID; 3099 3100 /** 3101 * Predicate for matching labeled view id with its label for 3102 * accessibility purposes. 3103 */ 3104 private MatchLabelForPredicate mMatchLabelForPredicate; 3105 3106 /** 3107 * Predicate for matching a view by its id. 3108 */ 3109 private MatchIdPredicate mMatchIdPredicate; 3110 3111 /** 3112 * Cache the paddingRight set by the user to append to the scrollbar's size. 3113 * 3114 * @hide 3115 */ 3116 @ViewDebug.ExportedProperty(category = "padding") 3117 protected int mUserPaddingRight; 3118 3119 /** 3120 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3121 * 3122 * @hide 3123 */ 3124 @ViewDebug.ExportedProperty(category = "padding") 3125 protected int mUserPaddingBottom; 3126 3127 /** 3128 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3129 * 3130 * @hide 3131 */ 3132 @ViewDebug.ExportedProperty(category = "padding") 3133 protected int mUserPaddingLeft; 3134 3135 /** 3136 * Cache the paddingStart set by the user to append to the scrollbar's size. 3137 * 3138 */ 3139 @ViewDebug.ExportedProperty(category = "padding") 3140 int mUserPaddingStart; 3141 3142 /** 3143 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3144 * 3145 */ 3146 @ViewDebug.ExportedProperty(category = "padding") 3147 int mUserPaddingEnd; 3148 3149 /** 3150 * Cache initial left padding. 3151 * 3152 * @hide 3153 */ 3154 int mUserPaddingLeftInitial; 3155 3156 /** 3157 * Cache initial right padding. 3158 * 3159 * @hide 3160 */ 3161 int mUserPaddingRightInitial; 3162 3163 /** 3164 * Default undefined padding 3165 */ 3166 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3167 3168 /** 3169 * Cache if a left padding has been defined 3170 */ 3171 private boolean mLeftPaddingDefined = false; 3172 3173 /** 3174 * Cache if a right padding has been defined 3175 */ 3176 private boolean mRightPaddingDefined = false; 3177 3178 /** 3179 * @hide 3180 */ 3181 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3182 /** 3183 * @hide 3184 */ 3185 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3186 3187 private LongSparseLongArray mMeasureCache; 3188 3189 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3190 private Drawable mBackground; 3191 private ColorStateList mBackgroundTint = null; 3192 private PorterDuff.Mode mBackgroundTintMode = PorterDuff.Mode.SRC_ATOP; 3193 private boolean mHasBackgroundTint = false; 3194 3195 /** 3196 * RenderNode used for backgrounds. 3197 * <p> 3198 * When non-null and valid, this is expected to contain an up-to-date copy 3199 * of the background drawable. It is cleared on temporary detach, and reset 3200 * on cleanup. 3201 */ 3202 private RenderNode mBackgroundRenderNode; 3203 3204 private int mBackgroundResource; 3205 private boolean mBackgroundSizeChanged; 3206 3207 private String mTransitionName; 3208 3209 static class ListenerInfo { 3210 /** 3211 * Listener used to dispatch focus change events. 3212 * This field should be made private, so it is hidden from the SDK. 3213 * {@hide} 3214 */ 3215 protected OnFocusChangeListener mOnFocusChangeListener; 3216 3217 /** 3218 * Listeners for layout change events. 3219 */ 3220 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3221 3222 /** 3223 * Listeners for attach events. 3224 */ 3225 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3226 3227 /** 3228 * Listener used to dispatch click events. 3229 * This field should be made private, so it is hidden from the SDK. 3230 * {@hide} 3231 */ 3232 public OnClickListener mOnClickListener; 3233 3234 /** 3235 * Listener used to dispatch long click events. 3236 * This field should be made private, so it is hidden from the SDK. 3237 * {@hide} 3238 */ 3239 protected OnLongClickListener mOnLongClickListener; 3240 3241 /** 3242 * Listener used to build the context menu. 3243 * This field should be made private, so it is hidden from the SDK. 3244 * {@hide} 3245 */ 3246 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3247 3248 private OnKeyListener mOnKeyListener; 3249 3250 private OnTouchListener mOnTouchListener; 3251 3252 private OnHoverListener mOnHoverListener; 3253 3254 private OnGenericMotionListener mOnGenericMotionListener; 3255 3256 private OnDragListener mOnDragListener; 3257 3258 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3259 3260 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3261 } 3262 3263 ListenerInfo mListenerInfo; 3264 3265 /** 3266 * The application environment this view lives in. 3267 * This field should be made private, so it is hidden from the SDK. 3268 * {@hide} 3269 */ 3270 protected Context mContext; 3271 3272 private final Resources mResources; 3273 3274 private ScrollabilityCache mScrollCache; 3275 3276 private int[] mDrawableState = null; 3277 3278 /** 3279 * Stores the outline of the view, passed down to the DisplayList level for 3280 * defining shadow shape. 3281 */ 3282 private Outline mOutline; 3283 3284 /** 3285 * Animator that automatically runs based on state changes. 3286 */ 3287 private StateListAnimator mStateListAnimator; 3288 3289 /** 3290 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3291 * the user may specify which view to go to next. 3292 */ 3293 private int mNextFocusLeftId = View.NO_ID; 3294 3295 /** 3296 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3297 * the user may specify which view to go to next. 3298 */ 3299 private int mNextFocusRightId = View.NO_ID; 3300 3301 /** 3302 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3303 * the user may specify which view to go to next. 3304 */ 3305 private int mNextFocusUpId = View.NO_ID; 3306 3307 /** 3308 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3309 * the user may specify which view to go to next. 3310 */ 3311 private int mNextFocusDownId = View.NO_ID; 3312 3313 /** 3314 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3315 * the user may specify which view to go to next. 3316 */ 3317 int mNextFocusForwardId = View.NO_ID; 3318 3319 private CheckForLongPress mPendingCheckForLongPress; 3320 private CheckForTap mPendingCheckForTap = null; 3321 private PerformClick mPerformClick; 3322 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3323 3324 private UnsetPressedState mUnsetPressedState; 3325 3326 /** 3327 * Whether the long press's action has been invoked. The tap's action is invoked on the 3328 * up event while a long press is invoked as soon as the long press duration is reached, so 3329 * a long press could be performed before the tap is checked, in which case the tap's action 3330 * should not be invoked. 3331 */ 3332 private boolean mHasPerformedLongPress; 3333 3334 /** 3335 * The minimum height of the view. We'll try our best to have the height 3336 * of this view to at least this amount. 3337 */ 3338 @ViewDebug.ExportedProperty(category = "measurement") 3339 private int mMinHeight; 3340 3341 /** 3342 * The minimum width of the view. We'll try our best to have the width 3343 * of this view to at least this amount. 3344 */ 3345 @ViewDebug.ExportedProperty(category = "measurement") 3346 private int mMinWidth; 3347 3348 /** 3349 * The delegate to handle touch events that are physically in this view 3350 * but should be handled by another view. 3351 */ 3352 private TouchDelegate mTouchDelegate = null; 3353 3354 /** 3355 * Solid color to use as a background when creating the drawing cache. Enables 3356 * the cache to use 16 bit bitmaps instead of 32 bit. 3357 */ 3358 private int mDrawingCacheBackgroundColor = 0; 3359 3360 /** 3361 * Special tree observer used when mAttachInfo is null. 3362 */ 3363 private ViewTreeObserver mFloatingTreeObserver; 3364 3365 /** 3366 * Cache the touch slop from the context that created the view. 3367 */ 3368 private int mTouchSlop; 3369 3370 /** 3371 * Object that handles automatic animation of view properties. 3372 */ 3373 private ViewPropertyAnimator mAnimator = null; 3374 3375 /** 3376 * Flag indicating that a drag can cross window boundaries. When 3377 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3378 * with this flag set, all visible applications will be able to participate 3379 * in the drag operation and receive the dragged content. 3380 * 3381 * @hide 3382 */ 3383 public static final int DRAG_FLAG_GLOBAL = 1; 3384 3385 /** 3386 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3387 */ 3388 private float mVerticalScrollFactor; 3389 3390 /** 3391 * Position of the vertical scroll bar. 3392 */ 3393 private int mVerticalScrollbarPosition; 3394 3395 /** 3396 * Position the scroll bar at the default position as determined by the system. 3397 */ 3398 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3399 3400 /** 3401 * Position the scroll bar along the left edge. 3402 */ 3403 public static final int SCROLLBAR_POSITION_LEFT = 1; 3404 3405 /** 3406 * Position the scroll bar along the right edge. 3407 */ 3408 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3409 3410 /** 3411 * Indicates that the view does not have a layer. 3412 * 3413 * @see #getLayerType() 3414 * @see #setLayerType(int, android.graphics.Paint) 3415 * @see #LAYER_TYPE_SOFTWARE 3416 * @see #LAYER_TYPE_HARDWARE 3417 */ 3418 public static final int LAYER_TYPE_NONE = 0; 3419 3420 /** 3421 * <p>Indicates that the view has a software layer. A software layer is backed 3422 * by a bitmap and causes the view to be rendered using Android's software 3423 * rendering pipeline, even if hardware acceleration is enabled.</p> 3424 * 3425 * <p>Software layers have various usages:</p> 3426 * <p>When the application is not using hardware acceleration, a software layer 3427 * is useful to apply a specific color filter and/or blending mode and/or 3428 * translucency to a view and all its children.</p> 3429 * <p>When the application is using hardware acceleration, a software layer 3430 * is useful to render drawing primitives not supported by the hardware 3431 * accelerated pipeline. It can also be used to cache a complex view tree 3432 * into a texture and reduce the complexity of drawing operations. For instance, 3433 * when animating a complex view tree with a translation, a software layer can 3434 * be used to render the view tree only once.</p> 3435 * <p>Software layers should be avoided when the affected view tree updates 3436 * often. Every update will require to re-render the software layer, which can 3437 * potentially be slow (particularly when hardware acceleration is turned on 3438 * since the layer will have to be uploaded into a hardware texture after every 3439 * update.)</p> 3440 * 3441 * @see #getLayerType() 3442 * @see #setLayerType(int, android.graphics.Paint) 3443 * @see #LAYER_TYPE_NONE 3444 * @see #LAYER_TYPE_HARDWARE 3445 */ 3446 public static final int LAYER_TYPE_SOFTWARE = 1; 3447 3448 /** 3449 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3450 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3451 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3452 * rendering pipeline, but only if hardware acceleration is turned on for the 3453 * view hierarchy. When hardware acceleration is turned off, hardware layers 3454 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3455 * 3456 * <p>A hardware layer is useful to apply a specific color filter and/or 3457 * blending mode and/or translucency to a view and all its children.</p> 3458 * <p>A hardware layer can be used to cache a complex view tree into a 3459 * texture and reduce the complexity of drawing operations. For instance, 3460 * when animating a complex view tree with a translation, a hardware layer can 3461 * be used to render the view tree only once.</p> 3462 * <p>A hardware layer can also be used to increase the rendering quality when 3463 * rotation transformations are applied on a view. It can also be used to 3464 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3465 * 3466 * @see #getLayerType() 3467 * @see #setLayerType(int, android.graphics.Paint) 3468 * @see #LAYER_TYPE_NONE 3469 * @see #LAYER_TYPE_SOFTWARE 3470 */ 3471 public static final int LAYER_TYPE_HARDWARE = 2; 3472 3473 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3474 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3475 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3476 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3477 }) 3478 int mLayerType = LAYER_TYPE_NONE; 3479 Paint mLayerPaint; 3480 3481 /** 3482 * Set to true when drawing cache is enabled and cannot be created. 3483 * 3484 * @hide 3485 */ 3486 public boolean mCachingFailed; 3487 private Bitmap mDrawingCache; 3488 private Bitmap mUnscaledDrawingCache; 3489 3490 /** 3491 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3492 * <p> 3493 * When non-null and valid, this is expected to contain an up-to-date copy 3494 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3495 * cleanup. 3496 */ 3497 final RenderNode mRenderNode; 3498 3499 /** 3500 * Set to true when the view is sending hover accessibility events because it 3501 * is the innermost hovered view. 3502 */ 3503 private boolean mSendingHoverAccessibilityEvents; 3504 3505 /** 3506 * Delegate for injecting accessibility functionality. 3507 */ 3508 AccessibilityDelegate mAccessibilityDelegate; 3509 3510 /** 3511 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3512 * and add/remove objects to/from the overlay directly through the Overlay methods. 3513 */ 3514 ViewOverlay mOverlay; 3515 3516 /** 3517 * The currently active parent view for receiving delegated nested scrolling events. 3518 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3519 * by {@link #stopNestedScroll()} at the same point where we clear 3520 * requestDisallowInterceptTouchEvent. 3521 */ 3522 private ViewParent mNestedScrollingParent; 3523 3524 /** 3525 * Consistency verifier for debugging purposes. 3526 * @hide 3527 */ 3528 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3529 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3530 new InputEventConsistencyVerifier(this, 0) : null; 3531 3532 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3533 3534 private int[] mTempNestedScrollConsumed; 3535 3536 /** 3537 * Simple constructor to use when creating a view from code. 3538 * 3539 * @param context The Context the view is running in, through which it can 3540 * access the current theme, resources, etc. 3541 */ 3542 public View(Context context) { 3543 mContext = context; 3544 mResources = context != null ? context.getResources() : null; 3545 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3546 // Set some flags defaults 3547 mPrivateFlags2 = 3548 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3549 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3550 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3551 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3552 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3553 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3554 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3555 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3556 mUserPaddingStart = UNDEFINED_PADDING; 3557 mUserPaddingEnd = UNDEFINED_PADDING; 3558 mRenderNode = RenderNode.create(getClass().getName()); 3559 3560 if (!sCompatibilityDone && context != null) { 3561 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3562 3563 // Older apps may need this compatibility hack for measurement. 3564 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3565 3566 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3567 // of whether a layout was requested on that View. 3568 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3569 3570 // Older apps may need this to ignore the clip bounds 3571 sIgnoreClipBoundsForChildren = targetSdkVersion < L; 3572 3573 sCompatibilityDone = true; 3574 } 3575 } 3576 3577 /** 3578 * Constructor that is called when inflating a view from XML. This is called 3579 * when a view is being constructed from an XML file, supplying attributes 3580 * that were specified in the XML file. This version uses a default style of 3581 * 0, so the only attribute values applied are those in the Context's Theme 3582 * and the given AttributeSet. 3583 * 3584 * <p> 3585 * The method onFinishInflate() will be called after all children have been 3586 * added. 3587 * 3588 * @param context The Context the view is running in, through which it can 3589 * access the current theme, resources, etc. 3590 * @param attrs The attributes of the XML tag that is inflating the view. 3591 * @see #View(Context, AttributeSet, int) 3592 */ 3593 public View(Context context, AttributeSet attrs) { 3594 this(context, attrs, 0); 3595 } 3596 3597 /** 3598 * Perform inflation from XML and apply a class-specific base style from a 3599 * theme attribute. This constructor of View allows subclasses to use their 3600 * own base style when they are inflating. For example, a Button class's 3601 * constructor would call this version of the super class constructor and 3602 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3603 * allows the theme's button style to modify all of the base view attributes 3604 * (in particular its background) as well as the Button class's attributes. 3605 * 3606 * @param context The Context the view is running in, through which it can 3607 * access the current theme, resources, etc. 3608 * @param attrs The attributes of the XML tag that is inflating the view. 3609 * @param defStyleAttr An attribute in the current theme that contains a 3610 * reference to a style resource that supplies default values for 3611 * the view. Can be 0 to not look for defaults. 3612 * @see #View(Context, AttributeSet) 3613 */ 3614 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3615 this(context, attrs, defStyleAttr, 0); 3616 } 3617 3618 /** 3619 * Perform inflation from XML and apply a class-specific base style from a 3620 * theme attribute or style resource. This constructor of View allows 3621 * subclasses to use their own base style when they are inflating. 3622 * <p> 3623 * When determining the final value of a particular attribute, there are 3624 * four inputs that come into play: 3625 * <ol> 3626 * <li>Any attribute values in the given AttributeSet. 3627 * <li>The style resource specified in the AttributeSet (named "style"). 3628 * <li>The default style specified by <var>defStyleAttr</var>. 3629 * <li>The default style specified by <var>defStyleRes</var>. 3630 * <li>The base values in this theme. 3631 * </ol> 3632 * <p> 3633 * Each of these inputs is considered in-order, with the first listed taking 3634 * precedence over the following ones. In other words, if in the 3635 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3636 * , then the button's text will <em>always</em> be black, regardless of 3637 * what is specified in any of the styles. 3638 * 3639 * @param context The Context the view is running in, through which it can 3640 * access the current theme, resources, etc. 3641 * @param attrs The attributes of the XML tag that is inflating the view. 3642 * @param defStyleAttr An attribute in the current theme that contains a 3643 * reference to a style resource that supplies default values for 3644 * the view. Can be 0 to not look for defaults. 3645 * @param defStyleRes A resource identifier of a style resource that 3646 * supplies default values for the view, used only if 3647 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3648 * to not look for defaults. 3649 * @see #View(Context, AttributeSet, int) 3650 */ 3651 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3652 this(context); 3653 3654 final TypedArray a = context.obtainStyledAttributes( 3655 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3656 3657 Drawable background = null; 3658 3659 int leftPadding = -1; 3660 int topPadding = -1; 3661 int rightPadding = -1; 3662 int bottomPadding = -1; 3663 int startPadding = UNDEFINED_PADDING; 3664 int endPadding = UNDEFINED_PADDING; 3665 3666 int padding = -1; 3667 3668 int viewFlagValues = 0; 3669 int viewFlagMasks = 0; 3670 3671 boolean setScrollContainer = false; 3672 3673 int x = 0; 3674 int y = 0; 3675 3676 float tx = 0; 3677 float ty = 0; 3678 float tz = 0; 3679 float elevation = 0; 3680 float rotation = 0; 3681 float rotationX = 0; 3682 float rotationY = 0; 3683 float sx = 1f; 3684 float sy = 1f; 3685 boolean transformSet = false; 3686 3687 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3688 int overScrollMode = mOverScrollMode; 3689 boolean initializeScrollbars = false; 3690 3691 boolean startPaddingDefined = false; 3692 boolean endPaddingDefined = false; 3693 boolean leftPaddingDefined = false; 3694 boolean rightPaddingDefined = false; 3695 3696 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3697 3698 final int N = a.getIndexCount(); 3699 for (int i = 0; i < N; i++) { 3700 int attr = a.getIndex(i); 3701 switch (attr) { 3702 case com.android.internal.R.styleable.View_background: 3703 background = a.getDrawable(attr); 3704 break; 3705 case com.android.internal.R.styleable.View_padding: 3706 padding = a.getDimensionPixelSize(attr, -1); 3707 mUserPaddingLeftInitial = padding; 3708 mUserPaddingRightInitial = padding; 3709 leftPaddingDefined = true; 3710 rightPaddingDefined = true; 3711 break; 3712 case com.android.internal.R.styleable.View_paddingLeft: 3713 leftPadding = a.getDimensionPixelSize(attr, -1); 3714 mUserPaddingLeftInitial = leftPadding; 3715 leftPaddingDefined = true; 3716 break; 3717 case com.android.internal.R.styleable.View_paddingTop: 3718 topPadding = a.getDimensionPixelSize(attr, -1); 3719 break; 3720 case com.android.internal.R.styleable.View_paddingRight: 3721 rightPadding = a.getDimensionPixelSize(attr, -1); 3722 mUserPaddingRightInitial = rightPadding; 3723 rightPaddingDefined = true; 3724 break; 3725 case com.android.internal.R.styleable.View_paddingBottom: 3726 bottomPadding = a.getDimensionPixelSize(attr, -1); 3727 break; 3728 case com.android.internal.R.styleable.View_paddingStart: 3729 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3730 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3731 break; 3732 case com.android.internal.R.styleable.View_paddingEnd: 3733 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3734 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3735 break; 3736 case com.android.internal.R.styleable.View_scrollX: 3737 x = a.getDimensionPixelOffset(attr, 0); 3738 break; 3739 case com.android.internal.R.styleable.View_scrollY: 3740 y = a.getDimensionPixelOffset(attr, 0); 3741 break; 3742 case com.android.internal.R.styleable.View_alpha: 3743 setAlpha(a.getFloat(attr, 1f)); 3744 break; 3745 case com.android.internal.R.styleable.View_transformPivotX: 3746 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3747 break; 3748 case com.android.internal.R.styleable.View_transformPivotY: 3749 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3750 break; 3751 case com.android.internal.R.styleable.View_translationX: 3752 tx = a.getDimensionPixelOffset(attr, 0); 3753 transformSet = true; 3754 break; 3755 case com.android.internal.R.styleable.View_translationY: 3756 ty = a.getDimensionPixelOffset(attr, 0); 3757 transformSet = true; 3758 break; 3759 case com.android.internal.R.styleable.View_translationZ: 3760 tz = a.getDimensionPixelOffset(attr, 0); 3761 transformSet = true; 3762 break; 3763 case com.android.internal.R.styleable.View_elevation: 3764 elevation = a.getDimensionPixelOffset(attr, 0); 3765 transformSet = true; 3766 break; 3767 case com.android.internal.R.styleable.View_rotation: 3768 rotation = a.getFloat(attr, 0); 3769 transformSet = true; 3770 break; 3771 case com.android.internal.R.styleable.View_rotationX: 3772 rotationX = a.getFloat(attr, 0); 3773 transformSet = true; 3774 break; 3775 case com.android.internal.R.styleable.View_rotationY: 3776 rotationY = a.getFloat(attr, 0); 3777 transformSet = true; 3778 break; 3779 case com.android.internal.R.styleable.View_scaleX: 3780 sx = a.getFloat(attr, 1f); 3781 transformSet = true; 3782 break; 3783 case com.android.internal.R.styleable.View_scaleY: 3784 sy = a.getFloat(attr, 1f); 3785 transformSet = true; 3786 break; 3787 case com.android.internal.R.styleable.View_id: 3788 mID = a.getResourceId(attr, NO_ID); 3789 break; 3790 case com.android.internal.R.styleable.View_tag: 3791 mTag = a.getText(attr); 3792 break; 3793 case com.android.internal.R.styleable.View_fitsSystemWindows: 3794 if (a.getBoolean(attr, false)) { 3795 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3796 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3797 } 3798 break; 3799 case com.android.internal.R.styleable.View_focusable: 3800 if (a.getBoolean(attr, false)) { 3801 viewFlagValues |= FOCUSABLE; 3802 viewFlagMasks |= FOCUSABLE_MASK; 3803 } 3804 break; 3805 case com.android.internal.R.styleable.View_focusableInTouchMode: 3806 if (a.getBoolean(attr, false)) { 3807 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3808 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3809 } 3810 break; 3811 case com.android.internal.R.styleable.View_clickable: 3812 if (a.getBoolean(attr, false)) { 3813 viewFlagValues |= CLICKABLE; 3814 viewFlagMasks |= CLICKABLE; 3815 } 3816 break; 3817 case com.android.internal.R.styleable.View_longClickable: 3818 if (a.getBoolean(attr, false)) { 3819 viewFlagValues |= LONG_CLICKABLE; 3820 viewFlagMasks |= LONG_CLICKABLE; 3821 } 3822 break; 3823 case com.android.internal.R.styleable.View_saveEnabled: 3824 if (!a.getBoolean(attr, true)) { 3825 viewFlagValues |= SAVE_DISABLED; 3826 viewFlagMasks |= SAVE_DISABLED_MASK; 3827 } 3828 break; 3829 case com.android.internal.R.styleable.View_duplicateParentState: 3830 if (a.getBoolean(attr, false)) { 3831 viewFlagValues |= DUPLICATE_PARENT_STATE; 3832 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3833 } 3834 break; 3835 case com.android.internal.R.styleable.View_visibility: 3836 final int visibility = a.getInt(attr, 0); 3837 if (visibility != 0) { 3838 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3839 viewFlagMasks |= VISIBILITY_MASK; 3840 } 3841 break; 3842 case com.android.internal.R.styleable.View_layoutDirection: 3843 // Clear any layout direction flags (included resolved bits) already set 3844 mPrivateFlags2 &= 3845 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3846 // Set the layout direction flags depending on the value of the attribute 3847 final int layoutDirection = a.getInt(attr, -1); 3848 final int value = (layoutDirection != -1) ? 3849 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3850 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3851 break; 3852 case com.android.internal.R.styleable.View_drawingCacheQuality: 3853 final int cacheQuality = a.getInt(attr, 0); 3854 if (cacheQuality != 0) { 3855 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3856 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3857 } 3858 break; 3859 case com.android.internal.R.styleable.View_contentDescription: 3860 setContentDescription(a.getString(attr)); 3861 break; 3862 case com.android.internal.R.styleable.View_labelFor: 3863 setLabelFor(a.getResourceId(attr, NO_ID)); 3864 break; 3865 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3866 if (!a.getBoolean(attr, true)) { 3867 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3868 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3869 } 3870 break; 3871 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3872 if (!a.getBoolean(attr, true)) { 3873 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3874 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3875 } 3876 break; 3877 case R.styleable.View_scrollbars: 3878 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3879 if (scrollbars != SCROLLBARS_NONE) { 3880 viewFlagValues |= scrollbars; 3881 viewFlagMasks |= SCROLLBARS_MASK; 3882 initializeScrollbars = true; 3883 } 3884 break; 3885 //noinspection deprecation 3886 case R.styleable.View_fadingEdge: 3887 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3888 // Ignore the attribute starting with ICS 3889 break; 3890 } 3891 // With builds < ICS, fall through and apply fading edges 3892 case R.styleable.View_requiresFadingEdge: 3893 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3894 if (fadingEdge != FADING_EDGE_NONE) { 3895 viewFlagValues |= fadingEdge; 3896 viewFlagMasks |= FADING_EDGE_MASK; 3897 initializeFadingEdge(a); 3898 } 3899 break; 3900 case R.styleable.View_scrollbarStyle: 3901 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3902 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3903 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3904 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3905 } 3906 break; 3907 case R.styleable.View_isScrollContainer: 3908 setScrollContainer = true; 3909 if (a.getBoolean(attr, false)) { 3910 setScrollContainer(true); 3911 } 3912 break; 3913 case com.android.internal.R.styleable.View_keepScreenOn: 3914 if (a.getBoolean(attr, false)) { 3915 viewFlagValues |= KEEP_SCREEN_ON; 3916 viewFlagMasks |= KEEP_SCREEN_ON; 3917 } 3918 break; 3919 case R.styleable.View_filterTouchesWhenObscured: 3920 if (a.getBoolean(attr, false)) { 3921 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3922 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3923 } 3924 break; 3925 case R.styleable.View_nextFocusLeft: 3926 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3927 break; 3928 case R.styleable.View_nextFocusRight: 3929 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3930 break; 3931 case R.styleable.View_nextFocusUp: 3932 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3933 break; 3934 case R.styleable.View_nextFocusDown: 3935 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3936 break; 3937 case R.styleable.View_nextFocusForward: 3938 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3939 break; 3940 case R.styleable.View_minWidth: 3941 mMinWidth = a.getDimensionPixelSize(attr, 0); 3942 break; 3943 case R.styleable.View_minHeight: 3944 mMinHeight = a.getDimensionPixelSize(attr, 0); 3945 break; 3946 case R.styleable.View_onClick: 3947 if (context.isRestricted()) { 3948 throw new IllegalStateException("The android:onClick attribute cannot " 3949 + "be used within a restricted context"); 3950 } 3951 3952 final String handlerName = a.getString(attr); 3953 if (handlerName != null) { 3954 setOnClickListener(new OnClickListener() { 3955 private Method mHandler; 3956 3957 public void onClick(View v) { 3958 if (mHandler == null) { 3959 try { 3960 mHandler = getContext().getClass().getMethod(handlerName, 3961 View.class); 3962 } catch (NoSuchMethodException e) { 3963 int id = getId(); 3964 String idText = id == NO_ID ? "" : " with id '" 3965 + getContext().getResources().getResourceEntryName( 3966 id) + "'"; 3967 throw new IllegalStateException("Could not find a method " + 3968 handlerName + "(View) in the activity " 3969 + getContext().getClass() + " for onClick handler" 3970 + " on view " + View.this.getClass() + idText, e); 3971 } 3972 } 3973 3974 try { 3975 mHandler.invoke(getContext(), View.this); 3976 } catch (IllegalAccessException e) { 3977 throw new IllegalStateException("Could not execute non " 3978 + "public method of the activity", e); 3979 } catch (InvocationTargetException e) { 3980 throw new IllegalStateException("Could not execute " 3981 + "method of the activity", e); 3982 } 3983 } 3984 }); 3985 } 3986 break; 3987 case R.styleable.View_overScrollMode: 3988 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3989 break; 3990 case R.styleable.View_verticalScrollbarPosition: 3991 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3992 break; 3993 case R.styleable.View_layerType: 3994 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3995 break; 3996 case R.styleable.View_textDirection: 3997 // Clear any text direction flag already set 3998 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3999 // Set the text direction flags depending on the value of the attribute 4000 final int textDirection = a.getInt(attr, -1); 4001 if (textDirection != -1) { 4002 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4003 } 4004 break; 4005 case R.styleable.View_textAlignment: 4006 // Clear any text alignment flag already set 4007 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4008 // Set the text alignment flag depending on the value of the attribute 4009 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4010 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4011 break; 4012 case R.styleable.View_importantForAccessibility: 4013 setImportantForAccessibility(a.getInt(attr, 4014 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4015 break; 4016 case R.styleable.View_accessibilityLiveRegion: 4017 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4018 break; 4019 case R.styleable.View_transitionName: 4020 setTransitionName(a.getString(attr)); 4021 break; 4022 case R.styleable.View_nestedScrollingEnabled: 4023 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4024 break; 4025 case R.styleable.View_stateListAnimator: 4026 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4027 a.getResourceId(attr, 0))); 4028 break; 4029 case R.styleable.View_backgroundTint: 4030 // This will get applied later during setBackground(). 4031 mBackgroundTint = a.getColorStateList(R.styleable.View_backgroundTint); 4032 mHasBackgroundTint = true; 4033 break; 4034 case R.styleable.View_backgroundTintMode: 4035 // This will get applied later during setBackground(). 4036 mBackgroundTintMode = Drawable.parseTintMode(a.getInt( 4037 R.styleable.View_backgroundTintMode, -1), mBackgroundTintMode); 4038 break; 4039 } 4040 } 4041 4042 setOverScrollMode(overScrollMode); 4043 4044 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4045 // the resolved layout direction). Those cached values will be used later during padding 4046 // resolution. 4047 mUserPaddingStart = startPadding; 4048 mUserPaddingEnd = endPadding; 4049 4050 if (background != null) { 4051 setBackground(background); 4052 } 4053 4054 // setBackground above will record that padding is currently provided by the background. 4055 // If we have padding specified via xml, record that here instead and use it. 4056 mLeftPaddingDefined = leftPaddingDefined; 4057 mRightPaddingDefined = rightPaddingDefined; 4058 4059 if (padding >= 0) { 4060 leftPadding = padding; 4061 topPadding = padding; 4062 rightPadding = padding; 4063 bottomPadding = padding; 4064 mUserPaddingLeftInitial = padding; 4065 mUserPaddingRightInitial = padding; 4066 } 4067 4068 if (isRtlCompatibilityMode()) { 4069 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4070 // left / right padding are used if defined (meaning here nothing to do). If they are not 4071 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4072 // start / end and resolve them as left / right (layout direction is not taken into account). 4073 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4074 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4075 // defined. 4076 if (!mLeftPaddingDefined && startPaddingDefined) { 4077 leftPadding = startPadding; 4078 } 4079 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4080 if (!mRightPaddingDefined && endPaddingDefined) { 4081 rightPadding = endPadding; 4082 } 4083 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4084 } else { 4085 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4086 // values defined. Otherwise, left /right values are used. 4087 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4088 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4089 // defined. 4090 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4091 4092 if (mLeftPaddingDefined && !hasRelativePadding) { 4093 mUserPaddingLeftInitial = leftPadding; 4094 } 4095 if (mRightPaddingDefined && !hasRelativePadding) { 4096 mUserPaddingRightInitial = rightPadding; 4097 } 4098 } 4099 4100 internalSetPadding( 4101 mUserPaddingLeftInitial, 4102 topPadding >= 0 ? topPadding : mPaddingTop, 4103 mUserPaddingRightInitial, 4104 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4105 4106 if (viewFlagMasks != 0) { 4107 setFlags(viewFlagValues, viewFlagMasks); 4108 } 4109 4110 if (initializeScrollbars) { 4111 initializeScrollbars(a); 4112 } 4113 4114 a.recycle(); 4115 4116 // Needs to be called after mViewFlags is set 4117 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4118 recomputePadding(); 4119 } 4120 4121 if (x != 0 || y != 0) { 4122 scrollTo(x, y); 4123 } 4124 4125 if (transformSet) { 4126 setTranslationX(tx); 4127 setTranslationY(ty); 4128 setTranslationZ(tz); 4129 setElevation(elevation); 4130 setRotation(rotation); 4131 setRotationX(rotationX); 4132 setRotationY(rotationY); 4133 setScaleX(sx); 4134 setScaleY(sy); 4135 } 4136 4137 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4138 setScrollContainer(true); 4139 } 4140 4141 computeOpaqueFlags(); 4142 } 4143 4144 /** 4145 * Non-public constructor for use in testing 4146 */ 4147 View() { 4148 mResources = null; 4149 mRenderNode = RenderNode.create(getClass().getName()); 4150 } 4151 4152 public String toString() { 4153 StringBuilder out = new StringBuilder(128); 4154 out.append(getClass().getName()); 4155 out.append('{'); 4156 out.append(Integer.toHexString(System.identityHashCode(this))); 4157 out.append(' '); 4158 switch (mViewFlags&VISIBILITY_MASK) { 4159 case VISIBLE: out.append('V'); break; 4160 case INVISIBLE: out.append('I'); break; 4161 case GONE: out.append('G'); break; 4162 default: out.append('.'); break; 4163 } 4164 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4165 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4166 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4167 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4168 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4169 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4170 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4171 out.append(' '); 4172 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4173 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4174 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4175 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4176 out.append('p'); 4177 } else { 4178 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4179 } 4180 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4181 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4182 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4183 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4184 out.append(' '); 4185 out.append(mLeft); 4186 out.append(','); 4187 out.append(mTop); 4188 out.append('-'); 4189 out.append(mRight); 4190 out.append(','); 4191 out.append(mBottom); 4192 final int id = getId(); 4193 if (id != NO_ID) { 4194 out.append(" #"); 4195 out.append(Integer.toHexString(id)); 4196 final Resources r = mResources; 4197 if (Resources.resourceHasPackage(id) && r != null) { 4198 try { 4199 String pkgname; 4200 switch (id&0xff000000) { 4201 case 0x7f000000: 4202 pkgname="app"; 4203 break; 4204 case 0x01000000: 4205 pkgname="android"; 4206 break; 4207 default: 4208 pkgname = r.getResourcePackageName(id); 4209 break; 4210 } 4211 String typename = r.getResourceTypeName(id); 4212 String entryname = r.getResourceEntryName(id); 4213 out.append(" "); 4214 out.append(pkgname); 4215 out.append(":"); 4216 out.append(typename); 4217 out.append("/"); 4218 out.append(entryname); 4219 } catch (Resources.NotFoundException e) { 4220 } 4221 } 4222 } 4223 out.append("}"); 4224 return out.toString(); 4225 } 4226 4227 /** 4228 * <p> 4229 * Initializes the fading edges from a given set of styled attributes. This 4230 * method should be called by subclasses that need fading edges and when an 4231 * instance of these subclasses is created programmatically rather than 4232 * being inflated from XML. This method is automatically called when the XML 4233 * is inflated. 4234 * </p> 4235 * 4236 * @param a the styled attributes set to initialize the fading edges from 4237 */ 4238 protected void initializeFadingEdge(TypedArray a) { 4239 initScrollCache(); 4240 4241 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4242 R.styleable.View_fadingEdgeLength, 4243 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4244 } 4245 4246 /** 4247 * Returns the size of the vertical faded edges used to indicate that more 4248 * content in this view is visible. 4249 * 4250 * @return The size in pixels of the vertical faded edge or 0 if vertical 4251 * faded edges are not enabled for this view. 4252 * @attr ref android.R.styleable#View_fadingEdgeLength 4253 */ 4254 public int getVerticalFadingEdgeLength() { 4255 if (isVerticalFadingEdgeEnabled()) { 4256 ScrollabilityCache cache = mScrollCache; 4257 if (cache != null) { 4258 return cache.fadingEdgeLength; 4259 } 4260 } 4261 return 0; 4262 } 4263 4264 /** 4265 * Set the size of the faded edge used to indicate that more content in this 4266 * view is available. Will not change whether the fading edge is enabled; use 4267 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4268 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4269 * for the vertical or horizontal fading edges. 4270 * 4271 * @param length The size in pixels of the faded edge used to indicate that more 4272 * content in this view is visible. 4273 */ 4274 public void setFadingEdgeLength(int length) { 4275 initScrollCache(); 4276 mScrollCache.fadingEdgeLength = length; 4277 } 4278 4279 /** 4280 * Returns the size of the horizontal faded edges used to indicate that more 4281 * content in this view is visible. 4282 * 4283 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4284 * faded edges are not enabled for this view. 4285 * @attr ref android.R.styleable#View_fadingEdgeLength 4286 */ 4287 public int getHorizontalFadingEdgeLength() { 4288 if (isHorizontalFadingEdgeEnabled()) { 4289 ScrollabilityCache cache = mScrollCache; 4290 if (cache != null) { 4291 return cache.fadingEdgeLength; 4292 } 4293 } 4294 return 0; 4295 } 4296 4297 /** 4298 * Returns the width of the vertical scrollbar. 4299 * 4300 * @return The width in pixels of the vertical scrollbar or 0 if there 4301 * is no vertical scrollbar. 4302 */ 4303 public int getVerticalScrollbarWidth() { 4304 ScrollabilityCache cache = mScrollCache; 4305 if (cache != null) { 4306 ScrollBarDrawable scrollBar = cache.scrollBar; 4307 if (scrollBar != null) { 4308 int size = scrollBar.getSize(true); 4309 if (size <= 0) { 4310 size = cache.scrollBarSize; 4311 } 4312 return size; 4313 } 4314 return 0; 4315 } 4316 return 0; 4317 } 4318 4319 /** 4320 * Returns the height of the horizontal scrollbar. 4321 * 4322 * @return The height in pixels of the horizontal scrollbar or 0 if 4323 * there is no horizontal scrollbar. 4324 */ 4325 protected int getHorizontalScrollbarHeight() { 4326 ScrollabilityCache cache = mScrollCache; 4327 if (cache != null) { 4328 ScrollBarDrawable scrollBar = cache.scrollBar; 4329 if (scrollBar != null) { 4330 int size = scrollBar.getSize(false); 4331 if (size <= 0) { 4332 size = cache.scrollBarSize; 4333 } 4334 return size; 4335 } 4336 return 0; 4337 } 4338 return 0; 4339 } 4340 4341 /** 4342 * <p> 4343 * Initializes the scrollbars from a given set of styled attributes. This 4344 * method should be called by subclasses that need scrollbars and when an 4345 * instance of these subclasses is created programmatically rather than 4346 * being inflated from XML. This method is automatically called when the XML 4347 * is inflated. 4348 * </p> 4349 * 4350 * @param a the styled attributes set to initialize the scrollbars from 4351 */ 4352 protected void initializeScrollbars(TypedArray a) { 4353 initScrollCache(); 4354 4355 final ScrollabilityCache scrollabilityCache = mScrollCache; 4356 4357 if (scrollabilityCache.scrollBar == null) { 4358 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4359 } 4360 4361 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4362 4363 if (!fadeScrollbars) { 4364 scrollabilityCache.state = ScrollabilityCache.ON; 4365 } 4366 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4367 4368 4369 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4370 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4371 .getScrollBarFadeDuration()); 4372 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4373 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4374 ViewConfiguration.getScrollDefaultDelay()); 4375 4376 4377 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4378 com.android.internal.R.styleable.View_scrollbarSize, 4379 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4380 4381 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4382 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4383 4384 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4385 if (thumb != null) { 4386 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4387 } 4388 4389 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4390 false); 4391 if (alwaysDraw) { 4392 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4393 } 4394 4395 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4396 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4397 4398 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4399 if (thumb != null) { 4400 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4401 } 4402 4403 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4404 false); 4405 if (alwaysDraw) { 4406 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4407 } 4408 4409 // Apply layout direction to the new Drawables if needed 4410 final int layoutDirection = getLayoutDirection(); 4411 if (track != null) { 4412 track.setLayoutDirection(layoutDirection); 4413 } 4414 if (thumb != null) { 4415 thumb.setLayoutDirection(layoutDirection); 4416 } 4417 4418 // Re-apply user/background padding so that scrollbar(s) get added 4419 resolvePadding(); 4420 } 4421 4422 /** 4423 * <p> 4424 * Initalizes the scrollability cache if necessary. 4425 * </p> 4426 */ 4427 private void initScrollCache() { 4428 if (mScrollCache == null) { 4429 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4430 } 4431 } 4432 4433 private ScrollabilityCache getScrollCache() { 4434 initScrollCache(); 4435 return mScrollCache; 4436 } 4437 4438 /** 4439 * Set the position of the vertical scroll bar. Should be one of 4440 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4441 * {@link #SCROLLBAR_POSITION_RIGHT}. 4442 * 4443 * @param position Where the vertical scroll bar should be positioned. 4444 */ 4445 public void setVerticalScrollbarPosition(int position) { 4446 if (mVerticalScrollbarPosition != position) { 4447 mVerticalScrollbarPosition = position; 4448 computeOpaqueFlags(); 4449 resolvePadding(); 4450 } 4451 } 4452 4453 /** 4454 * @return The position where the vertical scroll bar will show, if applicable. 4455 * @see #setVerticalScrollbarPosition(int) 4456 */ 4457 public int getVerticalScrollbarPosition() { 4458 return mVerticalScrollbarPosition; 4459 } 4460 4461 ListenerInfo getListenerInfo() { 4462 if (mListenerInfo != null) { 4463 return mListenerInfo; 4464 } 4465 mListenerInfo = new ListenerInfo(); 4466 return mListenerInfo; 4467 } 4468 4469 /** 4470 * Register a callback to be invoked when focus of this view changed. 4471 * 4472 * @param l The callback that will run. 4473 */ 4474 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4475 getListenerInfo().mOnFocusChangeListener = l; 4476 } 4477 4478 /** 4479 * Add a listener that will be called when the bounds of the view change due to 4480 * layout processing. 4481 * 4482 * @param listener The listener that will be called when layout bounds change. 4483 */ 4484 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4485 ListenerInfo li = getListenerInfo(); 4486 if (li.mOnLayoutChangeListeners == null) { 4487 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4488 } 4489 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4490 li.mOnLayoutChangeListeners.add(listener); 4491 } 4492 } 4493 4494 /** 4495 * Remove a listener for layout changes. 4496 * 4497 * @param listener The listener for layout bounds change. 4498 */ 4499 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4500 ListenerInfo li = mListenerInfo; 4501 if (li == null || li.mOnLayoutChangeListeners == null) { 4502 return; 4503 } 4504 li.mOnLayoutChangeListeners.remove(listener); 4505 } 4506 4507 /** 4508 * Add a listener for attach state changes. 4509 * 4510 * This listener will be called whenever this view is attached or detached 4511 * from a window. Remove the listener using 4512 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4513 * 4514 * @param listener Listener to attach 4515 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4516 */ 4517 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4518 ListenerInfo li = getListenerInfo(); 4519 if (li.mOnAttachStateChangeListeners == null) { 4520 li.mOnAttachStateChangeListeners 4521 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4522 } 4523 li.mOnAttachStateChangeListeners.add(listener); 4524 } 4525 4526 /** 4527 * Remove a listener for attach state changes. The listener will receive no further 4528 * notification of window attach/detach events. 4529 * 4530 * @param listener Listener to remove 4531 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4532 */ 4533 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4534 ListenerInfo li = mListenerInfo; 4535 if (li == null || li.mOnAttachStateChangeListeners == null) { 4536 return; 4537 } 4538 li.mOnAttachStateChangeListeners.remove(listener); 4539 } 4540 4541 /** 4542 * Returns the focus-change callback registered for this view. 4543 * 4544 * @return The callback, or null if one is not registered. 4545 */ 4546 public OnFocusChangeListener getOnFocusChangeListener() { 4547 ListenerInfo li = mListenerInfo; 4548 return li != null ? li.mOnFocusChangeListener : null; 4549 } 4550 4551 /** 4552 * Register a callback to be invoked when this view is clicked. If this view is not 4553 * clickable, it becomes clickable. 4554 * 4555 * @param l The callback that will run 4556 * 4557 * @see #setClickable(boolean) 4558 */ 4559 public void setOnClickListener(OnClickListener l) { 4560 if (!isClickable()) { 4561 setClickable(true); 4562 } 4563 getListenerInfo().mOnClickListener = l; 4564 } 4565 4566 /** 4567 * Return whether this view has an attached OnClickListener. Returns 4568 * true if there is a listener, false if there is none. 4569 */ 4570 public boolean hasOnClickListeners() { 4571 ListenerInfo li = mListenerInfo; 4572 return (li != null && li.mOnClickListener != null); 4573 } 4574 4575 /** 4576 * Register a callback to be invoked when this view is clicked and held. If this view is not 4577 * long clickable, it becomes long clickable. 4578 * 4579 * @param l The callback that will run 4580 * 4581 * @see #setLongClickable(boolean) 4582 */ 4583 public void setOnLongClickListener(OnLongClickListener l) { 4584 if (!isLongClickable()) { 4585 setLongClickable(true); 4586 } 4587 getListenerInfo().mOnLongClickListener = l; 4588 } 4589 4590 /** 4591 * Register a callback to be invoked when the context menu for this view is 4592 * being built. If this view is not long clickable, it becomes long clickable. 4593 * 4594 * @param l The callback that will run 4595 * 4596 */ 4597 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4598 if (!isLongClickable()) { 4599 setLongClickable(true); 4600 } 4601 getListenerInfo().mOnCreateContextMenuListener = l; 4602 } 4603 4604 /** 4605 * Call this view's OnClickListener, if it is defined. Performs all normal 4606 * actions associated with clicking: reporting accessibility event, playing 4607 * a sound, etc. 4608 * 4609 * @return True there was an assigned OnClickListener that was called, false 4610 * otherwise is returned. 4611 */ 4612 public boolean performClick() { 4613 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4614 4615 ListenerInfo li = mListenerInfo; 4616 if (li != null && li.mOnClickListener != null) { 4617 playSoundEffect(SoundEffectConstants.CLICK); 4618 li.mOnClickListener.onClick(this); 4619 return true; 4620 } 4621 4622 return false; 4623 } 4624 4625 /** 4626 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4627 * this only calls the listener, and does not do any associated clicking 4628 * actions like reporting an accessibility event. 4629 * 4630 * @return True there was an assigned OnClickListener that was called, false 4631 * otherwise is returned. 4632 */ 4633 public boolean callOnClick() { 4634 ListenerInfo li = mListenerInfo; 4635 if (li != null && li.mOnClickListener != null) { 4636 li.mOnClickListener.onClick(this); 4637 return true; 4638 } 4639 return false; 4640 } 4641 4642 /** 4643 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4644 * OnLongClickListener did not consume the event. 4645 * 4646 * @return True if one of the above receivers consumed the event, false otherwise. 4647 */ 4648 public boolean performLongClick() { 4649 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4650 4651 boolean handled = false; 4652 ListenerInfo li = mListenerInfo; 4653 if (li != null && li.mOnLongClickListener != null) { 4654 handled = li.mOnLongClickListener.onLongClick(View.this); 4655 } 4656 if (!handled) { 4657 handled = showContextMenu(); 4658 } 4659 if (handled) { 4660 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4661 } 4662 return handled; 4663 } 4664 4665 /** 4666 * Performs button-related actions during a touch down event. 4667 * 4668 * @param event The event. 4669 * @return True if the down was consumed. 4670 * 4671 * @hide 4672 */ 4673 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4674 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4675 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4676 return true; 4677 } 4678 } 4679 return false; 4680 } 4681 4682 /** 4683 * Bring up the context menu for this view. 4684 * 4685 * @return Whether a context menu was displayed. 4686 */ 4687 public boolean showContextMenu() { 4688 return getParent().showContextMenuForChild(this); 4689 } 4690 4691 /** 4692 * Bring up the context menu for this view, referring to the item under the specified point. 4693 * 4694 * @param x The referenced x coordinate. 4695 * @param y The referenced y coordinate. 4696 * @param metaState The keyboard modifiers that were pressed. 4697 * @return Whether a context menu was displayed. 4698 * 4699 * @hide 4700 */ 4701 public boolean showContextMenu(float x, float y, int metaState) { 4702 return showContextMenu(); 4703 } 4704 4705 /** 4706 * Start an action mode. 4707 * 4708 * @param callback Callback that will control the lifecycle of the action mode 4709 * @return The new action mode if it is started, null otherwise 4710 * 4711 * @see ActionMode 4712 */ 4713 public ActionMode startActionMode(ActionMode.Callback callback) { 4714 ViewParent parent = getParent(); 4715 if (parent == null) return null; 4716 return parent.startActionModeForChild(this, callback); 4717 } 4718 4719 /** 4720 * Register a callback to be invoked when a hardware key is pressed in this view. 4721 * Key presses in software input methods will generally not trigger the methods of 4722 * this listener. 4723 * @param l the key listener to attach to this view 4724 */ 4725 public void setOnKeyListener(OnKeyListener l) { 4726 getListenerInfo().mOnKeyListener = l; 4727 } 4728 4729 /** 4730 * Register a callback to be invoked when a touch event is sent to this view. 4731 * @param l the touch listener to attach to this view 4732 */ 4733 public void setOnTouchListener(OnTouchListener l) { 4734 getListenerInfo().mOnTouchListener = l; 4735 } 4736 4737 /** 4738 * Register a callback to be invoked when a generic motion event is sent to this view. 4739 * @param l the generic motion listener to attach to this view 4740 */ 4741 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4742 getListenerInfo().mOnGenericMotionListener = l; 4743 } 4744 4745 /** 4746 * Register a callback to be invoked when a hover event is sent to this view. 4747 * @param l the hover listener to attach to this view 4748 */ 4749 public void setOnHoverListener(OnHoverListener l) { 4750 getListenerInfo().mOnHoverListener = l; 4751 } 4752 4753 /** 4754 * Register a drag event listener callback object for this View. The parameter is 4755 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4756 * View, the system calls the 4757 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4758 * @param l An implementation of {@link android.view.View.OnDragListener}. 4759 */ 4760 public void setOnDragListener(OnDragListener l) { 4761 getListenerInfo().mOnDragListener = l; 4762 } 4763 4764 /** 4765 * Give this view focus. This will cause 4766 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4767 * 4768 * Note: this does not check whether this {@link View} should get focus, it just 4769 * gives it focus no matter what. It should only be called internally by framework 4770 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4771 * 4772 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4773 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4774 * focus moved when requestFocus() is called. It may not always 4775 * apply, in which case use the default View.FOCUS_DOWN. 4776 * @param previouslyFocusedRect The rectangle of the view that had focus 4777 * prior in this View's coordinate system. 4778 */ 4779 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4780 if (DBG) { 4781 System.out.println(this + " requestFocus()"); 4782 } 4783 4784 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4785 mPrivateFlags |= PFLAG_FOCUSED; 4786 4787 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4788 4789 if (mParent != null) { 4790 mParent.requestChildFocus(this, this); 4791 } 4792 4793 if (mAttachInfo != null) { 4794 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4795 } 4796 4797 onFocusChanged(true, direction, previouslyFocusedRect); 4798 manageFocusHotspot(true, oldFocus); 4799 refreshDrawableState(); 4800 } 4801 } 4802 4803 /** 4804 * Forwards focus information to the background drawable, if necessary. When 4805 * the view is gaining focus, <code>v</code> is the previous focus holder. 4806 * When the view is losing focus, <code>v</code> is the next focus holder. 4807 * 4808 * @param focused whether this view is focused 4809 * @param v previous or the next focus holder, or null if none 4810 */ 4811 private void manageFocusHotspot(boolean focused, View v) { 4812 final Rect r = new Rect(); 4813 if (!focused && v != null && mAttachInfo != null) { 4814 v.getBoundsOnScreen(r); 4815 final int[] location = mAttachInfo.mTmpLocation; 4816 getLocationOnScreen(location); 4817 r.offset(-location[0], -location[1]); 4818 } else { 4819 r.set(0, 0, mRight - mLeft, mBottom - mTop); 4820 } 4821 4822 final float x = r.exactCenterX(); 4823 final float y = r.exactCenterY(); 4824 drawableHotspotChanged(x, y); 4825 } 4826 4827 /** 4828 * Request that a rectangle of this view be visible on the screen, 4829 * scrolling if necessary just enough. 4830 * 4831 * <p>A View should call this if it maintains some notion of which part 4832 * of its content is interesting. For example, a text editing view 4833 * should call this when its cursor moves. 4834 * 4835 * @param rectangle The rectangle. 4836 * @return Whether any parent scrolled. 4837 */ 4838 public boolean requestRectangleOnScreen(Rect rectangle) { 4839 return requestRectangleOnScreen(rectangle, false); 4840 } 4841 4842 /** 4843 * Request that a rectangle of this view be visible on the screen, 4844 * scrolling if necessary just enough. 4845 * 4846 * <p>A View should call this if it maintains some notion of which part 4847 * of its content is interesting. For example, a text editing view 4848 * should call this when its cursor moves. 4849 * 4850 * <p>When <code>immediate</code> is set to true, scrolling will not be 4851 * animated. 4852 * 4853 * @param rectangle The rectangle. 4854 * @param immediate True to forbid animated scrolling, false otherwise 4855 * @return Whether any parent scrolled. 4856 */ 4857 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4858 if (mParent == null) { 4859 return false; 4860 } 4861 4862 View child = this; 4863 4864 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4865 position.set(rectangle); 4866 4867 ViewParent parent = mParent; 4868 boolean scrolled = false; 4869 while (parent != null) { 4870 rectangle.set((int) position.left, (int) position.top, 4871 (int) position.right, (int) position.bottom); 4872 4873 scrolled |= parent.requestChildRectangleOnScreen(child, 4874 rectangle, immediate); 4875 4876 if (!child.hasIdentityMatrix()) { 4877 child.getMatrix().mapRect(position); 4878 } 4879 4880 position.offset(child.mLeft, child.mTop); 4881 4882 if (!(parent instanceof View)) { 4883 break; 4884 } 4885 4886 View parentView = (View) parent; 4887 4888 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4889 4890 child = parentView; 4891 parent = child.getParent(); 4892 } 4893 4894 return scrolled; 4895 } 4896 4897 /** 4898 * Called when this view wants to give up focus. If focus is cleared 4899 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4900 * <p> 4901 * <strong>Note:</strong> When a View clears focus the framework is trying 4902 * to give focus to the first focusable View from the top. Hence, if this 4903 * View is the first from the top that can take focus, then all callbacks 4904 * related to clearing focus will be invoked after wich the framework will 4905 * give focus to this view. 4906 * </p> 4907 */ 4908 public void clearFocus() { 4909 if (DBG) { 4910 System.out.println(this + " clearFocus()"); 4911 } 4912 4913 clearFocusInternal(null, true, true); 4914 } 4915 4916 /** 4917 * Clears focus from the view, optionally propagating the change up through 4918 * the parent hierarchy and requesting that the root view place new focus. 4919 * 4920 * @param propagate whether to propagate the change up through the parent 4921 * hierarchy 4922 * @param refocus when propagate is true, specifies whether to request the 4923 * root view place new focus 4924 */ 4925 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4926 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4927 mPrivateFlags &= ~PFLAG_FOCUSED; 4928 4929 if (propagate && mParent != null) { 4930 mParent.clearChildFocus(this); 4931 } 4932 4933 onFocusChanged(false, 0, null); 4934 4935 manageFocusHotspot(false, focused); 4936 refreshDrawableState(); 4937 4938 if (propagate && (!refocus || !rootViewRequestFocus())) { 4939 notifyGlobalFocusCleared(this); 4940 } 4941 } 4942 } 4943 4944 void notifyGlobalFocusCleared(View oldFocus) { 4945 if (oldFocus != null && mAttachInfo != null) { 4946 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4947 } 4948 } 4949 4950 boolean rootViewRequestFocus() { 4951 final View root = getRootView(); 4952 return root != null && root.requestFocus(); 4953 } 4954 4955 /** 4956 * Called internally by the view system when a new view is getting focus. 4957 * This is what clears the old focus. 4958 * <p> 4959 * <b>NOTE:</b> The parent view's focused child must be updated manually 4960 * after calling this method. Otherwise, the view hierarchy may be left in 4961 * an inconstent state. 4962 */ 4963 void unFocus(View focused) { 4964 if (DBG) { 4965 System.out.println(this + " unFocus()"); 4966 } 4967 4968 clearFocusInternal(focused, false, false); 4969 } 4970 4971 /** 4972 * Returns true if this view has focus iteself, or is the ancestor of the 4973 * view that has focus. 4974 * 4975 * @return True if this view has or contains focus, false otherwise. 4976 */ 4977 @ViewDebug.ExportedProperty(category = "focus") 4978 public boolean hasFocus() { 4979 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4980 } 4981 4982 /** 4983 * Returns true if this view is focusable or if it contains a reachable View 4984 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4985 * is a View whose parents do not block descendants focus. 4986 * 4987 * Only {@link #VISIBLE} views are considered focusable. 4988 * 4989 * @return True if the view is focusable or if the view contains a focusable 4990 * View, false otherwise. 4991 * 4992 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4993 */ 4994 public boolean hasFocusable() { 4995 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4996 } 4997 4998 /** 4999 * Called by the view system when the focus state of this view changes. 5000 * When the focus change event is caused by directional navigation, direction 5001 * and previouslyFocusedRect provide insight into where the focus is coming from. 5002 * When overriding, be sure to call up through to the super class so that 5003 * the standard focus handling will occur. 5004 * 5005 * @param gainFocus True if the View has focus; false otherwise. 5006 * @param direction The direction focus has moved when requestFocus() 5007 * is called to give this view focus. Values are 5008 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5009 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5010 * It may not always apply, in which case use the default. 5011 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5012 * system, of the previously focused view. If applicable, this will be 5013 * passed in as finer grained information about where the focus is coming 5014 * from (in addition to direction). Will be <code>null</code> otherwise. 5015 */ 5016 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5017 @Nullable Rect previouslyFocusedRect) { 5018 if (gainFocus) { 5019 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5020 } else { 5021 notifyViewAccessibilityStateChangedIfNeeded( 5022 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5023 } 5024 5025 InputMethodManager imm = InputMethodManager.peekInstance(); 5026 if (!gainFocus) { 5027 if (isPressed()) { 5028 setPressed(false); 5029 } 5030 if (imm != null && mAttachInfo != null 5031 && mAttachInfo.mHasWindowFocus) { 5032 imm.focusOut(this); 5033 } 5034 onFocusLost(); 5035 } else if (imm != null && mAttachInfo != null 5036 && mAttachInfo.mHasWindowFocus) { 5037 imm.focusIn(this); 5038 } 5039 5040 invalidate(true); 5041 ListenerInfo li = mListenerInfo; 5042 if (li != null && li.mOnFocusChangeListener != null) { 5043 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5044 } 5045 5046 if (mAttachInfo != null) { 5047 mAttachInfo.mKeyDispatchState.reset(this); 5048 } 5049 } 5050 5051 /** 5052 * Sends an accessibility event of the given type. If accessibility is 5053 * not enabled this method has no effect. The default implementation calls 5054 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5055 * to populate information about the event source (this View), then calls 5056 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5057 * populate the text content of the event source including its descendants, 5058 * and last calls 5059 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5060 * on its parent to resuest sending of the event to interested parties. 5061 * <p> 5062 * If an {@link AccessibilityDelegate} has been specified via calling 5063 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5064 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5065 * responsible for handling this call. 5066 * </p> 5067 * 5068 * @param eventType The type of the event to send, as defined by several types from 5069 * {@link android.view.accessibility.AccessibilityEvent}, such as 5070 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5071 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5072 * 5073 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5074 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5075 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5076 * @see AccessibilityDelegate 5077 */ 5078 public void sendAccessibilityEvent(int eventType) { 5079 if (mAccessibilityDelegate != null) { 5080 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5081 } else { 5082 sendAccessibilityEventInternal(eventType); 5083 } 5084 } 5085 5086 /** 5087 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5088 * {@link AccessibilityEvent} to make an announcement which is related to some 5089 * sort of a context change for which none of the events representing UI transitions 5090 * is a good fit. For example, announcing a new page in a book. If accessibility 5091 * is not enabled this method does nothing. 5092 * 5093 * @param text The announcement text. 5094 */ 5095 public void announceForAccessibility(CharSequence text) { 5096 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5097 AccessibilityEvent event = AccessibilityEvent.obtain( 5098 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5099 onInitializeAccessibilityEvent(event); 5100 event.getText().add(text); 5101 event.setContentDescription(null); 5102 mParent.requestSendAccessibilityEvent(this, event); 5103 } 5104 } 5105 5106 /** 5107 * @see #sendAccessibilityEvent(int) 5108 * 5109 * Note: Called from the default {@link AccessibilityDelegate}. 5110 */ 5111 void sendAccessibilityEventInternal(int eventType) { 5112 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5113 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5114 } 5115 } 5116 5117 /** 5118 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5119 * takes as an argument an empty {@link AccessibilityEvent} and does not 5120 * perform a check whether accessibility is enabled. 5121 * <p> 5122 * If an {@link AccessibilityDelegate} has been specified via calling 5123 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5124 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5125 * is responsible for handling this call. 5126 * </p> 5127 * 5128 * @param event The event to send. 5129 * 5130 * @see #sendAccessibilityEvent(int) 5131 */ 5132 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5133 if (mAccessibilityDelegate != null) { 5134 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5135 } else { 5136 sendAccessibilityEventUncheckedInternal(event); 5137 } 5138 } 5139 5140 /** 5141 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5142 * 5143 * Note: Called from the default {@link AccessibilityDelegate}. 5144 */ 5145 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5146 if (!isShown()) { 5147 return; 5148 } 5149 onInitializeAccessibilityEvent(event); 5150 // Only a subset of accessibility events populates text content. 5151 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5152 dispatchPopulateAccessibilityEvent(event); 5153 } 5154 // In the beginning we called #isShown(), so we know that getParent() is not null. 5155 getParent().requestSendAccessibilityEvent(this, event); 5156 } 5157 5158 /** 5159 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5160 * to its children for adding their text content to the event. Note that the 5161 * event text is populated in a separate dispatch path since we add to the 5162 * event not only the text of the source but also the text of all its descendants. 5163 * A typical implementation will call 5164 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5165 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5166 * on each child. Override this method if custom population of the event text 5167 * content is required. 5168 * <p> 5169 * If an {@link AccessibilityDelegate} has been specified via calling 5170 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5171 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5172 * is responsible for handling this call. 5173 * </p> 5174 * <p> 5175 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5176 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5177 * </p> 5178 * 5179 * @param event The event. 5180 * 5181 * @return True if the event population was completed. 5182 */ 5183 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5184 if (mAccessibilityDelegate != null) { 5185 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5186 } else { 5187 return dispatchPopulateAccessibilityEventInternal(event); 5188 } 5189 } 5190 5191 /** 5192 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5193 * 5194 * Note: Called from the default {@link AccessibilityDelegate}. 5195 */ 5196 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5197 onPopulateAccessibilityEvent(event); 5198 return false; 5199 } 5200 5201 /** 5202 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5203 * giving a chance to this View to populate the accessibility event with its 5204 * text content. While this method is free to modify event 5205 * attributes other than text content, doing so should normally be performed in 5206 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5207 * <p> 5208 * Example: Adding formatted date string to an accessibility event in addition 5209 * to the text added by the super implementation: 5210 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5211 * super.onPopulateAccessibilityEvent(event); 5212 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5213 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5214 * mCurrentDate.getTimeInMillis(), flags); 5215 * event.getText().add(selectedDateUtterance); 5216 * }</pre> 5217 * <p> 5218 * If an {@link AccessibilityDelegate} has been specified via calling 5219 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5220 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5221 * is responsible for handling this call. 5222 * </p> 5223 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5224 * information to the event, in case the default implementation has basic information to add. 5225 * </p> 5226 * 5227 * @param event The accessibility event which to populate. 5228 * 5229 * @see #sendAccessibilityEvent(int) 5230 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5231 */ 5232 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5233 if (mAccessibilityDelegate != null) { 5234 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5235 } else { 5236 onPopulateAccessibilityEventInternal(event); 5237 } 5238 } 5239 5240 /** 5241 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5242 * 5243 * Note: Called from the default {@link AccessibilityDelegate}. 5244 */ 5245 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5246 } 5247 5248 /** 5249 * Initializes an {@link AccessibilityEvent} with information about 5250 * this View which is the event source. In other words, the source of 5251 * an accessibility event is the view whose state change triggered firing 5252 * the event. 5253 * <p> 5254 * Example: Setting the password property of an event in addition 5255 * to properties set by the super implementation: 5256 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5257 * super.onInitializeAccessibilityEvent(event); 5258 * event.setPassword(true); 5259 * }</pre> 5260 * <p> 5261 * If an {@link AccessibilityDelegate} has been specified via calling 5262 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5263 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5264 * is responsible for handling this call. 5265 * </p> 5266 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5267 * information to the event, in case the default implementation has basic information to add. 5268 * </p> 5269 * @param event The event to initialize. 5270 * 5271 * @see #sendAccessibilityEvent(int) 5272 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5273 */ 5274 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5275 if (mAccessibilityDelegate != null) { 5276 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5277 } else { 5278 onInitializeAccessibilityEventInternal(event); 5279 } 5280 } 5281 5282 /** 5283 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5284 * 5285 * Note: Called from the default {@link AccessibilityDelegate}. 5286 */ 5287 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5288 event.setSource(this); 5289 event.setClassName(View.class.getName()); 5290 event.setPackageName(getContext().getPackageName()); 5291 event.setEnabled(isEnabled()); 5292 event.setContentDescription(mContentDescription); 5293 5294 switch (event.getEventType()) { 5295 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5296 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5297 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5298 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5299 event.setItemCount(focusablesTempList.size()); 5300 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5301 if (mAttachInfo != null) { 5302 focusablesTempList.clear(); 5303 } 5304 } break; 5305 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5306 CharSequence text = getIterableTextForAccessibility(); 5307 if (text != null && text.length() > 0) { 5308 event.setFromIndex(getAccessibilitySelectionStart()); 5309 event.setToIndex(getAccessibilitySelectionEnd()); 5310 event.setItemCount(text.length()); 5311 } 5312 } break; 5313 } 5314 } 5315 5316 /** 5317 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5318 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5319 * This method is responsible for obtaining an accessibility node info from a 5320 * pool of reusable instances and calling 5321 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5322 * initialize the former. 5323 * <p> 5324 * Note: The client is responsible for recycling the obtained instance by calling 5325 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5326 * </p> 5327 * 5328 * @return A populated {@link AccessibilityNodeInfo}. 5329 * 5330 * @see AccessibilityNodeInfo 5331 */ 5332 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5333 if (mAccessibilityDelegate != null) { 5334 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5335 } else { 5336 return createAccessibilityNodeInfoInternal(); 5337 } 5338 } 5339 5340 /** 5341 * @see #createAccessibilityNodeInfo() 5342 */ 5343 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5344 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5345 if (provider != null) { 5346 return provider.createAccessibilityNodeInfo(View.NO_ID); 5347 } else { 5348 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5349 onInitializeAccessibilityNodeInfo(info); 5350 return info; 5351 } 5352 } 5353 5354 /** 5355 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5356 * The base implementation sets: 5357 * <ul> 5358 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5359 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5360 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5361 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5362 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5363 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5364 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5365 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5366 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5367 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5368 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5369 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5370 * </ul> 5371 * <p> 5372 * Subclasses should override this method, call the super implementation, 5373 * and set additional attributes. 5374 * </p> 5375 * <p> 5376 * If an {@link AccessibilityDelegate} has been specified via calling 5377 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5378 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5379 * is responsible for handling this call. 5380 * </p> 5381 * 5382 * @param info The instance to initialize. 5383 */ 5384 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5385 if (mAccessibilityDelegate != null) { 5386 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5387 } else { 5388 onInitializeAccessibilityNodeInfoInternal(info); 5389 } 5390 } 5391 5392 /** 5393 * Gets the location of this view in screen coordintates. 5394 * 5395 * @param outRect The output location 5396 * @hide 5397 */ 5398 public void getBoundsOnScreen(Rect outRect) { 5399 if (mAttachInfo == null) { 5400 return; 5401 } 5402 5403 RectF position = mAttachInfo.mTmpTransformRect; 5404 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5405 5406 if (!hasIdentityMatrix()) { 5407 getMatrix().mapRect(position); 5408 } 5409 5410 position.offset(mLeft, mTop); 5411 5412 ViewParent parent = mParent; 5413 while (parent instanceof View) { 5414 View parentView = (View) parent; 5415 5416 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5417 5418 if (!parentView.hasIdentityMatrix()) { 5419 parentView.getMatrix().mapRect(position); 5420 } 5421 5422 position.offset(parentView.mLeft, parentView.mTop); 5423 5424 parent = parentView.mParent; 5425 } 5426 5427 if (parent instanceof ViewRootImpl) { 5428 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5429 position.offset(0, -viewRootImpl.mCurScrollY); 5430 } 5431 5432 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5433 5434 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5435 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5436 } 5437 5438 /** 5439 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5440 * 5441 * Note: Called from the default {@link AccessibilityDelegate}. 5442 */ 5443 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5444 Rect bounds = mAttachInfo.mTmpInvalRect; 5445 5446 getDrawingRect(bounds); 5447 info.setBoundsInParent(bounds); 5448 5449 getBoundsOnScreen(bounds); 5450 info.setBoundsInScreen(bounds); 5451 5452 ViewParent parent = getParentForAccessibility(); 5453 if (parent instanceof View) { 5454 info.setParent((View) parent); 5455 } 5456 5457 if (mID != View.NO_ID) { 5458 View rootView = getRootView(); 5459 if (rootView == null) { 5460 rootView = this; 5461 } 5462 View label = rootView.findLabelForView(this, mID); 5463 if (label != null) { 5464 info.setLabeledBy(label); 5465 } 5466 5467 if ((mAttachInfo.mAccessibilityFetchFlags 5468 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5469 && Resources.resourceHasPackage(mID)) { 5470 try { 5471 String viewId = getResources().getResourceName(mID); 5472 info.setViewIdResourceName(viewId); 5473 } catch (Resources.NotFoundException nfe) { 5474 /* ignore */ 5475 } 5476 } 5477 } 5478 5479 if (mLabelForId != View.NO_ID) { 5480 View rootView = getRootView(); 5481 if (rootView == null) { 5482 rootView = this; 5483 } 5484 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5485 if (labeled != null) { 5486 info.setLabelFor(labeled); 5487 } 5488 } 5489 5490 info.setVisibleToUser(isVisibleToUser()); 5491 5492 info.setPackageName(mContext.getPackageName()); 5493 info.setClassName(View.class.getName()); 5494 info.setContentDescription(getContentDescription()); 5495 5496 info.setEnabled(isEnabled()); 5497 info.setClickable(isClickable()); 5498 info.setFocusable(isFocusable()); 5499 info.setFocused(isFocused()); 5500 info.setAccessibilityFocused(isAccessibilityFocused()); 5501 info.setSelected(isSelected()); 5502 info.setLongClickable(isLongClickable()); 5503 info.setLiveRegion(getAccessibilityLiveRegion()); 5504 5505 // TODO: These make sense only if we are in an AdapterView but all 5506 // views can be selected. Maybe from accessibility perspective 5507 // we should report as selectable view in an AdapterView. 5508 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5509 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5510 5511 if (isFocusable()) { 5512 if (isFocused()) { 5513 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5514 } else { 5515 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5516 } 5517 } 5518 5519 if (!isAccessibilityFocused()) { 5520 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5521 } else { 5522 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5523 } 5524 5525 if (isClickable() && isEnabled()) { 5526 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5527 } 5528 5529 if (isLongClickable() && isEnabled()) { 5530 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5531 } 5532 5533 CharSequence text = getIterableTextForAccessibility(); 5534 if (text != null && text.length() > 0) { 5535 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5536 5537 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5538 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5539 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5540 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5541 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5542 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5543 } 5544 } 5545 5546 private View findLabelForView(View view, int labeledId) { 5547 if (mMatchLabelForPredicate == null) { 5548 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5549 } 5550 mMatchLabelForPredicate.mLabeledId = labeledId; 5551 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5552 } 5553 5554 /** 5555 * Computes whether this view is visible to the user. Such a view is 5556 * attached, visible, all its predecessors are visible, it is not clipped 5557 * entirely by its predecessors, and has an alpha greater than zero. 5558 * 5559 * @return Whether the view is visible on the screen. 5560 * 5561 * @hide 5562 */ 5563 protected boolean isVisibleToUser() { 5564 return isVisibleToUser(null); 5565 } 5566 5567 /** 5568 * Computes whether the given portion of this view is visible to the user. 5569 * Such a view is attached, visible, all its predecessors are visible, 5570 * has an alpha greater than zero, and the specified portion is not 5571 * clipped entirely by its predecessors. 5572 * 5573 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5574 * <code>null</code>, and the entire view will be tested in this case. 5575 * When <code>true</code> is returned by the function, the actual visible 5576 * region will be stored in this parameter; that is, if boundInView is fully 5577 * contained within the view, no modification will be made, otherwise regions 5578 * outside of the visible area of the view will be clipped. 5579 * 5580 * @return Whether the specified portion of the view is visible on the screen. 5581 * 5582 * @hide 5583 */ 5584 protected boolean isVisibleToUser(Rect boundInView) { 5585 if (mAttachInfo != null) { 5586 // Attached to invisible window means this view is not visible. 5587 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5588 return false; 5589 } 5590 // An invisible predecessor or one with alpha zero means 5591 // that this view is not visible to the user. 5592 Object current = this; 5593 while (current instanceof View) { 5594 View view = (View) current; 5595 // We have attach info so this view is attached and there is no 5596 // need to check whether we reach to ViewRootImpl on the way up. 5597 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5598 view.getVisibility() != VISIBLE) { 5599 return false; 5600 } 5601 current = view.mParent; 5602 } 5603 // Check if the view is entirely covered by its predecessors. 5604 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5605 Point offset = mAttachInfo.mPoint; 5606 if (!getGlobalVisibleRect(visibleRect, offset)) { 5607 return false; 5608 } 5609 // Check if the visible portion intersects the rectangle of interest. 5610 if (boundInView != null) { 5611 visibleRect.offset(-offset.x, -offset.y); 5612 return boundInView.intersect(visibleRect); 5613 } 5614 return true; 5615 } 5616 return false; 5617 } 5618 5619 /** 5620 * Returns the delegate for implementing accessibility support via 5621 * composition. For more details see {@link AccessibilityDelegate}. 5622 * 5623 * @return The delegate, or null if none set. 5624 * 5625 * @hide 5626 */ 5627 public AccessibilityDelegate getAccessibilityDelegate() { 5628 return mAccessibilityDelegate; 5629 } 5630 5631 /** 5632 * Sets a delegate for implementing accessibility support via composition as 5633 * opposed to inheritance. The delegate's primary use is for implementing 5634 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5635 * 5636 * @param delegate The delegate instance. 5637 * 5638 * @see AccessibilityDelegate 5639 */ 5640 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5641 mAccessibilityDelegate = delegate; 5642 } 5643 5644 /** 5645 * Gets the provider for managing a virtual view hierarchy rooted at this View 5646 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5647 * that explore the window content. 5648 * <p> 5649 * If this method returns an instance, this instance is responsible for managing 5650 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5651 * View including the one representing the View itself. Similarly the returned 5652 * instance is responsible for performing accessibility actions on any virtual 5653 * view or the root view itself. 5654 * </p> 5655 * <p> 5656 * If an {@link AccessibilityDelegate} has been specified via calling 5657 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5658 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5659 * is responsible for handling this call. 5660 * </p> 5661 * 5662 * @return The provider. 5663 * 5664 * @see AccessibilityNodeProvider 5665 */ 5666 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5667 if (mAccessibilityDelegate != null) { 5668 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5669 } else { 5670 return null; 5671 } 5672 } 5673 5674 /** 5675 * Gets the unique identifier of this view on the screen for accessibility purposes. 5676 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5677 * 5678 * @return The view accessibility id. 5679 * 5680 * @hide 5681 */ 5682 public int getAccessibilityViewId() { 5683 if (mAccessibilityViewId == NO_ID) { 5684 mAccessibilityViewId = sNextAccessibilityViewId++; 5685 } 5686 return mAccessibilityViewId; 5687 } 5688 5689 /** 5690 * Gets the unique identifier of the window in which this View reseides. 5691 * 5692 * @return The window accessibility id. 5693 * 5694 * @hide 5695 */ 5696 public int getAccessibilityWindowId() { 5697 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5698 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5699 } 5700 5701 /** 5702 * Gets the {@link View} description. It briefly describes the view and is 5703 * primarily used for accessibility support. Set this property to enable 5704 * better accessibility support for your application. This is especially 5705 * true for views that do not have textual representation (For example, 5706 * ImageButton). 5707 * 5708 * @return The content description. 5709 * 5710 * @attr ref android.R.styleable#View_contentDescription 5711 */ 5712 @ViewDebug.ExportedProperty(category = "accessibility") 5713 public CharSequence getContentDescription() { 5714 return mContentDescription; 5715 } 5716 5717 /** 5718 * Sets the {@link View} description. It briefly describes the view and is 5719 * primarily used for accessibility support. Set this property to enable 5720 * better accessibility support for your application. This is especially 5721 * true for views that do not have textual representation (For example, 5722 * ImageButton). 5723 * 5724 * @param contentDescription The content description. 5725 * 5726 * @attr ref android.R.styleable#View_contentDescription 5727 */ 5728 @RemotableViewMethod 5729 public void setContentDescription(CharSequence contentDescription) { 5730 if (mContentDescription == null) { 5731 if (contentDescription == null) { 5732 return; 5733 } 5734 } else if (mContentDescription.equals(contentDescription)) { 5735 return; 5736 } 5737 mContentDescription = contentDescription; 5738 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5739 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5740 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5741 notifySubtreeAccessibilityStateChangedIfNeeded(); 5742 } else { 5743 notifyViewAccessibilityStateChangedIfNeeded( 5744 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5745 } 5746 } 5747 5748 /** 5749 * Gets the id of a view for which this view serves as a label for 5750 * accessibility purposes. 5751 * 5752 * @return The labeled view id. 5753 */ 5754 @ViewDebug.ExportedProperty(category = "accessibility") 5755 public int getLabelFor() { 5756 return mLabelForId; 5757 } 5758 5759 /** 5760 * Sets the id of a view for which this view serves as a label for 5761 * accessibility purposes. 5762 * 5763 * @param id The labeled view id. 5764 */ 5765 @RemotableViewMethod 5766 public void setLabelFor(int id) { 5767 mLabelForId = id; 5768 if (mLabelForId != View.NO_ID 5769 && mID == View.NO_ID) { 5770 mID = generateViewId(); 5771 } 5772 } 5773 5774 /** 5775 * Invoked whenever this view loses focus, either by losing window focus or by losing 5776 * focus within its window. This method can be used to clear any state tied to the 5777 * focus. For instance, if a button is held pressed with the trackball and the window 5778 * loses focus, this method can be used to cancel the press. 5779 * 5780 * Subclasses of View overriding this method should always call super.onFocusLost(). 5781 * 5782 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5783 * @see #onWindowFocusChanged(boolean) 5784 * 5785 * @hide pending API council approval 5786 */ 5787 protected void onFocusLost() { 5788 resetPressedState(); 5789 } 5790 5791 private void resetPressedState() { 5792 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5793 return; 5794 } 5795 5796 if (isPressed()) { 5797 setPressed(false); 5798 5799 if (!mHasPerformedLongPress) { 5800 removeLongPressCallback(); 5801 } 5802 } 5803 } 5804 5805 /** 5806 * Returns true if this view has focus 5807 * 5808 * @return True if this view has focus, false otherwise. 5809 */ 5810 @ViewDebug.ExportedProperty(category = "focus") 5811 public boolean isFocused() { 5812 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5813 } 5814 5815 /** 5816 * Find the view in the hierarchy rooted at this view that currently has 5817 * focus. 5818 * 5819 * @return The view that currently has focus, or null if no focused view can 5820 * be found. 5821 */ 5822 public View findFocus() { 5823 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5824 } 5825 5826 /** 5827 * Indicates whether this view is one of the set of scrollable containers in 5828 * its window. 5829 * 5830 * @return whether this view is one of the set of scrollable containers in 5831 * its window 5832 * 5833 * @attr ref android.R.styleable#View_isScrollContainer 5834 */ 5835 public boolean isScrollContainer() { 5836 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5837 } 5838 5839 /** 5840 * Change whether this view is one of the set of scrollable containers in 5841 * its window. This will be used to determine whether the window can 5842 * resize or must pan when a soft input area is open -- scrollable 5843 * containers allow the window to use resize mode since the container 5844 * will appropriately shrink. 5845 * 5846 * @attr ref android.R.styleable#View_isScrollContainer 5847 */ 5848 public void setScrollContainer(boolean isScrollContainer) { 5849 if (isScrollContainer) { 5850 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5851 mAttachInfo.mScrollContainers.add(this); 5852 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5853 } 5854 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5855 } else { 5856 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5857 mAttachInfo.mScrollContainers.remove(this); 5858 } 5859 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5860 } 5861 } 5862 5863 /** 5864 * Returns the quality of the drawing cache. 5865 * 5866 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5867 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5868 * 5869 * @see #setDrawingCacheQuality(int) 5870 * @see #setDrawingCacheEnabled(boolean) 5871 * @see #isDrawingCacheEnabled() 5872 * 5873 * @attr ref android.R.styleable#View_drawingCacheQuality 5874 */ 5875 @DrawingCacheQuality 5876 public int getDrawingCacheQuality() { 5877 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5878 } 5879 5880 /** 5881 * Set the drawing cache quality of this view. This value is used only when the 5882 * drawing cache is enabled 5883 * 5884 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5885 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5886 * 5887 * @see #getDrawingCacheQuality() 5888 * @see #setDrawingCacheEnabled(boolean) 5889 * @see #isDrawingCacheEnabled() 5890 * 5891 * @attr ref android.R.styleable#View_drawingCacheQuality 5892 */ 5893 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5894 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5895 } 5896 5897 /** 5898 * Returns whether the screen should remain on, corresponding to the current 5899 * value of {@link #KEEP_SCREEN_ON}. 5900 * 5901 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5902 * 5903 * @see #setKeepScreenOn(boolean) 5904 * 5905 * @attr ref android.R.styleable#View_keepScreenOn 5906 */ 5907 public boolean getKeepScreenOn() { 5908 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5909 } 5910 5911 /** 5912 * Controls whether the screen should remain on, modifying the 5913 * value of {@link #KEEP_SCREEN_ON}. 5914 * 5915 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5916 * 5917 * @see #getKeepScreenOn() 5918 * 5919 * @attr ref android.R.styleable#View_keepScreenOn 5920 */ 5921 public void setKeepScreenOn(boolean keepScreenOn) { 5922 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5923 } 5924 5925 /** 5926 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5927 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5928 * 5929 * @attr ref android.R.styleable#View_nextFocusLeft 5930 */ 5931 public int getNextFocusLeftId() { 5932 return mNextFocusLeftId; 5933 } 5934 5935 /** 5936 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5937 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5938 * decide automatically. 5939 * 5940 * @attr ref android.R.styleable#View_nextFocusLeft 5941 */ 5942 public void setNextFocusLeftId(int nextFocusLeftId) { 5943 mNextFocusLeftId = nextFocusLeftId; 5944 } 5945 5946 /** 5947 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5948 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5949 * 5950 * @attr ref android.R.styleable#View_nextFocusRight 5951 */ 5952 public int getNextFocusRightId() { 5953 return mNextFocusRightId; 5954 } 5955 5956 /** 5957 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5958 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5959 * decide automatically. 5960 * 5961 * @attr ref android.R.styleable#View_nextFocusRight 5962 */ 5963 public void setNextFocusRightId(int nextFocusRightId) { 5964 mNextFocusRightId = nextFocusRightId; 5965 } 5966 5967 /** 5968 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5969 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5970 * 5971 * @attr ref android.R.styleable#View_nextFocusUp 5972 */ 5973 public int getNextFocusUpId() { 5974 return mNextFocusUpId; 5975 } 5976 5977 /** 5978 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5979 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5980 * decide automatically. 5981 * 5982 * @attr ref android.R.styleable#View_nextFocusUp 5983 */ 5984 public void setNextFocusUpId(int nextFocusUpId) { 5985 mNextFocusUpId = nextFocusUpId; 5986 } 5987 5988 /** 5989 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5990 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5991 * 5992 * @attr ref android.R.styleable#View_nextFocusDown 5993 */ 5994 public int getNextFocusDownId() { 5995 return mNextFocusDownId; 5996 } 5997 5998 /** 5999 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6000 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6001 * decide automatically. 6002 * 6003 * @attr ref android.R.styleable#View_nextFocusDown 6004 */ 6005 public void setNextFocusDownId(int nextFocusDownId) { 6006 mNextFocusDownId = nextFocusDownId; 6007 } 6008 6009 /** 6010 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6011 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6012 * 6013 * @attr ref android.R.styleable#View_nextFocusForward 6014 */ 6015 public int getNextFocusForwardId() { 6016 return mNextFocusForwardId; 6017 } 6018 6019 /** 6020 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6021 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6022 * decide automatically. 6023 * 6024 * @attr ref android.R.styleable#View_nextFocusForward 6025 */ 6026 public void setNextFocusForwardId(int nextFocusForwardId) { 6027 mNextFocusForwardId = nextFocusForwardId; 6028 } 6029 6030 /** 6031 * Returns the visibility of this view and all of its ancestors 6032 * 6033 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6034 */ 6035 public boolean isShown() { 6036 View current = this; 6037 //noinspection ConstantConditions 6038 do { 6039 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6040 return false; 6041 } 6042 ViewParent parent = current.mParent; 6043 if (parent == null) { 6044 return false; // We are not attached to the view root 6045 } 6046 if (!(parent instanceof View)) { 6047 return true; 6048 } 6049 current = (View) parent; 6050 } while (current != null); 6051 6052 return false; 6053 } 6054 6055 /** 6056 * Called by the view hierarchy when the content insets for a window have 6057 * changed, to allow it to adjust its content to fit within those windows. 6058 * The content insets tell you the space that the status bar, input method, 6059 * and other system windows infringe on the application's window. 6060 * 6061 * <p>You do not normally need to deal with this function, since the default 6062 * window decoration given to applications takes care of applying it to the 6063 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6064 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6065 * and your content can be placed under those system elements. You can then 6066 * use this method within your view hierarchy if you have parts of your UI 6067 * which you would like to ensure are not being covered. 6068 * 6069 * <p>The default implementation of this method simply applies the content 6070 * insets to the view's padding, consuming that content (modifying the 6071 * insets to be 0), and returning true. This behavior is off by default, but can 6072 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6073 * 6074 * <p>This function's traversal down the hierarchy is depth-first. The same content 6075 * insets object is propagated down the hierarchy, so any changes made to it will 6076 * be seen by all following views (including potentially ones above in 6077 * the hierarchy since this is a depth-first traversal). The first view 6078 * that returns true will abort the entire traversal. 6079 * 6080 * <p>The default implementation works well for a situation where it is 6081 * used with a container that covers the entire window, allowing it to 6082 * apply the appropriate insets to its content on all edges. If you need 6083 * a more complicated layout (such as two different views fitting system 6084 * windows, one on the top of the window, and one on the bottom), 6085 * you can override the method and handle the insets however you would like. 6086 * Note that the insets provided by the framework are always relative to the 6087 * far edges of the window, not accounting for the location of the called view 6088 * within that window. (In fact when this method is called you do not yet know 6089 * where the layout will place the view, as it is done before layout happens.) 6090 * 6091 * <p>Note: unlike many View methods, there is no dispatch phase to this 6092 * call. If you are overriding it in a ViewGroup and want to allow the 6093 * call to continue to your children, you must be sure to call the super 6094 * implementation. 6095 * 6096 * <p>Here is a sample layout that makes use of fitting system windows 6097 * to have controls for a video view placed inside of the window decorations 6098 * that it hides and shows. This can be used with code like the second 6099 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6100 * 6101 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6102 * 6103 * @param insets Current content insets of the window. Prior to 6104 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6105 * the insets or else you and Android will be unhappy. 6106 * 6107 * @return {@code true} if this view applied the insets and it should not 6108 * continue propagating further down the hierarchy, {@code false} otherwise. 6109 * @see #getFitsSystemWindows() 6110 * @see #setFitsSystemWindows(boolean) 6111 * @see #setSystemUiVisibility(int) 6112 * 6113 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6114 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6115 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6116 * to implement handling their own insets. 6117 */ 6118 protected boolean fitSystemWindows(Rect insets) { 6119 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6120 if (insets == null) { 6121 // Null insets by definition have already been consumed. 6122 // This call cannot apply insets since there are none to apply, 6123 // so return false. 6124 return false; 6125 } 6126 // If we're not in the process of dispatching the newer apply insets call, 6127 // that means we're not in the compatibility path. Dispatch into the newer 6128 // apply insets path and take things from there. 6129 try { 6130 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6131 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 6132 } finally { 6133 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6134 } 6135 } else { 6136 // We're being called from the newer apply insets path. 6137 // Perform the standard fallback behavior. 6138 return fitSystemWindowsInt(insets); 6139 } 6140 } 6141 6142 private boolean fitSystemWindowsInt(Rect insets) { 6143 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6144 mUserPaddingStart = UNDEFINED_PADDING; 6145 mUserPaddingEnd = UNDEFINED_PADDING; 6146 Rect localInsets = sThreadLocal.get(); 6147 if (localInsets == null) { 6148 localInsets = new Rect(); 6149 sThreadLocal.set(localInsets); 6150 } 6151 boolean res = computeFitSystemWindows(insets, localInsets); 6152 mUserPaddingLeftInitial = localInsets.left; 6153 mUserPaddingRightInitial = localInsets.right; 6154 internalSetPadding(localInsets.left, localInsets.top, 6155 localInsets.right, localInsets.bottom); 6156 return res; 6157 } 6158 return false; 6159 } 6160 6161 /** 6162 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6163 * 6164 * <p>This method should be overridden by views that wish to apply a policy different from or 6165 * in addition to the default behavior. Clients that wish to force a view subtree 6166 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6167 * 6168 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6169 * it will be called during dispatch instead of this method. The listener may optionally 6170 * call this method from its own implementation if it wishes to apply the view's default 6171 * insets policy in addition to its own.</p> 6172 * 6173 * <p>Implementations of this method should either return the insets parameter unchanged 6174 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6175 * that this view applied itself. This allows new inset types added in future platform 6176 * versions to pass through existing implementations unchanged without being erroneously 6177 * consumed.</p> 6178 * 6179 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6180 * property is set then the view will consume the system window insets and apply them 6181 * as padding for the view.</p> 6182 * 6183 * @param insets Insets to apply 6184 * @return The supplied insets with any applied insets consumed 6185 */ 6186 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6187 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6188 // We weren't called from within a direct call to fitSystemWindows, 6189 // call into it as a fallback in case we're in a class that overrides it 6190 // and has logic to perform. 6191 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6192 return insets.consumeSystemWindowInsets(); 6193 } 6194 } else { 6195 // We were called from within a direct call to fitSystemWindows. 6196 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6197 return insets.consumeSystemWindowInsets(); 6198 } 6199 } 6200 return insets; 6201 } 6202 6203 /** 6204 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6205 * window insets to this view. The listener's 6206 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6207 * method will be called instead of the view's 6208 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6209 * 6210 * @param listener Listener to set 6211 * 6212 * @see #onApplyWindowInsets(WindowInsets) 6213 */ 6214 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6215 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6216 } 6217 6218 /** 6219 * Request to apply the given window insets to this view or another view in its subtree. 6220 * 6221 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6222 * obscured by window decorations or overlays. This can include the status and navigation bars, 6223 * action bars, input methods and more. New inset categories may be added in the future. 6224 * The method returns the insets provided minus any that were applied by this view or its 6225 * children.</p> 6226 * 6227 * <p>Clients wishing to provide custom behavior should override the 6228 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6229 * {@link OnApplyWindowInsetsListener} via the 6230 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6231 * method.</p> 6232 * 6233 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6234 * </p> 6235 * 6236 * @param insets Insets to apply 6237 * @return The provided insets minus the insets that were consumed 6238 */ 6239 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6240 try { 6241 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6242 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6243 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6244 } else { 6245 return onApplyWindowInsets(insets); 6246 } 6247 } finally { 6248 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6249 } 6250 } 6251 6252 /** 6253 * @hide Compute the insets that should be consumed by this view and the ones 6254 * that should propagate to those under it. 6255 */ 6256 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6257 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6258 || mAttachInfo == null 6259 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6260 && !mAttachInfo.mOverscanRequested)) { 6261 outLocalInsets.set(inoutInsets); 6262 inoutInsets.set(0, 0, 0, 0); 6263 return true; 6264 } else { 6265 // The application wants to take care of fitting system window for 6266 // the content... however we still need to take care of any overscan here. 6267 final Rect overscan = mAttachInfo.mOverscanInsets; 6268 outLocalInsets.set(overscan); 6269 inoutInsets.left -= overscan.left; 6270 inoutInsets.top -= overscan.top; 6271 inoutInsets.right -= overscan.right; 6272 inoutInsets.bottom -= overscan.bottom; 6273 return false; 6274 } 6275 } 6276 6277 /** 6278 * Sets whether or not this view should account for system screen decorations 6279 * such as the status bar and inset its content; that is, controlling whether 6280 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6281 * executed. See that method for more details. 6282 * 6283 * <p>Note that if you are providing your own implementation of 6284 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6285 * flag to true -- your implementation will be overriding the default 6286 * implementation that checks this flag. 6287 * 6288 * @param fitSystemWindows If true, then the default implementation of 6289 * {@link #fitSystemWindows(Rect)} will be executed. 6290 * 6291 * @attr ref android.R.styleable#View_fitsSystemWindows 6292 * @see #getFitsSystemWindows() 6293 * @see #fitSystemWindows(Rect) 6294 * @see #setSystemUiVisibility(int) 6295 */ 6296 public void setFitsSystemWindows(boolean fitSystemWindows) { 6297 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6298 } 6299 6300 /** 6301 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6302 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6303 * will be executed. 6304 * 6305 * @return {@code true} if the default implementation of 6306 * {@link #fitSystemWindows(Rect)} will be executed. 6307 * 6308 * @attr ref android.R.styleable#View_fitsSystemWindows 6309 * @see #setFitsSystemWindows(boolean) 6310 * @see #fitSystemWindows(Rect) 6311 * @see #setSystemUiVisibility(int) 6312 */ 6313 public boolean getFitsSystemWindows() { 6314 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6315 } 6316 6317 /** @hide */ 6318 public boolean fitsSystemWindows() { 6319 return getFitsSystemWindows(); 6320 } 6321 6322 /** 6323 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6324 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6325 */ 6326 public void requestFitSystemWindows() { 6327 if (mParent != null) { 6328 mParent.requestFitSystemWindows(); 6329 } 6330 } 6331 6332 /** 6333 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6334 */ 6335 public void requestApplyInsets() { 6336 requestFitSystemWindows(); 6337 } 6338 6339 /** 6340 * For use by PhoneWindow to make its own system window fitting optional. 6341 * @hide 6342 */ 6343 public void makeOptionalFitsSystemWindows() { 6344 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6345 } 6346 6347 /** 6348 * Returns the visibility status for this view. 6349 * 6350 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6351 * @attr ref android.R.styleable#View_visibility 6352 */ 6353 @ViewDebug.ExportedProperty(mapping = { 6354 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6355 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6356 @ViewDebug.IntToString(from = GONE, to = "GONE") 6357 }) 6358 @Visibility 6359 public int getVisibility() { 6360 return mViewFlags & VISIBILITY_MASK; 6361 } 6362 6363 /** 6364 * Set the enabled state of this view. 6365 * 6366 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6367 * @attr ref android.R.styleable#View_visibility 6368 */ 6369 @RemotableViewMethod 6370 public void setVisibility(@Visibility int visibility) { 6371 setFlags(visibility, VISIBILITY_MASK); 6372 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6373 } 6374 6375 /** 6376 * Returns the enabled status for this view. The interpretation of the 6377 * enabled state varies by subclass. 6378 * 6379 * @return True if this view is enabled, false otherwise. 6380 */ 6381 @ViewDebug.ExportedProperty 6382 public boolean isEnabled() { 6383 return (mViewFlags & ENABLED_MASK) == ENABLED; 6384 } 6385 6386 /** 6387 * Set the enabled state of this view. The interpretation of the enabled 6388 * state varies by subclass. 6389 * 6390 * @param enabled True if this view is enabled, false otherwise. 6391 */ 6392 @RemotableViewMethod 6393 public void setEnabled(boolean enabled) { 6394 if (enabled == isEnabled()) return; 6395 6396 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6397 6398 /* 6399 * The View most likely has to change its appearance, so refresh 6400 * the drawable state. 6401 */ 6402 refreshDrawableState(); 6403 6404 // Invalidate too, since the default behavior for views is to be 6405 // be drawn at 50% alpha rather than to change the drawable. 6406 invalidate(true); 6407 6408 if (!enabled) { 6409 cancelPendingInputEvents(); 6410 } 6411 } 6412 6413 /** 6414 * Set whether this view can receive the focus. 6415 * 6416 * Setting this to false will also ensure that this view is not focusable 6417 * in touch mode. 6418 * 6419 * @param focusable If true, this view can receive the focus. 6420 * 6421 * @see #setFocusableInTouchMode(boolean) 6422 * @attr ref android.R.styleable#View_focusable 6423 */ 6424 public void setFocusable(boolean focusable) { 6425 if (!focusable) { 6426 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6427 } 6428 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6429 } 6430 6431 /** 6432 * Set whether this view can receive focus while in touch mode. 6433 * 6434 * Setting this to true will also ensure that this view is focusable. 6435 * 6436 * @param focusableInTouchMode If true, this view can receive the focus while 6437 * in touch mode. 6438 * 6439 * @see #setFocusable(boolean) 6440 * @attr ref android.R.styleable#View_focusableInTouchMode 6441 */ 6442 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6443 // Focusable in touch mode should always be set before the focusable flag 6444 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6445 // which, in touch mode, will not successfully request focus on this view 6446 // because the focusable in touch mode flag is not set 6447 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6448 if (focusableInTouchMode) { 6449 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6450 } 6451 } 6452 6453 /** 6454 * Set whether this view should have sound effects enabled for events such as 6455 * clicking and touching. 6456 * 6457 * <p>You may wish to disable sound effects for a view if you already play sounds, 6458 * for instance, a dial key that plays dtmf tones. 6459 * 6460 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6461 * @see #isSoundEffectsEnabled() 6462 * @see #playSoundEffect(int) 6463 * @attr ref android.R.styleable#View_soundEffectsEnabled 6464 */ 6465 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6466 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6467 } 6468 6469 /** 6470 * @return whether this view should have sound effects enabled for events such as 6471 * clicking and touching. 6472 * 6473 * @see #setSoundEffectsEnabled(boolean) 6474 * @see #playSoundEffect(int) 6475 * @attr ref android.R.styleable#View_soundEffectsEnabled 6476 */ 6477 @ViewDebug.ExportedProperty 6478 public boolean isSoundEffectsEnabled() { 6479 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6480 } 6481 6482 /** 6483 * Set whether this view should have haptic feedback for events such as 6484 * long presses. 6485 * 6486 * <p>You may wish to disable haptic feedback if your view already controls 6487 * its own haptic feedback. 6488 * 6489 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6490 * @see #isHapticFeedbackEnabled() 6491 * @see #performHapticFeedback(int) 6492 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6493 */ 6494 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6495 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6496 } 6497 6498 /** 6499 * @return whether this view should have haptic feedback enabled for events 6500 * long presses. 6501 * 6502 * @see #setHapticFeedbackEnabled(boolean) 6503 * @see #performHapticFeedback(int) 6504 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6505 */ 6506 @ViewDebug.ExportedProperty 6507 public boolean isHapticFeedbackEnabled() { 6508 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6509 } 6510 6511 /** 6512 * Returns the layout direction for this view. 6513 * 6514 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6515 * {@link #LAYOUT_DIRECTION_RTL}, 6516 * {@link #LAYOUT_DIRECTION_INHERIT} or 6517 * {@link #LAYOUT_DIRECTION_LOCALE}. 6518 * 6519 * @attr ref android.R.styleable#View_layoutDirection 6520 * 6521 * @hide 6522 */ 6523 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6524 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6525 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6526 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6527 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6528 }) 6529 @LayoutDir 6530 public int getRawLayoutDirection() { 6531 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6532 } 6533 6534 /** 6535 * Set the layout direction for this view. This will propagate a reset of layout direction 6536 * resolution to the view's children and resolve layout direction for this view. 6537 * 6538 * @param layoutDirection the layout direction to set. Should be one of: 6539 * 6540 * {@link #LAYOUT_DIRECTION_LTR}, 6541 * {@link #LAYOUT_DIRECTION_RTL}, 6542 * {@link #LAYOUT_DIRECTION_INHERIT}, 6543 * {@link #LAYOUT_DIRECTION_LOCALE}. 6544 * 6545 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6546 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6547 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6548 * 6549 * @attr ref android.R.styleable#View_layoutDirection 6550 */ 6551 @RemotableViewMethod 6552 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6553 if (getRawLayoutDirection() != layoutDirection) { 6554 // Reset the current layout direction and the resolved one 6555 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6556 resetRtlProperties(); 6557 // Set the new layout direction (filtered) 6558 mPrivateFlags2 |= 6559 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6560 // We need to resolve all RTL properties as they all depend on layout direction 6561 resolveRtlPropertiesIfNeeded(); 6562 requestLayout(); 6563 invalidate(true); 6564 } 6565 } 6566 6567 /** 6568 * Returns the resolved layout direction for this view. 6569 * 6570 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6571 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6572 * 6573 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6574 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6575 * 6576 * @attr ref android.R.styleable#View_layoutDirection 6577 */ 6578 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6579 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6580 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6581 }) 6582 @ResolvedLayoutDir 6583 public int getLayoutDirection() { 6584 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6585 if (targetSdkVersion < JELLY_BEAN_MR1) { 6586 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6587 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6588 } 6589 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6590 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6591 } 6592 6593 /** 6594 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6595 * layout attribute and/or the inherited value from the parent 6596 * 6597 * @return true if the layout is right-to-left. 6598 * 6599 * @hide 6600 */ 6601 @ViewDebug.ExportedProperty(category = "layout") 6602 public boolean isLayoutRtl() { 6603 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6604 } 6605 6606 /** 6607 * Indicates whether the view is currently tracking transient state that the 6608 * app should not need to concern itself with saving and restoring, but that 6609 * the framework should take special note to preserve when possible. 6610 * 6611 * <p>A view with transient state cannot be trivially rebound from an external 6612 * data source, such as an adapter binding item views in a list. This may be 6613 * because the view is performing an animation, tracking user selection 6614 * of content, or similar.</p> 6615 * 6616 * @return true if the view has transient state 6617 */ 6618 @ViewDebug.ExportedProperty(category = "layout") 6619 public boolean hasTransientState() { 6620 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6621 } 6622 6623 /** 6624 * Set whether this view is currently tracking transient state that the 6625 * framework should attempt to preserve when possible. This flag is reference counted, 6626 * so every call to setHasTransientState(true) should be paired with a later call 6627 * to setHasTransientState(false). 6628 * 6629 * <p>A view with transient state cannot be trivially rebound from an external 6630 * data source, such as an adapter binding item views in a list. This may be 6631 * because the view is performing an animation, tracking user selection 6632 * of content, or similar.</p> 6633 * 6634 * @param hasTransientState true if this view has transient state 6635 */ 6636 public void setHasTransientState(boolean hasTransientState) { 6637 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6638 mTransientStateCount - 1; 6639 if (mTransientStateCount < 0) { 6640 mTransientStateCount = 0; 6641 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6642 "unmatched pair of setHasTransientState calls"); 6643 } else if ((hasTransientState && mTransientStateCount == 1) || 6644 (!hasTransientState && mTransientStateCount == 0)) { 6645 // update flag if we've just incremented up from 0 or decremented down to 0 6646 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6647 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6648 if (mParent != null) { 6649 try { 6650 mParent.childHasTransientStateChanged(this, hasTransientState); 6651 } catch (AbstractMethodError e) { 6652 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6653 " does not fully implement ViewParent", e); 6654 } 6655 } 6656 } 6657 } 6658 6659 /** 6660 * Returns true if this view is currently attached to a window. 6661 */ 6662 public boolean isAttachedToWindow() { 6663 return mAttachInfo != null; 6664 } 6665 6666 /** 6667 * Returns true if this view has been through at least one layout since it 6668 * was last attached to or detached from a window. 6669 */ 6670 public boolean isLaidOut() { 6671 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6672 } 6673 6674 /** 6675 * If this view doesn't do any drawing on its own, set this flag to 6676 * allow further optimizations. By default, this flag is not set on 6677 * View, but could be set on some View subclasses such as ViewGroup. 6678 * 6679 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6680 * you should clear this flag. 6681 * 6682 * @param willNotDraw whether or not this View draw on its own 6683 */ 6684 public void setWillNotDraw(boolean willNotDraw) { 6685 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6686 } 6687 6688 /** 6689 * Returns whether or not this View draws on its own. 6690 * 6691 * @return true if this view has nothing to draw, false otherwise 6692 */ 6693 @ViewDebug.ExportedProperty(category = "drawing") 6694 public boolean willNotDraw() { 6695 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6696 } 6697 6698 /** 6699 * When a View's drawing cache is enabled, drawing is redirected to an 6700 * offscreen bitmap. Some views, like an ImageView, must be able to 6701 * bypass this mechanism if they already draw a single bitmap, to avoid 6702 * unnecessary usage of the memory. 6703 * 6704 * @param willNotCacheDrawing true if this view does not cache its 6705 * drawing, false otherwise 6706 */ 6707 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6708 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6709 } 6710 6711 /** 6712 * Returns whether or not this View can cache its drawing or not. 6713 * 6714 * @return true if this view does not cache its drawing, false otherwise 6715 */ 6716 @ViewDebug.ExportedProperty(category = "drawing") 6717 public boolean willNotCacheDrawing() { 6718 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6719 } 6720 6721 /** 6722 * Indicates whether this view reacts to click events or not. 6723 * 6724 * @return true if the view is clickable, false otherwise 6725 * 6726 * @see #setClickable(boolean) 6727 * @attr ref android.R.styleable#View_clickable 6728 */ 6729 @ViewDebug.ExportedProperty 6730 public boolean isClickable() { 6731 return (mViewFlags & CLICKABLE) == CLICKABLE; 6732 } 6733 6734 /** 6735 * Enables or disables click events for this view. When a view 6736 * is clickable it will change its state to "pressed" on every click. 6737 * Subclasses should set the view clickable to visually react to 6738 * user's clicks. 6739 * 6740 * @param clickable true to make the view clickable, false otherwise 6741 * 6742 * @see #isClickable() 6743 * @attr ref android.R.styleable#View_clickable 6744 */ 6745 public void setClickable(boolean clickable) { 6746 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6747 } 6748 6749 /** 6750 * Indicates whether this view reacts to long click events or not. 6751 * 6752 * @return true if the view is long clickable, false otherwise 6753 * 6754 * @see #setLongClickable(boolean) 6755 * @attr ref android.R.styleable#View_longClickable 6756 */ 6757 public boolean isLongClickable() { 6758 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6759 } 6760 6761 /** 6762 * Enables or disables long click events for this view. When a view is long 6763 * clickable it reacts to the user holding down the button for a longer 6764 * duration than a tap. This event can either launch the listener or a 6765 * context menu. 6766 * 6767 * @param longClickable true to make the view long clickable, false otherwise 6768 * @see #isLongClickable() 6769 * @attr ref android.R.styleable#View_longClickable 6770 */ 6771 public void setLongClickable(boolean longClickable) { 6772 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6773 } 6774 6775 /** 6776 * Sets the pressed state for this view and provides a touch coordinate for 6777 * animation hinting. 6778 * 6779 * @param pressed Pass true to set the View's internal state to "pressed", 6780 * or false to reverts the View's internal state from a 6781 * previously set "pressed" state. 6782 * @param x The x coordinate of the touch that caused the press 6783 * @param y The y coordinate of the touch that caused the press 6784 */ 6785 private void setPressed(boolean pressed, float x, float y) { 6786 if (pressed) { 6787 drawableHotspotChanged(x, y); 6788 } 6789 6790 setPressed(pressed); 6791 } 6792 6793 /** 6794 * Sets the pressed state for this view. 6795 * 6796 * @see #isClickable() 6797 * @see #setClickable(boolean) 6798 * 6799 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6800 * the View's internal state from a previously set "pressed" state. 6801 */ 6802 public void setPressed(boolean pressed) { 6803 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6804 6805 if (pressed) { 6806 mPrivateFlags |= PFLAG_PRESSED; 6807 } else { 6808 mPrivateFlags &= ~PFLAG_PRESSED; 6809 } 6810 6811 if (needsRefresh) { 6812 refreshDrawableState(); 6813 } 6814 dispatchSetPressed(pressed); 6815 } 6816 6817 /** 6818 * Dispatch setPressed to all of this View's children. 6819 * 6820 * @see #setPressed(boolean) 6821 * 6822 * @param pressed The new pressed state 6823 */ 6824 protected void dispatchSetPressed(boolean pressed) { 6825 } 6826 6827 /** 6828 * Indicates whether the view is currently in pressed state. Unless 6829 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6830 * the pressed state. 6831 * 6832 * @see #setPressed(boolean) 6833 * @see #isClickable() 6834 * @see #setClickable(boolean) 6835 * 6836 * @return true if the view is currently pressed, false otherwise 6837 */ 6838 public boolean isPressed() { 6839 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6840 } 6841 6842 /** 6843 * Indicates whether this view will save its state (that is, 6844 * whether its {@link #onSaveInstanceState} method will be called). 6845 * 6846 * @return Returns true if the view state saving is enabled, else false. 6847 * 6848 * @see #setSaveEnabled(boolean) 6849 * @attr ref android.R.styleable#View_saveEnabled 6850 */ 6851 public boolean isSaveEnabled() { 6852 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6853 } 6854 6855 /** 6856 * Controls whether the saving of this view's state is 6857 * enabled (that is, whether its {@link #onSaveInstanceState} method 6858 * will be called). Note that even if freezing is enabled, the 6859 * view still must have an id assigned to it (via {@link #setId(int)}) 6860 * for its state to be saved. This flag can only disable the 6861 * saving of this view; any child views may still have their state saved. 6862 * 6863 * @param enabled Set to false to <em>disable</em> state saving, or true 6864 * (the default) to allow it. 6865 * 6866 * @see #isSaveEnabled() 6867 * @see #setId(int) 6868 * @see #onSaveInstanceState() 6869 * @attr ref android.R.styleable#View_saveEnabled 6870 */ 6871 public void setSaveEnabled(boolean enabled) { 6872 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6873 } 6874 6875 /** 6876 * Gets whether the framework should discard touches when the view's 6877 * window is obscured by another visible window. 6878 * Refer to the {@link View} security documentation for more details. 6879 * 6880 * @return True if touch filtering is enabled. 6881 * 6882 * @see #setFilterTouchesWhenObscured(boolean) 6883 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6884 */ 6885 @ViewDebug.ExportedProperty 6886 public boolean getFilterTouchesWhenObscured() { 6887 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6888 } 6889 6890 /** 6891 * Sets whether the framework should discard touches when the view's 6892 * window is obscured by another visible window. 6893 * Refer to the {@link View} security documentation for more details. 6894 * 6895 * @param enabled True if touch filtering should be enabled. 6896 * 6897 * @see #getFilterTouchesWhenObscured 6898 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6899 */ 6900 public void setFilterTouchesWhenObscured(boolean enabled) { 6901 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 6902 FILTER_TOUCHES_WHEN_OBSCURED); 6903 } 6904 6905 /** 6906 * Indicates whether the entire hierarchy under this view will save its 6907 * state when a state saving traversal occurs from its parent. The default 6908 * is true; if false, these views will not be saved unless 6909 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6910 * 6911 * @return Returns true if the view state saving from parent is enabled, else false. 6912 * 6913 * @see #setSaveFromParentEnabled(boolean) 6914 */ 6915 public boolean isSaveFromParentEnabled() { 6916 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6917 } 6918 6919 /** 6920 * Controls whether the entire hierarchy under this view will save its 6921 * state when a state saving traversal occurs from its parent. The default 6922 * is true; if false, these views will not be saved unless 6923 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6924 * 6925 * @param enabled Set to false to <em>disable</em> state saving, or true 6926 * (the default) to allow it. 6927 * 6928 * @see #isSaveFromParentEnabled() 6929 * @see #setId(int) 6930 * @see #onSaveInstanceState() 6931 */ 6932 public void setSaveFromParentEnabled(boolean enabled) { 6933 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6934 } 6935 6936 6937 /** 6938 * Returns whether this View is able to take focus. 6939 * 6940 * @return True if this view can take focus, or false otherwise. 6941 * @attr ref android.R.styleable#View_focusable 6942 */ 6943 @ViewDebug.ExportedProperty(category = "focus") 6944 public final boolean isFocusable() { 6945 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6946 } 6947 6948 /** 6949 * When a view is focusable, it may not want to take focus when in touch mode. 6950 * For example, a button would like focus when the user is navigating via a D-pad 6951 * so that the user can click on it, but once the user starts touching the screen, 6952 * the button shouldn't take focus 6953 * @return Whether the view is focusable in touch mode. 6954 * @attr ref android.R.styleable#View_focusableInTouchMode 6955 */ 6956 @ViewDebug.ExportedProperty 6957 public final boolean isFocusableInTouchMode() { 6958 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6959 } 6960 6961 /** 6962 * Find the nearest view in the specified direction that can take focus. 6963 * This does not actually give focus to that view. 6964 * 6965 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6966 * 6967 * @return The nearest focusable in the specified direction, or null if none 6968 * can be found. 6969 */ 6970 public View focusSearch(@FocusRealDirection int direction) { 6971 if (mParent != null) { 6972 return mParent.focusSearch(this, direction); 6973 } else { 6974 return null; 6975 } 6976 } 6977 6978 /** 6979 * This method is the last chance for the focused view and its ancestors to 6980 * respond to an arrow key. This is called when the focused view did not 6981 * consume the key internally, nor could the view system find a new view in 6982 * the requested direction to give focus to. 6983 * 6984 * @param focused The currently focused view. 6985 * @param direction The direction focus wants to move. One of FOCUS_UP, 6986 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6987 * @return True if the this view consumed this unhandled move. 6988 */ 6989 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 6990 return false; 6991 } 6992 6993 /** 6994 * If a user manually specified the next view id for a particular direction, 6995 * use the root to look up the view. 6996 * @param root The root view of the hierarchy containing this view. 6997 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6998 * or FOCUS_BACKWARD. 6999 * @return The user specified next view, or null if there is none. 7000 */ 7001 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7002 switch (direction) { 7003 case FOCUS_LEFT: 7004 if (mNextFocusLeftId == View.NO_ID) return null; 7005 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7006 case FOCUS_RIGHT: 7007 if (mNextFocusRightId == View.NO_ID) return null; 7008 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7009 case FOCUS_UP: 7010 if (mNextFocusUpId == View.NO_ID) return null; 7011 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7012 case FOCUS_DOWN: 7013 if (mNextFocusDownId == View.NO_ID) return null; 7014 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7015 case FOCUS_FORWARD: 7016 if (mNextFocusForwardId == View.NO_ID) return null; 7017 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7018 case FOCUS_BACKWARD: { 7019 if (mID == View.NO_ID) return null; 7020 final int id = mID; 7021 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7022 @Override 7023 public boolean apply(View t) { 7024 return t.mNextFocusForwardId == id; 7025 } 7026 }); 7027 } 7028 } 7029 return null; 7030 } 7031 7032 private View findViewInsideOutShouldExist(View root, int id) { 7033 if (mMatchIdPredicate == null) { 7034 mMatchIdPredicate = new MatchIdPredicate(); 7035 } 7036 mMatchIdPredicate.mId = id; 7037 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7038 if (result == null) { 7039 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7040 } 7041 return result; 7042 } 7043 7044 /** 7045 * Find and return all focusable views that are descendants of this view, 7046 * possibly including this view if it is focusable itself. 7047 * 7048 * @param direction The direction of the focus 7049 * @return A list of focusable views 7050 */ 7051 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7052 ArrayList<View> result = new ArrayList<View>(24); 7053 addFocusables(result, direction); 7054 return result; 7055 } 7056 7057 /** 7058 * Add any focusable views that are descendants of this view (possibly 7059 * including this view if it is focusable itself) to views. If we are in touch mode, 7060 * only add views that are also focusable in touch mode. 7061 * 7062 * @param views Focusable views found so far 7063 * @param direction The direction of the focus 7064 */ 7065 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7066 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7067 } 7068 7069 /** 7070 * Adds any focusable views that are descendants of this view (possibly 7071 * including this view if it is focusable itself) to views. This method 7072 * adds all focusable views regardless if we are in touch mode or 7073 * only views focusable in touch mode if we are in touch mode or 7074 * only views that can take accessibility focus if accessibility is enabeld 7075 * depending on the focusable mode paramater. 7076 * 7077 * @param views Focusable views found so far or null if all we are interested is 7078 * the number of focusables. 7079 * @param direction The direction of the focus. 7080 * @param focusableMode The type of focusables to be added. 7081 * 7082 * @see #FOCUSABLES_ALL 7083 * @see #FOCUSABLES_TOUCH_MODE 7084 */ 7085 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7086 @FocusableMode int focusableMode) { 7087 if (views == null) { 7088 return; 7089 } 7090 if (!isFocusable()) { 7091 return; 7092 } 7093 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7094 && isInTouchMode() && !isFocusableInTouchMode()) { 7095 return; 7096 } 7097 views.add(this); 7098 } 7099 7100 /** 7101 * Finds the Views that contain given text. The containment is case insensitive. 7102 * The search is performed by either the text that the View renders or the content 7103 * description that describes the view for accessibility purposes and the view does 7104 * not render or both. Clients can specify how the search is to be performed via 7105 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7106 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7107 * 7108 * @param outViews The output list of matching Views. 7109 * @param searched The text to match against. 7110 * 7111 * @see #FIND_VIEWS_WITH_TEXT 7112 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7113 * @see #setContentDescription(CharSequence) 7114 */ 7115 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7116 @FindViewFlags int flags) { 7117 if (getAccessibilityNodeProvider() != null) { 7118 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7119 outViews.add(this); 7120 } 7121 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7122 && (searched != null && searched.length() > 0) 7123 && (mContentDescription != null && mContentDescription.length() > 0)) { 7124 String searchedLowerCase = searched.toString().toLowerCase(); 7125 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7126 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7127 outViews.add(this); 7128 } 7129 } 7130 } 7131 7132 /** 7133 * Find and return all touchable views that are descendants of this view, 7134 * possibly including this view if it is touchable itself. 7135 * 7136 * @return A list of touchable views 7137 */ 7138 public ArrayList<View> getTouchables() { 7139 ArrayList<View> result = new ArrayList<View>(); 7140 addTouchables(result); 7141 return result; 7142 } 7143 7144 /** 7145 * Add any touchable views that are descendants of this view (possibly 7146 * including this view if it is touchable itself) to views. 7147 * 7148 * @param views Touchable views found so far 7149 */ 7150 public void addTouchables(ArrayList<View> views) { 7151 final int viewFlags = mViewFlags; 7152 7153 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7154 && (viewFlags & ENABLED_MASK) == ENABLED) { 7155 views.add(this); 7156 } 7157 } 7158 7159 /** 7160 * Returns whether this View is accessibility focused. 7161 * 7162 * @return True if this View is accessibility focused. 7163 */ 7164 public boolean isAccessibilityFocused() { 7165 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7166 } 7167 7168 /** 7169 * Call this to try to give accessibility focus to this view. 7170 * 7171 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7172 * returns false or the view is no visible or the view already has accessibility 7173 * focus. 7174 * 7175 * See also {@link #focusSearch(int)}, which is what you call to say that you 7176 * have focus, and you want your parent to look for the next one. 7177 * 7178 * @return Whether this view actually took accessibility focus. 7179 * 7180 * @hide 7181 */ 7182 public boolean requestAccessibilityFocus() { 7183 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7184 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7185 return false; 7186 } 7187 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7188 return false; 7189 } 7190 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7191 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7192 ViewRootImpl viewRootImpl = getViewRootImpl(); 7193 if (viewRootImpl != null) { 7194 viewRootImpl.setAccessibilityFocus(this, null); 7195 } 7196 Rect rect = (mAttachInfo != null) ? mAttachInfo.mTmpInvalRect : new Rect(); 7197 getDrawingRect(rect); 7198 requestRectangleOnScreen(rect, false); 7199 invalidate(); 7200 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7201 return true; 7202 } 7203 return false; 7204 } 7205 7206 /** 7207 * Call this to try to clear accessibility focus of this view. 7208 * 7209 * See also {@link #focusSearch(int)}, which is what you call to say that you 7210 * have focus, and you want your parent to look for the next one. 7211 * 7212 * @hide 7213 */ 7214 public void clearAccessibilityFocus() { 7215 clearAccessibilityFocusNoCallbacks(); 7216 // Clear the global reference of accessibility focus if this 7217 // view or any of its descendants had accessibility focus. 7218 ViewRootImpl viewRootImpl = getViewRootImpl(); 7219 if (viewRootImpl != null) { 7220 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7221 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7222 viewRootImpl.setAccessibilityFocus(null, null); 7223 } 7224 } 7225 } 7226 7227 private void sendAccessibilityHoverEvent(int eventType) { 7228 // Since we are not delivering to a client accessibility events from not 7229 // important views (unless the clinet request that) we need to fire the 7230 // event from the deepest view exposed to the client. As a consequence if 7231 // the user crosses a not exposed view the client will see enter and exit 7232 // of the exposed predecessor followed by and enter and exit of that same 7233 // predecessor when entering and exiting the not exposed descendant. This 7234 // is fine since the client has a clear idea which view is hovered at the 7235 // price of a couple more events being sent. This is a simple and 7236 // working solution. 7237 View source = this; 7238 while (true) { 7239 if (source.includeForAccessibility()) { 7240 source.sendAccessibilityEvent(eventType); 7241 return; 7242 } 7243 ViewParent parent = source.getParent(); 7244 if (parent instanceof View) { 7245 source = (View) parent; 7246 } else { 7247 return; 7248 } 7249 } 7250 } 7251 7252 /** 7253 * Clears accessibility focus without calling any callback methods 7254 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7255 * is used for clearing accessibility focus when giving this focus to 7256 * another view. 7257 */ 7258 void clearAccessibilityFocusNoCallbacks() { 7259 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7260 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7261 invalidate(); 7262 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7263 } 7264 } 7265 7266 /** 7267 * Call this to try to give focus to a specific view or to one of its 7268 * descendants. 7269 * 7270 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7271 * false), or if it is focusable and it is not focusable in touch mode 7272 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7273 * 7274 * See also {@link #focusSearch(int)}, which is what you call to say that you 7275 * have focus, and you want your parent to look for the next one. 7276 * 7277 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7278 * {@link #FOCUS_DOWN} and <code>null</code>. 7279 * 7280 * @return Whether this view or one of its descendants actually took focus. 7281 */ 7282 public final boolean requestFocus() { 7283 return requestFocus(View.FOCUS_DOWN); 7284 } 7285 7286 /** 7287 * Call this to try to give focus to a specific view or to one of its 7288 * descendants and give it a hint about what direction focus is heading. 7289 * 7290 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7291 * false), or if it is focusable and it is not focusable in touch mode 7292 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7293 * 7294 * See also {@link #focusSearch(int)}, which is what you call to say that you 7295 * have focus, and you want your parent to look for the next one. 7296 * 7297 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7298 * <code>null</code> set for the previously focused rectangle. 7299 * 7300 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7301 * @return Whether this view or one of its descendants actually took focus. 7302 */ 7303 public final boolean requestFocus(int direction) { 7304 return requestFocus(direction, null); 7305 } 7306 7307 /** 7308 * Call this to try to give focus to a specific view or to one of its descendants 7309 * and give it hints about the direction and a specific rectangle that the focus 7310 * is coming from. The rectangle can help give larger views a finer grained hint 7311 * about where focus is coming from, and therefore, where to show selection, or 7312 * forward focus change internally. 7313 * 7314 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7315 * false), or if it is focusable and it is not focusable in touch mode 7316 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7317 * 7318 * A View will not take focus if it is not visible. 7319 * 7320 * A View will not take focus if one of its parents has 7321 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7322 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7323 * 7324 * See also {@link #focusSearch(int)}, which is what you call to say that you 7325 * have focus, and you want your parent to look for the next one. 7326 * 7327 * You may wish to override this method if your custom {@link View} has an internal 7328 * {@link View} that it wishes to forward the request to. 7329 * 7330 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7331 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7332 * to give a finer grained hint about where focus is coming from. May be null 7333 * if there is no hint. 7334 * @return Whether this view or one of its descendants actually took focus. 7335 */ 7336 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7337 return requestFocusNoSearch(direction, previouslyFocusedRect); 7338 } 7339 7340 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7341 // need to be focusable 7342 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7343 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7344 return false; 7345 } 7346 7347 // need to be focusable in touch mode if in touch mode 7348 if (isInTouchMode() && 7349 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7350 return false; 7351 } 7352 7353 // need to not have any parents blocking us 7354 if (hasAncestorThatBlocksDescendantFocus()) { 7355 return false; 7356 } 7357 7358 handleFocusGainInternal(direction, previouslyFocusedRect); 7359 return true; 7360 } 7361 7362 /** 7363 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7364 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7365 * touch mode to request focus when they are touched. 7366 * 7367 * @return Whether this view or one of its descendants actually took focus. 7368 * 7369 * @see #isInTouchMode() 7370 * 7371 */ 7372 public final boolean requestFocusFromTouch() { 7373 // Leave touch mode if we need to 7374 if (isInTouchMode()) { 7375 ViewRootImpl viewRoot = getViewRootImpl(); 7376 if (viewRoot != null) { 7377 viewRoot.ensureTouchMode(false); 7378 } 7379 } 7380 return requestFocus(View.FOCUS_DOWN); 7381 } 7382 7383 /** 7384 * @return Whether any ancestor of this view blocks descendant focus. 7385 */ 7386 private boolean hasAncestorThatBlocksDescendantFocus() { 7387 ViewParent ancestor = mParent; 7388 while (ancestor instanceof ViewGroup) { 7389 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7390 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7391 return true; 7392 } else { 7393 ancestor = vgAncestor.getParent(); 7394 } 7395 } 7396 return false; 7397 } 7398 7399 /** 7400 * Gets the mode for determining whether this View is important for accessibility 7401 * which is if it fires accessibility events and if it is reported to 7402 * accessibility services that query the screen. 7403 * 7404 * @return The mode for determining whether a View is important for accessibility. 7405 * 7406 * @attr ref android.R.styleable#View_importantForAccessibility 7407 * 7408 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7409 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7410 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7411 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7412 */ 7413 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7414 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7415 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7416 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7417 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7418 to = "noHideDescendants") 7419 }) 7420 public int getImportantForAccessibility() { 7421 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7422 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7423 } 7424 7425 /** 7426 * Sets the live region mode for this view. This indicates to accessibility 7427 * services whether they should automatically notify the user about changes 7428 * to the view's content description or text, or to the content descriptions 7429 * or text of the view's children (where applicable). 7430 * <p> 7431 * For example, in a login screen with a TextView that displays an "incorrect 7432 * password" notification, that view should be marked as a live region with 7433 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7434 * <p> 7435 * To disable change notifications for this view, use 7436 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7437 * mode for most views. 7438 * <p> 7439 * To indicate that the user should be notified of changes, use 7440 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7441 * <p> 7442 * If the view's changes should interrupt ongoing speech and notify the user 7443 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7444 * 7445 * @param mode The live region mode for this view, one of: 7446 * <ul> 7447 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7448 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7449 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7450 * </ul> 7451 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7452 */ 7453 public void setAccessibilityLiveRegion(int mode) { 7454 if (mode != getAccessibilityLiveRegion()) { 7455 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7456 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7457 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7458 notifyViewAccessibilityStateChangedIfNeeded( 7459 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7460 } 7461 } 7462 7463 /** 7464 * Gets the live region mode for this View. 7465 * 7466 * @return The live region mode for the view. 7467 * 7468 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7469 * 7470 * @see #setAccessibilityLiveRegion(int) 7471 */ 7472 public int getAccessibilityLiveRegion() { 7473 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7474 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7475 } 7476 7477 /** 7478 * Sets how to determine whether this view is important for accessibility 7479 * which is if it fires accessibility events and if it is reported to 7480 * accessibility services that query the screen. 7481 * 7482 * @param mode How to determine whether this view is important for accessibility. 7483 * 7484 * @attr ref android.R.styleable#View_importantForAccessibility 7485 * 7486 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7487 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7488 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7489 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7490 */ 7491 public void setImportantForAccessibility(int mode) { 7492 final int oldMode = getImportantForAccessibility(); 7493 if (mode != oldMode) { 7494 // If we're moving between AUTO and another state, we might not need 7495 // to send a subtree changed notification. We'll store the computed 7496 // importance, since we'll need to check it later to make sure. 7497 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7498 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7499 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7500 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7501 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7502 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7503 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7504 notifySubtreeAccessibilityStateChangedIfNeeded(); 7505 } else { 7506 notifyViewAccessibilityStateChangedIfNeeded( 7507 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7508 } 7509 } 7510 } 7511 7512 /** 7513 * Computes whether this view should be exposed for accessibility. In 7514 * general, views that are interactive or provide information are exposed 7515 * while views that serve only as containers are hidden. 7516 * <p> 7517 * If an ancestor of this view has importance 7518 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7519 * returns <code>false</code>. 7520 * <p> 7521 * Otherwise, the value is computed according to the view's 7522 * {@link #getImportantForAccessibility()} value: 7523 * <ol> 7524 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7525 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7526 * </code> 7527 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7528 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7529 * view satisfies any of the following: 7530 * <ul> 7531 * <li>Is actionable, e.g. {@link #isClickable()}, 7532 * {@link #isLongClickable()}, or {@link #isFocusable()} 7533 * <li>Has an {@link AccessibilityDelegate} 7534 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7535 * {@link OnKeyListener}, etc. 7536 * <li>Is an accessibility live region, e.g. 7537 * {@link #getAccessibilityLiveRegion()} is not 7538 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7539 * </ul> 7540 * </ol> 7541 * 7542 * @return Whether the view is exposed for accessibility. 7543 * @see #setImportantForAccessibility(int) 7544 * @see #getImportantForAccessibility() 7545 */ 7546 public boolean isImportantForAccessibility() { 7547 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7548 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7549 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7550 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7551 return false; 7552 } 7553 7554 // Check parent mode to ensure we're not hidden. 7555 ViewParent parent = mParent; 7556 while (parent instanceof View) { 7557 if (((View) parent).getImportantForAccessibility() 7558 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7559 return false; 7560 } 7561 parent = parent.getParent(); 7562 } 7563 7564 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7565 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7566 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7567 } 7568 7569 /** 7570 * Gets the parent for accessibility purposes. Note that the parent for 7571 * accessibility is not necessary the immediate parent. It is the first 7572 * predecessor that is important for accessibility. 7573 * 7574 * @return The parent for accessibility purposes. 7575 */ 7576 public ViewParent getParentForAccessibility() { 7577 if (mParent instanceof View) { 7578 View parentView = (View) mParent; 7579 if (parentView.includeForAccessibility()) { 7580 return mParent; 7581 } else { 7582 return mParent.getParentForAccessibility(); 7583 } 7584 } 7585 return null; 7586 } 7587 7588 /** 7589 * Adds the children of a given View for accessibility. Since some Views are 7590 * not important for accessibility the children for accessibility are not 7591 * necessarily direct children of the view, rather they are the first level of 7592 * descendants important for accessibility. 7593 * 7594 * @param children The list of children for accessibility. 7595 */ 7596 public void addChildrenForAccessibility(ArrayList<View> children) { 7597 7598 } 7599 7600 /** 7601 * Whether to regard this view for accessibility. A view is regarded for 7602 * accessibility if it is important for accessibility or the querying 7603 * accessibility service has explicitly requested that view not 7604 * important for accessibility are regarded. 7605 * 7606 * @return Whether to regard the view for accessibility. 7607 * 7608 * @hide 7609 */ 7610 public boolean includeForAccessibility() { 7611 if (mAttachInfo != null) { 7612 return (mAttachInfo.mAccessibilityFetchFlags 7613 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7614 || isImportantForAccessibility(); 7615 } 7616 return false; 7617 } 7618 7619 /** 7620 * Returns whether the View is considered actionable from 7621 * accessibility perspective. Such view are important for 7622 * accessibility. 7623 * 7624 * @return True if the view is actionable for accessibility. 7625 * 7626 * @hide 7627 */ 7628 public boolean isActionableForAccessibility() { 7629 return (isClickable() || isLongClickable() || isFocusable()); 7630 } 7631 7632 /** 7633 * Returns whether the View has registered callbacks which makes it 7634 * important for accessibility. 7635 * 7636 * @return True if the view is actionable for accessibility. 7637 */ 7638 private boolean hasListenersForAccessibility() { 7639 ListenerInfo info = getListenerInfo(); 7640 return mTouchDelegate != null || info.mOnKeyListener != null 7641 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7642 || info.mOnHoverListener != null || info.mOnDragListener != null; 7643 } 7644 7645 /** 7646 * Notifies that the accessibility state of this view changed. The change 7647 * is local to this view and does not represent structural changes such 7648 * as children and parent. For example, the view became focusable. The 7649 * notification is at at most once every 7650 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7651 * to avoid unnecessary load to the system. Also once a view has a pending 7652 * notification this method is a NOP until the notification has been sent. 7653 * 7654 * @hide 7655 */ 7656 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7657 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7658 return; 7659 } 7660 if (mSendViewStateChangedAccessibilityEvent == null) { 7661 mSendViewStateChangedAccessibilityEvent = 7662 new SendViewStateChangedAccessibilityEvent(); 7663 } 7664 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7665 } 7666 7667 /** 7668 * Notifies that the accessibility state of this view changed. The change 7669 * is *not* local to this view and does represent structural changes such 7670 * as children and parent. For example, the view size changed. The 7671 * notification is at at most once every 7672 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7673 * to avoid unnecessary load to the system. Also once a view has a pending 7674 * notification this method is a NOP until the notification has been sent. 7675 * 7676 * @hide 7677 */ 7678 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7679 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7680 return; 7681 } 7682 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7683 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7684 if (mParent != null) { 7685 try { 7686 mParent.notifySubtreeAccessibilityStateChanged( 7687 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7688 } catch (AbstractMethodError e) { 7689 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7690 " does not fully implement ViewParent", e); 7691 } 7692 } 7693 } 7694 } 7695 7696 /** 7697 * Reset the flag indicating the accessibility state of the subtree rooted 7698 * at this view changed. 7699 */ 7700 void resetSubtreeAccessibilityStateChanged() { 7701 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7702 } 7703 7704 /** 7705 * Performs the specified accessibility action on the view. For 7706 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7707 * <p> 7708 * If an {@link AccessibilityDelegate} has been specified via calling 7709 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7710 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7711 * is responsible for handling this call. 7712 * </p> 7713 * 7714 * @param action The action to perform. 7715 * @param arguments Optional action arguments. 7716 * @return Whether the action was performed. 7717 */ 7718 public boolean performAccessibilityAction(int action, Bundle arguments) { 7719 if (mAccessibilityDelegate != null) { 7720 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7721 } else { 7722 return performAccessibilityActionInternal(action, arguments); 7723 } 7724 } 7725 7726 /** 7727 * @see #performAccessibilityAction(int, Bundle) 7728 * 7729 * Note: Called from the default {@link AccessibilityDelegate}. 7730 */ 7731 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7732 switch (action) { 7733 case AccessibilityNodeInfo.ACTION_CLICK: { 7734 if (isClickable()) { 7735 performClick(); 7736 return true; 7737 } 7738 } break; 7739 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7740 if (isLongClickable()) { 7741 performLongClick(); 7742 return true; 7743 } 7744 } break; 7745 case AccessibilityNodeInfo.ACTION_FOCUS: { 7746 if (!hasFocus()) { 7747 // Get out of touch mode since accessibility 7748 // wants to move focus around. 7749 getViewRootImpl().ensureTouchMode(false); 7750 return requestFocus(); 7751 } 7752 } break; 7753 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7754 if (hasFocus()) { 7755 clearFocus(); 7756 return !isFocused(); 7757 } 7758 } break; 7759 case AccessibilityNodeInfo.ACTION_SELECT: { 7760 if (!isSelected()) { 7761 setSelected(true); 7762 return isSelected(); 7763 } 7764 } break; 7765 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7766 if (isSelected()) { 7767 setSelected(false); 7768 return !isSelected(); 7769 } 7770 } break; 7771 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7772 if (!isAccessibilityFocused()) { 7773 return requestAccessibilityFocus(); 7774 } 7775 } break; 7776 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7777 if (isAccessibilityFocused()) { 7778 clearAccessibilityFocus(); 7779 return true; 7780 } 7781 } break; 7782 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7783 if (arguments != null) { 7784 final int granularity = arguments.getInt( 7785 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7786 final boolean extendSelection = arguments.getBoolean( 7787 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7788 return traverseAtGranularity(granularity, true, extendSelection); 7789 } 7790 } break; 7791 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7792 if (arguments != null) { 7793 final int granularity = arguments.getInt( 7794 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7795 final boolean extendSelection = arguments.getBoolean( 7796 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7797 return traverseAtGranularity(granularity, false, extendSelection); 7798 } 7799 } break; 7800 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7801 CharSequence text = getIterableTextForAccessibility(); 7802 if (text == null) { 7803 return false; 7804 } 7805 final int start = (arguments != null) ? arguments.getInt( 7806 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7807 final int end = (arguments != null) ? arguments.getInt( 7808 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7809 // Only cursor position can be specified (selection length == 0) 7810 if ((getAccessibilitySelectionStart() != start 7811 || getAccessibilitySelectionEnd() != end) 7812 && (start == end)) { 7813 setAccessibilitySelection(start, end); 7814 notifyViewAccessibilityStateChangedIfNeeded( 7815 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7816 return true; 7817 } 7818 } break; 7819 } 7820 return false; 7821 } 7822 7823 private boolean traverseAtGranularity(int granularity, boolean forward, 7824 boolean extendSelection) { 7825 CharSequence text = getIterableTextForAccessibility(); 7826 if (text == null || text.length() == 0) { 7827 return false; 7828 } 7829 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7830 if (iterator == null) { 7831 return false; 7832 } 7833 int current = getAccessibilitySelectionEnd(); 7834 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7835 current = forward ? 0 : text.length(); 7836 } 7837 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7838 if (range == null) { 7839 return false; 7840 } 7841 final int segmentStart = range[0]; 7842 final int segmentEnd = range[1]; 7843 int selectionStart; 7844 int selectionEnd; 7845 if (extendSelection && isAccessibilitySelectionExtendable()) { 7846 selectionStart = getAccessibilitySelectionStart(); 7847 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7848 selectionStart = forward ? segmentStart : segmentEnd; 7849 } 7850 selectionEnd = forward ? segmentEnd : segmentStart; 7851 } else { 7852 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7853 } 7854 setAccessibilitySelection(selectionStart, selectionEnd); 7855 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7856 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7857 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7858 return true; 7859 } 7860 7861 /** 7862 * Gets the text reported for accessibility purposes. 7863 * 7864 * @return The accessibility text. 7865 * 7866 * @hide 7867 */ 7868 public CharSequence getIterableTextForAccessibility() { 7869 return getContentDescription(); 7870 } 7871 7872 /** 7873 * Gets whether accessibility selection can be extended. 7874 * 7875 * @return If selection is extensible. 7876 * 7877 * @hide 7878 */ 7879 public boolean isAccessibilitySelectionExtendable() { 7880 return false; 7881 } 7882 7883 /** 7884 * @hide 7885 */ 7886 public int getAccessibilitySelectionStart() { 7887 return mAccessibilityCursorPosition; 7888 } 7889 7890 /** 7891 * @hide 7892 */ 7893 public int getAccessibilitySelectionEnd() { 7894 return getAccessibilitySelectionStart(); 7895 } 7896 7897 /** 7898 * @hide 7899 */ 7900 public void setAccessibilitySelection(int start, int end) { 7901 if (start == end && end == mAccessibilityCursorPosition) { 7902 return; 7903 } 7904 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7905 mAccessibilityCursorPosition = start; 7906 } else { 7907 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7908 } 7909 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7910 } 7911 7912 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7913 int fromIndex, int toIndex) { 7914 if (mParent == null) { 7915 return; 7916 } 7917 AccessibilityEvent event = AccessibilityEvent.obtain( 7918 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7919 onInitializeAccessibilityEvent(event); 7920 onPopulateAccessibilityEvent(event); 7921 event.setFromIndex(fromIndex); 7922 event.setToIndex(toIndex); 7923 event.setAction(action); 7924 event.setMovementGranularity(granularity); 7925 mParent.requestSendAccessibilityEvent(this, event); 7926 } 7927 7928 /** 7929 * @hide 7930 */ 7931 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7932 switch (granularity) { 7933 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7934 CharSequence text = getIterableTextForAccessibility(); 7935 if (text != null && text.length() > 0) { 7936 CharacterTextSegmentIterator iterator = 7937 CharacterTextSegmentIterator.getInstance( 7938 mContext.getResources().getConfiguration().locale); 7939 iterator.initialize(text.toString()); 7940 return iterator; 7941 } 7942 } break; 7943 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7944 CharSequence text = getIterableTextForAccessibility(); 7945 if (text != null && text.length() > 0) { 7946 WordTextSegmentIterator iterator = 7947 WordTextSegmentIterator.getInstance( 7948 mContext.getResources().getConfiguration().locale); 7949 iterator.initialize(text.toString()); 7950 return iterator; 7951 } 7952 } break; 7953 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7954 CharSequence text = getIterableTextForAccessibility(); 7955 if (text != null && text.length() > 0) { 7956 ParagraphTextSegmentIterator iterator = 7957 ParagraphTextSegmentIterator.getInstance(); 7958 iterator.initialize(text.toString()); 7959 return iterator; 7960 } 7961 } break; 7962 } 7963 return null; 7964 } 7965 7966 /** 7967 * @hide 7968 */ 7969 public void dispatchStartTemporaryDetach() { 7970 onStartTemporaryDetach(); 7971 } 7972 7973 /** 7974 * This is called when a container is going to temporarily detach a child, with 7975 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7976 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7977 * {@link #onDetachedFromWindow()} when the container is done. 7978 */ 7979 public void onStartTemporaryDetach() { 7980 removeUnsetPressCallback(); 7981 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7982 } 7983 7984 /** 7985 * @hide 7986 */ 7987 public void dispatchFinishTemporaryDetach() { 7988 onFinishTemporaryDetach(); 7989 } 7990 7991 /** 7992 * Called after {@link #onStartTemporaryDetach} when the container is done 7993 * changing the view. 7994 */ 7995 public void onFinishTemporaryDetach() { 7996 } 7997 7998 /** 7999 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8000 * for this view's window. Returns null if the view is not currently attached 8001 * to the window. Normally you will not need to use this directly, but 8002 * just use the standard high-level event callbacks like 8003 * {@link #onKeyDown(int, KeyEvent)}. 8004 */ 8005 public KeyEvent.DispatcherState getKeyDispatcherState() { 8006 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8007 } 8008 8009 /** 8010 * Dispatch a key event before it is processed by any input method 8011 * associated with the view hierarchy. This can be used to intercept 8012 * key events in special situations before the IME consumes them; a 8013 * typical example would be handling the BACK key to update the application's 8014 * UI instead of allowing the IME to see it and close itself. 8015 * 8016 * @param event The key event to be dispatched. 8017 * @return True if the event was handled, false otherwise. 8018 */ 8019 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8020 return onKeyPreIme(event.getKeyCode(), event); 8021 } 8022 8023 /** 8024 * Dispatch a key event to the next view on the focus path. This path runs 8025 * from the top of the view tree down to the currently focused view. If this 8026 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8027 * the next node down the focus path. This method also fires any key 8028 * listeners. 8029 * 8030 * @param event The key event to be dispatched. 8031 * @return True if the event was handled, false otherwise. 8032 */ 8033 public boolean dispatchKeyEvent(KeyEvent event) { 8034 if (mInputEventConsistencyVerifier != null) { 8035 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8036 } 8037 8038 // Give any attached key listener a first crack at the event. 8039 //noinspection SimplifiableIfStatement 8040 ListenerInfo li = mListenerInfo; 8041 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8042 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8043 return true; 8044 } 8045 8046 if (event.dispatch(this, mAttachInfo != null 8047 ? mAttachInfo.mKeyDispatchState : null, this)) { 8048 return true; 8049 } 8050 8051 if (mInputEventConsistencyVerifier != null) { 8052 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8053 } 8054 return false; 8055 } 8056 8057 /** 8058 * Dispatches a key shortcut event. 8059 * 8060 * @param event The key event to be dispatched. 8061 * @return True if the event was handled by the view, false otherwise. 8062 */ 8063 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8064 return onKeyShortcut(event.getKeyCode(), event); 8065 } 8066 8067 /** 8068 * Pass the touch screen motion event down to the target view, or this 8069 * view if it is the target. 8070 * 8071 * @param event The motion event to be dispatched. 8072 * @return True if the event was handled by the view, false otherwise. 8073 */ 8074 public boolean dispatchTouchEvent(MotionEvent event) { 8075 boolean result = false; 8076 8077 if (mInputEventConsistencyVerifier != null) { 8078 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8079 } 8080 8081 final int actionMasked = event.getActionMasked(); 8082 if (actionMasked == MotionEvent.ACTION_DOWN) { 8083 // Defensive cleanup for new gesture 8084 stopNestedScroll(); 8085 } 8086 8087 if (onFilterTouchEventForSecurity(event)) { 8088 //noinspection SimplifiableIfStatement 8089 ListenerInfo li = mListenerInfo; 8090 if (li != null && li.mOnTouchListener != null 8091 && (mViewFlags & ENABLED_MASK) == ENABLED 8092 && li.mOnTouchListener.onTouch(this, event)) { 8093 result = true; 8094 } 8095 8096 if (!result && onTouchEvent(event)) { 8097 result = true; 8098 } 8099 } 8100 8101 if (!result && mInputEventConsistencyVerifier != null) { 8102 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8103 } 8104 8105 // Clean up after nested scrolls if this is the end of a gesture; 8106 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8107 // of the gesture. 8108 if (actionMasked == MotionEvent.ACTION_UP || 8109 actionMasked == MotionEvent.ACTION_CANCEL || 8110 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8111 stopNestedScroll(); 8112 } 8113 8114 return result; 8115 } 8116 8117 /** 8118 * Filter the touch event to apply security policies. 8119 * 8120 * @param event The motion event to be filtered. 8121 * @return True if the event should be dispatched, false if the event should be dropped. 8122 * 8123 * @see #getFilterTouchesWhenObscured 8124 */ 8125 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8126 //noinspection RedundantIfStatement 8127 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8128 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8129 // Window is obscured, drop this touch. 8130 return false; 8131 } 8132 return true; 8133 } 8134 8135 /** 8136 * Pass a trackball motion event down to the focused view. 8137 * 8138 * @param event The motion event to be dispatched. 8139 * @return True if the event was handled by the view, false otherwise. 8140 */ 8141 public boolean dispatchTrackballEvent(MotionEvent event) { 8142 if (mInputEventConsistencyVerifier != null) { 8143 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8144 } 8145 8146 return onTrackballEvent(event); 8147 } 8148 8149 /** 8150 * Dispatch a generic motion event. 8151 * <p> 8152 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8153 * are delivered to the view under the pointer. All other generic motion events are 8154 * delivered to the focused view. Hover events are handled specially and are delivered 8155 * to {@link #onHoverEvent(MotionEvent)}. 8156 * </p> 8157 * 8158 * @param event The motion event to be dispatched. 8159 * @return True if the event was handled by the view, false otherwise. 8160 */ 8161 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8162 if (mInputEventConsistencyVerifier != null) { 8163 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8164 } 8165 8166 final int source = event.getSource(); 8167 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8168 final int action = event.getAction(); 8169 if (action == MotionEvent.ACTION_HOVER_ENTER 8170 || action == MotionEvent.ACTION_HOVER_MOVE 8171 || action == MotionEvent.ACTION_HOVER_EXIT) { 8172 if (dispatchHoverEvent(event)) { 8173 return true; 8174 } 8175 } else if (dispatchGenericPointerEvent(event)) { 8176 return true; 8177 } 8178 } else if (dispatchGenericFocusedEvent(event)) { 8179 return true; 8180 } 8181 8182 if (dispatchGenericMotionEventInternal(event)) { 8183 return true; 8184 } 8185 8186 if (mInputEventConsistencyVerifier != null) { 8187 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8188 } 8189 return false; 8190 } 8191 8192 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8193 //noinspection SimplifiableIfStatement 8194 ListenerInfo li = mListenerInfo; 8195 if (li != null && li.mOnGenericMotionListener != null 8196 && (mViewFlags & ENABLED_MASK) == ENABLED 8197 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8198 return true; 8199 } 8200 8201 if (onGenericMotionEvent(event)) { 8202 return true; 8203 } 8204 8205 if (mInputEventConsistencyVerifier != null) { 8206 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8207 } 8208 return false; 8209 } 8210 8211 /** 8212 * Dispatch a hover event. 8213 * <p> 8214 * Do not call this method directly. 8215 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8216 * </p> 8217 * 8218 * @param event The motion event to be dispatched. 8219 * @return True if the event was handled by the view, false otherwise. 8220 */ 8221 protected boolean dispatchHoverEvent(MotionEvent event) { 8222 ListenerInfo li = mListenerInfo; 8223 //noinspection SimplifiableIfStatement 8224 if (li != null && li.mOnHoverListener != null 8225 && (mViewFlags & ENABLED_MASK) == ENABLED 8226 && li.mOnHoverListener.onHover(this, event)) { 8227 return true; 8228 } 8229 8230 return onHoverEvent(event); 8231 } 8232 8233 /** 8234 * Returns true if the view has a child to which it has recently sent 8235 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8236 * it does not have a hovered child, then it must be the innermost hovered view. 8237 * @hide 8238 */ 8239 protected boolean hasHoveredChild() { 8240 return false; 8241 } 8242 8243 /** 8244 * Dispatch a generic motion event to the view under the first pointer. 8245 * <p> 8246 * Do not call this method directly. 8247 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8248 * </p> 8249 * 8250 * @param event The motion event to be dispatched. 8251 * @return True if the event was handled by the view, false otherwise. 8252 */ 8253 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8254 return false; 8255 } 8256 8257 /** 8258 * Dispatch a generic motion event to the currently focused view. 8259 * <p> 8260 * Do not call this method directly. 8261 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8262 * </p> 8263 * 8264 * @param event The motion event to be dispatched. 8265 * @return True if the event was handled by the view, false otherwise. 8266 */ 8267 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8268 return false; 8269 } 8270 8271 /** 8272 * Dispatch a pointer event. 8273 * <p> 8274 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8275 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8276 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8277 * and should not be expected to handle other pointing device features. 8278 * </p> 8279 * 8280 * @param event The motion event to be dispatched. 8281 * @return True if the event was handled by the view, false otherwise. 8282 * @hide 8283 */ 8284 public final boolean dispatchPointerEvent(MotionEvent event) { 8285 if (event.isTouchEvent()) { 8286 return dispatchTouchEvent(event); 8287 } else { 8288 return dispatchGenericMotionEvent(event); 8289 } 8290 } 8291 8292 /** 8293 * Called when the window containing this view gains or loses window focus. 8294 * ViewGroups should override to route to their children. 8295 * 8296 * @param hasFocus True if the window containing this view now has focus, 8297 * false otherwise. 8298 */ 8299 public void dispatchWindowFocusChanged(boolean hasFocus) { 8300 onWindowFocusChanged(hasFocus); 8301 } 8302 8303 /** 8304 * Called when the window containing this view gains or loses focus. Note 8305 * that this is separate from view focus: to receive key events, both 8306 * your view and its window must have focus. If a window is displayed 8307 * on top of yours that takes input focus, then your own window will lose 8308 * focus but the view focus will remain unchanged. 8309 * 8310 * @param hasWindowFocus True if the window containing this view now has 8311 * focus, false otherwise. 8312 */ 8313 public void onWindowFocusChanged(boolean hasWindowFocus) { 8314 InputMethodManager imm = InputMethodManager.peekInstance(); 8315 if (!hasWindowFocus) { 8316 if (isPressed()) { 8317 setPressed(false); 8318 } 8319 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8320 imm.focusOut(this); 8321 } 8322 removeLongPressCallback(); 8323 removeTapCallback(); 8324 onFocusLost(); 8325 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8326 imm.focusIn(this); 8327 } 8328 refreshDrawableState(); 8329 } 8330 8331 /** 8332 * Returns true if this view is in a window that currently has window focus. 8333 * Note that this is not the same as the view itself having focus. 8334 * 8335 * @return True if this view is in a window that currently has window focus. 8336 */ 8337 public boolean hasWindowFocus() { 8338 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8339 } 8340 8341 /** 8342 * Dispatch a view visibility change down the view hierarchy. 8343 * ViewGroups should override to route to their children. 8344 * @param changedView The view whose visibility changed. Could be 'this' or 8345 * an ancestor view. 8346 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8347 * {@link #INVISIBLE} or {@link #GONE}. 8348 */ 8349 protected void dispatchVisibilityChanged(@NonNull View changedView, 8350 @Visibility int visibility) { 8351 onVisibilityChanged(changedView, visibility); 8352 } 8353 8354 /** 8355 * Called when the visibility of the view or an ancestor of the view is changed. 8356 * @param changedView The view whose visibility changed. Could be 'this' or 8357 * an ancestor view. 8358 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8359 * {@link #INVISIBLE} or {@link #GONE}. 8360 */ 8361 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8362 if (visibility == VISIBLE) { 8363 if (mAttachInfo != null) { 8364 initialAwakenScrollBars(); 8365 } else { 8366 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8367 } 8368 } 8369 } 8370 8371 /** 8372 * Dispatch a hint about whether this view is displayed. For instance, when 8373 * a View moves out of the screen, it might receives a display hint indicating 8374 * the view is not displayed. Applications should not <em>rely</em> on this hint 8375 * as there is no guarantee that they will receive one. 8376 * 8377 * @param hint A hint about whether or not this view is displayed: 8378 * {@link #VISIBLE} or {@link #INVISIBLE}. 8379 */ 8380 public void dispatchDisplayHint(@Visibility int hint) { 8381 onDisplayHint(hint); 8382 } 8383 8384 /** 8385 * Gives this view a hint about whether is displayed or not. For instance, when 8386 * a View moves out of the screen, it might receives a display hint indicating 8387 * the view is not displayed. Applications should not <em>rely</em> on this hint 8388 * as there is no guarantee that they will receive one. 8389 * 8390 * @param hint A hint about whether or not this view is displayed: 8391 * {@link #VISIBLE} or {@link #INVISIBLE}. 8392 */ 8393 protected void onDisplayHint(@Visibility int hint) { 8394 } 8395 8396 /** 8397 * Dispatch a window visibility change down the view hierarchy. 8398 * ViewGroups should override to route to their children. 8399 * 8400 * @param visibility The new visibility of the window. 8401 * 8402 * @see #onWindowVisibilityChanged(int) 8403 */ 8404 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8405 onWindowVisibilityChanged(visibility); 8406 } 8407 8408 /** 8409 * Called when the window containing has change its visibility 8410 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8411 * that this tells you whether or not your window is being made visible 8412 * to the window manager; this does <em>not</em> tell you whether or not 8413 * your window is obscured by other windows on the screen, even if it 8414 * is itself visible. 8415 * 8416 * @param visibility The new visibility of the window. 8417 */ 8418 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8419 if (visibility == VISIBLE) { 8420 initialAwakenScrollBars(); 8421 } 8422 } 8423 8424 /** 8425 * Returns the current visibility of the window this view is attached to 8426 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8427 * 8428 * @return Returns the current visibility of the view's window. 8429 */ 8430 @Visibility 8431 public int getWindowVisibility() { 8432 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8433 } 8434 8435 /** 8436 * Retrieve the overall visible display size in which the window this view is 8437 * attached to has been positioned in. This takes into account screen 8438 * decorations above the window, for both cases where the window itself 8439 * is being position inside of them or the window is being placed under 8440 * then and covered insets are used for the window to position its content 8441 * inside. In effect, this tells you the available area where content can 8442 * be placed and remain visible to users. 8443 * 8444 * <p>This function requires an IPC back to the window manager to retrieve 8445 * the requested information, so should not be used in performance critical 8446 * code like drawing. 8447 * 8448 * @param outRect Filled in with the visible display frame. If the view 8449 * is not attached to a window, this is simply the raw display size. 8450 */ 8451 public void getWindowVisibleDisplayFrame(Rect outRect) { 8452 if (mAttachInfo != null) { 8453 try { 8454 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8455 } catch (RemoteException e) { 8456 return; 8457 } 8458 // XXX This is really broken, and probably all needs to be done 8459 // in the window manager, and we need to know more about whether 8460 // we want the area behind or in front of the IME. 8461 final Rect insets = mAttachInfo.mVisibleInsets; 8462 outRect.left += insets.left; 8463 outRect.top += insets.top; 8464 outRect.right -= insets.right; 8465 outRect.bottom -= insets.bottom; 8466 return; 8467 } 8468 // The view is not attached to a display so we don't have a context. 8469 // Make a best guess about the display size. 8470 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8471 d.getRectSize(outRect); 8472 } 8473 8474 /** 8475 * Dispatch a notification about a resource configuration change down 8476 * the view hierarchy. 8477 * ViewGroups should override to route to their children. 8478 * 8479 * @param newConfig The new resource configuration. 8480 * 8481 * @see #onConfigurationChanged(android.content.res.Configuration) 8482 */ 8483 public void dispatchConfigurationChanged(Configuration newConfig) { 8484 onConfigurationChanged(newConfig); 8485 } 8486 8487 /** 8488 * Called when the current configuration of the resources being used 8489 * by the application have changed. You can use this to decide when 8490 * to reload resources that can changed based on orientation and other 8491 * configuration characterstics. You only need to use this if you are 8492 * not relying on the normal {@link android.app.Activity} mechanism of 8493 * recreating the activity instance upon a configuration change. 8494 * 8495 * @param newConfig The new resource configuration. 8496 */ 8497 protected void onConfigurationChanged(Configuration newConfig) { 8498 } 8499 8500 /** 8501 * Private function to aggregate all per-view attributes in to the view 8502 * root. 8503 */ 8504 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8505 performCollectViewAttributes(attachInfo, visibility); 8506 } 8507 8508 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8509 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8510 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8511 attachInfo.mKeepScreenOn = true; 8512 } 8513 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8514 ListenerInfo li = mListenerInfo; 8515 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8516 attachInfo.mHasSystemUiListeners = true; 8517 } 8518 } 8519 } 8520 8521 void needGlobalAttributesUpdate(boolean force) { 8522 final AttachInfo ai = mAttachInfo; 8523 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8524 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8525 || ai.mHasSystemUiListeners) { 8526 ai.mRecomputeGlobalAttributes = true; 8527 } 8528 } 8529 } 8530 8531 /** 8532 * Returns whether the device is currently in touch mode. Touch mode is entered 8533 * once the user begins interacting with the device by touch, and affects various 8534 * things like whether focus is always visible to the user. 8535 * 8536 * @return Whether the device is in touch mode. 8537 */ 8538 @ViewDebug.ExportedProperty 8539 public boolean isInTouchMode() { 8540 if (mAttachInfo != null) { 8541 return mAttachInfo.mInTouchMode; 8542 } else { 8543 return ViewRootImpl.isInTouchMode(); 8544 } 8545 } 8546 8547 /** 8548 * Returns the context the view is running in, through which it can 8549 * access the current theme, resources, etc. 8550 * 8551 * @return The view's Context. 8552 */ 8553 @ViewDebug.CapturedViewProperty 8554 public final Context getContext() { 8555 return mContext; 8556 } 8557 8558 /** 8559 * Handle a key event before it is processed by any input method 8560 * associated with the view hierarchy. This can be used to intercept 8561 * key events in special situations before the IME consumes them; a 8562 * typical example would be handling the BACK key to update the application's 8563 * UI instead of allowing the IME to see it and close itself. 8564 * 8565 * @param keyCode The value in event.getKeyCode(). 8566 * @param event Description of the key event. 8567 * @return If you handled the event, return true. If you want to allow the 8568 * event to be handled by the next receiver, return false. 8569 */ 8570 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8571 return false; 8572 } 8573 8574 /** 8575 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8576 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8577 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8578 * is released, if the view is enabled and clickable. 8579 * 8580 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8581 * although some may elect to do so in some situations. Do not rely on this to 8582 * catch software key presses. 8583 * 8584 * @param keyCode A key code that represents the button pressed, from 8585 * {@link android.view.KeyEvent}. 8586 * @param event The KeyEvent object that defines the button action. 8587 */ 8588 public boolean onKeyDown(int keyCode, KeyEvent event) { 8589 boolean result = false; 8590 8591 if (KeyEvent.isConfirmKey(keyCode)) { 8592 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8593 return true; 8594 } 8595 // Long clickable items don't necessarily have to be clickable 8596 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8597 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8598 (event.getRepeatCount() == 0)) { 8599 setPressed(true); 8600 checkForLongClick(0); 8601 return true; 8602 } 8603 } 8604 return result; 8605 } 8606 8607 /** 8608 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8609 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8610 * the event). 8611 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8612 * although some may elect to do so in some situations. Do not rely on this to 8613 * catch software key presses. 8614 */ 8615 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8616 return false; 8617 } 8618 8619 /** 8620 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8621 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8622 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8623 * {@link KeyEvent#KEYCODE_ENTER} is released. 8624 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8625 * although some may elect to do so in some situations. Do not rely on this to 8626 * catch software key presses. 8627 * 8628 * @param keyCode A key code that represents the button pressed, from 8629 * {@link android.view.KeyEvent}. 8630 * @param event The KeyEvent object that defines the button action. 8631 */ 8632 public boolean onKeyUp(int keyCode, KeyEvent event) { 8633 if (KeyEvent.isConfirmKey(keyCode)) { 8634 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8635 return true; 8636 } 8637 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8638 setPressed(false); 8639 8640 if (!mHasPerformedLongPress) { 8641 // This is a tap, so remove the longpress check 8642 removeLongPressCallback(); 8643 return performClick(); 8644 } 8645 } 8646 } 8647 return false; 8648 } 8649 8650 /** 8651 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8652 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8653 * the event). 8654 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8655 * although some may elect to do so in some situations. Do not rely on this to 8656 * catch software key presses. 8657 * 8658 * @param keyCode A key code that represents the button pressed, from 8659 * {@link android.view.KeyEvent}. 8660 * @param repeatCount The number of times the action was made. 8661 * @param event The KeyEvent object that defines the button action. 8662 */ 8663 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8664 return false; 8665 } 8666 8667 /** 8668 * Called on the focused view when a key shortcut event is not handled. 8669 * Override this method to implement local key shortcuts for the View. 8670 * Key shortcuts can also be implemented by setting the 8671 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8672 * 8673 * @param keyCode The value in event.getKeyCode(). 8674 * @param event Description of the key event. 8675 * @return If you handled the event, return true. If you want to allow the 8676 * event to be handled by the next receiver, return false. 8677 */ 8678 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8679 return false; 8680 } 8681 8682 /** 8683 * Check whether the called view is a text editor, in which case it 8684 * would make sense to automatically display a soft input window for 8685 * it. Subclasses should override this if they implement 8686 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8687 * a call on that method would return a non-null InputConnection, and 8688 * they are really a first-class editor that the user would normally 8689 * start typing on when the go into a window containing your view. 8690 * 8691 * <p>The default implementation always returns false. This does 8692 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8693 * will not be called or the user can not otherwise perform edits on your 8694 * view; it is just a hint to the system that this is not the primary 8695 * purpose of this view. 8696 * 8697 * @return Returns true if this view is a text editor, else false. 8698 */ 8699 public boolean onCheckIsTextEditor() { 8700 return false; 8701 } 8702 8703 /** 8704 * Create a new InputConnection for an InputMethod to interact 8705 * with the view. The default implementation returns null, since it doesn't 8706 * support input methods. You can override this to implement such support. 8707 * This is only needed for views that take focus and text input. 8708 * 8709 * <p>When implementing this, you probably also want to implement 8710 * {@link #onCheckIsTextEditor()} to indicate you will return a 8711 * non-null InputConnection.</p> 8712 * 8713 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8714 * object correctly and in its entirety, so that the connected IME can rely 8715 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8716 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8717 * must be filled in with the correct cursor position for IMEs to work correctly 8718 * with your application.</p> 8719 * 8720 * @param outAttrs Fill in with attribute information about the connection. 8721 */ 8722 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8723 return null; 8724 } 8725 8726 /** 8727 * Called by the {@link android.view.inputmethod.InputMethodManager} 8728 * when a view who is not the current 8729 * input connection target is trying to make a call on the manager. The 8730 * default implementation returns false; you can override this to return 8731 * true for certain views if you are performing InputConnection proxying 8732 * to them. 8733 * @param view The View that is making the InputMethodManager call. 8734 * @return Return true to allow the call, false to reject. 8735 */ 8736 public boolean checkInputConnectionProxy(View view) { 8737 return false; 8738 } 8739 8740 /** 8741 * Show the context menu for this view. It is not safe to hold on to the 8742 * menu after returning from this method. 8743 * 8744 * You should normally not overload this method. Overload 8745 * {@link #onCreateContextMenu(ContextMenu)} or define an 8746 * {@link OnCreateContextMenuListener} to add items to the context menu. 8747 * 8748 * @param menu The context menu to populate 8749 */ 8750 public void createContextMenu(ContextMenu menu) { 8751 ContextMenuInfo menuInfo = getContextMenuInfo(); 8752 8753 // Sets the current menu info so all items added to menu will have 8754 // my extra info set. 8755 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8756 8757 onCreateContextMenu(menu); 8758 ListenerInfo li = mListenerInfo; 8759 if (li != null && li.mOnCreateContextMenuListener != null) { 8760 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8761 } 8762 8763 // Clear the extra information so subsequent items that aren't mine don't 8764 // have my extra info. 8765 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8766 8767 if (mParent != null) { 8768 mParent.createContextMenu(menu); 8769 } 8770 } 8771 8772 /** 8773 * Views should implement this if they have extra information to associate 8774 * with the context menu. The return result is supplied as a parameter to 8775 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8776 * callback. 8777 * 8778 * @return Extra information about the item for which the context menu 8779 * should be shown. This information will vary across different 8780 * subclasses of View. 8781 */ 8782 protected ContextMenuInfo getContextMenuInfo() { 8783 return null; 8784 } 8785 8786 /** 8787 * Views should implement this if the view itself is going to add items to 8788 * the context menu. 8789 * 8790 * @param menu the context menu to populate 8791 */ 8792 protected void onCreateContextMenu(ContextMenu menu) { 8793 } 8794 8795 /** 8796 * Implement this method to handle trackball motion events. The 8797 * <em>relative</em> movement of the trackball since the last event 8798 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8799 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8800 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8801 * they will often be fractional values, representing the more fine-grained 8802 * movement information available from a trackball). 8803 * 8804 * @param event The motion event. 8805 * @return True if the event was handled, false otherwise. 8806 */ 8807 public boolean onTrackballEvent(MotionEvent event) { 8808 return false; 8809 } 8810 8811 /** 8812 * Implement this method to handle generic motion events. 8813 * <p> 8814 * Generic motion events describe joystick movements, mouse hovers, track pad 8815 * touches, scroll wheel movements and other input events. The 8816 * {@link MotionEvent#getSource() source} of the motion event specifies 8817 * the class of input that was received. Implementations of this method 8818 * must examine the bits in the source before processing the event. 8819 * The following code example shows how this is done. 8820 * </p><p> 8821 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8822 * are delivered to the view under the pointer. All other generic motion events are 8823 * delivered to the focused view. 8824 * </p> 8825 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8826 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8827 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8828 * // process the joystick movement... 8829 * return true; 8830 * } 8831 * } 8832 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8833 * switch (event.getAction()) { 8834 * case MotionEvent.ACTION_HOVER_MOVE: 8835 * // process the mouse hover movement... 8836 * return true; 8837 * case MotionEvent.ACTION_SCROLL: 8838 * // process the scroll wheel movement... 8839 * return true; 8840 * } 8841 * } 8842 * return super.onGenericMotionEvent(event); 8843 * }</pre> 8844 * 8845 * @param event The generic motion event being processed. 8846 * @return True if the event was handled, false otherwise. 8847 */ 8848 public boolean onGenericMotionEvent(MotionEvent event) { 8849 return false; 8850 } 8851 8852 /** 8853 * Implement this method to handle hover events. 8854 * <p> 8855 * This method is called whenever a pointer is hovering into, over, or out of the 8856 * bounds of a view and the view is not currently being touched. 8857 * Hover events are represented as pointer events with action 8858 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8859 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8860 * </p> 8861 * <ul> 8862 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8863 * when the pointer enters the bounds of the view.</li> 8864 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8865 * when the pointer has already entered the bounds of the view and has moved.</li> 8866 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8867 * when the pointer has exited the bounds of the view or when the pointer is 8868 * about to go down due to a button click, tap, or similar user action that 8869 * causes the view to be touched.</li> 8870 * </ul> 8871 * <p> 8872 * The view should implement this method to return true to indicate that it is 8873 * handling the hover event, such as by changing its drawable state. 8874 * </p><p> 8875 * The default implementation calls {@link #setHovered} to update the hovered state 8876 * of the view when a hover enter or hover exit event is received, if the view 8877 * is enabled and is clickable. The default implementation also sends hover 8878 * accessibility events. 8879 * </p> 8880 * 8881 * @param event The motion event that describes the hover. 8882 * @return True if the view handled the hover event. 8883 * 8884 * @see #isHovered 8885 * @see #setHovered 8886 * @see #onHoverChanged 8887 */ 8888 public boolean onHoverEvent(MotionEvent event) { 8889 // The root view may receive hover (or touch) events that are outside the bounds of 8890 // the window. This code ensures that we only send accessibility events for 8891 // hovers that are actually within the bounds of the root view. 8892 final int action = event.getActionMasked(); 8893 if (!mSendingHoverAccessibilityEvents) { 8894 if ((action == MotionEvent.ACTION_HOVER_ENTER 8895 || action == MotionEvent.ACTION_HOVER_MOVE) 8896 && !hasHoveredChild() 8897 && pointInView(event.getX(), event.getY())) { 8898 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8899 mSendingHoverAccessibilityEvents = true; 8900 } 8901 } else { 8902 if (action == MotionEvent.ACTION_HOVER_EXIT 8903 || (action == MotionEvent.ACTION_MOVE 8904 && !pointInView(event.getX(), event.getY()))) { 8905 mSendingHoverAccessibilityEvents = false; 8906 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8907 } 8908 } 8909 8910 if (isHoverable()) { 8911 switch (action) { 8912 case MotionEvent.ACTION_HOVER_ENTER: 8913 setHovered(true); 8914 break; 8915 case MotionEvent.ACTION_HOVER_EXIT: 8916 setHovered(false); 8917 break; 8918 } 8919 8920 // Dispatch the event to onGenericMotionEvent before returning true. 8921 // This is to provide compatibility with existing applications that 8922 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8923 // break because of the new default handling for hoverable views 8924 // in onHoverEvent. 8925 // Note that onGenericMotionEvent will be called by default when 8926 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8927 dispatchGenericMotionEventInternal(event); 8928 // The event was already handled by calling setHovered(), so always 8929 // return true. 8930 return true; 8931 } 8932 8933 return false; 8934 } 8935 8936 /** 8937 * Returns true if the view should handle {@link #onHoverEvent} 8938 * by calling {@link #setHovered} to change its hovered state. 8939 * 8940 * @return True if the view is hoverable. 8941 */ 8942 private boolean isHoverable() { 8943 final int viewFlags = mViewFlags; 8944 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8945 return false; 8946 } 8947 8948 return (viewFlags & CLICKABLE) == CLICKABLE 8949 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8950 } 8951 8952 /** 8953 * Returns true if the view is currently hovered. 8954 * 8955 * @return True if the view is currently hovered. 8956 * 8957 * @see #setHovered 8958 * @see #onHoverChanged 8959 */ 8960 @ViewDebug.ExportedProperty 8961 public boolean isHovered() { 8962 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8963 } 8964 8965 /** 8966 * Sets whether the view is currently hovered. 8967 * <p> 8968 * Calling this method also changes the drawable state of the view. This 8969 * enables the view to react to hover by using different drawable resources 8970 * to change its appearance. 8971 * </p><p> 8972 * The {@link #onHoverChanged} method is called when the hovered state changes. 8973 * </p> 8974 * 8975 * @param hovered True if the view is hovered. 8976 * 8977 * @see #isHovered 8978 * @see #onHoverChanged 8979 */ 8980 public void setHovered(boolean hovered) { 8981 if (hovered) { 8982 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8983 mPrivateFlags |= PFLAG_HOVERED; 8984 refreshDrawableState(); 8985 onHoverChanged(true); 8986 } 8987 } else { 8988 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8989 mPrivateFlags &= ~PFLAG_HOVERED; 8990 refreshDrawableState(); 8991 onHoverChanged(false); 8992 } 8993 } 8994 } 8995 8996 /** 8997 * Implement this method to handle hover state changes. 8998 * <p> 8999 * This method is called whenever the hover state changes as a result of a 9000 * call to {@link #setHovered}. 9001 * </p> 9002 * 9003 * @param hovered The current hover state, as returned by {@link #isHovered}. 9004 * 9005 * @see #isHovered 9006 * @see #setHovered 9007 */ 9008 public void onHoverChanged(boolean hovered) { 9009 } 9010 9011 /** 9012 * Implement this method to handle touch screen motion events. 9013 * <p> 9014 * If this method is used to detect click actions, it is recommended that 9015 * the actions be performed by implementing and calling 9016 * {@link #performClick()}. This will ensure consistent system behavior, 9017 * including: 9018 * <ul> 9019 * <li>obeying click sound preferences 9020 * <li>dispatching OnClickListener calls 9021 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9022 * accessibility features are enabled 9023 * </ul> 9024 * 9025 * @param event The motion event. 9026 * @return True if the event was handled, false otherwise. 9027 */ 9028 public boolean onTouchEvent(MotionEvent event) { 9029 final float x = event.getX(); 9030 final float y = event.getY(); 9031 final int viewFlags = mViewFlags; 9032 9033 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9034 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9035 setPressed(false); 9036 } 9037 // A disabled view that is clickable still consumes the touch 9038 // events, it just doesn't respond to them. 9039 return (((viewFlags & CLICKABLE) == CLICKABLE || 9040 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9041 } 9042 9043 if (mTouchDelegate != null) { 9044 if (mTouchDelegate.onTouchEvent(event)) { 9045 return true; 9046 } 9047 } 9048 9049 if (((viewFlags & CLICKABLE) == CLICKABLE || 9050 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9051 switch (event.getAction()) { 9052 case MotionEvent.ACTION_UP: 9053 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9054 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9055 // take focus if we don't have it already and we should in 9056 // touch mode. 9057 boolean focusTaken = false; 9058 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9059 focusTaken = requestFocus(); 9060 } 9061 9062 if (prepressed) { 9063 // The button is being released before we actually 9064 // showed it as pressed. Make it show the pressed 9065 // state now (before scheduling the click) to ensure 9066 // the user sees it. 9067 setPressed(true, x, y); 9068 } 9069 9070 if (!mHasPerformedLongPress) { 9071 // This is a tap, so remove the longpress check 9072 removeLongPressCallback(); 9073 9074 // Only perform take click actions if we were in the pressed state 9075 if (!focusTaken) { 9076 // Use a Runnable and post this rather than calling 9077 // performClick directly. This lets other visual state 9078 // of the view update before click actions start. 9079 if (mPerformClick == null) { 9080 mPerformClick = new PerformClick(); 9081 } 9082 if (!post(mPerformClick)) { 9083 performClick(); 9084 } 9085 } 9086 } 9087 9088 if (mUnsetPressedState == null) { 9089 mUnsetPressedState = new UnsetPressedState(); 9090 } 9091 9092 if (prepressed) { 9093 postDelayed(mUnsetPressedState, 9094 ViewConfiguration.getPressedStateDuration()); 9095 } else if (!post(mUnsetPressedState)) { 9096 // If the post failed, unpress right now 9097 mUnsetPressedState.run(); 9098 } 9099 9100 removeTapCallback(); 9101 } 9102 break; 9103 9104 case MotionEvent.ACTION_DOWN: 9105 mHasPerformedLongPress = false; 9106 9107 if (performButtonActionOnTouchDown(event)) { 9108 break; 9109 } 9110 9111 // Walk up the hierarchy to determine if we're inside a scrolling container. 9112 boolean isInScrollingContainer = isInScrollingContainer(); 9113 9114 // For views inside a scrolling container, delay the pressed feedback for 9115 // a short period in case this is a scroll. 9116 if (isInScrollingContainer) { 9117 mPrivateFlags |= PFLAG_PREPRESSED; 9118 if (mPendingCheckForTap == null) { 9119 mPendingCheckForTap = new CheckForTap(); 9120 } 9121 mPendingCheckForTap.x = event.getX(); 9122 mPendingCheckForTap.y = event.getY(); 9123 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9124 } else { 9125 // Not inside a scrolling container, so show the feedback right away 9126 setPressed(true, x, y); 9127 checkForLongClick(0); 9128 } 9129 break; 9130 9131 case MotionEvent.ACTION_CANCEL: 9132 setPressed(false); 9133 removeTapCallback(); 9134 removeLongPressCallback(); 9135 break; 9136 9137 case MotionEvent.ACTION_MOVE: 9138 drawableHotspotChanged(x, y); 9139 9140 // Be lenient about moving outside of buttons 9141 if (!pointInView(x, y, mTouchSlop)) { 9142 // Outside button 9143 removeTapCallback(); 9144 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9145 // Remove any future long press/tap checks 9146 removeLongPressCallback(); 9147 9148 setPressed(false); 9149 } 9150 } 9151 break; 9152 } 9153 9154 return true; 9155 } 9156 9157 return false; 9158 } 9159 9160 /** 9161 * @hide 9162 */ 9163 public boolean isInScrollingContainer() { 9164 ViewParent p = getParent(); 9165 while (p != null && p instanceof ViewGroup) { 9166 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9167 return true; 9168 } 9169 p = p.getParent(); 9170 } 9171 return false; 9172 } 9173 9174 /** 9175 * Remove the longpress detection timer. 9176 */ 9177 private void removeLongPressCallback() { 9178 if (mPendingCheckForLongPress != null) { 9179 removeCallbacks(mPendingCheckForLongPress); 9180 } 9181 } 9182 9183 /** 9184 * Remove the pending click action 9185 */ 9186 private void removePerformClickCallback() { 9187 if (mPerformClick != null) { 9188 removeCallbacks(mPerformClick); 9189 } 9190 } 9191 9192 /** 9193 * Remove the prepress detection timer. 9194 */ 9195 private void removeUnsetPressCallback() { 9196 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9197 setPressed(false); 9198 removeCallbacks(mUnsetPressedState); 9199 } 9200 } 9201 9202 /** 9203 * Remove the tap detection timer. 9204 */ 9205 private void removeTapCallback() { 9206 if (mPendingCheckForTap != null) { 9207 mPrivateFlags &= ~PFLAG_PREPRESSED; 9208 removeCallbacks(mPendingCheckForTap); 9209 } 9210 } 9211 9212 /** 9213 * Cancels a pending long press. Your subclass can use this if you 9214 * want the context menu to come up if the user presses and holds 9215 * at the same place, but you don't want it to come up if they press 9216 * and then move around enough to cause scrolling. 9217 */ 9218 public void cancelLongPress() { 9219 removeLongPressCallback(); 9220 9221 /* 9222 * The prepressed state handled by the tap callback is a display 9223 * construct, but the tap callback will post a long press callback 9224 * less its own timeout. Remove it here. 9225 */ 9226 removeTapCallback(); 9227 } 9228 9229 /** 9230 * Remove the pending callback for sending a 9231 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9232 */ 9233 private void removeSendViewScrolledAccessibilityEventCallback() { 9234 if (mSendViewScrolledAccessibilityEvent != null) { 9235 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9236 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9237 } 9238 } 9239 9240 /** 9241 * Sets the TouchDelegate for this View. 9242 */ 9243 public void setTouchDelegate(TouchDelegate delegate) { 9244 mTouchDelegate = delegate; 9245 } 9246 9247 /** 9248 * Gets the TouchDelegate for this View. 9249 */ 9250 public TouchDelegate getTouchDelegate() { 9251 return mTouchDelegate; 9252 } 9253 9254 /** 9255 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9256 * 9257 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9258 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9259 * available. This method should only be called for touch events. 9260 * 9261 * <p class="note">This api is not intended for most applications. Buffered dispatch 9262 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9263 * streams will not improve your input latency. Side effects include: increased latency, 9264 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9265 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9266 * you.</p> 9267 */ 9268 public final void requestUnbufferedDispatch(MotionEvent event) { 9269 final int action = event.getAction(); 9270 if (mAttachInfo == null 9271 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9272 || !event.isTouchEvent()) { 9273 return; 9274 } 9275 mAttachInfo.mUnbufferedDispatchRequested = true; 9276 } 9277 9278 /** 9279 * Set flags controlling behavior of this view. 9280 * 9281 * @param flags Constant indicating the value which should be set 9282 * @param mask Constant indicating the bit range that should be changed 9283 */ 9284 void setFlags(int flags, int mask) { 9285 final boolean accessibilityEnabled = 9286 AccessibilityManager.getInstance(mContext).isEnabled(); 9287 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9288 9289 int old = mViewFlags; 9290 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9291 9292 int changed = mViewFlags ^ old; 9293 if (changed == 0) { 9294 return; 9295 } 9296 int privateFlags = mPrivateFlags; 9297 9298 /* Check if the FOCUSABLE bit has changed */ 9299 if (((changed & FOCUSABLE_MASK) != 0) && 9300 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9301 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9302 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9303 /* Give up focus if we are no longer focusable */ 9304 clearFocus(); 9305 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9306 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9307 /* 9308 * Tell the view system that we are now available to take focus 9309 * if no one else already has it. 9310 */ 9311 if (mParent != null) mParent.focusableViewAvailable(this); 9312 } 9313 } 9314 9315 final int newVisibility = flags & VISIBILITY_MASK; 9316 if (newVisibility == VISIBLE) { 9317 if ((changed & VISIBILITY_MASK) != 0) { 9318 /* 9319 * If this view is becoming visible, invalidate it in case it changed while 9320 * it was not visible. Marking it drawn ensures that the invalidation will 9321 * go through. 9322 */ 9323 mPrivateFlags |= PFLAG_DRAWN; 9324 invalidate(true); 9325 9326 needGlobalAttributesUpdate(true); 9327 9328 // a view becoming visible is worth notifying the parent 9329 // about in case nothing has focus. even if this specific view 9330 // isn't focusable, it may contain something that is, so let 9331 // the root view try to give this focus if nothing else does. 9332 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9333 mParent.focusableViewAvailable(this); 9334 } 9335 } 9336 } 9337 9338 /* Check if the GONE bit has changed */ 9339 if ((changed & GONE) != 0) { 9340 needGlobalAttributesUpdate(false); 9341 requestLayout(); 9342 9343 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9344 if (hasFocus()) clearFocus(); 9345 clearAccessibilityFocus(); 9346 destroyDrawingCache(); 9347 if (mParent instanceof View) { 9348 // GONE views noop invalidation, so invalidate the parent 9349 ((View) mParent).invalidate(true); 9350 } 9351 // Mark the view drawn to ensure that it gets invalidated properly the next 9352 // time it is visible and gets invalidated 9353 mPrivateFlags |= PFLAG_DRAWN; 9354 } 9355 if (mAttachInfo != null) { 9356 mAttachInfo.mViewVisibilityChanged = true; 9357 } 9358 } 9359 9360 /* Check if the VISIBLE bit has changed */ 9361 if ((changed & INVISIBLE) != 0) { 9362 needGlobalAttributesUpdate(false); 9363 /* 9364 * If this view is becoming invisible, set the DRAWN flag so that 9365 * the next invalidate() will not be skipped. 9366 */ 9367 mPrivateFlags |= PFLAG_DRAWN; 9368 9369 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9370 // root view becoming invisible shouldn't clear focus and accessibility focus 9371 if (getRootView() != this) { 9372 if (hasFocus()) clearFocus(); 9373 clearAccessibilityFocus(); 9374 } 9375 } 9376 if (mAttachInfo != null) { 9377 mAttachInfo.mViewVisibilityChanged = true; 9378 } 9379 } 9380 9381 if ((changed & VISIBILITY_MASK) != 0) { 9382 // If the view is invisible, cleanup its display list to free up resources 9383 if (newVisibility != VISIBLE && mAttachInfo != null) { 9384 cleanupDraw(); 9385 } 9386 9387 if (mParent instanceof ViewGroup) { 9388 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9389 (changed & VISIBILITY_MASK), newVisibility); 9390 ((View) mParent).invalidate(true); 9391 } else if (mParent != null) { 9392 mParent.invalidateChild(this, null); 9393 } 9394 dispatchVisibilityChanged(this, newVisibility); 9395 9396 notifySubtreeAccessibilityStateChangedIfNeeded(); 9397 } 9398 9399 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9400 destroyDrawingCache(); 9401 } 9402 9403 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9404 destroyDrawingCache(); 9405 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9406 invalidateParentCaches(); 9407 } 9408 9409 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9410 destroyDrawingCache(); 9411 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9412 } 9413 9414 if ((changed & DRAW_MASK) != 0) { 9415 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9416 if (mBackground != null) { 9417 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9418 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9419 } else { 9420 mPrivateFlags |= PFLAG_SKIP_DRAW; 9421 } 9422 } else { 9423 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9424 } 9425 requestLayout(); 9426 invalidate(true); 9427 } 9428 9429 if ((changed & KEEP_SCREEN_ON) != 0) { 9430 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9431 mParent.recomputeViewAttributes(this); 9432 } 9433 } 9434 9435 if (accessibilityEnabled) { 9436 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9437 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9438 if (oldIncludeForAccessibility != includeForAccessibility()) { 9439 notifySubtreeAccessibilityStateChangedIfNeeded(); 9440 } else { 9441 notifyViewAccessibilityStateChangedIfNeeded( 9442 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9443 } 9444 } else if ((changed & ENABLED_MASK) != 0) { 9445 notifyViewAccessibilityStateChangedIfNeeded( 9446 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9447 } 9448 } 9449 } 9450 9451 /** 9452 * Change the view's z order in the tree, so it's on top of other sibling 9453 * views. This ordering change may affect layout, if the parent container 9454 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9455 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9456 * method should be followed by calls to {@link #requestLayout()} and 9457 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9458 * with the new child ordering. 9459 * 9460 * @see ViewGroup#bringChildToFront(View) 9461 */ 9462 public void bringToFront() { 9463 if (mParent != null) { 9464 mParent.bringChildToFront(this); 9465 } 9466 } 9467 9468 /** 9469 * This is called in response to an internal scroll in this view (i.e., the 9470 * view scrolled its own contents). This is typically as a result of 9471 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9472 * called. 9473 * 9474 * @param l Current horizontal scroll origin. 9475 * @param t Current vertical scroll origin. 9476 * @param oldl Previous horizontal scroll origin. 9477 * @param oldt Previous vertical scroll origin. 9478 */ 9479 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9480 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9481 postSendViewScrolledAccessibilityEventCallback(); 9482 } 9483 9484 mBackgroundSizeChanged = true; 9485 9486 final AttachInfo ai = mAttachInfo; 9487 if (ai != null) { 9488 ai.mViewScrollChanged = true; 9489 } 9490 } 9491 9492 /** 9493 * Interface definition for a callback to be invoked when the layout bounds of a view 9494 * changes due to layout processing. 9495 */ 9496 public interface OnLayoutChangeListener { 9497 /** 9498 * Called when the layout bounds of a view changes due to layout processing. 9499 * 9500 * @param v The view whose bounds have changed. 9501 * @param left The new value of the view's left property. 9502 * @param top The new value of the view's top property. 9503 * @param right The new value of the view's right property. 9504 * @param bottom The new value of the view's bottom property. 9505 * @param oldLeft The previous value of the view's left property. 9506 * @param oldTop The previous value of the view's top property. 9507 * @param oldRight The previous value of the view's right property. 9508 * @param oldBottom The previous value of the view's bottom property. 9509 */ 9510 void onLayoutChange(View v, int left, int top, int right, int bottom, 9511 int oldLeft, int oldTop, int oldRight, int oldBottom); 9512 } 9513 9514 /** 9515 * This is called during layout when the size of this view has changed. If 9516 * you were just added to the view hierarchy, you're called with the old 9517 * values of 0. 9518 * 9519 * @param w Current width of this view. 9520 * @param h Current height of this view. 9521 * @param oldw Old width of this view. 9522 * @param oldh Old height of this view. 9523 */ 9524 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9525 } 9526 9527 /** 9528 * Called by draw to draw the child views. This may be overridden 9529 * by derived classes to gain control just before its children are drawn 9530 * (but after its own view has been drawn). 9531 * @param canvas the canvas on which to draw the view 9532 */ 9533 protected void dispatchDraw(Canvas canvas) { 9534 9535 } 9536 9537 /** 9538 * Gets the parent of this view. Note that the parent is a 9539 * ViewParent and not necessarily a View. 9540 * 9541 * @return Parent of this view. 9542 */ 9543 public final ViewParent getParent() { 9544 return mParent; 9545 } 9546 9547 /** 9548 * Set the horizontal scrolled position of your view. This will cause a call to 9549 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9550 * invalidated. 9551 * @param value the x position to scroll to 9552 */ 9553 public void setScrollX(int value) { 9554 scrollTo(value, mScrollY); 9555 } 9556 9557 /** 9558 * Set the vertical scrolled position of your view. This will cause a call to 9559 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9560 * invalidated. 9561 * @param value the y position to scroll to 9562 */ 9563 public void setScrollY(int value) { 9564 scrollTo(mScrollX, value); 9565 } 9566 9567 /** 9568 * Return the scrolled left position of this view. This is the left edge of 9569 * the displayed part of your view. You do not need to draw any pixels 9570 * farther left, since those are outside of the frame of your view on 9571 * screen. 9572 * 9573 * @return The left edge of the displayed part of your view, in pixels. 9574 */ 9575 public final int getScrollX() { 9576 return mScrollX; 9577 } 9578 9579 /** 9580 * Return the scrolled top position of this view. This is the top edge of 9581 * the displayed part of your view. You do not need to draw any pixels above 9582 * it, since those are outside of the frame of your view on screen. 9583 * 9584 * @return The top edge of the displayed part of your view, in pixels. 9585 */ 9586 public final int getScrollY() { 9587 return mScrollY; 9588 } 9589 9590 /** 9591 * Return the width of the your view. 9592 * 9593 * @return The width of your view, in pixels. 9594 */ 9595 @ViewDebug.ExportedProperty(category = "layout") 9596 public final int getWidth() { 9597 return mRight - mLeft; 9598 } 9599 9600 /** 9601 * Return the height of your view. 9602 * 9603 * @return The height of your view, in pixels. 9604 */ 9605 @ViewDebug.ExportedProperty(category = "layout") 9606 public final int getHeight() { 9607 return mBottom - mTop; 9608 } 9609 9610 /** 9611 * Return the visible drawing bounds of your view. Fills in the output 9612 * rectangle with the values from getScrollX(), getScrollY(), 9613 * getWidth(), and getHeight(). These bounds do not account for any 9614 * transformation properties currently set on the view, such as 9615 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9616 * 9617 * @param outRect The (scrolled) drawing bounds of the view. 9618 */ 9619 public void getDrawingRect(Rect outRect) { 9620 outRect.left = mScrollX; 9621 outRect.top = mScrollY; 9622 outRect.right = mScrollX + (mRight - mLeft); 9623 outRect.bottom = mScrollY + (mBottom - mTop); 9624 } 9625 9626 /** 9627 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9628 * raw width component (that is the result is masked by 9629 * {@link #MEASURED_SIZE_MASK}). 9630 * 9631 * @return The raw measured width of this view. 9632 */ 9633 public final int getMeasuredWidth() { 9634 return mMeasuredWidth & MEASURED_SIZE_MASK; 9635 } 9636 9637 /** 9638 * Return the full width measurement information for this view as computed 9639 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9640 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9641 * This should be used during measurement and layout calculations only. Use 9642 * {@link #getWidth()} to see how wide a view is after layout. 9643 * 9644 * @return The measured width of this view as a bit mask. 9645 */ 9646 public final int getMeasuredWidthAndState() { 9647 return mMeasuredWidth; 9648 } 9649 9650 /** 9651 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9652 * raw width component (that is the result is masked by 9653 * {@link #MEASURED_SIZE_MASK}). 9654 * 9655 * @return The raw measured height of this view. 9656 */ 9657 public final int getMeasuredHeight() { 9658 return mMeasuredHeight & MEASURED_SIZE_MASK; 9659 } 9660 9661 /** 9662 * Return the full height measurement information for this view as computed 9663 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9664 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9665 * This should be used during measurement and layout calculations only. Use 9666 * {@link #getHeight()} to see how wide a view is after layout. 9667 * 9668 * @return The measured width of this view as a bit mask. 9669 */ 9670 public final int getMeasuredHeightAndState() { 9671 return mMeasuredHeight; 9672 } 9673 9674 /** 9675 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9676 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9677 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9678 * and the height component is at the shifted bits 9679 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9680 */ 9681 public final int getMeasuredState() { 9682 return (mMeasuredWidth&MEASURED_STATE_MASK) 9683 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9684 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9685 } 9686 9687 /** 9688 * The transform matrix of this view, which is calculated based on the current 9689 * rotation, scale, and pivot properties. 9690 * 9691 * @see #getRotation() 9692 * @see #getScaleX() 9693 * @see #getScaleY() 9694 * @see #getPivotX() 9695 * @see #getPivotY() 9696 * @return The current transform matrix for the view 9697 */ 9698 public Matrix getMatrix() { 9699 ensureTransformationInfo(); 9700 final Matrix matrix = mTransformationInfo.mMatrix; 9701 mRenderNode.getMatrix(matrix); 9702 return matrix; 9703 } 9704 9705 /** 9706 * Returns true if the transform matrix is the identity matrix. 9707 * Recomputes the matrix if necessary. 9708 * 9709 * @return True if the transform matrix is the identity matrix, false otherwise. 9710 */ 9711 final boolean hasIdentityMatrix() { 9712 return mRenderNode.hasIdentityMatrix(); 9713 } 9714 9715 void ensureTransformationInfo() { 9716 if (mTransformationInfo == null) { 9717 mTransformationInfo = new TransformationInfo(); 9718 } 9719 } 9720 9721 /** 9722 * Utility method to retrieve the inverse of the current mMatrix property. 9723 * We cache the matrix to avoid recalculating it when transform properties 9724 * have not changed. 9725 * 9726 * @return The inverse of the current matrix of this view. 9727 */ 9728 final Matrix getInverseMatrix() { 9729 ensureTransformationInfo(); 9730 if (mTransformationInfo.mInverseMatrix == null) { 9731 mTransformationInfo.mInverseMatrix = new Matrix(); 9732 } 9733 final Matrix matrix = mTransformationInfo.mInverseMatrix; 9734 mRenderNode.getInverseMatrix(matrix); 9735 return matrix; 9736 } 9737 9738 /** 9739 * Gets the distance along the Z axis from the camera to this view. 9740 * 9741 * @see #setCameraDistance(float) 9742 * 9743 * @return The distance along the Z axis. 9744 */ 9745 public float getCameraDistance() { 9746 final float dpi = mResources.getDisplayMetrics().densityDpi; 9747 return -(mRenderNode.getCameraDistance() * dpi); 9748 } 9749 9750 /** 9751 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9752 * views are drawn) from the camera to this view. The camera's distance 9753 * affects 3D transformations, for instance rotations around the X and Y 9754 * axis. If the rotationX or rotationY properties are changed and this view is 9755 * large (more than half the size of the screen), it is recommended to always 9756 * use a camera distance that's greater than the height (X axis rotation) or 9757 * the width (Y axis rotation) of this view.</p> 9758 * 9759 * <p>The distance of the camera from the view plane can have an affect on the 9760 * perspective distortion of the view when it is rotated around the x or y axis. 9761 * For example, a large distance will result in a large viewing angle, and there 9762 * will not be much perspective distortion of the view as it rotates. A short 9763 * distance may cause much more perspective distortion upon rotation, and can 9764 * also result in some drawing artifacts if the rotated view ends up partially 9765 * behind the camera (which is why the recommendation is to use a distance at 9766 * least as far as the size of the view, if the view is to be rotated.)</p> 9767 * 9768 * <p>The distance is expressed in "depth pixels." The default distance depends 9769 * on the screen density. For instance, on a medium density display, the 9770 * default distance is 1280. On a high density display, the default distance 9771 * is 1920.</p> 9772 * 9773 * <p>If you want to specify a distance that leads to visually consistent 9774 * results across various densities, use the following formula:</p> 9775 * <pre> 9776 * float scale = context.getResources().getDisplayMetrics().density; 9777 * view.setCameraDistance(distance * scale); 9778 * </pre> 9779 * 9780 * <p>The density scale factor of a high density display is 1.5, 9781 * and 1920 = 1280 * 1.5.</p> 9782 * 9783 * @param distance The distance in "depth pixels", if negative the opposite 9784 * value is used 9785 * 9786 * @see #setRotationX(float) 9787 * @see #setRotationY(float) 9788 */ 9789 public void setCameraDistance(float distance) { 9790 final float dpi = mResources.getDisplayMetrics().densityDpi; 9791 9792 invalidateViewProperty(true, false); 9793 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 9794 invalidateViewProperty(false, false); 9795 9796 invalidateParentIfNeededAndWasQuickRejected(); 9797 } 9798 9799 /** 9800 * The degrees that the view is rotated around the pivot point. 9801 * 9802 * @see #setRotation(float) 9803 * @see #getPivotX() 9804 * @see #getPivotY() 9805 * 9806 * @return The degrees of rotation. 9807 */ 9808 @ViewDebug.ExportedProperty(category = "drawing") 9809 public float getRotation() { 9810 return mRenderNode.getRotation(); 9811 } 9812 9813 /** 9814 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9815 * result in clockwise rotation. 9816 * 9817 * @param rotation The degrees of rotation. 9818 * 9819 * @see #getRotation() 9820 * @see #getPivotX() 9821 * @see #getPivotY() 9822 * @see #setRotationX(float) 9823 * @see #setRotationY(float) 9824 * 9825 * @attr ref android.R.styleable#View_rotation 9826 */ 9827 public void setRotation(float rotation) { 9828 if (rotation != getRotation()) { 9829 // Double-invalidation is necessary to capture view's old and new areas 9830 invalidateViewProperty(true, false); 9831 mRenderNode.setRotation(rotation); 9832 invalidateViewProperty(false, true); 9833 9834 invalidateParentIfNeededAndWasQuickRejected(); 9835 notifySubtreeAccessibilityStateChangedIfNeeded(); 9836 } 9837 } 9838 9839 /** 9840 * The degrees that the view is rotated around the vertical axis through the pivot point. 9841 * 9842 * @see #getPivotX() 9843 * @see #getPivotY() 9844 * @see #setRotationY(float) 9845 * 9846 * @return The degrees of Y rotation. 9847 */ 9848 @ViewDebug.ExportedProperty(category = "drawing") 9849 public float getRotationY() { 9850 return mRenderNode.getRotationY(); 9851 } 9852 9853 /** 9854 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9855 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9856 * down the y axis. 9857 * 9858 * When rotating large views, it is recommended to adjust the camera distance 9859 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9860 * 9861 * @param rotationY The degrees of Y rotation. 9862 * 9863 * @see #getRotationY() 9864 * @see #getPivotX() 9865 * @see #getPivotY() 9866 * @see #setRotation(float) 9867 * @see #setRotationX(float) 9868 * @see #setCameraDistance(float) 9869 * 9870 * @attr ref android.R.styleable#View_rotationY 9871 */ 9872 public void setRotationY(float rotationY) { 9873 if (rotationY != getRotationY()) { 9874 invalidateViewProperty(true, false); 9875 mRenderNode.setRotationY(rotationY); 9876 invalidateViewProperty(false, true); 9877 9878 invalidateParentIfNeededAndWasQuickRejected(); 9879 notifySubtreeAccessibilityStateChangedIfNeeded(); 9880 } 9881 } 9882 9883 /** 9884 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9885 * 9886 * @see #getPivotX() 9887 * @see #getPivotY() 9888 * @see #setRotationX(float) 9889 * 9890 * @return The degrees of X rotation. 9891 */ 9892 @ViewDebug.ExportedProperty(category = "drawing") 9893 public float getRotationX() { 9894 return mRenderNode.getRotationX(); 9895 } 9896 9897 /** 9898 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9899 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9900 * x axis. 9901 * 9902 * When rotating large views, it is recommended to adjust the camera distance 9903 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9904 * 9905 * @param rotationX The degrees of X rotation. 9906 * 9907 * @see #getRotationX() 9908 * @see #getPivotX() 9909 * @see #getPivotY() 9910 * @see #setRotation(float) 9911 * @see #setRotationY(float) 9912 * @see #setCameraDistance(float) 9913 * 9914 * @attr ref android.R.styleable#View_rotationX 9915 */ 9916 public void setRotationX(float rotationX) { 9917 if (rotationX != getRotationX()) { 9918 invalidateViewProperty(true, false); 9919 mRenderNode.setRotationX(rotationX); 9920 invalidateViewProperty(false, true); 9921 9922 invalidateParentIfNeededAndWasQuickRejected(); 9923 notifySubtreeAccessibilityStateChangedIfNeeded(); 9924 } 9925 } 9926 9927 /** 9928 * The amount that the view is scaled in x around the pivot point, as a proportion of 9929 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9930 * 9931 * <p>By default, this is 1.0f. 9932 * 9933 * @see #getPivotX() 9934 * @see #getPivotY() 9935 * @return The scaling factor. 9936 */ 9937 @ViewDebug.ExportedProperty(category = "drawing") 9938 public float getScaleX() { 9939 return mRenderNode.getScaleX(); 9940 } 9941 9942 /** 9943 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9944 * the view's unscaled width. A value of 1 means that no scaling is applied. 9945 * 9946 * @param scaleX The scaling factor. 9947 * @see #getPivotX() 9948 * @see #getPivotY() 9949 * 9950 * @attr ref android.R.styleable#View_scaleX 9951 */ 9952 public void setScaleX(float scaleX) { 9953 if (scaleX != getScaleX()) { 9954 invalidateViewProperty(true, false); 9955 mRenderNode.setScaleX(scaleX); 9956 invalidateViewProperty(false, true); 9957 9958 invalidateParentIfNeededAndWasQuickRejected(); 9959 notifySubtreeAccessibilityStateChangedIfNeeded(); 9960 } 9961 } 9962 9963 /** 9964 * The amount that the view is scaled in y around the pivot point, as a proportion of 9965 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9966 * 9967 * <p>By default, this is 1.0f. 9968 * 9969 * @see #getPivotX() 9970 * @see #getPivotY() 9971 * @return The scaling factor. 9972 */ 9973 @ViewDebug.ExportedProperty(category = "drawing") 9974 public float getScaleY() { 9975 return mRenderNode.getScaleY(); 9976 } 9977 9978 /** 9979 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9980 * the view's unscaled width. A value of 1 means that no scaling is applied. 9981 * 9982 * @param scaleY The scaling factor. 9983 * @see #getPivotX() 9984 * @see #getPivotY() 9985 * 9986 * @attr ref android.R.styleable#View_scaleY 9987 */ 9988 public void setScaleY(float scaleY) { 9989 if (scaleY != getScaleY()) { 9990 invalidateViewProperty(true, false); 9991 mRenderNode.setScaleY(scaleY); 9992 invalidateViewProperty(false, true); 9993 9994 invalidateParentIfNeededAndWasQuickRejected(); 9995 notifySubtreeAccessibilityStateChangedIfNeeded(); 9996 } 9997 } 9998 9999 /** 10000 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10001 * and {@link #setScaleX(float) scaled}. 10002 * 10003 * @see #getRotation() 10004 * @see #getScaleX() 10005 * @see #getScaleY() 10006 * @see #getPivotY() 10007 * @return The x location of the pivot point. 10008 * 10009 * @attr ref android.R.styleable#View_transformPivotX 10010 */ 10011 @ViewDebug.ExportedProperty(category = "drawing") 10012 public float getPivotX() { 10013 return mRenderNode.getPivotX(); 10014 } 10015 10016 /** 10017 * Sets the x location of the point around which the view is 10018 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10019 * By default, the pivot point is centered on the object. 10020 * Setting this property disables this behavior and causes the view to use only the 10021 * explicitly set pivotX and pivotY values. 10022 * 10023 * @param pivotX The x location of the pivot point. 10024 * @see #getRotation() 10025 * @see #getScaleX() 10026 * @see #getScaleY() 10027 * @see #getPivotY() 10028 * 10029 * @attr ref android.R.styleable#View_transformPivotX 10030 */ 10031 public void setPivotX(float pivotX) { 10032 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10033 invalidateViewProperty(true, false); 10034 mRenderNode.setPivotX(pivotX); 10035 invalidateViewProperty(false, true); 10036 10037 invalidateParentIfNeededAndWasQuickRejected(); 10038 } 10039 } 10040 10041 /** 10042 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10043 * and {@link #setScaleY(float) scaled}. 10044 * 10045 * @see #getRotation() 10046 * @see #getScaleX() 10047 * @see #getScaleY() 10048 * @see #getPivotY() 10049 * @return The y location of the pivot point. 10050 * 10051 * @attr ref android.R.styleable#View_transformPivotY 10052 */ 10053 @ViewDebug.ExportedProperty(category = "drawing") 10054 public float getPivotY() { 10055 return mRenderNode.getPivotY(); 10056 } 10057 10058 /** 10059 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10060 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10061 * Setting this property disables this behavior and causes the view to use only the 10062 * explicitly set pivotX and pivotY values. 10063 * 10064 * @param pivotY The y location of the pivot point. 10065 * @see #getRotation() 10066 * @see #getScaleX() 10067 * @see #getScaleY() 10068 * @see #getPivotY() 10069 * 10070 * @attr ref android.R.styleable#View_transformPivotY 10071 */ 10072 public void setPivotY(float pivotY) { 10073 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10074 invalidateViewProperty(true, false); 10075 mRenderNode.setPivotY(pivotY); 10076 invalidateViewProperty(false, true); 10077 10078 invalidateParentIfNeededAndWasQuickRejected(); 10079 } 10080 } 10081 10082 /** 10083 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10084 * completely transparent and 1 means the view is completely opaque. 10085 * 10086 * <p>By default this is 1.0f. 10087 * @return The opacity of the view. 10088 */ 10089 @ViewDebug.ExportedProperty(category = "drawing") 10090 public float getAlpha() { 10091 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10092 } 10093 10094 /** 10095 * Returns whether this View has content which overlaps. 10096 * 10097 * <p>This function, intended to be overridden by specific View types, is an optimization when 10098 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10099 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10100 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10101 * directly. An example of overlapping rendering is a TextView with a background image, such as 10102 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10103 * ImageView with only the foreground image. The default implementation returns true; subclasses 10104 * should override if they have cases which can be optimized.</p> 10105 * 10106 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10107 * necessitates that a View return true if it uses the methods internally without passing the 10108 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10109 * 10110 * @return true if the content in this view might overlap, false otherwise. 10111 */ 10112 public boolean hasOverlappingRendering() { 10113 return true; 10114 } 10115 10116 /** 10117 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10118 * completely transparent and 1 means the view is completely opaque.</p> 10119 * 10120 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10121 * performance implications, especially for large views. It is best to use the alpha property 10122 * sparingly and transiently, as in the case of fading animations.</p> 10123 * 10124 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10125 * strongly recommended for performance reasons to either override 10126 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10127 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10128 * 10129 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10130 * responsible for applying the opacity itself.</p> 10131 * 10132 * <p>Note that if the view is backed by a 10133 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10134 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10135 * 1.0 will supercede the alpha of the layer paint.</p> 10136 * 10137 * @param alpha The opacity of the view. 10138 * 10139 * @see #hasOverlappingRendering() 10140 * @see #setLayerType(int, android.graphics.Paint) 10141 * 10142 * @attr ref android.R.styleable#View_alpha 10143 */ 10144 public void setAlpha(float alpha) { 10145 ensureTransformationInfo(); 10146 if (mTransformationInfo.mAlpha != alpha) { 10147 mTransformationInfo.mAlpha = alpha; 10148 if (onSetAlpha((int) (alpha * 255))) { 10149 mPrivateFlags |= PFLAG_ALPHA_SET; 10150 // subclass is handling alpha - don't optimize rendering cache invalidation 10151 invalidateParentCaches(); 10152 invalidate(true); 10153 } else { 10154 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10155 invalidateViewProperty(true, false); 10156 mRenderNode.setAlpha(getFinalAlpha()); 10157 notifyViewAccessibilityStateChangedIfNeeded( 10158 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10159 } 10160 } 10161 } 10162 10163 /** 10164 * Faster version of setAlpha() which performs the same steps except there are 10165 * no calls to invalidate(). The caller of this function should perform proper invalidation 10166 * on the parent and this object. The return value indicates whether the subclass handles 10167 * alpha (the return value for onSetAlpha()). 10168 * 10169 * @param alpha The new value for the alpha property 10170 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10171 * the new value for the alpha property is different from the old value 10172 */ 10173 boolean setAlphaNoInvalidation(float alpha) { 10174 ensureTransformationInfo(); 10175 if (mTransformationInfo.mAlpha != alpha) { 10176 mTransformationInfo.mAlpha = alpha; 10177 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10178 if (subclassHandlesAlpha) { 10179 mPrivateFlags |= PFLAG_ALPHA_SET; 10180 return true; 10181 } else { 10182 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10183 mRenderNode.setAlpha(getFinalAlpha()); 10184 } 10185 } 10186 return false; 10187 } 10188 10189 /** 10190 * This property is hidden and intended only for use by the Fade transition, which 10191 * animates it to produce a visual translucency that does not side-effect (or get 10192 * affected by) the real alpha property. This value is composited with the other 10193 * alpha value (and the AlphaAnimation value, when that is present) to produce 10194 * a final visual translucency result, which is what is passed into the DisplayList. 10195 * 10196 * @hide 10197 */ 10198 public void setTransitionAlpha(float alpha) { 10199 ensureTransformationInfo(); 10200 if (mTransformationInfo.mTransitionAlpha != alpha) { 10201 mTransformationInfo.mTransitionAlpha = alpha; 10202 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10203 invalidateViewProperty(true, false); 10204 mRenderNode.setAlpha(getFinalAlpha()); 10205 } 10206 } 10207 10208 /** 10209 * Calculates the visual alpha of this view, which is a combination of the actual 10210 * alpha value and the transitionAlpha value (if set). 10211 */ 10212 private float getFinalAlpha() { 10213 if (mTransformationInfo != null) { 10214 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10215 } 10216 return 1; 10217 } 10218 10219 /** 10220 * This property is hidden and intended only for use by the Fade transition, which 10221 * animates it to produce a visual translucency that does not side-effect (or get 10222 * affected by) the real alpha property. This value is composited with the other 10223 * alpha value (and the AlphaAnimation value, when that is present) to produce 10224 * a final visual translucency result, which is what is passed into the DisplayList. 10225 * 10226 * @hide 10227 */ 10228 public float getTransitionAlpha() { 10229 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10230 } 10231 10232 /** 10233 * Top position of this view relative to its parent. 10234 * 10235 * @return The top of this view, in pixels. 10236 */ 10237 @ViewDebug.CapturedViewProperty 10238 public final int getTop() { 10239 return mTop; 10240 } 10241 10242 /** 10243 * Sets the top position of this view relative to its parent. This method is meant to be called 10244 * by the layout system and should not generally be called otherwise, because the property 10245 * may be changed at any time by the layout. 10246 * 10247 * @param top The top of this view, in pixels. 10248 */ 10249 public final void setTop(int top) { 10250 if (top != mTop) { 10251 final boolean matrixIsIdentity = hasIdentityMatrix(); 10252 if (matrixIsIdentity) { 10253 if (mAttachInfo != null) { 10254 int minTop; 10255 int yLoc; 10256 if (top < mTop) { 10257 minTop = top; 10258 yLoc = top - mTop; 10259 } else { 10260 minTop = mTop; 10261 yLoc = 0; 10262 } 10263 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10264 } 10265 } else { 10266 // Double-invalidation is necessary to capture view's old and new areas 10267 invalidate(true); 10268 } 10269 10270 int width = mRight - mLeft; 10271 int oldHeight = mBottom - mTop; 10272 10273 mTop = top; 10274 mRenderNode.setTop(mTop); 10275 10276 sizeChange(width, mBottom - mTop, width, oldHeight); 10277 10278 if (!matrixIsIdentity) { 10279 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10280 invalidate(true); 10281 } 10282 mBackgroundSizeChanged = true; 10283 invalidateParentIfNeeded(); 10284 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10285 // View was rejected last time it was drawn by its parent; this may have changed 10286 invalidateParentIfNeeded(); 10287 } 10288 } 10289 } 10290 10291 /** 10292 * Bottom position of this view relative to its parent. 10293 * 10294 * @return The bottom of this view, in pixels. 10295 */ 10296 @ViewDebug.CapturedViewProperty 10297 public final int getBottom() { 10298 return mBottom; 10299 } 10300 10301 /** 10302 * True if this view has changed since the last time being drawn. 10303 * 10304 * @return The dirty state of this view. 10305 */ 10306 public boolean isDirty() { 10307 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10308 } 10309 10310 /** 10311 * Sets the bottom position of this view relative to its parent. This method is meant to be 10312 * called by the layout system and should not generally be called otherwise, because the 10313 * property may be changed at any time by the layout. 10314 * 10315 * @param bottom The bottom of this view, in pixels. 10316 */ 10317 public final void setBottom(int bottom) { 10318 if (bottom != mBottom) { 10319 final boolean matrixIsIdentity = hasIdentityMatrix(); 10320 if (matrixIsIdentity) { 10321 if (mAttachInfo != null) { 10322 int maxBottom; 10323 if (bottom < mBottom) { 10324 maxBottom = mBottom; 10325 } else { 10326 maxBottom = bottom; 10327 } 10328 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10329 } 10330 } else { 10331 // Double-invalidation is necessary to capture view's old and new areas 10332 invalidate(true); 10333 } 10334 10335 int width = mRight - mLeft; 10336 int oldHeight = mBottom - mTop; 10337 10338 mBottom = bottom; 10339 mRenderNode.setBottom(mBottom); 10340 10341 sizeChange(width, mBottom - mTop, width, oldHeight); 10342 10343 if (!matrixIsIdentity) { 10344 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10345 invalidate(true); 10346 } 10347 mBackgroundSizeChanged = true; 10348 invalidateParentIfNeeded(); 10349 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10350 // View was rejected last time it was drawn by its parent; this may have changed 10351 invalidateParentIfNeeded(); 10352 } 10353 } 10354 } 10355 10356 /** 10357 * Left position of this view relative to its parent. 10358 * 10359 * @return The left edge of this view, in pixels. 10360 */ 10361 @ViewDebug.CapturedViewProperty 10362 public final int getLeft() { 10363 return mLeft; 10364 } 10365 10366 /** 10367 * Sets the left position of this view relative to its parent. This method is meant to be called 10368 * by the layout system and should not generally be called otherwise, because the property 10369 * may be changed at any time by the layout. 10370 * 10371 * @param left The left of this view, in pixels. 10372 */ 10373 public final void setLeft(int left) { 10374 if (left != mLeft) { 10375 final boolean matrixIsIdentity = hasIdentityMatrix(); 10376 if (matrixIsIdentity) { 10377 if (mAttachInfo != null) { 10378 int minLeft; 10379 int xLoc; 10380 if (left < mLeft) { 10381 minLeft = left; 10382 xLoc = left - mLeft; 10383 } else { 10384 minLeft = mLeft; 10385 xLoc = 0; 10386 } 10387 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10388 } 10389 } else { 10390 // Double-invalidation is necessary to capture view's old and new areas 10391 invalidate(true); 10392 } 10393 10394 int oldWidth = mRight - mLeft; 10395 int height = mBottom - mTop; 10396 10397 mLeft = left; 10398 mRenderNode.setLeft(left); 10399 10400 sizeChange(mRight - mLeft, height, oldWidth, height); 10401 10402 if (!matrixIsIdentity) { 10403 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10404 invalidate(true); 10405 } 10406 mBackgroundSizeChanged = true; 10407 invalidateParentIfNeeded(); 10408 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10409 // View was rejected last time it was drawn by its parent; this may have changed 10410 invalidateParentIfNeeded(); 10411 } 10412 } 10413 } 10414 10415 /** 10416 * Right position of this view relative to its parent. 10417 * 10418 * @return The right edge of this view, in pixels. 10419 */ 10420 @ViewDebug.CapturedViewProperty 10421 public final int getRight() { 10422 return mRight; 10423 } 10424 10425 /** 10426 * Sets the right position of this view relative to its parent. This method is meant to be called 10427 * by the layout system and should not generally be called otherwise, because the property 10428 * may be changed at any time by the layout. 10429 * 10430 * @param right The right of this view, in pixels. 10431 */ 10432 public final void setRight(int right) { 10433 if (right != mRight) { 10434 final boolean matrixIsIdentity = hasIdentityMatrix(); 10435 if (matrixIsIdentity) { 10436 if (mAttachInfo != null) { 10437 int maxRight; 10438 if (right < mRight) { 10439 maxRight = mRight; 10440 } else { 10441 maxRight = right; 10442 } 10443 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10444 } 10445 } else { 10446 // Double-invalidation is necessary to capture view's old and new areas 10447 invalidate(true); 10448 } 10449 10450 int oldWidth = mRight - mLeft; 10451 int height = mBottom - mTop; 10452 10453 mRight = right; 10454 mRenderNode.setRight(mRight); 10455 10456 sizeChange(mRight - mLeft, height, oldWidth, height); 10457 10458 if (!matrixIsIdentity) { 10459 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10460 invalidate(true); 10461 } 10462 mBackgroundSizeChanged = true; 10463 invalidateParentIfNeeded(); 10464 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10465 // View was rejected last time it was drawn by its parent; this may have changed 10466 invalidateParentIfNeeded(); 10467 } 10468 } 10469 } 10470 10471 /** 10472 * The visual x position of this view, in pixels. This is equivalent to the 10473 * {@link #setTranslationX(float) translationX} property plus the current 10474 * {@link #getLeft() left} property. 10475 * 10476 * @return The visual x position of this view, in pixels. 10477 */ 10478 @ViewDebug.ExportedProperty(category = "drawing") 10479 public float getX() { 10480 return mLeft + getTranslationX(); 10481 } 10482 10483 /** 10484 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10485 * {@link #setTranslationX(float) translationX} property to be the difference between 10486 * the x value passed in and the current {@link #getLeft() left} property. 10487 * 10488 * @param x The visual x position of this view, in pixels. 10489 */ 10490 public void setX(float x) { 10491 setTranslationX(x - mLeft); 10492 } 10493 10494 /** 10495 * The visual y position of this view, in pixels. This is equivalent to the 10496 * {@link #setTranslationY(float) translationY} property plus the current 10497 * {@link #getTop() top} property. 10498 * 10499 * @return The visual y position of this view, in pixels. 10500 */ 10501 @ViewDebug.ExportedProperty(category = "drawing") 10502 public float getY() { 10503 return mTop + getTranslationY(); 10504 } 10505 10506 /** 10507 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10508 * {@link #setTranslationY(float) translationY} property to be the difference between 10509 * the y value passed in and the current {@link #getTop() top} property. 10510 * 10511 * @param y The visual y position of this view, in pixels. 10512 */ 10513 public void setY(float y) { 10514 setTranslationY(y - mTop); 10515 } 10516 10517 /** 10518 * The visual z position of this view, in pixels. This is equivalent to the 10519 * {@link #setTranslationZ(float) translationZ} property plus the current 10520 * {@link #getElevation() elevation} property. 10521 * 10522 * @return The visual z position of this view, in pixels. 10523 */ 10524 @ViewDebug.ExportedProperty(category = "drawing") 10525 public float getZ() { 10526 return getElevation() + getTranslationZ(); 10527 } 10528 10529 /** 10530 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10531 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10532 * the x value passed in and the current {@link #getElevation() elevation} property. 10533 * 10534 * @param z The visual z position of this view, in pixels. 10535 */ 10536 public void setZ(float z) { 10537 setTranslationZ(z - getElevation()); 10538 } 10539 10540 /** 10541 * The base elevation of this view relative to its parent, in pixels. 10542 * 10543 * @return The base depth position of the view, in pixels. 10544 */ 10545 @ViewDebug.ExportedProperty(category = "drawing") 10546 public float getElevation() { 10547 return mRenderNode.getElevation(); 10548 } 10549 10550 /** 10551 * Sets the base elevation of this view, in pixels. 10552 * 10553 * @attr ref android.R.styleable#View_elevation 10554 */ 10555 public void setElevation(float elevation) { 10556 if (elevation != getElevation()) { 10557 invalidateViewProperty(true, false); 10558 mRenderNode.setElevation(elevation); 10559 invalidateViewProperty(false, true); 10560 10561 invalidateParentIfNeededAndWasQuickRejected(); 10562 } 10563 } 10564 10565 /** 10566 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10567 * This position is post-layout, in addition to wherever the object's 10568 * layout placed it. 10569 * 10570 * @return The horizontal position of this view relative to its left position, in pixels. 10571 */ 10572 @ViewDebug.ExportedProperty(category = "drawing") 10573 public float getTranslationX() { 10574 return mRenderNode.getTranslationX(); 10575 } 10576 10577 /** 10578 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10579 * This effectively positions the object post-layout, in addition to wherever the object's 10580 * layout placed it. 10581 * 10582 * @param translationX The horizontal position of this view relative to its left position, 10583 * in pixels. 10584 * 10585 * @attr ref android.R.styleable#View_translationX 10586 */ 10587 public void setTranslationX(float translationX) { 10588 if (translationX != getTranslationX()) { 10589 invalidateViewProperty(true, false); 10590 mRenderNode.setTranslationX(translationX); 10591 invalidateViewProperty(false, true); 10592 10593 invalidateParentIfNeededAndWasQuickRejected(); 10594 notifySubtreeAccessibilityStateChangedIfNeeded(); 10595 } 10596 } 10597 10598 /** 10599 * The vertical location of this view relative to its {@link #getTop() top} position. 10600 * This position is post-layout, in addition to wherever the object's 10601 * layout placed it. 10602 * 10603 * @return The vertical position of this view relative to its top position, 10604 * in pixels. 10605 */ 10606 @ViewDebug.ExportedProperty(category = "drawing") 10607 public float getTranslationY() { 10608 return mRenderNode.getTranslationY(); 10609 } 10610 10611 /** 10612 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10613 * This effectively positions the object post-layout, in addition to wherever the object's 10614 * layout placed it. 10615 * 10616 * @param translationY The vertical position of this view relative to its top position, 10617 * in pixels. 10618 * 10619 * @attr ref android.R.styleable#View_translationY 10620 */ 10621 public void setTranslationY(float translationY) { 10622 if (translationY != getTranslationY()) { 10623 invalidateViewProperty(true, false); 10624 mRenderNode.setTranslationY(translationY); 10625 invalidateViewProperty(false, true); 10626 10627 invalidateParentIfNeededAndWasQuickRejected(); 10628 } 10629 } 10630 10631 /** 10632 * The depth location of this view relative to its {@link #getElevation() elevation}. 10633 * 10634 * @return The depth of this view relative to its elevation. 10635 */ 10636 @ViewDebug.ExportedProperty(category = "drawing") 10637 public float getTranslationZ() { 10638 return mRenderNode.getTranslationZ(); 10639 } 10640 10641 /** 10642 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 10643 * 10644 * @attr ref android.R.styleable#View_translationZ 10645 */ 10646 public void setTranslationZ(float translationZ) { 10647 if (translationZ != getTranslationZ()) { 10648 invalidateViewProperty(true, false); 10649 mRenderNode.setTranslationZ(translationZ); 10650 invalidateViewProperty(false, true); 10651 10652 invalidateParentIfNeededAndWasQuickRejected(); 10653 } 10654 } 10655 10656 /** 10657 * Returns a ValueAnimator which can animate a clearing circle. 10658 * <p> 10659 * The View is prevented from drawing within the circle, so the content 10660 * behind the View shows through. 10661 * 10662 * @param centerX The x coordinate of the center of the animating circle. 10663 * @param centerY The y coordinate of the center of the animating circle. 10664 * @param startRadius The starting radius of the animating circle. 10665 * @param endRadius The ending radius of the animating circle. 10666 * 10667 * @hide 10668 */ 10669 public final ValueAnimator createClearCircleAnimator(int centerX, int centerY, 10670 float startRadius, float endRadius) { 10671 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10672 startRadius, endRadius, true); 10673 } 10674 10675 /** 10676 * Returns the current StateListAnimator if exists. 10677 * 10678 * @return StateListAnimator or null if it does not exists 10679 * @see #setStateListAnimator(android.animation.StateListAnimator) 10680 */ 10681 public StateListAnimator getStateListAnimator() { 10682 return mStateListAnimator; 10683 } 10684 10685 /** 10686 * Attaches the provided StateListAnimator to this View. 10687 * <p> 10688 * Any previously attached StateListAnimator will be detached. 10689 * 10690 * @param stateListAnimator The StateListAnimator to update the view 10691 * @see {@link android.animation.StateListAnimator} 10692 */ 10693 public void setStateListAnimator(StateListAnimator stateListAnimator) { 10694 if (mStateListAnimator == stateListAnimator) { 10695 return; 10696 } 10697 if (mStateListAnimator != null) { 10698 mStateListAnimator.setTarget(null); 10699 } 10700 mStateListAnimator = stateListAnimator; 10701 if (stateListAnimator != null) { 10702 stateListAnimator.setTarget(this); 10703 if (isAttachedToWindow()) { 10704 stateListAnimator.setState(getDrawableState()); 10705 } 10706 } 10707 } 10708 10709 /** 10710 * Sets the {@link Outline} of the view, which defines the shape of the shadow it 10711 * casts, and enables outline clipping. 10712 * <p> 10713 * By default, a View queries its Outline from its background drawable, via 10714 * {@link Drawable#getOutline(Outline)}. Manually setting the Outline with this method allows 10715 * this behavior to be overridden. 10716 * <p> 10717 * If the outline is {@link Outline#isEmpty()} or is <code>null</code>, 10718 * shadows will not be cast. 10719 * <p> 10720 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 10721 * 10722 * @param outline The new outline of the view. 10723 * 10724 * @see #setClipToOutline(boolean) 10725 * @see #getClipToOutline() 10726 */ 10727 public void setOutline(@Nullable Outline outline) { 10728 mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED; 10729 10730 if (outline == null || outline.isEmpty()) { 10731 if (mOutline != null) { 10732 mOutline.setEmpty(); 10733 } 10734 } else { 10735 // always copy the path since caller may reuse 10736 if (mOutline == null) { 10737 mOutline = new Outline(); 10738 } 10739 mOutline.set(outline); 10740 } 10741 mRenderNode.setOutline(mOutline); 10742 } 10743 10744 /** 10745 * Returns whether the Outline should be used to clip the contents of the View. 10746 * <p> 10747 * Note that this flag will only be respected if the View's Outline returns true from 10748 * {@link Outline#canClip()}. 10749 * 10750 * @see #setOutline(Outline) 10751 * @see #setClipToOutline(boolean) 10752 */ 10753 public final boolean getClipToOutline() { 10754 return mRenderNode.getClipToOutline(); 10755 } 10756 10757 /** 10758 * Sets whether the View's Outline should be used to clip the contents of the View. 10759 * <p> 10760 * Note that this flag will only be respected if the View's Outline returns true from 10761 * {@link Outline#canClip()}. 10762 * 10763 * @see #setOutline(Outline) 10764 * @see #getClipToOutline() 10765 */ 10766 public void setClipToOutline(boolean clipToOutline) { 10767 damageInParent(); 10768 if (getClipToOutline() != clipToOutline) { 10769 mRenderNode.setClipToOutline(clipToOutline); 10770 } 10771 } 10772 10773 private void queryOutlineFromBackgroundIfUndefined() { 10774 if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) { 10775 // Outline not currently defined, query from background 10776 if (mOutline == null) { 10777 mOutline = new Outline(); 10778 } else { 10779 //invalidate outline, to ensure background calculates it 10780 mOutline.setEmpty(); 10781 } 10782 if (mBackground.getOutline(mOutline)) { 10783 if (mOutline.isEmpty()) { 10784 throw new IllegalStateException("Background drawable failed to build outline"); 10785 } 10786 mRenderNode.setOutline(mOutline); 10787 } else { 10788 mRenderNode.setOutline(null); 10789 } 10790 notifySubtreeAccessibilityStateChangedIfNeeded(); 10791 } 10792 } 10793 10794 /** 10795 * Private API to be used for reveal animation 10796 * 10797 * @hide 10798 */ 10799 public void setRevealClip(boolean shouldClip, boolean inverseClip, 10800 float x, float y, float radius) { 10801 mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius); 10802 // TODO: Handle this invalidate in a better way, or purely in native. 10803 invalidate(); 10804 } 10805 10806 /** 10807 * Hit rectangle in parent's coordinates 10808 * 10809 * @param outRect The hit rectangle of the view. 10810 */ 10811 public void getHitRect(Rect outRect) { 10812 if (hasIdentityMatrix() || mAttachInfo == null) { 10813 outRect.set(mLeft, mTop, mRight, mBottom); 10814 } else { 10815 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10816 tmpRect.set(0, 0, getWidth(), getHeight()); 10817 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 10818 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10819 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10820 } 10821 } 10822 10823 /** 10824 * Determines whether the given point, in local coordinates is inside the view. 10825 */ 10826 /*package*/ final boolean pointInView(float localX, float localY) { 10827 return localX >= 0 && localX < (mRight - mLeft) 10828 && localY >= 0 && localY < (mBottom - mTop); 10829 } 10830 10831 /** 10832 * Utility method to determine whether the given point, in local coordinates, 10833 * is inside the view, where the area of the view is expanded by the slop factor. 10834 * This method is called while processing touch-move events to determine if the event 10835 * is still within the view. 10836 * 10837 * @hide 10838 */ 10839 public boolean pointInView(float localX, float localY, float slop) { 10840 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10841 localY < ((mBottom - mTop) + slop); 10842 } 10843 10844 /** 10845 * When a view has focus and the user navigates away from it, the next view is searched for 10846 * starting from the rectangle filled in by this method. 10847 * 10848 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10849 * of the view. However, if your view maintains some idea of internal selection, 10850 * such as a cursor, or a selected row or column, you should override this method and 10851 * fill in a more specific rectangle. 10852 * 10853 * @param r The rectangle to fill in, in this view's coordinates. 10854 */ 10855 public void getFocusedRect(Rect r) { 10856 getDrawingRect(r); 10857 } 10858 10859 /** 10860 * If some part of this view is not clipped by any of its parents, then 10861 * return that area in r in global (root) coordinates. To convert r to local 10862 * coordinates (without taking possible View rotations into account), offset 10863 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10864 * If the view is completely clipped or translated out, return false. 10865 * 10866 * @param r If true is returned, r holds the global coordinates of the 10867 * visible portion of this view. 10868 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10869 * between this view and its root. globalOffet may be null. 10870 * @return true if r is non-empty (i.e. part of the view is visible at the 10871 * root level. 10872 */ 10873 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10874 int width = mRight - mLeft; 10875 int height = mBottom - mTop; 10876 if (width > 0 && height > 0) { 10877 r.set(0, 0, width, height); 10878 if (globalOffset != null) { 10879 globalOffset.set(-mScrollX, -mScrollY); 10880 } 10881 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10882 } 10883 return false; 10884 } 10885 10886 public final boolean getGlobalVisibleRect(Rect r) { 10887 return getGlobalVisibleRect(r, null); 10888 } 10889 10890 public final boolean getLocalVisibleRect(Rect r) { 10891 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10892 if (getGlobalVisibleRect(r, offset)) { 10893 r.offset(-offset.x, -offset.y); // make r local 10894 return true; 10895 } 10896 return false; 10897 } 10898 10899 /** 10900 * Offset this view's vertical location by the specified number of pixels. 10901 * 10902 * @param offset the number of pixels to offset the view by 10903 */ 10904 public void offsetTopAndBottom(int offset) { 10905 if (offset != 0) { 10906 final boolean matrixIsIdentity = hasIdentityMatrix(); 10907 if (matrixIsIdentity) { 10908 if (isHardwareAccelerated()) { 10909 invalidateViewProperty(false, false); 10910 } else { 10911 final ViewParent p = mParent; 10912 if (p != null && mAttachInfo != null) { 10913 final Rect r = mAttachInfo.mTmpInvalRect; 10914 int minTop; 10915 int maxBottom; 10916 int yLoc; 10917 if (offset < 0) { 10918 minTop = mTop + offset; 10919 maxBottom = mBottom; 10920 yLoc = offset; 10921 } else { 10922 minTop = mTop; 10923 maxBottom = mBottom + offset; 10924 yLoc = 0; 10925 } 10926 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10927 p.invalidateChild(this, r); 10928 } 10929 } 10930 } else { 10931 invalidateViewProperty(false, false); 10932 } 10933 10934 mTop += offset; 10935 mBottom += offset; 10936 mRenderNode.offsetTopAndBottom(offset); 10937 if (isHardwareAccelerated()) { 10938 invalidateViewProperty(false, false); 10939 } else { 10940 if (!matrixIsIdentity) { 10941 invalidateViewProperty(false, true); 10942 } 10943 invalidateParentIfNeeded(); 10944 } 10945 notifySubtreeAccessibilityStateChangedIfNeeded(); 10946 } 10947 } 10948 10949 /** 10950 * Offset this view's horizontal location by the specified amount of pixels. 10951 * 10952 * @param offset the number of pixels to offset the view by 10953 */ 10954 public void offsetLeftAndRight(int offset) { 10955 if (offset != 0) { 10956 final boolean matrixIsIdentity = hasIdentityMatrix(); 10957 if (matrixIsIdentity) { 10958 if (isHardwareAccelerated()) { 10959 invalidateViewProperty(false, false); 10960 } else { 10961 final ViewParent p = mParent; 10962 if (p != null && mAttachInfo != null) { 10963 final Rect r = mAttachInfo.mTmpInvalRect; 10964 int minLeft; 10965 int maxRight; 10966 if (offset < 0) { 10967 minLeft = mLeft + offset; 10968 maxRight = mRight; 10969 } else { 10970 minLeft = mLeft; 10971 maxRight = mRight + offset; 10972 } 10973 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10974 p.invalidateChild(this, r); 10975 } 10976 } 10977 } else { 10978 invalidateViewProperty(false, false); 10979 } 10980 10981 mLeft += offset; 10982 mRight += offset; 10983 mRenderNode.offsetLeftAndRight(offset); 10984 if (isHardwareAccelerated()) { 10985 invalidateViewProperty(false, false); 10986 } else { 10987 if (!matrixIsIdentity) { 10988 invalidateViewProperty(false, true); 10989 } 10990 invalidateParentIfNeeded(); 10991 } 10992 notifySubtreeAccessibilityStateChangedIfNeeded(); 10993 } 10994 } 10995 10996 /** 10997 * Get the LayoutParams associated with this view. All views should have 10998 * layout parameters. These supply parameters to the <i>parent</i> of this 10999 * view specifying how it should be arranged. There are many subclasses of 11000 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11001 * of ViewGroup that are responsible for arranging their children. 11002 * 11003 * This method may return null if this View is not attached to a parent 11004 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11005 * was not invoked successfully. When a View is attached to a parent 11006 * ViewGroup, this method must not return null. 11007 * 11008 * @return The LayoutParams associated with this view, or null if no 11009 * parameters have been set yet 11010 */ 11011 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11012 public ViewGroup.LayoutParams getLayoutParams() { 11013 return mLayoutParams; 11014 } 11015 11016 /** 11017 * Set the layout parameters associated with this view. These supply 11018 * parameters to the <i>parent</i> of this view specifying how it should be 11019 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11020 * correspond to the different subclasses of ViewGroup that are responsible 11021 * for arranging their children. 11022 * 11023 * @param params The layout parameters for this view, cannot be null 11024 */ 11025 public void setLayoutParams(ViewGroup.LayoutParams params) { 11026 if (params == null) { 11027 throw new NullPointerException("Layout parameters cannot be null"); 11028 } 11029 mLayoutParams = params; 11030 resolveLayoutParams(); 11031 if (mParent instanceof ViewGroup) { 11032 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11033 } 11034 requestLayout(); 11035 } 11036 11037 /** 11038 * Resolve the layout parameters depending on the resolved layout direction 11039 * 11040 * @hide 11041 */ 11042 public void resolveLayoutParams() { 11043 if (mLayoutParams != null) { 11044 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11045 } 11046 } 11047 11048 /** 11049 * Set the scrolled position of your view. This will cause a call to 11050 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11051 * invalidated. 11052 * @param x the x position to scroll to 11053 * @param y the y position to scroll to 11054 */ 11055 public void scrollTo(int x, int y) { 11056 if (mScrollX != x || mScrollY != y) { 11057 int oldX = mScrollX; 11058 int oldY = mScrollY; 11059 mScrollX = x; 11060 mScrollY = y; 11061 invalidateParentCaches(); 11062 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11063 if (!awakenScrollBars()) { 11064 postInvalidateOnAnimation(); 11065 } 11066 } 11067 } 11068 11069 /** 11070 * Move the scrolled position of your view. This will cause a call to 11071 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11072 * invalidated. 11073 * @param x the amount of pixels to scroll by horizontally 11074 * @param y the amount of pixels to scroll by vertically 11075 */ 11076 public void scrollBy(int x, int y) { 11077 scrollTo(mScrollX + x, mScrollY + y); 11078 } 11079 11080 /** 11081 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11082 * animation to fade the scrollbars out after a default delay. If a subclass 11083 * provides animated scrolling, the start delay should equal the duration 11084 * of the scrolling animation.</p> 11085 * 11086 * <p>The animation starts only if at least one of the scrollbars is 11087 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11088 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11089 * this method returns true, and false otherwise. If the animation is 11090 * started, this method calls {@link #invalidate()}; in that case the 11091 * caller should not call {@link #invalidate()}.</p> 11092 * 11093 * <p>This method should be invoked every time a subclass directly updates 11094 * the scroll parameters.</p> 11095 * 11096 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11097 * and {@link #scrollTo(int, int)}.</p> 11098 * 11099 * @return true if the animation is played, false otherwise 11100 * 11101 * @see #awakenScrollBars(int) 11102 * @see #scrollBy(int, int) 11103 * @see #scrollTo(int, int) 11104 * @see #isHorizontalScrollBarEnabled() 11105 * @see #isVerticalScrollBarEnabled() 11106 * @see #setHorizontalScrollBarEnabled(boolean) 11107 * @see #setVerticalScrollBarEnabled(boolean) 11108 */ 11109 protected boolean awakenScrollBars() { 11110 return mScrollCache != null && 11111 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11112 } 11113 11114 /** 11115 * Trigger the scrollbars to draw. 11116 * This method differs from awakenScrollBars() only in its default duration. 11117 * initialAwakenScrollBars() will show the scroll bars for longer than 11118 * usual to give the user more of a chance to notice them. 11119 * 11120 * @return true if the animation is played, false otherwise. 11121 */ 11122 private boolean initialAwakenScrollBars() { 11123 return mScrollCache != null && 11124 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11125 } 11126 11127 /** 11128 * <p> 11129 * Trigger the scrollbars to draw. When invoked this method starts an 11130 * animation to fade the scrollbars out after a fixed delay. If a subclass 11131 * provides animated scrolling, the start delay should equal the duration of 11132 * the scrolling animation. 11133 * </p> 11134 * 11135 * <p> 11136 * The animation starts only if at least one of the scrollbars is enabled, 11137 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11138 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11139 * this method returns true, and false otherwise. If the animation is 11140 * started, this method calls {@link #invalidate()}; in that case the caller 11141 * should not call {@link #invalidate()}. 11142 * </p> 11143 * 11144 * <p> 11145 * This method should be invoked everytime a subclass directly updates the 11146 * scroll parameters. 11147 * </p> 11148 * 11149 * @param startDelay the delay, in milliseconds, after which the animation 11150 * should start; when the delay is 0, the animation starts 11151 * immediately 11152 * @return true if the animation is played, false otherwise 11153 * 11154 * @see #scrollBy(int, int) 11155 * @see #scrollTo(int, int) 11156 * @see #isHorizontalScrollBarEnabled() 11157 * @see #isVerticalScrollBarEnabled() 11158 * @see #setHorizontalScrollBarEnabled(boolean) 11159 * @see #setVerticalScrollBarEnabled(boolean) 11160 */ 11161 protected boolean awakenScrollBars(int startDelay) { 11162 return awakenScrollBars(startDelay, true); 11163 } 11164 11165 /** 11166 * <p> 11167 * Trigger the scrollbars to draw. When invoked this method starts an 11168 * animation to fade the scrollbars out after a fixed delay. If a subclass 11169 * provides animated scrolling, the start delay should equal the duration of 11170 * the scrolling animation. 11171 * </p> 11172 * 11173 * <p> 11174 * The animation starts only if at least one of the scrollbars is enabled, 11175 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11176 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11177 * this method returns true, and false otherwise. If the animation is 11178 * started, this method calls {@link #invalidate()} if the invalidate parameter 11179 * is set to true; in that case the caller 11180 * should not call {@link #invalidate()}. 11181 * </p> 11182 * 11183 * <p> 11184 * This method should be invoked everytime a subclass directly updates the 11185 * scroll parameters. 11186 * </p> 11187 * 11188 * @param startDelay the delay, in milliseconds, after which the animation 11189 * should start; when the delay is 0, the animation starts 11190 * immediately 11191 * 11192 * @param invalidate Wheter this method should call invalidate 11193 * 11194 * @return true if the animation is played, false otherwise 11195 * 11196 * @see #scrollBy(int, int) 11197 * @see #scrollTo(int, int) 11198 * @see #isHorizontalScrollBarEnabled() 11199 * @see #isVerticalScrollBarEnabled() 11200 * @see #setHorizontalScrollBarEnabled(boolean) 11201 * @see #setVerticalScrollBarEnabled(boolean) 11202 */ 11203 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11204 final ScrollabilityCache scrollCache = mScrollCache; 11205 11206 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11207 return false; 11208 } 11209 11210 if (scrollCache.scrollBar == null) { 11211 scrollCache.scrollBar = new ScrollBarDrawable(); 11212 } 11213 11214 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11215 11216 if (invalidate) { 11217 // Invalidate to show the scrollbars 11218 postInvalidateOnAnimation(); 11219 } 11220 11221 if (scrollCache.state == ScrollabilityCache.OFF) { 11222 // FIXME: this is copied from WindowManagerService. 11223 // We should get this value from the system when it 11224 // is possible to do so. 11225 final int KEY_REPEAT_FIRST_DELAY = 750; 11226 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11227 } 11228 11229 // Tell mScrollCache when we should start fading. This may 11230 // extend the fade start time if one was already scheduled 11231 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11232 scrollCache.fadeStartTime = fadeStartTime; 11233 scrollCache.state = ScrollabilityCache.ON; 11234 11235 // Schedule our fader to run, unscheduling any old ones first 11236 if (mAttachInfo != null) { 11237 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11238 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11239 } 11240 11241 return true; 11242 } 11243 11244 return false; 11245 } 11246 11247 /** 11248 * Do not invalidate views which are not visible and which are not running an animation. They 11249 * will not get drawn and they should not set dirty flags as if they will be drawn 11250 */ 11251 private boolean skipInvalidate() { 11252 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11253 (!(mParent instanceof ViewGroup) || 11254 !((ViewGroup) mParent).isViewTransitioning(this)); 11255 } 11256 11257 /** 11258 * Mark the area defined by dirty as needing to be drawn. If the view is 11259 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11260 * point in the future. 11261 * <p> 11262 * This must be called from a UI thread. To call from a non-UI thread, call 11263 * {@link #postInvalidate()}. 11264 * <p> 11265 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11266 * {@code dirty}. 11267 * 11268 * @param dirty the rectangle representing the bounds of the dirty region 11269 */ 11270 public void invalidate(Rect dirty) { 11271 final int scrollX = mScrollX; 11272 final int scrollY = mScrollY; 11273 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11274 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11275 } 11276 11277 /** 11278 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11279 * coordinates of the dirty rect are relative to the view. If the view is 11280 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11281 * point in the future. 11282 * <p> 11283 * This must be called from a UI thread. To call from a non-UI thread, call 11284 * {@link #postInvalidate()}. 11285 * 11286 * @param l the left position of the dirty region 11287 * @param t the top position of the dirty region 11288 * @param r the right position of the dirty region 11289 * @param b the bottom position of the dirty region 11290 */ 11291 public void invalidate(int l, int t, int r, int b) { 11292 final int scrollX = mScrollX; 11293 final int scrollY = mScrollY; 11294 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11295 } 11296 11297 /** 11298 * Invalidate the whole view. If the view is visible, 11299 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11300 * the future. 11301 * <p> 11302 * This must be called from a UI thread. To call from a non-UI thread, call 11303 * {@link #postInvalidate()}. 11304 */ 11305 public void invalidate() { 11306 invalidate(true); 11307 } 11308 11309 /** 11310 * This is where the invalidate() work actually happens. A full invalidate() 11311 * causes the drawing cache to be invalidated, but this function can be 11312 * called with invalidateCache set to false to skip that invalidation step 11313 * for cases that do not need it (for example, a component that remains at 11314 * the same dimensions with the same content). 11315 * 11316 * @param invalidateCache Whether the drawing cache for this view should be 11317 * invalidated as well. This is usually true for a full 11318 * invalidate, but may be set to false if the View's contents or 11319 * dimensions have not changed. 11320 */ 11321 void invalidate(boolean invalidateCache) { 11322 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11323 } 11324 11325 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11326 boolean fullInvalidate) { 11327 if (skipInvalidate()) { 11328 return; 11329 } 11330 11331 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11332 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11333 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11334 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11335 if (fullInvalidate) { 11336 mLastIsOpaque = isOpaque(); 11337 mPrivateFlags &= ~PFLAG_DRAWN; 11338 } 11339 11340 mPrivateFlags |= PFLAG_DIRTY; 11341 11342 if (invalidateCache) { 11343 mPrivateFlags |= PFLAG_INVALIDATED; 11344 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11345 } 11346 11347 // Propagate the damage rectangle to the parent view. 11348 final AttachInfo ai = mAttachInfo; 11349 final ViewParent p = mParent; 11350 if (p != null && ai != null && l < r && t < b) { 11351 final Rect damage = ai.mTmpInvalRect; 11352 damage.set(l, t, r, b); 11353 p.invalidateChild(this, damage); 11354 } 11355 11356 // Damage the entire projection receiver, if necessary. 11357 if (mBackground != null && mBackground.isProjected()) { 11358 final View receiver = getProjectionReceiver(); 11359 if (receiver != null) { 11360 receiver.damageInParent(); 11361 } 11362 } 11363 11364 // Damage the entire IsolatedZVolume recieving this view's shadow. 11365 if (isHardwareAccelerated() && getZ() != 0) { 11366 damageShadowReceiver(); 11367 } 11368 } 11369 } 11370 11371 /** 11372 * @return this view's projection receiver, or {@code null} if none exists 11373 */ 11374 private View getProjectionReceiver() { 11375 ViewParent p = getParent(); 11376 while (p != null && p instanceof View) { 11377 final View v = (View) p; 11378 if (v.isProjectionReceiver()) { 11379 return v; 11380 } 11381 p = p.getParent(); 11382 } 11383 11384 return null; 11385 } 11386 11387 /** 11388 * @return whether the view is a projection receiver 11389 */ 11390 private boolean isProjectionReceiver() { 11391 return mBackground != null; 11392 } 11393 11394 /** 11395 * Damage area of the screen that can be covered by this View's shadow. 11396 * 11397 * This method will guarantee that any changes to shadows cast by a View 11398 * are damaged on the screen for future redraw. 11399 */ 11400 private void damageShadowReceiver() { 11401 final AttachInfo ai = mAttachInfo; 11402 if (ai != null) { 11403 ViewParent p = getParent(); 11404 if (p != null && p instanceof ViewGroup) { 11405 final ViewGroup vg = (ViewGroup) p; 11406 vg.damageInParent(); 11407 } 11408 } 11409 } 11410 11411 /** 11412 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11413 * set any flags or handle all of the cases handled by the default invalidation methods. 11414 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11415 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11416 * walk up the hierarchy, transforming the dirty rect as necessary. 11417 * 11418 * The method also handles normal invalidation logic if display list properties are not 11419 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11420 * backup approach, to handle these cases used in the various property-setting methods. 11421 * 11422 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11423 * are not being used in this view 11424 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11425 * list properties are not being used in this view 11426 */ 11427 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11428 if (!isHardwareAccelerated() 11429 || !mRenderNode.isValid() 11430 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11431 if (invalidateParent) { 11432 invalidateParentCaches(); 11433 } 11434 if (forceRedraw) { 11435 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11436 } 11437 invalidate(false); 11438 } else { 11439 damageInParent(); 11440 } 11441 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11442 damageShadowReceiver(); 11443 } 11444 } 11445 11446 /** 11447 * Tells the parent view to damage this view's bounds. 11448 * 11449 * @hide 11450 */ 11451 protected void damageInParent() { 11452 final AttachInfo ai = mAttachInfo; 11453 final ViewParent p = mParent; 11454 if (p != null && ai != null) { 11455 final Rect r = ai.mTmpInvalRect; 11456 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11457 if (mParent instanceof ViewGroup) { 11458 ((ViewGroup) mParent).damageChild(this, r); 11459 } else { 11460 mParent.invalidateChild(this, r); 11461 } 11462 } 11463 } 11464 11465 /** 11466 * Utility method to transform a given Rect by the current matrix of this view. 11467 */ 11468 void transformRect(final Rect rect) { 11469 if (!getMatrix().isIdentity()) { 11470 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11471 boundingRect.set(rect); 11472 getMatrix().mapRect(boundingRect); 11473 rect.set((int) Math.floor(boundingRect.left), 11474 (int) Math.floor(boundingRect.top), 11475 (int) Math.ceil(boundingRect.right), 11476 (int) Math.ceil(boundingRect.bottom)); 11477 } 11478 } 11479 11480 /** 11481 * Used to indicate that the parent of this view should clear its caches. This functionality 11482 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11483 * which is necessary when various parent-managed properties of the view change, such as 11484 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11485 * clears the parent caches and does not causes an invalidate event. 11486 * 11487 * @hide 11488 */ 11489 protected void invalidateParentCaches() { 11490 if (mParent instanceof View) { 11491 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11492 } 11493 } 11494 11495 /** 11496 * Used to indicate that the parent of this view should be invalidated. This functionality 11497 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11498 * which is necessary when various parent-managed properties of the view change, such as 11499 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11500 * an invalidation event to the parent. 11501 * 11502 * @hide 11503 */ 11504 protected void invalidateParentIfNeeded() { 11505 if (isHardwareAccelerated() && mParent instanceof View) { 11506 ((View) mParent).invalidate(true); 11507 } 11508 } 11509 11510 /** 11511 * @hide 11512 */ 11513 protected void invalidateParentIfNeededAndWasQuickRejected() { 11514 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11515 // View was rejected last time it was drawn by its parent; this may have changed 11516 invalidateParentIfNeeded(); 11517 } 11518 } 11519 11520 /** 11521 * Indicates whether this View is opaque. An opaque View guarantees that it will 11522 * draw all the pixels overlapping its bounds using a fully opaque color. 11523 * 11524 * Subclasses of View should override this method whenever possible to indicate 11525 * whether an instance is opaque. Opaque Views are treated in a special way by 11526 * the View hierarchy, possibly allowing it to perform optimizations during 11527 * invalidate/draw passes. 11528 * 11529 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11530 */ 11531 @ViewDebug.ExportedProperty(category = "drawing") 11532 public boolean isOpaque() { 11533 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11534 getFinalAlpha() >= 1.0f; 11535 } 11536 11537 /** 11538 * @hide 11539 */ 11540 protected void computeOpaqueFlags() { 11541 // Opaque if: 11542 // - Has a background 11543 // - Background is opaque 11544 // - Doesn't have scrollbars or scrollbars overlay 11545 11546 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11547 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11548 } else { 11549 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11550 } 11551 11552 final int flags = mViewFlags; 11553 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11554 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11555 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11556 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11557 } else { 11558 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11559 } 11560 } 11561 11562 /** 11563 * @hide 11564 */ 11565 protected boolean hasOpaqueScrollbars() { 11566 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11567 } 11568 11569 /** 11570 * @return A handler associated with the thread running the View. This 11571 * handler can be used to pump events in the UI events queue. 11572 */ 11573 public Handler getHandler() { 11574 final AttachInfo attachInfo = mAttachInfo; 11575 if (attachInfo != null) { 11576 return attachInfo.mHandler; 11577 } 11578 return null; 11579 } 11580 11581 /** 11582 * Gets the view root associated with the View. 11583 * @return The view root, or null if none. 11584 * @hide 11585 */ 11586 public ViewRootImpl getViewRootImpl() { 11587 if (mAttachInfo != null) { 11588 return mAttachInfo.mViewRootImpl; 11589 } 11590 return null; 11591 } 11592 11593 /** 11594 * @hide 11595 */ 11596 public HardwareRenderer getHardwareRenderer() { 11597 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11598 } 11599 11600 /** 11601 * <p>Causes the Runnable to be added to the message queue. 11602 * The runnable will be run on the user interface thread.</p> 11603 * 11604 * @param action The Runnable that will be executed. 11605 * 11606 * @return Returns true if the Runnable was successfully placed in to the 11607 * message queue. Returns false on failure, usually because the 11608 * looper processing the message queue is exiting. 11609 * 11610 * @see #postDelayed 11611 * @see #removeCallbacks 11612 */ 11613 public boolean post(Runnable action) { 11614 final AttachInfo attachInfo = mAttachInfo; 11615 if (attachInfo != null) { 11616 return attachInfo.mHandler.post(action); 11617 } 11618 // Assume that post will succeed later 11619 ViewRootImpl.getRunQueue().post(action); 11620 return true; 11621 } 11622 11623 /** 11624 * <p>Causes the Runnable to be added to the message queue, to be run 11625 * after the specified amount of time elapses. 11626 * The runnable will be run on the user interface thread.</p> 11627 * 11628 * @param action The Runnable that will be executed. 11629 * @param delayMillis The delay (in milliseconds) until the Runnable 11630 * will be executed. 11631 * 11632 * @return true if the Runnable was successfully placed in to the 11633 * message queue. Returns false on failure, usually because the 11634 * looper processing the message queue is exiting. Note that a 11635 * result of true does not mean the Runnable will be processed -- 11636 * if the looper is quit before the delivery time of the message 11637 * occurs then the message will be dropped. 11638 * 11639 * @see #post 11640 * @see #removeCallbacks 11641 */ 11642 public boolean postDelayed(Runnable action, long delayMillis) { 11643 final AttachInfo attachInfo = mAttachInfo; 11644 if (attachInfo != null) { 11645 return attachInfo.mHandler.postDelayed(action, delayMillis); 11646 } 11647 // Assume that post will succeed later 11648 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11649 return true; 11650 } 11651 11652 /** 11653 * <p>Causes the Runnable to execute on the next animation time step. 11654 * The runnable will be run on the user interface thread.</p> 11655 * 11656 * @param action The Runnable that will be executed. 11657 * 11658 * @see #postOnAnimationDelayed 11659 * @see #removeCallbacks 11660 */ 11661 public void postOnAnimation(Runnable action) { 11662 final AttachInfo attachInfo = mAttachInfo; 11663 if (attachInfo != null) { 11664 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11665 Choreographer.CALLBACK_ANIMATION, action, null); 11666 } else { 11667 // Assume that post will succeed later 11668 ViewRootImpl.getRunQueue().post(action); 11669 } 11670 } 11671 11672 /** 11673 * <p>Causes the Runnable to execute on the next animation time step, 11674 * after the specified amount of time elapses. 11675 * The runnable will be run on the user interface thread.</p> 11676 * 11677 * @param action The Runnable that will be executed. 11678 * @param delayMillis The delay (in milliseconds) until the Runnable 11679 * will be executed. 11680 * 11681 * @see #postOnAnimation 11682 * @see #removeCallbacks 11683 */ 11684 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11685 final AttachInfo attachInfo = mAttachInfo; 11686 if (attachInfo != null) { 11687 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11688 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11689 } else { 11690 // Assume that post will succeed later 11691 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11692 } 11693 } 11694 11695 /** 11696 * <p>Removes the specified Runnable from the message queue.</p> 11697 * 11698 * @param action The Runnable to remove from the message handling queue 11699 * 11700 * @return true if this view could ask the Handler to remove the Runnable, 11701 * false otherwise. When the returned value is true, the Runnable 11702 * may or may not have been actually removed from the message queue 11703 * (for instance, if the Runnable was not in the queue already.) 11704 * 11705 * @see #post 11706 * @see #postDelayed 11707 * @see #postOnAnimation 11708 * @see #postOnAnimationDelayed 11709 */ 11710 public boolean removeCallbacks(Runnable action) { 11711 if (action != null) { 11712 final AttachInfo attachInfo = mAttachInfo; 11713 if (attachInfo != null) { 11714 attachInfo.mHandler.removeCallbacks(action); 11715 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11716 Choreographer.CALLBACK_ANIMATION, action, null); 11717 } 11718 // Assume that post will succeed later 11719 ViewRootImpl.getRunQueue().removeCallbacks(action); 11720 } 11721 return true; 11722 } 11723 11724 /** 11725 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11726 * Use this to invalidate the View from a non-UI thread.</p> 11727 * 11728 * <p>This method can be invoked from outside of the UI thread 11729 * only when this View is attached to a window.</p> 11730 * 11731 * @see #invalidate() 11732 * @see #postInvalidateDelayed(long) 11733 */ 11734 public void postInvalidate() { 11735 postInvalidateDelayed(0); 11736 } 11737 11738 /** 11739 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11740 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11741 * 11742 * <p>This method can be invoked from outside of the UI thread 11743 * only when this View is attached to a window.</p> 11744 * 11745 * @param left The left coordinate of the rectangle to invalidate. 11746 * @param top The top coordinate of the rectangle to invalidate. 11747 * @param right The right coordinate of the rectangle to invalidate. 11748 * @param bottom The bottom coordinate of the rectangle to invalidate. 11749 * 11750 * @see #invalidate(int, int, int, int) 11751 * @see #invalidate(Rect) 11752 * @see #postInvalidateDelayed(long, int, int, int, int) 11753 */ 11754 public void postInvalidate(int left, int top, int right, int bottom) { 11755 postInvalidateDelayed(0, left, top, right, bottom); 11756 } 11757 11758 /** 11759 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11760 * loop. Waits for the specified amount of time.</p> 11761 * 11762 * <p>This method can be invoked from outside of the UI thread 11763 * only when this View is attached to a window.</p> 11764 * 11765 * @param delayMilliseconds the duration in milliseconds to delay the 11766 * invalidation by 11767 * 11768 * @see #invalidate() 11769 * @see #postInvalidate() 11770 */ 11771 public void postInvalidateDelayed(long delayMilliseconds) { 11772 // We try only with the AttachInfo because there's no point in invalidating 11773 // if we are not attached to our window 11774 final AttachInfo attachInfo = mAttachInfo; 11775 if (attachInfo != null) { 11776 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11777 } 11778 } 11779 11780 /** 11781 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11782 * through the event loop. Waits for the specified amount of time.</p> 11783 * 11784 * <p>This method can be invoked from outside of the UI thread 11785 * only when this View is attached to a window.</p> 11786 * 11787 * @param delayMilliseconds the duration in milliseconds to delay the 11788 * invalidation by 11789 * @param left The left coordinate of the rectangle to invalidate. 11790 * @param top The top coordinate of the rectangle to invalidate. 11791 * @param right The right coordinate of the rectangle to invalidate. 11792 * @param bottom The bottom coordinate of the rectangle to invalidate. 11793 * 11794 * @see #invalidate(int, int, int, int) 11795 * @see #invalidate(Rect) 11796 * @see #postInvalidate(int, int, int, int) 11797 */ 11798 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11799 int right, int bottom) { 11800 11801 // We try only with the AttachInfo because there's no point in invalidating 11802 // if we are not attached to our window 11803 final AttachInfo attachInfo = mAttachInfo; 11804 if (attachInfo != null) { 11805 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11806 info.target = this; 11807 info.left = left; 11808 info.top = top; 11809 info.right = right; 11810 info.bottom = bottom; 11811 11812 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11813 } 11814 } 11815 11816 /** 11817 * <p>Cause an invalidate to happen on the next animation time step, typically the 11818 * next display frame.</p> 11819 * 11820 * <p>This method can be invoked from outside of the UI thread 11821 * only when this View is attached to a window.</p> 11822 * 11823 * @see #invalidate() 11824 */ 11825 public void postInvalidateOnAnimation() { 11826 // We try only with the AttachInfo because there's no point in invalidating 11827 // if we are not attached to our window 11828 final AttachInfo attachInfo = mAttachInfo; 11829 if (attachInfo != null) { 11830 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11831 } 11832 } 11833 11834 /** 11835 * <p>Cause an invalidate of the specified area to happen on the next animation 11836 * time step, typically the next display frame.</p> 11837 * 11838 * <p>This method can be invoked from outside of the UI thread 11839 * only when this View is attached to a window.</p> 11840 * 11841 * @param left The left coordinate of the rectangle to invalidate. 11842 * @param top The top coordinate of the rectangle to invalidate. 11843 * @param right The right coordinate of the rectangle to invalidate. 11844 * @param bottom The bottom coordinate of the rectangle to invalidate. 11845 * 11846 * @see #invalidate(int, int, int, int) 11847 * @see #invalidate(Rect) 11848 */ 11849 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11850 // We try only with the AttachInfo because there's no point in invalidating 11851 // if we are not attached to our window 11852 final AttachInfo attachInfo = mAttachInfo; 11853 if (attachInfo != null) { 11854 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11855 info.target = this; 11856 info.left = left; 11857 info.top = top; 11858 info.right = right; 11859 info.bottom = bottom; 11860 11861 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11862 } 11863 } 11864 11865 /** 11866 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11867 * This event is sent at most once every 11868 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11869 */ 11870 private void postSendViewScrolledAccessibilityEventCallback() { 11871 if (mSendViewScrolledAccessibilityEvent == null) { 11872 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11873 } 11874 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11875 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11876 postDelayed(mSendViewScrolledAccessibilityEvent, 11877 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11878 } 11879 } 11880 11881 /** 11882 * Called by a parent to request that a child update its values for mScrollX 11883 * and mScrollY if necessary. This will typically be done if the child is 11884 * animating a scroll using a {@link android.widget.Scroller Scroller} 11885 * object. 11886 */ 11887 public void computeScroll() { 11888 } 11889 11890 /** 11891 * <p>Indicate whether the horizontal edges are faded when the view is 11892 * scrolled horizontally.</p> 11893 * 11894 * @return true if the horizontal edges should are faded on scroll, false 11895 * otherwise 11896 * 11897 * @see #setHorizontalFadingEdgeEnabled(boolean) 11898 * 11899 * @attr ref android.R.styleable#View_requiresFadingEdge 11900 */ 11901 public boolean isHorizontalFadingEdgeEnabled() { 11902 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11903 } 11904 11905 /** 11906 * <p>Define whether the horizontal edges should be faded when this view 11907 * is scrolled horizontally.</p> 11908 * 11909 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11910 * be faded when the view is scrolled 11911 * horizontally 11912 * 11913 * @see #isHorizontalFadingEdgeEnabled() 11914 * 11915 * @attr ref android.R.styleable#View_requiresFadingEdge 11916 */ 11917 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11918 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11919 if (horizontalFadingEdgeEnabled) { 11920 initScrollCache(); 11921 } 11922 11923 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11924 } 11925 } 11926 11927 /** 11928 * <p>Indicate whether the vertical edges are faded when the view is 11929 * scrolled horizontally.</p> 11930 * 11931 * @return true if the vertical edges should are faded on scroll, false 11932 * otherwise 11933 * 11934 * @see #setVerticalFadingEdgeEnabled(boolean) 11935 * 11936 * @attr ref android.R.styleable#View_requiresFadingEdge 11937 */ 11938 public boolean isVerticalFadingEdgeEnabled() { 11939 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11940 } 11941 11942 /** 11943 * <p>Define whether the vertical edges should be faded when this view 11944 * is scrolled vertically.</p> 11945 * 11946 * @param verticalFadingEdgeEnabled true if the vertical edges should 11947 * be faded when the view is scrolled 11948 * vertically 11949 * 11950 * @see #isVerticalFadingEdgeEnabled() 11951 * 11952 * @attr ref android.R.styleable#View_requiresFadingEdge 11953 */ 11954 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11955 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11956 if (verticalFadingEdgeEnabled) { 11957 initScrollCache(); 11958 } 11959 11960 mViewFlags ^= FADING_EDGE_VERTICAL; 11961 } 11962 } 11963 11964 /** 11965 * Returns the strength, or intensity, of the top faded edge. The strength is 11966 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11967 * returns 0.0 or 1.0 but no value in between. 11968 * 11969 * Subclasses should override this method to provide a smoother fade transition 11970 * when scrolling occurs. 11971 * 11972 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11973 */ 11974 protected float getTopFadingEdgeStrength() { 11975 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11976 } 11977 11978 /** 11979 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11980 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11981 * returns 0.0 or 1.0 but no value in between. 11982 * 11983 * Subclasses should override this method to provide a smoother fade transition 11984 * when scrolling occurs. 11985 * 11986 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11987 */ 11988 protected float getBottomFadingEdgeStrength() { 11989 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11990 computeVerticalScrollRange() ? 1.0f : 0.0f; 11991 } 11992 11993 /** 11994 * Returns the strength, or intensity, of the left faded edge. The strength is 11995 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11996 * returns 0.0 or 1.0 but no value in between. 11997 * 11998 * Subclasses should override this method to provide a smoother fade transition 11999 * when scrolling occurs. 12000 * 12001 * @return the intensity of the left fade as a float between 0.0f and 1.0f 12002 */ 12003 protected float getLeftFadingEdgeStrength() { 12004 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12005 } 12006 12007 /** 12008 * Returns the strength, or intensity, of the right faded edge. The strength is 12009 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12010 * returns 0.0 or 1.0 but no value in between. 12011 * 12012 * Subclasses should override this method to provide a smoother fade transition 12013 * when scrolling occurs. 12014 * 12015 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12016 */ 12017 protected float getRightFadingEdgeStrength() { 12018 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12019 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12020 } 12021 12022 /** 12023 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12024 * scrollbar is not drawn by default.</p> 12025 * 12026 * @return true if the horizontal scrollbar should be painted, false 12027 * otherwise 12028 * 12029 * @see #setHorizontalScrollBarEnabled(boolean) 12030 */ 12031 public boolean isHorizontalScrollBarEnabled() { 12032 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12033 } 12034 12035 /** 12036 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12037 * scrollbar is not drawn by default.</p> 12038 * 12039 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12040 * be painted 12041 * 12042 * @see #isHorizontalScrollBarEnabled() 12043 */ 12044 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12045 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12046 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12047 computeOpaqueFlags(); 12048 resolvePadding(); 12049 } 12050 } 12051 12052 /** 12053 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12054 * scrollbar is not drawn by default.</p> 12055 * 12056 * @return true if the vertical scrollbar should be painted, false 12057 * otherwise 12058 * 12059 * @see #setVerticalScrollBarEnabled(boolean) 12060 */ 12061 public boolean isVerticalScrollBarEnabled() { 12062 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12063 } 12064 12065 /** 12066 * <p>Define whether the vertical scrollbar should be drawn or not. The 12067 * scrollbar is not drawn by default.</p> 12068 * 12069 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12070 * be painted 12071 * 12072 * @see #isVerticalScrollBarEnabled() 12073 */ 12074 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12075 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12076 mViewFlags ^= SCROLLBARS_VERTICAL; 12077 computeOpaqueFlags(); 12078 resolvePadding(); 12079 } 12080 } 12081 12082 /** 12083 * @hide 12084 */ 12085 protected void recomputePadding() { 12086 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12087 } 12088 12089 /** 12090 * Define whether scrollbars will fade when the view is not scrolling. 12091 * 12092 * @param fadeScrollbars wheter to enable fading 12093 * 12094 * @attr ref android.R.styleable#View_fadeScrollbars 12095 */ 12096 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12097 initScrollCache(); 12098 final ScrollabilityCache scrollabilityCache = mScrollCache; 12099 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12100 if (fadeScrollbars) { 12101 scrollabilityCache.state = ScrollabilityCache.OFF; 12102 } else { 12103 scrollabilityCache.state = ScrollabilityCache.ON; 12104 } 12105 } 12106 12107 /** 12108 * 12109 * Returns true if scrollbars will fade when this view is not scrolling 12110 * 12111 * @return true if scrollbar fading is enabled 12112 * 12113 * @attr ref android.R.styleable#View_fadeScrollbars 12114 */ 12115 public boolean isScrollbarFadingEnabled() { 12116 return mScrollCache != null && mScrollCache.fadeScrollBars; 12117 } 12118 12119 /** 12120 * 12121 * Returns the delay before scrollbars fade. 12122 * 12123 * @return the delay before scrollbars fade 12124 * 12125 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12126 */ 12127 public int getScrollBarDefaultDelayBeforeFade() { 12128 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12129 mScrollCache.scrollBarDefaultDelayBeforeFade; 12130 } 12131 12132 /** 12133 * Define the delay before scrollbars fade. 12134 * 12135 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12136 * 12137 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12138 */ 12139 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12140 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12141 } 12142 12143 /** 12144 * 12145 * Returns the scrollbar fade duration. 12146 * 12147 * @return the scrollbar fade duration 12148 * 12149 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12150 */ 12151 public int getScrollBarFadeDuration() { 12152 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12153 mScrollCache.scrollBarFadeDuration; 12154 } 12155 12156 /** 12157 * Define the scrollbar fade duration. 12158 * 12159 * @param scrollBarFadeDuration - the scrollbar fade duration 12160 * 12161 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12162 */ 12163 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12164 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12165 } 12166 12167 /** 12168 * 12169 * Returns the scrollbar size. 12170 * 12171 * @return the scrollbar size 12172 * 12173 * @attr ref android.R.styleable#View_scrollbarSize 12174 */ 12175 public int getScrollBarSize() { 12176 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12177 mScrollCache.scrollBarSize; 12178 } 12179 12180 /** 12181 * Define the scrollbar size. 12182 * 12183 * @param scrollBarSize - the scrollbar size 12184 * 12185 * @attr ref android.R.styleable#View_scrollbarSize 12186 */ 12187 public void setScrollBarSize(int scrollBarSize) { 12188 getScrollCache().scrollBarSize = scrollBarSize; 12189 } 12190 12191 /** 12192 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12193 * inset. When inset, they add to the padding of the view. And the scrollbars 12194 * can be drawn inside the padding area or on the edge of the view. For example, 12195 * if a view has a background drawable and you want to draw the scrollbars 12196 * inside the padding specified by the drawable, you can use 12197 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12198 * appear at the edge of the view, ignoring the padding, then you can use 12199 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12200 * @param style the style of the scrollbars. Should be one of 12201 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12202 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12203 * @see #SCROLLBARS_INSIDE_OVERLAY 12204 * @see #SCROLLBARS_INSIDE_INSET 12205 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12206 * @see #SCROLLBARS_OUTSIDE_INSET 12207 * 12208 * @attr ref android.R.styleable#View_scrollbarStyle 12209 */ 12210 public void setScrollBarStyle(@ScrollBarStyle int style) { 12211 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12212 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12213 computeOpaqueFlags(); 12214 resolvePadding(); 12215 } 12216 } 12217 12218 /** 12219 * <p>Returns the current scrollbar style.</p> 12220 * @return the current scrollbar style 12221 * @see #SCROLLBARS_INSIDE_OVERLAY 12222 * @see #SCROLLBARS_INSIDE_INSET 12223 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12224 * @see #SCROLLBARS_OUTSIDE_INSET 12225 * 12226 * @attr ref android.R.styleable#View_scrollbarStyle 12227 */ 12228 @ViewDebug.ExportedProperty(mapping = { 12229 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12230 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12231 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12232 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12233 }) 12234 @ScrollBarStyle 12235 public int getScrollBarStyle() { 12236 return mViewFlags & SCROLLBARS_STYLE_MASK; 12237 } 12238 12239 /** 12240 * <p>Compute the horizontal range that the horizontal scrollbar 12241 * represents.</p> 12242 * 12243 * <p>The range is expressed in arbitrary units that must be the same as the 12244 * units used by {@link #computeHorizontalScrollExtent()} and 12245 * {@link #computeHorizontalScrollOffset()}.</p> 12246 * 12247 * <p>The default range is the drawing width of this view.</p> 12248 * 12249 * @return the total horizontal range represented by the horizontal 12250 * scrollbar 12251 * 12252 * @see #computeHorizontalScrollExtent() 12253 * @see #computeHorizontalScrollOffset() 12254 * @see android.widget.ScrollBarDrawable 12255 */ 12256 protected int computeHorizontalScrollRange() { 12257 return getWidth(); 12258 } 12259 12260 /** 12261 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12262 * within the horizontal range. This value is used to compute the position 12263 * of the thumb within the scrollbar's track.</p> 12264 * 12265 * <p>The range is expressed in arbitrary units that must be the same as the 12266 * units used by {@link #computeHorizontalScrollRange()} and 12267 * {@link #computeHorizontalScrollExtent()}.</p> 12268 * 12269 * <p>The default offset is the scroll offset of this view.</p> 12270 * 12271 * @return the horizontal offset of the scrollbar's thumb 12272 * 12273 * @see #computeHorizontalScrollRange() 12274 * @see #computeHorizontalScrollExtent() 12275 * @see android.widget.ScrollBarDrawable 12276 */ 12277 protected int computeHorizontalScrollOffset() { 12278 return mScrollX; 12279 } 12280 12281 /** 12282 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12283 * within the horizontal range. This value is used to compute the length 12284 * of the thumb within the scrollbar's track.</p> 12285 * 12286 * <p>The range is expressed in arbitrary units that must be the same as the 12287 * units used by {@link #computeHorizontalScrollRange()} and 12288 * {@link #computeHorizontalScrollOffset()}.</p> 12289 * 12290 * <p>The default extent is the drawing width of this view.</p> 12291 * 12292 * @return the horizontal extent of the scrollbar's thumb 12293 * 12294 * @see #computeHorizontalScrollRange() 12295 * @see #computeHorizontalScrollOffset() 12296 * @see android.widget.ScrollBarDrawable 12297 */ 12298 protected int computeHorizontalScrollExtent() { 12299 return getWidth(); 12300 } 12301 12302 /** 12303 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12304 * 12305 * <p>The range is expressed in arbitrary units that must be the same as the 12306 * units used by {@link #computeVerticalScrollExtent()} and 12307 * {@link #computeVerticalScrollOffset()}.</p> 12308 * 12309 * @return the total vertical range represented by the vertical scrollbar 12310 * 12311 * <p>The default range is the drawing height of this view.</p> 12312 * 12313 * @see #computeVerticalScrollExtent() 12314 * @see #computeVerticalScrollOffset() 12315 * @see android.widget.ScrollBarDrawable 12316 */ 12317 protected int computeVerticalScrollRange() { 12318 return getHeight(); 12319 } 12320 12321 /** 12322 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12323 * within the horizontal range. This value is used to compute the position 12324 * of the thumb within the scrollbar's track.</p> 12325 * 12326 * <p>The range is expressed in arbitrary units that must be the same as the 12327 * units used by {@link #computeVerticalScrollRange()} and 12328 * {@link #computeVerticalScrollExtent()}.</p> 12329 * 12330 * <p>The default offset is the scroll offset of this view.</p> 12331 * 12332 * @return the vertical offset of the scrollbar's thumb 12333 * 12334 * @see #computeVerticalScrollRange() 12335 * @see #computeVerticalScrollExtent() 12336 * @see android.widget.ScrollBarDrawable 12337 */ 12338 protected int computeVerticalScrollOffset() { 12339 return mScrollY; 12340 } 12341 12342 /** 12343 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12344 * within the vertical range. This value is used to compute the length 12345 * of the thumb within the scrollbar's track.</p> 12346 * 12347 * <p>The range is expressed in arbitrary units that must be the same as the 12348 * units used by {@link #computeVerticalScrollRange()} and 12349 * {@link #computeVerticalScrollOffset()}.</p> 12350 * 12351 * <p>The default extent is the drawing height of this view.</p> 12352 * 12353 * @return the vertical extent of the scrollbar's thumb 12354 * 12355 * @see #computeVerticalScrollRange() 12356 * @see #computeVerticalScrollOffset() 12357 * @see android.widget.ScrollBarDrawable 12358 */ 12359 protected int computeVerticalScrollExtent() { 12360 return getHeight(); 12361 } 12362 12363 /** 12364 * Check if this view can be scrolled horizontally in a certain direction. 12365 * 12366 * @param direction Negative to check scrolling left, positive to check scrolling right. 12367 * @return true if this view can be scrolled in the specified direction, false otherwise. 12368 */ 12369 public boolean canScrollHorizontally(int direction) { 12370 final int offset = computeHorizontalScrollOffset(); 12371 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12372 if (range == 0) return false; 12373 if (direction < 0) { 12374 return offset > 0; 12375 } else { 12376 return offset < range - 1; 12377 } 12378 } 12379 12380 /** 12381 * Check if this view can be scrolled vertically in a certain direction. 12382 * 12383 * @param direction Negative to check scrolling up, positive to check scrolling down. 12384 * @return true if this view can be scrolled in the specified direction, false otherwise. 12385 */ 12386 public boolean canScrollVertically(int direction) { 12387 final int offset = computeVerticalScrollOffset(); 12388 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12389 if (range == 0) return false; 12390 if (direction < 0) { 12391 return offset > 0; 12392 } else { 12393 return offset < range - 1; 12394 } 12395 } 12396 12397 /** 12398 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12399 * scrollbars are painted only if they have been awakened first.</p> 12400 * 12401 * @param canvas the canvas on which to draw the scrollbars 12402 * 12403 * @see #awakenScrollBars(int) 12404 */ 12405 protected final void onDrawScrollBars(Canvas canvas) { 12406 // scrollbars are drawn only when the animation is running 12407 final ScrollabilityCache cache = mScrollCache; 12408 if (cache != null) { 12409 12410 int state = cache.state; 12411 12412 if (state == ScrollabilityCache.OFF) { 12413 return; 12414 } 12415 12416 boolean invalidate = false; 12417 12418 if (state == ScrollabilityCache.FADING) { 12419 // We're fading -- get our fade interpolation 12420 if (cache.interpolatorValues == null) { 12421 cache.interpolatorValues = new float[1]; 12422 } 12423 12424 float[] values = cache.interpolatorValues; 12425 12426 // Stops the animation if we're done 12427 if (cache.scrollBarInterpolator.timeToValues(values) == 12428 Interpolator.Result.FREEZE_END) { 12429 cache.state = ScrollabilityCache.OFF; 12430 } else { 12431 cache.scrollBar.setAlpha(Math.round(values[0])); 12432 } 12433 12434 // This will make the scroll bars inval themselves after 12435 // drawing. We only want this when we're fading so that 12436 // we prevent excessive redraws 12437 invalidate = true; 12438 } else { 12439 // We're just on -- but we may have been fading before so 12440 // reset alpha 12441 cache.scrollBar.setAlpha(255); 12442 } 12443 12444 12445 final int viewFlags = mViewFlags; 12446 12447 final boolean drawHorizontalScrollBar = 12448 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12449 final boolean drawVerticalScrollBar = 12450 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12451 && !isVerticalScrollBarHidden(); 12452 12453 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12454 final int width = mRight - mLeft; 12455 final int height = mBottom - mTop; 12456 12457 final ScrollBarDrawable scrollBar = cache.scrollBar; 12458 12459 final int scrollX = mScrollX; 12460 final int scrollY = mScrollY; 12461 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12462 12463 int left; 12464 int top; 12465 int right; 12466 int bottom; 12467 12468 if (drawHorizontalScrollBar) { 12469 int size = scrollBar.getSize(false); 12470 if (size <= 0) { 12471 size = cache.scrollBarSize; 12472 } 12473 12474 scrollBar.setParameters(computeHorizontalScrollRange(), 12475 computeHorizontalScrollOffset(), 12476 computeHorizontalScrollExtent(), false); 12477 final int verticalScrollBarGap = drawVerticalScrollBar ? 12478 getVerticalScrollbarWidth() : 0; 12479 top = scrollY + height - size - (mUserPaddingBottom & inside); 12480 left = scrollX + (mPaddingLeft & inside); 12481 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12482 bottom = top + size; 12483 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12484 if (invalidate) { 12485 invalidate(left, top, right, bottom); 12486 } 12487 } 12488 12489 if (drawVerticalScrollBar) { 12490 int size = scrollBar.getSize(true); 12491 if (size <= 0) { 12492 size = cache.scrollBarSize; 12493 } 12494 12495 scrollBar.setParameters(computeVerticalScrollRange(), 12496 computeVerticalScrollOffset(), 12497 computeVerticalScrollExtent(), true); 12498 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12499 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12500 verticalScrollbarPosition = isLayoutRtl() ? 12501 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12502 } 12503 switch (verticalScrollbarPosition) { 12504 default: 12505 case SCROLLBAR_POSITION_RIGHT: 12506 left = scrollX + width - size - (mUserPaddingRight & inside); 12507 break; 12508 case SCROLLBAR_POSITION_LEFT: 12509 left = scrollX + (mUserPaddingLeft & inside); 12510 break; 12511 } 12512 top = scrollY + (mPaddingTop & inside); 12513 right = left + size; 12514 bottom = scrollY + height - (mUserPaddingBottom & inside); 12515 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12516 if (invalidate) { 12517 invalidate(left, top, right, bottom); 12518 } 12519 } 12520 } 12521 } 12522 } 12523 12524 /** 12525 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12526 * FastScroller is visible. 12527 * @return whether to temporarily hide the vertical scrollbar 12528 * @hide 12529 */ 12530 protected boolean isVerticalScrollBarHidden() { 12531 return false; 12532 } 12533 12534 /** 12535 * <p>Draw the horizontal scrollbar if 12536 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12537 * 12538 * @param canvas the canvas on which to draw the scrollbar 12539 * @param scrollBar the scrollbar's drawable 12540 * 12541 * @see #isHorizontalScrollBarEnabled() 12542 * @see #computeHorizontalScrollRange() 12543 * @see #computeHorizontalScrollExtent() 12544 * @see #computeHorizontalScrollOffset() 12545 * @see android.widget.ScrollBarDrawable 12546 * @hide 12547 */ 12548 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12549 int l, int t, int r, int b) { 12550 scrollBar.setBounds(l, t, r, b); 12551 scrollBar.draw(canvas); 12552 } 12553 12554 /** 12555 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12556 * returns true.</p> 12557 * 12558 * @param canvas the canvas on which to draw the scrollbar 12559 * @param scrollBar the scrollbar's drawable 12560 * 12561 * @see #isVerticalScrollBarEnabled() 12562 * @see #computeVerticalScrollRange() 12563 * @see #computeVerticalScrollExtent() 12564 * @see #computeVerticalScrollOffset() 12565 * @see android.widget.ScrollBarDrawable 12566 * @hide 12567 */ 12568 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12569 int l, int t, int r, int b) { 12570 scrollBar.setBounds(l, t, r, b); 12571 scrollBar.draw(canvas); 12572 } 12573 12574 /** 12575 * Implement this to do your drawing. 12576 * 12577 * @param canvas the canvas on which the background will be drawn 12578 */ 12579 protected void onDraw(Canvas canvas) { 12580 } 12581 12582 /* 12583 * Caller is responsible for calling requestLayout if necessary. 12584 * (This allows addViewInLayout to not request a new layout.) 12585 */ 12586 void assignParent(ViewParent parent) { 12587 if (mParent == null) { 12588 mParent = parent; 12589 } else if (parent == null) { 12590 mParent = null; 12591 } else { 12592 throw new RuntimeException("view " + this + " being added, but" 12593 + " it already has a parent"); 12594 } 12595 } 12596 12597 /** 12598 * This is called when the view is attached to a window. At this point it 12599 * has a Surface and will start drawing. Note that this function is 12600 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12601 * however it may be called any time before the first onDraw -- including 12602 * before or after {@link #onMeasure(int, int)}. 12603 * 12604 * @see #onDetachedFromWindow() 12605 */ 12606 protected void onAttachedToWindow() { 12607 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12608 mParent.requestTransparentRegion(this); 12609 } 12610 12611 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12612 initialAwakenScrollBars(); 12613 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12614 } 12615 12616 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12617 12618 jumpDrawablesToCurrentState(); 12619 12620 resetSubtreeAccessibilityStateChanged(); 12621 12622 if (isFocused()) { 12623 InputMethodManager imm = InputMethodManager.peekInstance(); 12624 imm.focusIn(this); 12625 } 12626 } 12627 12628 /** 12629 * Resolve all RTL related properties. 12630 * 12631 * @return true if resolution of RTL properties has been done 12632 * 12633 * @hide 12634 */ 12635 public boolean resolveRtlPropertiesIfNeeded() { 12636 if (!needRtlPropertiesResolution()) return false; 12637 12638 // Order is important here: LayoutDirection MUST be resolved first 12639 if (!isLayoutDirectionResolved()) { 12640 resolveLayoutDirection(); 12641 resolveLayoutParams(); 12642 } 12643 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12644 if (!isTextDirectionResolved()) { 12645 resolveTextDirection(); 12646 } 12647 if (!isTextAlignmentResolved()) { 12648 resolveTextAlignment(); 12649 } 12650 // Should resolve Drawables before Padding because we need the layout direction of the 12651 // Drawable to correctly resolve Padding. 12652 if (!isDrawablesResolved()) { 12653 resolveDrawables(); 12654 } 12655 if (!isPaddingResolved()) { 12656 resolvePadding(); 12657 } 12658 onRtlPropertiesChanged(getLayoutDirection()); 12659 return true; 12660 } 12661 12662 /** 12663 * Reset resolution of all RTL related properties. 12664 * 12665 * @hide 12666 */ 12667 public void resetRtlProperties() { 12668 resetResolvedLayoutDirection(); 12669 resetResolvedTextDirection(); 12670 resetResolvedTextAlignment(); 12671 resetResolvedPadding(); 12672 resetResolvedDrawables(); 12673 } 12674 12675 /** 12676 * @see #onScreenStateChanged(int) 12677 */ 12678 void dispatchScreenStateChanged(int screenState) { 12679 onScreenStateChanged(screenState); 12680 } 12681 12682 /** 12683 * This method is called whenever the state of the screen this view is 12684 * attached to changes. A state change will usually occurs when the screen 12685 * turns on or off (whether it happens automatically or the user does it 12686 * manually.) 12687 * 12688 * @param screenState The new state of the screen. Can be either 12689 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12690 */ 12691 public void onScreenStateChanged(int screenState) { 12692 } 12693 12694 /** 12695 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12696 */ 12697 private boolean hasRtlSupport() { 12698 return mContext.getApplicationInfo().hasRtlSupport(); 12699 } 12700 12701 /** 12702 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12703 * RTL not supported) 12704 */ 12705 private boolean isRtlCompatibilityMode() { 12706 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12707 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12708 } 12709 12710 /** 12711 * @return true if RTL properties need resolution. 12712 * 12713 */ 12714 private boolean needRtlPropertiesResolution() { 12715 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12716 } 12717 12718 /** 12719 * Called when any RTL property (layout direction or text direction or text alignment) has 12720 * been changed. 12721 * 12722 * Subclasses need to override this method to take care of cached information that depends on the 12723 * resolved layout direction, or to inform child views that inherit their layout direction. 12724 * 12725 * The default implementation does nothing. 12726 * 12727 * @param layoutDirection the direction of the layout 12728 * 12729 * @see #LAYOUT_DIRECTION_LTR 12730 * @see #LAYOUT_DIRECTION_RTL 12731 */ 12732 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12733 } 12734 12735 /** 12736 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12737 * that the parent directionality can and will be resolved before its children. 12738 * 12739 * @return true if resolution has been done, false otherwise. 12740 * 12741 * @hide 12742 */ 12743 public boolean resolveLayoutDirection() { 12744 // Clear any previous layout direction resolution 12745 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12746 12747 if (hasRtlSupport()) { 12748 // Set resolved depending on layout direction 12749 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12750 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12751 case LAYOUT_DIRECTION_INHERIT: 12752 // We cannot resolve yet. LTR is by default and let the resolution happen again 12753 // later to get the correct resolved value 12754 if (!canResolveLayoutDirection()) return false; 12755 12756 // Parent has not yet resolved, LTR is still the default 12757 try { 12758 if (!mParent.isLayoutDirectionResolved()) return false; 12759 12760 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12761 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12762 } 12763 } catch (AbstractMethodError e) { 12764 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12765 " does not fully implement ViewParent", e); 12766 } 12767 break; 12768 case LAYOUT_DIRECTION_RTL: 12769 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12770 break; 12771 case LAYOUT_DIRECTION_LOCALE: 12772 if((LAYOUT_DIRECTION_RTL == 12773 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12774 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12775 } 12776 break; 12777 default: 12778 // Nothing to do, LTR by default 12779 } 12780 } 12781 12782 // Set to resolved 12783 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12784 return true; 12785 } 12786 12787 /** 12788 * Check if layout direction resolution can be done. 12789 * 12790 * @return true if layout direction resolution can be done otherwise return false. 12791 */ 12792 public boolean canResolveLayoutDirection() { 12793 switch (getRawLayoutDirection()) { 12794 case LAYOUT_DIRECTION_INHERIT: 12795 if (mParent != null) { 12796 try { 12797 return mParent.canResolveLayoutDirection(); 12798 } catch (AbstractMethodError e) { 12799 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12800 " does not fully implement ViewParent", e); 12801 } 12802 } 12803 return false; 12804 12805 default: 12806 return true; 12807 } 12808 } 12809 12810 /** 12811 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12812 * {@link #onMeasure(int, int)}. 12813 * 12814 * @hide 12815 */ 12816 public void resetResolvedLayoutDirection() { 12817 // Reset the current resolved bits 12818 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12819 } 12820 12821 /** 12822 * @return true if the layout direction is inherited. 12823 * 12824 * @hide 12825 */ 12826 public boolean isLayoutDirectionInherited() { 12827 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12828 } 12829 12830 /** 12831 * @return true if layout direction has been resolved. 12832 */ 12833 public boolean isLayoutDirectionResolved() { 12834 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12835 } 12836 12837 /** 12838 * Return if padding has been resolved 12839 * 12840 * @hide 12841 */ 12842 boolean isPaddingResolved() { 12843 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12844 } 12845 12846 /** 12847 * Resolves padding depending on layout direction, if applicable, and 12848 * recomputes internal padding values to adjust for scroll bars. 12849 * 12850 * @hide 12851 */ 12852 public void resolvePadding() { 12853 final int resolvedLayoutDirection = getLayoutDirection(); 12854 12855 if (!isRtlCompatibilityMode()) { 12856 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12857 // If start / end padding are defined, they will be resolved (hence overriding) to 12858 // left / right or right / left depending on the resolved layout direction. 12859 // If start / end padding are not defined, use the left / right ones. 12860 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12861 Rect padding = sThreadLocal.get(); 12862 if (padding == null) { 12863 padding = new Rect(); 12864 sThreadLocal.set(padding); 12865 } 12866 mBackground.getPadding(padding); 12867 if (!mLeftPaddingDefined) { 12868 mUserPaddingLeftInitial = padding.left; 12869 } 12870 if (!mRightPaddingDefined) { 12871 mUserPaddingRightInitial = padding.right; 12872 } 12873 } 12874 switch (resolvedLayoutDirection) { 12875 case LAYOUT_DIRECTION_RTL: 12876 if (mUserPaddingStart != UNDEFINED_PADDING) { 12877 mUserPaddingRight = mUserPaddingStart; 12878 } else { 12879 mUserPaddingRight = mUserPaddingRightInitial; 12880 } 12881 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12882 mUserPaddingLeft = mUserPaddingEnd; 12883 } else { 12884 mUserPaddingLeft = mUserPaddingLeftInitial; 12885 } 12886 break; 12887 case LAYOUT_DIRECTION_LTR: 12888 default: 12889 if (mUserPaddingStart != UNDEFINED_PADDING) { 12890 mUserPaddingLeft = mUserPaddingStart; 12891 } else { 12892 mUserPaddingLeft = mUserPaddingLeftInitial; 12893 } 12894 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12895 mUserPaddingRight = mUserPaddingEnd; 12896 } else { 12897 mUserPaddingRight = mUserPaddingRightInitial; 12898 } 12899 } 12900 12901 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12902 } 12903 12904 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12905 onRtlPropertiesChanged(resolvedLayoutDirection); 12906 12907 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12908 } 12909 12910 /** 12911 * Reset the resolved layout direction. 12912 * 12913 * @hide 12914 */ 12915 public void resetResolvedPadding() { 12916 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12917 } 12918 12919 /** 12920 * This is called when the view is detached from a window. At this point it 12921 * no longer has a surface for drawing. 12922 * 12923 * @see #onAttachedToWindow() 12924 */ 12925 protected void onDetachedFromWindow() { 12926 } 12927 12928 /** 12929 * This is a framework-internal mirror of onDetachedFromWindow() that's called 12930 * after onDetachedFromWindow(). 12931 * 12932 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 12933 * The super method should be called at the end of the overriden method to ensure 12934 * subclasses are destroyed first 12935 * 12936 * @hide 12937 */ 12938 protected void onDetachedFromWindowInternal() { 12939 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12940 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12941 12942 removeUnsetPressCallback(); 12943 removeLongPressCallback(); 12944 removePerformClickCallback(); 12945 removeSendViewScrolledAccessibilityEventCallback(); 12946 stopNestedScroll(); 12947 12948 destroyDrawingCache(); 12949 12950 cleanupDraw(); 12951 mCurrentAnimation = null; 12952 } 12953 12954 private void cleanupDraw() { 12955 resetDisplayList(); 12956 if (mAttachInfo != null) { 12957 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12958 } 12959 } 12960 12961 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12962 } 12963 12964 /** 12965 * @return The number of times this view has been attached to a window 12966 */ 12967 protected int getWindowAttachCount() { 12968 return mWindowAttachCount; 12969 } 12970 12971 /** 12972 * Retrieve a unique token identifying the window this view is attached to. 12973 * @return Return the window's token for use in 12974 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 12975 */ 12976 public IBinder getWindowToken() { 12977 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 12978 } 12979 12980 /** 12981 * Retrieve the {@link WindowId} for the window this view is 12982 * currently attached to. 12983 */ 12984 public WindowId getWindowId() { 12985 if (mAttachInfo == null) { 12986 return null; 12987 } 12988 if (mAttachInfo.mWindowId == null) { 12989 try { 12990 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 12991 mAttachInfo.mWindowToken); 12992 mAttachInfo.mWindowId = new WindowId( 12993 mAttachInfo.mIWindowId); 12994 } catch (RemoteException e) { 12995 } 12996 } 12997 return mAttachInfo.mWindowId; 12998 } 12999 13000 /** 13001 * Retrieve a unique token identifying the top-level "real" window of 13002 * the window that this view is attached to. That is, this is like 13003 * {@link #getWindowToken}, except if the window this view in is a panel 13004 * window (attached to another containing window), then the token of 13005 * the containing window is returned instead. 13006 * 13007 * @return Returns the associated window token, either 13008 * {@link #getWindowToken()} or the containing window's token. 13009 */ 13010 public IBinder getApplicationWindowToken() { 13011 AttachInfo ai = mAttachInfo; 13012 if (ai != null) { 13013 IBinder appWindowToken = ai.mPanelParentWindowToken; 13014 if (appWindowToken == null) { 13015 appWindowToken = ai.mWindowToken; 13016 } 13017 return appWindowToken; 13018 } 13019 return null; 13020 } 13021 13022 /** 13023 * Gets the logical display to which the view's window has been attached. 13024 * 13025 * @return The logical display, or null if the view is not currently attached to a window. 13026 */ 13027 public Display getDisplay() { 13028 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13029 } 13030 13031 /** 13032 * Retrieve private session object this view hierarchy is using to 13033 * communicate with the window manager. 13034 * @return the session object to communicate with the window manager 13035 */ 13036 /*package*/ IWindowSession getWindowSession() { 13037 return mAttachInfo != null ? mAttachInfo.mSession : null; 13038 } 13039 13040 /** 13041 * @param info the {@link android.view.View.AttachInfo} to associated with 13042 * this view 13043 */ 13044 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13045 //System.out.println("Attached! " + this); 13046 mAttachInfo = info; 13047 if (mOverlay != null) { 13048 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13049 } 13050 mWindowAttachCount++; 13051 // We will need to evaluate the drawable state at least once. 13052 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13053 if (mFloatingTreeObserver != null) { 13054 info.mTreeObserver.merge(mFloatingTreeObserver); 13055 mFloatingTreeObserver = null; 13056 } 13057 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13058 mAttachInfo.mScrollContainers.add(this); 13059 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13060 } 13061 performCollectViewAttributes(mAttachInfo, visibility); 13062 onAttachedToWindow(); 13063 13064 ListenerInfo li = mListenerInfo; 13065 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13066 li != null ? li.mOnAttachStateChangeListeners : null; 13067 if (listeners != null && listeners.size() > 0) { 13068 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13069 // perform the dispatching. The iterator is a safe guard against listeners that 13070 // could mutate the list by calling the various add/remove methods. This prevents 13071 // the array from being modified while we iterate it. 13072 for (OnAttachStateChangeListener listener : listeners) { 13073 listener.onViewAttachedToWindow(this); 13074 } 13075 } 13076 13077 int vis = info.mWindowVisibility; 13078 if (vis != GONE) { 13079 onWindowVisibilityChanged(vis); 13080 } 13081 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13082 // If nobody has evaluated the drawable state yet, then do it now. 13083 refreshDrawableState(); 13084 } 13085 needGlobalAttributesUpdate(false); 13086 } 13087 13088 void dispatchDetachedFromWindow() { 13089 AttachInfo info = mAttachInfo; 13090 if (info != null) { 13091 int vis = info.mWindowVisibility; 13092 if (vis != GONE) { 13093 onWindowVisibilityChanged(GONE); 13094 } 13095 } 13096 13097 onDetachedFromWindow(); 13098 onDetachedFromWindowInternal(); 13099 13100 ListenerInfo li = mListenerInfo; 13101 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13102 li != null ? li.mOnAttachStateChangeListeners : null; 13103 if (listeners != null && listeners.size() > 0) { 13104 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13105 // perform the dispatching. The iterator is a safe guard against listeners that 13106 // could mutate the list by calling the various add/remove methods. This prevents 13107 // the array from being modified while we iterate it. 13108 for (OnAttachStateChangeListener listener : listeners) { 13109 listener.onViewDetachedFromWindow(this); 13110 } 13111 } 13112 13113 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13114 mAttachInfo.mScrollContainers.remove(this); 13115 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13116 } 13117 13118 mAttachInfo = null; 13119 if (mOverlay != null) { 13120 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13121 } 13122 } 13123 13124 /** 13125 * Cancel any deferred high-level input events that were previously posted to the event queue. 13126 * 13127 * <p>Many views post high-level events such as click handlers to the event queue 13128 * to run deferred in order to preserve a desired user experience - clearing visible 13129 * pressed states before executing, etc. This method will abort any events of this nature 13130 * that are currently in flight.</p> 13131 * 13132 * <p>Custom views that generate their own high-level deferred input events should override 13133 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13134 * 13135 * <p>This will also cancel pending input events for any child views.</p> 13136 * 13137 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13138 * This will not impact newer events posted after this call that may occur as a result of 13139 * lower-level input events still waiting in the queue. If you are trying to prevent 13140 * double-submitted events for the duration of some sort of asynchronous transaction 13141 * you should also take other steps to protect against unexpected double inputs e.g. calling 13142 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13143 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13144 */ 13145 public final void cancelPendingInputEvents() { 13146 dispatchCancelPendingInputEvents(); 13147 } 13148 13149 /** 13150 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13151 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13152 */ 13153 void dispatchCancelPendingInputEvents() { 13154 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13155 onCancelPendingInputEvents(); 13156 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13157 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13158 " did not call through to super.onCancelPendingInputEvents()"); 13159 } 13160 } 13161 13162 /** 13163 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13164 * a parent view. 13165 * 13166 * <p>This method is responsible for removing any pending high-level input events that were 13167 * posted to the event queue to run later. Custom view classes that post their own deferred 13168 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13169 * {@link android.os.Handler} should override this method, call 13170 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13171 * </p> 13172 */ 13173 public void onCancelPendingInputEvents() { 13174 removePerformClickCallback(); 13175 cancelLongPress(); 13176 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13177 } 13178 13179 /** 13180 * Store this view hierarchy's frozen state into the given container. 13181 * 13182 * @param container The SparseArray in which to save the view's state. 13183 * 13184 * @see #restoreHierarchyState(android.util.SparseArray) 13185 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13186 * @see #onSaveInstanceState() 13187 */ 13188 public void saveHierarchyState(SparseArray<Parcelable> container) { 13189 dispatchSaveInstanceState(container); 13190 } 13191 13192 /** 13193 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13194 * this view and its children. May be overridden to modify how freezing happens to a 13195 * view's children; for example, some views may want to not store state for their children. 13196 * 13197 * @param container The SparseArray in which to save the view's state. 13198 * 13199 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13200 * @see #saveHierarchyState(android.util.SparseArray) 13201 * @see #onSaveInstanceState() 13202 */ 13203 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13204 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13205 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13206 Parcelable state = onSaveInstanceState(); 13207 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13208 throw new IllegalStateException( 13209 "Derived class did not call super.onSaveInstanceState()"); 13210 } 13211 if (state != null) { 13212 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13213 // + ": " + state); 13214 container.put(mID, state); 13215 } 13216 } 13217 } 13218 13219 /** 13220 * Hook allowing a view to generate a representation of its internal state 13221 * that can later be used to create a new instance with that same state. 13222 * This state should only contain information that is not persistent or can 13223 * not be reconstructed later. For example, you will never store your 13224 * current position on screen because that will be computed again when a 13225 * new instance of the view is placed in its view hierarchy. 13226 * <p> 13227 * Some examples of things you may store here: the current cursor position 13228 * in a text view (but usually not the text itself since that is stored in a 13229 * content provider or other persistent storage), the currently selected 13230 * item in a list view. 13231 * 13232 * @return Returns a Parcelable object containing the view's current dynamic 13233 * state, or null if there is nothing interesting to save. The 13234 * default implementation returns null. 13235 * @see #onRestoreInstanceState(android.os.Parcelable) 13236 * @see #saveHierarchyState(android.util.SparseArray) 13237 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13238 * @see #setSaveEnabled(boolean) 13239 */ 13240 protected Parcelable onSaveInstanceState() { 13241 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13242 return BaseSavedState.EMPTY_STATE; 13243 } 13244 13245 /** 13246 * Restore this view hierarchy's frozen state from the given container. 13247 * 13248 * @param container The SparseArray which holds previously frozen states. 13249 * 13250 * @see #saveHierarchyState(android.util.SparseArray) 13251 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13252 * @see #onRestoreInstanceState(android.os.Parcelable) 13253 */ 13254 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13255 dispatchRestoreInstanceState(container); 13256 } 13257 13258 /** 13259 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13260 * state for this view and its children. May be overridden to modify how restoring 13261 * happens to a view's children; for example, some views may want to not store state 13262 * for their children. 13263 * 13264 * @param container The SparseArray which holds previously saved state. 13265 * 13266 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13267 * @see #restoreHierarchyState(android.util.SparseArray) 13268 * @see #onRestoreInstanceState(android.os.Parcelable) 13269 */ 13270 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13271 if (mID != NO_ID) { 13272 Parcelable state = container.get(mID); 13273 if (state != null) { 13274 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13275 // + ": " + state); 13276 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13277 onRestoreInstanceState(state); 13278 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13279 throw new IllegalStateException( 13280 "Derived class did not call super.onRestoreInstanceState()"); 13281 } 13282 } 13283 } 13284 } 13285 13286 /** 13287 * Hook allowing a view to re-apply a representation of its internal state that had previously 13288 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13289 * null state. 13290 * 13291 * @param state The frozen state that had previously been returned by 13292 * {@link #onSaveInstanceState}. 13293 * 13294 * @see #onSaveInstanceState() 13295 * @see #restoreHierarchyState(android.util.SparseArray) 13296 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13297 */ 13298 protected void onRestoreInstanceState(Parcelable state) { 13299 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13300 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13301 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13302 + "received " + state.getClass().toString() + " instead. This usually happens " 13303 + "when two views of different type have the same id in the same hierarchy. " 13304 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13305 + "other views do not use the same id."); 13306 } 13307 } 13308 13309 /** 13310 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13311 * 13312 * @return the drawing start time in milliseconds 13313 */ 13314 public long getDrawingTime() { 13315 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13316 } 13317 13318 /** 13319 * <p>Enables or disables the duplication of the parent's state into this view. When 13320 * duplication is enabled, this view gets its drawable state from its parent rather 13321 * than from its own internal properties.</p> 13322 * 13323 * <p>Note: in the current implementation, setting this property to true after the 13324 * view was added to a ViewGroup might have no effect at all. This property should 13325 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13326 * 13327 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13328 * property is enabled, an exception will be thrown.</p> 13329 * 13330 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13331 * parent, these states should not be affected by this method.</p> 13332 * 13333 * @param enabled True to enable duplication of the parent's drawable state, false 13334 * to disable it. 13335 * 13336 * @see #getDrawableState() 13337 * @see #isDuplicateParentStateEnabled() 13338 */ 13339 public void setDuplicateParentStateEnabled(boolean enabled) { 13340 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13341 } 13342 13343 /** 13344 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13345 * 13346 * @return True if this view's drawable state is duplicated from the parent, 13347 * false otherwise 13348 * 13349 * @see #getDrawableState() 13350 * @see #setDuplicateParentStateEnabled(boolean) 13351 */ 13352 public boolean isDuplicateParentStateEnabled() { 13353 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13354 } 13355 13356 /** 13357 * <p>Specifies the type of layer backing this view. The layer can be 13358 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13359 * {@link #LAYER_TYPE_HARDWARE}.</p> 13360 * 13361 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13362 * instance that controls how the layer is composed on screen. The following 13363 * properties of the paint are taken into account when composing the layer:</p> 13364 * <ul> 13365 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13366 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13367 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13368 * </ul> 13369 * 13370 * <p>If this view has an alpha value set to < 1.0 by calling 13371 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13372 * by this view's alpha value.</p> 13373 * 13374 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13375 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13376 * for more information on when and how to use layers.</p> 13377 * 13378 * @param layerType The type of layer to use with this view, must be one of 13379 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13380 * {@link #LAYER_TYPE_HARDWARE} 13381 * @param paint The paint used to compose the layer. This argument is optional 13382 * and can be null. It is ignored when the layer type is 13383 * {@link #LAYER_TYPE_NONE} 13384 * 13385 * @see #getLayerType() 13386 * @see #LAYER_TYPE_NONE 13387 * @see #LAYER_TYPE_SOFTWARE 13388 * @see #LAYER_TYPE_HARDWARE 13389 * @see #setAlpha(float) 13390 * 13391 * @attr ref android.R.styleable#View_layerType 13392 */ 13393 public void setLayerType(int layerType, Paint paint) { 13394 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13395 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13396 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13397 } 13398 13399 boolean typeChanged = mRenderNode.setLayerType(layerType); 13400 13401 if (!typeChanged) { 13402 setLayerPaint(paint); 13403 return; 13404 } 13405 13406 // Destroy any previous software drawing cache if needed 13407 if (mLayerType == LAYER_TYPE_SOFTWARE) { 13408 destroyDrawingCache(); 13409 } 13410 13411 mLayerType = layerType; 13412 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 13413 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13414 mRenderNode.setLayerPaint(mLayerPaint); 13415 13416 // draw() behaves differently if we are on a layer, so we need to 13417 // invalidate() here 13418 invalidateParentCaches(); 13419 invalidate(true); 13420 } 13421 13422 /** 13423 * Updates the {@link Paint} object used with the current layer (used only if the current 13424 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13425 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13426 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13427 * ensure that the view gets redrawn immediately. 13428 * 13429 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13430 * instance that controls how the layer is composed on screen. The following 13431 * properties of the paint are taken into account when composing the layer:</p> 13432 * <ul> 13433 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13434 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13435 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13436 * </ul> 13437 * 13438 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13439 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13440 * 13441 * @param paint The paint used to compose the layer. This argument is optional 13442 * and can be null. It is ignored when the layer type is 13443 * {@link #LAYER_TYPE_NONE} 13444 * 13445 * @see #setLayerType(int, android.graphics.Paint) 13446 */ 13447 public void setLayerPaint(Paint paint) { 13448 int layerType = getLayerType(); 13449 if (layerType != LAYER_TYPE_NONE) { 13450 mLayerPaint = paint == null ? new Paint() : paint; 13451 if (layerType == LAYER_TYPE_HARDWARE) { 13452 if (mRenderNode.setLayerPaint(mLayerPaint)) { 13453 invalidateViewProperty(false, false); 13454 } 13455 } else { 13456 invalidate(); 13457 } 13458 } 13459 } 13460 13461 /** 13462 * Indicates whether this view has a static layer. A view with layer type 13463 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13464 * dynamic. 13465 */ 13466 boolean hasStaticLayer() { 13467 return true; 13468 } 13469 13470 /** 13471 * Indicates what type of layer is currently associated with this view. By default 13472 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13473 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13474 * for more information on the different types of layers. 13475 * 13476 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13477 * {@link #LAYER_TYPE_HARDWARE} 13478 * 13479 * @see #setLayerType(int, android.graphics.Paint) 13480 * @see #buildLayer() 13481 * @see #LAYER_TYPE_NONE 13482 * @see #LAYER_TYPE_SOFTWARE 13483 * @see #LAYER_TYPE_HARDWARE 13484 */ 13485 public int getLayerType() { 13486 return mLayerType; 13487 } 13488 13489 /** 13490 * Forces this view's layer to be created and this view to be rendered 13491 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13492 * invoking this method will have no effect. 13493 * 13494 * This method can for instance be used to render a view into its layer before 13495 * starting an animation. If this view is complex, rendering into the layer 13496 * before starting the animation will avoid skipping frames. 13497 * 13498 * @throws IllegalStateException If this view is not attached to a window 13499 * 13500 * @see #setLayerType(int, android.graphics.Paint) 13501 */ 13502 public void buildLayer() { 13503 if (mLayerType == LAYER_TYPE_NONE) return; 13504 13505 final AttachInfo attachInfo = mAttachInfo; 13506 if (attachInfo == null) { 13507 throw new IllegalStateException("This view must be attached to a window first"); 13508 } 13509 13510 if (getWidth() == 0 || getHeight() == 0) { 13511 return; 13512 } 13513 13514 switch (mLayerType) { 13515 case LAYER_TYPE_HARDWARE: 13516 // The only part of a hardware layer we can build in response to 13517 // this call is to ensure the display list is up to date. 13518 // The actual rendering of the display list into the layer must 13519 // be done at playback time 13520 updateDisplayListIfDirty(); 13521 break; 13522 case LAYER_TYPE_SOFTWARE: 13523 buildDrawingCache(true); 13524 break; 13525 } 13526 } 13527 13528 /** 13529 * If this View draws with a HardwareLayer, returns it. 13530 * Otherwise returns null 13531 * 13532 * TODO: Only TextureView uses this, can we eliminate it? 13533 */ 13534 HardwareLayer getHardwareLayer() { 13535 return null; 13536 } 13537 13538 /** 13539 * Destroys all hardware rendering resources. This method is invoked 13540 * when the system needs to reclaim resources. Upon execution of this 13541 * method, you should free any OpenGL resources created by the view. 13542 * 13543 * Note: you <strong>must</strong> call 13544 * <code>super.destroyHardwareResources()</code> when overriding 13545 * this method. 13546 * 13547 * @hide 13548 */ 13549 protected void destroyHardwareResources() { 13550 resetDisplayList(); 13551 } 13552 13553 /** 13554 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13555 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13556 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13557 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13558 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13559 * null.</p> 13560 * 13561 * <p>Enabling the drawing cache is similar to 13562 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13563 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13564 * drawing cache has no effect on rendering because the system uses a different mechanism 13565 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13566 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13567 * for information on how to enable software and hardware layers.</p> 13568 * 13569 * <p>This API can be used to manually generate 13570 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13571 * {@link #getDrawingCache()}.</p> 13572 * 13573 * @param enabled true to enable the drawing cache, false otherwise 13574 * 13575 * @see #isDrawingCacheEnabled() 13576 * @see #getDrawingCache() 13577 * @see #buildDrawingCache() 13578 * @see #setLayerType(int, android.graphics.Paint) 13579 */ 13580 public void setDrawingCacheEnabled(boolean enabled) { 13581 mCachingFailed = false; 13582 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13583 } 13584 13585 /** 13586 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13587 * 13588 * @return true if the drawing cache is enabled 13589 * 13590 * @see #setDrawingCacheEnabled(boolean) 13591 * @see #getDrawingCache() 13592 */ 13593 @ViewDebug.ExportedProperty(category = "drawing") 13594 public boolean isDrawingCacheEnabled() { 13595 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13596 } 13597 13598 /** 13599 * Debugging utility which recursively outputs the dirty state of a view and its 13600 * descendants. 13601 * 13602 * @hide 13603 */ 13604 @SuppressWarnings({"UnusedDeclaration"}) 13605 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13606 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13607 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13608 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13609 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13610 if (clear) { 13611 mPrivateFlags &= clearMask; 13612 } 13613 if (this instanceof ViewGroup) { 13614 ViewGroup parent = (ViewGroup) this; 13615 final int count = parent.getChildCount(); 13616 for (int i = 0; i < count; i++) { 13617 final View child = parent.getChildAt(i); 13618 child.outputDirtyFlags(indent + " ", clear, clearMask); 13619 } 13620 } 13621 } 13622 13623 /** 13624 * This method is used by ViewGroup to cause its children to restore or recreate their 13625 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13626 * to recreate its own display list, which would happen if it went through the normal 13627 * draw/dispatchDraw mechanisms. 13628 * 13629 * @hide 13630 */ 13631 protected void dispatchGetDisplayList() {} 13632 13633 /** 13634 * A view that is not attached or hardware accelerated cannot create a display list. 13635 * This method checks these conditions and returns the appropriate result. 13636 * 13637 * @return true if view has the ability to create a display list, false otherwise. 13638 * 13639 * @hide 13640 */ 13641 public boolean canHaveDisplayList() { 13642 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13643 } 13644 13645 private void updateDisplayListIfDirty() { 13646 final RenderNode renderNode = mRenderNode; 13647 if (!canHaveDisplayList()) { 13648 // can't populate RenderNode, don't try 13649 return; 13650 } 13651 13652 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13653 || !renderNode.isValid() 13654 || (mRecreateDisplayList)) { 13655 // Don't need to recreate the display list, just need to tell our 13656 // children to restore/recreate theirs 13657 if (renderNode.isValid() 13658 && !mRecreateDisplayList) { 13659 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13660 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13661 dispatchGetDisplayList(); 13662 13663 return; // no work needed 13664 } 13665 13666 // If we got here, we're recreating it. Mark it as such to ensure that 13667 // we copy in child display lists into ours in drawChild() 13668 mRecreateDisplayList = true; 13669 13670 int width = mRight - mLeft; 13671 int height = mBottom - mTop; 13672 int layerType = getLayerType(); 13673 13674 final HardwareCanvas canvas = renderNode.start(width, height); 13675 13676 try { 13677 final HardwareLayer layer = getHardwareLayer(); 13678 if (layer != null && layer.isValid()) { 13679 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13680 } else if (layerType == LAYER_TYPE_SOFTWARE) { 13681 buildDrawingCache(true); 13682 Bitmap cache = getDrawingCache(true); 13683 if (cache != null) { 13684 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13685 } 13686 } else { 13687 computeScroll(); 13688 13689 canvas.translate(-mScrollX, -mScrollY); 13690 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13691 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13692 13693 // Fast path for layouts with no backgrounds 13694 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13695 dispatchDraw(canvas); 13696 if (mOverlay != null && !mOverlay.isEmpty()) { 13697 mOverlay.getOverlayView().draw(canvas); 13698 } 13699 } else { 13700 draw(canvas); 13701 } 13702 } 13703 } finally { 13704 renderNode.end(canvas); 13705 setDisplayListProperties(renderNode); 13706 } 13707 } else { 13708 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13709 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13710 } 13711 } 13712 13713 /** 13714 * Returns a RenderNode with View draw content recorded, which can be 13715 * used to draw this view again without executing its draw method. 13716 * 13717 * @return A RenderNode ready to replay, or null if caching is not enabled. 13718 * 13719 * @hide 13720 */ 13721 public RenderNode getDisplayList() { 13722 updateDisplayListIfDirty(); 13723 return mRenderNode; 13724 } 13725 13726 private void resetDisplayList() { 13727 if (mRenderNode.isValid()) { 13728 mRenderNode.destroyDisplayListData(); 13729 } 13730 13731 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 13732 mBackgroundRenderNode.destroyDisplayListData(); 13733 } 13734 } 13735 13736 /** 13737 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13738 * 13739 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13740 * 13741 * @see #getDrawingCache(boolean) 13742 */ 13743 public Bitmap getDrawingCache() { 13744 return getDrawingCache(false); 13745 } 13746 13747 /** 13748 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13749 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13750 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13751 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13752 * request the drawing cache by calling this method and draw it on screen if the 13753 * returned bitmap is not null.</p> 13754 * 13755 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13756 * this method will create a bitmap of the same size as this view. Because this bitmap 13757 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13758 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13759 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13760 * size than the view. This implies that your application must be able to handle this 13761 * size.</p> 13762 * 13763 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13764 * the current density of the screen when the application is in compatibility 13765 * mode. 13766 * 13767 * @return A bitmap representing this view or null if cache is disabled. 13768 * 13769 * @see #setDrawingCacheEnabled(boolean) 13770 * @see #isDrawingCacheEnabled() 13771 * @see #buildDrawingCache(boolean) 13772 * @see #destroyDrawingCache() 13773 */ 13774 public Bitmap getDrawingCache(boolean autoScale) { 13775 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13776 return null; 13777 } 13778 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13779 buildDrawingCache(autoScale); 13780 } 13781 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13782 } 13783 13784 /** 13785 * <p>Frees the resources used by the drawing cache. If you call 13786 * {@link #buildDrawingCache()} manually without calling 13787 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13788 * should cleanup the cache with this method afterwards.</p> 13789 * 13790 * @see #setDrawingCacheEnabled(boolean) 13791 * @see #buildDrawingCache() 13792 * @see #getDrawingCache() 13793 */ 13794 public void destroyDrawingCache() { 13795 if (mDrawingCache != null) { 13796 mDrawingCache.recycle(); 13797 mDrawingCache = null; 13798 } 13799 if (mUnscaledDrawingCache != null) { 13800 mUnscaledDrawingCache.recycle(); 13801 mUnscaledDrawingCache = null; 13802 } 13803 } 13804 13805 /** 13806 * Setting a solid background color for the drawing cache's bitmaps will improve 13807 * performance and memory usage. Note, though that this should only be used if this 13808 * view will always be drawn on top of a solid color. 13809 * 13810 * @param color The background color to use for the drawing cache's bitmap 13811 * 13812 * @see #setDrawingCacheEnabled(boolean) 13813 * @see #buildDrawingCache() 13814 * @see #getDrawingCache() 13815 */ 13816 public void setDrawingCacheBackgroundColor(int color) { 13817 if (color != mDrawingCacheBackgroundColor) { 13818 mDrawingCacheBackgroundColor = color; 13819 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13820 } 13821 } 13822 13823 /** 13824 * @see #setDrawingCacheBackgroundColor(int) 13825 * 13826 * @return The background color to used for the drawing cache's bitmap 13827 */ 13828 public int getDrawingCacheBackgroundColor() { 13829 return mDrawingCacheBackgroundColor; 13830 } 13831 13832 /** 13833 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13834 * 13835 * @see #buildDrawingCache(boolean) 13836 */ 13837 public void buildDrawingCache() { 13838 buildDrawingCache(false); 13839 } 13840 13841 /** 13842 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13843 * 13844 * <p>If you call {@link #buildDrawingCache()} manually without calling 13845 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13846 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13847 * 13848 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13849 * this method will create a bitmap of the same size as this view. Because this bitmap 13850 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13851 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13852 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13853 * size than the view. This implies that your application must be able to handle this 13854 * size.</p> 13855 * 13856 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13857 * you do not need the drawing cache bitmap, calling this method will increase memory 13858 * usage and cause the view to be rendered in software once, thus negatively impacting 13859 * performance.</p> 13860 * 13861 * @see #getDrawingCache() 13862 * @see #destroyDrawingCache() 13863 */ 13864 public void buildDrawingCache(boolean autoScale) { 13865 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13866 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13867 mCachingFailed = false; 13868 13869 int width = mRight - mLeft; 13870 int height = mBottom - mTop; 13871 13872 final AttachInfo attachInfo = mAttachInfo; 13873 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13874 13875 if (autoScale && scalingRequired) { 13876 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13877 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13878 } 13879 13880 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13881 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13882 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13883 13884 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13885 final long drawingCacheSize = 13886 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13887 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13888 if (width > 0 && height > 0) { 13889 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13890 + projectedBitmapSize + " bytes, only " 13891 + drawingCacheSize + " available"); 13892 } 13893 destroyDrawingCache(); 13894 mCachingFailed = true; 13895 return; 13896 } 13897 13898 boolean clear = true; 13899 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13900 13901 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13902 Bitmap.Config quality; 13903 if (!opaque) { 13904 // Never pick ARGB_4444 because it looks awful 13905 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13906 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13907 case DRAWING_CACHE_QUALITY_AUTO: 13908 case DRAWING_CACHE_QUALITY_LOW: 13909 case DRAWING_CACHE_QUALITY_HIGH: 13910 default: 13911 quality = Bitmap.Config.ARGB_8888; 13912 break; 13913 } 13914 } else { 13915 // Optimization for translucent windows 13916 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13917 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13918 } 13919 13920 // Try to cleanup memory 13921 if (bitmap != null) bitmap.recycle(); 13922 13923 try { 13924 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13925 width, height, quality); 13926 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 13927 if (autoScale) { 13928 mDrawingCache = bitmap; 13929 } else { 13930 mUnscaledDrawingCache = bitmap; 13931 } 13932 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 13933 } catch (OutOfMemoryError e) { 13934 // If there is not enough memory to create the bitmap cache, just 13935 // ignore the issue as bitmap caches are not required to draw the 13936 // view hierarchy 13937 if (autoScale) { 13938 mDrawingCache = null; 13939 } else { 13940 mUnscaledDrawingCache = null; 13941 } 13942 mCachingFailed = true; 13943 return; 13944 } 13945 13946 clear = drawingCacheBackgroundColor != 0; 13947 } 13948 13949 Canvas canvas; 13950 if (attachInfo != null) { 13951 canvas = attachInfo.mCanvas; 13952 if (canvas == null) { 13953 canvas = new Canvas(); 13954 } 13955 canvas.setBitmap(bitmap); 13956 // Temporarily clobber the cached Canvas in case one of our children 13957 // is also using a drawing cache. Without this, the children would 13958 // steal the canvas by attaching their own bitmap to it and bad, bad 13959 // thing would happen (invisible views, corrupted drawings, etc.) 13960 attachInfo.mCanvas = null; 13961 } else { 13962 // This case should hopefully never or seldom happen 13963 canvas = new Canvas(bitmap); 13964 } 13965 13966 if (clear) { 13967 bitmap.eraseColor(drawingCacheBackgroundColor); 13968 } 13969 13970 computeScroll(); 13971 final int restoreCount = canvas.save(); 13972 13973 if (autoScale && scalingRequired) { 13974 final float scale = attachInfo.mApplicationScale; 13975 canvas.scale(scale, scale); 13976 } 13977 13978 canvas.translate(-mScrollX, -mScrollY); 13979 13980 mPrivateFlags |= PFLAG_DRAWN; 13981 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 13982 mLayerType != LAYER_TYPE_NONE) { 13983 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 13984 } 13985 13986 // Fast path for layouts with no backgrounds 13987 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13988 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13989 dispatchDraw(canvas); 13990 if (mOverlay != null && !mOverlay.isEmpty()) { 13991 mOverlay.getOverlayView().draw(canvas); 13992 } 13993 } else { 13994 draw(canvas); 13995 } 13996 13997 canvas.restoreToCount(restoreCount); 13998 canvas.setBitmap(null); 13999 14000 if (attachInfo != null) { 14001 // Restore the cached Canvas for our siblings 14002 attachInfo.mCanvas = canvas; 14003 } 14004 } 14005 } 14006 14007 /** 14008 * Create a snapshot of the view into a bitmap. We should probably make 14009 * some form of this public, but should think about the API. 14010 */ 14011 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14012 int width = mRight - mLeft; 14013 int height = mBottom - mTop; 14014 14015 final AttachInfo attachInfo = mAttachInfo; 14016 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14017 width = (int) ((width * scale) + 0.5f); 14018 height = (int) ((height * scale) + 0.5f); 14019 14020 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14021 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14022 if (bitmap == null) { 14023 throw new OutOfMemoryError(); 14024 } 14025 14026 Resources resources = getResources(); 14027 if (resources != null) { 14028 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14029 } 14030 14031 Canvas canvas; 14032 if (attachInfo != null) { 14033 canvas = attachInfo.mCanvas; 14034 if (canvas == null) { 14035 canvas = new Canvas(); 14036 } 14037 canvas.setBitmap(bitmap); 14038 // Temporarily clobber the cached Canvas in case one of our children 14039 // is also using a drawing cache. Without this, the children would 14040 // steal the canvas by attaching their own bitmap to it and bad, bad 14041 // things would happen (invisible views, corrupted drawings, etc.) 14042 attachInfo.mCanvas = null; 14043 } else { 14044 // This case should hopefully never or seldom happen 14045 canvas = new Canvas(bitmap); 14046 } 14047 14048 if ((backgroundColor & 0xff000000) != 0) { 14049 bitmap.eraseColor(backgroundColor); 14050 } 14051 14052 computeScroll(); 14053 final int restoreCount = canvas.save(); 14054 canvas.scale(scale, scale); 14055 canvas.translate(-mScrollX, -mScrollY); 14056 14057 // Temporarily remove the dirty mask 14058 int flags = mPrivateFlags; 14059 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14060 14061 // Fast path for layouts with no backgrounds 14062 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14063 dispatchDraw(canvas); 14064 if (mOverlay != null && !mOverlay.isEmpty()) { 14065 mOverlay.getOverlayView().draw(canvas); 14066 } 14067 } else { 14068 draw(canvas); 14069 } 14070 14071 mPrivateFlags = flags; 14072 14073 canvas.restoreToCount(restoreCount); 14074 canvas.setBitmap(null); 14075 14076 if (attachInfo != null) { 14077 // Restore the cached Canvas for our siblings 14078 attachInfo.mCanvas = canvas; 14079 } 14080 14081 return bitmap; 14082 } 14083 14084 /** 14085 * Indicates whether this View is currently in edit mode. A View is usually 14086 * in edit mode when displayed within a developer tool. For instance, if 14087 * this View is being drawn by a visual user interface builder, this method 14088 * should return true. 14089 * 14090 * Subclasses should check the return value of this method to provide 14091 * different behaviors if their normal behavior might interfere with the 14092 * host environment. For instance: the class spawns a thread in its 14093 * constructor, the drawing code relies on device-specific features, etc. 14094 * 14095 * This method is usually checked in the drawing code of custom widgets. 14096 * 14097 * @return True if this View is in edit mode, false otherwise. 14098 */ 14099 public boolean isInEditMode() { 14100 return false; 14101 } 14102 14103 /** 14104 * If the View draws content inside its padding and enables fading edges, 14105 * it needs to support padding offsets. Padding offsets are added to the 14106 * fading edges to extend the length of the fade so that it covers pixels 14107 * drawn inside the padding. 14108 * 14109 * Subclasses of this class should override this method if they need 14110 * to draw content inside the padding. 14111 * 14112 * @return True if padding offset must be applied, false otherwise. 14113 * 14114 * @see #getLeftPaddingOffset() 14115 * @see #getRightPaddingOffset() 14116 * @see #getTopPaddingOffset() 14117 * @see #getBottomPaddingOffset() 14118 * 14119 * @since CURRENT 14120 */ 14121 protected boolean isPaddingOffsetRequired() { 14122 return false; 14123 } 14124 14125 /** 14126 * Amount by which to extend the left fading region. Called only when 14127 * {@link #isPaddingOffsetRequired()} returns true. 14128 * 14129 * @return The left padding offset in pixels. 14130 * 14131 * @see #isPaddingOffsetRequired() 14132 * 14133 * @since CURRENT 14134 */ 14135 protected int getLeftPaddingOffset() { 14136 return 0; 14137 } 14138 14139 /** 14140 * Amount by which to extend the right fading region. Called only when 14141 * {@link #isPaddingOffsetRequired()} returns true. 14142 * 14143 * @return The right padding offset in pixels. 14144 * 14145 * @see #isPaddingOffsetRequired() 14146 * 14147 * @since CURRENT 14148 */ 14149 protected int getRightPaddingOffset() { 14150 return 0; 14151 } 14152 14153 /** 14154 * Amount by which to extend the top fading region. Called only when 14155 * {@link #isPaddingOffsetRequired()} returns true. 14156 * 14157 * @return The top padding offset in pixels. 14158 * 14159 * @see #isPaddingOffsetRequired() 14160 * 14161 * @since CURRENT 14162 */ 14163 protected int getTopPaddingOffset() { 14164 return 0; 14165 } 14166 14167 /** 14168 * Amount by which to extend the bottom fading region. Called only when 14169 * {@link #isPaddingOffsetRequired()} returns true. 14170 * 14171 * @return The bottom padding offset in pixels. 14172 * 14173 * @see #isPaddingOffsetRequired() 14174 * 14175 * @since CURRENT 14176 */ 14177 protected int getBottomPaddingOffset() { 14178 return 0; 14179 } 14180 14181 /** 14182 * @hide 14183 * @param offsetRequired 14184 */ 14185 protected int getFadeTop(boolean offsetRequired) { 14186 int top = mPaddingTop; 14187 if (offsetRequired) top += getTopPaddingOffset(); 14188 return top; 14189 } 14190 14191 /** 14192 * @hide 14193 * @param offsetRequired 14194 */ 14195 protected int getFadeHeight(boolean offsetRequired) { 14196 int padding = mPaddingTop; 14197 if (offsetRequired) padding += getTopPaddingOffset(); 14198 return mBottom - mTop - mPaddingBottom - padding; 14199 } 14200 14201 /** 14202 * <p>Indicates whether this view is attached to a hardware accelerated 14203 * window or not.</p> 14204 * 14205 * <p>Even if this method returns true, it does not mean that every call 14206 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14207 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14208 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14209 * window is hardware accelerated, 14210 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14211 * return false, and this method will return true.</p> 14212 * 14213 * @return True if the view is attached to a window and the window is 14214 * hardware accelerated; false in any other case. 14215 */ 14216 @ViewDebug.ExportedProperty(category = "drawing") 14217 public boolean isHardwareAccelerated() { 14218 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14219 } 14220 14221 /** 14222 * Sets a rectangular area on this view to which the view will be clipped 14223 * when it is drawn. Setting the value to null will remove the clip bounds 14224 * and the view will draw normally, using its full bounds. 14225 * 14226 * @param clipBounds The rectangular area, in the local coordinates of 14227 * this view, to which future drawing operations will be clipped. 14228 */ 14229 public void setClipBounds(Rect clipBounds) { 14230 if (clipBounds != null) { 14231 if (clipBounds.equals(mClipBounds)) { 14232 return; 14233 } 14234 if (mClipBounds == null) { 14235 invalidate(); 14236 mClipBounds = new Rect(clipBounds); 14237 } else { 14238 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14239 Math.min(mClipBounds.top, clipBounds.top), 14240 Math.max(mClipBounds.right, clipBounds.right), 14241 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14242 mClipBounds.set(clipBounds); 14243 } 14244 } else { 14245 if (mClipBounds != null) { 14246 invalidate(); 14247 mClipBounds = null; 14248 } 14249 } 14250 } 14251 14252 /** 14253 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14254 * 14255 * @return A copy of the current clip bounds if clip bounds are set, 14256 * otherwise null. 14257 */ 14258 public Rect getClipBounds() { 14259 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14260 } 14261 14262 /** 14263 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14264 * case of an active Animation being run on the view. 14265 */ 14266 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14267 Animation a, boolean scalingRequired) { 14268 Transformation invalidationTransform; 14269 final int flags = parent.mGroupFlags; 14270 final boolean initialized = a.isInitialized(); 14271 if (!initialized) { 14272 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14273 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14274 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14275 onAnimationStart(); 14276 } 14277 14278 final Transformation t = parent.getChildTransformation(); 14279 boolean more = a.getTransformation(drawingTime, t, 1f); 14280 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14281 if (parent.mInvalidationTransformation == null) { 14282 parent.mInvalidationTransformation = new Transformation(); 14283 } 14284 invalidationTransform = parent.mInvalidationTransformation; 14285 a.getTransformation(drawingTime, invalidationTransform, 1f); 14286 } else { 14287 invalidationTransform = t; 14288 } 14289 14290 if (more) { 14291 if (!a.willChangeBounds()) { 14292 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14293 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14294 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14295 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14296 // The child need to draw an animation, potentially offscreen, so 14297 // make sure we do not cancel invalidate requests 14298 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14299 parent.invalidate(mLeft, mTop, mRight, mBottom); 14300 } 14301 } else { 14302 if (parent.mInvalidateRegion == null) { 14303 parent.mInvalidateRegion = new RectF(); 14304 } 14305 final RectF region = parent.mInvalidateRegion; 14306 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14307 invalidationTransform); 14308 14309 // The child need to draw an animation, potentially offscreen, so 14310 // make sure we do not cancel invalidate requests 14311 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14312 14313 final int left = mLeft + (int) region.left; 14314 final int top = mTop + (int) region.top; 14315 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14316 top + (int) (region.height() + .5f)); 14317 } 14318 } 14319 return more; 14320 } 14321 14322 /** 14323 * This method is called by getDisplayList() when a display list is recorded for a View. 14324 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14325 */ 14326 void setDisplayListProperties(RenderNode renderNode) { 14327 if (renderNode != null) { 14328 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14329 if (mParent instanceof ViewGroup) { 14330 renderNode.setClipToBounds( 14331 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14332 } 14333 float alpha = 1; 14334 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14335 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14336 ViewGroup parentVG = (ViewGroup) mParent; 14337 final Transformation t = parentVG.getChildTransformation(); 14338 if (parentVG.getChildStaticTransformation(this, t)) { 14339 final int transformType = t.getTransformationType(); 14340 if (transformType != Transformation.TYPE_IDENTITY) { 14341 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14342 alpha = t.getAlpha(); 14343 } 14344 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14345 renderNode.setStaticMatrix(t.getMatrix()); 14346 } 14347 } 14348 } 14349 } 14350 if (mTransformationInfo != null) { 14351 alpha *= getFinalAlpha(); 14352 if (alpha < 1) { 14353 final int multipliedAlpha = (int) (255 * alpha); 14354 if (onSetAlpha(multipliedAlpha)) { 14355 alpha = 1; 14356 } 14357 } 14358 renderNode.setAlpha(alpha); 14359 } else if (alpha < 1) { 14360 renderNode.setAlpha(alpha); 14361 } 14362 } 14363 } 14364 14365 /** 14366 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14367 * This draw() method is an implementation detail and is not intended to be overridden or 14368 * to be called from anywhere else other than ViewGroup.drawChild(). 14369 */ 14370 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14371 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14372 boolean more = false; 14373 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14374 final int flags = parent.mGroupFlags; 14375 14376 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14377 parent.getChildTransformation().clear(); 14378 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14379 } 14380 14381 Transformation transformToApply = null; 14382 boolean concatMatrix = false; 14383 14384 boolean scalingRequired = false; 14385 boolean caching; 14386 int layerType = getLayerType(); 14387 14388 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14389 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14390 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14391 caching = true; 14392 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14393 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14394 } else { 14395 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14396 } 14397 14398 final Animation a = getAnimation(); 14399 if (a != null) { 14400 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14401 concatMatrix = a.willChangeTransformationMatrix(); 14402 if (concatMatrix) { 14403 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14404 } 14405 transformToApply = parent.getChildTransformation(); 14406 } else { 14407 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14408 // No longer animating: clear out old animation matrix 14409 mRenderNode.setAnimationMatrix(null); 14410 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14411 } 14412 if (!useDisplayListProperties && 14413 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14414 final Transformation t = parent.getChildTransformation(); 14415 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14416 if (hasTransform) { 14417 final int transformType = t.getTransformationType(); 14418 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14419 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14420 } 14421 } 14422 } 14423 14424 concatMatrix |= !childHasIdentityMatrix; 14425 14426 // Sets the flag as early as possible to allow draw() implementations 14427 // to call invalidate() successfully when doing animations 14428 mPrivateFlags |= PFLAG_DRAWN; 14429 14430 if (!concatMatrix && 14431 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14432 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14433 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14434 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14435 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14436 return more; 14437 } 14438 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14439 14440 if (hardwareAccelerated) { 14441 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14442 // retain the flag's value temporarily in the mRecreateDisplayList flag 14443 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14444 mPrivateFlags &= ~PFLAG_INVALIDATED; 14445 } 14446 14447 RenderNode renderNode = null; 14448 Bitmap cache = null; 14449 boolean hasDisplayList = false; 14450 if (caching) { 14451 if (!hardwareAccelerated) { 14452 if (layerType != LAYER_TYPE_NONE) { 14453 layerType = LAYER_TYPE_SOFTWARE; 14454 buildDrawingCache(true); 14455 } 14456 cache = getDrawingCache(true); 14457 } else { 14458 switch (layerType) { 14459 case LAYER_TYPE_SOFTWARE: 14460 if (useDisplayListProperties) { 14461 hasDisplayList = canHaveDisplayList(); 14462 } else { 14463 buildDrawingCache(true); 14464 cache = getDrawingCache(true); 14465 } 14466 break; 14467 case LAYER_TYPE_HARDWARE: 14468 if (useDisplayListProperties) { 14469 hasDisplayList = canHaveDisplayList(); 14470 } 14471 break; 14472 case LAYER_TYPE_NONE: 14473 // Delay getting the display list until animation-driven alpha values are 14474 // set up and possibly passed on to the view 14475 hasDisplayList = canHaveDisplayList(); 14476 break; 14477 } 14478 } 14479 } 14480 useDisplayListProperties &= hasDisplayList; 14481 if (useDisplayListProperties) { 14482 renderNode = getDisplayList(); 14483 if (!renderNode.isValid()) { 14484 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14485 // to getDisplayList(), the display list will be marked invalid and we should not 14486 // try to use it again. 14487 renderNode = null; 14488 hasDisplayList = false; 14489 useDisplayListProperties = false; 14490 } 14491 } 14492 14493 int sx = 0; 14494 int sy = 0; 14495 if (!hasDisplayList) { 14496 computeScroll(); 14497 sx = mScrollX; 14498 sy = mScrollY; 14499 } 14500 14501 final boolean hasNoCache = cache == null || hasDisplayList; 14502 final boolean offsetForScroll = cache == null && !hasDisplayList && 14503 layerType != LAYER_TYPE_HARDWARE; 14504 14505 int restoreTo = -1; 14506 if (!useDisplayListProperties || transformToApply != null) { 14507 restoreTo = canvas.save(); 14508 } 14509 if (offsetForScroll) { 14510 canvas.translate(mLeft - sx, mTop - sy); 14511 } else { 14512 if (!useDisplayListProperties) { 14513 canvas.translate(mLeft, mTop); 14514 } 14515 if (scalingRequired) { 14516 if (useDisplayListProperties) { 14517 // TODO: Might not need this if we put everything inside the DL 14518 restoreTo = canvas.save(); 14519 } 14520 // mAttachInfo cannot be null, otherwise scalingRequired == false 14521 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14522 canvas.scale(scale, scale); 14523 } 14524 } 14525 14526 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14527 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14528 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14529 if (transformToApply != null || !childHasIdentityMatrix) { 14530 int transX = 0; 14531 int transY = 0; 14532 14533 if (offsetForScroll) { 14534 transX = -sx; 14535 transY = -sy; 14536 } 14537 14538 if (transformToApply != null) { 14539 if (concatMatrix) { 14540 if (useDisplayListProperties) { 14541 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 14542 } else { 14543 // Undo the scroll translation, apply the transformation matrix, 14544 // then redo the scroll translate to get the correct result. 14545 canvas.translate(-transX, -transY); 14546 canvas.concat(transformToApply.getMatrix()); 14547 canvas.translate(transX, transY); 14548 } 14549 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14550 } 14551 14552 float transformAlpha = transformToApply.getAlpha(); 14553 if (transformAlpha < 1) { 14554 alpha *= transformAlpha; 14555 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14556 } 14557 } 14558 14559 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14560 canvas.translate(-transX, -transY); 14561 canvas.concat(getMatrix()); 14562 canvas.translate(transX, transY); 14563 } 14564 } 14565 14566 // Deal with alpha if it is or used to be <1 14567 if (alpha < 1 || 14568 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14569 if (alpha < 1) { 14570 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14571 } else { 14572 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14573 } 14574 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14575 if (hasNoCache) { 14576 final int multipliedAlpha = (int) (255 * alpha); 14577 if (!onSetAlpha(multipliedAlpha)) { 14578 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14579 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14580 layerType != LAYER_TYPE_NONE) { 14581 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14582 } 14583 if (useDisplayListProperties) { 14584 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14585 } else if (layerType == LAYER_TYPE_NONE) { 14586 final int scrollX = hasDisplayList ? 0 : sx; 14587 final int scrollY = hasDisplayList ? 0 : sy; 14588 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14589 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14590 } 14591 } else { 14592 // Alpha is handled by the child directly, clobber the layer's alpha 14593 mPrivateFlags |= PFLAG_ALPHA_SET; 14594 } 14595 } 14596 } 14597 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14598 onSetAlpha(255); 14599 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14600 } 14601 14602 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14603 !useDisplayListProperties && cache == null) { 14604 if (offsetForScroll) { 14605 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14606 } else { 14607 if (!scalingRequired || cache == null) { 14608 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14609 } else { 14610 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14611 } 14612 } 14613 } 14614 14615 if (!useDisplayListProperties && hasDisplayList) { 14616 renderNode = getDisplayList(); 14617 if (!renderNode.isValid()) { 14618 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14619 // to getDisplayList(), the display list will be marked invalid and we should not 14620 // try to use it again. 14621 renderNode = null; 14622 hasDisplayList = false; 14623 } 14624 } 14625 14626 if (hasNoCache) { 14627 boolean layerRendered = false; 14628 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14629 final HardwareLayer layer = getHardwareLayer(); 14630 if (layer != null && layer.isValid()) { 14631 mLayerPaint.setAlpha((int) (alpha * 255)); 14632 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14633 layerRendered = true; 14634 } else { 14635 final int scrollX = hasDisplayList ? 0 : sx; 14636 final int scrollY = hasDisplayList ? 0 : sy; 14637 canvas.saveLayer(scrollX, scrollY, 14638 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14639 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14640 } 14641 } 14642 14643 if (!layerRendered) { 14644 if (!hasDisplayList) { 14645 // Fast path for layouts with no backgrounds 14646 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14647 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14648 dispatchDraw(canvas); 14649 } else { 14650 draw(canvas); 14651 } 14652 } else { 14653 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14654 ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags); 14655 } 14656 } 14657 } else if (cache != null) { 14658 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14659 Paint cachePaint; 14660 14661 if (layerType == LAYER_TYPE_NONE) { 14662 cachePaint = parent.mCachePaint; 14663 if (cachePaint == null) { 14664 cachePaint = new Paint(); 14665 cachePaint.setDither(false); 14666 parent.mCachePaint = cachePaint; 14667 } 14668 if (alpha < 1) { 14669 cachePaint.setAlpha((int) (alpha * 255)); 14670 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14671 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14672 cachePaint.setAlpha(255); 14673 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14674 } 14675 } else { 14676 cachePaint = mLayerPaint; 14677 cachePaint.setAlpha((int) (alpha * 255)); 14678 } 14679 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14680 } 14681 14682 if (restoreTo >= 0) { 14683 canvas.restoreToCount(restoreTo); 14684 } 14685 14686 if (a != null && !more) { 14687 if (!hardwareAccelerated && !a.getFillAfter()) { 14688 onSetAlpha(255); 14689 } 14690 parent.finishAnimatingView(this, a); 14691 } 14692 14693 if (more && hardwareAccelerated) { 14694 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14695 // alpha animations should cause the child to recreate its display list 14696 invalidate(true); 14697 } 14698 } 14699 14700 mRecreateDisplayList = false; 14701 14702 return more; 14703 } 14704 14705 /** 14706 * Manually render this view (and all of its children) to the given Canvas. 14707 * The view must have already done a full layout before this function is 14708 * called. When implementing a view, implement 14709 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14710 * If you do need to override this method, call the superclass version. 14711 * 14712 * @param canvas The Canvas to which the View is rendered. 14713 */ 14714 public void draw(Canvas canvas) { 14715 if (mClipBounds != null) { 14716 canvas.clipRect(mClipBounds); 14717 } 14718 final int privateFlags = mPrivateFlags; 14719 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14720 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14721 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14722 14723 /* 14724 * Draw traversal performs several drawing steps which must be executed 14725 * in the appropriate order: 14726 * 14727 * 1. Draw the background 14728 * 2. If necessary, save the canvas' layers to prepare for fading 14729 * 3. Draw view's content 14730 * 4. Draw children 14731 * 5. If necessary, draw the fading edges and restore layers 14732 * 6. Draw decorations (scrollbars for instance) 14733 */ 14734 14735 // Step 1, draw the background, if needed 14736 int saveCount; 14737 14738 if (!dirtyOpaque) { 14739 drawBackground(canvas); 14740 } 14741 14742 // skip step 2 & 5 if possible (common case) 14743 final int viewFlags = mViewFlags; 14744 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14745 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14746 if (!verticalEdges && !horizontalEdges) { 14747 // Step 3, draw the content 14748 if (!dirtyOpaque) onDraw(canvas); 14749 14750 // Step 4, draw the children 14751 dispatchDraw(canvas); 14752 14753 // Step 6, draw decorations (scrollbars) 14754 onDrawScrollBars(canvas); 14755 14756 if (mOverlay != null && !mOverlay.isEmpty()) { 14757 mOverlay.getOverlayView().dispatchDraw(canvas); 14758 } 14759 14760 // we're done... 14761 return; 14762 } 14763 14764 /* 14765 * Here we do the full fledged routine... 14766 * (this is an uncommon case where speed matters less, 14767 * this is why we repeat some of the tests that have been 14768 * done above) 14769 */ 14770 14771 boolean drawTop = false; 14772 boolean drawBottom = false; 14773 boolean drawLeft = false; 14774 boolean drawRight = false; 14775 14776 float topFadeStrength = 0.0f; 14777 float bottomFadeStrength = 0.0f; 14778 float leftFadeStrength = 0.0f; 14779 float rightFadeStrength = 0.0f; 14780 14781 // Step 2, save the canvas' layers 14782 int paddingLeft = mPaddingLeft; 14783 14784 final boolean offsetRequired = isPaddingOffsetRequired(); 14785 if (offsetRequired) { 14786 paddingLeft += getLeftPaddingOffset(); 14787 } 14788 14789 int left = mScrollX + paddingLeft; 14790 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14791 int top = mScrollY + getFadeTop(offsetRequired); 14792 int bottom = top + getFadeHeight(offsetRequired); 14793 14794 if (offsetRequired) { 14795 right += getRightPaddingOffset(); 14796 bottom += getBottomPaddingOffset(); 14797 } 14798 14799 final ScrollabilityCache scrollabilityCache = mScrollCache; 14800 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14801 int length = (int) fadeHeight; 14802 14803 // clip the fade length if top and bottom fades overlap 14804 // overlapping fades produce odd-looking artifacts 14805 if (verticalEdges && (top + length > bottom - length)) { 14806 length = (bottom - top) / 2; 14807 } 14808 14809 // also clip horizontal fades if necessary 14810 if (horizontalEdges && (left + length > right - length)) { 14811 length = (right - left) / 2; 14812 } 14813 14814 if (verticalEdges) { 14815 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14816 drawTop = topFadeStrength * fadeHeight > 1.0f; 14817 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14818 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14819 } 14820 14821 if (horizontalEdges) { 14822 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14823 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14824 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14825 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14826 } 14827 14828 saveCount = canvas.getSaveCount(); 14829 14830 int solidColor = getSolidColor(); 14831 if (solidColor == 0) { 14832 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14833 14834 if (drawTop) { 14835 canvas.saveLayer(left, top, right, top + length, null, flags); 14836 } 14837 14838 if (drawBottom) { 14839 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14840 } 14841 14842 if (drawLeft) { 14843 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14844 } 14845 14846 if (drawRight) { 14847 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14848 } 14849 } else { 14850 scrollabilityCache.setFadeColor(solidColor); 14851 } 14852 14853 // Step 3, draw the content 14854 if (!dirtyOpaque) onDraw(canvas); 14855 14856 // Step 4, draw the children 14857 dispatchDraw(canvas); 14858 14859 // Step 5, draw the fade effect and restore layers 14860 final Paint p = scrollabilityCache.paint; 14861 final Matrix matrix = scrollabilityCache.matrix; 14862 final Shader fade = scrollabilityCache.shader; 14863 14864 if (drawTop) { 14865 matrix.setScale(1, fadeHeight * topFadeStrength); 14866 matrix.postTranslate(left, top); 14867 fade.setLocalMatrix(matrix); 14868 canvas.drawRect(left, top, right, top + length, p); 14869 } 14870 14871 if (drawBottom) { 14872 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14873 matrix.postRotate(180); 14874 matrix.postTranslate(left, bottom); 14875 fade.setLocalMatrix(matrix); 14876 canvas.drawRect(left, bottom - length, right, bottom, p); 14877 } 14878 14879 if (drawLeft) { 14880 matrix.setScale(1, fadeHeight * leftFadeStrength); 14881 matrix.postRotate(-90); 14882 matrix.postTranslate(left, top); 14883 fade.setLocalMatrix(matrix); 14884 canvas.drawRect(left, top, left + length, bottom, p); 14885 } 14886 14887 if (drawRight) { 14888 matrix.setScale(1, fadeHeight * rightFadeStrength); 14889 matrix.postRotate(90); 14890 matrix.postTranslate(right, top); 14891 fade.setLocalMatrix(matrix); 14892 canvas.drawRect(right - length, top, right, bottom, p); 14893 } 14894 14895 canvas.restoreToCount(saveCount); 14896 14897 // Step 6, draw decorations (scrollbars) 14898 onDrawScrollBars(canvas); 14899 14900 if (mOverlay != null && !mOverlay.isEmpty()) { 14901 mOverlay.getOverlayView().dispatchDraw(canvas); 14902 } 14903 } 14904 14905 /** 14906 * Draws the background onto the specified canvas. 14907 * 14908 * @param canvas Canvas on which to draw the background 14909 */ 14910 private void drawBackground(Canvas canvas) { 14911 final Drawable background = mBackground; 14912 if (background == null) { 14913 return; 14914 } 14915 14916 if (mBackgroundSizeChanged) { 14917 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14918 mBackgroundSizeChanged = false; 14919 queryOutlineFromBackgroundIfUndefined(); 14920 } 14921 14922 // Attempt to use a display list if requested. 14923 if (canvas.isHardwareAccelerated() && mAttachInfo != null 14924 && mAttachInfo.mHardwareRenderer != null) { 14925 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 14926 14927 final RenderNode displayList = mBackgroundRenderNode; 14928 if (displayList != null && displayList.isValid()) { 14929 setBackgroundDisplayListProperties(displayList); 14930 ((HardwareCanvas) canvas).drawRenderNode(displayList); 14931 return; 14932 } 14933 } 14934 14935 final int scrollX = mScrollX; 14936 final int scrollY = mScrollY; 14937 if ((scrollX | scrollY) == 0) { 14938 background.draw(canvas); 14939 } else { 14940 canvas.translate(scrollX, scrollY); 14941 background.draw(canvas); 14942 canvas.translate(-scrollX, -scrollY); 14943 } 14944 } 14945 14946 /** 14947 * Set up background drawable display list properties. 14948 * 14949 * @param displayList Valid display list for the background drawable 14950 */ 14951 private void setBackgroundDisplayListProperties(RenderNode displayList) { 14952 displayList.setTranslationX(mScrollX); 14953 displayList.setTranslationY(mScrollY); 14954 } 14955 14956 /** 14957 * Creates a new display list or updates the existing display list for the 14958 * specified Drawable. 14959 * 14960 * @param drawable Drawable for which to create a display list 14961 * @param renderNode Existing RenderNode, or {@code null} 14962 * @return A valid display list for the specified drawable 14963 */ 14964 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 14965 if (renderNode == null) { 14966 renderNode = RenderNode.create(drawable.getClass().getName()); 14967 } 14968 14969 final Rect bounds = drawable.getBounds(); 14970 final int width = bounds.width(); 14971 final int height = bounds.height(); 14972 final HardwareCanvas canvas = renderNode.start(width, height); 14973 try { 14974 drawable.draw(canvas); 14975 } finally { 14976 renderNode.end(canvas); 14977 } 14978 14979 // Set up drawable properties that are view-independent. 14980 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 14981 renderNode.setProjectBackwards(drawable.isProjected()); 14982 renderNode.setProjectionReceiver(true); 14983 renderNode.setClipToBounds(false); 14984 return renderNode; 14985 } 14986 14987 /** 14988 * Returns the overlay for this view, creating it if it does not yet exist. 14989 * Adding drawables to the overlay will cause them to be displayed whenever 14990 * the view itself is redrawn. Objects in the overlay should be actively 14991 * managed: remove them when they should not be displayed anymore. The 14992 * overlay will always have the same size as its host view. 14993 * 14994 * <p>Note: Overlays do not currently work correctly with {@link 14995 * SurfaceView} or {@link TextureView}; contents in overlays for these 14996 * types of views may not display correctly.</p> 14997 * 14998 * @return The ViewOverlay object for this view. 14999 * @see ViewOverlay 15000 */ 15001 public ViewOverlay getOverlay() { 15002 if (mOverlay == null) { 15003 mOverlay = new ViewOverlay(mContext, this); 15004 } 15005 return mOverlay; 15006 } 15007 15008 /** 15009 * Override this if your view is known to always be drawn on top of a solid color background, 15010 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15011 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15012 * should be set to 0xFF. 15013 * 15014 * @see #setVerticalFadingEdgeEnabled(boolean) 15015 * @see #setHorizontalFadingEdgeEnabled(boolean) 15016 * 15017 * @return The known solid color background for this view, or 0 if the color may vary 15018 */ 15019 @ViewDebug.ExportedProperty(category = "drawing") 15020 public int getSolidColor() { 15021 return 0; 15022 } 15023 15024 /** 15025 * Build a human readable string representation of the specified view flags. 15026 * 15027 * @param flags the view flags to convert to a string 15028 * @return a String representing the supplied flags 15029 */ 15030 private static String printFlags(int flags) { 15031 String output = ""; 15032 int numFlags = 0; 15033 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15034 output += "TAKES_FOCUS"; 15035 numFlags++; 15036 } 15037 15038 switch (flags & VISIBILITY_MASK) { 15039 case INVISIBLE: 15040 if (numFlags > 0) { 15041 output += " "; 15042 } 15043 output += "INVISIBLE"; 15044 // USELESS HERE numFlags++; 15045 break; 15046 case GONE: 15047 if (numFlags > 0) { 15048 output += " "; 15049 } 15050 output += "GONE"; 15051 // USELESS HERE numFlags++; 15052 break; 15053 default: 15054 break; 15055 } 15056 return output; 15057 } 15058 15059 /** 15060 * Build a human readable string representation of the specified private 15061 * view flags. 15062 * 15063 * @param privateFlags the private view flags to convert to a string 15064 * @return a String representing the supplied flags 15065 */ 15066 private static String printPrivateFlags(int privateFlags) { 15067 String output = ""; 15068 int numFlags = 0; 15069 15070 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15071 output += "WANTS_FOCUS"; 15072 numFlags++; 15073 } 15074 15075 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15076 if (numFlags > 0) { 15077 output += " "; 15078 } 15079 output += "FOCUSED"; 15080 numFlags++; 15081 } 15082 15083 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15084 if (numFlags > 0) { 15085 output += " "; 15086 } 15087 output += "SELECTED"; 15088 numFlags++; 15089 } 15090 15091 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15092 if (numFlags > 0) { 15093 output += " "; 15094 } 15095 output += "IS_ROOT_NAMESPACE"; 15096 numFlags++; 15097 } 15098 15099 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15100 if (numFlags > 0) { 15101 output += " "; 15102 } 15103 output += "HAS_BOUNDS"; 15104 numFlags++; 15105 } 15106 15107 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15108 if (numFlags > 0) { 15109 output += " "; 15110 } 15111 output += "DRAWN"; 15112 // USELESS HERE numFlags++; 15113 } 15114 return output; 15115 } 15116 15117 /** 15118 * <p>Indicates whether or not this view's layout will be requested during 15119 * the next hierarchy layout pass.</p> 15120 * 15121 * @return true if the layout will be forced during next layout pass 15122 */ 15123 public boolean isLayoutRequested() { 15124 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15125 } 15126 15127 /** 15128 * Return true if o is a ViewGroup that is laying out using optical bounds. 15129 * @hide 15130 */ 15131 public static boolean isLayoutModeOptical(Object o) { 15132 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15133 } 15134 15135 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15136 Insets parentInsets = mParent instanceof View ? 15137 ((View) mParent).getOpticalInsets() : Insets.NONE; 15138 Insets childInsets = getOpticalInsets(); 15139 return setFrame( 15140 left + parentInsets.left - childInsets.left, 15141 top + parentInsets.top - childInsets.top, 15142 right + parentInsets.left + childInsets.right, 15143 bottom + parentInsets.top + childInsets.bottom); 15144 } 15145 15146 /** 15147 * Assign a size and position to a view and all of its 15148 * descendants 15149 * 15150 * <p>This is the second phase of the layout mechanism. 15151 * (The first is measuring). In this phase, each parent calls 15152 * layout on all of its children to position them. 15153 * This is typically done using the child measurements 15154 * that were stored in the measure pass().</p> 15155 * 15156 * <p>Derived classes should not override this method. 15157 * Derived classes with children should override 15158 * onLayout. In that method, they should 15159 * call layout on each of their children.</p> 15160 * 15161 * @param l Left position, relative to parent 15162 * @param t Top position, relative to parent 15163 * @param r Right position, relative to parent 15164 * @param b Bottom position, relative to parent 15165 */ 15166 @SuppressWarnings({"unchecked"}) 15167 public void layout(int l, int t, int r, int b) { 15168 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15169 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15170 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15171 } 15172 15173 int oldL = mLeft; 15174 int oldT = mTop; 15175 int oldB = mBottom; 15176 int oldR = mRight; 15177 15178 boolean changed = isLayoutModeOptical(mParent) ? 15179 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15180 15181 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15182 onLayout(changed, l, t, r, b); 15183 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15184 15185 ListenerInfo li = mListenerInfo; 15186 if (li != null && li.mOnLayoutChangeListeners != null) { 15187 ArrayList<OnLayoutChangeListener> listenersCopy = 15188 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15189 int numListeners = listenersCopy.size(); 15190 for (int i = 0; i < numListeners; ++i) { 15191 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15192 } 15193 } 15194 } 15195 15196 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15197 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15198 } 15199 15200 /** 15201 * Called from layout when this view should 15202 * assign a size and position to each of its children. 15203 * 15204 * Derived classes with children should override 15205 * this method and call layout on each of 15206 * their children. 15207 * @param changed This is a new size or position for this view 15208 * @param left Left position, relative to parent 15209 * @param top Top position, relative to parent 15210 * @param right Right position, relative to parent 15211 * @param bottom Bottom position, relative to parent 15212 */ 15213 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15214 } 15215 15216 /** 15217 * Assign a size and position to this view. 15218 * 15219 * This is called from layout. 15220 * 15221 * @param left Left position, relative to parent 15222 * @param top Top position, relative to parent 15223 * @param right Right position, relative to parent 15224 * @param bottom Bottom position, relative to parent 15225 * @return true if the new size and position are different than the 15226 * previous ones 15227 * {@hide} 15228 */ 15229 protected boolean setFrame(int left, int top, int right, int bottom) { 15230 boolean changed = false; 15231 15232 if (DBG) { 15233 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15234 + right + "," + bottom + ")"); 15235 } 15236 15237 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15238 changed = true; 15239 15240 // Remember our drawn bit 15241 int drawn = mPrivateFlags & PFLAG_DRAWN; 15242 15243 int oldWidth = mRight - mLeft; 15244 int oldHeight = mBottom - mTop; 15245 int newWidth = right - left; 15246 int newHeight = bottom - top; 15247 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15248 15249 // Invalidate our old position 15250 invalidate(sizeChanged); 15251 15252 mLeft = left; 15253 mTop = top; 15254 mRight = right; 15255 mBottom = bottom; 15256 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15257 15258 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15259 15260 15261 if (sizeChanged) { 15262 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15263 } 15264 15265 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15266 // If we are visible, force the DRAWN bit to on so that 15267 // this invalidate will go through (at least to our parent). 15268 // This is because someone may have invalidated this view 15269 // before this call to setFrame came in, thereby clearing 15270 // the DRAWN bit. 15271 mPrivateFlags |= PFLAG_DRAWN; 15272 invalidate(sizeChanged); 15273 // parent display list may need to be recreated based on a change in the bounds 15274 // of any child 15275 invalidateParentCaches(); 15276 } 15277 15278 // Reset drawn bit to original value (invalidate turns it off) 15279 mPrivateFlags |= drawn; 15280 15281 mBackgroundSizeChanged = true; 15282 15283 notifySubtreeAccessibilityStateChangedIfNeeded(); 15284 } 15285 return changed; 15286 } 15287 15288 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15289 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15290 if (mOverlay != null) { 15291 mOverlay.getOverlayView().setRight(newWidth); 15292 mOverlay.getOverlayView().setBottom(newHeight); 15293 } 15294 } 15295 15296 /** 15297 * Finalize inflating a view from XML. This is called as the last phase 15298 * of inflation, after all child views have been added. 15299 * 15300 * <p>Even if the subclass overrides onFinishInflate, they should always be 15301 * sure to call the super method, so that we get called. 15302 */ 15303 protected void onFinishInflate() { 15304 } 15305 15306 /** 15307 * Returns the resources associated with this view. 15308 * 15309 * @return Resources object. 15310 */ 15311 public Resources getResources() { 15312 return mResources; 15313 } 15314 15315 /** 15316 * Invalidates the specified Drawable. 15317 * 15318 * @param drawable the drawable to invalidate 15319 */ 15320 @Override 15321 public void invalidateDrawable(@NonNull Drawable drawable) { 15322 if (verifyDrawable(drawable)) { 15323 final Rect dirty = drawable.getDirtyBounds(); 15324 final int scrollX = mScrollX; 15325 final int scrollY = mScrollY; 15326 15327 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15328 dirty.right + scrollX, dirty.bottom + scrollY); 15329 15330 if (drawable == mBackground) { 15331 queryOutlineFromBackgroundIfUndefined(); 15332 } 15333 } 15334 } 15335 15336 /** 15337 * Schedules an action on a drawable to occur at a specified time. 15338 * 15339 * @param who the recipient of the action 15340 * @param what the action to run on the drawable 15341 * @param when the time at which the action must occur. Uses the 15342 * {@link SystemClock#uptimeMillis} timebase. 15343 */ 15344 @Override 15345 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15346 if (verifyDrawable(who) && what != null) { 15347 final long delay = when - SystemClock.uptimeMillis(); 15348 if (mAttachInfo != null) { 15349 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15350 Choreographer.CALLBACK_ANIMATION, what, who, 15351 Choreographer.subtractFrameDelay(delay)); 15352 } else { 15353 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15354 } 15355 } 15356 } 15357 15358 /** 15359 * Cancels a scheduled action on a drawable. 15360 * 15361 * @param who the recipient of the action 15362 * @param what the action to cancel 15363 */ 15364 @Override 15365 public void unscheduleDrawable(Drawable who, Runnable what) { 15366 if (verifyDrawable(who) && what != null) { 15367 if (mAttachInfo != null) { 15368 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15369 Choreographer.CALLBACK_ANIMATION, what, who); 15370 } 15371 ViewRootImpl.getRunQueue().removeCallbacks(what); 15372 } 15373 } 15374 15375 /** 15376 * Unschedule any events associated with the given Drawable. This can be 15377 * used when selecting a new Drawable into a view, so that the previous 15378 * one is completely unscheduled. 15379 * 15380 * @param who The Drawable to unschedule. 15381 * 15382 * @see #drawableStateChanged 15383 */ 15384 public void unscheduleDrawable(Drawable who) { 15385 if (mAttachInfo != null && who != null) { 15386 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15387 Choreographer.CALLBACK_ANIMATION, null, who); 15388 } 15389 } 15390 15391 /** 15392 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15393 * that the View directionality can and will be resolved before its Drawables. 15394 * 15395 * Will call {@link View#onResolveDrawables} when resolution is done. 15396 * 15397 * @hide 15398 */ 15399 protected void resolveDrawables() { 15400 // Drawables resolution may need to happen before resolving the layout direction (which is 15401 // done only during the measure() call). 15402 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15403 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15404 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15405 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15406 // direction to be resolved as its resolved value will be the same as its raw value. 15407 if (!isLayoutDirectionResolved() && 15408 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15409 return; 15410 } 15411 15412 final int layoutDirection = isLayoutDirectionResolved() ? 15413 getLayoutDirection() : getRawLayoutDirection(); 15414 15415 if (mBackground != null) { 15416 mBackground.setLayoutDirection(layoutDirection); 15417 } 15418 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15419 onResolveDrawables(layoutDirection); 15420 } 15421 15422 /** 15423 * Called when layout direction has been resolved. 15424 * 15425 * The default implementation does nothing. 15426 * 15427 * @param layoutDirection The resolved layout direction. 15428 * 15429 * @see #LAYOUT_DIRECTION_LTR 15430 * @see #LAYOUT_DIRECTION_RTL 15431 * 15432 * @hide 15433 */ 15434 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15435 } 15436 15437 /** 15438 * @hide 15439 */ 15440 protected void resetResolvedDrawables() { 15441 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15442 } 15443 15444 private boolean isDrawablesResolved() { 15445 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15446 } 15447 15448 /** 15449 * If your view subclass is displaying its own Drawable objects, it should 15450 * override this function and return true for any Drawable it is 15451 * displaying. This allows animations for those drawables to be 15452 * scheduled. 15453 * 15454 * <p>Be sure to call through to the super class when overriding this 15455 * function. 15456 * 15457 * @param who The Drawable to verify. Return true if it is one you are 15458 * displaying, else return the result of calling through to the 15459 * super class. 15460 * 15461 * @return boolean If true than the Drawable is being displayed in the 15462 * view; else false and it is not allowed to animate. 15463 * 15464 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15465 * @see #drawableStateChanged() 15466 */ 15467 protected boolean verifyDrawable(Drawable who) { 15468 return who == mBackground; 15469 } 15470 15471 /** 15472 * This function is called whenever the state of the view changes in such 15473 * a way that it impacts the state of drawables being shown. 15474 * <p> 15475 * If the View has a StateListAnimator, it will also be called to run necessary state 15476 * change animations. 15477 * <p> 15478 * Be sure to call through to the superclass when overriding this function. 15479 * 15480 * @see Drawable#setState(int[]) 15481 */ 15482 protected void drawableStateChanged() { 15483 final Drawable d = mBackground; 15484 if (d != null && d.isStateful()) { 15485 d.setState(getDrawableState()); 15486 } 15487 15488 if (mStateListAnimator != null) { 15489 mStateListAnimator.setState(getDrawableState()); 15490 } 15491 } 15492 15493 /** 15494 * This function is called whenever the drawable hotspot changes. 15495 * <p> 15496 * Be sure to call through to the superclass when overriding this function. 15497 * 15498 * @param x hotspot x coordinate 15499 * @param y hotspot y coordinate 15500 */ 15501 public void drawableHotspotChanged(float x, float y) { 15502 if (mBackground != null) { 15503 mBackground.setHotspot(x, y); 15504 } 15505 } 15506 15507 /** 15508 * Call this to force a view to update its drawable state. This will cause 15509 * drawableStateChanged to be called on this view. Views that are interested 15510 * in the new state should call getDrawableState. 15511 * 15512 * @see #drawableStateChanged 15513 * @see #getDrawableState 15514 */ 15515 public void refreshDrawableState() { 15516 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15517 drawableStateChanged(); 15518 15519 ViewParent parent = mParent; 15520 if (parent != null) { 15521 parent.childDrawableStateChanged(this); 15522 } 15523 } 15524 15525 /** 15526 * Return an array of resource IDs of the drawable states representing the 15527 * current state of the view. 15528 * 15529 * @return The current drawable state 15530 * 15531 * @see Drawable#setState(int[]) 15532 * @see #drawableStateChanged() 15533 * @see #onCreateDrawableState(int) 15534 */ 15535 public final int[] getDrawableState() { 15536 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15537 return mDrawableState; 15538 } else { 15539 mDrawableState = onCreateDrawableState(0); 15540 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15541 return mDrawableState; 15542 } 15543 } 15544 15545 /** 15546 * Generate the new {@link android.graphics.drawable.Drawable} state for 15547 * this view. This is called by the view 15548 * system when the cached Drawable state is determined to be invalid. To 15549 * retrieve the current state, you should use {@link #getDrawableState}. 15550 * 15551 * @param extraSpace if non-zero, this is the number of extra entries you 15552 * would like in the returned array in which you can place your own 15553 * states. 15554 * 15555 * @return Returns an array holding the current {@link Drawable} state of 15556 * the view. 15557 * 15558 * @see #mergeDrawableStates(int[], int[]) 15559 */ 15560 protected int[] onCreateDrawableState(int extraSpace) { 15561 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15562 mParent instanceof View) { 15563 return ((View) mParent).onCreateDrawableState(extraSpace); 15564 } 15565 15566 int[] drawableState; 15567 15568 int privateFlags = mPrivateFlags; 15569 15570 int viewStateIndex = 0; 15571 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15572 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15573 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15574 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15575 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15576 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15577 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15578 HardwareRenderer.isAvailable()) { 15579 // This is set if HW acceleration is requested, even if the current 15580 // process doesn't allow it. This is just to allow app preview 15581 // windows to better match their app. 15582 viewStateIndex |= VIEW_STATE_ACCELERATED; 15583 } 15584 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15585 15586 final int privateFlags2 = mPrivateFlags2; 15587 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15588 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15589 15590 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15591 15592 //noinspection ConstantIfStatement 15593 if (false) { 15594 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15595 Log.i("View", toString() 15596 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15597 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15598 + " fo=" + hasFocus() 15599 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15600 + " wf=" + hasWindowFocus() 15601 + ": " + Arrays.toString(drawableState)); 15602 } 15603 15604 if (extraSpace == 0) { 15605 return drawableState; 15606 } 15607 15608 final int[] fullState; 15609 if (drawableState != null) { 15610 fullState = new int[drawableState.length + extraSpace]; 15611 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15612 } else { 15613 fullState = new int[extraSpace]; 15614 } 15615 15616 return fullState; 15617 } 15618 15619 /** 15620 * Merge your own state values in <var>additionalState</var> into the base 15621 * state values <var>baseState</var> that were returned by 15622 * {@link #onCreateDrawableState(int)}. 15623 * 15624 * @param baseState The base state values returned by 15625 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15626 * own additional state values. 15627 * 15628 * @param additionalState The additional state values you would like 15629 * added to <var>baseState</var>; this array is not modified. 15630 * 15631 * @return As a convenience, the <var>baseState</var> array you originally 15632 * passed into the function is returned. 15633 * 15634 * @see #onCreateDrawableState(int) 15635 */ 15636 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15637 final int N = baseState.length; 15638 int i = N - 1; 15639 while (i >= 0 && baseState[i] == 0) { 15640 i--; 15641 } 15642 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15643 return baseState; 15644 } 15645 15646 /** 15647 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15648 * on all Drawable objects associated with this view. 15649 * <p> 15650 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 15651 * attached to this view. 15652 */ 15653 public void jumpDrawablesToCurrentState() { 15654 if (mBackground != null) { 15655 mBackground.jumpToCurrentState(); 15656 } 15657 if (mStateListAnimator != null) { 15658 mStateListAnimator.jumpToCurrentState(); 15659 } 15660 } 15661 15662 /** 15663 * Sets the background color for this view. 15664 * @param color the color of the background 15665 */ 15666 @RemotableViewMethod 15667 public void setBackgroundColor(int color) { 15668 if (mBackground instanceof ColorDrawable) { 15669 ((ColorDrawable) mBackground.mutate()).setColor(color); 15670 computeOpaqueFlags(); 15671 mBackgroundResource = 0; 15672 } else { 15673 setBackground(new ColorDrawable(color)); 15674 } 15675 } 15676 15677 /** 15678 * Set the background to a given resource. The resource should refer to 15679 * a Drawable object or 0 to remove the background. 15680 * @param resid The identifier of the resource. 15681 * 15682 * @attr ref android.R.styleable#View_background 15683 */ 15684 @RemotableViewMethod 15685 public void setBackgroundResource(int resid) { 15686 if (resid != 0 && resid == mBackgroundResource) { 15687 return; 15688 } 15689 15690 Drawable d = null; 15691 if (resid != 0) { 15692 d = mContext.getDrawable(resid); 15693 } 15694 setBackground(d); 15695 15696 mBackgroundResource = resid; 15697 } 15698 15699 /** 15700 * Set the background to a given Drawable, or remove the background. If the 15701 * background has padding, this View's padding is set to the background's 15702 * padding. However, when a background is removed, this View's padding isn't 15703 * touched. If setting the padding is desired, please use 15704 * {@link #setPadding(int, int, int, int)}. 15705 * 15706 * @param background The Drawable to use as the background, or null to remove the 15707 * background 15708 */ 15709 public void setBackground(Drawable background) { 15710 //noinspection deprecation 15711 setBackgroundDrawable(background); 15712 } 15713 15714 /** 15715 * @deprecated use {@link #setBackground(Drawable)} instead 15716 */ 15717 @Deprecated 15718 public void setBackgroundDrawable(Drawable background) { 15719 computeOpaqueFlags(); 15720 15721 if (background == mBackground) { 15722 return; 15723 } 15724 15725 boolean requestLayout = false; 15726 15727 mBackgroundResource = 0; 15728 15729 /* 15730 * Regardless of whether we're setting a new background or not, we want 15731 * to clear the previous drawable. 15732 */ 15733 if (mBackground != null) { 15734 mBackground.setCallback(null); 15735 unscheduleDrawable(mBackground); 15736 } 15737 15738 if (background != null) { 15739 Rect padding = sThreadLocal.get(); 15740 if (padding == null) { 15741 padding = new Rect(); 15742 sThreadLocal.set(padding); 15743 } 15744 resetResolvedDrawables(); 15745 background.setLayoutDirection(getLayoutDirection()); 15746 if (background.getPadding(padding)) { 15747 resetResolvedPadding(); 15748 switch (background.getLayoutDirection()) { 15749 case LAYOUT_DIRECTION_RTL: 15750 mUserPaddingLeftInitial = padding.right; 15751 mUserPaddingRightInitial = padding.left; 15752 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15753 break; 15754 case LAYOUT_DIRECTION_LTR: 15755 default: 15756 mUserPaddingLeftInitial = padding.left; 15757 mUserPaddingRightInitial = padding.right; 15758 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15759 } 15760 mLeftPaddingDefined = false; 15761 mRightPaddingDefined = false; 15762 } 15763 15764 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15765 // if it has a different minimum size, we should layout again 15766 if (mBackground == null 15767 || mBackground.getMinimumHeight() != background.getMinimumHeight() 15768 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15769 requestLayout = true; 15770 } 15771 15772 background.setCallback(this); 15773 if (background.isStateful()) { 15774 background.setState(getDrawableState()); 15775 } 15776 background.setVisible(getVisibility() == VISIBLE, false); 15777 mBackground = background; 15778 15779 applyBackgroundTint(); 15780 15781 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15782 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15783 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15784 requestLayout = true; 15785 } 15786 } else { 15787 /* Remove the background */ 15788 mBackground = null; 15789 15790 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15791 /* 15792 * This view ONLY drew the background before and we're removing 15793 * the background, so now it won't draw anything 15794 * (hence we SKIP_DRAW) 15795 */ 15796 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15797 mPrivateFlags |= PFLAG_SKIP_DRAW; 15798 } 15799 15800 /* 15801 * When the background is set, we try to apply its padding to this 15802 * View. When the background is removed, we don't touch this View's 15803 * padding. This is noted in the Javadocs. Hence, we don't need to 15804 * requestLayout(), the invalidate() below is sufficient. 15805 */ 15806 15807 // The old background's minimum size could have affected this 15808 // View's layout, so let's requestLayout 15809 requestLayout = true; 15810 } 15811 15812 computeOpaqueFlags(); 15813 15814 if (requestLayout) { 15815 requestLayout(); 15816 } 15817 15818 mBackgroundSizeChanged = true; 15819 invalidate(true); 15820 } 15821 15822 /** 15823 * Gets the background drawable 15824 * 15825 * @return The drawable used as the background for this view, if any. 15826 * 15827 * @see #setBackground(Drawable) 15828 * 15829 * @attr ref android.R.styleable#View_background 15830 */ 15831 public Drawable getBackground() { 15832 return mBackground; 15833 } 15834 15835 /** 15836 * Applies a tint to the background drawable. 15837 * <p> 15838 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 15839 * mutate the drawable and apply the specified tint and tint mode using 15840 * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}. 15841 * 15842 * @param tint the tint to apply, may be {@code null} to clear tint 15843 * @param tintMode the blending mode used to apply the tint, may be 15844 * {@code null} to clear tint 15845 * 15846 * @attr ref android.R.styleable#View_backgroundTint 15847 * @attr ref android.R.styleable#View_backgroundTintMode 15848 * @see Drawable#setTint(ColorStateList, PorterDuff.Mode) 15849 */ 15850 private void setBackgroundTint(@Nullable ColorStateList tint, 15851 @Nullable PorterDuff.Mode tintMode) { 15852 mBackgroundTint = tint; 15853 mBackgroundTintMode = tintMode; 15854 mHasBackgroundTint = true; 15855 15856 applyBackgroundTint(); 15857 } 15858 15859 /** 15860 * Applies a tint to the background drawable. Does not modify the current tint 15861 * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default. 15862 * <p> 15863 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 15864 * mutate the drawable and apply the specified tint and tint mode using 15865 * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}. 15866 * 15867 * @param tint the tint to apply, may be {@code null} to clear tint 15868 * 15869 * @attr ref android.R.styleable#View_backgroundTint 15870 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15871 */ 15872 public void setBackgroundTint(@Nullable ColorStateList tint) { 15873 setBackgroundTint(tint, mBackgroundTintMode); 15874 } 15875 15876 /** 15877 * @return the tint applied to the background drawable 15878 * @attr ref android.R.styleable#View_backgroundTint 15879 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15880 */ 15881 @Nullable 15882 public ColorStateList getBackgroundTint() { 15883 return mBackgroundTint; 15884 } 15885 15886 /** 15887 * Specifies the blending mode used to apply the tint specified by 15888 * {@link #setBackgroundTint(ColorStateList)}} to the background drawable. 15889 * The default mode is {@link PorterDuff.Mode#SRC_ATOP}. 15890 * 15891 * @param tintMode the blending mode used to apply the tint, may be 15892 * {@code null} to clear tint 15893 * @attr ref android.R.styleable#View_backgroundTintMode 15894 * @see #setBackgroundTint(ColorStateList) 15895 */ 15896 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 15897 setBackgroundTint(mBackgroundTint, tintMode); 15898 } 15899 15900 /** 15901 * @return the blending mode used to apply the tint to the background drawable 15902 * @attr ref android.R.styleable#View_backgroundTintMode 15903 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15904 */ 15905 @Nullable 15906 public PorterDuff.Mode getBackgroundTintMode() { 15907 return mBackgroundTintMode; 15908 } 15909 15910 private void applyBackgroundTint() { 15911 if (mBackground != null && mHasBackgroundTint) { 15912 mBackground = mBackground.mutate(); 15913 mBackground.setTint(mBackgroundTint, mBackgroundTintMode); 15914 } 15915 } 15916 15917 /** 15918 * Sets the padding. The view may add on the space required to display 15919 * the scrollbars, depending on the style and visibility of the scrollbars. 15920 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15921 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15922 * from the values set in this call. 15923 * 15924 * @attr ref android.R.styleable#View_padding 15925 * @attr ref android.R.styleable#View_paddingBottom 15926 * @attr ref android.R.styleable#View_paddingLeft 15927 * @attr ref android.R.styleable#View_paddingRight 15928 * @attr ref android.R.styleable#View_paddingTop 15929 * @param left the left padding in pixels 15930 * @param top the top padding in pixels 15931 * @param right the right padding in pixels 15932 * @param bottom the bottom padding in pixels 15933 */ 15934 public void setPadding(int left, int top, int right, int bottom) { 15935 resetResolvedPadding(); 15936 15937 mUserPaddingStart = UNDEFINED_PADDING; 15938 mUserPaddingEnd = UNDEFINED_PADDING; 15939 15940 mUserPaddingLeftInitial = left; 15941 mUserPaddingRightInitial = right; 15942 15943 mLeftPaddingDefined = true; 15944 mRightPaddingDefined = true; 15945 15946 internalSetPadding(left, top, right, bottom); 15947 } 15948 15949 /** 15950 * @hide 15951 */ 15952 protected void internalSetPadding(int left, int top, int right, int bottom) { 15953 mUserPaddingLeft = left; 15954 mUserPaddingRight = right; 15955 mUserPaddingBottom = bottom; 15956 15957 final int viewFlags = mViewFlags; 15958 boolean changed = false; 15959 15960 // Common case is there are no scroll bars. 15961 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15962 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15963 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15964 ? 0 : getVerticalScrollbarWidth(); 15965 switch (mVerticalScrollbarPosition) { 15966 case SCROLLBAR_POSITION_DEFAULT: 15967 if (isLayoutRtl()) { 15968 left += offset; 15969 } else { 15970 right += offset; 15971 } 15972 break; 15973 case SCROLLBAR_POSITION_RIGHT: 15974 right += offset; 15975 break; 15976 case SCROLLBAR_POSITION_LEFT: 15977 left += offset; 15978 break; 15979 } 15980 } 15981 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 15982 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 15983 ? 0 : getHorizontalScrollbarHeight(); 15984 } 15985 } 15986 15987 if (mPaddingLeft != left) { 15988 changed = true; 15989 mPaddingLeft = left; 15990 } 15991 if (mPaddingTop != top) { 15992 changed = true; 15993 mPaddingTop = top; 15994 } 15995 if (mPaddingRight != right) { 15996 changed = true; 15997 mPaddingRight = right; 15998 } 15999 if (mPaddingBottom != bottom) { 16000 changed = true; 16001 mPaddingBottom = bottom; 16002 } 16003 16004 if (changed) { 16005 requestLayout(); 16006 } 16007 } 16008 16009 /** 16010 * Sets the relative padding. The view may add on the space required to display 16011 * the scrollbars, depending on the style and visibility of the scrollbars. 16012 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16013 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16014 * from the values set in this call. 16015 * 16016 * @attr ref android.R.styleable#View_padding 16017 * @attr ref android.R.styleable#View_paddingBottom 16018 * @attr ref android.R.styleable#View_paddingStart 16019 * @attr ref android.R.styleable#View_paddingEnd 16020 * @attr ref android.R.styleable#View_paddingTop 16021 * @param start the start padding in pixels 16022 * @param top the top padding in pixels 16023 * @param end the end padding in pixels 16024 * @param bottom the bottom padding in pixels 16025 */ 16026 public void setPaddingRelative(int start, int top, int end, int bottom) { 16027 resetResolvedPadding(); 16028 16029 mUserPaddingStart = start; 16030 mUserPaddingEnd = end; 16031 mLeftPaddingDefined = true; 16032 mRightPaddingDefined = true; 16033 16034 switch(getLayoutDirection()) { 16035 case LAYOUT_DIRECTION_RTL: 16036 mUserPaddingLeftInitial = end; 16037 mUserPaddingRightInitial = start; 16038 internalSetPadding(end, top, start, bottom); 16039 break; 16040 case LAYOUT_DIRECTION_LTR: 16041 default: 16042 mUserPaddingLeftInitial = start; 16043 mUserPaddingRightInitial = end; 16044 internalSetPadding(start, top, end, bottom); 16045 } 16046 } 16047 16048 /** 16049 * Returns the top padding of this view. 16050 * 16051 * @return the top padding in pixels 16052 */ 16053 public int getPaddingTop() { 16054 return mPaddingTop; 16055 } 16056 16057 /** 16058 * Returns the bottom padding of this view. If there are inset and enabled 16059 * scrollbars, this value may include the space required to display the 16060 * scrollbars as well. 16061 * 16062 * @return the bottom padding in pixels 16063 */ 16064 public int getPaddingBottom() { 16065 return mPaddingBottom; 16066 } 16067 16068 /** 16069 * Returns the left padding of this view. If there are inset and enabled 16070 * scrollbars, this value may include the space required to display the 16071 * scrollbars as well. 16072 * 16073 * @return the left padding in pixels 16074 */ 16075 public int getPaddingLeft() { 16076 if (!isPaddingResolved()) { 16077 resolvePadding(); 16078 } 16079 return mPaddingLeft; 16080 } 16081 16082 /** 16083 * Returns the start padding of this view depending on its resolved layout direction. 16084 * If there are inset and enabled scrollbars, this value may include the space 16085 * required to display the scrollbars as well. 16086 * 16087 * @return the start padding in pixels 16088 */ 16089 public int getPaddingStart() { 16090 if (!isPaddingResolved()) { 16091 resolvePadding(); 16092 } 16093 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16094 mPaddingRight : mPaddingLeft; 16095 } 16096 16097 /** 16098 * Returns the right padding of this view. If there are inset and enabled 16099 * scrollbars, this value may include the space required to display the 16100 * scrollbars as well. 16101 * 16102 * @return the right padding in pixels 16103 */ 16104 public int getPaddingRight() { 16105 if (!isPaddingResolved()) { 16106 resolvePadding(); 16107 } 16108 return mPaddingRight; 16109 } 16110 16111 /** 16112 * Returns the end padding of this view depending on its resolved layout direction. 16113 * If there are inset and enabled scrollbars, this value may include the space 16114 * required to display the scrollbars as well. 16115 * 16116 * @return the end padding in pixels 16117 */ 16118 public int getPaddingEnd() { 16119 if (!isPaddingResolved()) { 16120 resolvePadding(); 16121 } 16122 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16123 mPaddingLeft : mPaddingRight; 16124 } 16125 16126 /** 16127 * Return if the padding as been set thru relative values 16128 * {@link #setPaddingRelative(int, int, int, int)} or thru 16129 * @attr ref android.R.styleable#View_paddingStart or 16130 * @attr ref android.R.styleable#View_paddingEnd 16131 * 16132 * @return true if the padding is relative or false if it is not. 16133 */ 16134 public boolean isPaddingRelative() { 16135 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16136 } 16137 16138 Insets computeOpticalInsets() { 16139 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16140 } 16141 16142 /** 16143 * @hide 16144 */ 16145 public void resetPaddingToInitialValues() { 16146 if (isRtlCompatibilityMode()) { 16147 mPaddingLeft = mUserPaddingLeftInitial; 16148 mPaddingRight = mUserPaddingRightInitial; 16149 return; 16150 } 16151 if (isLayoutRtl()) { 16152 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16153 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16154 } else { 16155 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16156 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16157 } 16158 } 16159 16160 /** 16161 * @hide 16162 */ 16163 public Insets getOpticalInsets() { 16164 if (mLayoutInsets == null) { 16165 mLayoutInsets = computeOpticalInsets(); 16166 } 16167 return mLayoutInsets; 16168 } 16169 16170 /** 16171 * Set this view's optical insets. 16172 * 16173 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16174 * property. Views that compute their own optical insets should call it as part of measurement. 16175 * This method does not request layout. If you are setting optical insets outside of 16176 * measure/layout itself you will want to call requestLayout() yourself. 16177 * </p> 16178 * @hide 16179 */ 16180 public void setOpticalInsets(Insets insets) { 16181 mLayoutInsets = insets; 16182 } 16183 16184 /** 16185 * Changes the selection state of this view. A view can be selected or not. 16186 * Note that selection is not the same as focus. Views are typically 16187 * selected in the context of an AdapterView like ListView or GridView; 16188 * the selected view is the view that is highlighted. 16189 * 16190 * @param selected true if the view must be selected, false otherwise 16191 */ 16192 public void setSelected(boolean selected) { 16193 //noinspection DoubleNegation 16194 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16195 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16196 if (!selected) resetPressedState(); 16197 invalidate(true); 16198 refreshDrawableState(); 16199 dispatchSetSelected(selected); 16200 notifyViewAccessibilityStateChangedIfNeeded( 16201 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16202 } 16203 } 16204 16205 /** 16206 * Dispatch setSelected to all of this View's children. 16207 * 16208 * @see #setSelected(boolean) 16209 * 16210 * @param selected The new selected state 16211 */ 16212 protected void dispatchSetSelected(boolean selected) { 16213 } 16214 16215 /** 16216 * Indicates the selection state of this view. 16217 * 16218 * @return true if the view is selected, false otherwise 16219 */ 16220 @ViewDebug.ExportedProperty 16221 public boolean isSelected() { 16222 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16223 } 16224 16225 /** 16226 * Changes the activated state of this view. A view can be activated or not. 16227 * Note that activation is not the same as selection. Selection is 16228 * a transient property, representing the view (hierarchy) the user is 16229 * currently interacting with. Activation is a longer-term state that the 16230 * user can move views in and out of. For example, in a list view with 16231 * single or multiple selection enabled, the views in the current selection 16232 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16233 * here.) The activated state is propagated down to children of the view it 16234 * is set on. 16235 * 16236 * @param activated true if the view must be activated, false otherwise 16237 */ 16238 public void setActivated(boolean activated) { 16239 //noinspection DoubleNegation 16240 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16241 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16242 invalidate(true); 16243 refreshDrawableState(); 16244 dispatchSetActivated(activated); 16245 } 16246 } 16247 16248 /** 16249 * Dispatch setActivated to all of this View's children. 16250 * 16251 * @see #setActivated(boolean) 16252 * 16253 * @param activated The new activated state 16254 */ 16255 protected void dispatchSetActivated(boolean activated) { 16256 } 16257 16258 /** 16259 * Indicates the activation state of this view. 16260 * 16261 * @return true if the view is activated, false otherwise 16262 */ 16263 @ViewDebug.ExportedProperty 16264 public boolean isActivated() { 16265 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16266 } 16267 16268 /** 16269 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16270 * observer can be used to get notifications when global events, like 16271 * layout, happen. 16272 * 16273 * The returned ViewTreeObserver observer is not guaranteed to remain 16274 * valid for the lifetime of this View. If the caller of this method keeps 16275 * a long-lived reference to ViewTreeObserver, it should always check for 16276 * the return value of {@link ViewTreeObserver#isAlive()}. 16277 * 16278 * @return The ViewTreeObserver for this view's hierarchy. 16279 */ 16280 public ViewTreeObserver getViewTreeObserver() { 16281 if (mAttachInfo != null) { 16282 return mAttachInfo.mTreeObserver; 16283 } 16284 if (mFloatingTreeObserver == null) { 16285 mFloatingTreeObserver = new ViewTreeObserver(); 16286 } 16287 return mFloatingTreeObserver; 16288 } 16289 16290 /** 16291 * <p>Finds the topmost view in the current view hierarchy.</p> 16292 * 16293 * @return the topmost view containing this view 16294 */ 16295 public View getRootView() { 16296 if (mAttachInfo != null) { 16297 final View v = mAttachInfo.mRootView; 16298 if (v != null) { 16299 return v; 16300 } 16301 } 16302 16303 View parent = this; 16304 16305 while (parent.mParent != null && parent.mParent instanceof View) { 16306 parent = (View) parent.mParent; 16307 } 16308 16309 return parent; 16310 } 16311 16312 /** 16313 * Transforms a motion event from view-local coordinates to on-screen 16314 * coordinates. 16315 * 16316 * @param ev the view-local motion event 16317 * @return false if the transformation could not be applied 16318 * @hide 16319 */ 16320 public boolean toGlobalMotionEvent(MotionEvent ev) { 16321 final AttachInfo info = mAttachInfo; 16322 if (info == null) { 16323 return false; 16324 } 16325 16326 final Matrix m = info.mTmpMatrix; 16327 m.set(Matrix.IDENTITY_MATRIX); 16328 transformMatrixToGlobal(m); 16329 ev.transform(m); 16330 return true; 16331 } 16332 16333 /** 16334 * Transforms a motion event from on-screen coordinates to view-local 16335 * coordinates. 16336 * 16337 * @param ev the on-screen motion event 16338 * @return false if the transformation could not be applied 16339 * @hide 16340 */ 16341 public boolean toLocalMotionEvent(MotionEvent ev) { 16342 final AttachInfo info = mAttachInfo; 16343 if (info == null) { 16344 return false; 16345 } 16346 16347 final Matrix m = info.mTmpMatrix; 16348 m.set(Matrix.IDENTITY_MATRIX); 16349 transformMatrixToLocal(m); 16350 ev.transform(m); 16351 return true; 16352 } 16353 16354 /** 16355 * Modifies the input matrix such that it maps view-local coordinates to 16356 * on-screen coordinates. 16357 * 16358 * @param m input matrix to modify 16359 */ 16360 void transformMatrixToGlobal(Matrix m) { 16361 final ViewParent parent = mParent; 16362 if (parent instanceof View) { 16363 final View vp = (View) parent; 16364 vp.transformMatrixToGlobal(m); 16365 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16366 } else if (parent instanceof ViewRootImpl) { 16367 final ViewRootImpl vr = (ViewRootImpl) parent; 16368 vr.transformMatrixToGlobal(m); 16369 m.postTranslate(0, -vr.mCurScrollY); 16370 } 16371 16372 m.postTranslate(mLeft, mTop); 16373 16374 if (!hasIdentityMatrix()) { 16375 m.postConcat(getMatrix()); 16376 } 16377 } 16378 16379 /** 16380 * Modifies the input matrix such that it maps on-screen coordinates to 16381 * view-local coordinates. 16382 * 16383 * @param m input matrix to modify 16384 */ 16385 void transformMatrixToLocal(Matrix m) { 16386 final ViewParent parent = mParent; 16387 if (parent instanceof View) { 16388 final View vp = (View) parent; 16389 vp.transformMatrixToLocal(m); 16390 m.preTranslate(vp.mScrollX, vp.mScrollY); 16391 } else if (parent instanceof ViewRootImpl) { 16392 final ViewRootImpl vr = (ViewRootImpl) parent; 16393 vr.transformMatrixToLocal(m); 16394 m.preTranslate(0, vr.mCurScrollY); 16395 } 16396 16397 m.preTranslate(-mLeft, -mTop); 16398 16399 if (!hasIdentityMatrix()) { 16400 m.preConcat(getInverseMatrix()); 16401 } 16402 } 16403 16404 /** 16405 * <p>Computes the coordinates of this view on the screen. The argument 16406 * must be an array of two integers. After the method returns, the array 16407 * contains the x and y location in that order.</p> 16408 * 16409 * @param location an array of two integers in which to hold the coordinates 16410 */ 16411 public void getLocationOnScreen(int[] location) { 16412 getLocationInWindow(location); 16413 16414 final AttachInfo info = mAttachInfo; 16415 if (info != null) { 16416 location[0] += info.mWindowLeft; 16417 location[1] += info.mWindowTop; 16418 } 16419 } 16420 16421 /** 16422 * <p>Computes the coordinates of this view in its window. The argument 16423 * must be an array of two integers. After the method returns, the array 16424 * contains the x and y location in that order.</p> 16425 * 16426 * @param location an array of two integers in which to hold the coordinates 16427 */ 16428 public void getLocationInWindow(int[] location) { 16429 if (location == null || location.length < 2) { 16430 throw new IllegalArgumentException("location must be an array of two integers"); 16431 } 16432 16433 if (mAttachInfo == null) { 16434 // When the view is not attached to a window, this method does not make sense 16435 location[0] = location[1] = 0; 16436 return; 16437 } 16438 16439 float[] position = mAttachInfo.mTmpTransformLocation; 16440 position[0] = position[1] = 0.0f; 16441 16442 if (!hasIdentityMatrix()) { 16443 getMatrix().mapPoints(position); 16444 } 16445 16446 position[0] += mLeft; 16447 position[1] += mTop; 16448 16449 ViewParent viewParent = mParent; 16450 while (viewParent instanceof View) { 16451 final View view = (View) viewParent; 16452 16453 position[0] -= view.mScrollX; 16454 position[1] -= view.mScrollY; 16455 16456 if (!view.hasIdentityMatrix()) { 16457 view.getMatrix().mapPoints(position); 16458 } 16459 16460 position[0] += view.mLeft; 16461 position[1] += view.mTop; 16462 16463 viewParent = view.mParent; 16464 } 16465 16466 if (viewParent instanceof ViewRootImpl) { 16467 // *cough* 16468 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16469 position[1] -= vr.mCurScrollY; 16470 } 16471 16472 location[0] = (int) (position[0] + 0.5f); 16473 location[1] = (int) (position[1] + 0.5f); 16474 } 16475 16476 /** 16477 * {@hide} 16478 * @param id the id of the view to be found 16479 * @return the view of the specified id, null if cannot be found 16480 */ 16481 protected View findViewTraversal(int id) { 16482 if (id == mID) { 16483 return this; 16484 } 16485 return null; 16486 } 16487 16488 /** 16489 * {@hide} 16490 * @param tag the tag of the view to be found 16491 * @return the view of specified tag, null if cannot be found 16492 */ 16493 protected View findViewWithTagTraversal(Object tag) { 16494 if (tag != null && tag.equals(mTag)) { 16495 return this; 16496 } 16497 return null; 16498 } 16499 16500 /** 16501 * {@hide} 16502 * @param predicate The predicate to evaluate. 16503 * @param childToSkip If not null, ignores this child during the recursive traversal. 16504 * @return The first view that matches the predicate or null. 16505 */ 16506 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16507 if (predicate.apply(this)) { 16508 return this; 16509 } 16510 return null; 16511 } 16512 16513 /** 16514 * Look for a child view with the given id. If this view has the given 16515 * id, return this view. 16516 * 16517 * @param id The id to search for. 16518 * @return The view that has the given id in the hierarchy or null 16519 */ 16520 public final View findViewById(int id) { 16521 if (id < 0) { 16522 return null; 16523 } 16524 return findViewTraversal(id); 16525 } 16526 16527 /** 16528 * Finds a view by its unuque and stable accessibility id. 16529 * 16530 * @param accessibilityId The searched accessibility id. 16531 * @return The found view. 16532 */ 16533 final View findViewByAccessibilityId(int accessibilityId) { 16534 if (accessibilityId < 0) { 16535 return null; 16536 } 16537 return findViewByAccessibilityIdTraversal(accessibilityId); 16538 } 16539 16540 /** 16541 * Performs the traversal to find a view by its unuque and stable accessibility id. 16542 * 16543 * <strong>Note:</strong>This method does not stop at the root namespace 16544 * boundary since the user can touch the screen at an arbitrary location 16545 * potentially crossing the root namespace bounday which will send an 16546 * accessibility event to accessibility services and they should be able 16547 * to obtain the event source. Also accessibility ids are guaranteed to be 16548 * unique in the window. 16549 * 16550 * @param accessibilityId The accessibility id. 16551 * @return The found view. 16552 * 16553 * @hide 16554 */ 16555 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16556 if (getAccessibilityViewId() == accessibilityId) { 16557 return this; 16558 } 16559 return null; 16560 } 16561 16562 /** 16563 * Look for a child view with the given tag. If this view has the given 16564 * tag, return this view. 16565 * 16566 * @param tag The tag to search for, using "tag.equals(getTag())". 16567 * @return The View that has the given tag in the hierarchy or null 16568 */ 16569 public final View findViewWithTag(Object tag) { 16570 if (tag == null) { 16571 return null; 16572 } 16573 return findViewWithTagTraversal(tag); 16574 } 16575 16576 /** 16577 * {@hide} 16578 * Look for a child view that matches the specified predicate. 16579 * If this view matches the predicate, return this view. 16580 * 16581 * @param predicate The predicate to evaluate. 16582 * @return The first view that matches the predicate or null. 16583 */ 16584 public final View findViewByPredicate(Predicate<View> predicate) { 16585 return findViewByPredicateTraversal(predicate, null); 16586 } 16587 16588 /** 16589 * {@hide} 16590 * Look for a child view that matches the specified predicate, 16591 * starting with the specified view and its descendents and then 16592 * recusively searching the ancestors and siblings of that view 16593 * until this view is reached. 16594 * 16595 * This method is useful in cases where the predicate does not match 16596 * a single unique view (perhaps multiple views use the same id) 16597 * and we are trying to find the view that is "closest" in scope to the 16598 * starting view. 16599 * 16600 * @param start The view to start from. 16601 * @param predicate The predicate to evaluate. 16602 * @return The first view that matches the predicate or null. 16603 */ 16604 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16605 View childToSkip = null; 16606 for (;;) { 16607 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16608 if (view != null || start == this) { 16609 return view; 16610 } 16611 16612 ViewParent parent = start.getParent(); 16613 if (parent == null || !(parent instanceof View)) { 16614 return null; 16615 } 16616 16617 childToSkip = start; 16618 start = (View) parent; 16619 } 16620 } 16621 16622 /** 16623 * Sets the identifier for this view. The identifier does not have to be 16624 * unique in this view's hierarchy. The identifier should be a positive 16625 * number. 16626 * 16627 * @see #NO_ID 16628 * @see #getId() 16629 * @see #findViewById(int) 16630 * 16631 * @param id a number used to identify the view 16632 * 16633 * @attr ref android.R.styleable#View_id 16634 */ 16635 public void setId(int id) { 16636 mID = id; 16637 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16638 mID = generateViewId(); 16639 } 16640 } 16641 16642 /** 16643 * {@hide} 16644 * 16645 * @param isRoot true if the view belongs to the root namespace, false 16646 * otherwise 16647 */ 16648 public void setIsRootNamespace(boolean isRoot) { 16649 if (isRoot) { 16650 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16651 } else { 16652 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16653 } 16654 } 16655 16656 /** 16657 * {@hide} 16658 * 16659 * @return true if the view belongs to the root namespace, false otherwise 16660 */ 16661 public boolean isRootNamespace() { 16662 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16663 } 16664 16665 /** 16666 * Returns this view's identifier. 16667 * 16668 * @return a positive integer used to identify the view or {@link #NO_ID} 16669 * if the view has no ID 16670 * 16671 * @see #setId(int) 16672 * @see #findViewById(int) 16673 * @attr ref android.R.styleable#View_id 16674 */ 16675 @ViewDebug.CapturedViewProperty 16676 public int getId() { 16677 return mID; 16678 } 16679 16680 /** 16681 * Returns this view's tag. 16682 * 16683 * @return the Object stored in this view as a tag, or {@code null} if not 16684 * set 16685 * 16686 * @see #setTag(Object) 16687 * @see #getTag(int) 16688 */ 16689 @ViewDebug.ExportedProperty 16690 public Object getTag() { 16691 return mTag; 16692 } 16693 16694 /** 16695 * Sets the tag associated with this view. A tag can be used to mark 16696 * a view in its hierarchy and does not have to be unique within the 16697 * hierarchy. Tags can also be used to store data within a view without 16698 * resorting to another data structure. 16699 * 16700 * @param tag an Object to tag the view with 16701 * 16702 * @see #getTag() 16703 * @see #setTag(int, Object) 16704 */ 16705 public void setTag(final Object tag) { 16706 mTag = tag; 16707 } 16708 16709 /** 16710 * Returns the tag associated with this view and the specified key. 16711 * 16712 * @param key The key identifying the tag 16713 * 16714 * @return the Object stored in this view as a tag, or {@code null} if not 16715 * set 16716 * 16717 * @see #setTag(int, Object) 16718 * @see #getTag() 16719 */ 16720 public Object getTag(int key) { 16721 if (mKeyedTags != null) return mKeyedTags.get(key); 16722 return null; 16723 } 16724 16725 /** 16726 * Sets a tag associated with this view and a key. A tag can be used 16727 * to mark a view in its hierarchy and does not have to be unique within 16728 * the hierarchy. Tags can also be used to store data within a view 16729 * without resorting to another data structure. 16730 * 16731 * The specified key should be an id declared in the resources of the 16732 * application to ensure it is unique (see the <a 16733 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16734 * Keys identified as belonging to 16735 * the Android framework or not associated with any package will cause 16736 * an {@link IllegalArgumentException} to be thrown. 16737 * 16738 * @param key The key identifying the tag 16739 * @param tag An Object to tag the view with 16740 * 16741 * @throws IllegalArgumentException If they specified key is not valid 16742 * 16743 * @see #setTag(Object) 16744 * @see #getTag(int) 16745 */ 16746 public void setTag(int key, final Object tag) { 16747 // If the package id is 0x00 or 0x01, it's either an undefined package 16748 // or a framework id 16749 if ((key >>> 24) < 2) { 16750 throw new IllegalArgumentException("The key must be an application-specific " 16751 + "resource id."); 16752 } 16753 16754 setKeyedTag(key, tag); 16755 } 16756 16757 /** 16758 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16759 * framework id. 16760 * 16761 * @hide 16762 */ 16763 public void setTagInternal(int key, Object tag) { 16764 if ((key >>> 24) != 0x1) { 16765 throw new IllegalArgumentException("The key must be a framework-specific " 16766 + "resource id."); 16767 } 16768 16769 setKeyedTag(key, tag); 16770 } 16771 16772 private void setKeyedTag(int key, Object tag) { 16773 if (mKeyedTags == null) { 16774 mKeyedTags = new SparseArray<Object>(2); 16775 } 16776 16777 mKeyedTags.put(key, tag); 16778 } 16779 16780 /** 16781 * Prints information about this view in the log output, with the tag 16782 * {@link #VIEW_LOG_TAG}. 16783 * 16784 * @hide 16785 */ 16786 public void debug() { 16787 debug(0); 16788 } 16789 16790 /** 16791 * Prints information about this view in the log output, with the tag 16792 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16793 * indentation defined by the <code>depth</code>. 16794 * 16795 * @param depth the indentation level 16796 * 16797 * @hide 16798 */ 16799 protected void debug(int depth) { 16800 String output = debugIndent(depth - 1); 16801 16802 output += "+ " + this; 16803 int id = getId(); 16804 if (id != -1) { 16805 output += " (id=" + id + ")"; 16806 } 16807 Object tag = getTag(); 16808 if (tag != null) { 16809 output += " (tag=" + tag + ")"; 16810 } 16811 Log.d(VIEW_LOG_TAG, output); 16812 16813 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16814 output = debugIndent(depth) + " FOCUSED"; 16815 Log.d(VIEW_LOG_TAG, output); 16816 } 16817 16818 output = debugIndent(depth); 16819 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16820 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16821 + "} "; 16822 Log.d(VIEW_LOG_TAG, output); 16823 16824 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16825 || mPaddingBottom != 0) { 16826 output = debugIndent(depth); 16827 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16828 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16829 Log.d(VIEW_LOG_TAG, output); 16830 } 16831 16832 output = debugIndent(depth); 16833 output += "mMeasureWidth=" + mMeasuredWidth + 16834 " mMeasureHeight=" + mMeasuredHeight; 16835 Log.d(VIEW_LOG_TAG, output); 16836 16837 output = debugIndent(depth); 16838 if (mLayoutParams == null) { 16839 output += "BAD! no layout params"; 16840 } else { 16841 output = mLayoutParams.debug(output); 16842 } 16843 Log.d(VIEW_LOG_TAG, output); 16844 16845 output = debugIndent(depth); 16846 output += "flags={"; 16847 output += View.printFlags(mViewFlags); 16848 output += "}"; 16849 Log.d(VIEW_LOG_TAG, output); 16850 16851 output = debugIndent(depth); 16852 output += "privateFlags={"; 16853 output += View.printPrivateFlags(mPrivateFlags); 16854 output += "}"; 16855 Log.d(VIEW_LOG_TAG, output); 16856 } 16857 16858 /** 16859 * Creates a string of whitespaces used for indentation. 16860 * 16861 * @param depth the indentation level 16862 * @return a String containing (depth * 2 + 3) * 2 white spaces 16863 * 16864 * @hide 16865 */ 16866 protected static String debugIndent(int depth) { 16867 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16868 for (int i = 0; i < (depth * 2) + 3; i++) { 16869 spaces.append(' ').append(' '); 16870 } 16871 return spaces.toString(); 16872 } 16873 16874 /** 16875 * <p>Return the offset of the widget's text baseline from the widget's top 16876 * boundary. If this widget does not support baseline alignment, this 16877 * method returns -1. </p> 16878 * 16879 * @return the offset of the baseline within the widget's bounds or -1 16880 * if baseline alignment is not supported 16881 */ 16882 @ViewDebug.ExportedProperty(category = "layout") 16883 public int getBaseline() { 16884 return -1; 16885 } 16886 16887 /** 16888 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16889 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16890 * a layout pass. 16891 * 16892 * @return whether the view hierarchy is currently undergoing a layout pass 16893 */ 16894 public boolean isInLayout() { 16895 ViewRootImpl viewRoot = getViewRootImpl(); 16896 return (viewRoot != null && viewRoot.isInLayout()); 16897 } 16898 16899 /** 16900 * Call this when something has changed which has invalidated the 16901 * layout of this view. This will schedule a layout pass of the view 16902 * tree. This should not be called while the view hierarchy is currently in a layout 16903 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16904 * end of the current layout pass (and then layout will run again) or after the current 16905 * frame is drawn and the next layout occurs. 16906 * 16907 * <p>Subclasses which override this method should call the superclass method to 16908 * handle possible request-during-layout errors correctly.</p> 16909 */ 16910 public void requestLayout() { 16911 if (mMeasureCache != null) mMeasureCache.clear(); 16912 16913 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16914 // Only trigger request-during-layout logic if this is the view requesting it, 16915 // not the views in its parent hierarchy 16916 ViewRootImpl viewRoot = getViewRootImpl(); 16917 if (viewRoot != null && viewRoot.isInLayout()) { 16918 if (!viewRoot.requestLayoutDuringLayout(this)) { 16919 return; 16920 } 16921 } 16922 mAttachInfo.mViewRequestingLayout = this; 16923 } 16924 16925 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16926 mPrivateFlags |= PFLAG_INVALIDATED; 16927 16928 if (mParent != null && !mParent.isLayoutRequested()) { 16929 mParent.requestLayout(); 16930 } 16931 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16932 mAttachInfo.mViewRequestingLayout = null; 16933 } 16934 } 16935 16936 /** 16937 * Forces this view to be laid out during the next layout pass. 16938 * This method does not call requestLayout() or forceLayout() 16939 * on the parent. 16940 */ 16941 public void forceLayout() { 16942 if (mMeasureCache != null) mMeasureCache.clear(); 16943 16944 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16945 mPrivateFlags |= PFLAG_INVALIDATED; 16946 } 16947 16948 /** 16949 * <p> 16950 * This is called to find out how big a view should be. The parent 16951 * supplies constraint information in the width and height parameters. 16952 * </p> 16953 * 16954 * <p> 16955 * The actual measurement work of a view is performed in 16956 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16957 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16958 * </p> 16959 * 16960 * 16961 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16962 * parent 16963 * @param heightMeasureSpec Vertical space requirements as imposed by the 16964 * parent 16965 * 16966 * @see #onMeasure(int, int) 16967 */ 16968 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16969 boolean optical = isLayoutModeOptical(this); 16970 if (optical != isLayoutModeOptical(mParent)) { 16971 Insets insets = getOpticalInsets(); 16972 int oWidth = insets.left + insets.right; 16973 int oHeight = insets.top + insets.bottom; 16974 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 16975 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 16976 } 16977 16978 // Suppress sign extension for the low bytes 16979 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 16980 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 16981 16982 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 16983 widthMeasureSpec != mOldWidthMeasureSpec || 16984 heightMeasureSpec != mOldHeightMeasureSpec) { 16985 16986 // first clears the measured dimension flag 16987 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 16988 16989 resolveRtlPropertiesIfNeeded(); 16990 16991 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 16992 mMeasureCache.indexOfKey(key); 16993 if (cacheIndex < 0 || sIgnoreMeasureCache) { 16994 // measure ourselves, this should set the measured dimension flag back 16995 onMeasure(widthMeasureSpec, heightMeasureSpec); 16996 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16997 } else { 16998 long value = mMeasureCache.valueAt(cacheIndex); 16999 // Casting a long to int drops the high 32 bits, no mask needed 17000 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17001 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17002 } 17003 17004 // flag not set, setMeasuredDimension() was not invoked, we raise 17005 // an exception to warn the developer 17006 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17007 throw new IllegalStateException("onMeasure() did not set the" 17008 + " measured dimension by calling" 17009 + " setMeasuredDimension()"); 17010 } 17011 17012 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17013 } 17014 17015 mOldWidthMeasureSpec = widthMeasureSpec; 17016 mOldHeightMeasureSpec = heightMeasureSpec; 17017 17018 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17019 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17020 } 17021 17022 /** 17023 * <p> 17024 * Measure the view and its content to determine the measured width and the 17025 * measured height. This method is invoked by {@link #measure(int, int)} and 17026 * should be overriden by subclasses to provide accurate and efficient 17027 * measurement of their contents. 17028 * </p> 17029 * 17030 * <p> 17031 * <strong>CONTRACT:</strong> When overriding this method, you 17032 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17033 * measured width and height of this view. Failure to do so will trigger an 17034 * <code>IllegalStateException</code>, thrown by 17035 * {@link #measure(int, int)}. Calling the superclass' 17036 * {@link #onMeasure(int, int)} is a valid use. 17037 * </p> 17038 * 17039 * <p> 17040 * The base class implementation of measure defaults to the background size, 17041 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17042 * override {@link #onMeasure(int, int)} to provide better measurements of 17043 * their content. 17044 * </p> 17045 * 17046 * <p> 17047 * If this method is overridden, it is the subclass's responsibility to make 17048 * sure the measured height and width are at least the view's minimum height 17049 * and width ({@link #getSuggestedMinimumHeight()} and 17050 * {@link #getSuggestedMinimumWidth()}). 17051 * </p> 17052 * 17053 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17054 * The requirements are encoded with 17055 * {@link android.view.View.MeasureSpec}. 17056 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17057 * The requirements are encoded with 17058 * {@link android.view.View.MeasureSpec}. 17059 * 17060 * @see #getMeasuredWidth() 17061 * @see #getMeasuredHeight() 17062 * @see #setMeasuredDimension(int, int) 17063 * @see #getSuggestedMinimumHeight() 17064 * @see #getSuggestedMinimumWidth() 17065 * @see android.view.View.MeasureSpec#getMode(int) 17066 * @see android.view.View.MeasureSpec#getSize(int) 17067 */ 17068 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17069 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17070 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17071 } 17072 17073 /** 17074 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17075 * measured width and measured height. Failing to do so will trigger an 17076 * exception at measurement time.</p> 17077 * 17078 * @param measuredWidth The measured width of this view. May be a complex 17079 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17080 * {@link #MEASURED_STATE_TOO_SMALL}. 17081 * @param measuredHeight The measured height of this view. May be a complex 17082 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17083 * {@link #MEASURED_STATE_TOO_SMALL}. 17084 */ 17085 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17086 boolean optical = isLayoutModeOptical(this); 17087 if (optical != isLayoutModeOptical(mParent)) { 17088 Insets insets = getOpticalInsets(); 17089 int opticalWidth = insets.left + insets.right; 17090 int opticalHeight = insets.top + insets.bottom; 17091 17092 measuredWidth += optical ? opticalWidth : -opticalWidth; 17093 measuredHeight += optical ? opticalHeight : -opticalHeight; 17094 } 17095 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17096 } 17097 17098 /** 17099 * Sets the measured dimension without extra processing for things like optical bounds. 17100 * Useful for reapplying consistent values that have already been cooked with adjustments 17101 * for optical bounds, etc. such as those from the measurement cache. 17102 * 17103 * @param measuredWidth The measured width of this view. May be a complex 17104 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17105 * {@link #MEASURED_STATE_TOO_SMALL}. 17106 * @param measuredHeight The measured height of this view. May be a complex 17107 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17108 * {@link #MEASURED_STATE_TOO_SMALL}. 17109 */ 17110 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17111 mMeasuredWidth = measuredWidth; 17112 mMeasuredHeight = measuredHeight; 17113 17114 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17115 } 17116 17117 /** 17118 * Merge two states as returned by {@link #getMeasuredState()}. 17119 * @param curState The current state as returned from a view or the result 17120 * of combining multiple views. 17121 * @param newState The new view state to combine. 17122 * @return Returns a new integer reflecting the combination of the two 17123 * states. 17124 */ 17125 public static int combineMeasuredStates(int curState, int newState) { 17126 return curState | newState; 17127 } 17128 17129 /** 17130 * Version of {@link #resolveSizeAndState(int, int, int)} 17131 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17132 */ 17133 public static int resolveSize(int size, int measureSpec) { 17134 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17135 } 17136 17137 /** 17138 * Utility to reconcile a desired size and state, with constraints imposed 17139 * by a MeasureSpec. Will take the desired size, unless a different size 17140 * is imposed by the constraints. The returned value is a compound integer, 17141 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17142 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17143 * size is smaller than the size the view wants to be. 17144 * 17145 * @param size How big the view wants to be 17146 * @param measureSpec Constraints imposed by the parent 17147 * @return Size information bit mask as defined by 17148 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17149 */ 17150 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17151 int result = size; 17152 int specMode = MeasureSpec.getMode(measureSpec); 17153 int specSize = MeasureSpec.getSize(measureSpec); 17154 switch (specMode) { 17155 case MeasureSpec.UNSPECIFIED: 17156 result = size; 17157 break; 17158 case MeasureSpec.AT_MOST: 17159 if (specSize < size) { 17160 result = specSize | MEASURED_STATE_TOO_SMALL; 17161 } else { 17162 result = size; 17163 } 17164 break; 17165 case MeasureSpec.EXACTLY: 17166 result = specSize; 17167 break; 17168 } 17169 return result | (childMeasuredState&MEASURED_STATE_MASK); 17170 } 17171 17172 /** 17173 * Utility to return a default size. Uses the supplied size if the 17174 * MeasureSpec imposed no constraints. Will get larger if allowed 17175 * by the MeasureSpec. 17176 * 17177 * @param size Default size for this view 17178 * @param measureSpec Constraints imposed by the parent 17179 * @return The size this view should be. 17180 */ 17181 public static int getDefaultSize(int size, int measureSpec) { 17182 int result = size; 17183 int specMode = MeasureSpec.getMode(measureSpec); 17184 int specSize = MeasureSpec.getSize(measureSpec); 17185 17186 switch (specMode) { 17187 case MeasureSpec.UNSPECIFIED: 17188 result = size; 17189 break; 17190 case MeasureSpec.AT_MOST: 17191 case MeasureSpec.EXACTLY: 17192 result = specSize; 17193 break; 17194 } 17195 return result; 17196 } 17197 17198 /** 17199 * Returns the suggested minimum height that the view should use. This 17200 * returns the maximum of the view's minimum height 17201 * and the background's minimum height 17202 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17203 * <p> 17204 * When being used in {@link #onMeasure(int, int)}, the caller should still 17205 * ensure the returned height is within the requirements of the parent. 17206 * 17207 * @return The suggested minimum height of the view. 17208 */ 17209 protected int getSuggestedMinimumHeight() { 17210 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17211 17212 } 17213 17214 /** 17215 * Returns the suggested minimum width that the view should use. This 17216 * returns the maximum of the view's minimum width) 17217 * and the background's minimum width 17218 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17219 * <p> 17220 * When being used in {@link #onMeasure(int, int)}, the caller should still 17221 * ensure the returned width is within the requirements of the parent. 17222 * 17223 * @return The suggested minimum width of the view. 17224 */ 17225 protected int getSuggestedMinimumWidth() { 17226 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17227 } 17228 17229 /** 17230 * Returns the minimum height of the view. 17231 * 17232 * @return the minimum height the view will try to be. 17233 * 17234 * @see #setMinimumHeight(int) 17235 * 17236 * @attr ref android.R.styleable#View_minHeight 17237 */ 17238 public int getMinimumHeight() { 17239 return mMinHeight; 17240 } 17241 17242 /** 17243 * Sets the minimum height of the view. It is not guaranteed the view will 17244 * be able to achieve this minimum height (for example, if its parent layout 17245 * constrains it with less available height). 17246 * 17247 * @param minHeight The minimum height the view will try to be. 17248 * 17249 * @see #getMinimumHeight() 17250 * 17251 * @attr ref android.R.styleable#View_minHeight 17252 */ 17253 public void setMinimumHeight(int minHeight) { 17254 mMinHeight = minHeight; 17255 requestLayout(); 17256 } 17257 17258 /** 17259 * Returns the minimum width of the view. 17260 * 17261 * @return the minimum width the view will try to be. 17262 * 17263 * @see #setMinimumWidth(int) 17264 * 17265 * @attr ref android.R.styleable#View_minWidth 17266 */ 17267 public int getMinimumWidth() { 17268 return mMinWidth; 17269 } 17270 17271 /** 17272 * Sets the minimum width of the view. It is not guaranteed the view will 17273 * be able to achieve this minimum width (for example, if its parent layout 17274 * constrains it with less available width). 17275 * 17276 * @param minWidth The minimum width the view will try to be. 17277 * 17278 * @see #getMinimumWidth() 17279 * 17280 * @attr ref android.R.styleable#View_minWidth 17281 */ 17282 public void setMinimumWidth(int minWidth) { 17283 mMinWidth = minWidth; 17284 requestLayout(); 17285 17286 } 17287 17288 /** 17289 * Get the animation currently associated with this view. 17290 * 17291 * @return The animation that is currently playing or 17292 * scheduled to play for this view. 17293 */ 17294 public Animation getAnimation() { 17295 return mCurrentAnimation; 17296 } 17297 17298 /** 17299 * Start the specified animation now. 17300 * 17301 * @param animation the animation to start now 17302 */ 17303 public void startAnimation(Animation animation) { 17304 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17305 setAnimation(animation); 17306 invalidateParentCaches(); 17307 invalidate(true); 17308 } 17309 17310 /** 17311 * Cancels any animations for this view. 17312 */ 17313 public void clearAnimation() { 17314 if (mCurrentAnimation != null) { 17315 mCurrentAnimation.detach(); 17316 } 17317 mCurrentAnimation = null; 17318 invalidateParentIfNeeded(); 17319 } 17320 17321 /** 17322 * Sets the next animation to play for this view. 17323 * If you want the animation to play immediately, use 17324 * {@link #startAnimation(android.view.animation.Animation)} instead. 17325 * This method provides allows fine-grained 17326 * control over the start time and invalidation, but you 17327 * must make sure that 1) the animation has a start time set, and 17328 * 2) the view's parent (which controls animations on its children) 17329 * will be invalidated when the animation is supposed to 17330 * start. 17331 * 17332 * @param animation The next animation, or null. 17333 */ 17334 public void setAnimation(Animation animation) { 17335 mCurrentAnimation = animation; 17336 17337 if (animation != null) { 17338 // If the screen is off assume the animation start time is now instead of 17339 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17340 // would cause the animation to start when the screen turns back on 17341 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17342 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17343 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17344 } 17345 animation.reset(); 17346 } 17347 } 17348 17349 /** 17350 * Invoked by a parent ViewGroup to notify the start of the animation 17351 * currently associated with this view. If you override this method, 17352 * always call super.onAnimationStart(); 17353 * 17354 * @see #setAnimation(android.view.animation.Animation) 17355 * @see #getAnimation() 17356 */ 17357 protected void onAnimationStart() { 17358 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17359 } 17360 17361 /** 17362 * Invoked by a parent ViewGroup to notify the end of the animation 17363 * currently associated with this view. If you override this method, 17364 * always call super.onAnimationEnd(); 17365 * 17366 * @see #setAnimation(android.view.animation.Animation) 17367 * @see #getAnimation() 17368 */ 17369 protected void onAnimationEnd() { 17370 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17371 } 17372 17373 /** 17374 * Invoked if there is a Transform that involves alpha. Subclass that can 17375 * draw themselves with the specified alpha should return true, and then 17376 * respect that alpha when their onDraw() is called. If this returns false 17377 * then the view may be redirected to draw into an offscreen buffer to 17378 * fulfill the request, which will look fine, but may be slower than if the 17379 * subclass handles it internally. The default implementation returns false. 17380 * 17381 * @param alpha The alpha (0..255) to apply to the view's drawing 17382 * @return true if the view can draw with the specified alpha. 17383 */ 17384 protected boolean onSetAlpha(int alpha) { 17385 return false; 17386 } 17387 17388 /** 17389 * This is used by the RootView to perform an optimization when 17390 * the view hierarchy contains one or several SurfaceView. 17391 * SurfaceView is always considered transparent, but its children are not, 17392 * therefore all View objects remove themselves from the global transparent 17393 * region (passed as a parameter to this function). 17394 * 17395 * @param region The transparent region for this ViewAncestor (window). 17396 * 17397 * @return Returns true if the effective visibility of the view at this 17398 * point is opaque, regardless of the transparent region; returns false 17399 * if it is possible for underlying windows to be seen behind the view. 17400 * 17401 * {@hide} 17402 */ 17403 public boolean gatherTransparentRegion(Region region) { 17404 final AttachInfo attachInfo = mAttachInfo; 17405 if (region != null && attachInfo != null) { 17406 final int pflags = mPrivateFlags; 17407 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17408 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17409 // remove it from the transparent region. 17410 final int[] location = attachInfo.mTransparentLocation; 17411 getLocationInWindow(location); 17412 region.op(location[0], location[1], location[0] + mRight - mLeft, 17413 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17414 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 17415 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17416 // exists, so we remove the background drawable's non-transparent 17417 // parts from this transparent region. 17418 applyDrawableToTransparentRegion(mBackground, region); 17419 } 17420 } 17421 return true; 17422 } 17423 17424 /** 17425 * Play a sound effect for this view. 17426 * 17427 * <p>The framework will play sound effects for some built in actions, such as 17428 * clicking, but you may wish to play these effects in your widget, 17429 * for instance, for internal navigation. 17430 * 17431 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17432 * {@link #isSoundEffectsEnabled()} is true. 17433 * 17434 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17435 */ 17436 public void playSoundEffect(int soundConstant) { 17437 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17438 return; 17439 } 17440 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17441 } 17442 17443 /** 17444 * BZZZTT!!1! 17445 * 17446 * <p>Provide haptic feedback to the user for this view. 17447 * 17448 * <p>The framework will provide haptic feedback for some built in actions, 17449 * such as long presses, but you may wish to provide feedback for your 17450 * own widget. 17451 * 17452 * <p>The feedback will only be performed if 17453 * {@link #isHapticFeedbackEnabled()} is true. 17454 * 17455 * @param feedbackConstant One of the constants defined in 17456 * {@link HapticFeedbackConstants} 17457 */ 17458 public boolean performHapticFeedback(int feedbackConstant) { 17459 return performHapticFeedback(feedbackConstant, 0); 17460 } 17461 17462 /** 17463 * BZZZTT!!1! 17464 * 17465 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17466 * 17467 * @param feedbackConstant One of the constants defined in 17468 * {@link HapticFeedbackConstants} 17469 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17470 */ 17471 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17472 if (mAttachInfo == null) { 17473 return false; 17474 } 17475 //noinspection SimplifiableIfStatement 17476 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17477 && !isHapticFeedbackEnabled()) { 17478 return false; 17479 } 17480 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17481 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17482 } 17483 17484 /** 17485 * Request that the visibility of the status bar or other screen/window 17486 * decorations be changed. 17487 * 17488 * <p>This method is used to put the over device UI into temporary modes 17489 * where the user's attention is focused more on the application content, 17490 * by dimming or hiding surrounding system affordances. This is typically 17491 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17492 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17493 * to be placed behind the action bar (and with these flags other system 17494 * affordances) so that smooth transitions between hiding and showing them 17495 * can be done. 17496 * 17497 * <p>Two representative examples of the use of system UI visibility is 17498 * implementing a content browsing application (like a magazine reader) 17499 * and a video playing application. 17500 * 17501 * <p>The first code shows a typical implementation of a View in a content 17502 * browsing application. In this implementation, the application goes 17503 * into a content-oriented mode by hiding the status bar and action bar, 17504 * and putting the navigation elements into lights out mode. The user can 17505 * then interact with content while in this mode. Such an application should 17506 * provide an easy way for the user to toggle out of the mode (such as to 17507 * check information in the status bar or access notifications). In the 17508 * implementation here, this is done simply by tapping on the content. 17509 * 17510 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17511 * content} 17512 * 17513 * <p>This second code sample shows a typical implementation of a View 17514 * in a video playing application. In this situation, while the video is 17515 * playing the application would like to go into a complete full-screen mode, 17516 * to use as much of the display as possible for the video. When in this state 17517 * the user can not interact with the application; the system intercepts 17518 * touching on the screen to pop the UI out of full screen mode. See 17519 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17520 * 17521 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17522 * content} 17523 * 17524 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17525 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17526 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17527 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17528 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17529 */ 17530 public void setSystemUiVisibility(int visibility) { 17531 if (visibility != mSystemUiVisibility) { 17532 mSystemUiVisibility = visibility; 17533 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17534 mParent.recomputeViewAttributes(this); 17535 } 17536 } 17537 } 17538 17539 /** 17540 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17541 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17542 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17543 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17544 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17545 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17546 */ 17547 public int getSystemUiVisibility() { 17548 return mSystemUiVisibility; 17549 } 17550 17551 /** 17552 * Returns the current system UI visibility that is currently set for 17553 * the entire window. This is the combination of the 17554 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17555 * views in the window. 17556 */ 17557 public int getWindowSystemUiVisibility() { 17558 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17559 } 17560 17561 /** 17562 * Override to find out when the window's requested system UI visibility 17563 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17564 * This is different from the callbacks received through 17565 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17566 * in that this is only telling you about the local request of the window, 17567 * not the actual values applied by the system. 17568 */ 17569 public void onWindowSystemUiVisibilityChanged(int visible) { 17570 } 17571 17572 /** 17573 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17574 * the view hierarchy. 17575 */ 17576 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17577 onWindowSystemUiVisibilityChanged(visible); 17578 } 17579 17580 /** 17581 * Set a listener to receive callbacks when the visibility of the system bar changes. 17582 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17583 */ 17584 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17585 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17586 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17587 mParent.recomputeViewAttributes(this); 17588 } 17589 } 17590 17591 /** 17592 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17593 * the view hierarchy. 17594 */ 17595 public void dispatchSystemUiVisibilityChanged(int visibility) { 17596 ListenerInfo li = mListenerInfo; 17597 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17598 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17599 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17600 } 17601 } 17602 17603 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17604 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17605 if (val != mSystemUiVisibility) { 17606 setSystemUiVisibility(val); 17607 return true; 17608 } 17609 return false; 17610 } 17611 17612 /** @hide */ 17613 public void setDisabledSystemUiVisibility(int flags) { 17614 if (mAttachInfo != null) { 17615 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17616 mAttachInfo.mDisabledSystemUiVisibility = flags; 17617 if (mParent != null) { 17618 mParent.recomputeViewAttributes(this); 17619 } 17620 } 17621 } 17622 } 17623 17624 /** 17625 * Creates an image that the system displays during the drag and drop 17626 * operation. This is called a "drag shadow". The default implementation 17627 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17628 * appearance as the given View. The default also positions the center of the drag shadow 17629 * directly under the touch point. If no View is provided (the constructor with no parameters 17630 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17631 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17632 * default is an invisible drag shadow. 17633 * <p> 17634 * You are not required to use the View you provide to the constructor as the basis of the 17635 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17636 * anything you want as the drag shadow. 17637 * </p> 17638 * <p> 17639 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17640 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17641 * size and position of the drag shadow. It uses this data to construct a 17642 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17643 * so that your application can draw the shadow image in the Canvas. 17644 * </p> 17645 * 17646 * <div class="special reference"> 17647 * <h3>Developer Guides</h3> 17648 * <p>For a guide to implementing drag and drop features, read the 17649 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17650 * </div> 17651 */ 17652 public static class DragShadowBuilder { 17653 private final WeakReference<View> mView; 17654 17655 /** 17656 * Constructs a shadow image builder based on a View. By default, the resulting drag 17657 * shadow will have the same appearance and dimensions as the View, with the touch point 17658 * over the center of the View. 17659 * @param view A View. Any View in scope can be used. 17660 */ 17661 public DragShadowBuilder(View view) { 17662 mView = new WeakReference<View>(view); 17663 } 17664 17665 /** 17666 * Construct a shadow builder object with no associated View. This 17667 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17668 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17669 * to supply the drag shadow's dimensions and appearance without 17670 * reference to any View object. If they are not overridden, then the result is an 17671 * invisible drag shadow. 17672 */ 17673 public DragShadowBuilder() { 17674 mView = new WeakReference<View>(null); 17675 } 17676 17677 /** 17678 * Returns the View object that had been passed to the 17679 * {@link #View.DragShadowBuilder(View)} 17680 * constructor. If that View parameter was {@code null} or if the 17681 * {@link #View.DragShadowBuilder()} 17682 * constructor was used to instantiate the builder object, this method will return 17683 * null. 17684 * 17685 * @return The View object associate with this builder object. 17686 */ 17687 @SuppressWarnings({"JavadocReference"}) 17688 final public View getView() { 17689 return mView.get(); 17690 } 17691 17692 /** 17693 * Provides the metrics for the shadow image. These include the dimensions of 17694 * the shadow image, and the point within that shadow that should 17695 * be centered under the touch location while dragging. 17696 * <p> 17697 * The default implementation sets the dimensions of the shadow to be the 17698 * same as the dimensions of the View itself and centers the shadow under 17699 * the touch point. 17700 * </p> 17701 * 17702 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17703 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17704 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17705 * image. 17706 * 17707 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17708 * shadow image that should be underneath the touch point during the drag and drop 17709 * operation. Your application must set {@link android.graphics.Point#x} to the 17710 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17711 */ 17712 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17713 final View view = mView.get(); 17714 if (view != null) { 17715 shadowSize.set(view.getWidth(), view.getHeight()); 17716 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17717 } else { 17718 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17719 } 17720 } 17721 17722 /** 17723 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17724 * based on the dimensions it received from the 17725 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17726 * 17727 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17728 */ 17729 public void onDrawShadow(Canvas canvas) { 17730 final View view = mView.get(); 17731 if (view != null) { 17732 view.draw(canvas); 17733 } else { 17734 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17735 } 17736 } 17737 } 17738 17739 /** 17740 * Starts a drag and drop operation. When your application calls this method, it passes a 17741 * {@link android.view.View.DragShadowBuilder} object to the system. The 17742 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17743 * to get metrics for the drag shadow, and then calls the object's 17744 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17745 * <p> 17746 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17747 * drag events to all the View objects in your application that are currently visible. It does 17748 * this either by calling the View object's drag listener (an implementation of 17749 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17750 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17751 * Both are passed a {@link android.view.DragEvent} object that has a 17752 * {@link android.view.DragEvent#getAction()} value of 17753 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17754 * </p> 17755 * <p> 17756 * Your application can invoke startDrag() on any attached View object. The View object does not 17757 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17758 * be related to the View the user selected for dragging. 17759 * </p> 17760 * @param data A {@link android.content.ClipData} object pointing to the data to be 17761 * transferred by the drag and drop operation. 17762 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17763 * drag shadow. 17764 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17765 * drop operation. This Object is put into every DragEvent object sent by the system during the 17766 * current drag. 17767 * <p> 17768 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17769 * to the target Views. For example, it can contain flags that differentiate between a 17770 * a copy operation and a move operation. 17771 * </p> 17772 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17773 * so the parameter should be set to 0. 17774 * @return {@code true} if the method completes successfully, or 17775 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17776 * do a drag, and so no drag operation is in progress. 17777 */ 17778 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17779 Object myLocalState, int flags) { 17780 if (ViewDebug.DEBUG_DRAG) { 17781 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17782 } 17783 boolean okay = false; 17784 17785 Point shadowSize = new Point(); 17786 Point shadowTouchPoint = new Point(); 17787 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17788 17789 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17790 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17791 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17792 } 17793 17794 if (ViewDebug.DEBUG_DRAG) { 17795 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17796 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17797 } 17798 Surface surface = new Surface(); 17799 try { 17800 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17801 flags, shadowSize.x, shadowSize.y, surface); 17802 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17803 + " surface=" + surface); 17804 if (token != null) { 17805 Canvas canvas = surface.lockCanvas(null); 17806 try { 17807 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17808 shadowBuilder.onDrawShadow(canvas); 17809 } finally { 17810 surface.unlockCanvasAndPost(canvas); 17811 } 17812 17813 final ViewRootImpl root = getViewRootImpl(); 17814 17815 // Cache the local state object for delivery with DragEvents 17816 root.setLocalDragState(myLocalState); 17817 17818 // repurpose 'shadowSize' for the last touch point 17819 root.getLastTouchPoint(shadowSize); 17820 17821 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17822 shadowSize.x, shadowSize.y, 17823 shadowTouchPoint.x, shadowTouchPoint.y, data); 17824 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17825 17826 // Off and running! Release our local surface instance; the drag 17827 // shadow surface is now managed by the system process. 17828 surface.release(); 17829 } 17830 } catch (Exception e) { 17831 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17832 surface.destroy(); 17833 } 17834 17835 return okay; 17836 } 17837 17838 /** 17839 * Handles drag events sent by the system following a call to 17840 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17841 *<p> 17842 * When the system calls this method, it passes a 17843 * {@link android.view.DragEvent} object. A call to 17844 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17845 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17846 * operation. 17847 * @param event The {@link android.view.DragEvent} sent by the system. 17848 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17849 * in DragEvent, indicating the type of drag event represented by this object. 17850 * @return {@code true} if the method was successful, otherwise {@code false}. 17851 * <p> 17852 * The method should return {@code true} in response to an action type of 17853 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17854 * operation. 17855 * </p> 17856 * <p> 17857 * The method should also return {@code true} in response to an action type of 17858 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17859 * {@code false} if it didn't. 17860 * </p> 17861 */ 17862 public boolean onDragEvent(DragEvent event) { 17863 return false; 17864 } 17865 17866 /** 17867 * Detects if this View is enabled and has a drag event listener. 17868 * If both are true, then it calls the drag event listener with the 17869 * {@link android.view.DragEvent} it received. If the drag event listener returns 17870 * {@code true}, then dispatchDragEvent() returns {@code true}. 17871 * <p> 17872 * For all other cases, the method calls the 17873 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17874 * method and returns its result. 17875 * </p> 17876 * <p> 17877 * This ensures that a drag event is always consumed, even if the View does not have a drag 17878 * event listener. However, if the View has a listener and the listener returns true, then 17879 * onDragEvent() is not called. 17880 * </p> 17881 */ 17882 public boolean dispatchDragEvent(DragEvent event) { 17883 ListenerInfo li = mListenerInfo; 17884 //noinspection SimplifiableIfStatement 17885 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17886 && li.mOnDragListener.onDrag(this, event)) { 17887 return true; 17888 } 17889 return onDragEvent(event); 17890 } 17891 17892 boolean canAcceptDrag() { 17893 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17894 } 17895 17896 /** 17897 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17898 * it is ever exposed at all. 17899 * @hide 17900 */ 17901 public void onCloseSystemDialogs(String reason) { 17902 } 17903 17904 /** 17905 * Given a Drawable whose bounds have been set to draw into this view, 17906 * update a Region being computed for 17907 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17908 * that any non-transparent parts of the Drawable are removed from the 17909 * given transparent region. 17910 * 17911 * @param dr The Drawable whose transparency is to be applied to the region. 17912 * @param region A Region holding the current transparency information, 17913 * where any parts of the region that are set are considered to be 17914 * transparent. On return, this region will be modified to have the 17915 * transparency information reduced by the corresponding parts of the 17916 * Drawable that are not transparent. 17917 * {@hide} 17918 */ 17919 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17920 if (DBG) { 17921 Log.i("View", "Getting transparent region for: " + this); 17922 } 17923 final Region r = dr.getTransparentRegion(); 17924 final Rect db = dr.getBounds(); 17925 final AttachInfo attachInfo = mAttachInfo; 17926 if (r != null && attachInfo != null) { 17927 final int w = getRight()-getLeft(); 17928 final int h = getBottom()-getTop(); 17929 if (db.left > 0) { 17930 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17931 r.op(0, 0, db.left, h, Region.Op.UNION); 17932 } 17933 if (db.right < w) { 17934 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17935 r.op(db.right, 0, w, h, Region.Op.UNION); 17936 } 17937 if (db.top > 0) { 17938 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17939 r.op(0, 0, w, db.top, Region.Op.UNION); 17940 } 17941 if (db.bottom < h) { 17942 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17943 r.op(0, db.bottom, w, h, Region.Op.UNION); 17944 } 17945 final int[] location = attachInfo.mTransparentLocation; 17946 getLocationInWindow(location); 17947 r.translate(location[0], location[1]); 17948 region.op(r, Region.Op.INTERSECT); 17949 } else { 17950 region.op(db, Region.Op.DIFFERENCE); 17951 } 17952 } 17953 17954 private void checkForLongClick(int delayOffset) { 17955 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17956 mHasPerformedLongPress = false; 17957 17958 if (mPendingCheckForLongPress == null) { 17959 mPendingCheckForLongPress = new CheckForLongPress(); 17960 } 17961 mPendingCheckForLongPress.rememberWindowAttachCount(); 17962 postDelayed(mPendingCheckForLongPress, 17963 ViewConfiguration.getLongPressTimeout() - delayOffset); 17964 } 17965 } 17966 17967 /** 17968 * Inflate a view from an XML resource. This convenience method wraps the {@link 17969 * LayoutInflater} class, which provides a full range of options for view inflation. 17970 * 17971 * @param context The Context object for your activity or application. 17972 * @param resource The resource ID to inflate 17973 * @param root A view group that will be the parent. Used to properly inflate the 17974 * layout_* parameters. 17975 * @see LayoutInflater 17976 */ 17977 public static View inflate(Context context, int resource, ViewGroup root) { 17978 LayoutInflater factory = LayoutInflater.from(context); 17979 return factory.inflate(resource, root); 17980 } 17981 17982 /** 17983 * Scroll the view with standard behavior for scrolling beyond the normal 17984 * content boundaries. Views that call this method should override 17985 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 17986 * results of an over-scroll operation. 17987 * 17988 * Views can use this method to handle any touch or fling-based scrolling. 17989 * 17990 * @param deltaX Change in X in pixels 17991 * @param deltaY Change in Y in pixels 17992 * @param scrollX Current X scroll value in pixels before applying deltaX 17993 * @param scrollY Current Y scroll value in pixels before applying deltaY 17994 * @param scrollRangeX Maximum content scroll range along the X axis 17995 * @param scrollRangeY Maximum content scroll range along the Y axis 17996 * @param maxOverScrollX Number of pixels to overscroll by in either direction 17997 * along the X axis. 17998 * @param maxOverScrollY Number of pixels to overscroll by in either direction 17999 * along the Y axis. 18000 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18001 * @return true if scrolling was clamped to an over-scroll boundary along either 18002 * axis, false otherwise. 18003 */ 18004 @SuppressWarnings({"UnusedParameters"}) 18005 protected boolean overScrollBy(int deltaX, int deltaY, 18006 int scrollX, int scrollY, 18007 int scrollRangeX, int scrollRangeY, 18008 int maxOverScrollX, int maxOverScrollY, 18009 boolean isTouchEvent) { 18010 final int overScrollMode = mOverScrollMode; 18011 final boolean canScrollHorizontal = 18012 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18013 final boolean canScrollVertical = 18014 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18015 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18016 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18017 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18018 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18019 18020 int newScrollX = scrollX + deltaX; 18021 if (!overScrollHorizontal) { 18022 maxOverScrollX = 0; 18023 } 18024 18025 int newScrollY = scrollY + deltaY; 18026 if (!overScrollVertical) { 18027 maxOverScrollY = 0; 18028 } 18029 18030 // Clamp values if at the limits and record 18031 final int left = -maxOverScrollX; 18032 final int right = maxOverScrollX + scrollRangeX; 18033 final int top = -maxOverScrollY; 18034 final int bottom = maxOverScrollY + scrollRangeY; 18035 18036 boolean clampedX = false; 18037 if (newScrollX > right) { 18038 newScrollX = right; 18039 clampedX = true; 18040 } else if (newScrollX < left) { 18041 newScrollX = left; 18042 clampedX = true; 18043 } 18044 18045 boolean clampedY = false; 18046 if (newScrollY > bottom) { 18047 newScrollY = bottom; 18048 clampedY = true; 18049 } else if (newScrollY < top) { 18050 newScrollY = top; 18051 clampedY = true; 18052 } 18053 18054 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18055 18056 return clampedX || clampedY; 18057 } 18058 18059 /** 18060 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18061 * respond to the results of an over-scroll operation. 18062 * 18063 * @param scrollX New X scroll value in pixels 18064 * @param scrollY New Y scroll value in pixels 18065 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18066 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18067 */ 18068 protected void onOverScrolled(int scrollX, int scrollY, 18069 boolean clampedX, boolean clampedY) { 18070 // Intentionally empty. 18071 } 18072 18073 /** 18074 * Returns the over-scroll mode for this view. The result will be 18075 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18076 * (allow over-scrolling only if the view content is larger than the container), 18077 * or {@link #OVER_SCROLL_NEVER}. 18078 * 18079 * @return This view's over-scroll mode. 18080 */ 18081 public int getOverScrollMode() { 18082 return mOverScrollMode; 18083 } 18084 18085 /** 18086 * Set the over-scroll mode for this view. Valid over-scroll modes are 18087 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18088 * (allow over-scrolling only if the view content is larger than the container), 18089 * or {@link #OVER_SCROLL_NEVER}. 18090 * 18091 * Setting the over-scroll mode of a view will have an effect only if the 18092 * view is capable of scrolling. 18093 * 18094 * @param overScrollMode The new over-scroll mode for this view. 18095 */ 18096 public void setOverScrollMode(int overScrollMode) { 18097 if (overScrollMode != OVER_SCROLL_ALWAYS && 18098 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18099 overScrollMode != OVER_SCROLL_NEVER) { 18100 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18101 } 18102 mOverScrollMode = overScrollMode; 18103 } 18104 18105 /** 18106 * Enable or disable nested scrolling for this view. 18107 * 18108 * <p>If this property is set to true the view will be permitted to initiate nested 18109 * scrolling operations with a compatible parent view in the current hierarchy. If this 18110 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18111 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18112 * the nested scroll.</p> 18113 * 18114 * @param enabled true to enable nested scrolling, false to disable 18115 * 18116 * @see #isNestedScrollingEnabled() 18117 */ 18118 public void setNestedScrollingEnabled(boolean enabled) { 18119 if (enabled) { 18120 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18121 } else { 18122 stopNestedScroll(); 18123 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18124 } 18125 } 18126 18127 /** 18128 * Returns true if nested scrolling is enabled for this view. 18129 * 18130 * <p>If nested scrolling is enabled and this View class implementation supports it, 18131 * this view will act as a nested scrolling child view when applicable, forwarding data 18132 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18133 * parent.</p> 18134 * 18135 * @return true if nested scrolling is enabled 18136 * 18137 * @see #setNestedScrollingEnabled(boolean) 18138 */ 18139 public boolean isNestedScrollingEnabled() { 18140 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18141 PFLAG3_NESTED_SCROLLING_ENABLED; 18142 } 18143 18144 /** 18145 * Begin a nestable scroll operation along the given axes. 18146 * 18147 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18148 * 18149 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18150 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18151 * In the case of touch scrolling the nested scroll will be terminated automatically in 18152 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18153 * In the event of programmatic scrolling the caller must explicitly call 18154 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18155 * 18156 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18157 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18158 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18159 * 18160 * <p>At each incremental step of the scroll the caller should invoke 18161 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18162 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18163 * parent at least partially consumed the scroll and the caller should adjust the amount it 18164 * scrolls by.</p> 18165 * 18166 * <p>After applying the remainder of the scroll delta the caller should invoke 18167 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18168 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18169 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18170 * </p> 18171 * 18172 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18173 * {@link #SCROLL_AXIS_VERTICAL}. 18174 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18175 * the current gesture. 18176 * 18177 * @see #stopNestedScroll() 18178 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18179 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18180 */ 18181 public boolean startNestedScroll(int axes) { 18182 if (hasNestedScrollingParent()) { 18183 // Already in progress 18184 return true; 18185 } 18186 if (isNestedScrollingEnabled()) { 18187 ViewParent p = getParent(); 18188 View child = this; 18189 while (p != null) { 18190 try { 18191 if (p.onStartNestedScroll(child, this, axes)) { 18192 mNestedScrollingParent = p; 18193 p.onNestedScrollAccepted(child, this, axes); 18194 return true; 18195 } 18196 } catch (AbstractMethodError e) { 18197 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18198 "method onStartNestedScroll", e); 18199 // Allow the search upward to continue 18200 } 18201 if (p instanceof View) { 18202 child = (View) p; 18203 } 18204 p = p.getParent(); 18205 } 18206 } 18207 return false; 18208 } 18209 18210 /** 18211 * Stop a nested scroll in progress. 18212 * 18213 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18214 * 18215 * @see #startNestedScroll(int) 18216 */ 18217 public void stopNestedScroll() { 18218 if (mNestedScrollingParent != null) { 18219 mNestedScrollingParent.onStopNestedScroll(this); 18220 mNestedScrollingParent = null; 18221 } 18222 } 18223 18224 /** 18225 * Returns true if this view has a nested scrolling parent. 18226 * 18227 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18228 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18229 * 18230 * @return whether this view has a nested scrolling parent 18231 */ 18232 public boolean hasNestedScrollingParent() { 18233 return mNestedScrollingParent != null; 18234 } 18235 18236 /** 18237 * Dispatch one step of a nested scroll in progress. 18238 * 18239 * <p>Implementations of views that support nested scrolling should call this to report 18240 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18241 * is not currently in progress or nested scrolling is not 18242 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18243 * 18244 * <p>Compatible View implementations should also call 18245 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18246 * consuming a component of the scroll event themselves.</p> 18247 * 18248 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18249 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18250 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18251 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18252 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18253 * in local view coordinates of this view from before this operation 18254 * to after it completes. View implementations may use this to adjust 18255 * expected input coordinate tracking. 18256 * @return true if the event was dispatched, false if it could not be dispatched. 18257 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18258 */ 18259 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18260 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18261 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18262 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18263 int startX = 0; 18264 int startY = 0; 18265 if (offsetInWindow != null) { 18266 getLocationInWindow(offsetInWindow); 18267 startX = offsetInWindow[0]; 18268 startY = offsetInWindow[1]; 18269 } 18270 18271 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18272 dxUnconsumed, dyUnconsumed); 18273 18274 if (offsetInWindow != null) { 18275 getLocationInWindow(offsetInWindow); 18276 offsetInWindow[0] -= startX; 18277 offsetInWindow[1] -= startY; 18278 } 18279 return true; 18280 } else if (offsetInWindow != null) { 18281 // No motion, no dispatch. Keep offsetInWindow up to date. 18282 offsetInWindow[0] = 0; 18283 offsetInWindow[1] = 0; 18284 } 18285 } 18286 return false; 18287 } 18288 18289 /** 18290 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18291 * 18292 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18293 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18294 * scrolling operation to consume some or all of the scroll operation before the child view 18295 * consumes it.</p> 18296 * 18297 * @param dx Horizontal scroll distance in pixels 18298 * @param dy Vertical scroll distance in pixels 18299 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18300 * and consumed[1] the consumed dy. 18301 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18302 * in local view coordinates of this view from before this operation 18303 * to after it completes. View implementations may use this to adjust 18304 * expected input coordinate tracking. 18305 * @return true if the parent consumed some or all of the scroll delta 18306 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18307 */ 18308 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18309 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18310 if (dx != 0 || dy != 0) { 18311 int startX = 0; 18312 int startY = 0; 18313 if (offsetInWindow != null) { 18314 getLocationInWindow(offsetInWindow); 18315 startX = offsetInWindow[0]; 18316 startY = offsetInWindow[1]; 18317 } 18318 18319 if (consumed == null) { 18320 if (mTempNestedScrollConsumed == null) { 18321 mTempNestedScrollConsumed = new int[2]; 18322 } 18323 consumed = mTempNestedScrollConsumed; 18324 } 18325 consumed[0] = 0; 18326 consumed[1] = 0; 18327 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18328 18329 if (offsetInWindow != null) { 18330 getLocationInWindow(offsetInWindow); 18331 offsetInWindow[0] -= startX; 18332 offsetInWindow[1] -= startY; 18333 } 18334 return consumed[0] != 0 || consumed[1] != 0; 18335 } else if (offsetInWindow != null) { 18336 offsetInWindow[0] = 0; 18337 offsetInWindow[1] = 0; 18338 } 18339 } 18340 return false; 18341 } 18342 18343 /** 18344 * Dispatch a fling to a nested scrolling parent. 18345 * 18346 * <p>This method should be used to indicate that a nested scrolling child has detected 18347 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18348 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18349 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18350 * along a scrollable axis.</p> 18351 * 18352 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18353 * its own content, it can use this method to delegate the fling to its nested scrolling 18354 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18355 * 18356 * @param velocityX Horizontal fling velocity in pixels per second 18357 * @param velocityY Vertical fling velocity in pixels per second 18358 * @param consumed true if the child consumed the fling, false otherwise 18359 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18360 */ 18361 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18362 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18363 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18364 } 18365 return false; 18366 } 18367 18368 /** 18369 * Gets a scale factor that determines the distance the view should scroll 18370 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18371 * @return The vertical scroll scale factor. 18372 * @hide 18373 */ 18374 protected float getVerticalScrollFactor() { 18375 if (mVerticalScrollFactor == 0) { 18376 TypedValue outValue = new TypedValue(); 18377 if (!mContext.getTheme().resolveAttribute( 18378 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18379 throw new IllegalStateException( 18380 "Expected theme to define listPreferredItemHeight."); 18381 } 18382 mVerticalScrollFactor = outValue.getDimension( 18383 mContext.getResources().getDisplayMetrics()); 18384 } 18385 return mVerticalScrollFactor; 18386 } 18387 18388 /** 18389 * Gets a scale factor that determines the distance the view should scroll 18390 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18391 * @return The horizontal scroll scale factor. 18392 * @hide 18393 */ 18394 protected float getHorizontalScrollFactor() { 18395 // TODO: Should use something else. 18396 return getVerticalScrollFactor(); 18397 } 18398 18399 /** 18400 * Return the value specifying the text direction or policy that was set with 18401 * {@link #setTextDirection(int)}. 18402 * 18403 * @return the defined text direction. It can be one of: 18404 * 18405 * {@link #TEXT_DIRECTION_INHERIT}, 18406 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18407 * {@link #TEXT_DIRECTION_ANY_RTL}, 18408 * {@link #TEXT_DIRECTION_LTR}, 18409 * {@link #TEXT_DIRECTION_RTL}, 18410 * {@link #TEXT_DIRECTION_LOCALE} 18411 * 18412 * @attr ref android.R.styleable#View_textDirection 18413 * 18414 * @hide 18415 */ 18416 @ViewDebug.ExportedProperty(category = "text", mapping = { 18417 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18418 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18419 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18420 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18421 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18422 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18423 }) 18424 public int getRawTextDirection() { 18425 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18426 } 18427 18428 /** 18429 * Set the text direction. 18430 * 18431 * @param textDirection the direction to set. Should be one of: 18432 * 18433 * {@link #TEXT_DIRECTION_INHERIT}, 18434 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18435 * {@link #TEXT_DIRECTION_ANY_RTL}, 18436 * {@link #TEXT_DIRECTION_LTR}, 18437 * {@link #TEXT_DIRECTION_RTL}, 18438 * {@link #TEXT_DIRECTION_LOCALE} 18439 * 18440 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18441 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18442 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18443 * 18444 * @attr ref android.R.styleable#View_textDirection 18445 */ 18446 public void setTextDirection(int textDirection) { 18447 if (getRawTextDirection() != textDirection) { 18448 // Reset the current text direction and the resolved one 18449 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18450 resetResolvedTextDirection(); 18451 // Set the new text direction 18452 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18453 // Do resolution 18454 resolveTextDirection(); 18455 // Notify change 18456 onRtlPropertiesChanged(getLayoutDirection()); 18457 // Refresh 18458 requestLayout(); 18459 invalidate(true); 18460 } 18461 } 18462 18463 /** 18464 * Return the resolved text direction. 18465 * 18466 * @return the resolved text direction. Returns one of: 18467 * 18468 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18469 * {@link #TEXT_DIRECTION_ANY_RTL}, 18470 * {@link #TEXT_DIRECTION_LTR}, 18471 * {@link #TEXT_DIRECTION_RTL}, 18472 * {@link #TEXT_DIRECTION_LOCALE} 18473 * 18474 * @attr ref android.R.styleable#View_textDirection 18475 */ 18476 @ViewDebug.ExportedProperty(category = "text", mapping = { 18477 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18478 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18479 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18480 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18481 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18482 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18483 }) 18484 public int getTextDirection() { 18485 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18486 } 18487 18488 /** 18489 * Resolve the text direction. 18490 * 18491 * @return true if resolution has been done, false otherwise. 18492 * 18493 * @hide 18494 */ 18495 public boolean resolveTextDirection() { 18496 // Reset any previous text direction resolution 18497 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18498 18499 if (hasRtlSupport()) { 18500 // Set resolved text direction flag depending on text direction flag 18501 final int textDirection = getRawTextDirection(); 18502 switch(textDirection) { 18503 case TEXT_DIRECTION_INHERIT: 18504 if (!canResolveTextDirection()) { 18505 // We cannot do the resolution if there is no parent, so use the default one 18506 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18507 // Resolution will need to happen again later 18508 return false; 18509 } 18510 18511 // Parent has not yet resolved, so we still return the default 18512 try { 18513 if (!mParent.isTextDirectionResolved()) { 18514 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18515 // Resolution will need to happen again later 18516 return false; 18517 } 18518 } catch (AbstractMethodError e) { 18519 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18520 " does not fully implement ViewParent", e); 18521 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18522 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18523 return true; 18524 } 18525 18526 // Set current resolved direction to the same value as the parent's one 18527 int parentResolvedDirection; 18528 try { 18529 parentResolvedDirection = mParent.getTextDirection(); 18530 } catch (AbstractMethodError e) { 18531 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18532 " does not fully implement ViewParent", e); 18533 parentResolvedDirection = TEXT_DIRECTION_LTR; 18534 } 18535 switch (parentResolvedDirection) { 18536 case TEXT_DIRECTION_FIRST_STRONG: 18537 case TEXT_DIRECTION_ANY_RTL: 18538 case TEXT_DIRECTION_LTR: 18539 case TEXT_DIRECTION_RTL: 18540 case TEXT_DIRECTION_LOCALE: 18541 mPrivateFlags2 |= 18542 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18543 break; 18544 default: 18545 // Default resolved direction is "first strong" heuristic 18546 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18547 } 18548 break; 18549 case TEXT_DIRECTION_FIRST_STRONG: 18550 case TEXT_DIRECTION_ANY_RTL: 18551 case TEXT_DIRECTION_LTR: 18552 case TEXT_DIRECTION_RTL: 18553 case TEXT_DIRECTION_LOCALE: 18554 // Resolved direction is the same as text direction 18555 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18556 break; 18557 default: 18558 // Default resolved direction is "first strong" heuristic 18559 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18560 } 18561 } else { 18562 // Default resolved direction is "first strong" heuristic 18563 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18564 } 18565 18566 // Set to resolved 18567 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18568 return true; 18569 } 18570 18571 /** 18572 * Check if text direction resolution can be done. 18573 * 18574 * @return true if text direction resolution can be done otherwise return false. 18575 */ 18576 public boolean canResolveTextDirection() { 18577 switch (getRawTextDirection()) { 18578 case TEXT_DIRECTION_INHERIT: 18579 if (mParent != null) { 18580 try { 18581 return mParent.canResolveTextDirection(); 18582 } catch (AbstractMethodError e) { 18583 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18584 " does not fully implement ViewParent", e); 18585 } 18586 } 18587 return false; 18588 18589 default: 18590 return true; 18591 } 18592 } 18593 18594 /** 18595 * Reset resolved text direction. Text direction will be resolved during a call to 18596 * {@link #onMeasure(int, int)}. 18597 * 18598 * @hide 18599 */ 18600 public void resetResolvedTextDirection() { 18601 // Reset any previous text direction resolution 18602 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18603 // Set to default value 18604 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18605 } 18606 18607 /** 18608 * @return true if text direction is inherited. 18609 * 18610 * @hide 18611 */ 18612 public boolean isTextDirectionInherited() { 18613 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18614 } 18615 18616 /** 18617 * @return true if text direction is resolved. 18618 */ 18619 public boolean isTextDirectionResolved() { 18620 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18621 } 18622 18623 /** 18624 * Return the value specifying the text alignment or policy that was set with 18625 * {@link #setTextAlignment(int)}. 18626 * 18627 * @return the defined text alignment. It can be one of: 18628 * 18629 * {@link #TEXT_ALIGNMENT_INHERIT}, 18630 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18631 * {@link #TEXT_ALIGNMENT_CENTER}, 18632 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18633 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18634 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18635 * {@link #TEXT_ALIGNMENT_VIEW_END} 18636 * 18637 * @attr ref android.R.styleable#View_textAlignment 18638 * 18639 * @hide 18640 */ 18641 @ViewDebug.ExportedProperty(category = "text", mapping = { 18642 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18643 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18644 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18645 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18646 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18647 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18648 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18649 }) 18650 @TextAlignment 18651 public int getRawTextAlignment() { 18652 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18653 } 18654 18655 /** 18656 * Set the text alignment. 18657 * 18658 * @param textAlignment The text alignment to set. Should be one of 18659 * 18660 * {@link #TEXT_ALIGNMENT_INHERIT}, 18661 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18662 * {@link #TEXT_ALIGNMENT_CENTER}, 18663 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18664 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18665 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18666 * {@link #TEXT_ALIGNMENT_VIEW_END} 18667 * 18668 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18669 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18670 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18671 * 18672 * @attr ref android.R.styleable#View_textAlignment 18673 */ 18674 public void setTextAlignment(@TextAlignment int textAlignment) { 18675 if (textAlignment != getRawTextAlignment()) { 18676 // Reset the current and resolved text alignment 18677 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18678 resetResolvedTextAlignment(); 18679 // Set the new text alignment 18680 mPrivateFlags2 |= 18681 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18682 // Do resolution 18683 resolveTextAlignment(); 18684 // Notify change 18685 onRtlPropertiesChanged(getLayoutDirection()); 18686 // Refresh 18687 requestLayout(); 18688 invalidate(true); 18689 } 18690 } 18691 18692 /** 18693 * Return the resolved text alignment. 18694 * 18695 * @return the resolved text alignment. Returns one of: 18696 * 18697 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18698 * {@link #TEXT_ALIGNMENT_CENTER}, 18699 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18700 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18701 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18702 * {@link #TEXT_ALIGNMENT_VIEW_END} 18703 * 18704 * @attr ref android.R.styleable#View_textAlignment 18705 */ 18706 @ViewDebug.ExportedProperty(category = "text", mapping = { 18707 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18708 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18709 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18710 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18711 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18712 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18713 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18714 }) 18715 @TextAlignment 18716 public int getTextAlignment() { 18717 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18718 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18719 } 18720 18721 /** 18722 * Resolve the text alignment. 18723 * 18724 * @return true if resolution has been done, false otherwise. 18725 * 18726 * @hide 18727 */ 18728 public boolean resolveTextAlignment() { 18729 // Reset any previous text alignment resolution 18730 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18731 18732 if (hasRtlSupport()) { 18733 // Set resolved text alignment flag depending on text alignment flag 18734 final int textAlignment = getRawTextAlignment(); 18735 switch (textAlignment) { 18736 case TEXT_ALIGNMENT_INHERIT: 18737 // Check if we can resolve the text alignment 18738 if (!canResolveTextAlignment()) { 18739 // We cannot do the resolution if there is no parent so use the default 18740 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18741 // Resolution will need to happen again later 18742 return false; 18743 } 18744 18745 // Parent has not yet resolved, so we still return the default 18746 try { 18747 if (!mParent.isTextAlignmentResolved()) { 18748 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18749 // Resolution will need to happen again later 18750 return false; 18751 } 18752 } catch (AbstractMethodError e) { 18753 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18754 " does not fully implement ViewParent", e); 18755 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18756 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18757 return true; 18758 } 18759 18760 int parentResolvedTextAlignment; 18761 try { 18762 parentResolvedTextAlignment = mParent.getTextAlignment(); 18763 } catch (AbstractMethodError e) { 18764 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18765 " does not fully implement ViewParent", e); 18766 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18767 } 18768 switch (parentResolvedTextAlignment) { 18769 case TEXT_ALIGNMENT_GRAVITY: 18770 case TEXT_ALIGNMENT_TEXT_START: 18771 case TEXT_ALIGNMENT_TEXT_END: 18772 case TEXT_ALIGNMENT_CENTER: 18773 case TEXT_ALIGNMENT_VIEW_START: 18774 case TEXT_ALIGNMENT_VIEW_END: 18775 // Resolved text alignment is the same as the parent resolved 18776 // text alignment 18777 mPrivateFlags2 |= 18778 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18779 break; 18780 default: 18781 // Use default resolved text alignment 18782 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18783 } 18784 break; 18785 case TEXT_ALIGNMENT_GRAVITY: 18786 case TEXT_ALIGNMENT_TEXT_START: 18787 case TEXT_ALIGNMENT_TEXT_END: 18788 case TEXT_ALIGNMENT_CENTER: 18789 case TEXT_ALIGNMENT_VIEW_START: 18790 case TEXT_ALIGNMENT_VIEW_END: 18791 // Resolved text alignment is the same as text alignment 18792 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18793 break; 18794 default: 18795 // Use default resolved text alignment 18796 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18797 } 18798 } else { 18799 // Use default resolved text alignment 18800 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18801 } 18802 18803 // Set the resolved 18804 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18805 return true; 18806 } 18807 18808 /** 18809 * Check if text alignment resolution can be done. 18810 * 18811 * @return true if text alignment resolution can be done otherwise return false. 18812 */ 18813 public boolean canResolveTextAlignment() { 18814 switch (getRawTextAlignment()) { 18815 case TEXT_DIRECTION_INHERIT: 18816 if (mParent != null) { 18817 try { 18818 return mParent.canResolveTextAlignment(); 18819 } catch (AbstractMethodError e) { 18820 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18821 " does not fully implement ViewParent", e); 18822 } 18823 } 18824 return false; 18825 18826 default: 18827 return true; 18828 } 18829 } 18830 18831 /** 18832 * Reset resolved text alignment. Text alignment will be resolved during a call to 18833 * {@link #onMeasure(int, int)}. 18834 * 18835 * @hide 18836 */ 18837 public void resetResolvedTextAlignment() { 18838 // Reset any previous text alignment resolution 18839 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18840 // Set to default 18841 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18842 } 18843 18844 /** 18845 * @return true if text alignment is inherited. 18846 * 18847 * @hide 18848 */ 18849 public boolean isTextAlignmentInherited() { 18850 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18851 } 18852 18853 /** 18854 * @return true if text alignment is resolved. 18855 */ 18856 public boolean isTextAlignmentResolved() { 18857 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18858 } 18859 18860 /** 18861 * Generate a value suitable for use in {@link #setId(int)}. 18862 * This value will not collide with ID values generated at build time by aapt for R.id. 18863 * 18864 * @return a generated ID value 18865 */ 18866 public static int generateViewId() { 18867 for (;;) { 18868 final int result = sNextGeneratedId.get(); 18869 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18870 int newValue = result + 1; 18871 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18872 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18873 return result; 18874 } 18875 } 18876 } 18877 18878 /** 18879 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 18880 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 18881 * a normal View or a ViewGroup with 18882 * {@link android.view.ViewGroup#isTransitionGroup()} true. 18883 * @hide 18884 */ 18885 public void captureTransitioningViews(List<View> transitioningViews) { 18886 if (getVisibility() == View.VISIBLE) { 18887 transitioningViews.add(this); 18888 } 18889 } 18890 18891 /** 18892 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 18893 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 18894 * @hide 18895 */ 18896 public void findNamedViews(Map<String, View> namedElements) { 18897 if (getVisibility() == VISIBLE) { 18898 String transitionName = getTransitionName(); 18899 if (transitionName != null) { 18900 namedElements.put(transitionName, this); 18901 } 18902 } 18903 } 18904 18905 // 18906 // Properties 18907 // 18908 /** 18909 * A Property wrapper around the <code>alpha</code> functionality handled by the 18910 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18911 */ 18912 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18913 @Override 18914 public void setValue(View object, float value) { 18915 object.setAlpha(value); 18916 } 18917 18918 @Override 18919 public Float get(View object) { 18920 return object.getAlpha(); 18921 } 18922 }; 18923 18924 /** 18925 * A Property wrapper around the <code>translationX</code> functionality handled by the 18926 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 18927 */ 18928 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 18929 @Override 18930 public void setValue(View object, float value) { 18931 object.setTranslationX(value); 18932 } 18933 18934 @Override 18935 public Float get(View object) { 18936 return object.getTranslationX(); 18937 } 18938 }; 18939 18940 /** 18941 * A Property wrapper around the <code>translationY</code> functionality handled by the 18942 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 18943 */ 18944 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 18945 @Override 18946 public void setValue(View object, float value) { 18947 object.setTranslationY(value); 18948 } 18949 18950 @Override 18951 public Float get(View object) { 18952 return object.getTranslationY(); 18953 } 18954 }; 18955 18956 /** 18957 * A Property wrapper around the <code>translationZ</code> functionality handled by the 18958 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 18959 */ 18960 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 18961 @Override 18962 public void setValue(View object, float value) { 18963 object.setTranslationZ(value); 18964 } 18965 18966 @Override 18967 public Float get(View object) { 18968 return object.getTranslationZ(); 18969 } 18970 }; 18971 18972 /** 18973 * A Property wrapper around the <code>x</code> functionality handled by the 18974 * {@link View#setX(float)} and {@link View#getX()} methods. 18975 */ 18976 public static final Property<View, Float> X = new FloatProperty<View>("x") { 18977 @Override 18978 public void setValue(View object, float value) { 18979 object.setX(value); 18980 } 18981 18982 @Override 18983 public Float get(View object) { 18984 return object.getX(); 18985 } 18986 }; 18987 18988 /** 18989 * A Property wrapper around the <code>y</code> functionality handled by the 18990 * {@link View#setY(float)} and {@link View#getY()} methods. 18991 */ 18992 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 18993 @Override 18994 public void setValue(View object, float value) { 18995 object.setY(value); 18996 } 18997 18998 @Override 18999 public Float get(View object) { 19000 return object.getY(); 19001 } 19002 }; 19003 19004 /** 19005 * A Property wrapper around the <code>z</code> functionality handled by the 19006 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19007 */ 19008 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19009 @Override 19010 public void setValue(View object, float value) { 19011 object.setZ(value); 19012 } 19013 19014 @Override 19015 public Float get(View object) { 19016 return object.getZ(); 19017 } 19018 }; 19019 19020 /** 19021 * A Property wrapper around the <code>rotation</code> functionality handled by the 19022 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19023 */ 19024 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19025 @Override 19026 public void setValue(View object, float value) { 19027 object.setRotation(value); 19028 } 19029 19030 @Override 19031 public Float get(View object) { 19032 return object.getRotation(); 19033 } 19034 }; 19035 19036 /** 19037 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19038 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19039 */ 19040 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19041 @Override 19042 public void setValue(View object, float value) { 19043 object.setRotationX(value); 19044 } 19045 19046 @Override 19047 public Float get(View object) { 19048 return object.getRotationX(); 19049 } 19050 }; 19051 19052 /** 19053 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19054 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19055 */ 19056 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19057 @Override 19058 public void setValue(View object, float value) { 19059 object.setRotationY(value); 19060 } 19061 19062 @Override 19063 public Float get(View object) { 19064 return object.getRotationY(); 19065 } 19066 }; 19067 19068 /** 19069 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19070 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19071 */ 19072 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19073 @Override 19074 public void setValue(View object, float value) { 19075 object.setScaleX(value); 19076 } 19077 19078 @Override 19079 public Float get(View object) { 19080 return object.getScaleX(); 19081 } 19082 }; 19083 19084 /** 19085 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19086 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19087 */ 19088 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19089 @Override 19090 public void setValue(View object, float value) { 19091 object.setScaleY(value); 19092 } 19093 19094 @Override 19095 public Float get(View object) { 19096 return object.getScaleY(); 19097 } 19098 }; 19099 19100 /** 19101 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19102 * Each MeasureSpec represents a requirement for either the width or the height. 19103 * A MeasureSpec is comprised of a size and a mode. There are three possible 19104 * modes: 19105 * <dl> 19106 * <dt>UNSPECIFIED</dt> 19107 * <dd> 19108 * The parent has not imposed any constraint on the child. It can be whatever size 19109 * it wants. 19110 * </dd> 19111 * 19112 * <dt>EXACTLY</dt> 19113 * <dd> 19114 * The parent has determined an exact size for the child. The child is going to be 19115 * given those bounds regardless of how big it wants to be. 19116 * </dd> 19117 * 19118 * <dt>AT_MOST</dt> 19119 * <dd> 19120 * The child can be as large as it wants up to the specified size. 19121 * </dd> 19122 * </dl> 19123 * 19124 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19125 * is provided to pack and unpack the <size, mode> tuple into the int. 19126 */ 19127 public static class MeasureSpec { 19128 private static final int MODE_SHIFT = 30; 19129 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19130 19131 /** 19132 * Measure specification mode: The parent has not imposed any constraint 19133 * on the child. It can be whatever size it wants. 19134 */ 19135 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19136 19137 /** 19138 * Measure specification mode: The parent has determined an exact size 19139 * for the child. The child is going to be given those bounds regardless 19140 * of how big it wants to be. 19141 */ 19142 public static final int EXACTLY = 1 << MODE_SHIFT; 19143 19144 /** 19145 * Measure specification mode: The child can be as large as it wants up 19146 * to the specified size. 19147 */ 19148 public static final int AT_MOST = 2 << MODE_SHIFT; 19149 19150 /** 19151 * Creates a measure specification based on the supplied size and mode. 19152 * 19153 * The mode must always be one of the following: 19154 * <ul> 19155 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19156 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19157 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19158 * </ul> 19159 * 19160 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19161 * implementation was such that the order of arguments did not matter 19162 * and overflow in either value could impact the resulting MeasureSpec. 19163 * {@link android.widget.RelativeLayout} was affected by this bug. 19164 * Apps targeting API levels greater than 17 will get the fixed, more strict 19165 * behavior.</p> 19166 * 19167 * @param size the size of the measure specification 19168 * @param mode the mode of the measure specification 19169 * @return the measure specification based on size and mode 19170 */ 19171 public static int makeMeasureSpec(int size, int mode) { 19172 if (sUseBrokenMakeMeasureSpec) { 19173 return size + mode; 19174 } else { 19175 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19176 } 19177 } 19178 19179 /** 19180 * Extracts the mode from the supplied measure specification. 19181 * 19182 * @param measureSpec the measure specification to extract the mode from 19183 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19184 * {@link android.view.View.MeasureSpec#AT_MOST} or 19185 * {@link android.view.View.MeasureSpec#EXACTLY} 19186 */ 19187 public static int getMode(int measureSpec) { 19188 return (measureSpec & MODE_MASK); 19189 } 19190 19191 /** 19192 * Extracts the size from the supplied measure specification. 19193 * 19194 * @param measureSpec the measure specification to extract the size from 19195 * @return the size in pixels defined in the supplied measure specification 19196 */ 19197 public static int getSize(int measureSpec) { 19198 return (measureSpec & ~MODE_MASK); 19199 } 19200 19201 static int adjust(int measureSpec, int delta) { 19202 final int mode = getMode(measureSpec); 19203 if (mode == UNSPECIFIED) { 19204 // No need to adjust size for UNSPECIFIED mode. 19205 return makeMeasureSpec(0, UNSPECIFIED); 19206 } 19207 int size = getSize(measureSpec) + delta; 19208 if (size < 0) { 19209 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19210 ") spec: " + toString(measureSpec) + " delta: " + delta); 19211 size = 0; 19212 } 19213 return makeMeasureSpec(size, mode); 19214 } 19215 19216 /** 19217 * Returns a String representation of the specified measure 19218 * specification. 19219 * 19220 * @param measureSpec the measure specification to convert to a String 19221 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19222 */ 19223 public static String toString(int measureSpec) { 19224 int mode = getMode(measureSpec); 19225 int size = getSize(measureSpec); 19226 19227 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19228 19229 if (mode == UNSPECIFIED) 19230 sb.append("UNSPECIFIED "); 19231 else if (mode == EXACTLY) 19232 sb.append("EXACTLY "); 19233 else if (mode == AT_MOST) 19234 sb.append("AT_MOST "); 19235 else 19236 sb.append(mode).append(" "); 19237 19238 sb.append(size); 19239 return sb.toString(); 19240 } 19241 } 19242 19243 private final class CheckForLongPress implements Runnable { 19244 private int mOriginalWindowAttachCount; 19245 19246 @Override 19247 public void run() { 19248 if (isPressed() && (mParent != null) 19249 && mOriginalWindowAttachCount == mWindowAttachCount) { 19250 if (performLongClick()) { 19251 mHasPerformedLongPress = true; 19252 } 19253 } 19254 } 19255 19256 public void rememberWindowAttachCount() { 19257 mOriginalWindowAttachCount = mWindowAttachCount; 19258 } 19259 } 19260 19261 private final class CheckForTap implements Runnable { 19262 public float x; 19263 public float y; 19264 19265 @Override 19266 public void run() { 19267 mPrivateFlags &= ~PFLAG_PREPRESSED; 19268 setPressed(true, x, y); 19269 checkForLongClick(ViewConfiguration.getTapTimeout()); 19270 } 19271 } 19272 19273 private final class PerformClick implements Runnable { 19274 @Override 19275 public void run() { 19276 performClick(); 19277 } 19278 } 19279 19280 /** @hide */ 19281 public void hackTurnOffWindowResizeAnim(boolean off) { 19282 mAttachInfo.mTurnOffWindowResizeAnim = off; 19283 } 19284 19285 /** 19286 * This method returns a ViewPropertyAnimator object, which can be used to animate 19287 * specific properties on this View. 19288 * 19289 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19290 */ 19291 public ViewPropertyAnimator animate() { 19292 if (mAnimator == null) { 19293 mAnimator = new ViewPropertyAnimator(this); 19294 } 19295 return mAnimator; 19296 } 19297 19298 /** 19299 * Sets the name of the View to be used to identify Views in Transitions. 19300 * Names should be unique in the View hierarchy. 19301 * 19302 * @param transitionName The name of the View to uniquely identify it for Transitions. 19303 */ 19304 public final void setTransitionName(String transitionName) { 19305 mTransitionName = transitionName; 19306 } 19307 19308 /** 19309 * To be removed before L release. 19310 * @hide 19311 */ 19312 public final void setViewName(String transitionName) { 19313 setTransitionName(transitionName); 19314 } 19315 19316 /** 19317 * Returns the name of the View to be used to identify Views in Transitions. 19318 * Names should be unique in the View hierarchy. 19319 * 19320 * <p>This returns null if the View has not been given a name.</p> 19321 * 19322 * @return The name used of the View to be used to identify Views in Transitions or null 19323 * if no name has been given. 19324 */ 19325 public String getTransitionName() { 19326 return mTransitionName; 19327 } 19328 19329 /** 19330 * To be removed before L release. 19331 * @hide 19332 */ 19333 public String getViewName() { return getTransitionName(); } 19334 19335 /** 19336 * Interface definition for a callback to be invoked when a hardware key event is 19337 * dispatched to this view. The callback will be invoked before the key event is 19338 * given to the view. This is only useful for hardware keyboards; a software input 19339 * method has no obligation to trigger this listener. 19340 */ 19341 public interface OnKeyListener { 19342 /** 19343 * Called when a hardware key is dispatched to a view. This allows listeners to 19344 * get a chance to respond before the target view. 19345 * <p>Key presses in software keyboards will generally NOT trigger this method, 19346 * although some may elect to do so in some situations. Do not assume a 19347 * software input method has to be key-based; even if it is, it may use key presses 19348 * in a different way than you expect, so there is no way to reliably catch soft 19349 * input key presses. 19350 * 19351 * @param v The view the key has been dispatched to. 19352 * @param keyCode The code for the physical key that was pressed 19353 * @param event The KeyEvent object containing full information about 19354 * the event. 19355 * @return True if the listener has consumed the event, false otherwise. 19356 */ 19357 boolean onKey(View v, int keyCode, KeyEvent event); 19358 } 19359 19360 /** 19361 * Interface definition for a callback to be invoked when a touch event is 19362 * dispatched to this view. The callback will be invoked before the touch 19363 * event is given to the view. 19364 */ 19365 public interface OnTouchListener { 19366 /** 19367 * Called when a touch event is dispatched to a view. This allows listeners to 19368 * get a chance to respond before the target view. 19369 * 19370 * @param v The view the touch event has been dispatched to. 19371 * @param event The MotionEvent object containing full information about 19372 * the event. 19373 * @return True if the listener has consumed the event, false otherwise. 19374 */ 19375 boolean onTouch(View v, MotionEvent event); 19376 } 19377 19378 /** 19379 * Interface definition for a callback to be invoked when a hover event is 19380 * dispatched to this view. The callback will be invoked before the hover 19381 * event is given to the view. 19382 */ 19383 public interface OnHoverListener { 19384 /** 19385 * Called when a hover event is dispatched to a view. This allows listeners to 19386 * get a chance to respond before the target view. 19387 * 19388 * @param v The view the hover event has been dispatched to. 19389 * @param event The MotionEvent object containing full information about 19390 * the event. 19391 * @return True if the listener has consumed the event, false otherwise. 19392 */ 19393 boolean onHover(View v, MotionEvent event); 19394 } 19395 19396 /** 19397 * Interface definition for a callback to be invoked when a generic motion event is 19398 * dispatched to this view. The callback will be invoked before the generic motion 19399 * event is given to the view. 19400 */ 19401 public interface OnGenericMotionListener { 19402 /** 19403 * Called when a generic motion event is dispatched to a view. This allows listeners to 19404 * get a chance to respond before the target view. 19405 * 19406 * @param v The view the generic motion event has been dispatched to. 19407 * @param event The MotionEvent object containing full information about 19408 * the event. 19409 * @return True if the listener has consumed the event, false otherwise. 19410 */ 19411 boolean onGenericMotion(View v, MotionEvent event); 19412 } 19413 19414 /** 19415 * Interface definition for a callback to be invoked when a view has been clicked and held. 19416 */ 19417 public interface OnLongClickListener { 19418 /** 19419 * Called when a view has been clicked and held. 19420 * 19421 * @param v The view that was clicked and held. 19422 * 19423 * @return true if the callback consumed the long click, false otherwise. 19424 */ 19425 boolean onLongClick(View v); 19426 } 19427 19428 /** 19429 * Interface definition for a callback to be invoked when a drag is being dispatched 19430 * to this view. The callback will be invoked before the hosting view's own 19431 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19432 * onDrag(event) behavior, it should return 'false' from this callback. 19433 * 19434 * <div class="special reference"> 19435 * <h3>Developer Guides</h3> 19436 * <p>For a guide to implementing drag and drop features, read the 19437 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19438 * </div> 19439 */ 19440 public interface OnDragListener { 19441 /** 19442 * Called when a drag event is dispatched to a view. This allows listeners 19443 * to get a chance to override base View behavior. 19444 * 19445 * @param v The View that received the drag event. 19446 * @param event The {@link android.view.DragEvent} object for the drag event. 19447 * @return {@code true} if the drag event was handled successfully, or {@code false} 19448 * if the drag event was not handled. Note that {@code false} will trigger the View 19449 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19450 */ 19451 boolean onDrag(View v, DragEvent event); 19452 } 19453 19454 /** 19455 * Interface definition for a callback to be invoked when the focus state of 19456 * a view changed. 19457 */ 19458 public interface OnFocusChangeListener { 19459 /** 19460 * Called when the focus state of a view has changed. 19461 * 19462 * @param v The view whose state has changed. 19463 * @param hasFocus The new focus state of v. 19464 */ 19465 void onFocusChange(View v, boolean hasFocus); 19466 } 19467 19468 /** 19469 * Interface definition for a callback to be invoked when a view is clicked. 19470 */ 19471 public interface OnClickListener { 19472 /** 19473 * Called when a view has been clicked. 19474 * 19475 * @param v The view that was clicked. 19476 */ 19477 void onClick(View v); 19478 } 19479 19480 /** 19481 * Interface definition for a callback to be invoked when the context menu 19482 * for this view is being built. 19483 */ 19484 public interface OnCreateContextMenuListener { 19485 /** 19486 * Called when the context menu for this view is being built. It is not 19487 * safe to hold onto the menu after this method returns. 19488 * 19489 * @param menu The context menu that is being built 19490 * @param v The view for which the context menu is being built 19491 * @param menuInfo Extra information about the item for which the 19492 * context menu should be shown. This information will vary 19493 * depending on the class of v. 19494 */ 19495 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19496 } 19497 19498 /** 19499 * Interface definition for a callback to be invoked when the status bar changes 19500 * visibility. This reports <strong>global</strong> changes to the system UI 19501 * state, not what the application is requesting. 19502 * 19503 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19504 */ 19505 public interface OnSystemUiVisibilityChangeListener { 19506 /** 19507 * Called when the status bar changes visibility because of a call to 19508 * {@link View#setSystemUiVisibility(int)}. 19509 * 19510 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19511 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19512 * This tells you the <strong>global</strong> state of these UI visibility 19513 * flags, not what your app is currently applying. 19514 */ 19515 public void onSystemUiVisibilityChange(int visibility); 19516 } 19517 19518 /** 19519 * Interface definition for a callback to be invoked when this view is attached 19520 * or detached from its window. 19521 */ 19522 public interface OnAttachStateChangeListener { 19523 /** 19524 * Called when the view is attached to a window. 19525 * @param v The view that was attached 19526 */ 19527 public void onViewAttachedToWindow(View v); 19528 /** 19529 * Called when the view is detached from a window. 19530 * @param v The view that was detached 19531 */ 19532 public void onViewDetachedFromWindow(View v); 19533 } 19534 19535 /** 19536 * Listener for applying window insets on a view in a custom way. 19537 * 19538 * <p>Apps may choose to implement this interface if they want to apply custom policy 19539 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19540 * is set, its 19541 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19542 * method will be called instead of the View's own 19543 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19544 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19545 * the View's normal behavior as part of its own.</p> 19546 */ 19547 public interface OnApplyWindowInsetsListener { 19548 /** 19549 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19550 * on a View, this listener method will be called instead of the view's own 19551 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19552 * 19553 * @param v The view applying window insets 19554 * @param insets The insets to apply 19555 * @return The insets supplied, minus any insets that were consumed 19556 */ 19557 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19558 } 19559 19560 private final class UnsetPressedState implements Runnable { 19561 @Override 19562 public void run() { 19563 setPressed(false); 19564 } 19565 } 19566 19567 /** 19568 * Base class for derived classes that want to save and restore their own 19569 * state in {@link android.view.View#onSaveInstanceState()}. 19570 */ 19571 public static class BaseSavedState extends AbsSavedState { 19572 /** 19573 * Constructor used when reading from a parcel. Reads the state of the superclass. 19574 * 19575 * @param source 19576 */ 19577 public BaseSavedState(Parcel source) { 19578 super(source); 19579 } 19580 19581 /** 19582 * Constructor called by derived classes when creating their SavedState objects 19583 * 19584 * @param superState The state of the superclass of this view 19585 */ 19586 public BaseSavedState(Parcelable superState) { 19587 super(superState); 19588 } 19589 19590 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19591 new Parcelable.Creator<BaseSavedState>() { 19592 public BaseSavedState createFromParcel(Parcel in) { 19593 return new BaseSavedState(in); 19594 } 19595 19596 public BaseSavedState[] newArray(int size) { 19597 return new BaseSavedState[size]; 19598 } 19599 }; 19600 } 19601 19602 /** 19603 * A set of information given to a view when it is attached to its parent 19604 * window. 19605 */ 19606 final static class AttachInfo { 19607 interface Callbacks { 19608 void playSoundEffect(int effectId); 19609 boolean performHapticFeedback(int effectId, boolean always); 19610 } 19611 19612 /** 19613 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19614 * to a Handler. This class contains the target (View) to invalidate and 19615 * the coordinates of the dirty rectangle. 19616 * 19617 * For performance purposes, this class also implements a pool of up to 19618 * POOL_LIMIT objects that get reused. This reduces memory allocations 19619 * whenever possible. 19620 */ 19621 static class InvalidateInfo { 19622 private static final int POOL_LIMIT = 10; 19623 19624 private static final SynchronizedPool<InvalidateInfo> sPool = 19625 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19626 19627 View target; 19628 19629 int left; 19630 int top; 19631 int right; 19632 int bottom; 19633 19634 public static InvalidateInfo obtain() { 19635 InvalidateInfo instance = sPool.acquire(); 19636 return (instance != null) ? instance : new InvalidateInfo(); 19637 } 19638 19639 public void recycle() { 19640 target = null; 19641 sPool.release(this); 19642 } 19643 } 19644 19645 final IWindowSession mSession; 19646 19647 final IWindow mWindow; 19648 19649 final IBinder mWindowToken; 19650 19651 final Display mDisplay; 19652 19653 final Callbacks mRootCallbacks; 19654 19655 IWindowId mIWindowId; 19656 WindowId mWindowId; 19657 19658 /** 19659 * The top view of the hierarchy. 19660 */ 19661 View mRootView; 19662 19663 IBinder mPanelParentWindowToken; 19664 19665 boolean mHardwareAccelerated; 19666 boolean mHardwareAccelerationRequested; 19667 HardwareRenderer mHardwareRenderer; 19668 19669 /** 19670 * The state of the display to which the window is attached, as reported 19671 * by {@link Display#getState()}. Note that the display state constants 19672 * declared by {@link Display} do not exactly line up with the screen state 19673 * constants declared by {@link View} (there are more display states than 19674 * screen states). 19675 */ 19676 int mDisplayState = Display.STATE_UNKNOWN; 19677 19678 /** 19679 * Scale factor used by the compatibility mode 19680 */ 19681 float mApplicationScale; 19682 19683 /** 19684 * Indicates whether the application is in compatibility mode 19685 */ 19686 boolean mScalingRequired; 19687 19688 /** 19689 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19690 */ 19691 boolean mTurnOffWindowResizeAnim; 19692 19693 /** 19694 * Left position of this view's window 19695 */ 19696 int mWindowLeft; 19697 19698 /** 19699 * Top position of this view's window 19700 */ 19701 int mWindowTop; 19702 19703 /** 19704 * Indicates whether views need to use 32-bit drawing caches 19705 */ 19706 boolean mUse32BitDrawingCache; 19707 19708 /** 19709 * For windows that are full-screen but using insets to layout inside 19710 * of the screen areas, these are the current insets to appear inside 19711 * the overscan area of the display. 19712 */ 19713 final Rect mOverscanInsets = new Rect(); 19714 19715 /** 19716 * For windows that are full-screen but using insets to layout inside 19717 * of the screen decorations, these are the current insets for the 19718 * content of the window. 19719 */ 19720 final Rect mContentInsets = new Rect(); 19721 19722 /** 19723 * For windows that are full-screen but using insets to layout inside 19724 * of the screen decorations, these are the current insets for the 19725 * actual visible parts of the window. 19726 */ 19727 final Rect mVisibleInsets = new Rect(); 19728 19729 /** 19730 * The internal insets given by this window. This value is 19731 * supplied by the client (through 19732 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19733 * be given to the window manager when changed to be used in laying 19734 * out windows behind it. 19735 */ 19736 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19737 = new ViewTreeObserver.InternalInsetsInfo(); 19738 19739 /** 19740 * Set to true when mGivenInternalInsets is non-empty. 19741 */ 19742 boolean mHasNonEmptyGivenInternalInsets; 19743 19744 /** 19745 * All views in the window's hierarchy that serve as scroll containers, 19746 * used to determine if the window can be resized or must be panned 19747 * to adjust for a soft input area. 19748 */ 19749 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19750 19751 final KeyEvent.DispatcherState mKeyDispatchState 19752 = new KeyEvent.DispatcherState(); 19753 19754 /** 19755 * Indicates whether the view's window currently has the focus. 19756 */ 19757 boolean mHasWindowFocus; 19758 19759 /** 19760 * The current visibility of the window. 19761 */ 19762 int mWindowVisibility; 19763 19764 /** 19765 * Indicates the time at which drawing started to occur. 19766 */ 19767 long mDrawingTime; 19768 19769 /** 19770 * Indicates whether or not ignoring the DIRTY_MASK flags. 19771 */ 19772 boolean mIgnoreDirtyState; 19773 19774 /** 19775 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19776 * to avoid clearing that flag prematurely. 19777 */ 19778 boolean mSetIgnoreDirtyState = false; 19779 19780 /** 19781 * Indicates whether the view's window is currently in touch mode. 19782 */ 19783 boolean mInTouchMode; 19784 19785 /** 19786 * Indicates whether the view has requested unbuffered input dispatching for the current 19787 * event stream. 19788 */ 19789 boolean mUnbufferedDispatchRequested; 19790 19791 /** 19792 * Indicates that ViewAncestor should trigger a global layout change 19793 * the next time it performs a traversal 19794 */ 19795 boolean mRecomputeGlobalAttributes; 19796 19797 /** 19798 * Always report new attributes at next traversal. 19799 */ 19800 boolean mForceReportNewAttributes; 19801 19802 /** 19803 * Set during a traveral if any views want to keep the screen on. 19804 */ 19805 boolean mKeepScreenOn; 19806 19807 /** 19808 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19809 */ 19810 int mSystemUiVisibility; 19811 19812 /** 19813 * Hack to force certain system UI visibility flags to be cleared. 19814 */ 19815 int mDisabledSystemUiVisibility; 19816 19817 /** 19818 * Last global system UI visibility reported by the window manager. 19819 */ 19820 int mGlobalSystemUiVisibility; 19821 19822 /** 19823 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19824 * attached. 19825 */ 19826 boolean mHasSystemUiListeners; 19827 19828 /** 19829 * Set if the window has requested to extend into the overscan region 19830 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19831 */ 19832 boolean mOverscanRequested; 19833 19834 /** 19835 * Set if the visibility of any views has changed. 19836 */ 19837 boolean mViewVisibilityChanged; 19838 19839 /** 19840 * Set to true if a view has been scrolled. 19841 */ 19842 boolean mViewScrollChanged; 19843 19844 /** 19845 * Global to the view hierarchy used as a temporary for dealing with 19846 * x/y points in the transparent region computations. 19847 */ 19848 final int[] mTransparentLocation = new int[2]; 19849 19850 /** 19851 * Global to the view hierarchy used as a temporary for dealing with 19852 * x/y points in the ViewGroup.invalidateChild implementation. 19853 */ 19854 final int[] mInvalidateChildLocation = new int[2]; 19855 19856 /** 19857 * Global to the view hierarchy used as a temporary for dealng with 19858 * computing absolute on-screen location. 19859 */ 19860 final int[] mTmpLocation = new int[2]; 19861 19862 /** 19863 * Global to the view hierarchy used as a temporary for dealing with 19864 * x/y location when view is transformed. 19865 */ 19866 final float[] mTmpTransformLocation = new float[2]; 19867 19868 /** 19869 * The view tree observer used to dispatch global events like 19870 * layout, pre-draw, touch mode change, etc. 19871 */ 19872 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19873 19874 /** 19875 * A Canvas used by the view hierarchy to perform bitmap caching. 19876 */ 19877 Canvas mCanvas; 19878 19879 /** 19880 * The view root impl. 19881 */ 19882 final ViewRootImpl mViewRootImpl; 19883 19884 /** 19885 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19886 * handler can be used to pump events in the UI events queue. 19887 */ 19888 final Handler mHandler; 19889 19890 /** 19891 * Temporary for use in computing invalidate rectangles while 19892 * calling up the hierarchy. 19893 */ 19894 final Rect mTmpInvalRect = new Rect(); 19895 19896 /** 19897 * Temporary for use in computing hit areas with transformed views 19898 */ 19899 final RectF mTmpTransformRect = new RectF(); 19900 19901 /** 19902 * Temporary for use in transforming invalidation rect 19903 */ 19904 final Matrix mTmpMatrix = new Matrix(); 19905 19906 /** 19907 * Temporary for use in transforming invalidation rect 19908 */ 19909 final Transformation mTmpTransformation = new Transformation(); 19910 19911 /** 19912 * Temporary list for use in collecting focusable descendents of a view. 19913 */ 19914 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19915 19916 /** 19917 * The id of the window for accessibility purposes. 19918 */ 19919 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 19920 19921 /** 19922 * Flags related to accessibility processing. 19923 * 19924 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 19925 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 19926 */ 19927 int mAccessibilityFetchFlags; 19928 19929 /** 19930 * The drawable for highlighting accessibility focus. 19931 */ 19932 Drawable mAccessibilityFocusDrawable; 19933 19934 /** 19935 * Show where the margins, bounds and layout bounds are for each view. 19936 */ 19937 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 19938 19939 /** 19940 * Point used to compute visible regions. 19941 */ 19942 final Point mPoint = new Point(); 19943 19944 /** 19945 * Used to track which View originated a requestLayout() call, used when 19946 * requestLayout() is called during layout. 19947 */ 19948 View mViewRequestingLayout; 19949 19950 /** 19951 * Creates a new set of attachment information with the specified 19952 * events handler and thread. 19953 * 19954 * @param handler the events handler the view must use 19955 */ 19956 AttachInfo(IWindowSession session, IWindow window, Display display, 19957 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 19958 mSession = session; 19959 mWindow = window; 19960 mWindowToken = window.asBinder(); 19961 mDisplay = display; 19962 mViewRootImpl = viewRootImpl; 19963 mHandler = handler; 19964 mRootCallbacks = effectPlayer; 19965 } 19966 } 19967 19968 /** 19969 * <p>ScrollabilityCache holds various fields used by a View when scrolling 19970 * is supported. This avoids keeping too many unused fields in most 19971 * instances of View.</p> 19972 */ 19973 private static class ScrollabilityCache implements Runnable { 19974 19975 /** 19976 * Scrollbars are not visible 19977 */ 19978 public static final int OFF = 0; 19979 19980 /** 19981 * Scrollbars are visible 19982 */ 19983 public static final int ON = 1; 19984 19985 /** 19986 * Scrollbars are fading away 19987 */ 19988 public static final int FADING = 2; 19989 19990 public boolean fadeScrollBars; 19991 19992 public int fadingEdgeLength; 19993 public int scrollBarDefaultDelayBeforeFade; 19994 public int scrollBarFadeDuration; 19995 19996 public int scrollBarSize; 19997 public ScrollBarDrawable scrollBar; 19998 public float[] interpolatorValues; 19999 public View host; 20000 20001 public final Paint paint; 20002 public final Matrix matrix; 20003 public Shader shader; 20004 20005 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 20006 20007 private static final float[] OPAQUE = { 255 }; 20008 private static final float[] TRANSPARENT = { 0.0f }; 20009 20010 /** 20011 * When fading should start. This time moves into the future every time 20012 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20013 */ 20014 public long fadeStartTime; 20015 20016 20017 /** 20018 * The current state of the scrollbars: ON, OFF, or FADING 20019 */ 20020 public int state = OFF; 20021 20022 private int mLastColor; 20023 20024 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20025 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20026 scrollBarSize = configuration.getScaledScrollBarSize(); 20027 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20028 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20029 20030 paint = new Paint(); 20031 matrix = new Matrix(); 20032 // use use a height of 1, and then wack the matrix each time we 20033 // actually use it. 20034 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20035 paint.setShader(shader); 20036 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20037 20038 this.host = host; 20039 } 20040 20041 public void setFadeColor(int color) { 20042 if (color != mLastColor) { 20043 mLastColor = color; 20044 20045 if (color != 0) { 20046 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20047 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20048 paint.setShader(shader); 20049 // Restore the default transfer mode (src_over) 20050 paint.setXfermode(null); 20051 } else { 20052 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20053 paint.setShader(shader); 20054 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20055 } 20056 } 20057 } 20058 20059 public void run() { 20060 long now = AnimationUtils.currentAnimationTimeMillis(); 20061 if (now >= fadeStartTime) { 20062 20063 // the animation fades the scrollbars out by changing 20064 // the opacity (alpha) from fully opaque to fully 20065 // transparent 20066 int nextFrame = (int) now; 20067 int framesCount = 0; 20068 20069 Interpolator interpolator = scrollBarInterpolator; 20070 20071 // Start opaque 20072 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20073 20074 // End transparent 20075 nextFrame += scrollBarFadeDuration; 20076 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20077 20078 state = FADING; 20079 20080 // Kick off the fade animation 20081 host.invalidate(true); 20082 } 20083 } 20084 } 20085 20086 /** 20087 * Resuable callback for sending 20088 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20089 */ 20090 private class SendViewScrolledAccessibilityEvent implements Runnable { 20091 public volatile boolean mIsPending; 20092 20093 public void run() { 20094 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20095 mIsPending = false; 20096 } 20097 } 20098 20099 /** 20100 * <p> 20101 * This class represents a delegate that can be registered in a {@link View} 20102 * to enhance accessibility support via composition rather via inheritance. 20103 * It is specifically targeted to widget developers that extend basic View 20104 * classes i.e. classes in package android.view, that would like their 20105 * applications to be backwards compatible. 20106 * </p> 20107 * <div class="special reference"> 20108 * <h3>Developer Guides</h3> 20109 * <p>For more information about making applications accessible, read the 20110 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20111 * developer guide.</p> 20112 * </div> 20113 * <p> 20114 * A scenario in which a developer would like to use an accessibility delegate 20115 * is overriding a method introduced in a later API version then the minimal API 20116 * version supported by the application. For example, the method 20117 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20118 * in API version 4 when the accessibility APIs were first introduced. If a 20119 * developer would like his application to run on API version 4 devices (assuming 20120 * all other APIs used by the application are version 4 or lower) and take advantage 20121 * of this method, instead of overriding the method which would break the application's 20122 * backwards compatibility, he can override the corresponding method in this 20123 * delegate and register the delegate in the target View if the API version of 20124 * the system is high enough i.e. the API version is same or higher to the API 20125 * version that introduced 20126 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20127 * </p> 20128 * <p> 20129 * Here is an example implementation: 20130 * </p> 20131 * <code><pre><p> 20132 * if (Build.VERSION.SDK_INT >= 14) { 20133 * // If the API version is equal of higher than the version in 20134 * // which onInitializeAccessibilityNodeInfo was introduced we 20135 * // register a delegate with a customized implementation. 20136 * View view = findViewById(R.id.view_id); 20137 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20138 * public void onInitializeAccessibilityNodeInfo(View host, 20139 * AccessibilityNodeInfo info) { 20140 * // Let the default implementation populate the info. 20141 * super.onInitializeAccessibilityNodeInfo(host, info); 20142 * // Set some other information. 20143 * info.setEnabled(host.isEnabled()); 20144 * } 20145 * }); 20146 * } 20147 * </code></pre></p> 20148 * <p> 20149 * This delegate contains methods that correspond to the accessibility methods 20150 * in View. If a delegate has been specified the implementation in View hands 20151 * off handling to the corresponding method in this delegate. The default 20152 * implementation the delegate methods behaves exactly as the corresponding 20153 * method in View for the case of no accessibility delegate been set. Hence, 20154 * to customize the behavior of a View method, clients can override only the 20155 * corresponding delegate method without altering the behavior of the rest 20156 * accessibility related methods of the host view. 20157 * </p> 20158 */ 20159 public static class AccessibilityDelegate { 20160 20161 /** 20162 * Sends an accessibility event of the given type. If accessibility is not 20163 * enabled this method has no effect. 20164 * <p> 20165 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20166 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20167 * been set. 20168 * </p> 20169 * 20170 * @param host The View hosting the delegate. 20171 * @param eventType The type of the event to send. 20172 * 20173 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20174 */ 20175 public void sendAccessibilityEvent(View host, int eventType) { 20176 host.sendAccessibilityEventInternal(eventType); 20177 } 20178 20179 /** 20180 * Performs the specified accessibility action on the view. For 20181 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20182 * <p> 20183 * The default implementation behaves as 20184 * {@link View#performAccessibilityAction(int, Bundle) 20185 * View#performAccessibilityAction(int, Bundle)} for the case of 20186 * no accessibility delegate been set. 20187 * </p> 20188 * 20189 * @param action The action to perform. 20190 * @return Whether the action was performed. 20191 * 20192 * @see View#performAccessibilityAction(int, Bundle) 20193 * View#performAccessibilityAction(int, Bundle) 20194 */ 20195 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20196 return host.performAccessibilityActionInternal(action, args); 20197 } 20198 20199 /** 20200 * Sends an accessibility event. This method behaves exactly as 20201 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20202 * empty {@link AccessibilityEvent} and does not perform a check whether 20203 * accessibility is enabled. 20204 * <p> 20205 * The default implementation behaves as 20206 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20207 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20208 * the case of no accessibility delegate been set. 20209 * </p> 20210 * 20211 * @param host The View hosting the delegate. 20212 * @param event The event to send. 20213 * 20214 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20215 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20216 */ 20217 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20218 host.sendAccessibilityEventUncheckedInternal(event); 20219 } 20220 20221 /** 20222 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20223 * to its children for adding their text content to the event. 20224 * <p> 20225 * The default implementation behaves as 20226 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20227 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20228 * the case of no accessibility delegate been set. 20229 * </p> 20230 * 20231 * @param host The View hosting the delegate. 20232 * @param event The event. 20233 * @return True if the event population was completed. 20234 * 20235 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20236 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20237 */ 20238 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20239 return host.dispatchPopulateAccessibilityEventInternal(event); 20240 } 20241 20242 /** 20243 * Gives a chance to the host View to populate the accessibility event with its 20244 * text content. 20245 * <p> 20246 * The default implementation behaves as 20247 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20248 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20249 * the case of no accessibility delegate been set. 20250 * </p> 20251 * 20252 * @param host The View hosting the delegate. 20253 * @param event The accessibility event which to populate. 20254 * 20255 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20256 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20257 */ 20258 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20259 host.onPopulateAccessibilityEventInternal(event); 20260 } 20261 20262 /** 20263 * Initializes an {@link AccessibilityEvent} with information about the 20264 * the host View which is the event source. 20265 * <p> 20266 * The default implementation behaves as 20267 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20268 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20269 * the case of no accessibility delegate been set. 20270 * </p> 20271 * 20272 * @param host The View hosting the delegate. 20273 * @param event The event to initialize. 20274 * 20275 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20276 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20277 */ 20278 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20279 host.onInitializeAccessibilityEventInternal(event); 20280 } 20281 20282 /** 20283 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20284 * <p> 20285 * The default implementation behaves as 20286 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20287 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20288 * the case of no accessibility delegate been set. 20289 * </p> 20290 * 20291 * @param host The View hosting the delegate. 20292 * @param info The instance to initialize. 20293 * 20294 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20295 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20296 */ 20297 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20298 host.onInitializeAccessibilityNodeInfoInternal(info); 20299 } 20300 20301 /** 20302 * Called when a child of the host View has requested sending an 20303 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20304 * to augment the event. 20305 * <p> 20306 * The default implementation behaves as 20307 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20308 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20309 * the case of no accessibility delegate been set. 20310 * </p> 20311 * 20312 * @param host The View hosting the delegate. 20313 * @param child The child which requests sending the event. 20314 * @param event The event to be sent. 20315 * @return True if the event should be sent 20316 * 20317 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20318 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20319 */ 20320 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20321 AccessibilityEvent event) { 20322 return host.onRequestSendAccessibilityEventInternal(child, event); 20323 } 20324 20325 /** 20326 * Gets the provider for managing a virtual view hierarchy rooted at this View 20327 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20328 * that explore the window content. 20329 * <p> 20330 * The default implementation behaves as 20331 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20332 * the case of no accessibility delegate been set. 20333 * </p> 20334 * 20335 * @return The provider. 20336 * 20337 * @see AccessibilityNodeProvider 20338 */ 20339 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20340 return null; 20341 } 20342 20343 /** 20344 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20345 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20346 * This method is responsible for obtaining an accessibility node info from a 20347 * pool of reusable instances and calling 20348 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20349 * view to initialize the former. 20350 * <p> 20351 * <strong>Note:</strong> The client is responsible for recycling the obtained 20352 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20353 * creation. 20354 * </p> 20355 * <p> 20356 * The default implementation behaves as 20357 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20358 * the case of no accessibility delegate been set. 20359 * </p> 20360 * @return A populated {@link AccessibilityNodeInfo}. 20361 * 20362 * @see AccessibilityNodeInfo 20363 * 20364 * @hide 20365 */ 20366 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20367 return host.createAccessibilityNodeInfoInternal(); 20368 } 20369 } 20370 20371 private class MatchIdPredicate implements Predicate<View> { 20372 public int mId; 20373 20374 @Override 20375 public boolean apply(View view) { 20376 return (view.mID == mId); 20377 } 20378 } 20379 20380 private class MatchLabelForPredicate implements Predicate<View> { 20381 private int mLabeledId; 20382 20383 @Override 20384 public boolean apply(View view) { 20385 return (view.mLabelForId == mLabeledId); 20386 } 20387 } 20388 20389 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20390 private int mChangeTypes = 0; 20391 private boolean mPosted; 20392 private boolean mPostedWithDelay; 20393 private long mLastEventTimeMillis; 20394 20395 @Override 20396 public void run() { 20397 mPosted = false; 20398 mPostedWithDelay = false; 20399 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20400 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20401 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20402 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20403 event.setContentChangeTypes(mChangeTypes); 20404 sendAccessibilityEventUnchecked(event); 20405 } 20406 mChangeTypes = 0; 20407 } 20408 20409 public void runOrPost(int changeType) { 20410 mChangeTypes |= changeType; 20411 20412 // If this is a live region or the child of a live region, collect 20413 // all events from this frame and send them on the next frame. 20414 if (inLiveRegion()) { 20415 // If we're already posted with a delay, remove that. 20416 if (mPostedWithDelay) { 20417 removeCallbacks(this); 20418 mPostedWithDelay = false; 20419 } 20420 // Only post if we're not already posted. 20421 if (!mPosted) { 20422 post(this); 20423 mPosted = true; 20424 } 20425 return; 20426 } 20427 20428 if (mPosted) { 20429 return; 20430 } 20431 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20432 final long minEventIntevalMillis = 20433 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20434 if (timeSinceLastMillis >= minEventIntevalMillis) { 20435 removeCallbacks(this); 20436 run(); 20437 } else { 20438 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20439 mPosted = true; 20440 mPostedWithDelay = true; 20441 } 20442 } 20443 } 20444 20445 private boolean inLiveRegion() { 20446 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20447 return true; 20448 } 20449 20450 ViewParent parent = getParent(); 20451 while (parent instanceof View) { 20452 if (((View) parent).getAccessibilityLiveRegion() 20453 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20454 return true; 20455 } 20456 parent = parent.getParent(); 20457 } 20458 20459 return false; 20460 } 20461 20462 /** 20463 * Dump all private flags in readable format, useful for documentation and 20464 * sanity checking. 20465 */ 20466 private static void dumpFlags() { 20467 final HashMap<String, String> found = Maps.newHashMap(); 20468 try { 20469 for (Field field : View.class.getDeclaredFields()) { 20470 final int modifiers = field.getModifiers(); 20471 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20472 if (field.getType().equals(int.class)) { 20473 final int value = field.getInt(null); 20474 dumpFlag(found, field.getName(), value); 20475 } else if (field.getType().equals(int[].class)) { 20476 final int[] values = (int[]) field.get(null); 20477 for (int i = 0; i < values.length; i++) { 20478 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20479 } 20480 } 20481 } 20482 } 20483 } catch (IllegalAccessException e) { 20484 throw new RuntimeException(e); 20485 } 20486 20487 final ArrayList<String> keys = Lists.newArrayList(); 20488 keys.addAll(found.keySet()); 20489 Collections.sort(keys); 20490 for (String key : keys) { 20491 Log.d(VIEW_LOG_TAG, found.get(key)); 20492 } 20493 } 20494 20495 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20496 // Sort flags by prefix, then by bits, always keeping unique keys 20497 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20498 final int prefix = name.indexOf('_'); 20499 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20500 final String output = bits + " " + name; 20501 found.put(key, output); 20502 } 20503} 20504