View.java revision 1f681448c6b7db451c31af7d61c0b85b7b5af04f
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.PorterDuff.Mode; 49import android.graphics.drawable.ColorDrawable; 50import android.graphics.drawable.Drawable; 51import android.hardware.display.DisplayManagerGlobal; 52import android.os.Bundle; 53import android.os.Handler; 54import android.os.IBinder; 55import android.os.Parcel; 56import android.os.Parcelable; 57import android.os.RemoteException; 58import android.os.SystemClock; 59import android.os.SystemProperties; 60import android.text.TextUtils; 61import android.util.AttributeSet; 62import android.util.FloatProperty; 63import android.util.LayoutDirection; 64import android.util.Log; 65import android.util.LongSparseLongArray; 66import android.util.Pools.SynchronizedPool; 67import android.util.Property; 68import android.util.SparseArray; 69import android.util.SuperNotCalledException; 70import android.util.TypedValue; 71import android.view.ContextMenu.ContextMenuInfo; 72import android.view.AccessibilityIterators.TextSegmentIterator; 73import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 74import android.view.AccessibilityIterators.WordTextSegmentIterator; 75import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 76import android.view.accessibility.AccessibilityEvent; 77import android.view.accessibility.AccessibilityEventSource; 78import android.view.accessibility.AccessibilityManager; 79import android.view.accessibility.AccessibilityNodeInfo; 80import android.view.accessibility.AccessibilityNodeProvider; 81import android.view.animation.Animation; 82import android.view.animation.AnimationUtils; 83import android.view.animation.Transformation; 84import android.view.inputmethod.EditorInfo; 85import android.view.inputmethod.InputConnection; 86import android.view.inputmethod.InputMethodManager; 87import android.widget.ScrollBarDrawable; 88 89import static android.os.Build.VERSION_CODES.*; 90import static java.lang.Math.max; 91 92import com.android.internal.R; 93import com.android.internal.util.Predicate; 94import com.android.internal.view.menu.MenuBuilder; 95 96import com.google.android.collect.Lists; 97import com.google.android.collect.Maps; 98 99import java.lang.annotation.Retention; 100import java.lang.annotation.RetentionPolicy; 101import java.lang.ref.WeakReference; 102import java.lang.reflect.Field; 103import java.lang.reflect.InvocationTargetException; 104import java.lang.reflect.Method; 105import java.lang.reflect.Modifier; 106import java.util.ArrayList; 107import java.util.Arrays; 108import java.util.Collections; 109import java.util.HashMap; 110import java.util.List; 111import java.util.Locale; 112import java.util.Map; 113import java.util.concurrent.CopyOnWriteArrayList; 114import java.util.concurrent.atomic.AtomicInteger; 115 116/** 117 * <p> 118 * This class represents the basic building block for user interface components. A View 119 * occupies a rectangular area on the screen and is responsible for drawing and 120 * event handling. View is the base class for <em>widgets</em>, which are 121 * used to create interactive UI components (buttons, text fields, etc.). The 122 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 123 * are invisible containers that hold other Views (or other ViewGroups) and define 124 * their layout properties. 125 * </p> 126 * 127 * <div class="special reference"> 128 * <h3>Developer Guides</h3> 129 * <p>For information about using this class to develop your application's user interface, 130 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 131 * </div> 132 * 133 * <a name="Using"></a> 134 * <h3>Using Views</h3> 135 * <p> 136 * All of the views in a window are arranged in a single tree. You can add views 137 * either from code or by specifying a tree of views in one or more XML layout 138 * files. There are many specialized subclasses of views that act as controls or 139 * are capable of displaying text, images, or other content. 140 * </p> 141 * <p> 142 * Once you have created a tree of views, there are typically a few types of 143 * common operations you may wish to perform: 144 * <ul> 145 * <li><strong>Set properties:</strong> for example setting the text of a 146 * {@link android.widget.TextView}. The available properties and the methods 147 * that set them will vary among the different subclasses of views. Note that 148 * properties that are known at build time can be set in the XML layout 149 * files.</li> 150 * <li><strong>Set focus:</strong> The framework will handled moving focus in 151 * response to user input. To force focus to a specific view, call 152 * {@link #requestFocus}.</li> 153 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 154 * that will be notified when something interesting happens to the view. For 155 * example, all views will let you set a listener to be notified when the view 156 * gains or loses focus. You can register such a listener using 157 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 158 * Other view subclasses offer more specialized listeners. For example, a Button 159 * exposes a listener to notify clients when the button is clicked.</li> 160 * <li><strong>Set visibility:</strong> You can hide or show views using 161 * {@link #setVisibility(int)}.</li> 162 * </ul> 163 * </p> 164 * <p><em> 165 * Note: The Android framework is responsible for measuring, laying out and 166 * drawing views. You should not call methods that perform these actions on 167 * views yourself unless you are actually implementing a 168 * {@link android.view.ViewGroup}. 169 * </em></p> 170 * 171 * <a name="Lifecycle"></a> 172 * <h3>Implementing a Custom View</h3> 173 * 174 * <p> 175 * To implement a custom view, you will usually begin by providing overrides for 176 * some of the standard methods that the framework calls on all views. You do 177 * not need to override all of these methods. In fact, you can start by just 178 * overriding {@link #onDraw(android.graphics.Canvas)}. 179 * <table border="2" width="85%" align="center" cellpadding="5"> 180 * <thead> 181 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 182 * </thead> 183 * 184 * <tbody> 185 * <tr> 186 * <td rowspan="2">Creation</td> 187 * <td>Constructors</td> 188 * <td>There is a form of the constructor that are called when the view 189 * is created from code and a form that is called when the view is 190 * inflated from a layout file. The second form should parse and apply 191 * any attributes defined in the layout file. 192 * </td> 193 * </tr> 194 * <tr> 195 * <td><code>{@link #onFinishInflate()}</code></td> 196 * <td>Called after a view and all of its children has been inflated 197 * from XML.</td> 198 * </tr> 199 * 200 * <tr> 201 * <td rowspan="3">Layout</td> 202 * <td><code>{@link #onMeasure(int, int)}</code></td> 203 * <td>Called to determine the size requirements for this view and all 204 * of its children. 205 * </td> 206 * </tr> 207 * <tr> 208 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 209 * <td>Called when this view should assign a size and position to all 210 * of its children. 211 * </td> 212 * </tr> 213 * <tr> 214 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 215 * <td>Called when the size of this view has changed. 216 * </td> 217 * </tr> 218 * 219 * <tr> 220 * <td>Drawing</td> 221 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 222 * <td>Called when the view should render its content. 223 * </td> 224 * </tr> 225 * 226 * <tr> 227 * <td rowspan="4">Event processing</td> 228 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 229 * <td>Called when a new hardware key event occurs. 230 * </td> 231 * </tr> 232 * <tr> 233 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 234 * <td>Called when a hardware key up event occurs. 235 * </td> 236 * </tr> 237 * <tr> 238 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 239 * <td>Called when a trackball motion event occurs. 240 * </td> 241 * </tr> 242 * <tr> 243 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 244 * <td>Called when a touch screen motion event occurs. 245 * </td> 246 * </tr> 247 * 248 * <tr> 249 * <td rowspan="2">Focus</td> 250 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 251 * <td>Called when the view gains or loses focus. 252 * </td> 253 * </tr> 254 * 255 * <tr> 256 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 257 * <td>Called when the window containing the view gains or loses focus. 258 * </td> 259 * </tr> 260 * 261 * <tr> 262 * <td rowspan="3">Attaching</td> 263 * <td><code>{@link #onAttachedToWindow()}</code></td> 264 * <td>Called when the view is attached to a window. 265 * </td> 266 * </tr> 267 * 268 * <tr> 269 * <td><code>{@link #onDetachedFromWindow}</code></td> 270 * <td>Called when the view is detached from its window. 271 * </td> 272 * </tr> 273 * 274 * <tr> 275 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 276 * <td>Called when the visibility of the window containing the view 277 * has changed. 278 * </td> 279 * </tr> 280 * </tbody> 281 * 282 * </table> 283 * </p> 284 * 285 * <a name="IDs"></a> 286 * <h3>IDs</h3> 287 * Views may have an integer id associated with them. These ids are typically 288 * assigned in the layout XML files, and are used to find specific views within 289 * the view tree. A common pattern is to: 290 * <ul> 291 * <li>Define a Button in the layout file and assign it a unique ID. 292 * <pre> 293 * <Button 294 * android:id="@+id/my_button" 295 * android:layout_width="wrap_content" 296 * android:layout_height="wrap_content" 297 * android:text="@string/my_button_text"/> 298 * </pre></li> 299 * <li>From the onCreate method of an Activity, find the Button 300 * <pre class="prettyprint"> 301 * Button myButton = (Button) findViewById(R.id.my_button); 302 * </pre></li> 303 * </ul> 304 * <p> 305 * View IDs need not be unique throughout the tree, but it is good practice to 306 * ensure that they are at least unique within the part of the tree you are 307 * searching. 308 * </p> 309 * 310 * <a name="Position"></a> 311 * <h3>Position</h3> 312 * <p> 313 * The geometry of a view is that of a rectangle. A view has a location, 314 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 315 * two dimensions, expressed as a width and a height. The unit for location 316 * and dimensions is the pixel. 317 * </p> 318 * 319 * <p> 320 * It is possible to retrieve the location of a view by invoking the methods 321 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 322 * coordinate of the rectangle representing the view. The latter returns the 323 * top, or Y, coordinate of the rectangle representing the view. These methods 324 * both return the location of the view relative to its parent. For instance, 325 * when getLeft() returns 20, that means the view is located 20 pixels to the 326 * right of the left edge of its direct parent. 327 * </p> 328 * 329 * <p> 330 * In addition, several convenience methods are offered to avoid unnecessary 331 * computations, namely {@link #getRight()} and {@link #getBottom()}. 332 * These methods return the coordinates of the right and bottom edges of the 333 * rectangle representing the view. For instance, calling {@link #getRight()} 334 * is similar to the following computation: <code>getLeft() + getWidth()</code> 335 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 336 * </p> 337 * 338 * <a name="SizePaddingMargins"></a> 339 * <h3>Size, padding and margins</h3> 340 * <p> 341 * The size of a view is expressed with a width and a height. A view actually 342 * possess two pairs of width and height values. 343 * </p> 344 * 345 * <p> 346 * The first pair is known as <em>measured width</em> and 347 * <em>measured height</em>. These dimensions define how big a view wants to be 348 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 349 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 350 * and {@link #getMeasuredHeight()}. 351 * </p> 352 * 353 * <p> 354 * The second pair is simply known as <em>width</em> and <em>height</em>, or 355 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 356 * dimensions define the actual size of the view on screen, at drawing time and 357 * after layout. These values may, but do not have to, be different from the 358 * measured width and height. The width and height can be obtained by calling 359 * {@link #getWidth()} and {@link #getHeight()}. 360 * </p> 361 * 362 * <p> 363 * To measure its dimensions, a view takes into account its padding. The padding 364 * is expressed in pixels for the left, top, right and bottom parts of the view. 365 * Padding can be used to offset the content of the view by a specific amount of 366 * pixels. For instance, a left padding of 2 will push the view's content by 367 * 2 pixels to the right of the left edge. Padding can be set using the 368 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 369 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 370 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 371 * {@link #getPaddingEnd()}. 372 * </p> 373 * 374 * <p> 375 * Even though a view can define a padding, it does not provide any support for 376 * margins. However, view groups provide such a support. Refer to 377 * {@link android.view.ViewGroup} and 378 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 379 * </p> 380 * 381 * <a name="Layout"></a> 382 * <h3>Layout</h3> 383 * <p> 384 * Layout is a two pass process: a measure pass and a layout pass. The measuring 385 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 386 * of the view tree. Each view pushes dimension specifications down the tree 387 * during the recursion. At the end of the measure pass, every view has stored 388 * its measurements. The second pass happens in 389 * {@link #layout(int,int,int,int)} and is also top-down. During 390 * this pass each parent is responsible for positioning all of its children 391 * using the sizes computed in the measure pass. 392 * </p> 393 * 394 * <p> 395 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 396 * {@link #getMeasuredHeight()} values must be set, along with those for all of 397 * that view's descendants. A view's measured width and measured height values 398 * must respect the constraints imposed by the view's parents. This guarantees 399 * that at the end of the measure pass, all parents accept all of their 400 * children's measurements. A parent view may call measure() more than once on 401 * its children. For example, the parent may measure each child once with 402 * unspecified dimensions to find out how big they want to be, then call 403 * measure() on them again with actual numbers if the sum of all the children's 404 * unconstrained sizes is too big or too small. 405 * </p> 406 * 407 * <p> 408 * The measure pass uses two classes to communicate dimensions. The 409 * {@link MeasureSpec} class is used by views to tell their parents how they 410 * want to be measured and positioned. The base LayoutParams class just 411 * describes how big the view wants to be for both width and height. For each 412 * dimension, it can specify one of: 413 * <ul> 414 * <li> an exact number 415 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 416 * (minus padding) 417 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 418 * enclose its content (plus padding). 419 * </ul> 420 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 421 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 422 * an X and Y value. 423 * </p> 424 * 425 * <p> 426 * MeasureSpecs are used to push requirements down the tree from parent to 427 * child. A MeasureSpec can be in one of three modes: 428 * <ul> 429 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 430 * of a child view. For example, a LinearLayout may call measure() on its child 431 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 432 * tall the child view wants to be given a width of 240 pixels. 433 * <li>EXACTLY: This is used by the parent to impose an exact size on the 434 * child. The child must use this size, and guarantee that all of its 435 * descendants will fit within this size. 436 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 437 * child. The child must guarantee that it and all of its descendants will fit 438 * within this size. 439 * </ul> 440 * </p> 441 * 442 * <p> 443 * To intiate a layout, call {@link #requestLayout}. This method is typically 444 * called by a view on itself when it believes that is can no longer fit within 445 * its current bounds. 446 * </p> 447 * 448 * <a name="Drawing"></a> 449 * <h3>Drawing</h3> 450 * <p> 451 * Drawing is handled by walking the tree and rendering each view that 452 * intersects the invalid region. Because the tree is traversed in-order, 453 * this means that parents will draw before (i.e., behind) their children, with 454 * siblings drawn in the order they appear in the tree. 455 * If you set a background drawable for a View, then the View will draw it for you 456 * before calling back to its <code>onDraw()</code> method. 457 * </p> 458 * 459 * <p> 460 * Note that the framework will not draw views that are not in the invalid region. 461 * </p> 462 * 463 * <p> 464 * To force a view to draw, call {@link #invalidate()}. 465 * </p> 466 * 467 * <a name="EventHandlingThreading"></a> 468 * <h3>Event Handling and Threading</h3> 469 * <p> 470 * The basic cycle of a view is as follows: 471 * <ol> 472 * <li>An event comes in and is dispatched to the appropriate view. The view 473 * handles the event and notifies any listeners.</li> 474 * <li>If in the course of processing the event, the view's bounds may need 475 * to be changed, the view will call {@link #requestLayout()}.</li> 476 * <li>Similarly, if in the course of processing the event the view's appearance 477 * may need to be changed, the view will call {@link #invalidate()}.</li> 478 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 479 * the framework will take care of measuring, laying out, and drawing the tree 480 * as appropriate.</li> 481 * </ol> 482 * </p> 483 * 484 * <p><em>Note: The entire view tree is single threaded. You must always be on 485 * the UI thread when calling any method on any view.</em> 486 * If you are doing work on other threads and want to update the state of a view 487 * from that thread, you should use a {@link Handler}. 488 * </p> 489 * 490 * <a name="FocusHandling"></a> 491 * <h3>Focus Handling</h3> 492 * <p> 493 * The framework will handle routine focus movement in response to user input. 494 * This includes changing the focus as views are removed or hidden, or as new 495 * views become available. Views indicate their willingness to take focus 496 * through the {@link #isFocusable} method. To change whether a view can take 497 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 498 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 499 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 500 * </p> 501 * <p> 502 * Focus movement is based on an algorithm which finds the nearest neighbor in a 503 * given direction. In rare cases, the default algorithm may not match the 504 * intended behavior of the developer. In these situations, you can provide 505 * explicit overrides by using these XML attributes in the layout file: 506 * <pre> 507 * nextFocusDown 508 * nextFocusLeft 509 * nextFocusRight 510 * nextFocusUp 511 * </pre> 512 * </p> 513 * 514 * 515 * <p> 516 * To get a particular view to take focus, call {@link #requestFocus()}. 517 * </p> 518 * 519 * <a name="TouchMode"></a> 520 * <h3>Touch Mode</h3> 521 * <p> 522 * When a user is navigating a user interface via directional keys such as a D-pad, it is 523 * necessary to give focus to actionable items such as buttons so the user can see 524 * what will take input. If the device has touch capabilities, however, and the user 525 * begins interacting with the interface by touching it, it is no longer necessary to 526 * always highlight, or give focus to, a particular view. This motivates a mode 527 * for interaction named 'touch mode'. 528 * </p> 529 * <p> 530 * For a touch capable device, once the user touches the screen, the device 531 * will enter touch mode. From this point onward, only views for which 532 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 533 * Other views that are touchable, like buttons, will not take focus when touched; they will 534 * only fire the on click listeners. 535 * </p> 536 * <p> 537 * Any time a user hits a directional key, such as a D-pad direction, the view device will 538 * exit touch mode, and find a view to take focus, so that the user may resume interacting 539 * with the user interface without touching the screen again. 540 * </p> 541 * <p> 542 * The touch mode state is maintained across {@link android.app.Activity}s. Call 543 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 544 * </p> 545 * 546 * <a name="Scrolling"></a> 547 * <h3>Scrolling</h3> 548 * <p> 549 * The framework provides basic support for views that wish to internally 550 * scroll their content. This includes keeping track of the X and Y scroll 551 * offset as well as mechanisms for drawing scrollbars. See 552 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 553 * {@link #awakenScrollBars()} for more details. 554 * </p> 555 * 556 * <a name="Tags"></a> 557 * <h3>Tags</h3> 558 * <p> 559 * Unlike IDs, tags are not used to identify views. Tags are essentially an 560 * extra piece of information that can be associated with a view. They are most 561 * often used as a convenience to store data related to views in the views 562 * themselves rather than by putting them in a separate structure. 563 * </p> 564 * 565 * <a name="Properties"></a> 566 * <h3>Properties</h3> 567 * <p> 568 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 569 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 570 * available both in the {@link Property} form as well as in similarly-named setter/getter 571 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 572 * be used to set persistent state associated with these rendering-related properties on the view. 573 * The properties and methods can also be used in conjunction with 574 * {@link android.animation.Animator Animator}-based animations, described more in the 575 * <a href="#Animation">Animation</a> section. 576 * </p> 577 * 578 * <a name="Animation"></a> 579 * <h3>Animation</h3> 580 * <p> 581 * Starting with Android 3.0, the preferred way of animating views is to use the 582 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 583 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 584 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 585 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 586 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 587 * makes animating these View properties particularly easy and efficient. 588 * </p> 589 * <p> 590 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 591 * You can attach an {@link Animation} object to a view using 592 * {@link #setAnimation(Animation)} or 593 * {@link #startAnimation(Animation)}. The animation can alter the scale, 594 * rotation, translation and alpha of a view over time. If the animation is 595 * attached to a view that has children, the animation will affect the entire 596 * subtree rooted by that node. When an animation is started, the framework will 597 * take care of redrawing the appropriate views until the animation completes. 598 * </p> 599 * 600 * <a name="Security"></a> 601 * <h3>Security</h3> 602 * <p> 603 * Sometimes it is essential that an application be able to verify that an action 604 * is being performed with the full knowledge and consent of the user, such as 605 * granting a permission request, making a purchase or clicking on an advertisement. 606 * Unfortunately, a malicious application could try to spoof the user into 607 * performing these actions, unaware, by concealing the intended purpose of the view. 608 * As a remedy, the framework offers a touch filtering mechanism that can be used to 609 * improve the security of views that provide access to sensitive functionality. 610 * </p><p> 611 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 612 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 613 * will discard touches that are received whenever the view's window is obscured by 614 * another visible window. As a result, the view will not receive touches whenever a 615 * toast, dialog or other window appears above the view's window. 616 * </p><p> 617 * For more fine-grained control over security, consider overriding the 618 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 619 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 620 * </p> 621 * 622 * @attr ref android.R.styleable#View_alpha 623 * @attr ref android.R.styleable#View_background 624 * @attr ref android.R.styleable#View_clickable 625 * @attr ref android.R.styleable#View_contentDescription 626 * @attr ref android.R.styleable#View_drawingCacheQuality 627 * @attr ref android.R.styleable#View_duplicateParentState 628 * @attr ref android.R.styleable#View_id 629 * @attr ref android.R.styleable#View_requiresFadingEdge 630 * @attr ref android.R.styleable#View_fadeScrollbars 631 * @attr ref android.R.styleable#View_fadingEdgeLength 632 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 633 * @attr ref android.R.styleable#View_fitsSystemWindows 634 * @attr ref android.R.styleable#View_isScrollContainer 635 * @attr ref android.R.styleable#View_focusable 636 * @attr ref android.R.styleable#View_focusableInTouchMode 637 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 638 * @attr ref android.R.styleable#View_keepScreenOn 639 * @attr ref android.R.styleable#View_layerType 640 * @attr ref android.R.styleable#View_layoutDirection 641 * @attr ref android.R.styleable#View_longClickable 642 * @attr ref android.R.styleable#View_minHeight 643 * @attr ref android.R.styleable#View_minWidth 644 * @attr ref android.R.styleable#View_nextFocusDown 645 * @attr ref android.R.styleable#View_nextFocusLeft 646 * @attr ref android.R.styleable#View_nextFocusRight 647 * @attr ref android.R.styleable#View_nextFocusUp 648 * @attr ref android.R.styleable#View_onClick 649 * @attr ref android.R.styleable#View_padding 650 * @attr ref android.R.styleable#View_paddingBottom 651 * @attr ref android.R.styleable#View_paddingLeft 652 * @attr ref android.R.styleable#View_paddingRight 653 * @attr ref android.R.styleable#View_paddingTop 654 * @attr ref android.R.styleable#View_paddingStart 655 * @attr ref android.R.styleable#View_paddingEnd 656 * @attr ref android.R.styleable#View_saveEnabled 657 * @attr ref android.R.styleable#View_rotation 658 * @attr ref android.R.styleable#View_rotationX 659 * @attr ref android.R.styleable#View_rotationY 660 * @attr ref android.R.styleable#View_scaleX 661 * @attr ref android.R.styleable#View_scaleY 662 * @attr ref android.R.styleable#View_scrollX 663 * @attr ref android.R.styleable#View_scrollY 664 * @attr ref android.R.styleable#View_scrollbarSize 665 * @attr ref android.R.styleable#View_scrollbarStyle 666 * @attr ref android.R.styleable#View_scrollbars 667 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 668 * @attr ref android.R.styleable#View_scrollbarFadeDuration 669 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 670 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 671 * @attr ref android.R.styleable#View_scrollbarThumbVertical 672 * @attr ref android.R.styleable#View_scrollbarTrackVertical 673 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 674 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 675 * @attr ref android.R.styleable#View_stateListAnimator 676 * @attr ref android.R.styleable#View_viewName 677 * @attr ref android.R.styleable#View_soundEffectsEnabled 678 * @attr ref android.R.styleable#View_tag 679 * @attr ref android.R.styleable#View_textAlignment 680 * @attr ref android.R.styleable#View_textDirection 681 * @attr ref android.R.styleable#View_transformPivotX 682 * @attr ref android.R.styleable#View_transformPivotY 683 * @attr ref android.R.styleable#View_translationX 684 * @attr ref android.R.styleable#View_translationY 685 * @attr ref android.R.styleable#View_translationZ 686 * @attr ref android.R.styleable#View_visibility 687 * 688 * @see android.view.ViewGroup 689 */ 690public class View implements Drawable.Callback, KeyEvent.Callback, 691 AccessibilityEventSource { 692 private static final boolean DBG = false; 693 694 /** 695 * The logging tag used by this class with android.util.Log. 696 */ 697 protected static final String VIEW_LOG_TAG = "View"; 698 699 /** 700 * When set to true, apps will draw debugging information about their layouts. 701 * 702 * @hide 703 */ 704 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 705 706 /** 707 * Used to mark a View that has no ID. 708 */ 709 public static final int NO_ID = -1; 710 711 /** 712 * Signals that compatibility booleans have been initialized according to 713 * target SDK versions. 714 */ 715 private static boolean sCompatibilityDone = false; 716 717 /** 718 * Use the old (broken) way of building MeasureSpecs. 719 */ 720 private static boolean sUseBrokenMakeMeasureSpec = false; 721 722 /** 723 * Ignore any optimizations using the measure cache. 724 */ 725 private static boolean sIgnoreMeasureCache = false; 726 727 /** 728 * Ignore the clipBounds of this view for the children. 729 */ 730 static boolean sIgnoreClipBoundsForChildren = false; 731 732 /** 733 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 734 * calling setFlags. 735 */ 736 private static final int NOT_FOCUSABLE = 0x00000000; 737 738 /** 739 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 740 * setFlags. 741 */ 742 private static final int FOCUSABLE = 0x00000001; 743 744 /** 745 * Mask for use with setFlags indicating bits used for focus. 746 */ 747 private static final int FOCUSABLE_MASK = 0x00000001; 748 749 /** 750 * This view will adjust its padding to fit sytem windows (e.g. status bar) 751 */ 752 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 753 754 /** @hide */ 755 @IntDef({VISIBLE, INVISIBLE, GONE}) 756 @Retention(RetentionPolicy.SOURCE) 757 public @interface Visibility {} 758 759 /** 760 * This view is visible. 761 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 762 * android:visibility}. 763 */ 764 public static final int VISIBLE = 0x00000000; 765 766 /** 767 * This view is invisible, but it still takes up space for layout purposes. 768 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 769 * android:visibility}. 770 */ 771 public static final int INVISIBLE = 0x00000004; 772 773 /** 774 * This view is invisible, and it doesn't take any space for layout 775 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 776 * android:visibility}. 777 */ 778 public static final int GONE = 0x00000008; 779 780 /** 781 * Mask for use with setFlags indicating bits used for visibility. 782 * {@hide} 783 */ 784 static final int VISIBILITY_MASK = 0x0000000C; 785 786 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 787 788 /** 789 * This view is enabled. Interpretation varies by subclass. 790 * Use with ENABLED_MASK when calling setFlags. 791 * {@hide} 792 */ 793 static final int ENABLED = 0x00000000; 794 795 /** 796 * This view is disabled. Interpretation varies by subclass. 797 * Use with ENABLED_MASK when calling setFlags. 798 * {@hide} 799 */ 800 static final int DISABLED = 0x00000020; 801 802 /** 803 * Mask for use with setFlags indicating bits used for indicating whether 804 * this view is enabled 805 * {@hide} 806 */ 807 static final int ENABLED_MASK = 0x00000020; 808 809 /** 810 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 811 * called and further optimizations will be performed. It is okay to have 812 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 813 * {@hide} 814 */ 815 static final int WILL_NOT_DRAW = 0x00000080; 816 817 /** 818 * Mask for use with setFlags indicating bits used for indicating whether 819 * this view is will draw 820 * {@hide} 821 */ 822 static final int DRAW_MASK = 0x00000080; 823 824 /** 825 * <p>This view doesn't show scrollbars.</p> 826 * {@hide} 827 */ 828 static final int SCROLLBARS_NONE = 0x00000000; 829 830 /** 831 * <p>This view shows horizontal scrollbars.</p> 832 * {@hide} 833 */ 834 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 835 836 /** 837 * <p>This view shows vertical scrollbars.</p> 838 * {@hide} 839 */ 840 static final int SCROLLBARS_VERTICAL = 0x00000200; 841 842 /** 843 * <p>Mask for use with setFlags indicating bits used for indicating which 844 * scrollbars are enabled.</p> 845 * {@hide} 846 */ 847 static final int SCROLLBARS_MASK = 0x00000300; 848 849 /** 850 * Indicates that the view should filter touches when its window is obscured. 851 * Refer to the class comments for more information about this security feature. 852 * {@hide} 853 */ 854 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 855 856 /** 857 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 858 * that they are optional and should be skipped if the window has 859 * requested system UI flags that ignore those insets for layout. 860 */ 861 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 862 863 /** 864 * <p>This view doesn't show fading edges.</p> 865 * {@hide} 866 */ 867 static final int FADING_EDGE_NONE = 0x00000000; 868 869 /** 870 * <p>This view shows horizontal fading edges.</p> 871 * {@hide} 872 */ 873 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 874 875 /** 876 * <p>This view shows vertical fading edges.</p> 877 * {@hide} 878 */ 879 static final int FADING_EDGE_VERTICAL = 0x00002000; 880 881 /** 882 * <p>Mask for use with setFlags indicating bits used for indicating which 883 * fading edges are enabled.</p> 884 * {@hide} 885 */ 886 static final int FADING_EDGE_MASK = 0x00003000; 887 888 /** 889 * <p>Indicates this view can be clicked. When clickable, a View reacts 890 * to clicks by notifying the OnClickListener.<p> 891 * {@hide} 892 */ 893 static final int CLICKABLE = 0x00004000; 894 895 /** 896 * <p>Indicates this view is caching its drawing into a bitmap.</p> 897 * {@hide} 898 */ 899 static final int DRAWING_CACHE_ENABLED = 0x00008000; 900 901 /** 902 * <p>Indicates that no icicle should be saved for this view.<p> 903 * {@hide} 904 */ 905 static final int SAVE_DISABLED = 0x000010000; 906 907 /** 908 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 909 * property.</p> 910 * {@hide} 911 */ 912 static final int SAVE_DISABLED_MASK = 0x000010000; 913 914 /** 915 * <p>Indicates that no drawing cache should ever be created for this view.<p> 916 * {@hide} 917 */ 918 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 919 920 /** 921 * <p>Indicates this view can take / keep focus when int touch mode.</p> 922 * {@hide} 923 */ 924 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 925 926 /** @hide */ 927 @Retention(RetentionPolicy.SOURCE) 928 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 929 public @interface DrawingCacheQuality {} 930 931 /** 932 * <p>Enables low quality mode for the drawing cache.</p> 933 */ 934 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 935 936 /** 937 * <p>Enables high quality mode for the drawing cache.</p> 938 */ 939 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 940 941 /** 942 * <p>Enables automatic quality mode for the drawing cache.</p> 943 */ 944 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 945 946 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 947 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 948 }; 949 950 /** 951 * <p>Mask for use with setFlags indicating bits used for the cache 952 * quality property.</p> 953 * {@hide} 954 */ 955 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 956 957 /** 958 * <p> 959 * Indicates this view can be long clicked. When long clickable, a View 960 * reacts to long clicks by notifying the OnLongClickListener or showing a 961 * context menu. 962 * </p> 963 * {@hide} 964 */ 965 static final int LONG_CLICKABLE = 0x00200000; 966 967 /** 968 * <p>Indicates that this view gets its drawable states from its direct parent 969 * and ignores its original internal states.</p> 970 * 971 * @hide 972 */ 973 static final int DUPLICATE_PARENT_STATE = 0x00400000; 974 975 /** @hide */ 976 @IntDef({ 977 SCROLLBARS_INSIDE_OVERLAY, 978 SCROLLBARS_INSIDE_INSET, 979 SCROLLBARS_OUTSIDE_OVERLAY, 980 SCROLLBARS_OUTSIDE_INSET 981 }) 982 @Retention(RetentionPolicy.SOURCE) 983 public @interface ScrollBarStyle {} 984 985 /** 986 * The scrollbar style to display the scrollbars inside the content area, 987 * without increasing the padding. The scrollbars will be overlaid with 988 * translucency on the view's content. 989 */ 990 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 991 992 /** 993 * The scrollbar style to display the scrollbars inside the padded area, 994 * increasing the padding of the view. The scrollbars will not overlap the 995 * content area of the view. 996 */ 997 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 998 999 /** 1000 * The scrollbar style to display the scrollbars at the edge of the view, 1001 * without increasing the padding. The scrollbars will be overlaid with 1002 * translucency. 1003 */ 1004 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1005 1006 /** 1007 * The scrollbar style to display the scrollbars at the edge of the view, 1008 * increasing the padding of the view. The scrollbars will only overlap the 1009 * background, if any. 1010 */ 1011 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1012 1013 /** 1014 * Mask to check if the scrollbar style is overlay or inset. 1015 * {@hide} 1016 */ 1017 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1018 1019 /** 1020 * Mask to check if the scrollbar style is inside or outside. 1021 * {@hide} 1022 */ 1023 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1024 1025 /** 1026 * Mask for scrollbar style. 1027 * {@hide} 1028 */ 1029 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1030 1031 /** 1032 * View flag indicating that the screen should remain on while the 1033 * window containing this view is visible to the user. This effectively 1034 * takes care of automatically setting the WindowManager's 1035 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1036 */ 1037 public static final int KEEP_SCREEN_ON = 0x04000000; 1038 1039 /** 1040 * View flag indicating whether this view should have sound effects enabled 1041 * for events such as clicking and touching. 1042 */ 1043 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1044 1045 /** 1046 * View flag indicating whether this view should have haptic feedback 1047 * enabled for events such as long presses. 1048 */ 1049 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1050 1051 /** 1052 * <p>Indicates that the view hierarchy should stop saving state when 1053 * it reaches this view. If state saving is initiated immediately at 1054 * the view, it will be allowed. 1055 * {@hide} 1056 */ 1057 static final int PARENT_SAVE_DISABLED = 0x20000000; 1058 1059 /** 1060 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1061 * {@hide} 1062 */ 1063 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1064 1065 /** @hide */ 1066 @IntDef(flag = true, 1067 value = { 1068 FOCUSABLES_ALL, 1069 FOCUSABLES_TOUCH_MODE 1070 }) 1071 @Retention(RetentionPolicy.SOURCE) 1072 public @interface FocusableMode {} 1073 1074 /** 1075 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1076 * should add all focusable Views regardless if they are focusable in touch mode. 1077 */ 1078 public static final int FOCUSABLES_ALL = 0x00000000; 1079 1080 /** 1081 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1082 * should add only Views focusable in touch mode. 1083 */ 1084 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1085 1086 /** @hide */ 1087 @IntDef({ 1088 FOCUS_BACKWARD, 1089 FOCUS_FORWARD, 1090 FOCUS_LEFT, 1091 FOCUS_UP, 1092 FOCUS_RIGHT, 1093 FOCUS_DOWN 1094 }) 1095 @Retention(RetentionPolicy.SOURCE) 1096 public @interface FocusDirection {} 1097 1098 /** @hide */ 1099 @IntDef({ 1100 FOCUS_LEFT, 1101 FOCUS_UP, 1102 FOCUS_RIGHT, 1103 FOCUS_DOWN 1104 }) 1105 @Retention(RetentionPolicy.SOURCE) 1106 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1107 1108 /** 1109 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1110 * item. 1111 */ 1112 public static final int FOCUS_BACKWARD = 0x00000001; 1113 1114 /** 1115 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1116 * item. 1117 */ 1118 public static final int FOCUS_FORWARD = 0x00000002; 1119 1120 /** 1121 * Use with {@link #focusSearch(int)}. Move focus to the left. 1122 */ 1123 public static final int FOCUS_LEFT = 0x00000011; 1124 1125 /** 1126 * Use with {@link #focusSearch(int)}. Move focus up. 1127 */ 1128 public static final int FOCUS_UP = 0x00000021; 1129 1130 /** 1131 * Use with {@link #focusSearch(int)}. Move focus to the right. 1132 */ 1133 public static final int FOCUS_RIGHT = 0x00000042; 1134 1135 /** 1136 * Use with {@link #focusSearch(int)}. Move focus down. 1137 */ 1138 public static final int FOCUS_DOWN = 0x00000082; 1139 1140 /** 1141 * Bits of {@link #getMeasuredWidthAndState()} and 1142 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1143 */ 1144 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1145 1146 /** 1147 * Bits of {@link #getMeasuredWidthAndState()} and 1148 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1149 */ 1150 public static final int MEASURED_STATE_MASK = 0xff000000; 1151 1152 /** 1153 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1154 * for functions that combine both width and height into a single int, 1155 * such as {@link #getMeasuredState()} and the childState argument of 1156 * {@link #resolveSizeAndState(int, int, int)}. 1157 */ 1158 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1159 1160 /** 1161 * Bit of {@link #getMeasuredWidthAndState()} and 1162 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1163 * is smaller that the space the view would like to have. 1164 */ 1165 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1166 1167 /** 1168 * Base View state sets 1169 */ 1170 // Singles 1171 /** 1172 * Indicates the view has no states set. States are used with 1173 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1174 * view depending on its state. 1175 * 1176 * @see android.graphics.drawable.Drawable 1177 * @see #getDrawableState() 1178 */ 1179 protected static final int[] EMPTY_STATE_SET; 1180 /** 1181 * Indicates the view is enabled. States are used with 1182 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1183 * view depending on its state. 1184 * 1185 * @see android.graphics.drawable.Drawable 1186 * @see #getDrawableState() 1187 */ 1188 protected static final int[] ENABLED_STATE_SET; 1189 /** 1190 * Indicates the view is focused. States are used with 1191 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1192 * view depending on its state. 1193 * 1194 * @see android.graphics.drawable.Drawable 1195 * @see #getDrawableState() 1196 */ 1197 protected static final int[] FOCUSED_STATE_SET; 1198 /** 1199 * Indicates the view is selected. States are used with 1200 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1201 * view depending on its state. 1202 * 1203 * @see android.graphics.drawable.Drawable 1204 * @see #getDrawableState() 1205 */ 1206 protected static final int[] SELECTED_STATE_SET; 1207 /** 1208 * Indicates the view is pressed. States are used with 1209 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1210 * view depending on its state. 1211 * 1212 * @see android.graphics.drawable.Drawable 1213 * @see #getDrawableState() 1214 */ 1215 protected static final int[] PRESSED_STATE_SET; 1216 /** 1217 * Indicates the view's window has focus. States are used with 1218 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1219 * view depending on its state. 1220 * 1221 * @see android.graphics.drawable.Drawable 1222 * @see #getDrawableState() 1223 */ 1224 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1225 // Doubles 1226 /** 1227 * Indicates the view is enabled and has the focus. 1228 * 1229 * @see #ENABLED_STATE_SET 1230 * @see #FOCUSED_STATE_SET 1231 */ 1232 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1233 /** 1234 * Indicates the view is enabled and selected. 1235 * 1236 * @see #ENABLED_STATE_SET 1237 * @see #SELECTED_STATE_SET 1238 */ 1239 protected static final int[] ENABLED_SELECTED_STATE_SET; 1240 /** 1241 * Indicates the view is enabled and that its window has focus. 1242 * 1243 * @see #ENABLED_STATE_SET 1244 * @see #WINDOW_FOCUSED_STATE_SET 1245 */ 1246 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1247 /** 1248 * Indicates the view is focused and selected. 1249 * 1250 * @see #FOCUSED_STATE_SET 1251 * @see #SELECTED_STATE_SET 1252 */ 1253 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1254 /** 1255 * Indicates the view has the focus and that its window has the focus. 1256 * 1257 * @see #FOCUSED_STATE_SET 1258 * @see #WINDOW_FOCUSED_STATE_SET 1259 */ 1260 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1261 /** 1262 * Indicates the view is selected and that its window has the focus. 1263 * 1264 * @see #SELECTED_STATE_SET 1265 * @see #WINDOW_FOCUSED_STATE_SET 1266 */ 1267 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1268 // Triples 1269 /** 1270 * Indicates the view is enabled, focused and selected. 1271 * 1272 * @see #ENABLED_STATE_SET 1273 * @see #FOCUSED_STATE_SET 1274 * @see #SELECTED_STATE_SET 1275 */ 1276 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1277 /** 1278 * Indicates the view is enabled, focused and its window has the focus. 1279 * 1280 * @see #ENABLED_STATE_SET 1281 * @see #FOCUSED_STATE_SET 1282 * @see #WINDOW_FOCUSED_STATE_SET 1283 */ 1284 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1285 /** 1286 * Indicates the view is enabled, selected and its window has the focus. 1287 * 1288 * @see #ENABLED_STATE_SET 1289 * @see #SELECTED_STATE_SET 1290 * @see #WINDOW_FOCUSED_STATE_SET 1291 */ 1292 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1293 /** 1294 * Indicates the view is focused, selected and its window has the focus. 1295 * 1296 * @see #FOCUSED_STATE_SET 1297 * @see #SELECTED_STATE_SET 1298 * @see #WINDOW_FOCUSED_STATE_SET 1299 */ 1300 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1301 /** 1302 * Indicates the view is enabled, focused, selected and its window 1303 * has the focus. 1304 * 1305 * @see #ENABLED_STATE_SET 1306 * @see #FOCUSED_STATE_SET 1307 * @see #SELECTED_STATE_SET 1308 * @see #WINDOW_FOCUSED_STATE_SET 1309 */ 1310 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1311 /** 1312 * Indicates the view is pressed and its window has the focus. 1313 * 1314 * @see #PRESSED_STATE_SET 1315 * @see #WINDOW_FOCUSED_STATE_SET 1316 */ 1317 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1318 /** 1319 * Indicates the view is pressed and selected. 1320 * 1321 * @see #PRESSED_STATE_SET 1322 * @see #SELECTED_STATE_SET 1323 */ 1324 protected static final int[] PRESSED_SELECTED_STATE_SET; 1325 /** 1326 * Indicates the view is pressed, selected and its window has the focus. 1327 * 1328 * @see #PRESSED_STATE_SET 1329 * @see #SELECTED_STATE_SET 1330 * @see #WINDOW_FOCUSED_STATE_SET 1331 */ 1332 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1333 /** 1334 * Indicates the view is pressed and focused. 1335 * 1336 * @see #PRESSED_STATE_SET 1337 * @see #FOCUSED_STATE_SET 1338 */ 1339 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1340 /** 1341 * Indicates the view is pressed, focused and its window has the focus. 1342 * 1343 * @see #PRESSED_STATE_SET 1344 * @see #FOCUSED_STATE_SET 1345 * @see #WINDOW_FOCUSED_STATE_SET 1346 */ 1347 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1348 /** 1349 * Indicates the view is pressed, focused and selected. 1350 * 1351 * @see #PRESSED_STATE_SET 1352 * @see #SELECTED_STATE_SET 1353 * @see #FOCUSED_STATE_SET 1354 */ 1355 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1356 /** 1357 * Indicates the view is pressed, focused, selected and its window has the focus. 1358 * 1359 * @see #PRESSED_STATE_SET 1360 * @see #FOCUSED_STATE_SET 1361 * @see #SELECTED_STATE_SET 1362 * @see #WINDOW_FOCUSED_STATE_SET 1363 */ 1364 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1365 /** 1366 * Indicates the view is pressed and enabled. 1367 * 1368 * @see #PRESSED_STATE_SET 1369 * @see #ENABLED_STATE_SET 1370 */ 1371 protected static final int[] PRESSED_ENABLED_STATE_SET; 1372 /** 1373 * Indicates the view is pressed, enabled and its window has the focus. 1374 * 1375 * @see #PRESSED_STATE_SET 1376 * @see #ENABLED_STATE_SET 1377 * @see #WINDOW_FOCUSED_STATE_SET 1378 */ 1379 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1380 /** 1381 * Indicates the view is pressed, enabled and selected. 1382 * 1383 * @see #PRESSED_STATE_SET 1384 * @see #ENABLED_STATE_SET 1385 * @see #SELECTED_STATE_SET 1386 */ 1387 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1388 /** 1389 * Indicates the view is pressed, enabled, selected and its window has the 1390 * focus. 1391 * 1392 * @see #PRESSED_STATE_SET 1393 * @see #ENABLED_STATE_SET 1394 * @see #SELECTED_STATE_SET 1395 * @see #WINDOW_FOCUSED_STATE_SET 1396 */ 1397 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1398 /** 1399 * Indicates the view is pressed, enabled and focused. 1400 * 1401 * @see #PRESSED_STATE_SET 1402 * @see #ENABLED_STATE_SET 1403 * @see #FOCUSED_STATE_SET 1404 */ 1405 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1406 /** 1407 * Indicates the view is pressed, enabled, focused and its window has the 1408 * focus. 1409 * 1410 * @see #PRESSED_STATE_SET 1411 * @see #ENABLED_STATE_SET 1412 * @see #FOCUSED_STATE_SET 1413 * @see #WINDOW_FOCUSED_STATE_SET 1414 */ 1415 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1416 /** 1417 * Indicates the view is pressed, enabled, focused and selected. 1418 * 1419 * @see #PRESSED_STATE_SET 1420 * @see #ENABLED_STATE_SET 1421 * @see #SELECTED_STATE_SET 1422 * @see #FOCUSED_STATE_SET 1423 */ 1424 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1425 /** 1426 * Indicates the view is pressed, enabled, focused, selected and its window 1427 * has the focus. 1428 * 1429 * @see #PRESSED_STATE_SET 1430 * @see #ENABLED_STATE_SET 1431 * @see #SELECTED_STATE_SET 1432 * @see #FOCUSED_STATE_SET 1433 * @see #WINDOW_FOCUSED_STATE_SET 1434 */ 1435 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1436 1437 /** 1438 * The order here is very important to {@link #getDrawableState()} 1439 */ 1440 private static final int[][] VIEW_STATE_SETS; 1441 1442 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1443 static final int VIEW_STATE_SELECTED = 1 << 1; 1444 static final int VIEW_STATE_FOCUSED = 1 << 2; 1445 static final int VIEW_STATE_ENABLED = 1 << 3; 1446 static final int VIEW_STATE_PRESSED = 1 << 4; 1447 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1448 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1449 static final int VIEW_STATE_HOVERED = 1 << 7; 1450 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1451 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1452 1453 static final int[] VIEW_STATE_IDS = new int[] { 1454 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1455 R.attr.state_selected, VIEW_STATE_SELECTED, 1456 R.attr.state_focused, VIEW_STATE_FOCUSED, 1457 R.attr.state_enabled, VIEW_STATE_ENABLED, 1458 R.attr.state_pressed, VIEW_STATE_PRESSED, 1459 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1460 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1461 R.attr.state_hovered, VIEW_STATE_HOVERED, 1462 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1463 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1464 }; 1465 1466 static { 1467 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1468 throw new IllegalStateException( 1469 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1470 } 1471 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1472 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1473 int viewState = R.styleable.ViewDrawableStates[i]; 1474 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1475 if (VIEW_STATE_IDS[j] == viewState) { 1476 orderedIds[i * 2] = viewState; 1477 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1478 } 1479 } 1480 } 1481 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1482 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1483 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1484 int numBits = Integer.bitCount(i); 1485 int[] set = new int[numBits]; 1486 int pos = 0; 1487 for (int j = 0; j < orderedIds.length; j += 2) { 1488 if ((i & orderedIds[j+1]) != 0) { 1489 set[pos++] = orderedIds[j]; 1490 } 1491 } 1492 VIEW_STATE_SETS[i] = set; 1493 } 1494 1495 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1496 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1497 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1498 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1499 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1500 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1501 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1502 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1503 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1504 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1505 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1506 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1507 | VIEW_STATE_FOCUSED]; 1508 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1509 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1510 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1511 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1512 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1513 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1514 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1515 | VIEW_STATE_ENABLED]; 1516 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1517 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1518 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1519 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1520 | VIEW_STATE_ENABLED]; 1521 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1522 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1523 | VIEW_STATE_ENABLED]; 1524 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1525 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1526 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1527 1528 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1529 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1530 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1531 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1532 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1533 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1534 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1535 | VIEW_STATE_PRESSED]; 1536 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1537 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1538 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1539 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1540 | VIEW_STATE_PRESSED]; 1541 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1542 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1543 | VIEW_STATE_PRESSED]; 1544 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1545 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1546 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1547 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1548 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1549 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1550 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1551 | VIEW_STATE_PRESSED]; 1552 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1553 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1554 | VIEW_STATE_PRESSED]; 1555 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1556 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1557 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1558 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1559 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1560 | VIEW_STATE_PRESSED]; 1561 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1562 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1563 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1564 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1565 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1566 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1567 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1568 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1569 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1570 | VIEW_STATE_PRESSED]; 1571 } 1572 1573 /** 1574 * Accessibility event types that are dispatched for text population. 1575 */ 1576 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1577 AccessibilityEvent.TYPE_VIEW_CLICKED 1578 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1579 | AccessibilityEvent.TYPE_VIEW_SELECTED 1580 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1581 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1582 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1583 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1584 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1585 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1586 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1587 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1588 1589 /** 1590 * Temporary Rect currently for use in setBackground(). This will probably 1591 * be extended in the future to hold our own class with more than just 1592 * a Rect. :) 1593 */ 1594 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1595 1596 /** 1597 * Map used to store views' tags. 1598 */ 1599 private SparseArray<Object> mKeyedTags; 1600 1601 /** 1602 * The next available accessibility id. 1603 */ 1604 private static int sNextAccessibilityViewId; 1605 1606 /** 1607 * The animation currently associated with this view. 1608 * @hide 1609 */ 1610 protected Animation mCurrentAnimation = null; 1611 1612 /** 1613 * Width as measured during measure pass. 1614 * {@hide} 1615 */ 1616 @ViewDebug.ExportedProperty(category = "measurement") 1617 int mMeasuredWidth; 1618 1619 /** 1620 * Height as measured during measure pass. 1621 * {@hide} 1622 */ 1623 @ViewDebug.ExportedProperty(category = "measurement") 1624 int mMeasuredHeight; 1625 1626 /** 1627 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1628 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1629 * its display list. This flag, used only when hw accelerated, allows us to clear the 1630 * flag while retaining this information until it's needed (at getDisplayList() time and 1631 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1632 * 1633 * {@hide} 1634 */ 1635 boolean mRecreateDisplayList = false; 1636 1637 /** 1638 * The view's identifier. 1639 * {@hide} 1640 * 1641 * @see #setId(int) 1642 * @see #getId() 1643 */ 1644 @ViewDebug.ExportedProperty(resolveId = true) 1645 int mID = NO_ID; 1646 1647 /** 1648 * The stable ID of this view for accessibility purposes. 1649 */ 1650 int mAccessibilityViewId = NO_ID; 1651 1652 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1653 1654 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1655 1656 /** 1657 * The view's tag. 1658 * {@hide} 1659 * 1660 * @see #setTag(Object) 1661 * @see #getTag() 1662 */ 1663 protected Object mTag = null; 1664 1665 // for mPrivateFlags: 1666 /** {@hide} */ 1667 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1668 /** {@hide} */ 1669 static final int PFLAG_FOCUSED = 0x00000002; 1670 /** {@hide} */ 1671 static final int PFLAG_SELECTED = 0x00000004; 1672 /** {@hide} */ 1673 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1674 /** {@hide} */ 1675 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1676 /** {@hide} */ 1677 static final int PFLAG_DRAWN = 0x00000020; 1678 /** 1679 * When this flag is set, this view is running an animation on behalf of its 1680 * children and should therefore not cancel invalidate requests, even if they 1681 * lie outside of this view's bounds. 1682 * 1683 * {@hide} 1684 */ 1685 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1686 /** {@hide} */ 1687 static final int PFLAG_SKIP_DRAW = 0x00000080; 1688 /** {@hide} */ 1689 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1690 /** {@hide} */ 1691 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1692 /** {@hide} */ 1693 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1694 /** {@hide} */ 1695 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1696 /** {@hide} */ 1697 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1698 /** {@hide} */ 1699 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1700 1701 private static final int PFLAG_PRESSED = 0x00004000; 1702 1703 /** {@hide} */ 1704 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1705 /** 1706 * Flag used to indicate that this view should be drawn once more (and only once 1707 * more) after its animation has completed. 1708 * {@hide} 1709 */ 1710 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1711 1712 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1713 1714 /** 1715 * Indicates that the View returned true when onSetAlpha() was called and that 1716 * the alpha must be restored. 1717 * {@hide} 1718 */ 1719 static final int PFLAG_ALPHA_SET = 0x00040000; 1720 1721 /** 1722 * Set by {@link #setScrollContainer(boolean)}. 1723 */ 1724 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1725 1726 /** 1727 * Set by {@link #setScrollContainer(boolean)}. 1728 */ 1729 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1730 1731 /** 1732 * View flag indicating whether this view was invalidated (fully or partially.) 1733 * 1734 * @hide 1735 */ 1736 static final int PFLAG_DIRTY = 0x00200000; 1737 1738 /** 1739 * View flag indicating whether this view was invalidated by an opaque 1740 * invalidate request. 1741 * 1742 * @hide 1743 */ 1744 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1745 1746 /** 1747 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1748 * 1749 * @hide 1750 */ 1751 static final int PFLAG_DIRTY_MASK = 0x00600000; 1752 1753 /** 1754 * Indicates whether the background is opaque. 1755 * 1756 * @hide 1757 */ 1758 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1759 1760 /** 1761 * Indicates whether the scrollbars are opaque. 1762 * 1763 * @hide 1764 */ 1765 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1766 1767 /** 1768 * Indicates whether the view is opaque. 1769 * 1770 * @hide 1771 */ 1772 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1773 1774 /** 1775 * Indicates a prepressed state; 1776 * the short time between ACTION_DOWN and recognizing 1777 * a 'real' press. Prepressed is used to recognize quick taps 1778 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1779 * 1780 * @hide 1781 */ 1782 private static final int PFLAG_PREPRESSED = 0x02000000; 1783 1784 /** 1785 * Indicates whether the view is temporarily detached. 1786 * 1787 * @hide 1788 */ 1789 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1790 1791 /** 1792 * Indicates that we should awaken scroll bars once attached 1793 * 1794 * @hide 1795 */ 1796 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1797 1798 /** 1799 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1800 * @hide 1801 */ 1802 private static final int PFLAG_HOVERED = 0x10000000; 1803 1804 /** 1805 * no longer needed, should be reused 1806 */ 1807 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1808 1809 /** {@hide} */ 1810 static final int PFLAG_ACTIVATED = 0x40000000; 1811 1812 /** 1813 * Indicates that this view was specifically invalidated, not just dirtied because some 1814 * child view was invalidated. The flag is used to determine when we need to recreate 1815 * a view's display list (as opposed to just returning a reference to its existing 1816 * display list). 1817 * 1818 * @hide 1819 */ 1820 static final int PFLAG_INVALIDATED = 0x80000000; 1821 1822 /** 1823 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1824 * 1825 * |-------|-------|-------|-------| 1826 * 1 PFLAG2_DRAG_CAN_ACCEPT 1827 * 1 PFLAG2_DRAG_HOVERED 1828 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1829 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1830 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1831 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1832 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1833 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1834 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1835 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1836 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1837 * 111 PFLAG2_TEXT_DIRECTION_MASK 1838 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1839 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1840 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1841 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1842 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1843 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1844 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1845 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1846 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1847 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1848 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1849 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1850 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1851 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1852 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1853 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1854 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1855 * 1 PFLAG2_VIEW_QUICK_REJECTED 1856 * 1 PFLAG2_PADDING_RESOLVED 1857 * 1 PFLAG2_DRAWABLE_RESOLVED 1858 * 1 PFLAG2_HAS_TRANSIENT_STATE 1859 * |-------|-------|-------|-------| 1860 */ 1861 1862 /** 1863 * Indicates that this view has reported that it can accept the current drag's content. 1864 * Cleared when the drag operation concludes. 1865 * @hide 1866 */ 1867 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1868 1869 /** 1870 * Indicates that this view is currently directly under the drag location in a 1871 * drag-and-drop operation involving content that it can accept. Cleared when 1872 * the drag exits the view, or when the drag operation concludes. 1873 * @hide 1874 */ 1875 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1876 1877 /** @hide */ 1878 @IntDef({ 1879 LAYOUT_DIRECTION_LTR, 1880 LAYOUT_DIRECTION_RTL, 1881 LAYOUT_DIRECTION_INHERIT, 1882 LAYOUT_DIRECTION_LOCALE 1883 }) 1884 @Retention(RetentionPolicy.SOURCE) 1885 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1886 public @interface LayoutDir {} 1887 1888 /** @hide */ 1889 @IntDef({ 1890 LAYOUT_DIRECTION_LTR, 1891 LAYOUT_DIRECTION_RTL 1892 }) 1893 @Retention(RetentionPolicy.SOURCE) 1894 public @interface ResolvedLayoutDir {} 1895 1896 /** 1897 * Horizontal layout direction of this view is from Left to Right. 1898 * Use with {@link #setLayoutDirection}. 1899 */ 1900 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1901 1902 /** 1903 * Horizontal layout direction of this view is from Right to Left. 1904 * Use with {@link #setLayoutDirection}. 1905 */ 1906 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1907 1908 /** 1909 * Horizontal layout direction of this view is inherited from its parent. 1910 * Use with {@link #setLayoutDirection}. 1911 */ 1912 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1913 1914 /** 1915 * Horizontal layout direction of this view is from deduced from the default language 1916 * script for the locale. Use with {@link #setLayoutDirection}. 1917 */ 1918 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1919 1920 /** 1921 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1922 * @hide 1923 */ 1924 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1925 1926 /** 1927 * Mask for use with private flags indicating bits used for horizontal layout direction. 1928 * @hide 1929 */ 1930 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1931 1932 /** 1933 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1934 * right-to-left direction. 1935 * @hide 1936 */ 1937 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1938 1939 /** 1940 * Indicates whether the view horizontal layout direction has been resolved. 1941 * @hide 1942 */ 1943 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1944 1945 /** 1946 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1947 * @hide 1948 */ 1949 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1950 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1951 1952 /* 1953 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1954 * flag value. 1955 * @hide 1956 */ 1957 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1958 LAYOUT_DIRECTION_LTR, 1959 LAYOUT_DIRECTION_RTL, 1960 LAYOUT_DIRECTION_INHERIT, 1961 LAYOUT_DIRECTION_LOCALE 1962 }; 1963 1964 /** 1965 * Default horizontal layout direction. 1966 */ 1967 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1968 1969 /** 1970 * Default horizontal layout direction. 1971 * @hide 1972 */ 1973 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1974 1975 /** 1976 * Text direction is inherited thru {@link ViewGroup} 1977 */ 1978 public static final int TEXT_DIRECTION_INHERIT = 0; 1979 1980 /** 1981 * Text direction is using "first strong algorithm". The first strong directional character 1982 * determines the paragraph direction. If there is no strong directional character, the 1983 * paragraph direction is the view's resolved layout direction. 1984 */ 1985 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1986 1987 /** 1988 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1989 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1990 * If there are neither, the paragraph direction is the view's resolved layout direction. 1991 */ 1992 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1993 1994 /** 1995 * Text direction is forced to LTR. 1996 */ 1997 public static final int TEXT_DIRECTION_LTR = 3; 1998 1999 /** 2000 * Text direction is forced to RTL. 2001 */ 2002 public static final int TEXT_DIRECTION_RTL = 4; 2003 2004 /** 2005 * Text direction is coming from the system Locale. 2006 */ 2007 public static final int TEXT_DIRECTION_LOCALE = 5; 2008 2009 /** 2010 * Default text direction is inherited 2011 */ 2012 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2013 2014 /** 2015 * Default resolved text direction 2016 * @hide 2017 */ 2018 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2019 2020 /** 2021 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2022 * @hide 2023 */ 2024 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2025 2026 /** 2027 * Mask for use with private flags indicating bits used for text direction. 2028 * @hide 2029 */ 2030 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2031 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2032 2033 /** 2034 * Array of text direction flags for mapping attribute "textDirection" to correct 2035 * flag value. 2036 * @hide 2037 */ 2038 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2039 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2040 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2041 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2042 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2043 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2044 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2045 }; 2046 2047 /** 2048 * Indicates whether the view text direction has been resolved. 2049 * @hide 2050 */ 2051 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2052 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2053 2054 /** 2055 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2056 * @hide 2057 */ 2058 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2059 2060 /** 2061 * Mask for use with private flags indicating bits used for resolved text direction. 2062 * @hide 2063 */ 2064 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2065 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2066 2067 /** 2068 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2069 * @hide 2070 */ 2071 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2072 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2073 2074 /** @hide */ 2075 @IntDef({ 2076 TEXT_ALIGNMENT_INHERIT, 2077 TEXT_ALIGNMENT_GRAVITY, 2078 TEXT_ALIGNMENT_CENTER, 2079 TEXT_ALIGNMENT_TEXT_START, 2080 TEXT_ALIGNMENT_TEXT_END, 2081 TEXT_ALIGNMENT_VIEW_START, 2082 TEXT_ALIGNMENT_VIEW_END 2083 }) 2084 @Retention(RetentionPolicy.SOURCE) 2085 public @interface TextAlignment {} 2086 2087 /** 2088 * Default text alignment. The text alignment of this View is inherited from its parent. 2089 * Use with {@link #setTextAlignment(int)} 2090 */ 2091 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2092 2093 /** 2094 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2095 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2096 * 2097 * Use with {@link #setTextAlignment(int)} 2098 */ 2099 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2100 2101 /** 2102 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2103 * 2104 * Use with {@link #setTextAlignment(int)} 2105 */ 2106 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2107 2108 /** 2109 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2110 * 2111 * Use with {@link #setTextAlignment(int)} 2112 */ 2113 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2114 2115 /** 2116 * Center the paragraph, e.g. ALIGN_CENTER. 2117 * 2118 * Use with {@link #setTextAlignment(int)} 2119 */ 2120 public static final int TEXT_ALIGNMENT_CENTER = 4; 2121 2122 /** 2123 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2124 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2125 * 2126 * Use with {@link #setTextAlignment(int)} 2127 */ 2128 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2129 2130 /** 2131 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2132 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2133 * 2134 * Use with {@link #setTextAlignment(int)} 2135 */ 2136 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2137 2138 /** 2139 * Default text alignment is inherited 2140 */ 2141 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2142 2143 /** 2144 * Default resolved text alignment 2145 * @hide 2146 */ 2147 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2148 2149 /** 2150 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2151 * @hide 2152 */ 2153 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2154 2155 /** 2156 * Mask for use with private flags indicating bits used for text alignment. 2157 * @hide 2158 */ 2159 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2160 2161 /** 2162 * Array of text direction flags for mapping attribute "textAlignment" to correct 2163 * flag value. 2164 * @hide 2165 */ 2166 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2167 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2168 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2169 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2170 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2171 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2172 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2173 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2174 }; 2175 2176 /** 2177 * Indicates whether the view text alignment has been resolved. 2178 * @hide 2179 */ 2180 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2181 2182 /** 2183 * Bit shift to get the resolved text alignment. 2184 * @hide 2185 */ 2186 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2187 2188 /** 2189 * Mask for use with private flags indicating bits used for text alignment. 2190 * @hide 2191 */ 2192 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2193 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2194 2195 /** 2196 * Indicates whether if the view text alignment has been resolved to gravity 2197 */ 2198 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2199 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2200 2201 // Accessiblity constants for mPrivateFlags2 2202 2203 /** 2204 * Shift for the bits in {@link #mPrivateFlags2} related to the 2205 * "importantForAccessibility" attribute. 2206 */ 2207 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2208 2209 /** 2210 * Automatically determine whether a view is important for accessibility. 2211 */ 2212 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2213 2214 /** 2215 * The view is important for accessibility. 2216 */ 2217 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2218 2219 /** 2220 * The view is not important for accessibility. 2221 */ 2222 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2223 2224 /** 2225 * The view is not important for accessibility, nor are any of its 2226 * descendant views. 2227 */ 2228 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2229 2230 /** 2231 * The default whether the view is important for accessibility. 2232 */ 2233 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2234 2235 /** 2236 * Mask for obtainig the bits which specify how to determine 2237 * whether a view is important for accessibility. 2238 */ 2239 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2240 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2241 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2242 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2243 2244 /** 2245 * Shift for the bits in {@link #mPrivateFlags2} related to the 2246 * "accessibilityLiveRegion" attribute. 2247 */ 2248 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2249 2250 /** 2251 * Live region mode specifying that accessibility services should not 2252 * automatically announce changes to this view. This is the default live 2253 * region mode for most views. 2254 * <p> 2255 * Use with {@link #setAccessibilityLiveRegion(int)}. 2256 */ 2257 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2258 2259 /** 2260 * Live region mode specifying that accessibility services should announce 2261 * changes to this view. 2262 * <p> 2263 * Use with {@link #setAccessibilityLiveRegion(int)}. 2264 */ 2265 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2266 2267 /** 2268 * Live region mode specifying that accessibility services should interrupt 2269 * ongoing speech to immediately announce changes to this view. 2270 * <p> 2271 * Use with {@link #setAccessibilityLiveRegion(int)}. 2272 */ 2273 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2274 2275 /** 2276 * The default whether the view is important for accessibility. 2277 */ 2278 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2279 2280 /** 2281 * Mask for obtaining the bits which specify a view's accessibility live 2282 * region mode. 2283 */ 2284 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2285 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2286 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2287 2288 /** 2289 * Flag indicating whether a view has accessibility focus. 2290 */ 2291 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2292 2293 /** 2294 * Flag whether the accessibility state of the subtree rooted at this view changed. 2295 */ 2296 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2297 2298 /** 2299 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2300 * is used to check whether later changes to the view's transform should invalidate the 2301 * view to force the quickReject test to run again. 2302 */ 2303 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2304 2305 /** 2306 * Flag indicating that start/end padding has been resolved into left/right padding 2307 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2308 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2309 * during measurement. In some special cases this is required such as when an adapter-based 2310 * view measures prospective children without attaching them to a window. 2311 */ 2312 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2313 2314 /** 2315 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2316 */ 2317 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2318 2319 /** 2320 * Indicates that the view is tracking some sort of transient state 2321 * that the app should not need to be aware of, but that the framework 2322 * should take special care to preserve. 2323 */ 2324 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2325 2326 /** 2327 * Group of bits indicating that RTL properties resolution is done. 2328 */ 2329 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2330 PFLAG2_TEXT_DIRECTION_RESOLVED | 2331 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2332 PFLAG2_PADDING_RESOLVED | 2333 PFLAG2_DRAWABLE_RESOLVED; 2334 2335 // There are a couple of flags left in mPrivateFlags2 2336 2337 /* End of masks for mPrivateFlags2 */ 2338 2339 /** 2340 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2341 * 2342 * |-------|-------|-------|-------| 2343 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2344 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2345 * 1 PFLAG3_IS_LAID_OUT 2346 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2347 * 1 PFLAG3_CALLED_SUPER 2348 * |-------|-------|-------|-------| 2349 */ 2350 2351 /** 2352 * Flag indicating that view has a transform animation set on it. This is used to track whether 2353 * an animation is cleared between successive frames, in order to tell the associated 2354 * DisplayList to clear its animation matrix. 2355 */ 2356 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2357 2358 /** 2359 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2360 * animation is cleared between successive frames, in order to tell the associated 2361 * DisplayList to restore its alpha value. 2362 */ 2363 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2364 2365 /** 2366 * Flag indicating that the view has been through at least one layout since it 2367 * was last attached to a window. 2368 */ 2369 static final int PFLAG3_IS_LAID_OUT = 0x4; 2370 2371 /** 2372 * Flag indicating that a call to measure() was skipped and should be done 2373 * instead when layout() is invoked. 2374 */ 2375 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2376 2377 /** 2378 * Flag indicating that an overridden method correctly called down to 2379 * the superclass implementation as required by the API spec. 2380 */ 2381 static final int PFLAG3_CALLED_SUPER = 0x10; 2382 2383 /** 2384 * Flag indicating that a view's outline has been specifically defined. 2385 */ 2386 static final int PFLAG3_OUTLINE_DEFINED = 0x20; 2387 2388 /** 2389 * Flag indicating that we're in the process of applying window insets. 2390 */ 2391 static final int PFLAG3_APPLYING_INSETS = 0x40; 2392 2393 /** 2394 * Flag indicating that we're in the process of fitting system windows using the old method. 2395 */ 2396 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80; 2397 2398 /** 2399 * Flag indicating that nested scrolling is enabled for this view. 2400 * The view will optionally cooperate with views up its parent chain to allow for 2401 * integrated nested scrolling along the same axis. 2402 */ 2403 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x200; 2404 2405 /* End of masks for mPrivateFlags3 */ 2406 2407 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2408 2409 /** 2410 * Always allow a user to over-scroll this view, provided it is a 2411 * view that can scroll. 2412 * 2413 * @see #getOverScrollMode() 2414 * @see #setOverScrollMode(int) 2415 */ 2416 public static final int OVER_SCROLL_ALWAYS = 0; 2417 2418 /** 2419 * Allow a user to over-scroll this view only if the content is large 2420 * enough to meaningfully scroll, provided it is a view that can scroll. 2421 * 2422 * @see #getOverScrollMode() 2423 * @see #setOverScrollMode(int) 2424 */ 2425 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2426 2427 /** 2428 * Never allow a user to over-scroll this view. 2429 * 2430 * @see #getOverScrollMode() 2431 * @see #setOverScrollMode(int) 2432 */ 2433 public static final int OVER_SCROLL_NEVER = 2; 2434 2435 /** 2436 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2437 * requested the system UI (status bar) to be visible (the default). 2438 * 2439 * @see #setSystemUiVisibility(int) 2440 */ 2441 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2442 2443 /** 2444 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2445 * system UI to enter an unobtrusive "low profile" mode. 2446 * 2447 * <p>This is for use in games, book readers, video players, or any other 2448 * "immersive" application where the usual system chrome is deemed too distracting. 2449 * 2450 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2451 * 2452 * @see #setSystemUiVisibility(int) 2453 */ 2454 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2455 2456 /** 2457 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2458 * system navigation be temporarily hidden. 2459 * 2460 * <p>This is an even less obtrusive state than that called for by 2461 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2462 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2463 * those to disappear. This is useful (in conjunction with the 2464 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2465 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2466 * window flags) for displaying content using every last pixel on the display. 2467 * 2468 * <p>There is a limitation: because navigation controls are so important, the least user 2469 * interaction will cause them to reappear immediately. When this happens, both 2470 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2471 * so that both elements reappear at the same time. 2472 * 2473 * @see #setSystemUiVisibility(int) 2474 */ 2475 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2476 2477 /** 2478 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2479 * into the normal fullscreen mode so that its content can take over the screen 2480 * while still allowing the user to interact with the application. 2481 * 2482 * <p>This has the same visual effect as 2483 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2484 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2485 * meaning that non-critical screen decorations (such as the status bar) will be 2486 * hidden while the user is in the View's window, focusing the experience on 2487 * that content. Unlike the window flag, if you are using ActionBar in 2488 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2489 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2490 * hide the action bar. 2491 * 2492 * <p>This approach to going fullscreen is best used over the window flag when 2493 * it is a transient state -- that is, the application does this at certain 2494 * points in its user interaction where it wants to allow the user to focus 2495 * on content, but not as a continuous state. For situations where the application 2496 * would like to simply stay full screen the entire time (such as a game that 2497 * wants to take over the screen), the 2498 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2499 * is usually a better approach. The state set here will be removed by the system 2500 * in various situations (such as the user moving to another application) like 2501 * the other system UI states. 2502 * 2503 * <p>When using this flag, the application should provide some easy facility 2504 * for the user to go out of it. A common example would be in an e-book 2505 * reader, where tapping on the screen brings back whatever screen and UI 2506 * decorations that had been hidden while the user was immersed in reading 2507 * the book. 2508 * 2509 * @see #setSystemUiVisibility(int) 2510 */ 2511 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2512 2513 /** 2514 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2515 * flags, we would like a stable view of the content insets given to 2516 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2517 * will always represent the worst case that the application can expect 2518 * as a continuous state. In the stock Android UI this is the space for 2519 * the system bar, nav bar, and status bar, but not more transient elements 2520 * such as an input method. 2521 * 2522 * The stable layout your UI sees is based on the system UI modes you can 2523 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2524 * then you will get a stable layout for changes of the 2525 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2526 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2527 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2528 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2529 * with a stable layout. (Note that you should avoid using 2530 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2531 * 2532 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2533 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2534 * then a hidden status bar will be considered a "stable" state for purposes 2535 * here. This allows your UI to continually hide the status bar, while still 2536 * using the system UI flags to hide the action bar while still retaining 2537 * a stable layout. Note that changing the window fullscreen flag will never 2538 * provide a stable layout for a clean transition. 2539 * 2540 * <p>If you are using ActionBar in 2541 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2542 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2543 * insets it adds to those given to the application. 2544 */ 2545 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2546 2547 /** 2548 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2549 * to be layed out as if it has requested 2550 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2551 * allows it to avoid artifacts when switching in and out of that mode, at 2552 * the expense that some of its user interface may be covered by screen 2553 * decorations when they are shown. You can perform layout of your inner 2554 * UI elements to account for the navigation system UI through the 2555 * {@link #fitSystemWindows(Rect)} method. 2556 */ 2557 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2558 2559 /** 2560 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2561 * to be layed out as if it has requested 2562 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2563 * allows it to avoid artifacts when switching in and out of that mode, at 2564 * the expense that some of its user interface may be covered by screen 2565 * decorations when they are shown. You can perform layout of your inner 2566 * UI elements to account for non-fullscreen system UI through the 2567 * {@link #fitSystemWindows(Rect)} method. 2568 */ 2569 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2570 2571 /** 2572 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2573 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2574 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2575 * user interaction. 2576 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2577 * has an effect when used in combination with that flag.</p> 2578 */ 2579 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2580 2581 /** 2582 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2583 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2584 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2585 * experience while also hiding the system bars. If this flag is not set, 2586 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2587 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2588 * if the user swipes from the top of the screen. 2589 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2590 * system gestures, such as swiping from the top of the screen. These transient system bars 2591 * will overlay app’s content, may have some degree of transparency, and will automatically 2592 * hide after a short timeout. 2593 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2594 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2595 * with one or both of those flags.</p> 2596 */ 2597 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2598 2599 /** 2600 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2601 */ 2602 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2603 2604 /** 2605 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2606 */ 2607 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2608 2609 /** 2610 * @hide 2611 * 2612 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2613 * out of the public fields to keep the undefined bits out of the developer's way. 2614 * 2615 * Flag to make the status bar not expandable. Unless you also 2616 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2617 */ 2618 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2619 2620 /** 2621 * @hide 2622 * 2623 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2624 * out of the public fields to keep the undefined bits out of the developer's way. 2625 * 2626 * Flag to hide notification icons and scrolling ticker text. 2627 */ 2628 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2629 2630 /** 2631 * @hide 2632 * 2633 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2634 * out of the public fields to keep the undefined bits out of the developer's way. 2635 * 2636 * Flag to disable incoming notification alerts. This will not block 2637 * icons, but it will block sound, vibrating and other visual or aural notifications. 2638 */ 2639 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2640 2641 /** 2642 * @hide 2643 * 2644 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2645 * out of the public fields to keep the undefined bits out of the developer's way. 2646 * 2647 * Flag to hide only the scrolling ticker. Note that 2648 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2649 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2650 */ 2651 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2652 2653 /** 2654 * @hide 2655 * 2656 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2657 * out of the public fields to keep the undefined bits out of the developer's way. 2658 * 2659 * Flag to hide the center system info area. 2660 */ 2661 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2662 2663 /** 2664 * @hide 2665 * 2666 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2667 * out of the public fields to keep the undefined bits out of the developer's way. 2668 * 2669 * Flag to hide only the home button. Don't use this 2670 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2671 */ 2672 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2673 2674 /** 2675 * @hide 2676 * 2677 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2678 * out of the public fields to keep the undefined bits out of the developer's way. 2679 * 2680 * Flag to hide only the back button. Don't use this 2681 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2682 */ 2683 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2684 2685 /** 2686 * @hide 2687 * 2688 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2689 * out of the public fields to keep the undefined bits out of the developer's way. 2690 * 2691 * Flag to hide only the clock. You might use this if your activity has 2692 * its own clock making the status bar's clock redundant. 2693 */ 2694 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2695 2696 /** 2697 * @hide 2698 * 2699 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2700 * out of the public fields to keep the undefined bits out of the developer's way. 2701 * 2702 * Flag to hide only the recent apps button. Don't use this 2703 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2704 */ 2705 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2706 2707 /** 2708 * @hide 2709 * 2710 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2711 * out of the public fields to keep the undefined bits out of the developer's way. 2712 * 2713 * Flag to disable the global search gesture. Don't use this 2714 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2715 */ 2716 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2717 2718 /** 2719 * @hide 2720 * 2721 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2722 * out of the public fields to keep the undefined bits out of the developer's way. 2723 * 2724 * Flag to specify that the status bar is displayed in transient mode. 2725 */ 2726 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2727 2728 /** 2729 * @hide 2730 * 2731 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2732 * out of the public fields to keep the undefined bits out of the developer's way. 2733 * 2734 * Flag to specify that the navigation bar is displayed in transient mode. 2735 */ 2736 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2737 2738 /** 2739 * @hide 2740 * 2741 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2742 * out of the public fields to keep the undefined bits out of the developer's way. 2743 * 2744 * Flag to specify that the hidden status bar would like to be shown. 2745 */ 2746 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2747 2748 /** 2749 * @hide 2750 * 2751 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2752 * out of the public fields to keep the undefined bits out of the developer's way. 2753 * 2754 * Flag to specify that the hidden navigation bar would like to be shown. 2755 */ 2756 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2757 2758 /** 2759 * @hide 2760 * 2761 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2762 * out of the public fields to keep the undefined bits out of the developer's way. 2763 * 2764 * Flag to specify that the status bar is displayed in translucent mode. 2765 */ 2766 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2767 2768 /** 2769 * @hide 2770 * 2771 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2772 * out of the public fields to keep the undefined bits out of the developer's way. 2773 * 2774 * Flag to specify that the navigation bar is displayed in translucent mode. 2775 */ 2776 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2777 2778 /** 2779 * @hide 2780 * 2781 * Whether Recents is visible or not. 2782 */ 2783 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2784 2785 /** 2786 * @hide 2787 * 2788 * Makes system ui transparent. 2789 */ 2790 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2791 2792 /** 2793 * @hide 2794 */ 2795 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2796 2797 /** 2798 * These are the system UI flags that can be cleared by events outside 2799 * of an application. Currently this is just the ability to tap on the 2800 * screen while hiding the navigation bar to have it return. 2801 * @hide 2802 */ 2803 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2804 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2805 | SYSTEM_UI_FLAG_FULLSCREEN; 2806 2807 /** 2808 * Flags that can impact the layout in relation to system UI. 2809 */ 2810 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2811 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2812 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2813 2814 /** @hide */ 2815 @IntDef(flag = true, 2816 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2817 @Retention(RetentionPolicy.SOURCE) 2818 public @interface FindViewFlags {} 2819 2820 /** 2821 * Find views that render the specified text. 2822 * 2823 * @see #findViewsWithText(ArrayList, CharSequence, int) 2824 */ 2825 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2826 2827 /** 2828 * Find find views that contain the specified content description. 2829 * 2830 * @see #findViewsWithText(ArrayList, CharSequence, int) 2831 */ 2832 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2833 2834 /** 2835 * Find views that contain {@link AccessibilityNodeProvider}. Such 2836 * a View is a root of virtual view hierarchy and may contain the searched 2837 * text. If this flag is set Views with providers are automatically 2838 * added and it is a responsibility of the client to call the APIs of 2839 * the provider to determine whether the virtual tree rooted at this View 2840 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2841 * representing the virtual views with this text. 2842 * 2843 * @see #findViewsWithText(ArrayList, CharSequence, int) 2844 * 2845 * @hide 2846 */ 2847 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2848 2849 /** 2850 * The undefined cursor position. 2851 * 2852 * @hide 2853 */ 2854 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2855 2856 /** 2857 * Indicates that the screen has changed state and is now off. 2858 * 2859 * @see #onScreenStateChanged(int) 2860 */ 2861 public static final int SCREEN_STATE_OFF = 0x0; 2862 2863 /** 2864 * Indicates that the screen has changed state and is now on. 2865 * 2866 * @see #onScreenStateChanged(int) 2867 */ 2868 public static final int SCREEN_STATE_ON = 0x1; 2869 2870 /** 2871 * Indicates no axis of view scrolling. 2872 */ 2873 public static final int SCROLL_AXIS_NONE = 0; 2874 2875 /** 2876 * Indicates scrolling along the horizontal axis. 2877 */ 2878 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2879 2880 /** 2881 * Indicates scrolling along the vertical axis. 2882 */ 2883 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2884 2885 /** 2886 * Controls the over-scroll mode for this view. 2887 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2888 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2889 * and {@link #OVER_SCROLL_NEVER}. 2890 */ 2891 private int mOverScrollMode; 2892 2893 /** 2894 * The parent this view is attached to. 2895 * {@hide} 2896 * 2897 * @see #getParent() 2898 */ 2899 protected ViewParent mParent; 2900 2901 /** 2902 * {@hide} 2903 */ 2904 AttachInfo mAttachInfo; 2905 2906 /** 2907 * {@hide} 2908 */ 2909 @ViewDebug.ExportedProperty(flagMapping = { 2910 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2911 name = "FORCE_LAYOUT"), 2912 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2913 name = "LAYOUT_REQUIRED"), 2914 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2915 name = "DRAWING_CACHE_INVALID", outputIf = false), 2916 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2917 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2918 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2919 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2920 }) 2921 int mPrivateFlags; 2922 int mPrivateFlags2; 2923 int mPrivateFlags3; 2924 2925 /** 2926 * This view's request for the visibility of the status bar. 2927 * @hide 2928 */ 2929 @ViewDebug.ExportedProperty(flagMapping = { 2930 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2931 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2932 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2933 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2934 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2935 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2936 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2937 equals = SYSTEM_UI_FLAG_VISIBLE, 2938 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2939 }) 2940 int mSystemUiVisibility; 2941 2942 /** 2943 * Reference count for transient state. 2944 * @see #setHasTransientState(boolean) 2945 */ 2946 int mTransientStateCount = 0; 2947 2948 /** 2949 * Count of how many windows this view has been attached to. 2950 */ 2951 int mWindowAttachCount; 2952 2953 /** 2954 * The layout parameters associated with this view and used by the parent 2955 * {@link android.view.ViewGroup} to determine how this view should be 2956 * laid out. 2957 * {@hide} 2958 */ 2959 protected ViewGroup.LayoutParams mLayoutParams; 2960 2961 /** 2962 * The view flags hold various views states. 2963 * {@hide} 2964 */ 2965 @ViewDebug.ExportedProperty 2966 int mViewFlags; 2967 2968 static class TransformationInfo { 2969 /** 2970 * The transform matrix for the View. This transform is calculated internally 2971 * based on the translation, rotation, and scale properties. 2972 * 2973 * Do *not* use this variable directly; instead call getMatrix(), which will 2974 * load the value from the View's RenderNode. 2975 */ 2976 private final Matrix mMatrix = new Matrix(); 2977 2978 /** 2979 * The inverse transform matrix for the View. This transform is calculated 2980 * internally based on the translation, rotation, and scale properties. 2981 * 2982 * Do *not* use this variable directly; instead call getInverseMatrix(), 2983 * which will load the value from the View's RenderNode. 2984 */ 2985 private Matrix mInverseMatrix; 2986 2987 /** 2988 * The opacity of the View. This is a value from 0 to 1, where 0 means 2989 * completely transparent and 1 means completely opaque. 2990 */ 2991 @ViewDebug.ExportedProperty 2992 float mAlpha = 1f; 2993 2994 /** 2995 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2996 * property only used by transitions, which is composited with the other alpha 2997 * values to calculate the final visual alpha value. 2998 */ 2999 float mTransitionAlpha = 1f; 3000 } 3001 3002 TransformationInfo mTransformationInfo; 3003 3004 /** 3005 * Current clip bounds. to which all drawing of this view are constrained. 3006 */ 3007 Rect mClipBounds = null; 3008 3009 private boolean mLastIsOpaque; 3010 3011 /** 3012 * The distance in pixels from the left edge of this view's parent 3013 * to the left edge of this view. 3014 * {@hide} 3015 */ 3016 @ViewDebug.ExportedProperty(category = "layout") 3017 protected int mLeft; 3018 /** 3019 * The distance in pixels from the left edge of this view's parent 3020 * to the right edge of this view. 3021 * {@hide} 3022 */ 3023 @ViewDebug.ExportedProperty(category = "layout") 3024 protected int mRight; 3025 /** 3026 * The distance in pixels from the top edge of this view's parent 3027 * to the top edge of this view. 3028 * {@hide} 3029 */ 3030 @ViewDebug.ExportedProperty(category = "layout") 3031 protected int mTop; 3032 /** 3033 * The distance in pixels from the top edge of this view's parent 3034 * to the bottom edge of this view. 3035 * {@hide} 3036 */ 3037 @ViewDebug.ExportedProperty(category = "layout") 3038 protected int mBottom; 3039 3040 /** 3041 * The offset, in pixels, by which the content of this view is scrolled 3042 * horizontally. 3043 * {@hide} 3044 */ 3045 @ViewDebug.ExportedProperty(category = "scrolling") 3046 protected int mScrollX; 3047 /** 3048 * The offset, in pixels, by which the content of this view is scrolled 3049 * vertically. 3050 * {@hide} 3051 */ 3052 @ViewDebug.ExportedProperty(category = "scrolling") 3053 protected int mScrollY; 3054 3055 /** 3056 * The left padding in pixels, that is the distance in pixels between the 3057 * left edge of this view and the left edge of its content. 3058 * {@hide} 3059 */ 3060 @ViewDebug.ExportedProperty(category = "padding") 3061 protected int mPaddingLeft = 0; 3062 /** 3063 * The right padding in pixels, that is the distance in pixels between the 3064 * right edge of this view and the right edge of its content. 3065 * {@hide} 3066 */ 3067 @ViewDebug.ExportedProperty(category = "padding") 3068 protected int mPaddingRight = 0; 3069 /** 3070 * The top padding in pixels, that is the distance in pixels between the 3071 * top edge of this view and the top edge of its content. 3072 * {@hide} 3073 */ 3074 @ViewDebug.ExportedProperty(category = "padding") 3075 protected int mPaddingTop; 3076 /** 3077 * The bottom padding in pixels, that is the distance in pixels between the 3078 * bottom edge of this view and the bottom edge of its content. 3079 * {@hide} 3080 */ 3081 @ViewDebug.ExportedProperty(category = "padding") 3082 protected int mPaddingBottom; 3083 3084 /** 3085 * The layout insets in pixels, that is the distance in pixels between the 3086 * visible edges of this view its bounds. 3087 */ 3088 private Insets mLayoutInsets; 3089 3090 /** 3091 * Briefly describes the view and is primarily used for accessibility support. 3092 */ 3093 private CharSequence mContentDescription; 3094 3095 /** 3096 * Specifies the id of a view for which this view serves as a label for 3097 * accessibility purposes. 3098 */ 3099 private int mLabelForId = View.NO_ID; 3100 3101 /** 3102 * Predicate for matching labeled view id with its label for 3103 * accessibility purposes. 3104 */ 3105 private MatchLabelForPredicate mMatchLabelForPredicate; 3106 3107 /** 3108 * Predicate for matching a view by its id. 3109 */ 3110 private MatchIdPredicate mMatchIdPredicate; 3111 3112 /** 3113 * Cache the paddingRight set by the user to append to the scrollbar's size. 3114 * 3115 * @hide 3116 */ 3117 @ViewDebug.ExportedProperty(category = "padding") 3118 protected int mUserPaddingRight; 3119 3120 /** 3121 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3122 * 3123 * @hide 3124 */ 3125 @ViewDebug.ExportedProperty(category = "padding") 3126 protected int mUserPaddingBottom; 3127 3128 /** 3129 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3130 * 3131 * @hide 3132 */ 3133 @ViewDebug.ExportedProperty(category = "padding") 3134 protected int mUserPaddingLeft; 3135 3136 /** 3137 * Cache the paddingStart set by the user to append to the scrollbar's size. 3138 * 3139 */ 3140 @ViewDebug.ExportedProperty(category = "padding") 3141 int mUserPaddingStart; 3142 3143 /** 3144 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3145 * 3146 */ 3147 @ViewDebug.ExportedProperty(category = "padding") 3148 int mUserPaddingEnd; 3149 3150 /** 3151 * Cache initial left padding. 3152 * 3153 * @hide 3154 */ 3155 int mUserPaddingLeftInitial; 3156 3157 /** 3158 * Cache initial right padding. 3159 * 3160 * @hide 3161 */ 3162 int mUserPaddingRightInitial; 3163 3164 /** 3165 * Default undefined padding 3166 */ 3167 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3168 3169 /** 3170 * Cache if a left padding has been defined 3171 */ 3172 private boolean mLeftPaddingDefined = false; 3173 3174 /** 3175 * Cache if a right padding has been defined 3176 */ 3177 private boolean mRightPaddingDefined = false; 3178 3179 /** 3180 * @hide 3181 */ 3182 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3183 /** 3184 * @hide 3185 */ 3186 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3187 3188 private LongSparseLongArray mMeasureCache; 3189 3190 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3191 private Drawable mBackground; 3192 private ColorStateList mBackgroundTint = null; 3193 private PorterDuff.Mode mBackgroundTintMode = PorterDuff.Mode.SRC_ATOP; 3194 private boolean mHasBackgroundTint = false; 3195 3196 /** 3197 * Display list used for backgrounds. 3198 * <p> 3199 * When non-null and valid, this is expected to contain an up-to-date copy 3200 * of the background drawable. It is cleared on temporary detach and reset 3201 * on cleanup. 3202 */ 3203 private RenderNode mBackgroundDisplayList; 3204 3205 private int mBackgroundResource; 3206 private boolean mBackgroundSizeChanged; 3207 3208 private String mViewName; 3209 3210 static class ListenerInfo { 3211 /** 3212 * Listener used to dispatch focus change events. 3213 * This field should be made private, so it is hidden from the SDK. 3214 * {@hide} 3215 */ 3216 protected OnFocusChangeListener mOnFocusChangeListener; 3217 3218 /** 3219 * Listeners for layout change events. 3220 */ 3221 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3222 3223 /** 3224 * Listeners for attach events. 3225 */ 3226 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3227 3228 /** 3229 * Listener used to dispatch click events. 3230 * This field should be made private, so it is hidden from the SDK. 3231 * {@hide} 3232 */ 3233 public OnClickListener mOnClickListener; 3234 3235 /** 3236 * Listener used to dispatch long click events. 3237 * This field should be made private, so it is hidden from the SDK. 3238 * {@hide} 3239 */ 3240 protected OnLongClickListener mOnLongClickListener; 3241 3242 /** 3243 * Listener used to build the context menu. 3244 * This field should be made private, so it is hidden from the SDK. 3245 * {@hide} 3246 */ 3247 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3248 3249 private OnKeyListener mOnKeyListener; 3250 3251 private OnTouchListener mOnTouchListener; 3252 3253 private OnHoverListener mOnHoverListener; 3254 3255 private OnGenericMotionListener mOnGenericMotionListener; 3256 3257 private OnDragListener mOnDragListener; 3258 3259 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3260 3261 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3262 } 3263 3264 ListenerInfo mListenerInfo; 3265 3266 /** 3267 * The application environment this view lives in. 3268 * This field should be made private, so it is hidden from the SDK. 3269 * {@hide} 3270 */ 3271 protected Context mContext; 3272 3273 private final Resources mResources; 3274 3275 private ScrollabilityCache mScrollCache; 3276 3277 private int[] mDrawableState = null; 3278 3279 /** 3280 * Stores the outline of the view, passed down to the DisplayList level for 3281 * defining shadow shape. 3282 */ 3283 private Outline mOutline; 3284 3285 /** 3286 * Animator that automatically runs based on state changes. 3287 */ 3288 private StateListAnimator mStateListAnimator; 3289 3290 /** 3291 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3292 * the user may specify which view to go to next. 3293 */ 3294 private int mNextFocusLeftId = View.NO_ID; 3295 3296 /** 3297 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3298 * the user may specify which view to go to next. 3299 */ 3300 private int mNextFocusRightId = View.NO_ID; 3301 3302 /** 3303 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3304 * the user may specify which view to go to next. 3305 */ 3306 private int mNextFocusUpId = View.NO_ID; 3307 3308 /** 3309 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3310 * the user may specify which view to go to next. 3311 */ 3312 private int mNextFocusDownId = View.NO_ID; 3313 3314 /** 3315 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3316 * the user may specify which view to go to next. 3317 */ 3318 int mNextFocusForwardId = View.NO_ID; 3319 3320 private CheckForLongPress mPendingCheckForLongPress; 3321 private CheckForTap mPendingCheckForTap = null; 3322 private PerformClick mPerformClick; 3323 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3324 3325 private UnsetPressedState mUnsetPressedState; 3326 3327 /** 3328 * Whether the long press's action has been invoked. The tap's action is invoked on the 3329 * up event while a long press is invoked as soon as the long press duration is reached, so 3330 * a long press could be performed before the tap is checked, in which case the tap's action 3331 * should not be invoked. 3332 */ 3333 private boolean mHasPerformedLongPress; 3334 3335 /** 3336 * The minimum height of the view. We'll try our best to have the height 3337 * of this view to at least this amount. 3338 */ 3339 @ViewDebug.ExportedProperty(category = "measurement") 3340 private int mMinHeight; 3341 3342 /** 3343 * The minimum width of the view. We'll try our best to have the width 3344 * of this view to at least this amount. 3345 */ 3346 @ViewDebug.ExportedProperty(category = "measurement") 3347 private int mMinWidth; 3348 3349 /** 3350 * The delegate to handle touch events that are physically in this view 3351 * but should be handled by another view. 3352 */ 3353 private TouchDelegate mTouchDelegate = null; 3354 3355 /** 3356 * Solid color to use as a background when creating the drawing cache. Enables 3357 * the cache to use 16 bit bitmaps instead of 32 bit. 3358 */ 3359 private int mDrawingCacheBackgroundColor = 0; 3360 3361 /** 3362 * Special tree observer used when mAttachInfo is null. 3363 */ 3364 private ViewTreeObserver mFloatingTreeObserver; 3365 3366 /** 3367 * Cache the touch slop from the context that created the view. 3368 */ 3369 private int mTouchSlop; 3370 3371 /** 3372 * Object that handles automatic animation of view properties. 3373 */ 3374 private ViewPropertyAnimator mAnimator = null; 3375 3376 /** 3377 * Flag indicating that a drag can cross window boundaries. When 3378 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3379 * with this flag set, all visible applications will be able to participate 3380 * in the drag operation and receive the dragged content. 3381 * 3382 * @hide 3383 */ 3384 public static final int DRAG_FLAG_GLOBAL = 1; 3385 3386 /** 3387 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3388 */ 3389 private float mVerticalScrollFactor; 3390 3391 /** 3392 * Position of the vertical scroll bar. 3393 */ 3394 private int mVerticalScrollbarPosition; 3395 3396 /** 3397 * Position the scroll bar at the default position as determined by the system. 3398 */ 3399 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3400 3401 /** 3402 * Position the scroll bar along the left edge. 3403 */ 3404 public static final int SCROLLBAR_POSITION_LEFT = 1; 3405 3406 /** 3407 * Position the scroll bar along the right edge. 3408 */ 3409 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3410 3411 /** 3412 * Indicates that the view does not have a layer. 3413 * 3414 * @see #getLayerType() 3415 * @see #setLayerType(int, android.graphics.Paint) 3416 * @see #LAYER_TYPE_SOFTWARE 3417 * @see #LAYER_TYPE_HARDWARE 3418 */ 3419 public static final int LAYER_TYPE_NONE = 0; 3420 3421 /** 3422 * <p>Indicates that the view has a software layer. A software layer is backed 3423 * by a bitmap and causes the view to be rendered using Android's software 3424 * rendering pipeline, even if hardware acceleration is enabled.</p> 3425 * 3426 * <p>Software layers have various usages:</p> 3427 * <p>When the application is not using hardware acceleration, a software layer 3428 * is useful to apply a specific color filter and/or blending mode and/or 3429 * translucency to a view and all its children.</p> 3430 * <p>When the application is using hardware acceleration, a software layer 3431 * is useful to render drawing primitives not supported by the hardware 3432 * accelerated pipeline. It can also be used to cache a complex view tree 3433 * into a texture and reduce the complexity of drawing operations. For instance, 3434 * when animating a complex view tree with a translation, a software layer can 3435 * be used to render the view tree only once.</p> 3436 * <p>Software layers should be avoided when the affected view tree updates 3437 * often. Every update will require to re-render the software layer, which can 3438 * potentially be slow (particularly when hardware acceleration is turned on 3439 * since the layer will have to be uploaded into a hardware texture after every 3440 * update.)</p> 3441 * 3442 * @see #getLayerType() 3443 * @see #setLayerType(int, android.graphics.Paint) 3444 * @see #LAYER_TYPE_NONE 3445 * @see #LAYER_TYPE_HARDWARE 3446 */ 3447 public static final int LAYER_TYPE_SOFTWARE = 1; 3448 3449 /** 3450 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3451 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3452 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3453 * rendering pipeline, but only if hardware acceleration is turned on for the 3454 * view hierarchy. When hardware acceleration is turned off, hardware layers 3455 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3456 * 3457 * <p>A hardware layer is useful to apply a specific color filter and/or 3458 * blending mode and/or translucency to a view and all its children.</p> 3459 * <p>A hardware layer can be used to cache a complex view tree into a 3460 * texture and reduce the complexity of drawing operations. For instance, 3461 * when animating a complex view tree with a translation, a hardware layer can 3462 * be used to render the view tree only once.</p> 3463 * <p>A hardware layer can also be used to increase the rendering quality when 3464 * rotation transformations are applied on a view. It can also be used to 3465 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3466 * 3467 * @see #getLayerType() 3468 * @see #setLayerType(int, android.graphics.Paint) 3469 * @see #LAYER_TYPE_NONE 3470 * @see #LAYER_TYPE_SOFTWARE 3471 */ 3472 public static final int LAYER_TYPE_HARDWARE = 2; 3473 3474 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3475 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3476 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3477 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3478 }) 3479 int mLayerType = LAYER_TYPE_NONE; 3480 Paint mLayerPaint; 3481 3482 /** 3483 * Set to true when drawing cache is enabled and cannot be created. 3484 * 3485 * @hide 3486 */ 3487 public boolean mCachingFailed; 3488 private Bitmap mDrawingCache; 3489 private Bitmap mUnscaledDrawingCache; 3490 3491 /** 3492 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3493 * <p> 3494 * When non-null and valid, this is expected to contain an up-to-date copy 3495 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3496 * cleanup. 3497 */ 3498 final RenderNode mRenderNode; 3499 3500 /** 3501 * Set to true when the view is sending hover accessibility events because it 3502 * is the innermost hovered view. 3503 */ 3504 private boolean mSendingHoverAccessibilityEvents; 3505 3506 /** 3507 * Delegate for injecting accessibility functionality. 3508 */ 3509 AccessibilityDelegate mAccessibilityDelegate; 3510 3511 /** 3512 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3513 * and add/remove objects to/from the overlay directly through the Overlay methods. 3514 */ 3515 ViewOverlay mOverlay; 3516 3517 /** 3518 * The currently active parent view for receiving delegated nested scrolling events. 3519 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3520 * by {@link #stopNestedScroll()} at the same point where we clear 3521 * requestDisallowInterceptTouchEvent. 3522 */ 3523 private ViewParent mNestedScrollingParent; 3524 3525 /** 3526 * Consistency verifier for debugging purposes. 3527 * @hide 3528 */ 3529 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3530 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3531 new InputEventConsistencyVerifier(this, 0) : null; 3532 3533 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3534 3535 private int[] mTempNestedScrollConsumed; 3536 3537 /** 3538 * Simple constructor to use when creating a view from code. 3539 * 3540 * @param context The Context the view is running in, through which it can 3541 * access the current theme, resources, etc. 3542 */ 3543 public View(Context context) { 3544 mContext = context; 3545 mResources = context != null ? context.getResources() : null; 3546 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3547 // Set some flags defaults 3548 mPrivateFlags2 = 3549 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3550 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3551 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3552 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3553 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3554 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3555 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3556 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3557 mUserPaddingStart = UNDEFINED_PADDING; 3558 mUserPaddingEnd = UNDEFINED_PADDING; 3559 mRenderNode = RenderNode.create(getClass().getName()); 3560 3561 if (!sCompatibilityDone && context != null) { 3562 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3563 3564 // Older apps may need this compatibility hack for measurement. 3565 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3566 3567 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3568 // of whether a layout was requested on that View. 3569 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3570 3571 // Older apps may need this to ignore the clip bounds 3572 sIgnoreClipBoundsForChildren = targetSdkVersion < L; 3573 3574 sCompatibilityDone = true; 3575 } 3576 } 3577 3578 /** 3579 * Constructor that is called when inflating a view from XML. This is called 3580 * when a view is being constructed from an XML file, supplying attributes 3581 * that were specified in the XML file. This version uses a default style of 3582 * 0, so the only attribute values applied are those in the Context's Theme 3583 * and the given AttributeSet. 3584 * 3585 * <p> 3586 * The method onFinishInflate() will be called after all children have been 3587 * added. 3588 * 3589 * @param context The Context the view is running in, through which it can 3590 * access the current theme, resources, etc. 3591 * @param attrs The attributes of the XML tag that is inflating the view. 3592 * @see #View(Context, AttributeSet, int) 3593 */ 3594 public View(Context context, AttributeSet attrs) { 3595 this(context, attrs, 0); 3596 } 3597 3598 /** 3599 * Perform inflation from XML and apply a class-specific base style from a 3600 * theme attribute. This constructor of View allows subclasses to use their 3601 * own base style when they are inflating. For example, a Button class's 3602 * constructor would call this version of the super class constructor and 3603 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3604 * allows the theme's button style to modify all of the base view attributes 3605 * (in particular its background) as well as the Button class's attributes. 3606 * 3607 * @param context The Context the view is running in, through which it can 3608 * access the current theme, resources, etc. 3609 * @param attrs The attributes of the XML tag that is inflating the view. 3610 * @param defStyleAttr An attribute in the current theme that contains a 3611 * reference to a style resource that supplies default values for 3612 * the view. Can be 0 to not look for defaults. 3613 * @see #View(Context, AttributeSet) 3614 */ 3615 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3616 this(context, attrs, defStyleAttr, 0); 3617 } 3618 3619 /** 3620 * Perform inflation from XML and apply a class-specific base style from a 3621 * theme attribute or style resource. This constructor of View allows 3622 * subclasses to use their own base style when they are inflating. 3623 * <p> 3624 * When determining the final value of a particular attribute, there are 3625 * four inputs that come into play: 3626 * <ol> 3627 * <li>Any attribute values in the given AttributeSet. 3628 * <li>The style resource specified in the AttributeSet (named "style"). 3629 * <li>The default style specified by <var>defStyleAttr</var>. 3630 * <li>The default style specified by <var>defStyleRes</var>. 3631 * <li>The base values in this theme. 3632 * </ol> 3633 * <p> 3634 * Each of these inputs is considered in-order, with the first listed taking 3635 * precedence over the following ones. In other words, if in the 3636 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3637 * , then the button's text will <em>always</em> be black, regardless of 3638 * what is specified in any of the styles. 3639 * 3640 * @param context The Context the view is running in, through which it can 3641 * access the current theme, resources, etc. 3642 * @param attrs The attributes of the XML tag that is inflating the view. 3643 * @param defStyleAttr An attribute in the current theme that contains a 3644 * reference to a style resource that supplies default values for 3645 * the view. Can be 0 to not look for defaults. 3646 * @param defStyleRes A resource identifier of a style resource that 3647 * supplies default values for the view, used only if 3648 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3649 * to not look for defaults. 3650 * @see #View(Context, AttributeSet, int) 3651 */ 3652 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3653 this(context); 3654 3655 final TypedArray a = context.obtainStyledAttributes( 3656 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3657 3658 Drawable background = null; 3659 3660 int leftPadding = -1; 3661 int topPadding = -1; 3662 int rightPadding = -1; 3663 int bottomPadding = -1; 3664 int startPadding = UNDEFINED_PADDING; 3665 int endPadding = UNDEFINED_PADDING; 3666 3667 int padding = -1; 3668 3669 int viewFlagValues = 0; 3670 int viewFlagMasks = 0; 3671 3672 boolean setScrollContainer = false; 3673 3674 int x = 0; 3675 int y = 0; 3676 3677 float tx = 0; 3678 float ty = 0; 3679 float tz = 0; 3680 float elevation = 0; 3681 float rotation = 0; 3682 float rotationX = 0; 3683 float rotationY = 0; 3684 float sx = 1f; 3685 float sy = 1f; 3686 boolean transformSet = false; 3687 3688 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3689 int overScrollMode = mOverScrollMode; 3690 boolean initializeScrollbars = false; 3691 3692 boolean startPaddingDefined = false; 3693 boolean endPaddingDefined = false; 3694 boolean leftPaddingDefined = false; 3695 boolean rightPaddingDefined = false; 3696 3697 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3698 3699 final int N = a.getIndexCount(); 3700 for (int i = 0; i < N; i++) { 3701 int attr = a.getIndex(i); 3702 switch (attr) { 3703 case com.android.internal.R.styleable.View_background: 3704 background = a.getDrawable(attr); 3705 break; 3706 case com.android.internal.R.styleable.View_padding: 3707 padding = a.getDimensionPixelSize(attr, -1); 3708 mUserPaddingLeftInitial = padding; 3709 mUserPaddingRightInitial = padding; 3710 leftPaddingDefined = true; 3711 rightPaddingDefined = true; 3712 break; 3713 case com.android.internal.R.styleable.View_paddingLeft: 3714 leftPadding = a.getDimensionPixelSize(attr, -1); 3715 mUserPaddingLeftInitial = leftPadding; 3716 leftPaddingDefined = true; 3717 break; 3718 case com.android.internal.R.styleable.View_paddingTop: 3719 topPadding = a.getDimensionPixelSize(attr, -1); 3720 break; 3721 case com.android.internal.R.styleable.View_paddingRight: 3722 rightPadding = a.getDimensionPixelSize(attr, -1); 3723 mUserPaddingRightInitial = rightPadding; 3724 rightPaddingDefined = true; 3725 break; 3726 case com.android.internal.R.styleable.View_paddingBottom: 3727 bottomPadding = a.getDimensionPixelSize(attr, -1); 3728 break; 3729 case com.android.internal.R.styleable.View_paddingStart: 3730 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3731 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3732 break; 3733 case com.android.internal.R.styleable.View_paddingEnd: 3734 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3735 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3736 break; 3737 case com.android.internal.R.styleable.View_scrollX: 3738 x = a.getDimensionPixelOffset(attr, 0); 3739 break; 3740 case com.android.internal.R.styleable.View_scrollY: 3741 y = a.getDimensionPixelOffset(attr, 0); 3742 break; 3743 case com.android.internal.R.styleable.View_alpha: 3744 setAlpha(a.getFloat(attr, 1f)); 3745 break; 3746 case com.android.internal.R.styleable.View_transformPivotX: 3747 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3748 break; 3749 case com.android.internal.R.styleable.View_transformPivotY: 3750 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3751 break; 3752 case com.android.internal.R.styleable.View_translationX: 3753 tx = a.getDimensionPixelOffset(attr, 0); 3754 transformSet = true; 3755 break; 3756 case com.android.internal.R.styleable.View_translationY: 3757 ty = a.getDimensionPixelOffset(attr, 0); 3758 transformSet = true; 3759 break; 3760 case com.android.internal.R.styleable.View_translationZ: 3761 tz = a.getDimensionPixelOffset(attr, 0); 3762 transformSet = true; 3763 break; 3764 case com.android.internal.R.styleable.View_elevation: 3765 elevation = a.getDimensionPixelOffset(attr, 0); 3766 transformSet = true; 3767 break; 3768 case com.android.internal.R.styleable.View_rotation: 3769 rotation = a.getFloat(attr, 0); 3770 transformSet = true; 3771 break; 3772 case com.android.internal.R.styleable.View_rotationX: 3773 rotationX = a.getFloat(attr, 0); 3774 transformSet = true; 3775 break; 3776 case com.android.internal.R.styleable.View_rotationY: 3777 rotationY = a.getFloat(attr, 0); 3778 transformSet = true; 3779 break; 3780 case com.android.internal.R.styleable.View_scaleX: 3781 sx = a.getFloat(attr, 1f); 3782 transformSet = true; 3783 break; 3784 case com.android.internal.R.styleable.View_scaleY: 3785 sy = a.getFloat(attr, 1f); 3786 transformSet = true; 3787 break; 3788 case com.android.internal.R.styleable.View_id: 3789 mID = a.getResourceId(attr, NO_ID); 3790 break; 3791 case com.android.internal.R.styleable.View_tag: 3792 mTag = a.getText(attr); 3793 break; 3794 case com.android.internal.R.styleable.View_fitsSystemWindows: 3795 if (a.getBoolean(attr, false)) { 3796 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3797 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3798 } 3799 break; 3800 case com.android.internal.R.styleable.View_focusable: 3801 if (a.getBoolean(attr, false)) { 3802 viewFlagValues |= FOCUSABLE; 3803 viewFlagMasks |= FOCUSABLE_MASK; 3804 } 3805 break; 3806 case com.android.internal.R.styleable.View_focusableInTouchMode: 3807 if (a.getBoolean(attr, false)) { 3808 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3809 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3810 } 3811 break; 3812 case com.android.internal.R.styleable.View_clickable: 3813 if (a.getBoolean(attr, false)) { 3814 viewFlagValues |= CLICKABLE; 3815 viewFlagMasks |= CLICKABLE; 3816 } 3817 break; 3818 case com.android.internal.R.styleable.View_longClickable: 3819 if (a.getBoolean(attr, false)) { 3820 viewFlagValues |= LONG_CLICKABLE; 3821 viewFlagMasks |= LONG_CLICKABLE; 3822 } 3823 break; 3824 case com.android.internal.R.styleable.View_saveEnabled: 3825 if (!a.getBoolean(attr, true)) { 3826 viewFlagValues |= SAVE_DISABLED; 3827 viewFlagMasks |= SAVE_DISABLED_MASK; 3828 } 3829 break; 3830 case com.android.internal.R.styleable.View_duplicateParentState: 3831 if (a.getBoolean(attr, false)) { 3832 viewFlagValues |= DUPLICATE_PARENT_STATE; 3833 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3834 } 3835 break; 3836 case com.android.internal.R.styleable.View_visibility: 3837 final int visibility = a.getInt(attr, 0); 3838 if (visibility != 0) { 3839 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3840 viewFlagMasks |= VISIBILITY_MASK; 3841 } 3842 break; 3843 case com.android.internal.R.styleable.View_layoutDirection: 3844 // Clear any layout direction flags (included resolved bits) already set 3845 mPrivateFlags2 &= 3846 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3847 // Set the layout direction flags depending on the value of the attribute 3848 final int layoutDirection = a.getInt(attr, -1); 3849 final int value = (layoutDirection != -1) ? 3850 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3851 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3852 break; 3853 case com.android.internal.R.styleable.View_drawingCacheQuality: 3854 final int cacheQuality = a.getInt(attr, 0); 3855 if (cacheQuality != 0) { 3856 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3857 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3858 } 3859 break; 3860 case com.android.internal.R.styleable.View_contentDescription: 3861 setContentDescription(a.getString(attr)); 3862 break; 3863 case com.android.internal.R.styleable.View_labelFor: 3864 setLabelFor(a.getResourceId(attr, NO_ID)); 3865 break; 3866 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3867 if (!a.getBoolean(attr, true)) { 3868 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3869 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3870 } 3871 break; 3872 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3873 if (!a.getBoolean(attr, true)) { 3874 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3875 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3876 } 3877 break; 3878 case R.styleable.View_scrollbars: 3879 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3880 if (scrollbars != SCROLLBARS_NONE) { 3881 viewFlagValues |= scrollbars; 3882 viewFlagMasks |= SCROLLBARS_MASK; 3883 initializeScrollbars = true; 3884 } 3885 break; 3886 //noinspection deprecation 3887 case R.styleable.View_fadingEdge: 3888 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3889 // Ignore the attribute starting with ICS 3890 break; 3891 } 3892 // With builds < ICS, fall through and apply fading edges 3893 case R.styleable.View_requiresFadingEdge: 3894 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3895 if (fadingEdge != FADING_EDGE_NONE) { 3896 viewFlagValues |= fadingEdge; 3897 viewFlagMasks |= FADING_EDGE_MASK; 3898 initializeFadingEdge(a); 3899 } 3900 break; 3901 case R.styleable.View_scrollbarStyle: 3902 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3903 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3904 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3905 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3906 } 3907 break; 3908 case R.styleable.View_isScrollContainer: 3909 setScrollContainer = true; 3910 if (a.getBoolean(attr, false)) { 3911 setScrollContainer(true); 3912 } 3913 break; 3914 case com.android.internal.R.styleable.View_keepScreenOn: 3915 if (a.getBoolean(attr, false)) { 3916 viewFlagValues |= KEEP_SCREEN_ON; 3917 viewFlagMasks |= KEEP_SCREEN_ON; 3918 } 3919 break; 3920 case R.styleable.View_filterTouchesWhenObscured: 3921 if (a.getBoolean(attr, false)) { 3922 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3923 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3924 } 3925 break; 3926 case R.styleable.View_nextFocusLeft: 3927 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3928 break; 3929 case R.styleable.View_nextFocusRight: 3930 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3931 break; 3932 case R.styleable.View_nextFocusUp: 3933 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3934 break; 3935 case R.styleable.View_nextFocusDown: 3936 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3937 break; 3938 case R.styleable.View_nextFocusForward: 3939 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3940 break; 3941 case R.styleable.View_minWidth: 3942 mMinWidth = a.getDimensionPixelSize(attr, 0); 3943 break; 3944 case R.styleable.View_minHeight: 3945 mMinHeight = a.getDimensionPixelSize(attr, 0); 3946 break; 3947 case R.styleable.View_onClick: 3948 if (context.isRestricted()) { 3949 throw new IllegalStateException("The android:onClick attribute cannot " 3950 + "be used within a restricted context"); 3951 } 3952 3953 final String handlerName = a.getString(attr); 3954 if (handlerName != null) { 3955 setOnClickListener(new OnClickListener() { 3956 private Method mHandler; 3957 3958 public void onClick(View v) { 3959 if (mHandler == null) { 3960 try { 3961 mHandler = getContext().getClass().getMethod(handlerName, 3962 View.class); 3963 } catch (NoSuchMethodException e) { 3964 int id = getId(); 3965 String idText = id == NO_ID ? "" : " with id '" 3966 + getContext().getResources().getResourceEntryName( 3967 id) + "'"; 3968 throw new IllegalStateException("Could not find a method " + 3969 handlerName + "(View) in the activity " 3970 + getContext().getClass() + " for onClick handler" 3971 + " on view " + View.this.getClass() + idText, e); 3972 } 3973 } 3974 3975 try { 3976 mHandler.invoke(getContext(), View.this); 3977 } catch (IllegalAccessException e) { 3978 throw new IllegalStateException("Could not execute non " 3979 + "public method of the activity", e); 3980 } catch (InvocationTargetException e) { 3981 throw new IllegalStateException("Could not execute " 3982 + "method of the activity", e); 3983 } 3984 } 3985 }); 3986 } 3987 break; 3988 case R.styleable.View_overScrollMode: 3989 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3990 break; 3991 case R.styleable.View_verticalScrollbarPosition: 3992 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3993 break; 3994 case R.styleable.View_layerType: 3995 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3996 break; 3997 case R.styleable.View_textDirection: 3998 // Clear any text direction flag already set 3999 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4000 // Set the text direction flags depending on the value of the attribute 4001 final int textDirection = a.getInt(attr, -1); 4002 if (textDirection != -1) { 4003 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4004 } 4005 break; 4006 case R.styleable.View_textAlignment: 4007 // Clear any text alignment flag already set 4008 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4009 // Set the text alignment flag depending on the value of the attribute 4010 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4011 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4012 break; 4013 case R.styleable.View_importantForAccessibility: 4014 setImportantForAccessibility(a.getInt(attr, 4015 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4016 break; 4017 case R.styleable.View_accessibilityLiveRegion: 4018 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4019 break; 4020 case R.styleable.View_viewName: 4021 setViewName(a.getString(attr)); 4022 break; 4023 case R.styleable.View_nestedScrollingEnabled: 4024 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4025 break; 4026 case R.styleable.View_stateListAnimator: 4027 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4028 a.getResourceId(attr, 0))); 4029 break; 4030 case R.styleable.View_backgroundTint: 4031 // This will get applied later during setBackground(). 4032 mBackgroundTint = a.getColorStateList(R.styleable.View_backgroundTint); 4033 mHasBackgroundTint = true; 4034 break; 4035 case R.styleable.View_backgroundTintMode: 4036 // This will get applied later during setBackground(). 4037 mBackgroundTintMode = Drawable.parseTintMode(a.getInt( 4038 R.styleable.View_backgroundTintMode, -1), mBackgroundTintMode); 4039 break; 4040 } 4041 } 4042 4043 setOverScrollMode(overScrollMode); 4044 4045 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4046 // the resolved layout direction). Those cached values will be used later during padding 4047 // resolution. 4048 mUserPaddingStart = startPadding; 4049 mUserPaddingEnd = endPadding; 4050 4051 if (background != null) { 4052 setBackground(background); 4053 } 4054 4055 // setBackground above will record that padding is currently provided by the background. 4056 // If we have padding specified via xml, record that here instead and use it. 4057 mLeftPaddingDefined = leftPaddingDefined; 4058 mRightPaddingDefined = rightPaddingDefined; 4059 4060 if (padding >= 0) { 4061 leftPadding = padding; 4062 topPadding = padding; 4063 rightPadding = padding; 4064 bottomPadding = padding; 4065 mUserPaddingLeftInitial = padding; 4066 mUserPaddingRightInitial = padding; 4067 } 4068 4069 if (isRtlCompatibilityMode()) { 4070 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4071 // left / right padding are used if defined (meaning here nothing to do). If they are not 4072 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4073 // start / end and resolve them as left / right (layout direction is not taken into account). 4074 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4075 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4076 // defined. 4077 if (!mLeftPaddingDefined && startPaddingDefined) { 4078 leftPadding = startPadding; 4079 } 4080 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4081 if (!mRightPaddingDefined && endPaddingDefined) { 4082 rightPadding = endPadding; 4083 } 4084 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4085 } else { 4086 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4087 // values defined. Otherwise, left /right values are used. 4088 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4089 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4090 // defined. 4091 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4092 4093 if (mLeftPaddingDefined && !hasRelativePadding) { 4094 mUserPaddingLeftInitial = leftPadding; 4095 } 4096 if (mRightPaddingDefined && !hasRelativePadding) { 4097 mUserPaddingRightInitial = rightPadding; 4098 } 4099 } 4100 4101 internalSetPadding( 4102 mUserPaddingLeftInitial, 4103 topPadding >= 0 ? topPadding : mPaddingTop, 4104 mUserPaddingRightInitial, 4105 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4106 4107 if (viewFlagMasks != 0) { 4108 setFlags(viewFlagValues, viewFlagMasks); 4109 } 4110 4111 if (initializeScrollbars) { 4112 initializeScrollbars(a); 4113 } 4114 4115 a.recycle(); 4116 4117 // Needs to be called after mViewFlags is set 4118 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4119 recomputePadding(); 4120 } 4121 4122 if (x != 0 || y != 0) { 4123 scrollTo(x, y); 4124 } 4125 4126 if (transformSet) { 4127 setTranslationX(tx); 4128 setTranslationY(ty); 4129 setTranslationZ(tz); 4130 setElevation(elevation); 4131 setRotation(rotation); 4132 setRotationX(rotationX); 4133 setRotationY(rotationY); 4134 setScaleX(sx); 4135 setScaleY(sy); 4136 } 4137 4138 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4139 setScrollContainer(true); 4140 } 4141 4142 computeOpaqueFlags(); 4143 } 4144 4145 /** 4146 * Non-public constructor for use in testing 4147 */ 4148 View() { 4149 mResources = null; 4150 mRenderNode = RenderNode.create(getClass().getName()); 4151 } 4152 4153 public String toString() { 4154 StringBuilder out = new StringBuilder(128); 4155 out.append(getClass().getName()); 4156 out.append('{'); 4157 out.append(Integer.toHexString(System.identityHashCode(this))); 4158 out.append(' '); 4159 switch (mViewFlags&VISIBILITY_MASK) { 4160 case VISIBLE: out.append('V'); break; 4161 case INVISIBLE: out.append('I'); break; 4162 case GONE: out.append('G'); break; 4163 default: out.append('.'); break; 4164 } 4165 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4166 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4167 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4168 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4169 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4170 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4171 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4172 out.append(' '); 4173 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4174 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4175 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4176 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4177 out.append('p'); 4178 } else { 4179 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4180 } 4181 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4182 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4183 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4184 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4185 out.append(' '); 4186 out.append(mLeft); 4187 out.append(','); 4188 out.append(mTop); 4189 out.append('-'); 4190 out.append(mRight); 4191 out.append(','); 4192 out.append(mBottom); 4193 final int id = getId(); 4194 if (id != NO_ID) { 4195 out.append(" #"); 4196 out.append(Integer.toHexString(id)); 4197 final Resources r = mResources; 4198 if (Resources.resourceHasPackage(id) && r != null) { 4199 try { 4200 String pkgname; 4201 switch (id&0xff000000) { 4202 case 0x7f000000: 4203 pkgname="app"; 4204 break; 4205 case 0x01000000: 4206 pkgname="android"; 4207 break; 4208 default: 4209 pkgname = r.getResourcePackageName(id); 4210 break; 4211 } 4212 String typename = r.getResourceTypeName(id); 4213 String entryname = r.getResourceEntryName(id); 4214 out.append(" "); 4215 out.append(pkgname); 4216 out.append(":"); 4217 out.append(typename); 4218 out.append("/"); 4219 out.append(entryname); 4220 } catch (Resources.NotFoundException e) { 4221 } 4222 } 4223 } 4224 out.append("}"); 4225 return out.toString(); 4226 } 4227 4228 /** 4229 * <p> 4230 * Initializes the fading edges from a given set of styled attributes. This 4231 * method should be called by subclasses that need fading edges and when an 4232 * instance of these subclasses is created programmatically rather than 4233 * being inflated from XML. This method is automatically called when the XML 4234 * is inflated. 4235 * </p> 4236 * 4237 * @param a the styled attributes set to initialize the fading edges from 4238 */ 4239 protected void initializeFadingEdge(TypedArray a) { 4240 initScrollCache(); 4241 4242 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4243 R.styleable.View_fadingEdgeLength, 4244 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4245 } 4246 4247 /** 4248 * Returns the size of the vertical faded edges used to indicate that more 4249 * content in this view is visible. 4250 * 4251 * @return The size in pixels of the vertical faded edge or 0 if vertical 4252 * faded edges are not enabled for this view. 4253 * @attr ref android.R.styleable#View_fadingEdgeLength 4254 */ 4255 public int getVerticalFadingEdgeLength() { 4256 if (isVerticalFadingEdgeEnabled()) { 4257 ScrollabilityCache cache = mScrollCache; 4258 if (cache != null) { 4259 return cache.fadingEdgeLength; 4260 } 4261 } 4262 return 0; 4263 } 4264 4265 /** 4266 * Set the size of the faded edge used to indicate that more content in this 4267 * view is available. Will not change whether the fading edge is enabled; use 4268 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4269 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4270 * for the vertical or horizontal fading edges. 4271 * 4272 * @param length The size in pixels of the faded edge used to indicate that more 4273 * content in this view is visible. 4274 */ 4275 public void setFadingEdgeLength(int length) { 4276 initScrollCache(); 4277 mScrollCache.fadingEdgeLength = length; 4278 } 4279 4280 /** 4281 * Returns the size of the horizontal faded edges used to indicate that more 4282 * content in this view is visible. 4283 * 4284 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4285 * faded edges are not enabled for this view. 4286 * @attr ref android.R.styleable#View_fadingEdgeLength 4287 */ 4288 public int getHorizontalFadingEdgeLength() { 4289 if (isHorizontalFadingEdgeEnabled()) { 4290 ScrollabilityCache cache = mScrollCache; 4291 if (cache != null) { 4292 return cache.fadingEdgeLength; 4293 } 4294 } 4295 return 0; 4296 } 4297 4298 /** 4299 * Returns the width of the vertical scrollbar. 4300 * 4301 * @return The width in pixels of the vertical scrollbar or 0 if there 4302 * is no vertical scrollbar. 4303 */ 4304 public int getVerticalScrollbarWidth() { 4305 ScrollabilityCache cache = mScrollCache; 4306 if (cache != null) { 4307 ScrollBarDrawable scrollBar = cache.scrollBar; 4308 if (scrollBar != null) { 4309 int size = scrollBar.getSize(true); 4310 if (size <= 0) { 4311 size = cache.scrollBarSize; 4312 } 4313 return size; 4314 } 4315 return 0; 4316 } 4317 return 0; 4318 } 4319 4320 /** 4321 * Returns the height of the horizontal scrollbar. 4322 * 4323 * @return The height in pixels of the horizontal scrollbar or 0 if 4324 * there is no horizontal scrollbar. 4325 */ 4326 protected int getHorizontalScrollbarHeight() { 4327 ScrollabilityCache cache = mScrollCache; 4328 if (cache != null) { 4329 ScrollBarDrawable scrollBar = cache.scrollBar; 4330 if (scrollBar != null) { 4331 int size = scrollBar.getSize(false); 4332 if (size <= 0) { 4333 size = cache.scrollBarSize; 4334 } 4335 return size; 4336 } 4337 return 0; 4338 } 4339 return 0; 4340 } 4341 4342 /** 4343 * <p> 4344 * Initializes the scrollbars from a given set of styled attributes. This 4345 * method should be called by subclasses that need scrollbars and when an 4346 * instance of these subclasses is created programmatically rather than 4347 * being inflated from XML. This method is automatically called when the XML 4348 * is inflated. 4349 * </p> 4350 * 4351 * @param a the styled attributes set to initialize the scrollbars from 4352 */ 4353 protected void initializeScrollbars(TypedArray a) { 4354 initScrollCache(); 4355 4356 final ScrollabilityCache scrollabilityCache = mScrollCache; 4357 4358 if (scrollabilityCache.scrollBar == null) { 4359 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4360 } 4361 4362 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4363 4364 if (!fadeScrollbars) { 4365 scrollabilityCache.state = ScrollabilityCache.ON; 4366 } 4367 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4368 4369 4370 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4371 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4372 .getScrollBarFadeDuration()); 4373 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4374 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4375 ViewConfiguration.getScrollDefaultDelay()); 4376 4377 4378 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4379 com.android.internal.R.styleable.View_scrollbarSize, 4380 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4381 4382 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4383 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4384 4385 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4386 if (thumb != null) { 4387 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4388 } 4389 4390 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4391 false); 4392 if (alwaysDraw) { 4393 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4394 } 4395 4396 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4397 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4398 4399 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4400 if (thumb != null) { 4401 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4402 } 4403 4404 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4405 false); 4406 if (alwaysDraw) { 4407 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4408 } 4409 4410 // Apply layout direction to the new Drawables if needed 4411 final int layoutDirection = getLayoutDirection(); 4412 if (track != null) { 4413 track.setLayoutDirection(layoutDirection); 4414 } 4415 if (thumb != null) { 4416 thumb.setLayoutDirection(layoutDirection); 4417 } 4418 4419 // Re-apply user/background padding so that scrollbar(s) get added 4420 resolvePadding(); 4421 } 4422 4423 /** 4424 * <p> 4425 * Initalizes the scrollability cache if necessary. 4426 * </p> 4427 */ 4428 private void initScrollCache() { 4429 if (mScrollCache == null) { 4430 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4431 } 4432 } 4433 4434 private ScrollabilityCache getScrollCache() { 4435 initScrollCache(); 4436 return mScrollCache; 4437 } 4438 4439 /** 4440 * Set the position of the vertical scroll bar. Should be one of 4441 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4442 * {@link #SCROLLBAR_POSITION_RIGHT}. 4443 * 4444 * @param position Where the vertical scroll bar should be positioned. 4445 */ 4446 public void setVerticalScrollbarPosition(int position) { 4447 if (mVerticalScrollbarPosition != position) { 4448 mVerticalScrollbarPosition = position; 4449 computeOpaqueFlags(); 4450 resolvePadding(); 4451 } 4452 } 4453 4454 /** 4455 * @return The position where the vertical scroll bar will show, if applicable. 4456 * @see #setVerticalScrollbarPosition(int) 4457 */ 4458 public int getVerticalScrollbarPosition() { 4459 return mVerticalScrollbarPosition; 4460 } 4461 4462 ListenerInfo getListenerInfo() { 4463 if (mListenerInfo != null) { 4464 return mListenerInfo; 4465 } 4466 mListenerInfo = new ListenerInfo(); 4467 return mListenerInfo; 4468 } 4469 4470 /** 4471 * Register a callback to be invoked when focus of this view changed. 4472 * 4473 * @param l The callback that will run. 4474 */ 4475 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4476 getListenerInfo().mOnFocusChangeListener = l; 4477 } 4478 4479 /** 4480 * Add a listener that will be called when the bounds of the view change due to 4481 * layout processing. 4482 * 4483 * @param listener The listener that will be called when layout bounds change. 4484 */ 4485 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4486 ListenerInfo li = getListenerInfo(); 4487 if (li.mOnLayoutChangeListeners == null) { 4488 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4489 } 4490 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4491 li.mOnLayoutChangeListeners.add(listener); 4492 } 4493 } 4494 4495 /** 4496 * Remove a listener for layout changes. 4497 * 4498 * @param listener The listener for layout bounds change. 4499 */ 4500 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4501 ListenerInfo li = mListenerInfo; 4502 if (li == null || li.mOnLayoutChangeListeners == null) { 4503 return; 4504 } 4505 li.mOnLayoutChangeListeners.remove(listener); 4506 } 4507 4508 /** 4509 * Add a listener for attach state changes. 4510 * 4511 * This listener will be called whenever this view is attached or detached 4512 * from a window. Remove the listener using 4513 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4514 * 4515 * @param listener Listener to attach 4516 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4517 */ 4518 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4519 ListenerInfo li = getListenerInfo(); 4520 if (li.mOnAttachStateChangeListeners == null) { 4521 li.mOnAttachStateChangeListeners 4522 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4523 } 4524 li.mOnAttachStateChangeListeners.add(listener); 4525 } 4526 4527 /** 4528 * Remove a listener for attach state changes. The listener will receive no further 4529 * notification of window attach/detach events. 4530 * 4531 * @param listener Listener to remove 4532 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4533 */ 4534 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4535 ListenerInfo li = mListenerInfo; 4536 if (li == null || li.mOnAttachStateChangeListeners == null) { 4537 return; 4538 } 4539 li.mOnAttachStateChangeListeners.remove(listener); 4540 } 4541 4542 /** 4543 * Returns the focus-change callback registered for this view. 4544 * 4545 * @return The callback, or null if one is not registered. 4546 */ 4547 public OnFocusChangeListener getOnFocusChangeListener() { 4548 ListenerInfo li = mListenerInfo; 4549 return li != null ? li.mOnFocusChangeListener : null; 4550 } 4551 4552 /** 4553 * Register a callback to be invoked when this view is clicked. If this view is not 4554 * clickable, it becomes clickable. 4555 * 4556 * @param l The callback that will run 4557 * 4558 * @see #setClickable(boolean) 4559 */ 4560 public void setOnClickListener(OnClickListener l) { 4561 if (!isClickable()) { 4562 setClickable(true); 4563 } 4564 getListenerInfo().mOnClickListener = l; 4565 } 4566 4567 /** 4568 * Return whether this view has an attached OnClickListener. Returns 4569 * true if there is a listener, false if there is none. 4570 */ 4571 public boolean hasOnClickListeners() { 4572 ListenerInfo li = mListenerInfo; 4573 return (li != null && li.mOnClickListener != null); 4574 } 4575 4576 /** 4577 * Register a callback to be invoked when this view is clicked and held. If this view is not 4578 * long clickable, it becomes long clickable. 4579 * 4580 * @param l The callback that will run 4581 * 4582 * @see #setLongClickable(boolean) 4583 */ 4584 public void setOnLongClickListener(OnLongClickListener l) { 4585 if (!isLongClickable()) { 4586 setLongClickable(true); 4587 } 4588 getListenerInfo().mOnLongClickListener = l; 4589 } 4590 4591 /** 4592 * Register a callback to be invoked when the context menu for this view is 4593 * being built. If this view is not long clickable, it becomes long clickable. 4594 * 4595 * @param l The callback that will run 4596 * 4597 */ 4598 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4599 if (!isLongClickable()) { 4600 setLongClickable(true); 4601 } 4602 getListenerInfo().mOnCreateContextMenuListener = l; 4603 } 4604 4605 /** 4606 * Call this view's OnClickListener, if it is defined. Performs all normal 4607 * actions associated with clicking: reporting accessibility event, playing 4608 * a sound, etc. 4609 * 4610 * @return True there was an assigned OnClickListener that was called, false 4611 * otherwise is returned. 4612 */ 4613 public boolean performClick() { 4614 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4615 4616 ListenerInfo li = mListenerInfo; 4617 if (li != null && li.mOnClickListener != null) { 4618 playSoundEffect(SoundEffectConstants.CLICK); 4619 li.mOnClickListener.onClick(this); 4620 return true; 4621 } 4622 4623 return false; 4624 } 4625 4626 /** 4627 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4628 * this only calls the listener, and does not do any associated clicking 4629 * actions like reporting an accessibility event. 4630 * 4631 * @return True there was an assigned OnClickListener that was called, false 4632 * otherwise is returned. 4633 */ 4634 public boolean callOnClick() { 4635 ListenerInfo li = mListenerInfo; 4636 if (li != null && li.mOnClickListener != null) { 4637 li.mOnClickListener.onClick(this); 4638 return true; 4639 } 4640 return false; 4641 } 4642 4643 /** 4644 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4645 * OnLongClickListener did not consume the event. 4646 * 4647 * @return True if one of the above receivers consumed the event, false otherwise. 4648 */ 4649 public boolean performLongClick() { 4650 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4651 4652 boolean handled = false; 4653 ListenerInfo li = mListenerInfo; 4654 if (li != null && li.mOnLongClickListener != null) { 4655 handled = li.mOnLongClickListener.onLongClick(View.this); 4656 } 4657 if (!handled) { 4658 handled = showContextMenu(); 4659 } 4660 if (handled) { 4661 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4662 } 4663 return handled; 4664 } 4665 4666 /** 4667 * Performs button-related actions during a touch down event. 4668 * 4669 * @param event The event. 4670 * @return True if the down was consumed. 4671 * 4672 * @hide 4673 */ 4674 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4675 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4676 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4677 return true; 4678 } 4679 } 4680 return false; 4681 } 4682 4683 /** 4684 * Bring up the context menu for this view. 4685 * 4686 * @return Whether a context menu was displayed. 4687 */ 4688 public boolean showContextMenu() { 4689 return getParent().showContextMenuForChild(this); 4690 } 4691 4692 /** 4693 * Bring up the context menu for this view, referring to the item under the specified point. 4694 * 4695 * @param x The referenced x coordinate. 4696 * @param y The referenced y coordinate. 4697 * @param metaState The keyboard modifiers that were pressed. 4698 * @return Whether a context menu was displayed. 4699 * 4700 * @hide 4701 */ 4702 public boolean showContextMenu(float x, float y, int metaState) { 4703 return showContextMenu(); 4704 } 4705 4706 /** 4707 * Start an action mode. 4708 * 4709 * @param callback Callback that will control the lifecycle of the action mode 4710 * @return The new action mode if it is started, null otherwise 4711 * 4712 * @see ActionMode 4713 */ 4714 public ActionMode startActionMode(ActionMode.Callback callback) { 4715 ViewParent parent = getParent(); 4716 if (parent == null) return null; 4717 return parent.startActionModeForChild(this, callback); 4718 } 4719 4720 /** 4721 * Register a callback to be invoked when a hardware key is pressed in this view. 4722 * Key presses in software input methods will generally not trigger the methods of 4723 * this listener. 4724 * @param l the key listener to attach to this view 4725 */ 4726 public void setOnKeyListener(OnKeyListener l) { 4727 getListenerInfo().mOnKeyListener = l; 4728 } 4729 4730 /** 4731 * Register a callback to be invoked when a touch event is sent to this view. 4732 * @param l the touch listener to attach to this view 4733 */ 4734 public void setOnTouchListener(OnTouchListener l) { 4735 getListenerInfo().mOnTouchListener = l; 4736 } 4737 4738 /** 4739 * Register a callback to be invoked when a generic motion event is sent to this view. 4740 * @param l the generic motion listener to attach to this view 4741 */ 4742 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4743 getListenerInfo().mOnGenericMotionListener = l; 4744 } 4745 4746 /** 4747 * Register a callback to be invoked when a hover event is sent to this view. 4748 * @param l the hover listener to attach to this view 4749 */ 4750 public void setOnHoverListener(OnHoverListener l) { 4751 getListenerInfo().mOnHoverListener = l; 4752 } 4753 4754 /** 4755 * Register a drag event listener callback object for this View. The parameter is 4756 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4757 * View, the system calls the 4758 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4759 * @param l An implementation of {@link android.view.View.OnDragListener}. 4760 */ 4761 public void setOnDragListener(OnDragListener l) { 4762 getListenerInfo().mOnDragListener = l; 4763 } 4764 4765 /** 4766 * Give this view focus. This will cause 4767 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4768 * 4769 * Note: this does not check whether this {@link View} should get focus, it just 4770 * gives it focus no matter what. It should only be called internally by framework 4771 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4772 * 4773 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4774 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4775 * focus moved when requestFocus() is called. It may not always 4776 * apply, in which case use the default View.FOCUS_DOWN. 4777 * @param previouslyFocusedRect The rectangle of the view that had focus 4778 * prior in this View's coordinate system. 4779 */ 4780 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4781 if (DBG) { 4782 System.out.println(this + " requestFocus()"); 4783 } 4784 4785 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4786 mPrivateFlags |= PFLAG_FOCUSED; 4787 4788 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4789 4790 if (mParent != null) { 4791 mParent.requestChildFocus(this, this); 4792 } 4793 4794 if (mAttachInfo != null) { 4795 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4796 } 4797 4798 onFocusChanged(true, direction, previouslyFocusedRect); 4799 manageFocusHotspot(true, oldFocus); 4800 refreshDrawableState(); 4801 } 4802 } 4803 4804 /** 4805 * Forwards focus information to the background drawable, if necessary. When 4806 * the view is gaining focus, <code>v</code> is the previous focus holder. 4807 * When the view is losing focus, <code>v</code> is the next focus holder. 4808 * 4809 * @param focused whether this view is focused 4810 * @param v previous or the next focus holder, or null if none 4811 */ 4812 private void manageFocusHotspot(boolean focused, View v) { 4813 final Rect r = new Rect(); 4814 if (!focused && v != null && mAttachInfo != null) { 4815 v.getBoundsOnScreen(r); 4816 final int[] location = mAttachInfo.mTmpLocation; 4817 getLocationOnScreen(location); 4818 r.offset(-location[0], -location[1]); 4819 } else { 4820 r.set(0, 0, mRight - mLeft, mBottom - mTop); 4821 } 4822 4823 final float x = r.exactCenterX(); 4824 final float y = r.exactCenterY(); 4825 setDrawableHotspot(x, y); 4826 } 4827 4828 /** 4829 * Sets the hotspot position for this View's drawables. 4830 * 4831 * @param x hotspot x coordinate 4832 * @param y hotspot y coordinate 4833 * @hide 4834 */ 4835 protected void setDrawableHotspot(float x, float y) { 4836 if (mBackground != null) { 4837 mBackground.setHotspot(x, y); 4838 } 4839 } 4840 4841 /** 4842 * Request that a rectangle of this view be visible on the screen, 4843 * scrolling if necessary just enough. 4844 * 4845 * <p>A View should call this if it maintains some notion of which part 4846 * of its content is interesting. For example, a text editing view 4847 * should call this when its cursor moves. 4848 * 4849 * @param rectangle The rectangle. 4850 * @return Whether any parent scrolled. 4851 */ 4852 public boolean requestRectangleOnScreen(Rect rectangle) { 4853 return requestRectangleOnScreen(rectangle, false); 4854 } 4855 4856 /** 4857 * Request that a rectangle of this view be visible on the screen, 4858 * scrolling if necessary just enough. 4859 * 4860 * <p>A View should call this if it maintains some notion of which part 4861 * of its content is interesting. For example, a text editing view 4862 * should call this when its cursor moves. 4863 * 4864 * <p>When <code>immediate</code> is set to true, scrolling will not be 4865 * animated. 4866 * 4867 * @param rectangle The rectangle. 4868 * @param immediate True to forbid animated scrolling, false otherwise 4869 * @return Whether any parent scrolled. 4870 */ 4871 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4872 if (mParent == null) { 4873 return false; 4874 } 4875 4876 View child = this; 4877 4878 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4879 position.set(rectangle); 4880 4881 ViewParent parent = mParent; 4882 boolean scrolled = false; 4883 while (parent != null) { 4884 rectangle.set((int) position.left, (int) position.top, 4885 (int) position.right, (int) position.bottom); 4886 4887 scrolled |= parent.requestChildRectangleOnScreen(child, 4888 rectangle, immediate); 4889 4890 if (!child.hasIdentityMatrix()) { 4891 child.getMatrix().mapRect(position); 4892 } 4893 4894 position.offset(child.mLeft, child.mTop); 4895 4896 if (!(parent instanceof View)) { 4897 break; 4898 } 4899 4900 View parentView = (View) parent; 4901 4902 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4903 4904 child = parentView; 4905 parent = child.getParent(); 4906 } 4907 4908 return scrolled; 4909 } 4910 4911 /** 4912 * Called when this view wants to give up focus. If focus is cleared 4913 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4914 * <p> 4915 * <strong>Note:</strong> When a View clears focus the framework is trying 4916 * to give focus to the first focusable View from the top. Hence, if this 4917 * View is the first from the top that can take focus, then all callbacks 4918 * related to clearing focus will be invoked after wich the framework will 4919 * give focus to this view. 4920 * </p> 4921 */ 4922 public void clearFocus() { 4923 if (DBG) { 4924 System.out.println(this + " clearFocus()"); 4925 } 4926 4927 clearFocusInternal(null, true, true); 4928 } 4929 4930 /** 4931 * Clears focus from the view, optionally propagating the change up through 4932 * the parent hierarchy and requesting that the root view place new focus. 4933 * 4934 * @param propagate whether to propagate the change up through the parent 4935 * hierarchy 4936 * @param refocus when propagate is true, specifies whether to request the 4937 * root view place new focus 4938 */ 4939 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4940 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4941 mPrivateFlags &= ~PFLAG_FOCUSED; 4942 4943 if (propagate && mParent != null) { 4944 mParent.clearChildFocus(this); 4945 } 4946 4947 onFocusChanged(false, 0, null); 4948 4949 manageFocusHotspot(false, focused); 4950 refreshDrawableState(); 4951 4952 if (propagate && (!refocus || !rootViewRequestFocus())) { 4953 notifyGlobalFocusCleared(this); 4954 } 4955 } 4956 } 4957 4958 void notifyGlobalFocusCleared(View oldFocus) { 4959 if (oldFocus != null && mAttachInfo != null) { 4960 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4961 } 4962 } 4963 4964 boolean rootViewRequestFocus() { 4965 final View root = getRootView(); 4966 return root != null && root.requestFocus(); 4967 } 4968 4969 /** 4970 * Called internally by the view system when a new view is getting focus. 4971 * This is what clears the old focus. 4972 * <p> 4973 * <b>NOTE:</b> The parent view's focused child must be updated manually 4974 * after calling this method. Otherwise, the view hierarchy may be left in 4975 * an inconstent state. 4976 */ 4977 void unFocus(View focused) { 4978 if (DBG) { 4979 System.out.println(this + " unFocus()"); 4980 } 4981 4982 clearFocusInternal(focused, false, false); 4983 } 4984 4985 /** 4986 * Returns true if this view has focus iteself, or is the ancestor of the 4987 * view that has focus. 4988 * 4989 * @return True if this view has or contains focus, false otherwise. 4990 */ 4991 @ViewDebug.ExportedProperty(category = "focus") 4992 public boolean hasFocus() { 4993 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4994 } 4995 4996 /** 4997 * Returns true if this view is focusable or if it contains a reachable View 4998 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4999 * is a View whose parents do not block descendants focus. 5000 * 5001 * Only {@link #VISIBLE} views are considered focusable. 5002 * 5003 * @return True if the view is focusable or if the view contains a focusable 5004 * View, false otherwise. 5005 * 5006 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5007 */ 5008 public boolean hasFocusable() { 5009 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5010 } 5011 5012 /** 5013 * Called by the view system when the focus state of this view changes. 5014 * When the focus change event is caused by directional navigation, direction 5015 * and previouslyFocusedRect provide insight into where the focus is coming from. 5016 * When overriding, be sure to call up through to the super class so that 5017 * the standard focus handling will occur. 5018 * 5019 * @param gainFocus True if the View has focus; false otherwise. 5020 * @param direction The direction focus has moved when requestFocus() 5021 * is called to give this view focus. Values are 5022 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5023 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5024 * It may not always apply, in which case use the default. 5025 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5026 * system, of the previously focused view. If applicable, this will be 5027 * passed in as finer grained information about where the focus is coming 5028 * from (in addition to direction). Will be <code>null</code> otherwise. 5029 */ 5030 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5031 @Nullable Rect previouslyFocusedRect) { 5032 if (gainFocus) { 5033 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5034 } else { 5035 notifyViewAccessibilityStateChangedIfNeeded( 5036 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5037 } 5038 5039 InputMethodManager imm = InputMethodManager.peekInstance(); 5040 if (!gainFocus) { 5041 if (isPressed()) { 5042 setPressed(false); 5043 } 5044 if (imm != null && mAttachInfo != null 5045 && mAttachInfo.mHasWindowFocus) { 5046 imm.focusOut(this); 5047 } 5048 onFocusLost(); 5049 } else if (imm != null && mAttachInfo != null 5050 && mAttachInfo.mHasWindowFocus) { 5051 imm.focusIn(this); 5052 } 5053 5054 invalidate(true); 5055 ListenerInfo li = mListenerInfo; 5056 if (li != null && li.mOnFocusChangeListener != null) { 5057 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5058 } 5059 5060 if (mAttachInfo != null) { 5061 mAttachInfo.mKeyDispatchState.reset(this); 5062 } 5063 } 5064 5065 /** 5066 * Sends an accessibility event of the given type. If accessibility is 5067 * not enabled this method has no effect. The default implementation calls 5068 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5069 * to populate information about the event source (this View), then calls 5070 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5071 * populate the text content of the event source including its descendants, 5072 * and last calls 5073 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5074 * on its parent to resuest sending of the event to interested parties. 5075 * <p> 5076 * If an {@link AccessibilityDelegate} has been specified via calling 5077 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5078 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5079 * responsible for handling this call. 5080 * </p> 5081 * 5082 * @param eventType The type of the event to send, as defined by several types from 5083 * {@link android.view.accessibility.AccessibilityEvent}, such as 5084 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5085 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5086 * 5087 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5088 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5089 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5090 * @see AccessibilityDelegate 5091 */ 5092 public void sendAccessibilityEvent(int eventType) { 5093 if (mAccessibilityDelegate != null) { 5094 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5095 } else { 5096 sendAccessibilityEventInternal(eventType); 5097 } 5098 } 5099 5100 /** 5101 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5102 * {@link AccessibilityEvent} to make an announcement which is related to some 5103 * sort of a context change for which none of the events representing UI transitions 5104 * is a good fit. For example, announcing a new page in a book. If accessibility 5105 * is not enabled this method does nothing. 5106 * 5107 * @param text The announcement text. 5108 */ 5109 public void announceForAccessibility(CharSequence text) { 5110 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5111 AccessibilityEvent event = AccessibilityEvent.obtain( 5112 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5113 onInitializeAccessibilityEvent(event); 5114 event.getText().add(text); 5115 event.setContentDescription(null); 5116 mParent.requestSendAccessibilityEvent(this, event); 5117 } 5118 } 5119 5120 /** 5121 * @see #sendAccessibilityEvent(int) 5122 * 5123 * Note: Called from the default {@link AccessibilityDelegate}. 5124 */ 5125 void sendAccessibilityEventInternal(int eventType) { 5126 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5127 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5128 } 5129 } 5130 5131 /** 5132 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5133 * takes as an argument an empty {@link AccessibilityEvent} and does not 5134 * perform a check whether accessibility is enabled. 5135 * <p> 5136 * If an {@link AccessibilityDelegate} has been specified via calling 5137 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5138 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5139 * is responsible for handling this call. 5140 * </p> 5141 * 5142 * @param event The event to send. 5143 * 5144 * @see #sendAccessibilityEvent(int) 5145 */ 5146 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5147 if (mAccessibilityDelegate != null) { 5148 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5149 } else { 5150 sendAccessibilityEventUncheckedInternal(event); 5151 } 5152 } 5153 5154 /** 5155 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5156 * 5157 * Note: Called from the default {@link AccessibilityDelegate}. 5158 */ 5159 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5160 if (!isShown()) { 5161 return; 5162 } 5163 onInitializeAccessibilityEvent(event); 5164 // Only a subset of accessibility events populates text content. 5165 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5166 dispatchPopulateAccessibilityEvent(event); 5167 } 5168 // In the beginning we called #isShown(), so we know that getParent() is not null. 5169 getParent().requestSendAccessibilityEvent(this, event); 5170 } 5171 5172 /** 5173 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5174 * to its children for adding their text content to the event. Note that the 5175 * event text is populated in a separate dispatch path since we add to the 5176 * event not only the text of the source but also the text of all its descendants. 5177 * A typical implementation will call 5178 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5179 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5180 * on each child. Override this method if custom population of the event text 5181 * content is required. 5182 * <p> 5183 * If an {@link AccessibilityDelegate} has been specified via calling 5184 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5185 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5186 * is responsible for handling this call. 5187 * </p> 5188 * <p> 5189 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5190 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5191 * </p> 5192 * 5193 * @param event The event. 5194 * 5195 * @return True if the event population was completed. 5196 */ 5197 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5198 if (mAccessibilityDelegate != null) { 5199 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5200 } else { 5201 return dispatchPopulateAccessibilityEventInternal(event); 5202 } 5203 } 5204 5205 /** 5206 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5207 * 5208 * Note: Called from the default {@link AccessibilityDelegate}. 5209 */ 5210 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5211 onPopulateAccessibilityEvent(event); 5212 return false; 5213 } 5214 5215 /** 5216 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5217 * giving a chance to this View to populate the accessibility event with its 5218 * text content. While this method is free to modify event 5219 * attributes other than text content, doing so should normally be performed in 5220 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5221 * <p> 5222 * Example: Adding formatted date string to an accessibility event in addition 5223 * to the text added by the super implementation: 5224 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5225 * super.onPopulateAccessibilityEvent(event); 5226 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5227 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5228 * mCurrentDate.getTimeInMillis(), flags); 5229 * event.getText().add(selectedDateUtterance); 5230 * }</pre> 5231 * <p> 5232 * If an {@link AccessibilityDelegate} has been specified via calling 5233 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5234 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5235 * is responsible for handling this call. 5236 * </p> 5237 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5238 * information to the event, in case the default implementation has basic information to add. 5239 * </p> 5240 * 5241 * @param event The accessibility event which to populate. 5242 * 5243 * @see #sendAccessibilityEvent(int) 5244 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5245 */ 5246 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5247 if (mAccessibilityDelegate != null) { 5248 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5249 } else { 5250 onPopulateAccessibilityEventInternal(event); 5251 } 5252 } 5253 5254 /** 5255 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5256 * 5257 * Note: Called from the default {@link AccessibilityDelegate}. 5258 */ 5259 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5260 } 5261 5262 /** 5263 * Initializes an {@link AccessibilityEvent} with information about 5264 * this View which is the event source. In other words, the source of 5265 * an accessibility event is the view whose state change triggered firing 5266 * the event. 5267 * <p> 5268 * Example: Setting the password property of an event in addition 5269 * to properties set by the super implementation: 5270 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5271 * super.onInitializeAccessibilityEvent(event); 5272 * event.setPassword(true); 5273 * }</pre> 5274 * <p> 5275 * If an {@link AccessibilityDelegate} has been specified via calling 5276 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5277 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5278 * is responsible for handling this call. 5279 * </p> 5280 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5281 * information to the event, in case the default implementation has basic information to add. 5282 * </p> 5283 * @param event The event to initialize. 5284 * 5285 * @see #sendAccessibilityEvent(int) 5286 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5287 */ 5288 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5289 if (mAccessibilityDelegate != null) { 5290 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5291 } else { 5292 onInitializeAccessibilityEventInternal(event); 5293 } 5294 } 5295 5296 /** 5297 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5298 * 5299 * Note: Called from the default {@link AccessibilityDelegate}. 5300 */ 5301 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5302 event.setSource(this); 5303 event.setClassName(View.class.getName()); 5304 event.setPackageName(getContext().getPackageName()); 5305 event.setEnabled(isEnabled()); 5306 event.setContentDescription(mContentDescription); 5307 5308 switch (event.getEventType()) { 5309 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5310 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5311 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5312 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5313 event.setItemCount(focusablesTempList.size()); 5314 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5315 if (mAttachInfo != null) { 5316 focusablesTempList.clear(); 5317 } 5318 } break; 5319 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5320 CharSequence text = getIterableTextForAccessibility(); 5321 if (text != null && text.length() > 0) { 5322 event.setFromIndex(getAccessibilitySelectionStart()); 5323 event.setToIndex(getAccessibilitySelectionEnd()); 5324 event.setItemCount(text.length()); 5325 } 5326 } break; 5327 } 5328 } 5329 5330 /** 5331 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5332 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5333 * This method is responsible for obtaining an accessibility node info from a 5334 * pool of reusable instances and calling 5335 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5336 * initialize the former. 5337 * <p> 5338 * Note: The client is responsible for recycling the obtained instance by calling 5339 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5340 * </p> 5341 * 5342 * @return A populated {@link AccessibilityNodeInfo}. 5343 * 5344 * @see AccessibilityNodeInfo 5345 */ 5346 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5347 if (mAccessibilityDelegate != null) { 5348 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5349 } else { 5350 return createAccessibilityNodeInfoInternal(); 5351 } 5352 } 5353 5354 /** 5355 * @see #createAccessibilityNodeInfo() 5356 */ 5357 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5358 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5359 if (provider != null) { 5360 return provider.createAccessibilityNodeInfo(View.NO_ID); 5361 } else { 5362 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5363 onInitializeAccessibilityNodeInfo(info); 5364 return info; 5365 } 5366 } 5367 5368 /** 5369 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5370 * The base implementation sets: 5371 * <ul> 5372 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5373 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5374 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5375 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5376 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5377 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5378 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5379 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5380 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5381 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5382 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5383 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5384 * </ul> 5385 * <p> 5386 * Subclasses should override this method, call the super implementation, 5387 * and set additional attributes. 5388 * </p> 5389 * <p> 5390 * If an {@link AccessibilityDelegate} has been specified via calling 5391 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5392 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5393 * is responsible for handling this call. 5394 * </p> 5395 * 5396 * @param info The instance to initialize. 5397 */ 5398 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5399 if (mAccessibilityDelegate != null) { 5400 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5401 } else { 5402 onInitializeAccessibilityNodeInfoInternal(info); 5403 } 5404 } 5405 5406 /** 5407 * Gets the location of this view in screen coordintates. 5408 * 5409 * @param outRect The output location 5410 * @hide 5411 */ 5412 public void getBoundsOnScreen(Rect outRect) { 5413 if (mAttachInfo == null) { 5414 return; 5415 } 5416 5417 RectF position = mAttachInfo.mTmpTransformRect; 5418 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5419 5420 if (!hasIdentityMatrix()) { 5421 getMatrix().mapRect(position); 5422 } 5423 5424 position.offset(mLeft, mTop); 5425 5426 ViewParent parent = mParent; 5427 while (parent instanceof View) { 5428 View parentView = (View) parent; 5429 5430 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5431 5432 if (!parentView.hasIdentityMatrix()) { 5433 parentView.getMatrix().mapRect(position); 5434 } 5435 5436 position.offset(parentView.mLeft, parentView.mTop); 5437 5438 parent = parentView.mParent; 5439 } 5440 5441 if (parent instanceof ViewRootImpl) { 5442 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5443 position.offset(0, -viewRootImpl.mCurScrollY); 5444 } 5445 5446 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5447 5448 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5449 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5450 } 5451 5452 /** 5453 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5454 * 5455 * Note: Called from the default {@link AccessibilityDelegate}. 5456 */ 5457 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5458 Rect bounds = mAttachInfo.mTmpInvalRect; 5459 5460 getDrawingRect(bounds); 5461 info.setBoundsInParent(bounds); 5462 5463 getBoundsOnScreen(bounds); 5464 info.setBoundsInScreen(bounds); 5465 5466 ViewParent parent = getParentForAccessibility(); 5467 if (parent instanceof View) { 5468 info.setParent((View) parent); 5469 } 5470 5471 if (mID != View.NO_ID) { 5472 View rootView = getRootView(); 5473 if (rootView == null) { 5474 rootView = this; 5475 } 5476 View label = rootView.findLabelForView(this, mID); 5477 if (label != null) { 5478 info.setLabeledBy(label); 5479 } 5480 5481 if ((mAttachInfo.mAccessibilityFetchFlags 5482 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5483 && Resources.resourceHasPackage(mID)) { 5484 try { 5485 String viewId = getResources().getResourceName(mID); 5486 info.setViewIdResourceName(viewId); 5487 } catch (Resources.NotFoundException nfe) { 5488 /* ignore */ 5489 } 5490 } 5491 } 5492 5493 if (mLabelForId != View.NO_ID) { 5494 View rootView = getRootView(); 5495 if (rootView == null) { 5496 rootView = this; 5497 } 5498 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5499 if (labeled != null) { 5500 info.setLabelFor(labeled); 5501 } 5502 } 5503 5504 info.setVisibleToUser(isVisibleToUser()); 5505 5506 info.setPackageName(mContext.getPackageName()); 5507 info.setClassName(View.class.getName()); 5508 info.setContentDescription(getContentDescription()); 5509 5510 info.setEnabled(isEnabled()); 5511 info.setClickable(isClickable()); 5512 info.setFocusable(isFocusable()); 5513 info.setFocused(isFocused()); 5514 info.setAccessibilityFocused(isAccessibilityFocused()); 5515 info.setSelected(isSelected()); 5516 info.setLongClickable(isLongClickable()); 5517 info.setLiveRegion(getAccessibilityLiveRegion()); 5518 5519 // TODO: These make sense only if we are in an AdapterView but all 5520 // views can be selected. Maybe from accessibility perspective 5521 // we should report as selectable view in an AdapterView. 5522 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5523 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5524 5525 if (isFocusable()) { 5526 if (isFocused()) { 5527 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5528 } else { 5529 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5530 } 5531 } 5532 5533 if (!isAccessibilityFocused()) { 5534 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5535 } else { 5536 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5537 } 5538 5539 if (isClickable() && isEnabled()) { 5540 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5541 } 5542 5543 if (isLongClickable() && isEnabled()) { 5544 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5545 } 5546 5547 CharSequence text = getIterableTextForAccessibility(); 5548 if (text != null && text.length() > 0) { 5549 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5550 5551 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5552 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5553 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5554 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5555 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5556 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5557 } 5558 } 5559 5560 private View findLabelForView(View view, int labeledId) { 5561 if (mMatchLabelForPredicate == null) { 5562 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5563 } 5564 mMatchLabelForPredicate.mLabeledId = labeledId; 5565 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5566 } 5567 5568 /** 5569 * Computes whether this view is visible to the user. Such a view is 5570 * attached, visible, all its predecessors are visible, it is not clipped 5571 * entirely by its predecessors, and has an alpha greater than zero. 5572 * 5573 * @return Whether the view is visible on the screen. 5574 * 5575 * @hide 5576 */ 5577 protected boolean isVisibleToUser() { 5578 return isVisibleToUser(null); 5579 } 5580 5581 /** 5582 * Computes whether the given portion of this view is visible to the user. 5583 * Such a view is attached, visible, all its predecessors are visible, 5584 * has an alpha greater than zero, and the specified portion is not 5585 * clipped entirely by its predecessors. 5586 * 5587 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5588 * <code>null</code>, and the entire view will be tested in this case. 5589 * When <code>true</code> is returned by the function, the actual visible 5590 * region will be stored in this parameter; that is, if boundInView is fully 5591 * contained within the view, no modification will be made, otherwise regions 5592 * outside of the visible area of the view will be clipped. 5593 * 5594 * @return Whether the specified portion of the view is visible on the screen. 5595 * 5596 * @hide 5597 */ 5598 protected boolean isVisibleToUser(Rect boundInView) { 5599 if (mAttachInfo != null) { 5600 // Attached to invisible window means this view is not visible. 5601 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5602 return false; 5603 } 5604 // An invisible predecessor or one with alpha zero means 5605 // that this view is not visible to the user. 5606 Object current = this; 5607 while (current instanceof View) { 5608 View view = (View) current; 5609 // We have attach info so this view is attached and there is no 5610 // need to check whether we reach to ViewRootImpl on the way up. 5611 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5612 view.getVisibility() != VISIBLE) { 5613 return false; 5614 } 5615 current = view.mParent; 5616 } 5617 // Check if the view is entirely covered by its predecessors. 5618 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5619 Point offset = mAttachInfo.mPoint; 5620 if (!getGlobalVisibleRect(visibleRect, offset)) { 5621 return false; 5622 } 5623 // Check if the visible portion intersects the rectangle of interest. 5624 if (boundInView != null) { 5625 visibleRect.offset(-offset.x, -offset.y); 5626 return boundInView.intersect(visibleRect); 5627 } 5628 return true; 5629 } 5630 return false; 5631 } 5632 5633 /** 5634 * Returns the delegate for implementing accessibility support via 5635 * composition. For more details see {@link AccessibilityDelegate}. 5636 * 5637 * @return The delegate, or null if none set. 5638 * 5639 * @hide 5640 */ 5641 public AccessibilityDelegate getAccessibilityDelegate() { 5642 return mAccessibilityDelegate; 5643 } 5644 5645 /** 5646 * Sets a delegate for implementing accessibility support via composition as 5647 * opposed to inheritance. The delegate's primary use is for implementing 5648 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5649 * 5650 * @param delegate The delegate instance. 5651 * 5652 * @see AccessibilityDelegate 5653 */ 5654 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5655 mAccessibilityDelegate = delegate; 5656 } 5657 5658 /** 5659 * Gets the provider for managing a virtual view hierarchy rooted at this View 5660 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5661 * that explore the window content. 5662 * <p> 5663 * If this method returns an instance, this instance is responsible for managing 5664 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5665 * View including the one representing the View itself. Similarly the returned 5666 * instance is responsible for performing accessibility actions on any virtual 5667 * view or the root view itself. 5668 * </p> 5669 * <p> 5670 * If an {@link AccessibilityDelegate} has been specified via calling 5671 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5672 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5673 * is responsible for handling this call. 5674 * </p> 5675 * 5676 * @return The provider. 5677 * 5678 * @see AccessibilityNodeProvider 5679 */ 5680 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5681 if (mAccessibilityDelegate != null) { 5682 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5683 } else { 5684 return null; 5685 } 5686 } 5687 5688 /** 5689 * Gets the unique identifier of this view on the screen for accessibility purposes. 5690 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5691 * 5692 * @return The view accessibility id. 5693 * 5694 * @hide 5695 */ 5696 public int getAccessibilityViewId() { 5697 if (mAccessibilityViewId == NO_ID) { 5698 mAccessibilityViewId = sNextAccessibilityViewId++; 5699 } 5700 return mAccessibilityViewId; 5701 } 5702 5703 /** 5704 * Gets the unique identifier of the window in which this View reseides. 5705 * 5706 * @return The window accessibility id. 5707 * 5708 * @hide 5709 */ 5710 public int getAccessibilityWindowId() { 5711 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5712 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5713 } 5714 5715 /** 5716 * Gets the {@link View} description. It briefly describes the view and is 5717 * primarily used for accessibility support. Set this property to enable 5718 * better accessibility support for your application. This is especially 5719 * true for views that do not have textual representation (For example, 5720 * ImageButton). 5721 * 5722 * @return The content description. 5723 * 5724 * @attr ref android.R.styleable#View_contentDescription 5725 */ 5726 @ViewDebug.ExportedProperty(category = "accessibility") 5727 public CharSequence getContentDescription() { 5728 return mContentDescription; 5729 } 5730 5731 /** 5732 * Sets the {@link View} description. It briefly describes the view and is 5733 * primarily used for accessibility support. Set this property to enable 5734 * better accessibility support for your application. This is especially 5735 * true for views that do not have textual representation (For example, 5736 * ImageButton). 5737 * 5738 * @param contentDescription The content description. 5739 * 5740 * @attr ref android.R.styleable#View_contentDescription 5741 */ 5742 @RemotableViewMethod 5743 public void setContentDescription(CharSequence contentDescription) { 5744 if (mContentDescription == null) { 5745 if (contentDescription == null) { 5746 return; 5747 } 5748 } else if (mContentDescription.equals(contentDescription)) { 5749 return; 5750 } 5751 mContentDescription = contentDescription; 5752 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5753 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5754 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5755 notifySubtreeAccessibilityStateChangedIfNeeded(); 5756 } else { 5757 notifyViewAccessibilityStateChangedIfNeeded( 5758 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5759 } 5760 } 5761 5762 /** 5763 * Gets the id of a view for which this view serves as a label for 5764 * accessibility purposes. 5765 * 5766 * @return The labeled view id. 5767 */ 5768 @ViewDebug.ExportedProperty(category = "accessibility") 5769 public int getLabelFor() { 5770 return mLabelForId; 5771 } 5772 5773 /** 5774 * Sets the id of a view for which this view serves as a label for 5775 * accessibility purposes. 5776 * 5777 * @param id The labeled view id. 5778 */ 5779 @RemotableViewMethod 5780 public void setLabelFor(int id) { 5781 mLabelForId = id; 5782 if (mLabelForId != View.NO_ID 5783 && mID == View.NO_ID) { 5784 mID = generateViewId(); 5785 } 5786 } 5787 5788 /** 5789 * Invoked whenever this view loses focus, either by losing window focus or by losing 5790 * focus within its window. This method can be used to clear any state tied to the 5791 * focus. For instance, if a button is held pressed with the trackball and the window 5792 * loses focus, this method can be used to cancel the press. 5793 * 5794 * Subclasses of View overriding this method should always call super.onFocusLost(). 5795 * 5796 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5797 * @see #onWindowFocusChanged(boolean) 5798 * 5799 * @hide pending API council approval 5800 */ 5801 protected void onFocusLost() { 5802 resetPressedState(); 5803 } 5804 5805 private void resetPressedState() { 5806 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5807 return; 5808 } 5809 5810 if (isPressed()) { 5811 setPressed(false); 5812 5813 if (!mHasPerformedLongPress) { 5814 removeLongPressCallback(); 5815 } 5816 } 5817 } 5818 5819 /** 5820 * Returns true if this view has focus 5821 * 5822 * @return True if this view has focus, false otherwise. 5823 */ 5824 @ViewDebug.ExportedProperty(category = "focus") 5825 public boolean isFocused() { 5826 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5827 } 5828 5829 /** 5830 * Find the view in the hierarchy rooted at this view that currently has 5831 * focus. 5832 * 5833 * @return The view that currently has focus, or null if no focused view can 5834 * be found. 5835 */ 5836 public View findFocus() { 5837 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5838 } 5839 5840 /** 5841 * Indicates whether this view is one of the set of scrollable containers in 5842 * its window. 5843 * 5844 * @return whether this view is one of the set of scrollable containers in 5845 * its window 5846 * 5847 * @attr ref android.R.styleable#View_isScrollContainer 5848 */ 5849 public boolean isScrollContainer() { 5850 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5851 } 5852 5853 /** 5854 * Change whether this view is one of the set of scrollable containers in 5855 * its window. This will be used to determine whether the window can 5856 * resize or must pan when a soft input area is open -- scrollable 5857 * containers allow the window to use resize mode since the container 5858 * will appropriately shrink. 5859 * 5860 * @attr ref android.R.styleable#View_isScrollContainer 5861 */ 5862 public void setScrollContainer(boolean isScrollContainer) { 5863 if (isScrollContainer) { 5864 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5865 mAttachInfo.mScrollContainers.add(this); 5866 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5867 } 5868 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5869 } else { 5870 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5871 mAttachInfo.mScrollContainers.remove(this); 5872 } 5873 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5874 } 5875 } 5876 5877 /** 5878 * Returns the quality of the drawing cache. 5879 * 5880 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5881 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5882 * 5883 * @see #setDrawingCacheQuality(int) 5884 * @see #setDrawingCacheEnabled(boolean) 5885 * @see #isDrawingCacheEnabled() 5886 * 5887 * @attr ref android.R.styleable#View_drawingCacheQuality 5888 */ 5889 @DrawingCacheQuality 5890 public int getDrawingCacheQuality() { 5891 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5892 } 5893 5894 /** 5895 * Set the drawing cache quality of this view. This value is used only when the 5896 * drawing cache is enabled 5897 * 5898 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5899 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5900 * 5901 * @see #getDrawingCacheQuality() 5902 * @see #setDrawingCacheEnabled(boolean) 5903 * @see #isDrawingCacheEnabled() 5904 * 5905 * @attr ref android.R.styleable#View_drawingCacheQuality 5906 */ 5907 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5908 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5909 } 5910 5911 /** 5912 * Returns whether the screen should remain on, corresponding to the current 5913 * value of {@link #KEEP_SCREEN_ON}. 5914 * 5915 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5916 * 5917 * @see #setKeepScreenOn(boolean) 5918 * 5919 * @attr ref android.R.styleable#View_keepScreenOn 5920 */ 5921 public boolean getKeepScreenOn() { 5922 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5923 } 5924 5925 /** 5926 * Controls whether the screen should remain on, modifying the 5927 * value of {@link #KEEP_SCREEN_ON}. 5928 * 5929 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5930 * 5931 * @see #getKeepScreenOn() 5932 * 5933 * @attr ref android.R.styleable#View_keepScreenOn 5934 */ 5935 public void setKeepScreenOn(boolean keepScreenOn) { 5936 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5937 } 5938 5939 /** 5940 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5941 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5942 * 5943 * @attr ref android.R.styleable#View_nextFocusLeft 5944 */ 5945 public int getNextFocusLeftId() { 5946 return mNextFocusLeftId; 5947 } 5948 5949 /** 5950 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5951 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5952 * decide automatically. 5953 * 5954 * @attr ref android.R.styleable#View_nextFocusLeft 5955 */ 5956 public void setNextFocusLeftId(int nextFocusLeftId) { 5957 mNextFocusLeftId = nextFocusLeftId; 5958 } 5959 5960 /** 5961 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5962 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5963 * 5964 * @attr ref android.R.styleable#View_nextFocusRight 5965 */ 5966 public int getNextFocusRightId() { 5967 return mNextFocusRightId; 5968 } 5969 5970 /** 5971 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5972 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5973 * decide automatically. 5974 * 5975 * @attr ref android.R.styleable#View_nextFocusRight 5976 */ 5977 public void setNextFocusRightId(int nextFocusRightId) { 5978 mNextFocusRightId = nextFocusRightId; 5979 } 5980 5981 /** 5982 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5983 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5984 * 5985 * @attr ref android.R.styleable#View_nextFocusUp 5986 */ 5987 public int getNextFocusUpId() { 5988 return mNextFocusUpId; 5989 } 5990 5991 /** 5992 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5993 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5994 * decide automatically. 5995 * 5996 * @attr ref android.R.styleable#View_nextFocusUp 5997 */ 5998 public void setNextFocusUpId(int nextFocusUpId) { 5999 mNextFocusUpId = nextFocusUpId; 6000 } 6001 6002 /** 6003 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6004 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6005 * 6006 * @attr ref android.R.styleable#View_nextFocusDown 6007 */ 6008 public int getNextFocusDownId() { 6009 return mNextFocusDownId; 6010 } 6011 6012 /** 6013 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6014 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6015 * decide automatically. 6016 * 6017 * @attr ref android.R.styleable#View_nextFocusDown 6018 */ 6019 public void setNextFocusDownId(int nextFocusDownId) { 6020 mNextFocusDownId = nextFocusDownId; 6021 } 6022 6023 /** 6024 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6025 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6026 * 6027 * @attr ref android.R.styleable#View_nextFocusForward 6028 */ 6029 public int getNextFocusForwardId() { 6030 return mNextFocusForwardId; 6031 } 6032 6033 /** 6034 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6035 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6036 * decide automatically. 6037 * 6038 * @attr ref android.R.styleable#View_nextFocusForward 6039 */ 6040 public void setNextFocusForwardId(int nextFocusForwardId) { 6041 mNextFocusForwardId = nextFocusForwardId; 6042 } 6043 6044 /** 6045 * Returns the visibility of this view and all of its ancestors 6046 * 6047 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6048 */ 6049 public boolean isShown() { 6050 View current = this; 6051 //noinspection ConstantConditions 6052 do { 6053 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6054 return false; 6055 } 6056 ViewParent parent = current.mParent; 6057 if (parent == null) { 6058 return false; // We are not attached to the view root 6059 } 6060 if (!(parent instanceof View)) { 6061 return true; 6062 } 6063 current = (View) parent; 6064 } while (current != null); 6065 6066 return false; 6067 } 6068 6069 /** 6070 * Called by the view hierarchy when the content insets for a window have 6071 * changed, to allow it to adjust its content to fit within those windows. 6072 * The content insets tell you the space that the status bar, input method, 6073 * and other system windows infringe on the application's window. 6074 * 6075 * <p>You do not normally need to deal with this function, since the default 6076 * window decoration given to applications takes care of applying it to the 6077 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6078 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6079 * and your content can be placed under those system elements. You can then 6080 * use this method within your view hierarchy if you have parts of your UI 6081 * which you would like to ensure are not being covered. 6082 * 6083 * <p>The default implementation of this method simply applies the content 6084 * insets to the view's padding, consuming that content (modifying the 6085 * insets to be 0), and returning true. This behavior is off by default, but can 6086 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6087 * 6088 * <p>This function's traversal down the hierarchy is depth-first. The same content 6089 * insets object is propagated down the hierarchy, so any changes made to it will 6090 * be seen by all following views (including potentially ones above in 6091 * the hierarchy since this is a depth-first traversal). The first view 6092 * that returns true will abort the entire traversal. 6093 * 6094 * <p>The default implementation works well for a situation where it is 6095 * used with a container that covers the entire window, allowing it to 6096 * apply the appropriate insets to its content on all edges. If you need 6097 * a more complicated layout (such as two different views fitting system 6098 * windows, one on the top of the window, and one on the bottom), 6099 * you can override the method and handle the insets however you would like. 6100 * Note that the insets provided by the framework are always relative to the 6101 * far edges of the window, not accounting for the location of the called view 6102 * within that window. (In fact when this method is called you do not yet know 6103 * where the layout will place the view, as it is done before layout happens.) 6104 * 6105 * <p>Note: unlike many View methods, there is no dispatch phase to this 6106 * call. If you are overriding it in a ViewGroup and want to allow the 6107 * call to continue to your children, you must be sure to call the super 6108 * implementation. 6109 * 6110 * <p>Here is a sample layout that makes use of fitting system windows 6111 * to have controls for a video view placed inside of the window decorations 6112 * that it hides and shows. This can be used with code like the second 6113 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6114 * 6115 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6116 * 6117 * @param insets Current content insets of the window. Prior to 6118 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6119 * the insets or else you and Android will be unhappy. 6120 * 6121 * @return {@code true} if this view applied the insets and it should not 6122 * continue propagating further down the hierarchy, {@code false} otherwise. 6123 * @see #getFitsSystemWindows() 6124 * @see #setFitsSystemWindows(boolean) 6125 * @see #setSystemUiVisibility(int) 6126 * 6127 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6128 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6129 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6130 * to implement handling their own insets. 6131 */ 6132 protected boolean fitSystemWindows(Rect insets) { 6133 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6134 if (insets == null) { 6135 // Null insets by definition have already been consumed. 6136 // This call cannot apply insets since there are none to apply, 6137 // so return false. 6138 return false; 6139 } 6140 // If we're not in the process of dispatching the newer apply insets call, 6141 // that means we're not in the compatibility path. Dispatch into the newer 6142 // apply insets path and take things from there. 6143 try { 6144 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6145 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 6146 } finally { 6147 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6148 } 6149 } else { 6150 // We're being called from the newer apply insets path. 6151 // Perform the standard fallback behavior. 6152 return fitSystemWindowsInt(insets); 6153 } 6154 } 6155 6156 private boolean fitSystemWindowsInt(Rect insets) { 6157 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6158 mUserPaddingStart = UNDEFINED_PADDING; 6159 mUserPaddingEnd = UNDEFINED_PADDING; 6160 Rect localInsets = sThreadLocal.get(); 6161 if (localInsets == null) { 6162 localInsets = new Rect(); 6163 sThreadLocal.set(localInsets); 6164 } 6165 boolean res = computeFitSystemWindows(insets, localInsets); 6166 mUserPaddingLeftInitial = localInsets.left; 6167 mUserPaddingRightInitial = localInsets.right; 6168 internalSetPadding(localInsets.left, localInsets.top, 6169 localInsets.right, localInsets.bottom); 6170 return res; 6171 } 6172 return false; 6173 } 6174 6175 /** 6176 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6177 * 6178 * <p>This method should be overridden by views that wish to apply a policy different from or 6179 * in addition to the default behavior. Clients that wish to force a view subtree 6180 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6181 * 6182 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6183 * it will be called during dispatch instead of this method. The listener may optionally 6184 * call this method from its own implementation if it wishes to apply the view's default 6185 * insets policy in addition to its own.</p> 6186 * 6187 * <p>Implementations of this method should either return the insets parameter unchanged 6188 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6189 * that this view applied itself. This allows new inset types added in future platform 6190 * versions to pass through existing implementations unchanged without being erroneously 6191 * consumed.</p> 6192 * 6193 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6194 * property is set then the view will consume the system window insets and apply them 6195 * as padding for the view.</p> 6196 * 6197 * @param insets Insets to apply 6198 * @return The supplied insets with any applied insets consumed 6199 */ 6200 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6201 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6202 // We weren't called from within a direct call to fitSystemWindows, 6203 // call into it as a fallback in case we're in a class that overrides it 6204 // and has logic to perform. 6205 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6206 return insets.consumeSystemWindowInsets(); 6207 } 6208 } else { 6209 // We were called from within a direct call to fitSystemWindows. 6210 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6211 return insets.consumeSystemWindowInsets(); 6212 } 6213 } 6214 return insets; 6215 } 6216 6217 /** 6218 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6219 * window insets to this view. The listener's 6220 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6221 * method will be called instead of the view's 6222 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6223 * 6224 * @param listener Listener to set 6225 * 6226 * @see #onApplyWindowInsets(WindowInsets) 6227 */ 6228 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6229 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6230 } 6231 6232 /** 6233 * Request to apply the given window insets to this view or another view in its subtree. 6234 * 6235 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6236 * obscured by window decorations or overlays. This can include the status and navigation bars, 6237 * action bars, input methods and more. New inset categories may be added in the future. 6238 * The method returns the insets provided minus any that were applied by this view or its 6239 * children.</p> 6240 * 6241 * <p>Clients wishing to provide custom behavior should override the 6242 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6243 * {@link OnApplyWindowInsetsListener} via the 6244 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6245 * method.</p> 6246 * 6247 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6248 * </p> 6249 * 6250 * @param insets Insets to apply 6251 * @return The provided insets minus the insets that were consumed 6252 */ 6253 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6254 try { 6255 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6256 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6257 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6258 } else { 6259 return onApplyWindowInsets(insets); 6260 } 6261 } finally { 6262 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6263 } 6264 } 6265 6266 /** 6267 * @hide Compute the insets that should be consumed by this view and the ones 6268 * that should propagate to those under it. 6269 */ 6270 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6271 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6272 || mAttachInfo == null 6273 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6274 && !mAttachInfo.mOverscanRequested)) { 6275 outLocalInsets.set(inoutInsets); 6276 inoutInsets.set(0, 0, 0, 0); 6277 return true; 6278 } else { 6279 // The application wants to take care of fitting system window for 6280 // the content... however we still need to take care of any overscan here. 6281 final Rect overscan = mAttachInfo.mOverscanInsets; 6282 outLocalInsets.set(overscan); 6283 inoutInsets.left -= overscan.left; 6284 inoutInsets.top -= overscan.top; 6285 inoutInsets.right -= overscan.right; 6286 inoutInsets.bottom -= overscan.bottom; 6287 return false; 6288 } 6289 } 6290 6291 /** 6292 * Sets whether or not this view should account for system screen decorations 6293 * such as the status bar and inset its content; that is, controlling whether 6294 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6295 * executed. See that method for more details. 6296 * 6297 * <p>Note that if you are providing your own implementation of 6298 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6299 * flag to true -- your implementation will be overriding the default 6300 * implementation that checks this flag. 6301 * 6302 * @param fitSystemWindows If true, then the default implementation of 6303 * {@link #fitSystemWindows(Rect)} will be executed. 6304 * 6305 * @attr ref android.R.styleable#View_fitsSystemWindows 6306 * @see #getFitsSystemWindows() 6307 * @see #fitSystemWindows(Rect) 6308 * @see #setSystemUiVisibility(int) 6309 */ 6310 public void setFitsSystemWindows(boolean fitSystemWindows) { 6311 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6312 } 6313 6314 /** 6315 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6316 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6317 * will be executed. 6318 * 6319 * @return {@code true} if the default implementation of 6320 * {@link #fitSystemWindows(Rect)} will be executed. 6321 * 6322 * @attr ref android.R.styleable#View_fitsSystemWindows 6323 * @see #setFitsSystemWindows(boolean) 6324 * @see #fitSystemWindows(Rect) 6325 * @see #setSystemUiVisibility(int) 6326 */ 6327 public boolean getFitsSystemWindows() { 6328 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6329 } 6330 6331 /** @hide */ 6332 public boolean fitsSystemWindows() { 6333 return getFitsSystemWindows(); 6334 } 6335 6336 /** 6337 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6338 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6339 */ 6340 public void requestFitSystemWindows() { 6341 if (mParent != null) { 6342 mParent.requestFitSystemWindows(); 6343 } 6344 } 6345 6346 /** 6347 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6348 */ 6349 public void requestApplyInsets() { 6350 requestFitSystemWindows(); 6351 } 6352 6353 /** 6354 * For use by PhoneWindow to make its own system window fitting optional. 6355 * @hide 6356 */ 6357 public void makeOptionalFitsSystemWindows() { 6358 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6359 } 6360 6361 /** 6362 * Returns the visibility status for this view. 6363 * 6364 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6365 * @attr ref android.R.styleable#View_visibility 6366 */ 6367 @ViewDebug.ExportedProperty(mapping = { 6368 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6369 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6370 @ViewDebug.IntToString(from = GONE, to = "GONE") 6371 }) 6372 @Visibility 6373 public int getVisibility() { 6374 return mViewFlags & VISIBILITY_MASK; 6375 } 6376 6377 /** 6378 * Set the enabled state of this view. 6379 * 6380 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6381 * @attr ref android.R.styleable#View_visibility 6382 */ 6383 @RemotableViewMethod 6384 public void setVisibility(@Visibility int visibility) { 6385 setFlags(visibility, VISIBILITY_MASK); 6386 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6387 } 6388 6389 /** 6390 * Returns the enabled status for this view. The interpretation of the 6391 * enabled state varies by subclass. 6392 * 6393 * @return True if this view is enabled, false otherwise. 6394 */ 6395 @ViewDebug.ExportedProperty 6396 public boolean isEnabled() { 6397 return (mViewFlags & ENABLED_MASK) == ENABLED; 6398 } 6399 6400 /** 6401 * Set the enabled state of this view. The interpretation of the enabled 6402 * state varies by subclass. 6403 * 6404 * @param enabled True if this view is enabled, false otherwise. 6405 */ 6406 @RemotableViewMethod 6407 public void setEnabled(boolean enabled) { 6408 if (enabled == isEnabled()) return; 6409 6410 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6411 6412 /* 6413 * The View most likely has to change its appearance, so refresh 6414 * the drawable state. 6415 */ 6416 refreshDrawableState(); 6417 6418 // Invalidate too, since the default behavior for views is to be 6419 // be drawn at 50% alpha rather than to change the drawable. 6420 invalidate(true); 6421 6422 if (!enabled) { 6423 cancelPendingInputEvents(); 6424 } 6425 } 6426 6427 /** 6428 * Set whether this view can receive the focus. 6429 * 6430 * Setting this to false will also ensure that this view is not focusable 6431 * in touch mode. 6432 * 6433 * @param focusable If true, this view can receive the focus. 6434 * 6435 * @see #setFocusableInTouchMode(boolean) 6436 * @attr ref android.R.styleable#View_focusable 6437 */ 6438 public void setFocusable(boolean focusable) { 6439 if (!focusable) { 6440 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6441 } 6442 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6443 } 6444 6445 /** 6446 * Set whether this view can receive focus while in touch mode. 6447 * 6448 * Setting this to true will also ensure that this view is focusable. 6449 * 6450 * @param focusableInTouchMode If true, this view can receive the focus while 6451 * in touch mode. 6452 * 6453 * @see #setFocusable(boolean) 6454 * @attr ref android.R.styleable#View_focusableInTouchMode 6455 */ 6456 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6457 // Focusable in touch mode should always be set before the focusable flag 6458 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6459 // which, in touch mode, will not successfully request focus on this view 6460 // because the focusable in touch mode flag is not set 6461 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6462 if (focusableInTouchMode) { 6463 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6464 } 6465 } 6466 6467 /** 6468 * Set whether this view should have sound effects enabled for events such as 6469 * clicking and touching. 6470 * 6471 * <p>You may wish to disable sound effects for a view if you already play sounds, 6472 * for instance, a dial key that plays dtmf tones. 6473 * 6474 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6475 * @see #isSoundEffectsEnabled() 6476 * @see #playSoundEffect(int) 6477 * @attr ref android.R.styleable#View_soundEffectsEnabled 6478 */ 6479 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6480 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6481 } 6482 6483 /** 6484 * @return whether this view should have sound effects enabled for events such as 6485 * clicking and touching. 6486 * 6487 * @see #setSoundEffectsEnabled(boolean) 6488 * @see #playSoundEffect(int) 6489 * @attr ref android.R.styleable#View_soundEffectsEnabled 6490 */ 6491 @ViewDebug.ExportedProperty 6492 public boolean isSoundEffectsEnabled() { 6493 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6494 } 6495 6496 /** 6497 * Set whether this view should have haptic feedback for events such as 6498 * long presses. 6499 * 6500 * <p>You may wish to disable haptic feedback if your view already controls 6501 * its own haptic feedback. 6502 * 6503 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6504 * @see #isHapticFeedbackEnabled() 6505 * @see #performHapticFeedback(int) 6506 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6507 */ 6508 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6509 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6510 } 6511 6512 /** 6513 * @return whether this view should have haptic feedback enabled for events 6514 * long presses. 6515 * 6516 * @see #setHapticFeedbackEnabled(boolean) 6517 * @see #performHapticFeedback(int) 6518 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6519 */ 6520 @ViewDebug.ExportedProperty 6521 public boolean isHapticFeedbackEnabled() { 6522 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6523 } 6524 6525 /** 6526 * Returns the layout direction for this view. 6527 * 6528 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6529 * {@link #LAYOUT_DIRECTION_RTL}, 6530 * {@link #LAYOUT_DIRECTION_INHERIT} or 6531 * {@link #LAYOUT_DIRECTION_LOCALE}. 6532 * 6533 * @attr ref android.R.styleable#View_layoutDirection 6534 * 6535 * @hide 6536 */ 6537 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6538 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6539 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6540 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6541 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6542 }) 6543 @LayoutDir 6544 public int getRawLayoutDirection() { 6545 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6546 } 6547 6548 /** 6549 * Set the layout direction for this view. This will propagate a reset of layout direction 6550 * resolution to the view's children and resolve layout direction for this view. 6551 * 6552 * @param layoutDirection the layout direction to set. Should be one of: 6553 * 6554 * {@link #LAYOUT_DIRECTION_LTR}, 6555 * {@link #LAYOUT_DIRECTION_RTL}, 6556 * {@link #LAYOUT_DIRECTION_INHERIT}, 6557 * {@link #LAYOUT_DIRECTION_LOCALE}. 6558 * 6559 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6560 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6561 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6562 * 6563 * @attr ref android.R.styleable#View_layoutDirection 6564 */ 6565 @RemotableViewMethod 6566 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6567 if (getRawLayoutDirection() != layoutDirection) { 6568 // Reset the current layout direction and the resolved one 6569 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6570 resetRtlProperties(); 6571 // Set the new layout direction (filtered) 6572 mPrivateFlags2 |= 6573 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6574 // We need to resolve all RTL properties as they all depend on layout direction 6575 resolveRtlPropertiesIfNeeded(); 6576 requestLayout(); 6577 invalidate(true); 6578 } 6579 } 6580 6581 /** 6582 * Returns the resolved layout direction for this view. 6583 * 6584 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6585 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6586 * 6587 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6588 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6589 * 6590 * @attr ref android.R.styleable#View_layoutDirection 6591 */ 6592 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6593 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6594 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6595 }) 6596 @ResolvedLayoutDir 6597 public int getLayoutDirection() { 6598 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6599 if (targetSdkVersion < JELLY_BEAN_MR1) { 6600 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6601 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6602 } 6603 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6604 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6605 } 6606 6607 /** 6608 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6609 * layout attribute and/or the inherited value from the parent 6610 * 6611 * @return true if the layout is right-to-left. 6612 * 6613 * @hide 6614 */ 6615 @ViewDebug.ExportedProperty(category = "layout") 6616 public boolean isLayoutRtl() { 6617 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6618 } 6619 6620 /** 6621 * Indicates whether the view is currently tracking transient state that the 6622 * app should not need to concern itself with saving and restoring, but that 6623 * the framework should take special note to preserve when possible. 6624 * 6625 * <p>A view with transient state cannot be trivially rebound from an external 6626 * data source, such as an adapter binding item views in a list. This may be 6627 * because the view is performing an animation, tracking user selection 6628 * of content, or similar.</p> 6629 * 6630 * @return true if the view has transient state 6631 */ 6632 @ViewDebug.ExportedProperty(category = "layout") 6633 public boolean hasTransientState() { 6634 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6635 } 6636 6637 /** 6638 * Set whether this view is currently tracking transient state that the 6639 * framework should attempt to preserve when possible. This flag is reference counted, 6640 * so every call to setHasTransientState(true) should be paired with a later call 6641 * to setHasTransientState(false). 6642 * 6643 * <p>A view with transient state cannot be trivially rebound from an external 6644 * data source, such as an adapter binding item views in a list. This may be 6645 * because the view is performing an animation, tracking user selection 6646 * of content, or similar.</p> 6647 * 6648 * @param hasTransientState true if this view has transient state 6649 */ 6650 public void setHasTransientState(boolean hasTransientState) { 6651 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6652 mTransientStateCount - 1; 6653 if (mTransientStateCount < 0) { 6654 mTransientStateCount = 0; 6655 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6656 "unmatched pair of setHasTransientState calls"); 6657 } else if ((hasTransientState && mTransientStateCount == 1) || 6658 (!hasTransientState && mTransientStateCount == 0)) { 6659 // update flag if we've just incremented up from 0 or decremented down to 0 6660 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6661 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6662 if (mParent != null) { 6663 try { 6664 mParent.childHasTransientStateChanged(this, hasTransientState); 6665 } catch (AbstractMethodError e) { 6666 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6667 " does not fully implement ViewParent", e); 6668 } 6669 } 6670 } 6671 } 6672 6673 /** 6674 * Returns true if this view is currently attached to a window. 6675 */ 6676 public boolean isAttachedToWindow() { 6677 return mAttachInfo != null; 6678 } 6679 6680 /** 6681 * Returns true if this view has been through at least one layout since it 6682 * was last attached to or detached from a window. 6683 */ 6684 public boolean isLaidOut() { 6685 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6686 } 6687 6688 /** 6689 * If this view doesn't do any drawing on its own, set this flag to 6690 * allow further optimizations. By default, this flag is not set on 6691 * View, but could be set on some View subclasses such as ViewGroup. 6692 * 6693 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6694 * you should clear this flag. 6695 * 6696 * @param willNotDraw whether or not this View draw on its own 6697 */ 6698 public void setWillNotDraw(boolean willNotDraw) { 6699 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6700 } 6701 6702 /** 6703 * Returns whether or not this View draws on its own. 6704 * 6705 * @return true if this view has nothing to draw, false otherwise 6706 */ 6707 @ViewDebug.ExportedProperty(category = "drawing") 6708 public boolean willNotDraw() { 6709 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6710 } 6711 6712 /** 6713 * When a View's drawing cache is enabled, drawing is redirected to an 6714 * offscreen bitmap. Some views, like an ImageView, must be able to 6715 * bypass this mechanism if they already draw a single bitmap, to avoid 6716 * unnecessary usage of the memory. 6717 * 6718 * @param willNotCacheDrawing true if this view does not cache its 6719 * drawing, false otherwise 6720 */ 6721 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6722 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6723 } 6724 6725 /** 6726 * Returns whether or not this View can cache its drawing or not. 6727 * 6728 * @return true if this view does not cache its drawing, false otherwise 6729 */ 6730 @ViewDebug.ExportedProperty(category = "drawing") 6731 public boolean willNotCacheDrawing() { 6732 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6733 } 6734 6735 /** 6736 * Indicates whether this view reacts to click events or not. 6737 * 6738 * @return true if the view is clickable, false otherwise 6739 * 6740 * @see #setClickable(boolean) 6741 * @attr ref android.R.styleable#View_clickable 6742 */ 6743 @ViewDebug.ExportedProperty 6744 public boolean isClickable() { 6745 return (mViewFlags & CLICKABLE) == CLICKABLE; 6746 } 6747 6748 /** 6749 * Enables or disables click events for this view. When a view 6750 * is clickable it will change its state to "pressed" on every click. 6751 * Subclasses should set the view clickable to visually react to 6752 * user's clicks. 6753 * 6754 * @param clickable true to make the view clickable, false otherwise 6755 * 6756 * @see #isClickable() 6757 * @attr ref android.R.styleable#View_clickable 6758 */ 6759 public void setClickable(boolean clickable) { 6760 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6761 } 6762 6763 /** 6764 * Indicates whether this view reacts to long click events or not. 6765 * 6766 * @return true if the view is long clickable, false otherwise 6767 * 6768 * @see #setLongClickable(boolean) 6769 * @attr ref android.R.styleable#View_longClickable 6770 */ 6771 public boolean isLongClickable() { 6772 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6773 } 6774 6775 /** 6776 * Enables or disables long click events for this view. When a view is long 6777 * clickable it reacts to the user holding down the button for a longer 6778 * duration than a tap. This event can either launch the listener or a 6779 * context menu. 6780 * 6781 * @param longClickable true to make the view long clickable, false otherwise 6782 * @see #isLongClickable() 6783 * @attr ref android.R.styleable#View_longClickable 6784 */ 6785 public void setLongClickable(boolean longClickable) { 6786 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6787 } 6788 6789 /** 6790 * Sets the pressed state for this view and provides a touch coordinate for 6791 * animation hinting. 6792 * 6793 * @param pressed Pass true to set the View's internal state to "pressed", 6794 * or false to reverts the View's internal state from a 6795 * previously set "pressed" state. 6796 * @param x The x coordinate of the touch that caused the press 6797 * @param y The y coordinate of the touch that caused the press 6798 */ 6799 private void setPressed(boolean pressed, float x, float y) { 6800 if (pressed) { 6801 setDrawableHotspot(x, y); 6802 } 6803 6804 setPressed(pressed); 6805 } 6806 6807 /** 6808 * Sets the pressed state for this view. 6809 * 6810 * @see #isClickable() 6811 * @see #setClickable(boolean) 6812 * 6813 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6814 * the View's internal state from a previously set "pressed" state. 6815 */ 6816 public void setPressed(boolean pressed) { 6817 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6818 6819 if (pressed) { 6820 mPrivateFlags |= PFLAG_PRESSED; 6821 } else { 6822 mPrivateFlags &= ~PFLAG_PRESSED; 6823 } 6824 6825 if (needsRefresh) { 6826 refreshDrawableState(); 6827 } 6828 dispatchSetPressed(pressed); 6829 } 6830 6831 /** 6832 * Dispatch setPressed to all of this View's children. 6833 * 6834 * @see #setPressed(boolean) 6835 * 6836 * @param pressed The new pressed state 6837 */ 6838 protected void dispatchSetPressed(boolean pressed) { 6839 } 6840 6841 /** 6842 * Indicates whether the view is currently in pressed state. Unless 6843 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6844 * the pressed state. 6845 * 6846 * @see #setPressed(boolean) 6847 * @see #isClickable() 6848 * @see #setClickable(boolean) 6849 * 6850 * @return true if the view is currently pressed, false otherwise 6851 */ 6852 public boolean isPressed() { 6853 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6854 } 6855 6856 /** 6857 * Indicates whether this view will save its state (that is, 6858 * whether its {@link #onSaveInstanceState} method will be called). 6859 * 6860 * @return Returns true if the view state saving is enabled, else false. 6861 * 6862 * @see #setSaveEnabled(boolean) 6863 * @attr ref android.R.styleable#View_saveEnabled 6864 */ 6865 public boolean isSaveEnabled() { 6866 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6867 } 6868 6869 /** 6870 * Controls whether the saving of this view's state is 6871 * enabled (that is, whether its {@link #onSaveInstanceState} method 6872 * will be called). Note that even if freezing is enabled, the 6873 * view still must have an id assigned to it (via {@link #setId(int)}) 6874 * for its state to be saved. This flag can only disable the 6875 * saving of this view; any child views may still have their state saved. 6876 * 6877 * @param enabled Set to false to <em>disable</em> state saving, or true 6878 * (the default) to allow it. 6879 * 6880 * @see #isSaveEnabled() 6881 * @see #setId(int) 6882 * @see #onSaveInstanceState() 6883 * @attr ref android.R.styleable#View_saveEnabled 6884 */ 6885 public void setSaveEnabled(boolean enabled) { 6886 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6887 } 6888 6889 /** 6890 * Gets whether the framework should discard touches when the view's 6891 * window is obscured by another visible window. 6892 * Refer to the {@link View} security documentation for more details. 6893 * 6894 * @return True if touch filtering is enabled. 6895 * 6896 * @see #setFilterTouchesWhenObscured(boolean) 6897 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6898 */ 6899 @ViewDebug.ExportedProperty 6900 public boolean getFilterTouchesWhenObscured() { 6901 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6902 } 6903 6904 /** 6905 * Sets whether the framework should discard touches when the view's 6906 * window is obscured by another visible window. 6907 * Refer to the {@link View} security documentation for more details. 6908 * 6909 * @param enabled True if touch filtering should be enabled. 6910 * 6911 * @see #getFilterTouchesWhenObscured 6912 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6913 */ 6914 public void setFilterTouchesWhenObscured(boolean enabled) { 6915 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 6916 FILTER_TOUCHES_WHEN_OBSCURED); 6917 } 6918 6919 /** 6920 * Indicates 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 * @return Returns true if the view state saving from parent is enabled, else false. 6926 * 6927 * @see #setSaveFromParentEnabled(boolean) 6928 */ 6929 public boolean isSaveFromParentEnabled() { 6930 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6931 } 6932 6933 /** 6934 * Controls whether the entire hierarchy under this view will save its 6935 * state when a state saving traversal occurs from its parent. The default 6936 * is true; if false, these views will not be saved unless 6937 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6938 * 6939 * @param enabled Set to false to <em>disable</em> state saving, or true 6940 * (the default) to allow it. 6941 * 6942 * @see #isSaveFromParentEnabled() 6943 * @see #setId(int) 6944 * @see #onSaveInstanceState() 6945 */ 6946 public void setSaveFromParentEnabled(boolean enabled) { 6947 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6948 } 6949 6950 6951 /** 6952 * Returns whether this View is able to take focus. 6953 * 6954 * @return True if this view can take focus, or false otherwise. 6955 * @attr ref android.R.styleable#View_focusable 6956 */ 6957 @ViewDebug.ExportedProperty(category = "focus") 6958 public final boolean isFocusable() { 6959 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6960 } 6961 6962 /** 6963 * When a view is focusable, it may not want to take focus when in touch mode. 6964 * For example, a button would like focus when the user is navigating via a D-pad 6965 * so that the user can click on it, but once the user starts touching the screen, 6966 * the button shouldn't take focus 6967 * @return Whether the view is focusable in touch mode. 6968 * @attr ref android.R.styleable#View_focusableInTouchMode 6969 */ 6970 @ViewDebug.ExportedProperty 6971 public final boolean isFocusableInTouchMode() { 6972 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6973 } 6974 6975 /** 6976 * Find the nearest view in the specified direction that can take focus. 6977 * This does not actually give focus to that view. 6978 * 6979 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6980 * 6981 * @return The nearest focusable in the specified direction, or null if none 6982 * can be found. 6983 */ 6984 public View focusSearch(@FocusRealDirection int direction) { 6985 if (mParent != null) { 6986 return mParent.focusSearch(this, direction); 6987 } else { 6988 return null; 6989 } 6990 } 6991 6992 /** 6993 * This method is the last chance for the focused view and its ancestors to 6994 * respond to an arrow key. This is called when the focused view did not 6995 * consume the key internally, nor could the view system find a new view in 6996 * the requested direction to give focus to. 6997 * 6998 * @param focused The currently focused view. 6999 * @param direction The direction focus wants to move. One of FOCUS_UP, 7000 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 7001 * @return True if the this view consumed this unhandled move. 7002 */ 7003 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 7004 return false; 7005 } 7006 7007 /** 7008 * If a user manually specified the next view id for a particular direction, 7009 * use the root to look up the view. 7010 * @param root The root view of the hierarchy containing this view. 7011 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 7012 * or FOCUS_BACKWARD. 7013 * @return The user specified next view, or null if there is none. 7014 */ 7015 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7016 switch (direction) { 7017 case FOCUS_LEFT: 7018 if (mNextFocusLeftId == View.NO_ID) return null; 7019 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7020 case FOCUS_RIGHT: 7021 if (mNextFocusRightId == View.NO_ID) return null; 7022 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7023 case FOCUS_UP: 7024 if (mNextFocusUpId == View.NO_ID) return null; 7025 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7026 case FOCUS_DOWN: 7027 if (mNextFocusDownId == View.NO_ID) return null; 7028 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7029 case FOCUS_FORWARD: 7030 if (mNextFocusForwardId == View.NO_ID) return null; 7031 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7032 case FOCUS_BACKWARD: { 7033 if (mID == View.NO_ID) return null; 7034 final int id = mID; 7035 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7036 @Override 7037 public boolean apply(View t) { 7038 return t.mNextFocusForwardId == id; 7039 } 7040 }); 7041 } 7042 } 7043 return null; 7044 } 7045 7046 private View findViewInsideOutShouldExist(View root, int id) { 7047 if (mMatchIdPredicate == null) { 7048 mMatchIdPredicate = new MatchIdPredicate(); 7049 } 7050 mMatchIdPredicate.mId = id; 7051 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7052 if (result == null) { 7053 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7054 } 7055 return result; 7056 } 7057 7058 /** 7059 * Find and return all focusable views that are descendants of this view, 7060 * possibly including this view if it is focusable itself. 7061 * 7062 * @param direction The direction of the focus 7063 * @return A list of focusable views 7064 */ 7065 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7066 ArrayList<View> result = new ArrayList<View>(24); 7067 addFocusables(result, direction); 7068 return result; 7069 } 7070 7071 /** 7072 * Add any focusable views that are descendants of this view (possibly 7073 * including this view if it is focusable itself) to views. If we are in touch mode, 7074 * only add views that are also focusable in touch mode. 7075 * 7076 * @param views Focusable views found so far 7077 * @param direction The direction of the focus 7078 */ 7079 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7080 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7081 } 7082 7083 /** 7084 * Adds any focusable views that are descendants of this view (possibly 7085 * including this view if it is focusable itself) to views. This method 7086 * adds all focusable views regardless if we are in touch mode or 7087 * only views focusable in touch mode if we are in touch mode or 7088 * only views that can take accessibility focus if accessibility is enabeld 7089 * depending on the focusable mode paramater. 7090 * 7091 * @param views Focusable views found so far or null if all we are interested is 7092 * the number of focusables. 7093 * @param direction The direction of the focus. 7094 * @param focusableMode The type of focusables to be added. 7095 * 7096 * @see #FOCUSABLES_ALL 7097 * @see #FOCUSABLES_TOUCH_MODE 7098 */ 7099 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7100 @FocusableMode int focusableMode) { 7101 if (views == null) { 7102 return; 7103 } 7104 if (!isFocusable()) { 7105 return; 7106 } 7107 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7108 && isInTouchMode() && !isFocusableInTouchMode()) { 7109 return; 7110 } 7111 views.add(this); 7112 } 7113 7114 /** 7115 * Finds the Views that contain given text. The containment is case insensitive. 7116 * The search is performed by either the text that the View renders or the content 7117 * description that describes the view for accessibility purposes and the view does 7118 * not render or both. Clients can specify how the search is to be performed via 7119 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7120 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7121 * 7122 * @param outViews The output list of matching Views. 7123 * @param searched The text to match against. 7124 * 7125 * @see #FIND_VIEWS_WITH_TEXT 7126 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7127 * @see #setContentDescription(CharSequence) 7128 */ 7129 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7130 @FindViewFlags int flags) { 7131 if (getAccessibilityNodeProvider() != null) { 7132 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7133 outViews.add(this); 7134 } 7135 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7136 && (searched != null && searched.length() > 0) 7137 && (mContentDescription != null && mContentDescription.length() > 0)) { 7138 String searchedLowerCase = searched.toString().toLowerCase(); 7139 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7140 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7141 outViews.add(this); 7142 } 7143 } 7144 } 7145 7146 /** 7147 * Find and return all touchable views that are descendants of this view, 7148 * possibly including this view if it is touchable itself. 7149 * 7150 * @return A list of touchable views 7151 */ 7152 public ArrayList<View> getTouchables() { 7153 ArrayList<View> result = new ArrayList<View>(); 7154 addTouchables(result); 7155 return result; 7156 } 7157 7158 /** 7159 * Add any touchable views that are descendants of this view (possibly 7160 * including this view if it is touchable itself) to views. 7161 * 7162 * @param views Touchable views found so far 7163 */ 7164 public void addTouchables(ArrayList<View> views) { 7165 final int viewFlags = mViewFlags; 7166 7167 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7168 && (viewFlags & ENABLED_MASK) == ENABLED) { 7169 views.add(this); 7170 } 7171 } 7172 7173 /** 7174 * Returns whether this View is accessibility focused. 7175 * 7176 * @return True if this View is accessibility focused. 7177 */ 7178 public boolean isAccessibilityFocused() { 7179 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7180 } 7181 7182 /** 7183 * Call this to try to give accessibility focus to this view. 7184 * 7185 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7186 * returns false or the view is no visible or the view already has accessibility 7187 * focus. 7188 * 7189 * See also {@link #focusSearch(int)}, which is what you call to say that you 7190 * have focus, and you want your parent to look for the next one. 7191 * 7192 * @return Whether this view actually took accessibility focus. 7193 * 7194 * @hide 7195 */ 7196 public boolean requestAccessibilityFocus() { 7197 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7198 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7199 return false; 7200 } 7201 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7202 return false; 7203 } 7204 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7205 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7206 ViewRootImpl viewRootImpl = getViewRootImpl(); 7207 if (viewRootImpl != null) { 7208 viewRootImpl.setAccessibilityFocus(this, null); 7209 } 7210 Rect rect = (mAttachInfo != null) ? mAttachInfo.mTmpInvalRect : new Rect(); 7211 getDrawingRect(rect); 7212 requestRectangleOnScreen(rect, false); 7213 invalidate(); 7214 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7215 return true; 7216 } 7217 return false; 7218 } 7219 7220 /** 7221 * Call this to try to clear accessibility focus of this view. 7222 * 7223 * See also {@link #focusSearch(int)}, which is what you call to say that you 7224 * have focus, and you want your parent to look for the next one. 7225 * 7226 * @hide 7227 */ 7228 public void clearAccessibilityFocus() { 7229 clearAccessibilityFocusNoCallbacks(); 7230 // Clear the global reference of accessibility focus if this 7231 // view or any of its descendants had accessibility focus. 7232 ViewRootImpl viewRootImpl = getViewRootImpl(); 7233 if (viewRootImpl != null) { 7234 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7235 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7236 viewRootImpl.setAccessibilityFocus(null, null); 7237 } 7238 } 7239 } 7240 7241 private void sendAccessibilityHoverEvent(int eventType) { 7242 // Since we are not delivering to a client accessibility events from not 7243 // important views (unless the clinet request that) we need to fire the 7244 // event from the deepest view exposed to the client. As a consequence if 7245 // the user crosses a not exposed view the client will see enter and exit 7246 // of the exposed predecessor followed by and enter and exit of that same 7247 // predecessor when entering and exiting the not exposed descendant. This 7248 // is fine since the client has a clear idea which view is hovered at the 7249 // price of a couple more events being sent. This is a simple and 7250 // working solution. 7251 View source = this; 7252 while (true) { 7253 if (source.includeForAccessibility()) { 7254 source.sendAccessibilityEvent(eventType); 7255 return; 7256 } 7257 ViewParent parent = source.getParent(); 7258 if (parent instanceof View) { 7259 source = (View) parent; 7260 } else { 7261 return; 7262 } 7263 } 7264 } 7265 7266 /** 7267 * Clears accessibility focus without calling any callback methods 7268 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7269 * is used for clearing accessibility focus when giving this focus to 7270 * another view. 7271 */ 7272 void clearAccessibilityFocusNoCallbacks() { 7273 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7274 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7275 invalidate(); 7276 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7277 } 7278 } 7279 7280 /** 7281 * Call this to try to give focus to a specific view or to one of its 7282 * descendants. 7283 * 7284 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7285 * false), or if it is focusable and it is not focusable in touch mode 7286 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7287 * 7288 * See also {@link #focusSearch(int)}, which is what you call to say that you 7289 * have focus, and you want your parent to look for the next one. 7290 * 7291 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7292 * {@link #FOCUS_DOWN} and <code>null</code>. 7293 * 7294 * @return Whether this view or one of its descendants actually took focus. 7295 */ 7296 public final boolean requestFocus() { 7297 return requestFocus(View.FOCUS_DOWN); 7298 } 7299 7300 /** 7301 * Call this to try to give focus to a specific view or to one of its 7302 * descendants and give it a hint about what direction focus is heading. 7303 * 7304 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7305 * false), or if it is focusable and it is not focusable in touch mode 7306 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7307 * 7308 * See also {@link #focusSearch(int)}, which is what you call to say that you 7309 * have focus, and you want your parent to look for the next one. 7310 * 7311 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7312 * <code>null</code> set for the previously focused rectangle. 7313 * 7314 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7315 * @return Whether this view or one of its descendants actually took focus. 7316 */ 7317 public final boolean requestFocus(int direction) { 7318 return requestFocus(direction, null); 7319 } 7320 7321 /** 7322 * Call this to try to give focus to a specific view or to one of its descendants 7323 * and give it hints about the direction and a specific rectangle that the focus 7324 * is coming from. The rectangle can help give larger views a finer grained hint 7325 * about where focus is coming from, and therefore, where to show selection, or 7326 * forward focus change internally. 7327 * 7328 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7329 * false), or if it is focusable and it is not focusable in touch mode 7330 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7331 * 7332 * A View will not take focus if it is not visible. 7333 * 7334 * A View will not take focus if one of its parents has 7335 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7336 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7337 * 7338 * See also {@link #focusSearch(int)}, which is what you call to say that you 7339 * have focus, and you want your parent to look for the next one. 7340 * 7341 * You may wish to override this method if your custom {@link View} has an internal 7342 * {@link View} that it wishes to forward the request to. 7343 * 7344 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7345 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7346 * to give a finer grained hint about where focus is coming from. May be null 7347 * if there is no hint. 7348 * @return Whether this view or one of its descendants actually took focus. 7349 */ 7350 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7351 return requestFocusNoSearch(direction, previouslyFocusedRect); 7352 } 7353 7354 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7355 // need to be focusable 7356 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7357 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7358 return false; 7359 } 7360 7361 // need to be focusable in touch mode if in touch mode 7362 if (isInTouchMode() && 7363 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7364 return false; 7365 } 7366 7367 // need to not have any parents blocking us 7368 if (hasAncestorThatBlocksDescendantFocus()) { 7369 return false; 7370 } 7371 7372 handleFocusGainInternal(direction, previouslyFocusedRect); 7373 return true; 7374 } 7375 7376 /** 7377 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7378 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7379 * touch mode to request focus when they are touched. 7380 * 7381 * @return Whether this view or one of its descendants actually took focus. 7382 * 7383 * @see #isInTouchMode() 7384 * 7385 */ 7386 public final boolean requestFocusFromTouch() { 7387 // Leave touch mode if we need to 7388 if (isInTouchMode()) { 7389 ViewRootImpl viewRoot = getViewRootImpl(); 7390 if (viewRoot != null) { 7391 viewRoot.ensureTouchMode(false); 7392 } 7393 } 7394 return requestFocus(View.FOCUS_DOWN); 7395 } 7396 7397 /** 7398 * @return Whether any ancestor of this view blocks descendant focus. 7399 */ 7400 private boolean hasAncestorThatBlocksDescendantFocus() { 7401 ViewParent ancestor = mParent; 7402 while (ancestor instanceof ViewGroup) { 7403 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7404 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7405 return true; 7406 } else { 7407 ancestor = vgAncestor.getParent(); 7408 } 7409 } 7410 return false; 7411 } 7412 7413 /** 7414 * Gets the mode for determining whether this View is important for accessibility 7415 * which is if it fires accessibility events and if it is reported to 7416 * accessibility services that query the screen. 7417 * 7418 * @return The mode for determining whether a View is important for accessibility. 7419 * 7420 * @attr ref android.R.styleable#View_importantForAccessibility 7421 * 7422 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7423 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7424 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7425 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7426 */ 7427 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7428 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7429 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7430 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7431 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7432 to = "noHideDescendants") 7433 }) 7434 public int getImportantForAccessibility() { 7435 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7436 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7437 } 7438 7439 /** 7440 * Sets the live region mode for this view. This indicates to accessibility 7441 * services whether they should automatically notify the user about changes 7442 * to the view's content description or text, or to the content descriptions 7443 * or text of the view's children (where applicable). 7444 * <p> 7445 * For example, in a login screen with a TextView that displays an "incorrect 7446 * password" notification, that view should be marked as a live region with 7447 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7448 * <p> 7449 * To disable change notifications for this view, use 7450 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7451 * mode for most views. 7452 * <p> 7453 * To indicate that the user should be notified of changes, use 7454 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7455 * <p> 7456 * If the view's changes should interrupt ongoing speech and notify the user 7457 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7458 * 7459 * @param mode The live region mode for this view, one of: 7460 * <ul> 7461 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7462 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7463 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7464 * </ul> 7465 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7466 */ 7467 public void setAccessibilityLiveRegion(int mode) { 7468 if (mode != getAccessibilityLiveRegion()) { 7469 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7470 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7471 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7472 notifyViewAccessibilityStateChangedIfNeeded( 7473 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7474 } 7475 } 7476 7477 /** 7478 * Gets the live region mode for this View. 7479 * 7480 * @return The live region mode for the view. 7481 * 7482 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7483 * 7484 * @see #setAccessibilityLiveRegion(int) 7485 */ 7486 public int getAccessibilityLiveRegion() { 7487 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7488 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7489 } 7490 7491 /** 7492 * Sets how to determine whether this view is important for accessibility 7493 * which is if it fires accessibility events and if it is reported to 7494 * accessibility services that query the screen. 7495 * 7496 * @param mode How to determine whether this view is important for accessibility. 7497 * 7498 * @attr ref android.R.styleable#View_importantForAccessibility 7499 * 7500 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7501 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7502 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7503 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7504 */ 7505 public void setImportantForAccessibility(int mode) { 7506 final int oldMode = getImportantForAccessibility(); 7507 if (mode != oldMode) { 7508 // If we're moving between AUTO and another state, we might not need 7509 // to send a subtree changed notification. We'll store the computed 7510 // importance, since we'll need to check it later to make sure. 7511 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7512 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7513 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7514 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7515 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7516 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7517 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7518 notifySubtreeAccessibilityStateChangedIfNeeded(); 7519 } else { 7520 notifyViewAccessibilityStateChangedIfNeeded( 7521 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7522 } 7523 } 7524 } 7525 7526 /** 7527 * Computes whether this view should be exposed for accessibility. In 7528 * general, views that are interactive or provide information are exposed 7529 * while views that serve only as containers are hidden. 7530 * <p> 7531 * If an ancestor of this view has importance 7532 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7533 * returns <code>false</code>. 7534 * <p> 7535 * Otherwise, the value is computed according to the view's 7536 * {@link #getImportantForAccessibility()} value: 7537 * <ol> 7538 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7539 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7540 * </code> 7541 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7542 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7543 * view satisfies any of the following: 7544 * <ul> 7545 * <li>Is actionable, e.g. {@link #isClickable()}, 7546 * {@link #isLongClickable()}, or {@link #isFocusable()} 7547 * <li>Has an {@link AccessibilityDelegate} 7548 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7549 * {@link OnKeyListener}, etc. 7550 * <li>Is an accessibility live region, e.g. 7551 * {@link #getAccessibilityLiveRegion()} is not 7552 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7553 * </ul> 7554 * </ol> 7555 * 7556 * @return Whether the view is exposed for accessibility. 7557 * @see #setImportantForAccessibility(int) 7558 * @see #getImportantForAccessibility() 7559 */ 7560 public boolean isImportantForAccessibility() { 7561 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7562 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7563 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7564 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7565 return false; 7566 } 7567 7568 // Check parent mode to ensure we're not hidden. 7569 ViewParent parent = mParent; 7570 while (parent instanceof View) { 7571 if (((View) parent).getImportantForAccessibility() 7572 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7573 return false; 7574 } 7575 parent = parent.getParent(); 7576 } 7577 7578 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7579 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7580 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7581 } 7582 7583 /** 7584 * Gets the parent for accessibility purposes. Note that the parent for 7585 * accessibility is not necessary the immediate parent. It is the first 7586 * predecessor that is important for accessibility. 7587 * 7588 * @return The parent for accessibility purposes. 7589 */ 7590 public ViewParent getParentForAccessibility() { 7591 if (mParent instanceof View) { 7592 View parentView = (View) mParent; 7593 if (parentView.includeForAccessibility()) { 7594 return mParent; 7595 } else { 7596 return mParent.getParentForAccessibility(); 7597 } 7598 } 7599 return null; 7600 } 7601 7602 /** 7603 * Adds the children of a given View for accessibility. Since some Views are 7604 * not important for accessibility the children for accessibility are not 7605 * necessarily direct children of the view, rather they are the first level of 7606 * descendants important for accessibility. 7607 * 7608 * @param children The list of children for accessibility. 7609 */ 7610 public void addChildrenForAccessibility(ArrayList<View> children) { 7611 7612 } 7613 7614 /** 7615 * Whether to regard this view for accessibility. A view is regarded for 7616 * accessibility if it is important for accessibility or the querying 7617 * accessibility service has explicitly requested that view not 7618 * important for accessibility are regarded. 7619 * 7620 * @return Whether to regard the view for accessibility. 7621 * 7622 * @hide 7623 */ 7624 public boolean includeForAccessibility() { 7625 if (mAttachInfo != null) { 7626 return (mAttachInfo.mAccessibilityFetchFlags 7627 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7628 || isImportantForAccessibility(); 7629 } 7630 return false; 7631 } 7632 7633 /** 7634 * Returns whether the View is considered actionable from 7635 * accessibility perspective. Such view are important for 7636 * accessibility. 7637 * 7638 * @return True if the view is actionable for accessibility. 7639 * 7640 * @hide 7641 */ 7642 public boolean isActionableForAccessibility() { 7643 return (isClickable() || isLongClickable() || isFocusable()); 7644 } 7645 7646 /** 7647 * Returns whether the View has registered callbacks which makes it 7648 * important for accessibility. 7649 * 7650 * @return True if the view is actionable for accessibility. 7651 */ 7652 private boolean hasListenersForAccessibility() { 7653 ListenerInfo info = getListenerInfo(); 7654 return mTouchDelegate != null || info.mOnKeyListener != null 7655 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7656 || info.mOnHoverListener != null || info.mOnDragListener != null; 7657 } 7658 7659 /** 7660 * Notifies that the accessibility state of this view changed. The change 7661 * is local to this view and does not represent structural changes such 7662 * as children and parent. For example, the view became focusable. The 7663 * notification is at at most once every 7664 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7665 * to avoid unnecessary load to the system. Also once a view has a pending 7666 * notification this method is a NOP until the notification has been sent. 7667 * 7668 * @hide 7669 */ 7670 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7671 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7672 return; 7673 } 7674 if (mSendViewStateChangedAccessibilityEvent == null) { 7675 mSendViewStateChangedAccessibilityEvent = 7676 new SendViewStateChangedAccessibilityEvent(); 7677 } 7678 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7679 } 7680 7681 /** 7682 * Notifies that the accessibility state of this view changed. The change 7683 * is *not* local to this view and does represent structural changes such 7684 * as children and parent. For example, the view size changed. The 7685 * notification is at at most once every 7686 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7687 * to avoid unnecessary load to the system. Also once a view has a pending 7688 * notification this method is a NOP until the notification has been sent. 7689 * 7690 * @hide 7691 */ 7692 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7693 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7694 return; 7695 } 7696 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7697 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7698 if (mParent != null) { 7699 try { 7700 mParent.notifySubtreeAccessibilityStateChanged( 7701 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7702 } catch (AbstractMethodError e) { 7703 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7704 " does not fully implement ViewParent", e); 7705 } 7706 } 7707 } 7708 } 7709 7710 /** 7711 * Reset the flag indicating the accessibility state of the subtree rooted 7712 * at this view changed. 7713 */ 7714 void resetSubtreeAccessibilityStateChanged() { 7715 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7716 } 7717 7718 /** 7719 * Performs the specified accessibility action on the view. For 7720 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7721 * <p> 7722 * If an {@link AccessibilityDelegate} has been specified via calling 7723 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7724 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7725 * is responsible for handling this call. 7726 * </p> 7727 * 7728 * @param action The action to perform. 7729 * @param arguments Optional action arguments. 7730 * @return Whether the action was performed. 7731 */ 7732 public boolean performAccessibilityAction(int action, Bundle arguments) { 7733 if (mAccessibilityDelegate != null) { 7734 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7735 } else { 7736 return performAccessibilityActionInternal(action, arguments); 7737 } 7738 } 7739 7740 /** 7741 * @see #performAccessibilityAction(int, Bundle) 7742 * 7743 * Note: Called from the default {@link AccessibilityDelegate}. 7744 */ 7745 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7746 switch (action) { 7747 case AccessibilityNodeInfo.ACTION_CLICK: { 7748 if (isClickable()) { 7749 performClick(); 7750 return true; 7751 } 7752 } break; 7753 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7754 if (isLongClickable()) { 7755 performLongClick(); 7756 return true; 7757 } 7758 } break; 7759 case AccessibilityNodeInfo.ACTION_FOCUS: { 7760 if (!hasFocus()) { 7761 // Get out of touch mode since accessibility 7762 // wants to move focus around. 7763 getViewRootImpl().ensureTouchMode(false); 7764 return requestFocus(); 7765 } 7766 } break; 7767 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7768 if (hasFocus()) { 7769 clearFocus(); 7770 return !isFocused(); 7771 } 7772 } break; 7773 case AccessibilityNodeInfo.ACTION_SELECT: { 7774 if (!isSelected()) { 7775 setSelected(true); 7776 return isSelected(); 7777 } 7778 } break; 7779 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7780 if (isSelected()) { 7781 setSelected(false); 7782 return !isSelected(); 7783 } 7784 } break; 7785 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7786 if (!isAccessibilityFocused()) { 7787 return requestAccessibilityFocus(); 7788 } 7789 } break; 7790 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7791 if (isAccessibilityFocused()) { 7792 clearAccessibilityFocus(); 7793 return true; 7794 } 7795 } break; 7796 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7797 if (arguments != null) { 7798 final int granularity = arguments.getInt( 7799 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7800 final boolean extendSelection = arguments.getBoolean( 7801 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7802 return traverseAtGranularity(granularity, true, extendSelection); 7803 } 7804 } break; 7805 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7806 if (arguments != null) { 7807 final int granularity = arguments.getInt( 7808 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7809 final boolean extendSelection = arguments.getBoolean( 7810 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7811 return traverseAtGranularity(granularity, false, extendSelection); 7812 } 7813 } break; 7814 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7815 CharSequence text = getIterableTextForAccessibility(); 7816 if (text == null) { 7817 return false; 7818 } 7819 final int start = (arguments != null) ? arguments.getInt( 7820 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7821 final int end = (arguments != null) ? arguments.getInt( 7822 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7823 // Only cursor position can be specified (selection length == 0) 7824 if ((getAccessibilitySelectionStart() != start 7825 || getAccessibilitySelectionEnd() != end) 7826 && (start == end)) { 7827 setAccessibilitySelection(start, end); 7828 notifyViewAccessibilityStateChangedIfNeeded( 7829 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7830 return true; 7831 } 7832 } break; 7833 } 7834 return false; 7835 } 7836 7837 private boolean traverseAtGranularity(int granularity, boolean forward, 7838 boolean extendSelection) { 7839 CharSequence text = getIterableTextForAccessibility(); 7840 if (text == null || text.length() == 0) { 7841 return false; 7842 } 7843 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7844 if (iterator == null) { 7845 return false; 7846 } 7847 int current = getAccessibilitySelectionEnd(); 7848 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7849 current = forward ? 0 : text.length(); 7850 } 7851 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7852 if (range == null) { 7853 return false; 7854 } 7855 final int segmentStart = range[0]; 7856 final int segmentEnd = range[1]; 7857 int selectionStart; 7858 int selectionEnd; 7859 if (extendSelection && isAccessibilitySelectionExtendable()) { 7860 selectionStart = getAccessibilitySelectionStart(); 7861 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7862 selectionStart = forward ? segmentStart : segmentEnd; 7863 } 7864 selectionEnd = forward ? segmentEnd : segmentStart; 7865 } else { 7866 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7867 } 7868 setAccessibilitySelection(selectionStart, selectionEnd); 7869 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7870 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7871 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7872 return true; 7873 } 7874 7875 /** 7876 * Gets the text reported for accessibility purposes. 7877 * 7878 * @return The accessibility text. 7879 * 7880 * @hide 7881 */ 7882 public CharSequence getIterableTextForAccessibility() { 7883 return getContentDescription(); 7884 } 7885 7886 /** 7887 * Gets whether accessibility selection can be extended. 7888 * 7889 * @return If selection is extensible. 7890 * 7891 * @hide 7892 */ 7893 public boolean isAccessibilitySelectionExtendable() { 7894 return false; 7895 } 7896 7897 /** 7898 * @hide 7899 */ 7900 public int getAccessibilitySelectionStart() { 7901 return mAccessibilityCursorPosition; 7902 } 7903 7904 /** 7905 * @hide 7906 */ 7907 public int getAccessibilitySelectionEnd() { 7908 return getAccessibilitySelectionStart(); 7909 } 7910 7911 /** 7912 * @hide 7913 */ 7914 public void setAccessibilitySelection(int start, int end) { 7915 if (start == end && end == mAccessibilityCursorPosition) { 7916 return; 7917 } 7918 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7919 mAccessibilityCursorPosition = start; 7920 } else { 7921 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7922 } 7923 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7924 } 7925 7926 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7927 int fromIndex, int toIndex) { 7928 if (mParent == null) { 7929 return; 7930 } 7931 AccessibilityEvent event = AccessibilityEvent.obtain( 7932 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7933 onInitializeAccessibilityEvent(event); 7934 onPopulateAccessibilityEvent(event); 7935 event.setFromIndex(fromIndex); 7936 event.setToIndex(toIndex); 7937 event.setAction(action); 7938 event.setMovementGranularity(granularity); 7939 mParent.requestSendAccessibilityEvent(this, event); 7940 } 7941 7942 /** 7943 * @hide 7944 */ 7945 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7946 switch (granularity) { 7947 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7948 CharSequence text = getIterableTextForAccessibility(); 7949 if (text != null && text.length() > 0) { 7950 CharacterTextSegmentIterator iterator = 7951 CharacterTextSegmentIterator.getInstance( 7952 mContext.getResources().getConfiguration().locale); 7953 iterator.initialize(text.toString()); 7954 return iterator; 7955 } 7956 } break; 7957 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7958 CharSequence text = getIterableTextForAccessibility(); 7959 if (text != null && text.length() > 0) { 7960 WordTextSegmentIterator iterator = 7961 WordTextSegmentIterator.getInstance( 7962 mContext.getResources().getConfiguration().locale); 7963 iterator.initialize(text.toString()); 7964 return iterator; 7965 } 7966 } break; 7967 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7968 CharSequence text = getIterableTextForAccessibility(); 7969 if (text != null && text.length() > 0) { 7970 ParagraphTextSegmentIterator iterator = 7971 ParagraphTextSegmentIterator.getInstance(); 7972 iterator.initialize(text.toString()); 7973 return iterator; 7974 } 7975 } break; 7976 } 7977 return null; 7978 } 7979 7980 /** 7981 * @hide 7982 */ 7983 public void dispatchStartTemporaryDetach() { 7984 onStartTemporaryDetach(); 7985 } 7986 7987 /** 7988 * This is called when a container is going to temporarily detach a child, with 7989 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7990 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7991 * {@link #onDetachedFromWindow()} when the container is done. 7992 */ 7993 public void onStartTemporaryDetach() { 7994 removeUnsetPressCallback(); 7995 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7996 } 7997 7998 /** 7999 * @hide 8000 */ 8001 public void dispatchFinishTemporaryDetach() { 8002 onFinishTemporaryDetach(); 8003 } 8004 8005 /** 8006 * Called after {@link #onStartTemporaryDetach} when the container is done 8007 * changing the view. 8008 */ 8009 public void onFinishTemporaryDetach() { 8010 } 8011 8012 /** 8013 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8014 * for this view's window. Returns null if the view is not currently attached 8015 * to the window. Normally you will not need to use this directly, but 8016 * just use the standard high-level event callbacks like 8017 * {@link #onKeyDown(int, KeyEvent)}. 8018 */ 8019 public KeyEvent.DispatcherState getKeyDispatcherState() { 8020 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8021 } 8022 8023 /** 8024 * Dispatch a key event before it is processed by any input method 8025 * associated with the view hierarchy. This can be used to intercept 8026 * key events in special situations before the IME consumes them; a 8027 * typical example would be handling the BACK key to update the application's 8028 * UI instead of allowing the IME to see it and close itself. 8029 * 8030 * @param event The key event to be dispatched. 8031 * @return True if the event was handled, false otherwise. 8032 */ 8033 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8034 return onKeyPreIme(event.getKeyCode(), event); 8035 } 8036 8037 /** 8038 * Dispatch a key event to the next view on the focus path. This path runs 8039 * from the top of the view tree down to the currently focused view. If this 8040 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8041 * the next node down the focus path. This method also fires any key 8042 * listeners. 8043 * 8044 * @param event The key event to be dispatched. 8045 * @return True if the event was handled, false otherwise. 8046 */ 8047 public boolean dispatchKeyEvent(KeyEvent event) { 8048 if (mInputEventConsistencyVerifier != null) { 8049 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8050 } 8051 8052 // Give any attached key listener a first crack at the event. 8053 //noinspection SimplifiableIfStatement 8054 ListenerInfo li = mListenerInfo; 8055 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8056 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8057 return true; 8058 } 8059 8060 if (event.dispatch(this, mAttachInfo != null 8061 ? mAttachInfo.mKeyDispatchState : null, this)) { 8062 return true; 8063 } 8064 8065 if (mInputEventConsistencyVerifier != null) { 8066 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8067 } 8068 return false; 8069 } 8070 8071 /** 8072 * Dispatches a key shortcut event. 8073 * 8074 * @param event The key event to be dispatched. 8075 * @return True if the event was handled by the view, false otherwise. 8076 */ 8077 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8078 return onKeyShortcut(event.getKeyCode(), event); 8079 } 8080 8081 /** 8082 * Pass the touch screen motion event down to the target view, or this 8083 * view if it is the target. 8084 * 8085 * @param event The motion event to be dispatched. 8086 * @return True if the event was handled by the view, false otherwise. 8087 */ 8088 public boolean dispatchTouchEvent(MotionEvent event) { 8089 boolean result = false; 8090 8091 if (mInputEventConsistencyVerifier != null) { 8092 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8093 } 8094 8095 final int actionMasked = event.getActionMasked(); 8096 if (actionMasked == MotionEvent.ACTION_DOWN) { 8097 // Defensive cleanup for new gesture 8098 stopNestedScroll(); 8099 } 8100 8101 if (onFilterTouchEventForSecurity(event)) { 8102 //noinspection SimplifiableIfStatement 8103 ListenerInfo li = mListenerInfo; 8104 if (li != null && li.mOnTouchListener != null 8105 && (mViewFlags & ENABLED_MASK) == ENABLED 8106 && li.mOnTouchListener.onTouch(this, event)) { 8107 result = true; 8108 } 8109 8110 if (!result && onTouchEvent(event)) { 8111 result = true; 8112 } 8113 } 8114 8115 if (!result && mInputEventConsistencyVerifier != null) { 8116 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8117 } 8118 8119 // Clean up after nested scrolls if this is the end of a gesture; 8120 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8121 // of the gesture. 8122 if (actionMasked == MotionEvent.ACTION_UP || 8123 actionMasked == MotionEvent.ACTION_CANCEL || 8124 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8125 stopNestedScroll(); 8126 } 8127 8128 return result; 8129 } 8130 8131 /** 8132 * Filter the touch event to apply security policies. 8133 * 8134 * @param event The motion event to be filtered. 8135 * @return True if the event should be dispatched, false if the event should be dropped. 8136 * 8137 * @see #getFilterTouchesWhenObscured 8138 */ 8139 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8140 //noinspection RedundantIfStatement 8141 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8142 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8143 // Window is obscured, drop this touch. 8144 return false; 8145 } 8146 return true; 8147 } 8148 8149 /** 8150 * Pass a trackball motion event down to the focused view. 8151 * 8152 * @param event The motion event to be dispatched. 8153 * @return True if the event was handled by the view, false otherwise. 8154 */ 8155 public boolean dispatchTrackballEvent(MotionEvent event) { 8156 if (mInputEventConsistencyVerifier != null) { 8157 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8158 } 8159 8160 return onTrackballEvent(event); 8161 } 8162 8163 /** 8164 * Dispatch a generic motion event. 8165 * <p> 8166 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8167 * are delivered to the view under the pointer. All other generic motion events are 8168 * delivered to the focused view. Hover events are handled specially and are delivered 8169 * to {@link #onHoverEvent(MotionEvent)}. 8170 * </p> 8171 * 8172 * @param event The motion event to be dispatched. 8173 * @return True if the event was handled by the view, false otherwise. 8174 */ 8175 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8176 if (mInputEventConsistencyVerifier != null) { 8177 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8178 } 8179 8180 final int source = event.getSource(); 8181 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8182 final int action = event.getAction(); 8183 if (action == MotionEvent.ACTION_HOVER_ENTER 8184 || action == MotionEvent.ACTION_HOVER_MOVE 8185 || action == MotionEvent.ACTION_HOVER_EXIT) { 8186 if (dispatchHoverEvent(event)) { 8187 return true; 8188 } 8189 } else if (dispatchGenericPointerEvent(event)) { 8190 return true; 8191 } 8192 } else if (dispatchGenericFocusedEvent(event)) { 8193 return true; 8194 } 8195 8196 if (dispatchGenericMotionEventInternal(event)) { 8197 return true; 8198 } 8199 8200 if (mInputEventConsistencyVerifier != null) { 8201 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8202 } 8203 return false; 8204 } 8205 8206 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8207 //noinspection SimplifiableIfStatement 8208 ListenerInfo li = mListenerInfo; 8209 if (li != null && li.mOnGenericMotionListener != null 8210 && (mViewFlags & ENABLED_MASK) == ENABLED 8211 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8212 return true; 8213 } 8214 8215 if (onGenericMotionEvent(event)) { 8216 return true; 8217 } 8218 8219 if (mInputEventConsistencyVerifier != null) { 8220 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8221 } 8222 return false; 8223 } 8224 8225 /** 8226 * Dispatch a hover event. 8227 * <p> 8228 * Do not call this method directly. 8229 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8230 * </p> 8231 * 8232 * @param event The motion event to be dispatched. 8233 * @return True if the event was handled by the view, false otherwise. 8234 */ 8235 protected boolean dispatchHoverEvent(MotionEvent event) { 8236 ListenerInfo li = mListenerInfo; 8237 //noinspection SimplifiableIfStatement 8238 if (li != null && li.mOnHoverListener != null 8239 && (mViewFlags & ENABLED_MASK) == ENABLED 8240 && li.mOnHoverListener.onHover(this, event)) { 8241 return true; 8242 } 8243 8244 return onHoverEvent(event); 8245 } 8246 8247 /** 8248 * Returns true if the view has a child to which it has recently sent 8249 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8250 * it does not have a hovered child, then it must be the innermost hovered view. 8251 * @hide 8252 */ 8253 protected boolean hasHoveredChild() { 8254 return false; 8255 } 8256 8257 /** 8258 * Dispatch a generic motion event to the view under the first pointer. 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 dispatchGenericPointerEvent(MotionEvent event) { 8268 return false; 8269 } 8270 8271 /** 8272 * Dispatch a generic motion event to the currently focused view. 8273 * <p> 8274 * Do not call this method directly. 8275 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8276 * </p> 8277 * 8278 * @param event The motion event to be dispatched. 8279 * @return True if the event was handled by the view, false otherwise. 8280 */ 8281 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8282 return false; 8283 } 8284 8285 /** 8286 * Dispatch a pointer event. 8287 * <p> 8288 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8289 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8290 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8291 * and should not be expected to handle other pointing device features. 8292 * </p> 8293 * 8294 * @param event The motion event to be dispatched. 8295 * @return True if the event was handled by the view, false otherwise. 8296 * @hide 8297 */ 8298 public final boolean dispatchPointerEvent(MotionEvent event) { 8299 if (event.isTouchEvent()) { 8300 return dispatchTouchEvent(event); 8301 } else { 8302 return dispatchGenericMotionEvent(event); 8303 } 8304 } 8305 8306 /** 8307 * Called when the window containing this view gains or loses window focus. 8308 * ViewGroups should override to route to their children. 8309 * 8310 * @param hasFocus True if the window containing this view now has focus, 8311 * false otherwise. 8312 */ 8313 public void dispatchWindowFocusChanged(boolean hasFocus) { 8314 onWindowFocusChanged(hasFocus); 8315 } 8316 8317 /** 8318 * Called when the window containing this view gains or loses focus. Note 8319 * that this is separate from view focus: to receive key events, both 8320 * your view and its window must have focus. If a window is displayed 8321 * on top of yours that takes input focus, then your own window will lose 8322 * focus but the view focus will remain unchanged. 8323 * 8324 * @param hasWindowFocus True if the window containing this view now has 8325 * focus, false otherwise. 8326 */ 8327 public void onWindowFocusChanged(boolean hasWindowFocus) { 8328 InputMethodManager imm = InputMethodManager.peekInstance(); 8329 if (!hasWindowFocus) { 8330 if (isPressed()) { 8331 setPressed(false); 8332 } 8333 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8334 imm.focusOut(this); 8335 } 8336 removeLongPressCallback(); 8337 removeTapCallback(); 8338 onFocusLost(); 8339 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8340 imm.focusIn(this); 8341 } 8342 refreshDrawableState(); 8343 } 8344 8345 /** 8346 * Returns true if this view is in a window that currently has window focus. 8347 * Note that this is not the same as the view itself having focus. 8348 * 8349 * @return True if this view is in a window that currently has window focus. 8350 */ 8351 public boolean hasWindowFocus() { 8352 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8353 } 8354 8355 /** 8356 * Dispatch a view visibility change down the view hierarchy. 8357 * ViewGroups should override to route to their children. 8358 * @param changedView The view whose visibility changed. Could be 'this' or 8359 * an ancestor view. 8360 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8361 * {@link #INVISIBLE} or {@link #GONE}. 8362 */ 8363 protected void dispatchVisibilityChanged(@NonNull View changedView, 8364 @Visibility int visibility) { 8365 onVisibilityChanged(changedView, visibility); 8366 } 8367 8368 /** 8369 * Called when the visibility of the view or an ancestor of the view is changed. 8370 * @param changedView The view whose visibility changed. Could be 'this' or 8371 * an ancestor view. 8372 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8373 * {@link #INVISIBLE} or {@link #GONE}. 8374 */ 8375 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8376 if (visibility == VISIBLE) { 8377 if (mAttachInfo != null) { 8378 initialAwakenScrollBars(); 8379 } else { 8380 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8381 } 8382 } 8383 } 8384 8385 /** 8386 * Dispatch a hint about whether this view is displayed. For instance, when 8387 * a View moves out of the screen, it might receives a display hint indicating 8388 * the view is not displayed. Applications should not <em>rely</em> on this hint 8389 * as there is no guarantee that they will receive one. 8390 * 8391 * @param hint A hint about whether or not this view is displayed: 8392 * {@link #VISIBLE} or {@link #INVISIBLE}. 8393 */ 8394 public void dispatchDisplayHint(@Visibility int hint) { 8395 onDisplayHint(hint); 8396 } 8397 8398 /** 8399 * Gives this view a hint about whether is displayed or not. For instance, when 8400 * a View moves out of the screen, it might receives a display hint indicating 8401 * the view is not displayed. Applications should not <em>rely</em> on this hint 8402 * as there is no guarantee that they will receive one. 8403 * 8404 * @param hint A hint about whether or not this view is displayed: 8405 * {@link #VISIBLE} or {@link #INVISIBLE}. 8406 */ 8407 protected void onDisplayHint(@Visibility int hint) { 8408 } 8409 8410 /** 8411 * Dispatch a window visibility change down the view hierarchy. 8412 * ViewGroups should override to route to their children. 8413 * 8414 * @param visibility The new visibility of the window. 8415 * 8416 * @see #onWindowVisibilityChanged(int) 8417 */ 8418 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8419 onWindowVisibilityChanged(visibility); 8420 } 8421 8422 /** 8423 * Called when the window containing has change its visibility 8424 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8425 * that this tells you whether or not your window is being made visible 8426 * to the window manager; this does <em>not</em> tell you whether or not 8427 * your window is obscured by other windows on the screen, even if it 8428 * is itself visible. 8429 * 8430 * @param visibility The new visibility of the window. 8431 */ 8432 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8433 if (visibility == VISIBLE) { 8434 initialAwakenScrollBars(); 8435 } 8436 } 8437 8438 /** 8439 * Returns the current visibility of the window this view is attached to 8440 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8441 * 8442 * @return Returns the current visibility of the view's window. 8443 */ 8444 @Visibility 8445 public int getWindowVisibility() { 8446 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8447 } 8448 8449 /** 8450 * Retrieve the overall visible display size in which the window this view is 8451 * attached to has been positioned in. This takes into account screen 8452 * decorations above the window, for both cases where the window itself 8453 * is being position inside of them or the window is being placed under 8454 * then and covered insets are used for the window to position its content 8455 * inside. In effect, this tells you the available area where content can 8456 * be placed and remain visible to users. 8457 * 8458 * <p>This function requires an IPC back to the window manager to retrieve 8459 * the requested information, so should not be used in performance critical 8460 * code like drawing. 8461 * 8462 * @param outRect Filled in with the visible display frame. If the view 8463 * is not attached to a window, this is simply the raw display size. 8464 */ 8465 public void getWindowVisibleDisplayFrame(Rect outRect) { 8466 if (mAttachInfo != null) { 8467 try { 8468 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8469 } catch (RemoteException e) { 8470 return; 8471 } 8472 // XXX This is really broken, and probably all needs to be done 8473 // in the window manager, and we need to know more about whether 8474 // we want the area behind or in front of the IME. 8475 final Rect insets = mAttachInfo.mVisibleInsets; 8476 outRect.left += insets.left; 8477 outRect.top += insets.top; 8478 outRect.right -= insets.right; 8479 outRect.bottom -= insets.bottom; 8480 return; 8481 } 8482 // The view is not attached to a display so we don't have a context. 8483 // Make a best guess about the display size. 8484 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8485 d.getRectSize(outRect); 8486 } 8487 8488 /** 8489 * Dispatch a notification about a resource configuration change down 8490 * the view hierarchy. 8491 * ViewGroups should override to route to their children. 8492 * 8493 * @param newConfig The new resource configuration. 8494 * 8495 * @see #onConfigurationChanged(android.content.res.Configuration) 8496 */ 8497 public void dispatchConfigurationChanged(Configuration newConfig) { 8498 onConfigurationChanged(newConfig); 8499 } 8500 8501 /** 8502 * Called when the current configuration of the resources being used 8503 * by the application have changed. You can use this to decide when 8504 * to reload resources that can changed based on orientation and other 8505 * configuration characterstics. You only need to use this if you are 8506 * not relying on the normal {@link android.app.Activity} mechanism of 8507 * recreating the activity instance upon a configuration change. 8508 * 8509 * @param newConfig The new resource configuration. 8510 */ 8511 protected void onConfigurationChanged(Configuration newConfig) { 8512 } 8513 8514 /** 8515 * Private function to aggregate all per-view attributes in to the view 8516 * root. 8517 */ 8518 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8519 performCollectViewAttributes(attachInfo, visibility); 8520 } 8521 8522 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8523 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8524 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8525 attachInfo.mKeepScreenOn = true; 8526 } 8527 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8528 ListenerInfo li = mListenerInfo; 8529 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8530 attachInfo.mHasSystemUiListeners = true; 8531 } 8532 } 8533 } 8534 8535 void needGlobalAttributesUpdate(boolean force) { 8536 final AttachInfo ai = mAttachInfo; 8537 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8538 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8539 || ai.mHasSystemUiListeners) { 8540 ai.mRecomputeGlobalAttributes = true; 8541 } 8542 } 8543 } 8544 8545 /** 8546 * Returns whether the device is currently in touch mode. Touch mode is entered 8547 * once the user begins interacting with the device by touch, and affects various 8548 * things like whether focus is always visible to the user. 8549 * 8550 * @return Whether the device is in touch mode. 8551 */ 8552 @ViewDebug.ExportedProperty 8553 public boolean isInTouchMode() { 8554 if (mAttachInfo != null) { 8555 return mAttachInfo.mInTouchMode; 8556 } else { 8557 return ViewRootImpl.isInTouchMode(); 8558 } 8559 } 8560 8561 /** 8562 * Returns the context the view is running in, through which it can 8563 * access the current theme, resources, etc. 8564 * 8565 * @return The view's Context. 8566 */ 8567 @ViewDebug.CapturedViewProperty 8568 public final Context getContext() { 8569 return mContext; 8570 } 8571 8572 /** 8573 * Handle a key event before it is processed by any input method 8574 * associated with the view hierarchy. This can be used to intercept 8575 * key events in special situations before the IME consumes them; a 8576 * typical example would be handling the BACK key to update the application's 8577 * UI instead of allowing the IME to see it and close itself. 8578 * 8579 * @param keyCode The value in event.getKeyCode(). 8580 * @param event Description of the key event. 8581 * @return If you handled the event, return true. If you want to allow the 8582 * event to be handled by the next receiver, return false. 8583 */ 8584 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8585 return false; 8586 } 8587 8588 /** 8589 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8590 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8591 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8592 * is released, if the view is enabled and clickable. 8593 * 8594 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8595 * although some may elect to do so in some situations. Do not rely on this to 8596 * catch software key presses. 8597 * 8598 * @param keyCode A key code that represents the button pressed, from 8599 * {@link android.view.KeyEvent}. 8600 * @param event The KeyEvent object that defines the button action. 8601 */ 8602 public boolean onKeyDown(int keyCode, KeyEvent event) { 8603 boolean result = false; 8604 8605 if (KeyEvent.isConfirmKey(keyCode)) { 8606 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8607 return true; 8608 } 8609 // Long clickable items don't necessarily have to be clickable 8610 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8611 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8612 (event.getRepeatCount() == 0)) { 8613 setPressed(true); 8614 checkForLongClick(0); 8615 return true; 8616 } 8617 } 8618 return result; 8619 } 8620 8621 /** 8622 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8623 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8624 * the event). 8625 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8626 * although some may elect to do so in some situations. Do not rely on this to 8627 * catch software key presses. 8628 */ 8629 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8630 return false; 8631 } 8632 8633 /** 8634 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8635 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8636 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8637 * {@link KeyEvent#KEYCODE_ENTER} is released. 8638 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8639 * although some may elect to do so in some situations. Do not rely on this to 8640 * catch software key presses. 8641 * 8642 * @param keyCode A key code that represents the button pressed, from 8643 * {@link android.view.KeyEvent}. 8644 * @param event The KeyEvent object that defines the button action. 8645 */ 8646 public boolean onKeyUp(int keyCode, KeyEvent event) { 8647 if (KeyEvent.isConfirmKey(keyCode)) { 8648 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8649 return true; 8650 } 8651 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8652 setPressed(false); 8653 8654 if (!mHasPerformedLongPress) { 8655 // This is a tap, so remove the longpress check 8656 removeLongPressCallback(); 8657 return performClick(); 8658 } 8659 } 8660 } 8661 return false; 8662 } 8663 8664 /** 8665 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8666 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8667 * the event). 8668 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8669 * although some may elect to do so in some situations. Do not rely on this to 8670 * catch software key presses. 8671 * 8672 * @param keyCode A key code that represents the button pressed, from 8673 * {@link android.view.KeyEvent}. 8674 * @param repeatCount The number of times the action was made. 8675 * @param event The KeyEvent object that defines the button action. 8676 */ 8677 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8678 return false; 8679 } 8680 8681 /** 8682 * Called on the focused view when a key shortcut event is not handled. 8683 * Override this method to implement local key shortcuts for the View. 8684 * Key shortcuts can also be implemented by setting the 8685 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8686 * 8687 * @param keyCode The value in event.getKeyCode(). 8688 * @param event Description of the key event. 8689 * @return If you handled the event, return true. If you want to allow the 8690 * event to be handled by the next receiver, return false. 8691 */ 8692 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8693 return false; 8694 } 8695 8696 /** 8697 * Check whether the called view is a text editor, in which case it 8698 * would make sense to automatically display a soft input window for 8699 * it. Subclasses should override this if they implement 8700 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8701 * a call on that method would return a non-null InputConnection, and 8702 * they are really a first-class editor that the user would normally 8703 * start typing on when the go into a window containing your view. 8704 * 8705 * <p>The default implementation always returns false. This does 8706 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8707 * will not be called or the user can not otherwise perform edits on your 8708 * view; it is just a hint to the system that this is not the primary 8709 * purpose of this view. 8710 * 8711 * @return Returns true if this view is a text editor, else false. 8712 */ 8713 public boolean onCheckIsTextEditor() { 8714 return false; 8715 } 8716 8717 /** 8718 * Create a new InputConnection for an InputMethod to interact 8719 * with the view. The default implementation returns null, since it doesn't 8720 * support input methods. You can override this to implement such support. 8721 * This is only needed for views that take focus and text input. 8722 * 8723 * <p>When implementing this, you probably also want to implement 8724 * {@link #onCheckIsTextEditor()} to indicate you will return a 8725 * non-null InputConnection.</p> 8726 * 8727 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8728 * object correctly and in its entirety, so that the connected IME can rely 8729 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8730 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8731 * must be filled in with the correct cursor position for IMEs to work correctly 8732 * with your application.</p> 8733 * 8734 * @param outAttrs Fill in with attribute information about the connection. 8735 */ 8736 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8737 return null; 8738 } 8739 8740 /** 8741 * Called by the {@link android.view.inputmethod.InputMethodManager} 8742 * when a view who is not the current 8743 * input connection target is trying to make a call on the manager. The 8744 * default implementation returns false; you can override this to return 8745 * true for certain views if you are performing InputConnection proxying 8746 * to them. 8747 * @param view The View that is making the InputMethodManager call. 8748 * @return Return true to allow the call, false to reject. 8749 */ 8750 public boolean checkInputConnectionProxy(View view) { 8751 return false; 8752 } 8753 8754 /** 8755 * Show the context menu for this view. It is not safe to hold on to the 8756 * menu after returning from this method. 8757 * 8758 * You should normally not overload this method. Overload 8759 * {@link #onCreateContextMenu(ContextMenu)} or define an 8760 * {@link OnCreateContextMenuListener} to add items to the context menu. 8761 * 8762 * @param menu The context menu to populate 8763 */ 8764 public void createContextMenu(ContextMenu menu) { 8765 ContextMenuInfo menuInfo = getContextMenuInfo(); 8766 8767 // Sets the current menu info so all items added to menu will have 8768 // my extra info set. 8769 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8770 8771 onCreateContextMenu(menu); 8772 ListenerInfo li = mListenerInfo; 8773 if (li != null && li.mOnCreateContextMenuListener != null) { 8774 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8775 } 8776 8777 // Clear the extra information so subsequent items that aren't mine don't 8778 // have my extra info. 8779 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8780 8781 if (mParent != null) { 8782 mParent.createContextMenu(menu); 8783 } 8784 } 8785 8786 /** 8787 * Views should implement this if they have extra information to associate 8788 * with the context menu. The return result is supplied as a parameter to 8789 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8790 * callback. 8791 * 8792 * @return Extra information about the item for which the context menu 8793 * should be shown. This information will vary across different 8794 * subclasses of View. 8795 */ 8796 protected ContextMenuInfo getContextMenuInfo() { 8797 return null; 8798 } 8799 8800 /** 8801 * Views should implement this if the view itself is going to add items to 8802 * the context menu. 8803 * 8804 * @param menu the context menu to populate 8805 */ 8806 protected void onCreateContextMenu(ContextMenu menu) { 8807 } 8808 8809 /** 8810 * Implement this method to handle trackball motion events. The 8811 * <em>relative</em> movement of the trackball since the last event 8812 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8813 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8814 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8815 * they will often be fractional values, representing the more fine-grained 8816 * movement information available from a trackball). 8817 * 8818 * @param event The motion event. 8819 * @return True if the event was handled, false otherwise. 8820 */ 8821 public boolean onTrackballEvent(MotionEvent event) { 8822 return false; 8823 } 8824 8825 /** 8826 * Implement this method to handle generic motion events. 8827 * <p> 8828 * Generic motion events describe joystick movements, mouse hovers, track pad 8829 * touches, scroll wheel movements and other input events. The 8830 * {@link MotionEvent#getSource() source} of the motion event specifies 8831 * the class of input that was received. Implementations of this method 8832 * must examine the bits in the source before processing the event. 8833 * The following code example shows how this is done. 8834 * </p><p> 8835 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8836 * are delivered to the view under the pointer. All other generic motion events are 8837 * delivered to the focused view. 8838 * </p> 8839 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8840 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8841 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8842 * // process the joystick movement... 8843 * return true; 8844 * } 8845 * } 8846 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8847 * switch (event.getAction()) { 8848 * case MotionEvent.ACTION_HOVER_MOVE: 8849 * // process the mouse hover movement... 8850 * return true; 8851 * case MotionEvent.ACTION_SCROLL: 8852 * // process the scroll wheel movement... 8853 * return true; 8854 * } 8855 * } 8856 * return super.onGenericMotionEvent(event); 8857 * }</pre> 8858 * 8859 * @param event The generic motion event being processed. 8860 * @return True if the event was handled, false otherwise. 8861 */ 8862 public boolean onGenericMotionEvent(MotionEvent event) { 8863 return false; 8864 } 8865 8866 /** 8867 * Implement this method to handle hover events. 8868 * <p> 8869 * This method is called whenever a pointer is hovering into, over, or out of the 8870 * bounds of a view and the view is not currently being touched. 8871 * Hover events are represented as pointer events with action 8872 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8873 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8874 * </p> 8875 * <ul> 8876 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8877 * when the pointer enters the bounds of the view.</li> 8878 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8879 * when the pointer has already entered the bounds of the view and has moved.</li> 8880 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8881 * when the pointer has exited the bounds of the view or when the pointer is 8882 * about to go down due to a button click, tap, or similar user action that 8883 * causes the view to be touched.</li> 8884 * </ul> 8885 * <p> 8886 * The view should implement this method to return true to indicate that it is 8887 * handling the hover event, such as by changing its drawable state. 8888 * </p><p> 8889 * The default implementation calls {@link #setHovered} to update the hovered state 8890 * of the view when a hover enter or hover exit event is received, if the view 8891 * is enabled and is clickable. The default implementation also sends hover 8892 * accessibility events. 8893 * </p> 8894 * 8895 * @param event The motion event that describes the hover. 8896 * @return True if the view handled the hover event. 8897 * 8898 * @see #isHovered 8899 * @see #setHovered 8900 * @see #onHoverChanged 8901 */ 8902 public boolean onHoverEvent(MotionEvent event) { 8903 // The root view may receive hover (or touch) events that are outside the bounds of 8904 // the window. This code ensures that we only send accessibility events for 8905 // hovers that are actually within the bounds of the root view. 8906 final int action = event.getActionMasked(); 8907 if (!mSendingHoverAccessibilityEvents) { 8908 if ((action == MotionEvent.ACTION_HOVER_ENTER 8909 || action == MotionEvent.ACTION_HOVER_MOVE) 8910 && !hasHoveredChild() 8911 && pointInView(event.getX(), event.getY())) { 8912 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8913 mSendingHoverAccessibilityEvents = true; 8914 } 8915 } else { 8916 if (action == MotionEvent.ACTION_HOVER_EXIT 8917 || (action == MotionEvent.ACTION_MOVE 8918 && !pointInView(event.getX(), event.getY()))) { 8919 mSendingHoverAccessibilityEvents = false; 8920 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8921 } 8922 } 8923 8924 if (isHoverable()) { 8925 switch (action) { 8926 case MotionEvent.ACTION_HOVER_ENTER: 8927 setHovered(true); 8928 break; 8929 case MotionEvent.ACTION_HOVER_EXIT: 8930 setHovered(false); 8931 break; 8932 } 8933 8934 // Dispatch the event to onGenericMotionEvent before returning true. 8935 // This is to provide compatibility with existing applications that 8936 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8937 // break because of the new default handling for hoverable views 8938 // in onHoverEvent. 8939 // Note that onGenericMotionEvent will be called by default when 8940 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8941 dispatchGenericMotionEventInternal(event); 8942 // The event was already handled by calling setHovered(), so always 8943 // return true. 8944 return true; 8945 } 8946 8947 return false; 8948 } 8949 8950 /** 8951 * Returns true if the view should handle {@link #onHoverEvent} 8952 * by calling {@link #setHovered} to change its hovered state. 8953 * 8954 * @return True if the view is hoverable. 8955 */ 8956 private boolean isHoverable() { 8957 final int viewFlags = mViewFlags; 8958 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8959 return false; 8960 } 8961 8962 return (viewFlags & CLICKABLE) == CLICKABLE 8963 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8964 } 8965 8966 /** 8967 * Returns true if the view is currently hovered. 8968 * 8969 * @return True if the view is currently hovered. 8970 * 8971 * @see #setHovered 8972 * @see #onHoverChanged 8973 */ 8974 @ViewDebug.ExportedProperty 8975 public boolean isHovered() { 8976 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8977 } 8978 8979 /** 8980 * Sets whether the view is currently hovered. 8981 * <p> 8982 * Calling this method also changes the drawable state of the view. This 8983 * enables the view to react to hover by using different drawable resources 8984 * to change its appearance. 8985 * </p><p> 8986 * The {@link #onHoverChanged} method is called when the hovered state changes. 8987 * </p> 8988 * 8989 * @param hovered True if the view is hovered. 8990 * 8991 * @see #isHovered 8992 * @see #onHoverChanged 8993 */ 8994 public void setHovered(boolean hovered) { 8995 if (hovered) { 8996 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8997 mPrivateFlags |= PFLAG_HOVERED; 8998 refreshDrawableState(); 8999 onHoverChanged(true); 9000 } 9001 } else { 9002 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 9003 mPrivateFlags &= ~PFLAG_HOVERED; 9004 refreshDrawableState(); 9005 onHoverChanged(false); 9006 } 9007 } 9008 } 9009 9010 /** 9011 * Implement this method to handle hover state changes. 9012 * <p> 9013 * This method is called whenever the hover state changes as a result of a 9014 * call to {@link #setHovered}. 9015 * </p> 9016 * 9017 * @param hovered The current hover state, as returned by {@link #isHovered}. 9018 * 9019 * @see #isHovered 9020 * @see #setHovered 9021 */ 9022 public void onHoverChanged(boolean hovered) { 9023 } 9024 9025 /** 9026 * Implement this method to handle touch screen motion events. 9027 * <p> 9028 * If this method is used to detect click actions, it is recommended that 9029 * the actions be performed by implementing and calling 9030 * {@link #performClick()}. This will ensure consistent system behavior, 9031 * including: 9032 * <ul> 9033 * <li>obeying click sound preferences 9034 * <li>dispatching OnClickListener calls 9035 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9036 * accessibility features are enabled 9037 * </ul> 9038 * 9039 * @param event The motion event. 9040 * @return True if the event was handled, false otherwise. 9041 */ 9042 public boolean onTouchEvent(MotionEvent event) { 9043 final float x = event.getX(); 9044 final float y = event.getY(); 9045 final int viewFlags = mViewFlags; 9046 9047 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9048 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9049 setPressed(false); 9050 } 9051 // A disabled view that is clickable still consumes the touch 9052 // events, it just doesn't respond to them. 9053 return (((viewFlags & CLICKABLE) == CLICKABLE || 9054 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9055 } 9056 9057 if (mTouchDelegate != null) { 9058 if (mTouchDelegate.onTouchEvent(event)) { 9059 return true; 9060 } 9061 } 9062 9063 if (((viewFlags & CLICKABLE) == CLICKABLE || 9064 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9065 switch (event.getAction()) { 9066 case MotionEvent.ACTION_UP: 9067 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9068 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9069 // take focus if we don't have it already and we should in 9070 // touch mode. 9071 boolean focusTaken = false; 9072 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9073 focusTaken = requestFocus(); 9074 } 9075 9076 if (prepressed) { 9077 // The button is being released before we actually 9078 // showed it as pressed. Make it show the pressed 9079 // state now (before scheduling the click) to ensure 9080 // the user sees it. 9081 setPressed(true, x, y); 9082 } 9083 9084 if (!mHasPerformedLongPress) { 9085 // This is a tap, so remove the longpress check 9086 removeLongPressCallback(); 9087 9088 // Only perform take click actions if we were in the pressed state 9089 if (!focusTaken) { 9090 // Use a Runnable and post this rather than calling 9091 // performClick directly. This lets other visual state 9092 // of the view update before click actions start. 9093 if (mPerformClick == null) { 9094 mPerformClick = new PerformClick(); 9095 } 9096 if (!post(mPerformClick)) { 9097 performClick(); 9098 } 9099 } 9100 } 9101 9102 if (mUnsetPressedState == null) { 9103 mUnsetPressedState = new UnsetPressedState(); 9104 } 9105 9106 if (prepressed) { 9107 postDelayed(mUnsetPressedState, 9108 ViewConfiguration.getPressedStateDuration()); 9109 } else if (!post(mUnsetPressedState)) { 9110 // If the post failed, unpress right now 9111 mUnsetPressedState.run(); 9112 } 9113 9114 removeTapCallback(); 9115 } 9116 break; 9117 9118 case MotionEvent.ACTION_DOWN: 9119 mHasPerformedLongPress = false; 9120 9121 if (performButtonActionOnTouchDown(event)) { 9122 break; 9123 } 9124 9125 // Walk up the hierarchy to determine if we're inside a scrolling container. 9126 boolean isInScrollingContainer = isInScrollingContainer(); 9127 9128 // For views inside a scrolling container, delay the pressed feedback for 9129 // a short period in case this is a scroll. 9130 if (isInScrollingContainer) { 9131 mPrivateFlags |= PFLAG_PREPRESSED; 9132 if (mPendingCheckForTap == null) { 9133 mPendingCheckForTap = new CheckForTap(); 9134 } 9135 mPendingCheckForTap.x = event.getX(); 9136 mPendingCheckForTap.y = event.getY(); 9137 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9138 } else { 9139 // Not inside a scrolling container, so show the feedback right away 9140 setPressed(true, x, y); 9141 checkForLongClick(0); 9142 } 9143 break; 9144 9145 case MotionEvent.ACTION_CANCEL: 9146 setPressed(false); 9147 removeTapCallback(); 9148 removeLongPressCallback(); 9149 break; 9150 9151 case MotionEvent.ACTION_MOVE: 9152 setDrawableHotspot(x, y); 9153 9154 // Be lenient about moving outside of buttons 9155 if (!pointInView(x, y, mTouchSlop)) { 9156 // Outside button 9157 removeTapCallback(); 9158 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9159 // Remove any future long press/tap checks 9160 removeLongPressCallback(); 9161 9162 setPressed(false); 9163 } 9164 } 9165 break; 9166 } 9167 9168 return true; 9169 } 9170 9171 return false; 9172 } 9173 9174 /** 9175 * @hide 9176 */ 9177 public boolean isInScrollingContainer() { 9178 ViewParent p = getParent(); 9179 while (p != null && p instanceof ViewGroup) { 9180 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9181 return true; 9182 } 9183 p = p.getParent(); 9184 } 9185 return false; 9186 } 9187 9188 /** 9189 * Remove the longpress detection timer. 9190 */ 9191 private void removeLongPressCallback() { 9192 if (mPendingCheckForLongPress != null) { 9193 removeCallbacks(mPendingCheckForLongPress); 9194 } 9195 } 9196 9197 /** 9198 * Remove the pending click action 9199 */ 9200 private void removePerformClickCallback() { 9201 if (mPerformClick != null) { 9202 removeCallbacks(mPerformClick); 9203 } 9204 } 9205 9206 /** 9207 * Remove the prepress detection timer. 9208 */ 9209 private void removeUnsetPressCallback() { 9210 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9211 setPressed(false); 9212 removeCallbacks(mUnsetPressedState); 9213 } 9214 } 9215 9216 /** 9217 * Remove the tap detection timer. 9218 */ 9219 private void removeTapCallback() { 9220 if (mPendingCheckForTap != null) { 9221 mPrivateFlags &= ~PFLAG_PREPRESSED; 9222 removeCallbacks(mPendingCheckForTap); 9223 } 9224 } 9225 9226 /** 9227 * Cancels a pending long press. Your subclass can use this if you 9228 * want the context menu to come up if the user presses and holds 9229 * at the same place, but you don't want it to come up if they press 9230 * and then move around enough to cause scrolling. 9231 */ 9232 public void cancelLongPress() { 9233 removeLongPressCallback(); 9234 9235 /* 9236 * The prepressed state handled by the tap callback is a display 9237 * construct, but the tap callback will post a long press callback 9238 * less its own timeout. Remove it here. 9239 */ 9240 removeTapCallback(); 9241 } 9242 9243 /** 9244 * Remove the pending callback for sending a 9245 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9246 */ 9247 private void removeSendViewScrolledAccessibilityEventCallback() { 9248 if (mSendViewScrolledAccessibilityEvent != null) { 9249 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9250 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9251 } 9252 } 9253 9254 /** 9255 * Sets the TouchDelegate for this View. 9256 */ 9257 public void setTouchDelegate(TouchDelegate delegate) { 9258 mTouchDelegate = delegate; 9259 } 9260 9261 /** 9262 * Gets the TouchDelegate for this View. 9263 */ 9264 public TouchDelegate getTouchDelegate() { 9265 return mTouchDelegate; 9266 } 9267 9268 /** 9269 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9270 * 9271 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9272 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9273 * available. This method should only be called for touch events. 9274 * 9275 * <p class="note">This api is not intended for most applications. Buffered dispatch 9276 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9277 * streams will not improve your input latency. Side effects include: increased latency, 9278 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9279 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9280 * you.</p> 9281 */ 9282 public final void requestUnbufferedDispatch(MotionEvent event) { 9283 final int action = event.getAction(); 9284 if (mAttachInfo == null 9285 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9286 || !event.isTouchEvent()) { 9287 return; 9288 } 9289 mAttachInfo.mUnbufferedDispatchRequested = true; 9290 } 9291 9292 /** 9293 * Set flags controlling behavior of this view. 9294 * 9295 * @param flags Constant indicating the value which should be set 9296 * @param mask Constant indicating the bit range that should be changed 9297 */ 9298 void setFlags(int flags, int mask) { 9299 final boolean accessibilityEnabled = 9300 AccessibilityManager.getInstance(mContext).isEnabled(); 9301 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9302 9303 int old = mViewFlags; 9304 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9305 9306 int changed = mViewFlags ^ old; 9307 if (changed == 0) { 9308 return; 9309 } 9310 int privateFlags = mPrivateFlags; 9311 9312 /* Check if the FOCUSABLE bit has changed */ 9313 if (((changed & FOCUSABLE_MASK) != 0) && 9314 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9315 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9316 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9317 /* Give up focus if we are no longer focusable */ 9318 clearFocus(); 9319 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9320 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9321 /* 9322 * Tell the view system that we are now available to take focus 9323 * if no one else already has it. 9324 */ 9325 if (mParent != null) mParent.focusableViewAvailable(this); 9326 } 9327 } 9328 9329 final int newVisibility = flags & VISIBILITY_MASK; 9330 if (newVisibility == VISIBLE) { 9331 if ((changed & VISIBILITY_MASK) != 0) { 9332 /* 9333 * If this view is becoming visible, invalidate it in case it changed while 9334 * it was not visible. Marking it drawn ensures that the invalidation will 9335 * go through. 9336 */ 9337 mPrivateFlags |= PFLAG_DRAWN; 9338 invalidate(true); 9339 9340 needGlobalAttributesUpdate(true); 9341 9342 // a view becoming visible is worth notifying the parent 9343 // about in case nothing has focus. even if this specific view 9344 // isn't focusable, it may contain something that is, so let 9345 // the root view try to give this focus if nothing else does. 9346 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9347 mParent.focusableViewAvailable(this); 9348 } 9349 } 9350 } 9351 9352 /* Check if the GONE bit has changed */ 9353 if ((changed & GONE) != 0) { 9354 needGlobalAttributesUpdate(false); 9355 requestLayout(); 9356 9357 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9358 if (hasFocus()) clearFocus(); 9359 clearAccessibilityFocus(); 9360 destroyDrawingCache(); 9361 if (mParent instanceof View) { 9362 // GONE views noop invalidation, so invalidate the parent 9363 ((View) mParent).invalidate(true); 9364 } 9365 // Mark the view drawn to ensure that it gets invalidated properly the next 9366 // time it is visible and gets invalidated 9367 mPrivateFlags |= PFLAG_DRAWN; 9368 } 9369 if (mAttachInfo != null) { 9370 mAttachInfo.mViewVisibilityChanged = true; 9371 } 9372 } 9373 9374 /* Check if the VISIBLE bit has changed */ 9375 if ((changed & INVISIBLE) != 0) { 9376 needGlobalAttributesUpdate(false); 9377 /* 9378 * If this view is becoming invisible, set the DRAWN flag so that 9379 * the next invalidate() will not be skipped. 9380 */ 9381 mPrivateFlags |= PFLAG_DRAWN; 9382 9383 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9384 // root view becoming invisible shouldn't clear focus and accessibility focus 9385 if (getRootView() != this) { 9386 if (hasFocus()) clearFocus(); 9387 clearAccessibilityFocus(); 9388 } 9389 } 9390 if (mAttachInfo != null) { 9391 mAttachInfo.mViewVisibilityChanged = true; 9392 } 9393 } 9394 9395 if ((changed & VISIBILITY_MASK) != 0) { 9396 // If the view is invisible, cleanup its display list to free up resources 9397 if (newVisibility != VISIBLE && mAttachInfo != null) { 9398 cleanupDraw(); 9399 } 9400 9401 if (mParent instanceof ViewGroup) { 9402 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9403 (changed & VISIBILITY_MASK), newVisibility); 9404 ((View) mParent).invalidate(true); 9405 } else if (mParent != null) { 9406 mParent.invalidateChild(this, null); 9407 } 9408 dispatchVisibilityChanged(this, newVisibility); 9409 9410 notifySubtreeAccessibilityStateChangedIfNeeded(); 9411 } 9412 9413 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9414 destroyDrawingCache(); 9415 } 9416 9417 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9418 destroyDrawingCache(); 9419 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9420 invalidateParentCaches(); 9421 } 9422 9423 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9424 destroyDrawingCache(); 9425 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9426 } 9427 9428 if ((changed & DRAW_MASK) != 0) { 9429 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9430 if (mBackground != null) { 9431 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9432 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9433 } else { 9434 mPrivateFlags |= PFLAG_SKIP_DRAW; 9435 } 9436 } else { 9437 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9438 } 9439 requestLayout(); 9440 invalidate(true); 9441 } 9442 9443 if ((changed & KEEP_SCREEN_ON) != 0) { 9444 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9445 mParent.recomputeViewAttributes(this); 9446 } 9447 } 9448 9449 if (accessibilityEnabled) { 9450 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9451 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9452 if (oldIncludeForAccessibility != includeForAccessibility()) { 9453 notifySubtreeAccessibilityStateChangedIfNeeded(); 9454 } else { 9455 notifyViewAccessibilityStateChangedIfNeeded( 9456 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9457 } 9458 } else if ((changed & ENABLED_MASK) != 0) { 9459 notifyViewAccessibilityStateChangedIfNeeded( 9460 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9461 } 9462 } 9463 } 9464 9465 /** 9466 * Change the view's z order in the tree, so it's on top of other sibling 9467 * views. This ordering change may affect layout, if the parent container 9468 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9469 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9470 * method should be followed by calls to {@link #requestLayout()} and 9471 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9472 * with the new child ordering. 9473 * 9474 * @see ViewGroup#bringChildToFront(View) 9475 */ 9476 public void bringToFront() { 9477 if (mParent != null) { 9478 mParent.bringChildToFront(this); 9479 } 9480 } 9481 9482 /** 9483 * This is called in response to an internal scroll in this view (i.e., the 9484 * view scrolled its own contents). This is typically as a result of 9485 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9486 * called. 9487 * 9488 * @param l Current horizontal scroll origin. 9489 * @param t Current vertical scroll origin. 9490 * @param oldl Previous horizontal scroll origin. 9491 * @param oldt Previous vertical scroll origin. 9492 */ 9493 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9494 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9495 postSendViewScrolledAccessibilityEventCallback(); 9496 } 9497 9498 mBackgroundSizeChanged = true; 9499 9500 final AttachInfo ai = mAttachInfo; 9501 if (ai != null) { 9502 ai.mViewScrollChanged = true; 9503 } 9504 } 9505 9506 /** 9507 * Interface definition for a callback to be invoked when the layout bounds of a view 9508 * changes due to layout processing. 9509 */ 9510 public interface OnLayoutChangeListener { 9511 /** 9512 * Called when the layout bounds of a view changes due to layout processing. 9513 * 9514 * @param v The view whose bounds have changed. 9515 * @param left The new value of the view's left property. 9516 * @param top The new value of the view's top property. 9517 * @param right The new value of the view's right property. 9518 * @param bottom The new value of the view's bottom property. 9519 * @param oldLeft The previous value of the view's left property. 9520 * @param oldTop The previous value of the view's top property. 9521 * @param oldRight The previous value of the view's right property. 9522 * @param oldBottom The previous value of the view's bottom property. 9523 */ 9524 void onLayoutChange(View v, int left, int top, int right, int bottom, 9525 int oldLeft, int oldTop, int oldRight, int oldBottom); 9526 } 9527 9528 /** 9529 * This is called during layout when the size of this view has changed. If 9530 * you were just added to the view hierarchy, you're called with the old 9531 * values of 0. 9532 * 9533 * @param w Current width of this view. 9534 * @param h Current height of this view. 9535 * @param oldw Old width of this view. 9536 * @param oldh Old height of this view. 9537 */ 9538 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9539 } 9540 9541 /** 9542 * Called by draw to draw the child views. This may be overridden 9543 * by derived classes to gain control just before its children are drawn 9544 * (but after its own view has been drawn). 9545 * @param canvas the canvas on which to draw the view 9546 */ 9547 protected void dispatchDraw(Canvas canvas) { 9548 9549 } 9550 9551 /** 9552 * Gets the parent of this view. Note that the parent is a 9553 * ViewParent and not necessarily a View. 9554 * 9555 * @return Parent of this view. 9556 */ 9557 public final ViewParent getParent() { 9558 return mParent; 9559 } 9560 9561 /** 9562 * Set the horizontal scrolled position of your view. This will cause a call to 9563 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9564 * invalidated. 9565 * @param value the x position to scroll to 9566 */ 9567 public void setScrollX(int value) { 9568 scrollTo(value, mScrollY); 9569 } 9570 9571 /** 9572 * Set the vertical scrolled position of your view. This will cause a call to 9573 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9574 * invalidated. 9575 * @param value the y position to scroll to 9576 */ 9577 public void setScrollY(int value) { 9578 scrollTo(mScrollX, value); 9579 } 9580 9581 /** 9582 * Return the scrolled left position of this view. This is the left edge of 9583 * the displayed part of your view. You do not need to draw any pixels 9584 * farther left, since those are outside of the frame of your view on 9585 * screen. 9586 * 9587 * @return The left edge of the displayed part of your view, in pixels. 9588 */ 9589 public final int getScrollX() { 9590 return mScrollX; 9591 } 9592 9593 /** 9594 * Return the scrolled top position of this view. This is the top edge of 9595 * the displayed part of your view. You do not need to draw any pixels above 9596 * it, since those are outside of the frame of your view on screen. 9597 * 9598 * @return The top edge of the displayed part of your view, in pixels. 9599 */ 9600 public final int getScrollY() { 9601 return mScrollY; 9602 } 9603 9604 /** 9605 * Return the width of the your view. 9606 * 9607 * @return The width of your view, in pixels. 9608 */ 9609 @ViewDebug.ExportedProperty(category = "layout") 9610 public final int getWidth() { 9611 return mRight - mLeft; 9612 } 9613 9614 /** 9615 * Return the height of your view. 9616 * 9617 * @return The height of your view, in pixels. 9618 */ 9619 @ViewDebug.ExportedProperty(category = "layout") 9620 public final int getHeight() { 9621 return mBottom - mTop; 9622 } 9623 9624 /** 9625 * Return the visible drawing bounds of your view. Fills in the output 9626 * rectangle with the values from getScrollX(), getScrollY(), 9627 * getWidth(), and getHeight(). These bounds do not account for any 9628 * transformation properties currently set on the view, such as 9629 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9630 * 9631 * @param outRect The (scrolled) drawing bounds of the view. 9632 */ 9633 public void getDrawingRect(Rect outRect) { 9634 outRect.left = mScrollX; 9635 outRect.top = mScrollY; 9636 outRect.right = mScrollX + (mRight - mLeft); 9637 outRect.bottom = mScrollY + (mBottom - mTop); 9638 } 9639 9640 /** 9641 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9642 * raw width component (that is the result is masked by 9643 * {@link #MEASURED_SIZE_MASK}). 9644 * 9645 * @return The raw measured width of this view. 9646 */ 9647 public final int getMeasuredWidth() { 9648 return mMeasuredWidth & MEASURED_SIZE_MASK; 9649 } 9650 9651 /** 9652 * Return the full width measurement information for this view as computed 9653 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9654 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9655 * This should be used during measurement and layout calculations only. Use 9656 * {@link #getWidth()} to see how wide a view is after layout. 9657 * 9658 * @return The measured width of this view as a bit mask. 9659 */ 9660 public final int getMeasuredWidthAndState() { 9661 return mMeasuredWidth; 9662 } 9663 9664 /** 9665 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9666 * raw width component (that is the result is masked by 9667 * {@link #MEASURED_SIZE_MASK}). 9668 * 9669 * @return The raw measured height of this view. 9670 */ 9671 public final int getMeasuredHeight() { 9672 return mMeasuredHeight & MEASURED_SIZE_MASK; 9673 } 9674 9675 /** 9676 * Return the full height measurement information for this view as computed 9677 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9678 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9679 * This should be used during measurement and layout calculations only. Use 9680 * {@link #getHeight()} to see how wide a view is after layout. 9681 * 9682 * @return The measured width of this view as a bit mask. 9683 */ 9684 public final int getMeasuredHeightAndState() { 9685 return mMeasuredHeight; 9686 } 9687 9688 /** 9689 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9690 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9691 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9692 * and the height component is at the shifted bits 9693 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9694 */ 9695 public final int getMeasuredState() { 9696 return (mMeasuredWidth&MEASURED_STATE_MASK) 9697 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9698 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9699 } 9700 9701 /** 9702 * The transform matrix of this view, which is calculated based on the current 9703 * rotation, scale, and pivot properties. 9704 * 9705 * @see #getRotation() 9706 * @see #getScaleX() 9707 * @see #getScaleY() 9708 * @see #getPivotX() 9709 * @see #getPivotY() 9710 * @return The current transform matrix for the view 9711 */ 9712 public Matrix getMatrix() { 9713 ensureTransformationInfo(); 9714 final Matrix matrix = mTransformationInfo.mMatrix; 9715 mRenderNode.getMatrix(matrix); 9716 return matrix; 9717 } 9718 9719 /** 9720 * Returns true if the transform matrix is the identity matrix. 9721 * Recomputes the matrix if necessary. 9722 * 9723 * @return True if the transform matrix is the identity matrix, false otherwise. 9724 */ 9725 final boolean hasIdentityMatrix() { 9726 return mRenderNode.hasIdentityMatrix(); 9727 } 9728 9729 void ensureTransformationInfo() { 9730 if (mTransformationInfo == null) { 9731 mTransformationInfo = new TransformationInfo(); 9732 } 9733 } 9734 9735 /** 9736 * Utility method to retrieve the inverse of the current mMatrix property. 9737 * We cache the matrix to avoid recalculating it when transform properties 9738 * have not changed. 9739 * 9740 * @return The inverse of the current matrix of this view. 9741 */ 9742 final Matrix getInverseMatrix() { 9743 ensureTransformationInfo(); 9744 if (mTransformationInfo.mInverseMatrix == null) { 9745 mTransformationInfo.mInverseMatrix = new Matrix(); 9746 } 9747 final Matrix matrix = mTransformationInfo.mInverseMatrix; 9748 mRenderNode.getInverseMatrix(matrix); 9749 return matrix; 9750 } 9751 9752 /** 9753 * Gets the distance along the Z axis from the camera to this view. 9754 * 9755 * @see #setCameraDistance(float) 9756 * 9757 * @return The distance along the Z axis. 9758 */ 9759 public float getCameraDistance() { 9760 final float dpi = mResources.getDisplayMetrics().densityDpi; 9761 return -(mRenderNode.getCameraDistance() * dpi); 9762 } 9763 9764 /** 9765 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9766 * views are drawn) from the camera to this view. The camera's distance 9767 * affects 3D transformations, for instance rotations around the X and Y 9768 * axis. If the rotationX or rotationY properties are changed and this view is 9769 * large (more than half the size of the screen), it is recommended to always 9770 * use a camera distance that's greater than the height (X axis rotation) or 9771 * the width (Y axis rotation) of this view.</p> 9772 * 9773 * <p>The distance of the camera from the view plane can have an affect on the 9774 * perspective distortion of the view when it is rotated around the x or y axis. 9775 * For example, a large distance will result in a large viewing angle, and there 9776 * will not be much perspective distortion of the view as it rotates. A short 9777 * distance may cause much more perspective distortion upon rotation, and can 9778 * also result in some drawing artifacts if the rotated view ends up partially 9779 * behind the camera (which is why the recommendation is to use a distance at 9780 * least as far as the size of the view, if the view is to be rotated.)</p> 9781 * 9782 * <p>The distance is expressed in "depth pixels." The default distance depends 9783 * on the screen density. For instance, on a medium density display, the 9784 * default distance is 1280. On a high density display, the default distance 9785 * is 1920.</p> 9786 * 9787 * <p>If you want to specify a distance that leads to visually consistent 9788 * results across various densities, use the following formula:</p> 9789 * <pre> 9790 * float scale = context.getResources().getDisplayMetrics().density; 9791 * view.setCameraDistance(distance * scale); 9792 * </pre> 9793 * 9794 * <p>The density scale factor of a high density display is 1.5, 9795 * and 1920 = 1280 * 1.5.</p> 9796 * 9797 * @param distance The distance in "depth pixels", if negative the opposite 9798 * value is used 9799 * 9800 * @see #setRotationX(float) 9801 * @see #setRotationY(float) 9802 */ 9803 public void setCameraDistance(float distance) { 9804 final float dpi = mResources.getDisplayMetrics().densityDpi; 9805 9806 invalidateViewProperty(true, false); 9807 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 9808 invalidateViewProperty(false, false); 9809 9810 invalidateParentIfNeededAndWasQuickRejected(); 9811 } 9812 9813 /** 9814 * The degrees that the view is rotated around the pivot point. 9815 * 9816 * @see #setRotation(float) 9817 * @see #getPivotX() 9818 * @see #getPivotY() 9819 * 9820 * @return The degrees of rotation. 9821 */ 9822 @ViewDebug.ExportedProperty(category = "drawing") 9823 public float getRotation() { 9824 return mRenderNode.getRotation(); 9825 } 9826 9827 /** 9828 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9829 * result in clockwise rotation. 9830 * 9831 * @param rotation The degrees of rotation. 9832 * 9833 * @see #getRotation() 9834 * @see #getPivotX() 9835 * @see #getPivotY() 9836 * @see #setRotationX(float) 9837 * @see #setRotationY(float) 9838 * 9839 * @attr ref android.R.styleable#View_rotation 9840 */ 9841 public void setRotation(float rotation) { 9842 if (rotation != getRotation()) { 9843 // Double-invalidation is necessary to capture view's old and new areas 9844 invalidateViewProperty(true, false); 9845 mRenderNode.setRotation(rotation); 9846 invalidateViewProperty(false, true); 9847 9848 invalidateParentIfNeededAndWasQuickRejected(); 9849 notifySubtreeAccessibilityStateChangedIfNeeded(); 9850 } 9851 } 9852 9853 /** 9854 * The degrees that the view is rotated around the vertical axis through the pivot point. 9855 * 9856 * @see #getPivotX() 9857 * @see #getPivotY() 9858 * @see #setRotationY(float) 9859 * 9860 * @return The degrees of Y rotation. 9861 */ 9862 @ViewDebug.ExportedProperty(category = "drawing") 9863 public float getRotationY() { 9864 return mRenderNode.getRotationY(); 9865 } 9866 9867 /** 9868 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9869 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9870 * down the y axis. 9871 * 9872 * When rotating large views, it is recommended to adjust the camera distance 9873 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9874 * 9875 * @param rotationY The degrees of Y rotation. 9876 * 9877 * @see #getRotationY() 9878 * @see #getPivotX() 9879 * @see #getPivotY() 9880 * @see #setRotation(float) 9881 * @see #setRotationX(float) 9882 * @see #setCameraDistance(float) 9883 * 9884 * @attr ref android.R.styleable#View_rotationY 9885 */ 9886 public void setRotationY(float rotationY) { 9887 if (rotationY != getRotationY()) { 9888 invalidateViewProperty(true, false); 9889 mRenderNode.setRotationY(rotationY); 9890 invalidateViewProperty(false, true); 9891 9892 invalidateParentIfNeededAndWasQuickRejected(); 9893 notifySubtreeAccessibilityStateChangedIfNeeded(); 9894 } 9895 } 9896 9897 /** 9898 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9899 * 9900 * @see #getPivotX() 9901 * @see #getPivotY() 9902 * @see #setRotationX(float) 9903 * 9904 * @return The degrees of X rotation. 9905 */ 9906 @ViewDebug.ExportedProperty(category = "drawing") 9907 public float getRotationX() { 9908 return mRenderNode.getRotationX(); 9909 } 9910 9911 /** 9912 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9913 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9914 * x axis. 9915 * 9916 * When rotating large views, it is recommended to adjust the camera distance 9917 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9918 * 9919 * @param rotationX The degrees of X rotation. 9920 * 9921 * @see #getRotationX() 9922 * @see #getPivotX() 9923 * @see #getPivotY() 9924 * @see #setRotation(float) 9925 * @see #setRotationY(float) 9926 * @see #setCameraDistance(float) 9927 * 9928 * @attr ref android.R.styleable#View_rotationX 9929 */ 9930 public void setRotationX(float rotationX) { 9931 if (rotationX != getRotationX()) { 9932 invalidateViewProperty(true, false); 9933 mRenderNode.setRotationX(rotationX); 9934 invalidateViewProperty(false, true); 9935 9936 invalidateParentIfNeededAndWasQuickRejected(); 9937 notifySubtreeAccessibilityStateChangedIfNeeded(); 9938 } 9939 } 9940 9941 /** 9942 * The amount that the view is scaled in x around the pivot point, as a proportion of 9943 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9944 * 9945 * <p>By default, this is 1.0f. 9946 * 9947 * @see #getPivotX() 9948 * @see #getPivotY() 9949 * @return The scaling factor. 9950 */ 9951 @ViewDebug.ExportedProperty(category = "drawing") 9952 public float getScaleX() { 9953 return mRenderNode.getScaleX(); 9954 } 9955 9956 /** 9957 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9958 * the view's unscaled width. A value of 1 means that no scaling is applied. 9959 * 9960 * @param scaleX The scaling factor. 9961 * @see #getPivotX() 9962 * @see #getPivotY() 9963 * 9964 * @attr ref android.R.styleable#View_scaleX 9965 */ 9966 public void setScaleX(float scaleX) { 9967 if (scaleX != getScaleX()) { 9968 invalidateViewProperty(true, false); 9969 mRenderNode.setScaleX(scaleX); 9970 invalidateViewProperty(false, true); 9971 9972 invalidateParentIfNeededAndWasQuickRejected(); 9973 notifySubtreeAccessibilityStateChangedIfNeeded(); 9974 } 9975 } 9976 9977 /** 9978 * The amount that the view is scaled in y around the pivot point, as a proportion of 9979 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9980 * 9981 * <p>By default, this is 1.0f. 9982 * 9983 * @see #getPivotX() 9984 * @see #getPivotY() 9985 * @return The scaling factor. 9986 */ 9987 @ViewDebug.ExportedProperty(category = "drawing") 9988 public float getScaleY() { 9989 return mRenderNode.getScaleY(); 9990 } 9991 9992 /** 9993 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9994 * the view's unscaled width. A value of 1 means that no scaling is applied. 9995 * 9996 * @param scaleY The scaling factor. 9997 * @see #getPivotX() 9998 * @see #getPivotY() 9999 * 10000 * @attr ref android.R.styleable#View_scaleY 10001 */ 10002 public void setScaleY(float scaleY) { 10003 if (scaleY != getScaleY()) { 10004 invalidateViewProperty(true, false); 10005 mRenderNode.setScaleY(scaleY); 10006 invalidateViewProperty(false, true); 10007 10008 invalidateParentIfNeededAndWasQuickRejected(); 10009 notifySubtreeAccessibilityStateChangedIfNeeded(); 10010 } 10011 } 10012 10013 /** 10014 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10015 * and {@link #setScaleX(float) scaled}. 10016 * 10017 * @see #getRotation() 10018 * @see #getScaleX() 10019 * @see #getScaleY() 10020 * @see #getPivotY() 10021 * @return The x location of the pivot point. 10022 * 10023 * @attr ref android.R.styleable#View_transformPivotX 10024 */ 10025 @ViewDebug.ExportedProperty(category = "drawing") 10026 public float getPivotX() { 10027 return mRenderNode.getPivotX(); 10028 } 10029 10030 /** 10031 * Sets the x location of the point around which the view is 10032 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10033 * By default, the pivot point is centered on the object. 10034 * Setting this property disables this behavior and causes the view to use only the 10035 * explicitly set pivotX and pivotY values. 10036 * 10037 * @param pivotX The x location of the pivot point. 10038 * @see #getRotation() 10039 * @see #getScaleX() 10040 * @see #getScaleY() 10041 * @see #getPivotY() 10042 * 10043 * @attr ref android.R.styleable#View_transformPivotX 10044 */ 10045 public void setPivotX(float pivotX) { 10046 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10047 invalidateViewProperty(true, false); 10048 mRenderNode.setPivotX(pivotX); 10049 invalidateViewProperty(false, true); 10050 10051 invalidateParentIfNeededAndWasQuickRejected(); 10052 } 10053 } 10054 10055 /** 10056 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10057 * and {@link #setScaleY(float) scaled}. 10058 * 10059 * @see #getRotation() 10060 * @see #getScaleX() 10061 * @see #getScaleY() 10062 * @see #getPivotY() 10063 * @return The y location of the pivot point. 10064 * 10065 * @attr ref android.R.styleable#View_transformPivotY 10066 */ 10067 @ViewDebug.ExportedProperty(category = "drawing") 10068 public float getPivotY() { 10069 return mRenderNode.getPivotY(); 10070 } 10071 10072 /** 10073 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10074 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10075 * Setting this property disables this behavior and causes the view to use only the 10076 * explicitly set pivotX and pivotY values. 10077 * 10078 * @param pivotY The y location of the pivot point. 10079 * @see #getRotation() 10080 * @see #getScaleX() 10081 * @see #getScaleY() 10082 * @see #getPivotY() 10083 * 10084 * @attr ref android.R.styleable#View_transformPivotY 10085 */ 10086 public void setPivotY(float pivotY) { 10087 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10088 invalidateViewProperty(true, false); 10089 mRenderNode.setPivotY(pivotY); 10090 invalidateViewProperty(false, true); 10091 10092 invalidateParentIfNeededAndWasQuickRejected(); 10093 } 10094 } 10095 10096 /** 10097 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10098 * completely transparent and 1 means the view is completely opaque. 10099 * 10100 * <p>By default this is 1.0f. 10101 * @return The opacity of the view. 10102 */ 10103 @ViewDebug.ExportedProperty(category = "drawing") 10104 public float getAlpha() { 10105 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10106 } 10107 10108 /** 10109 * Returns whether this View has content which overlaps. 10110 * 10111 * <p>This function, intended to be overridden by specific View types, is an optimization when 10112 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10113 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10114 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10115 * directly. An example of overlapping rendering is a TextView with a background image, such as 10116 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10117 * ImageView with only the foreground image. The default implementation returns true; subclasses 10118 * should override if they have cases which can be optimized.</p> 10119 * 10120 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10121 * necessitates that a View return true if it uses the methods internally without passing the 10122 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10123 * 10124 * @return true if the content in this view might overlap, false otherwise. 10125 */ 10126 public boolean hasOverlappingRendering() { 10127 return true; 10128 } 10129 10130 /** 10131 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10132 * completely transparent and 1 means the view is completely opaque.</p> 10133 * 10134 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10135 * performance implications, especially for large views. It is best to use the alpha property 10136 * sparingly and transiently, as in the case of fading animations.</p> 10137 * 10138 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10139 * strongly recommended for performance reasons to either override 10140 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10141 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10142 * 10143 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10144 * responsible for applying the opacity itself.</p> 10145 * 10146 * <p>Note that if the view is backed by a 10147 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10148 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10149 * 1.0 will supercede the alpha of the layer paint.</p> 10150 * 10151 * @param alpha The opacity of the view. 10152 * 10153 * @see #hasOverlappingRendering() 10154 * @see #setLayerType(int, android.graphics.Paint) 10155 * 10156 * @attr ref android.R.styleable#View_alpha 10157 */ 10158 public void setAlpha(float alpha) { 10159 ensureTransformationInfo(); 10160 if (mTransformationInfo.mAlpha != alpha) { 10161 mTransformationInfo.mAlpha = alpha; 10162 if (onSetAlpha((int) (alpha * 255))) { 10163 mPrivateFlags |= PFLAG_ALPHA_SET; 10164 // subclass is handling alpha - don't optimize rendering cache invalidation 10165 invalidateParentCaches(); 10166 invalidate(true); 10167 } else { 10168 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10169 invalidateViewProperty(true, false); 10170 mRenderNode.setAlpha(getFinalAlpha()); 10171 notifyViewAccessibilityStateChangedIfNeeded( 10172 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10173 } 10174 } 10175 } 10176 10177 /** 10178 * Faster version of setAlpha() which performs the same steps except there are 10179 * no calls to invalidate(). The caller of this function should perform proper invalidation 10180 * on the parent and this object. The return value indicates whether the subclass handles 10181 * alpha (the return value for onSetAlpha()). 10182 * 10183 * @param alpha The new value for the alpha property 10184 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10185 * the new value for the alpha property is different from the old value 10186 */ 10187 boolean setAlphaNoInvalidation(float alpha) { 10188 ensureTransformationInfo(); 10189 if (mTransformationInfo.mAlpha != alpha) { 10190 mTransformationInfo.mAlpha = alpha; 10191 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10192 if (subclassHandlesAlpha) { 10193 mPrivateFlags |= PFLAG_ALPHA_SET; 10194 return true; 10195 } else { 10196 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10197 mRenderNode.setAlpha(getFinalAlpha()); 10198 } 10199 } 10200 return false; 10201 } 10202 10203 /** 10204 * This property is hidden and intended only for use by the Fade transition, which 10205 * animates it to produce a visual translucency that does not side-effect (or get 10206 * affected by) the real alpha property. This value is composited with the other 10207 * alpha value (and the AlphaAnimation value, when that is present) to produce 10208 * a final visual translucency result, which is what is passed into the DisplayList. 10209 * 10210 * @hide 10211 */ 10212 public void setTransitionAlpha(float alpha) { 10213 ensureTransformationInfo(); 10214 if (mTransformationInfo.mTransitionAlpha != alpha) { 10215 mTransformationInfo.mTransitionAlpha = alpha; 10216 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10217 invalidateViewProperty(true, false); 10218 mRenderNode.setAlpha(getFinalAlpha()); 10219 } 10220 } 10221 10222 /** 10223 * Calculates the visual alpha of this view, which is a combination of the actual 10224 * alpha value and the transitionAlpha value (if set). 10225 */ 10226 private float getFinalAlpha() { 10227 if (mTransformationInfo != null) { 10228 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10229 } 10230 return 1; 10231 } 10232 10233 /** 10234 * This property is hidden and intended only for use by the Fade transition, which 10235 * animates it to produce a visual translucency that does not side-effect (or get 10236 * affected by) the real alpha property. This value is composited with the other 10237 * alpha value (and the AlphaAnimation value, when that is present) to produce 10238 * a final visual translucency result, which is what is passed into the DisplayList. 10239 * 10240 * @hide 10241 */ 10242 public float getTransitionAlpha() { 10243 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10244 } 10245 10246 /** 10247 * Top position of this view relative to its parent. 10248 * 10249 * @return The top of this view, in pixels. 10250 */ 10251 @ViewDebug.CapturedViewProperty 10252 public final int getTop() { 10253 return mTop; 10254 } 10255 10256 /** 10257 * Sets the top position of this view relative to its parent. This method is meant to be called 10258 * by the layout system and should not generally be called otherwise, because the property 10259 * may be changed at any time by the layout. 10260 * 10261 * @param top The top of this view, in pixels. 10262 */ 10263 public final void setTop(int top) { 10264 if (top != mTop) { 10265 final boolean matrixIsIdentity = hasIdentityMatrix(); 10266 if (matrixIsIdentity) { 10267 if (mAttachInfo != null) { 10268 int minTop; 10269 int yLoc; 10270 if (top < mTop) { 10271 minTop = top; 10272 yLoc = top - mTop; 10273 } else { 10274 minTop = mTop; 10275 yLoc = 0; 10276 } 10277 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10278 } 10279 } else { 10280 // Double-invalidation is necessary to capture view's old and new areas 10281 invalidate(true); 10282 } 10283 10284 int width = mRight - mLeft; 10285 int oldHeight = mBottom - mTop; 10286 10287 mTop = top; 10288 mRenderNode.setTop(mTop); 10289 10290 sizeChange(width, mBottom - mTop, width, oldHeight); 10291 10292 if (!matrixIsIdentity) { 10293 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10294 invalidate(true); 10295 } 10296 mBackgroundSizeChanged = true; 10297 invalidateParentIfNeeded(); 10298 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10299 // View was rejected last time it was drawn by its parent; this may have changed 10300 invalidateParentIfNeeded(); 10301 } 10302 } 10303 } 10304 10305 /** 10306 * Bottom position of this view relative to its parent. 10307 * 10308 * @return The bottom of this view, in pixels. 10309 */ 10310 @ViewDebug.CapturedViewProperty 10311 public final int getBottom() { 10312 return mBottom; 10313 } 10314 10315 /** 10316 * True if this view has changed since the last time being drawn. 10317 * 10318 * @return The dirty state of this view. 10319 */ 10320 public boolean isDirty() { 10321 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10322 } 10323 10324 /** 10325 * Sets the bottom position of this view relative to its parent. This method is meant to be 10326 * called by the layout system and should not generally be called otherwise, because the 10327 * property may be changed at any time by the layout. 10328 * 10329 * @param bottom The bottom of this view, in pixels. 10330 */ 10331 public final void setBottom(int bottom) { 10332 if (bottom != mBottom) { 10333 final boolean matrixIsIdentity = hasIdentityMatrix(); 10334 if (matrixIsIdentity) { 10335 if (mAttachInfo != null) { 10336 int maxBottom; 10337 if (bottom < mBottom) { 10338 maxBottom = mBottom; 10339 } else { 10340 maxBottom = bottom; 10341 } 10342 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10343 } 10344 } else { 10345 // Double-invalidation is necessary to capture view's old and new areas 10346 invalidate(true); 10347 } 10348 10349 int width = mRight - mLeft; 10350 int oldHeight = mBottom - mTop; 10351 10352 mBottom = bottom; 10353 mRenderNode.setBottom(mBottom); 10354 10355 sizeChange(width, mBottom - mTop, width, oldHeight); 10356 10357 if (!matrixIsIdentity) { 10358 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10359 invalidate(true); 10360 } 10361 mBackgroundSizeChanged = true; 10362 invalidateParentIfNeeded(); 10363 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10364 // View was rejected last time it was drawn by its parent; this may have changed 10365 invalidateParentIfNeeded(); 10366 } 10367 } 10368 } 10369 10370 /** 10371 * Left position of this view relative to its parent. 10372 * 10373 * @return The left edge of this view, in pixels. 10374 */ 10375 @ViewDebug.CapturedViewProperty 10376 public final int getLeft() { 10377 return mLeft; 10378 } 10379 10380 /** 10381 * Sets the left position of this view relative to its parent. This method is meant to be called 10382 * by the layout system and should not generally be called otherwise, because the property 10383 * may be changed at any time by the layout. 10384 * 10385 * @param left The left of this view, in pixels. 10386 */ 10387 public final void setLeft(int left) { 10388 if (left != mLeft) { 10389 final boolean matrixIsIdentity = hasIdentityMatrix(); 10390 if (matrixIsIdentity) { 10391 if (mAttachInfo != null) { 10392 int minLeft; 10393 int xLoc; 10394 if (left < mLeft) { 10395 minLeft = left; 10396 xLoc = left - mLeft; 10397 } else { 10398 minLeft = mLeft; 10399 xLoc = 0; 10400 } 10401 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10402 } 10403 } else { 10404 // Double-invalidation is necessary to capture view's old and new areas 10405 invalidate(true); 10406 } 10407 10408 int oldWidth = mRight - mLeft; 10409 int height = mBottom - mTop; 10410 10411 mLeft = left; 10412 mRenderNode.setLeft(left); 10413 10414 sizeChange(mRight - mLeft, height, oldWidth, height); 10415 10416 if (!matrixIsIdentity) { 10417 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10418 invalidate(true); 10419 } 10420 mBackgroundSizeChanged = true; 10421 invalidateParentIfNeeded(); 10422 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10423 // View was rejected last time it was drawn by its parent; this may have changed 10424 invalidateParentIfNeeded(); 10425 } 10426 } 10427 } 10428 10429 /** 10430 * Right position of this view relative to its parent. 10431 * 10432 * @return The right edge of this view, in pixels. 10433 */ 10434 @ViewDebug.CapturedViewProperty 10435 public final int getRight() { 10436 return mRight; 10437 } 10438 10439 /** 10440 * Sets the right position of this view relative to its parent. This method is meant to be called 10441 * by the layout system and should not generally be called otherwise, because the property 10442 * may be changed at any time by the layout. 10443 * 10444 * @param right The right of this view, in pixels. 10445 */ 10446 public final void setRight(int right) { 10447 if (right != mRight) { 10448 final boolean matrixIsIdentity = hasIdentityMatrix(); 10449 if (matrixIsIdentity) { 10450 if (mAttachInfo != null) { 10451 int maxRight; 10452 if (right < mRight) { 10453 maxRight = mRight; 10454 } else { 10455 maxRight = right; 10456 } 10457 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10458 } 10459 } else { 10460 // Double-invalidation is necessary to capture view's old and new areas 10461 invalidate(true); 10462 } 10463 10464 int oldWidth = mRight - mLeft; 10465 int height = mBottom - mTop; 10466 10467 mRight = right; 10468 mRenderNode.setRight(mRight); 10469 10470 sizeChange(mRight - mLeft, height, oldWidth, height); 10471 10472 if (!matrixIsIdentity) { 10473 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10474 invalidate(true); 10475 } 10476 mBackgroundSizeChanged = true; 10477 invalidateParentIfNeeded(); 10478 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10479 // View was rejected last time it was drawn by its parent; this may have changed 10480 invalidateParentIfNeeded(); 10481 } 10482 } 10483 } 10484 10485 /** 10486 * The visual x position of this view, in pixels. This is equivalent to the 10487 * {@link #setTranslationX(float) translationX} property plus the current 10488 * {@link #getLeft() left} property. 10489 * 10490 * @return The visual x position of this view, in pixels. 10491 */ 10492 @ViewDebug.ExportedProperty(category = "drawing") 10493 public float getX() { 10494 return mLeft + getTranslationX(); 10495 } 10496 10497 /** 10498 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10499 * {@link #setTranslationX(float) translationX} property to be the difference between 10500 * the x value passed in and the current {@link #getLeft() left} property. 10501 * 10502 * @param x The visual x position of this view, in pixels. 10503 */ 10504 public void setX(float x) { 10505 setTranslationX(x - mLeft); 10506 } 10507 10508 /** 10509 * The visual y position of this view, in pixels. This is equivalent to the 10510 * {@link #setTranslationY(float) translationY} property plus the current 10511 * {@link #getTop() top} property. 10512 * 10513 * @return The visual y position of this view, in pixels. 10514 */ 10515 @ViewDebug.ExportedProperty(category = "drawing") 10516 public float getY() { 10517 return mTop + getTranslationY(); 10518 } 10519 10520 /** 10521 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10522 * {@link #setTranslationY(float) translationY} property to be the difference between 10523 * the y value passed in and the current {@link #getTop() top} property. 10524 * 10525 * @param y The visual y position of this view, in pixels. 10526 */ 10527 public void setY(float y) { 10528 setTranslationY(y - mTop); 10529 } 10530 10531 /** 10532 * The visual z position of this view, in pixels. This is equivalent to the 10533 * {@link #setTranslationZ(float) translationZ} property plus the current 10534 * {@link #getElevation() elevation} property. 10535 * 10536 * @return The visual z position of this view, in pixels. 10537 */ 10538 @ViewDebug.ExportedProperty(category = "drawing") 10539 public float getZ() { 10540 return getElevation() + getTranslationZ(); 10541 } 10542 10543 /** 10544 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10545 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10546 * the x value passed in and the current {@link #getElevation() elevation} property. 10547 * 10548 * @param z The visual z position of this view, in pixels. 10549 */ 10550 public void setZ(float z) { 10551 setTranslationZ(z - getElevation()); 10552 } 10553 10554 /** 10555 * The base elevation of this view relative to its parent, in pixels. 10556 * 10557 * @return The base depth position of the view, in pixels. 10558 */ 10559 @ViewDebug.ExportedProperty(category = "drawing") 10560 public float getElevation() { 10561 return mRenderNode.getElevation(); 10562 } 10563 10564 /** 10565 * Sets the base elevation of this view, in pixels. 10566 * 10567 * @attr ref android.R.styleable#View_elevation 10568 */ 10569 public void setElevation(float elevation) { 10570 if (elevation != getElevation()) { 10571 invalidateViewProperty(true, false); 10572 mRenderNode.setElevation(elevation); 10573 invalidateViewProperty(false, true); 10574 10575 invalidateParentIfNeededAndWasQuickRejected(); 10576 } 10577 } 10578 10579 /** 10580 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10581 * This position is post-layout, in addition to wherever the object's 10582 * layout placed it. 10583 * 10584 * @return The horizontal position of this view relative to its left position, in pixels. 10585 */ 10586 @ViewDebug.ExportedProperty(category = "drawing") 10587 public float getTranslationX() { 10588 return mRenderNode.getTranslationX(); 10589 } 10590 10591 /** 10592 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10593 * This effectively positions the object post-layout, in addition to wherever the object's 10594 * layout placed it. 10595 * 10596 * @param translationX The horizontal position of this view relative to its left position, 10597 * in pixels. 10598 * 10599 * @attr ref android.R.styleable#View_translationX 10600 */ 10601 public void setTranslationX(float translationX) { 10602 if (translationX != getTranslationX()) { 10603 invalidateViewProperty(true, false); 10604 mRenderNode.setTranslationX(translationX); 10605 invalidateViewProperty(false, true); 10606 10607 invalidateParentIfNeededAndWasQuickRejected(); 10608 notifySubtreeAccessibilityStateChangedIfNeeded(); 10609 } 10610 } 10611 10612 /** 10613 * The vertical location of this view relative to its {@link #getTop() top} position. 10614 * This position is post-layout, in addition to wherever the object's 10615 * layout placed it. 10616 * 10617 * @return The vertical position of this view relative to its top position, 10618 * in pixels. 10619 */ 10620 @ViewDebug.ExportedProperty(category = "drawing") 10621 public float getTranslationY() { 10622 return mRenderNode.getTranslationY(); 10623 } 10624 10625 /** 10626 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10627 * This effectively positions the object post-layout, in addition to wherever the object's 10628 * layout placed it. 10629 * 10630 * @param translationY The vertical position of this view relative to its top position, 10631 * in pixels. 10632 * 10633 * @attr ref android.R.styleable#View_translationY 10634 */ 10635 public void setTranslationY(float translationY) { 10636 if (translationY != getTranslationY()) { 10637 invalidateViewProperty(true, false); 10638 mRenderNode.setTranslationY(translationY); 10639 invalidateViewProperty(false, true); 10640 10641 invalidateParentIfNeededAndWasQuickRejected(); 10642 } 10643 } 10644 10645 /** 10646 * The depth location of this view relative to its {@link #getElevation() elevation}. 10647 * 10648 * @return The depth of this view relative to its elevation. 10649 */ 10650 @ViewDebug.ExportedProperty(category = "drawing") 10651 public float getTranslationZ() { 10652 return mRenderNode.getTranslationZ(); 10653 } 10654 10655 /** 10656 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 10657 * 10658 * @attr ref android.R.styleable#View_translationZ 10659 */ 10660 public void setTranslationZ(float translationZ) { 10661 if (translationZ != getTranslationZ()) { 10662 invalidateViewProperty(true, false); 10663 mRenderNode.setTranslationZ(translationZ); 10664 invalidateViewProperty(false, true); 10665 10666 invalidateParentIfNeededAndWasQuickRejected(); 10667 } 10668 } 10669 10670 /** 10671 * Returns a ValueAnimator which can animate a clearing circle. 10672 * <p> 10673 * The View is prevented from drawing within the circle, so the content 10674 * behind the View shows through. 10675 * 10676 * @param centerX The x coordinate of the center of the animating circle. 10677 * @param centerY The y coordinate of the center of the animating circle. 10678 * @param startRadius The starting radius of the animating circle. 10679 * @param endRadius The ending radius of the animating circle. 10680 * 10681 * @hide 10682 */ 10683 public final ValueAnimator createClearCircleAnimator(int centerX, int centerY, 10684 float startRadius, float endRadius) { 10685 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10686 startRadius, endRadius, true); 10687 } 10688 10689 /** 10690 * Returns the current StateListAnimator if exists. 10691 * 10692 * @return StateListAnimator or null if it does not exists 10693 * @see #setStateListAnimator(android.animation.StateListAnimator) 10694 */ 10695 public StateListAnimator getStateListAnimator() { 10696 return mStateListAnimator; 10697 } 10698 10699 /** 10700 * Attaches the provided StateListAnimator to this View. 10701 * <p> 10702 * Any previously attached StateListAnimator will be detached. 10703 * 10704 * @param stateListAnimator The StateListAnimator to update the view 10705 * @see {@link android.animation.StateListAnimator} 10706 */ 10707 public void setStateListAnimator(StateListAnimator stateListAnimator) { 10708 if (mStateListAnimator == stateListAnimator) { 10709 return; 10710 } 10711 if (mStateListAnimator != null) { 10712 mStateListAnimator.setTarget(null); 10713 } 10714 mStateListAnimator = stateListAnimator; 10715 if (stateListAnimator != null) { 10716 stateListAnimator.setTarget(this); 10717 if (isAttachedToWindow()) { 10718 stateListAnimator.setState(getDrawableState()); 10719 } 10720 } 10721 } 10722 10723 /** 10724 * Sets the {@link Outline} of the view, which defines the shape of the shadow it 10725 * casts, and enables outline clipping. 10726 * <p> 10727 * By default, a View queries its Outline from its background drawable, via 10728 * {@link Drawable#getOutline(Outline)}. Manually setting the Outline with this method allows 10729 * this behavior to be overridden. 10730 * <p> 10731 * If the outline is {@link Outline#isEmpty()} or is <code>null</code>, 10732 * shadows will not be cast. 10733 * <p> 10734 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 10735 * 10736 * @param outline The new outline of the view. 10737 * 10738 * @see #setClipToOutline(boolean) 10739 * @see #getClipToOutline() 10740 */ 10741 public void setOutline(@Nullable Outline outline) { 10742 mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED; 10743 10744 if (outline == null || outline.isEmpty()) { 10745 if (mOutline != null) { 10746 mOutline.setEmpty(); 10747 } 10748 } else { 10749 // always copy the path since caller may reuse 10750 if (mOutline == null) { 10751 mOutline = new Outline(); 10752 } 10753 mOutline.set(outline); 10754 } 10755 mRenderNode.setOutline(mOutline); 10756 } 10757 10758 /** 10759 * Returns whether the Outline should be used to clip the contents of the View. 10760 * <p> 10761 * Note that this flag will only be respected if the View's Outline returns true from 10762 * {@link Outline#canClip()}. 10763 * 10764 * @see #setOutline(Outline) 10765 * @see #setClipToOutline(boolean) 10766 */ 10767 public final boolean getClipToOutline() { 10768 return mRenderNode.getClipToOutline(); 10769 } 10770 10771 /** 10772 * Sets whether the View's Outline should be used to clip the contents of the View. 10773 * <p> 10774 * Note that this flag will only be respected if the View's Outline returns true from 10775 * {@link Outline#canClip()}. 10776 * 10777 * @see #setOutline(Outline) 10778 * @see #getClipToOutline() 10779 */ 10780 public void setClipToOutline(boolean clipToOutline) { 10781 damageInParent(); 10782 if (getClipToOutline() != clipToOutline) { 10783 mRenderNode.setClipToOutline(clipToOutline); 10784 } 10785 } 10786 10787 private void queryOutlineFromBackgroundIfUndefined() { 10788 if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) { 10789 // Outline not currently defined, query from background 10790 if (mOutline == null) { 10791 mOutline = new Outline(); 10792 } else { 10793 //invalidate outline, to ensure background calculates it 10794 mOutline.setEmpty(); 10795 } 10796 if (mBackground.getOutline(mOutline)) { 10797 if (mOutline.isEmpty()) { 10798 throw new IllegalStateException("Background drawable failed to build outline"); 10799 } 10800 mRenderNode.setOutline(mOutline); 10801 } else { 10802 mRenderNode.setOutline(null); 10803 } 10804 notifySubtreeAccessibilityStateChangedIfNeeded(); 10805 } 10806 } 10807 10808 /** 10809 * Private API to be used for reveal animation 10810 * 10811 * @hide 10812 */ 10813 public void setRevealClip(boolean shouldClip, boolean inverseClip, 10814 float x, float y, float radius) { 10815 mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius); 10816 // TODO: Handle this invalidate in a better way, or purely in native. 10817 invalidate(); 10818 } 10819 10820 /** 10821 * Hit rectangle in parent's coordinates 10822 * 10823 * @param outRect The hit rectangle of the view. 10824 */ 10825 public void getHitRect(Rect outRect) { 10826 if (hasIdentityMatrix() || mAttachInfo == null) { 10827 outRect.set(mLeft, mTop, mRight, mBottom); 10828 } else { 10829 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10830 tmpRect.set(0, 0, getWidth(), getHeight()); 10831 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 10832 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10833 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10834 } 10835 } 10836 10837 /** 10838 * Determines whether the given point, in local coordinates is inside the view. 10839 */ 10840 /*package*/ final boolean pointInView(float localX, float localY) { 10841 return localX >= 0 && localX < (mRight - mLeft) 10842 && localY >= 0 && localY < (mBottom - mTop); 10843 } 10844 10845 /** 10846 * Utility method to determine whether the given point, in local coordinates, 10847 * is inside the view, where the area of the view is expanded by the slop factor. 10848 * This method is called while processing touch-move events to determine if the event 10849 * is still within the view. 10850 * 10851 * @hide 10852 */ 10853 public boolean pointInView(float localX, float localY, float slop) { 10854 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10855 localY < ((mBottom - mTop) + slop); 10856 } 10857 10858 /** 10859 * When a view has focus and the user navigates away from it, the next view is searched for 10860 * starting from the rectangle filled in by this method. 10861 * 10862 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10863 * of the view. However, if your view maintains some idea of internal selection, 10864 * such as a cursor, or a selected row or column, you should override this method and 10865 * fill in a more specific rectangle. 10866 * 10867 * @param r The rectangle to fill in, in this view's coordinates. 10868 */ 10869 public void getFocusedRect(Rect r) { 10870 getDrawingRect(r); 10871 } 10872 10873 /** 10874 * If some part of this view is not clipped by any of its parents, then 10875 * return that area in r in global (root) coordinates. To convert r to local 10876 * coordinates (without taking possible View rotations into account), offset 10877 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10878 * If the view is completely clipped or translated out, return false. 10879 * 10880 * @param r If true is returned, r holds the global coordinates of the 10881 * visible portion of this view. 10882 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10883 * between this view and its root. globalOffet may be null. 10884 * @return true if r is non-empty (i.e. part of the view is visible at the 10885 * root level. 10886 */ 10887 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10888 int width = mRight - mLeft; 10889 int height = mBottom - mTop; 10890 if (width > 0 && height > 0) { 10891 r.set(0, 0, width, height); 10892 if (globalOffset != null) { 10893 globalOffset.set(-mScrollX, -mScrollY); 10894 } 10895 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10896 } 10897 return false; 10898 } 10899 10900 public final boolean getGlobalVisibleRect(Rect r) { 10901 return getGlobalVisibleRect(r, null); 10902 } 10903 10904 public final boolean getLocalVisibleRect(Rect r) { 10905 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10906 if (getGlobalVisibleRect(r, offset)) { 10907 r.offset(-offset.x, -offset.y); // make r local 10908 return true; 10909 } 10910 return false; 10911 } 10912 10913 /** 10914 * Offset this view's vertical location by the specified number of pixels. 10915 * 10916 * @param offset the number of pixels to offset the view by 10917 */ 10918 public void offsetTopAndBottom(int offset) { 10919 if (offset != 0) { 10920 final boolean matrixIsIdentity = hasIdentityMatrix(); 10921 if (matrixIsIdentity) { 10922 if (isHardwareAccelerated()) { 10923 invalidateViewProperty(false, false); 10924 } else { 10925 final ViewParent p = mParent; 10926 if (p != null && mAttachInfo != null) { 10927 final Rect r = mAttachInfo.mTmpInvalRect; 10928 int minTop; 10929 int maxBottom; 10930 int yLoc; 10931 if (offset < 0) { 10932 minTop = mTop + offset; 10933 maxBottom = mBottom; 10934 yLoc = offset; 10935 } else { 10936 minTop = mTop; 10937 maxBottom = mBottom + offset; 10938 yLoc = 0; 10939 } 10940 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10941 p.invalidateChild(this, r); 10942 } 10943 } 10944 } else { 10945 invalidateViewProperty(false, false); 10946 } 10947 10948 mTop += offset; 10949 mBottom += offset; 10950 mRenderNode.offsetTopAndBottom(offset); 10951 if (isHardwareAccelerated()) { 10952 invalidateViewProperty(false, false); 10953 } else { 10954 if (!matrixIsIdentity) { 10955 invalidateViewProperty(false, true); 10956 } 10957 invalidateParentIfNeeded(); 10958 } 10959 notifySubtreeAccessibilityStateChangedIfNeeded(); 10960 } 10961 } 10962 10963 /** 10964 * Offset this view's horizontal location by the specified amount of pixels. 10965 * 10966 * @param offset the number of pixels to offset the view by 10967 */ 10968 public void offsetLeftAndRight(int offset) { 10969 if (offset != 0) { 10970 final boolean matrixIsIdentity = hasIdentityMatrix(); 10971 if (matrixIsIdentity) { 10972 if (isHardwareAccelerated()) { 10973 invalidateViewProperty(false, false); 10974 } else { 10975 final ViewParent p = mParent; 10976 if (p != null && mAttachInfo != null) { 10977 final Rect r = mAttachInfo.mTmpInvalRect; 10978 int minLeft; 10979 int maxRight; 10980 if (offset < 0) { 10981 minLeft = mLeft + offset; 10982 maxRight = mRight; 10983 } else { 10984 minLeft = mLeft; 10985 maxRight = mRight + offset; 10986 } 10987 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10988 p.invalidateChild(this, r); 10989 } 10990 } 10991 } else { 10992 invalidateViewProperty(false, false); 10993 } 10994 10995 mLeft += offset; 10996 mRight += offset; 10997 mRenderNode.offsetLeftAndRight(offset); 10998 if (isHardwareAccelerated()) { 10999 invalidateViewProperty(false, false); 11000 } else { 11001 if (!matrixIsIdentity) { 11002 invalidateViewProperty(false, true); 11003 } 11004 invalidateParentIfNeeded(); 11005 } 11006 notifySubtreeAccessibilityStateChangedIfNeeded(); 11007 } 11008 } 11009 11010 /** 11011 * Get the LayoutParams associated with this view. All views should have 11012 * layout parameters. These supply parameters to the <i>parent</i> of this 11013 * view specifying how it should be arranged. There are many subclasses of 11014 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11015 * of ViewGroup that are responsible for arranging their children. 11016 * 11017 * This method may return null if this View is not attached to a parent 11018 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11019 * was not invoked successfully. When a View is attached to a parent 11020 * ViewGroup, this method must not return null. 11021 * 11022 * @return The LayoutParams associated with this view, or null if no 11023 * parameters have been set yet 11024 */ 11025 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11026 public ViewGroup.LayoutParams getLayoutParams() { 11027 return mLayoutParams; 11028 } 11029 11030 /** 11031 * Set the layout parameters associated with this view. These supply 11032 * parameters to the <i>parent</i> of this view specifying how it should be 11033 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11034 * correspond to the different subclasses of ViewGroup that are responsible 11035 * for arranging their children. 11036 * 11037 * @param params The layout parameters for this view, cannot be null 11038 */ 11039 public void setLayoutParams(ViewGroup.LayoutParams params) { 11040 if (params == null) { 11041 throw new NullPointerException("Layout parameters cannot be null"); 11042 } 11043 mLayoutParams = params; 11044 resolveLayoutParams(); 11045 if (mParent instanceof ViewGroup) { 11046 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11047 } 11048 requestLayout(); 11049 } 11050 11051 /** 11052 * Resolve the layout parameters depending on the resolved layout direction 11053 * 11054 * @hide 11055 */ 11056 public void resolveLayoutParams() { 11057 if (mLayoutParams != null) { 11058 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11059 } 11060 } 11061 11062 /** 11063 * Set the scrolled position of your view. This will cause a call to 11064 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11065 * invalidated. 11066 * @param x the x position to scroll to 11067 * @param y the y position to scroll to 11068 */ 11069 public void scrollTo(int x, int y) { 11070 if (mScrollX != x || mScrollY != y) { 11071 int oldX = mScrollX; 11072 int oldY = mScrollY; 11073 mScrollX = x; 11074 mScrollY = y; 11075 invalidateParentCaches(); 11076 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11077 if (!awakenScrollBars()) { 11078 postInvalidateOnAnimation(); 11079 } 11080 } 11081 } 11082 11083 /** 11084 * Move the scrolled position of your view. This will cause a call to 11085 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11086 * invalidated. 11087 * @param x the amount of pixels to scroll by horizontally 11088 * @param y the amount of pixels to scroll by vertically 11089 */ 11090 public void scrollBy(int x, int y) { 11091 scrollTo(mScrollX + x, mScrollY + y); 11092 } 11093 11094 /** 11095 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11096 * animation to fade the scrollbars out after a default delay. If a subclass 11097 * provides animated scrolling, the start delay should equal the duration 11098 * of the scrolling animation.</p> 11099 * 11100 * <p>The animation starts only if at least one of the scrollbars is 11101 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11102 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11103 * this method returns true, and false otherwise. If the animation is 11104 * started, this method calls {@link #invalidate()}; in that case the 11105 * caller should not call {@link #invalidate()}.</p> 11106 * 11107 * <p>This method should be invoked every time a subclass directly updates 11108 * the scroll parameters.</p> 11109 * 11110 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11111 * and {@link #scrollTo(int, int)}.</p> 11112 * 11113 * @return true if the animation is played, false otherwise 11114 * 11115 * @see #awakenScrollBars(int) 11116 * @see #scrollBy(int, int) 11117 * @see #scrollTo(int, int) 11118 * @see #isHorizontalScrollBarEnabled() 11119 * @see #isVerticalScrollBarEnabled() 11120 * @see #setHorizontalScrollBarEnabled(boolean) 11121 * @see #setVerticalScrollBarEnabled(boolean) 11122 */ 11123 protected boolean awakenScrollBars() { 11124 return mScrollCache != null && 11125 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11126 } 11127 11128 /** 11129 * Trigger the scrollbars to draw. 11130 * This method differs from awakenScrollBars() only in its default duration. 11131 * initialAwakenScrollBars() will show the scroll bars for longer than 11132 * usual to give the user more of a chance to notice them. 11133 * 11134 * @return true if the animation is played, false otherwise. 11135 */ 11136 private boolean initialAwakenScrollBars() { 11137 return mScrollCache != null && 11138 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11139 } 11140 11141 /** 11142 * <p> 11143 * Trigger the scrollbars to draw. When invoked this method starts an 11144 * animation to fade the scrollbars out after a fixed delay. If a subclass 11145 * provides animated scrolling, the start delay should equal the duration of 11146 * the scrolling animation. 11147 * </p> 11148 * 11149 * <p> 11150 * The animation starts only if at least one of the scrollbars is enabled, 11151 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11152 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11153 * this method returns true, and false otherwise. If the animation is 11154 * started, this method calls {@link #invalidate()}; in that case the caller 11155 * should not call {@link #invalidate()}. 11156 * </p> 11157 * 11158 * <p> 11159 * This method should be invoked everytime a subclass directly updates the 11160 * scroll parameters. 11161 * </p> 11162 * 11163 * @param startDelay the delay, in milliseconds, after which the animation 11164 * should start; when the delay is 0, the animation starts 11165 * immediately 11166 * @return true if the animation is played, false otherwise 11167 * 11168 * @see #scrollBy(int, int) 11169 * @see #scrollTo(int, int) 11170 * @see #isHorizontalScrollBarEnabled() 11171 * @see #isVerticalScrollBarEnabled() 11172 * @see #setHorizontalScrollBarEnabled(boolean) 11173 * @see #setVerticalScrollBarEnabled(boolean) 11174 */ 11175 protected boolean awakenScrollBars(int startDelay) { 11176 return awakenScrollBars(startDelay, true); 11177 } 11178 11179 /** 11180 * <p> 11181 * Trigger the scrollbars to draw. When invoked this method starts an 11182 * animation to fade the scrollbars out after a fixed delay. If a subclass 11183 * provides animated scrolling, the start delay should equal the duration of 11184 * the scrolling animation. 11185 * </p> 11186 * 11187 * <p> 11188 * The animation starts only if at least one of the scrollbars is enabled, 11189 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11190 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11191 * this method returns true, and false otherwise. If the animation is 11192 * started, this method calls {@link #invalidate()} if the invalidate parameter 11193 * is set to true; in that case the caller 11194 * should not call {@link #invalidate()}. 11195 * </p> 11196 * 11197 * <p> 11198 * This method should be invoked everytime a subclass directly updates the 11199 * scroll parameters. 11200 * </p> 11201 * 11202 * @param startDelay the delay, in milliseconds, after which the animation 11203 * should start; when the delay is 0, the animation starts 11204 * immediately 11205 * 11206 * @param invalidate Wheter this method should call invalidate 11207 * 11208 * @return true if the animation is played, false otherwise 11209 * 11210 * @see #scrollBy(int, int) 11211 * @see #scrollTo(int, int) 11212 * @see #isHorizontalScrollBarEnabled() 11213 * @see #isVerticalScrollBarEnabled() 11214 * @see #setHorizontalScrollBarEnabled(boolean) 11215 * @see #setVerticalScrollBarEnabled(boolean) 11216 */ 11217 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11218 final ScrollabilityCache scrollCache = mScrollCache; 11219 11220 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11221 return false; 11222 } 11223 11224 if (scrollCache.scrollBar == null) { 11225 scrollCache.scrollBar = new ScrollBarDrawable(); 11226 } 11227 11228 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11229 11230 if (invalidate) { 11231 // Invalidate to show the scrollbars 11232 postInvalidateOnAnimation(); 11233 } 11234 11235 if (scrollCache.state == ScrollabilityCache.OFF) { 11236 // FIXME: this is copied from WindowManagerService. 11237 // We should get this value from the system when it 11238 // is possible to do so. 11239 final int KEY_REPEAT_FIRST_DELAY = 750; 11240 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11241 } 11242 11243 // Tell mScrollCache when we should start fading. This may 11244 // extend the fade start time if one was already scheduled 11245 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11246 scrollCache.fadeStartTime = fadeStartTime; 11247 scrollCache.state = ScrollabilityCache.ON; 11248 11249 // Schedule our fader to run, unscheduling any old ones first 11250 if (mAttachInfo != null) { 11251 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11252 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11253 } 11254 11255 return true; 11256 } 11257 11258 return false; 11259 } 11260 11261 /** 11262 * Do not invalidate views which are not visible and which are not running an animation. They 11263 * will not get drawn and they should not set dirty flags as if they will be drawn 11264 */ 11265 private boolean skipInvalidate() { 11266 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11267 (!(mParent instanceof ViewGroup) || 11268 !((ViewGroup) mParent).isViewTransitioning(this)); 11269 } 11270 11271 /** 11272 * Mark the area defined by dirty as needing to be drawn. If the view is 11273 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11274 * point in the future. 11275 * <p> 11276 * This must be called from a UI thread. To call from a non-UI thread, call 11277 * {@link #postInvalidate()}. 11278 * <p> 11279 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11280 * {@code dirty}. 11281 * 11282 * @param dirty the rectangle representing the bounds of the dirty region 11283 */ 11284 public void invalidate(Rect dirty) { 11285 final int scrollX = mScrollX; 11286 final int scrollY = mScrollY; 11287 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11288 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11289 } 11290 11291 /** 11292 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11293 * coordinates of the dirty rect are relative to the view. If the view is 11294 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11295 * point in the future. 11296 * <p> 11297 * This must be called from a UI thread. To call from a non-UI thread, call 11298 * {@link #postInvalidate()}. 11299 * 11300 * @param l the left position of the dirty region 11301 * @param t the top position of the dirty region 11302 * @param r the right position of the dirty region 11303 * @param b the bottom position of the dirty region 11304 */ 11305 public void invalidate(int l, int t, int r, int b) { 11306 final int scrollX = mScrollX; 11307 final int scrollY = mScrollY; 11308 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11309 } 11310 11311 /** 11312 * Invalidate the whole view. If the view is visible, 11313 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11314 * the future. 11315 * <p> 11316 * This must be called from a UI thread. To call from a non-UI thread, call 11317 * {@link #postInvalidate()}. 11318 */ 11319 public void invalidate() { 11320 invalidate(true); 11321 } 11322 11323 /** 11324 * This is where the invalidate() work actually happens. A full invalidate() 11325 * causes the drawing cache to be invalidated, but this function can be 11326 * called with invalidateCache set to false to skip that invalidation step 11327 * for cases that do not need it (for example, a component that remains at 11328 * the same dimensions with the same content). 11329 * 11330 * @param invalidateCache Whether the drawing cache for this view should be 11331 * invalidated as well. This is usually true for a full 11332 * invalidate, but may be set to false if the View's contents or 11333 * dimensions have not changed. 11334 */ 11335 void invalidate(boolean invalidateCache) { 11336 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11337 } 11338 11339 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11340 boolean fullInvalidate) { 11341 if (skipInvalidate()) { 11342 return; 11343 } 11344 11345 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11346 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11347 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11348 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11349 if (fullInvalidate) { 11350 mLastIsOpaque = isOpaque(); 11351 mPrivateFlags &= ~PFLAG_DRAWN; 11352 } 11353 11354 mPrivateFlags |= PFLAG_DIRTY; 11355 11356 if (invalidateCache) { 11357 mPrivateFlags |= PFLAG_INVALIDATED; 11358 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11359 } 11360 11361 // Propagate the damage rectangle to the parent view. 11362 final AttachInfo ai = mAttachInfo; 11363 final ViewParent p = mParent; 11364 if (p != null && ai != null && l < r && t < b) { 11365 final Rect damage = ai.mTmpInvalRect; 11366 damage.set(l, t, r, b); 11367 p.invalidateChild(this, damage); 11368 } 11369 11370 // Damage the entire projection receiver, if necessary. 11371 if (mBackground != null && mBackground.isProjected()) { 11372 final View receiver = getProjectionReceiver(); 11373 if (receiver != null) { 11374 receiver.damageInParent(); 11375 } 11376 } 11377 11378 // Damage the entire IsolatedZVolume recieving this view's shadow. 11379 if (isHardwareAccelerated() && getZ() != 0) { 11380 damageShadowReceiver(); 11381 } 11382 } 11383 } 11384 11385 /** 11386 * @return this view's projection receiver, or {@code null} if none exists 11387 */ 11388 private View getProjectionReceiver() { 11389 ViewParent p = getParent(); 11390 while (p != null && p instanceof View) { 11391 final View v = (View) p; 11392 if (v.isProjectionReceiver()) { 11393 return v; 11394 } 11395 p = p.getParent(); 11396 } 11397 11398 return null; 11399 } 11400 11401 /** 11402 * @return whether the view is a projection receiver 11403 */ 11404 private boolean isProjectionReceiver() { 11405 return mBackground != null; 11406 } 11407 11408 /** 11409 * Damage area of the screen that can be covered by this View's shadow. 11410 * 11411 * This method will guarantee that any changes to shadows cast by a View 11412 * are damaged on the screen for future redraw. 11413 */ 11414 private void damageShadowReceiver() { 11415 final AttachInfo ai = mAttachInfo; 11416 if (ai != null) { 11417 ViewParent p = getParent(); 11418 if (p != null && p instanceof ViewGroup) { 11419 final ViewGroup vg = (ViewGroup) p; 11420 vg.damageInParent(); 11421 } 11422 } 11423 } 11424 11425 /** 11426 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11427 * set any flags or handle all of the cases handled by the default invalidation methods. 11428 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11429 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11430 * walk up the hierarchy, transforming the dirty rect as necessary. 11431 * 11432 * The method also handles normal invalidation logic if display list properties are not 11433 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11434 * backup approach, to handle these cases used in the various property-setting methods. 11435 * 11436 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11437 * are not being used in this view 11438 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11439 * list properties are not being used in this view 11440 */ 11441 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11442 if (!isHardwareAccelerated() 11443 || !mRenderNode.isValid() 11444 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11445 if (invalidateParent) { 11446 invalidateParentCaches(); 11447 } 11448 if (forceRedraw) { 11449 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11450 } 11451 invalidate(false); 11452 } else { 11453 damageInParent(); 11454 } 11455 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11456 damageShadowReceiver(); 11457 } 11458 } 11459 11460 /** 11461 * Tells the parent view to damage this view's bounds. 11462 * 11463 * @hide 11464 */ 11465 protected void damageInParent() { 11466 final AttachInfo ai = mAttachInfo; 11467 final ViewParent p = mParent; 11468 if (p != null && ai != null) { 11469 final Rect r = ai.mTmpInvalRect; 11470 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11471 if (mParent instanceof ViewGroup) { 11472 ((ViewGroup) mParent).damageChild(this, r); 11473 } else { 11474 mParent.invalidateChild(this, r); 11475 } 11476 } 11477 } 11478 11479 /** 11480 * Utility method to transform a given Rect by the current matrix of this view. 11481 */ 11482 void transformRect(final Rect rect) { 11483 if (!getMatrix().isIdentity()) { 11484 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11485 boundingRect.set(rect); 11486 getMatrix().mapRect(boundingRect); 11487 rect.set((int) Math.floor(boundingRect.left), 11488 (int) Math.floor(boundingRect.top), 11489 (int) Math.ceil(boundingRect.right), 11490 (int) Math.ceil(boundingRect.bottom)); 11491 } 11492 } 11493 11494 /** 11495 * Used to indicate that the parent of this view should clear its caches. This functionality 11496 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11497 * which is necessary when various parent-managed properties of the view change, such as 11498 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11499 * clears the parent caches and does not causes an invalidate event. 11500 * 11501 * @hide 11502 */ 11503 protected void invalidateParentCaches() { 11504 if (mParent instanceof View) { 11505 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11506 } 11507 } 11508 11509 /** 11510 * Used to indicate that the parent of this view should be invalidated. This functionality 11511 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11512 * which is necessary when various parent-managed properties of the view change, such as 11513 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11514 * an invalidation event to the parent. 11515 * 11516 * @hide 11517 */ 11518 protected void invalidateParentIfNeeded() { 11519 if (isHardwareAccelerated() && mParent instanceof View) { 11520 ((View) mParent).invalidate(true); 11521 } 11522 } 11523 11524 /** 11525 * @hide 11526 */ 11527 protected void invalidateParentIfNeededAndWasQuickRejected() { 11528 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11529 // View was rejected last time it was drawn by its parent; this may have changed 11530 invalidateParentIfNeeded(); 11531 } 11532 } 11533 11534 /** 11535 * Indicates whether this View is opaque. An opaque View guarantees that it will 11536 * draw all the pixels overlapping its bounds using a fully opaque color. 11537 * 11538 * Subclasses of View should override this method whenever possible to indicate 11539 * whether an instance is opaque. Opaque Views are treated in a special way by 11540 * the View hierarchy, possibly allowing it to perform optimizations during 11541 * invalidate/draw passes. 11542 * 11543 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11544 */ 11545 @ViewDebug.ExportedProperty(category = "drawing") 11546 public boolean isOpaque() { 11547 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11548 getFinalAlpha() >= 1.0f; 11549 } 11550 11551 /** 11552 * @hide 11553 */ 11554 protected void computeOpaqueFlags() { 11555 // Opaque if: 11556 // - Has a background 11557 // - Background is opaque 11558 // - Doesn't have scrollbars or scrollbars overlay 11559 11560 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11561 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11562 } else { 11563 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11564 } 11565 11566 final int flags = mViewFlags; 11567 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11568 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11569 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11570 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11571 } else { 11572 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11573 } 11574 } 11575 11576 /** 11577 * @hide 11578 */ 11579 protected boolean hasOpaqueScrollbars() { 11580 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11581 } 11582 11583 /** 11584 * @return A handler associated with the thread running the View. This 11585 * handler can be used to pump events in the UI events queue. 11586 */ 11587 public Handler getHandler() { 11588 final AttachInfo attachInfo = mAttachInfo; 11589 if (attachInfo != null) { 11590 return attachInfo.mHandler; 11591 } 11592 return null; 11593 } 11594 11595 /** 11596 * Gets the view root associated with the View. 11597 * @return The view root, or null if none. 11598 * @hide 11599 */ 11600 public ViewRootImpl getViewRootImpl() { 11601 if (mAttachInfo != null) { 11602 return mAttachInfo.mViewRootImpl; 11603 } 11604 return null; 11605 } 11606 11607 /** 11608 * @hide 11609 */ 11610 public HardwareRenderer getHardwareRenderer() { 11611 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11612 } 11613 11614 /** 11615 * <p>Causes the Runnable to be added to the message queue. 11616 * The runnable will be run on the user interface thread.</p> 11617 * 11618 * @param action The Runnable that will be executed. 11619 * 11620 * @return Returns true if the Runnable was successfully placed in to the 11621 * message queue. Returns false on failure, usually because the 11622 * looper processing the message queue is exiting. 11623 * 11624 * @see #postDelayed 11625 * @see #removeCallbacks 11626 */ 11627 public boolean post(Runnable action) { 11628 final AttachInfo attachInfo = mAttachInfo; 11629 if (attachInfo != null) { 11630 return attachInfo.mHandler.post(action); 11631 } 11632 // Assume that post will succeed later 11633 ViewRootImpl.getRunQueue().post(action); 11634 return true; 11635 } 11636 11637 /** 11638 * <p>Causes the Runnable to be added to the message queue, to be run 11639 * after the specified amount of time elapses. 11640 * The runnable will be run on the user interface thread.</p> 11641 * 11642 * @param action The Runnable that will be executed. 11643 * @param delayMillis The delay (in milliseconds) until the Runnable 11644 * will be executed. 11645 * 11646 * @return true if the Runnable was successfully placed in to the 11647 * message queue. Returns false on failure, usually because the 11648 * looper processing the message queue is exiting. Note that a 11649 * result of true does not mean the Runnable will be processed -- 11650 * if the looper is quit before the delivery time of the message 11651 * occurs then the message will be dropped. 11652 * 11653 * @see #post 11654 * @see #removeCallbacks 11655 */ 11656 public boolean postDelayed(Runnable action, long delayMillis) { 11657 final AttachInfo attachInfo = mAttachInfo; 11658 if (attachInfo != null) { 11659 return attachInfo.mHandler.postDelayed(action, delayMillis); 11660 } 11661 // Assume that post will succeed later 11662 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11663 return true; 11664 } 11665 11666 /** 11667 * <p>Causes the Runnable to execute on the next animation time step. 11668 * The runnable will be run on the user interface thread.</p> 11669 * 11670 * @param action The Runnable that will be executed. 11671 * 11672 * @see #postOnAnimationDelayed 11673 * @see #removeCallbacks 11674 */ 11675 public void postOnAnimation(Runnable action) { 11676 final AttachInfo attachInfo = mAttachInfo; 11677 if (attachInfo != null) { 11678 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11679 Choreographer.CALLBACK_ANIMATION, action, null); 11680 } else { 11681 // Assume that post will succeed later 11682 ViewRootImpl.getRunQueue().post(action); 11683 } 11684 } 11685 11686 /** 11687 * <p>Causes the Runnable to execute on the next animation time step, 11688 * after the specified amount of time elapses. 11689 * The runnable will be run on the user interface thread.</p> 11690 * 11691 * @param action The Runnable that will be executed. 11692 * @param delayMillis The delay (in milliseconds) until the Runnable 11693 * will be executed. 11694 * 11695 * @see #postOnAnimation 11696 * @see #removeCallbacks 11697 */ 11698 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11699 final AttachInfo attachInfo = mAttachInfo; 11700 if (attachInfo != null) { 11701 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11702 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11703 } else { 11704 // Assume that post will succeed later 11705 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11706 } 11707 } 11708 11709 /** 11710 * <p>Removes the specified Runnable from the message queue.</p> 11711 * 11712 * @param action The Runnable to remove from the message handling queue 11713 * 11714 * @return true if this view could ask the Handler to remove the Runnable, 11715 * false otherwise. When the returned value is true, the Runnable 11716 * may or may not have been actually removed from the message queue 11717 * (for instance, if the Runnable was not in the queue already.) 11718 * 11719 * @see #post 11720 * @see #postDelayed 11721 * @see #postOnAnimation 11722 * @see #postOnAnimationDelayed 11723 */ 11724 public boolean removeCallbacks(Runnable action) { 11725 if (action != null) { 11726 final AttachInfo attachInfo = mAttachInfo; 11727 if (attachInfo != null) { 11728 attachInfo.mHandler.removeCallbacks(action); 11729 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11730 Choreographer.CALLBACK_ANIMATION, action, null); 11731 } 11732 // Assume that post will succeed later 11733 ViewRootImpl.getRunQueue().removeCallbacks(action); 11734 } 11735 return true; 11736 } 11737 11738 /** 11739 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11740 * 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 * @see #invalidate() 11746 * @see #postInvalidateDelayed(long) 11747 */ 11748 public void postInvalidate() { 11749 postInvalidateDelayed(0); 11750 } 11751 11752 /** 11753 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11754 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11755 * 11756 * <p>This method can be invoked from outside of the UI thread 11757 * only when this View is attached to a window.</p> 11758 * 11759 * @param left The left coordinate of the rectangle to invalidate. 11760 * @param top The top coordinate of the rectangle to invalidate. 11761 * @param right The right coordinate of the rectangle to invalidate. 11762 * @param bottom The bottom coordinate of the rectangle to invalidate. 11763 * 11764 * @see #invalidate(int, int, int, int) 11765 * @see #invalidate(Rect) 11766 * @see #postInvalidateDelayed(long, int, int, int, int) 11767 */ 11768 public void postInvalidate(int left, int top, int right, int bottom) { 11769 postInvalidateDelayed(0, left, top, right, bottom); 11770 } 11771 11772 /** 11773 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11774 * loop. Waits for the specified amount of time.</p> 11775 * 11776 * <p>This method can be invoked from outside of the UI thread 11777 * only when this View is attached to a window.</p> 11778 * 11779 * @param delayMilliseconds the duration in milliseconds to delay the 11780 * invalidation by 11781 * 11782 * @see #invalidate() 11783 * @see #postInvalidate() 11784 */ 11785 public void postInvalidateDelayed(long delayMilliseconds) { 11786 // We try only with the AttachInfo because there's no point in invalidating 11787 // if we are not attached to our window 11788 final AttachInfo attachInfo = mAttachInfo; 11789 if (attachInfo != null) { 11790 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11791 } 11792 } 11793 11794 /** 11795 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11796 * through the event loop. Waits for the specified amount of time.</p> 11797 * 11798 * <p>This method can be invoked from outside of the UI thread 11799 * only when this View is attached to a window.</p> 11800 * 11801 * @param delayMilliseconds the duration in milliseconds to delay the 11802 * invalidation by 11803 * @param left The left coordinate of the rectangle to invalidate. 11804 * @param top The top coordinate of the rectangle to invalidate. 11805 * @param right The right coordinate of the rectangle to invalidate. 11806 * @param bottom The bottom coordinate of the rectangle to invalidate. 11807 * 11808 * @see #invalidate(int, int, int, int) 11809 * @see #invalidate(Rect) 11810 * @see #postInvalidate(int, int, int, int) 11811 */ 11812 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11813 int right, int bottom) { 11814 11815 // We try only with the AttachInfo because there's no point in invalidating 11816 // if we are not attached to our window 11817 final AttachInfo attachInfo = mAttachInfo; 11818 if (attachInfo != null) { 11819 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11820 info.target = this; 11821 info.left = left; 11822 info.top = top; 11823 info.right = right; 11824 info.bottom = bottom; 11825 11826 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11827 } 11828 } 11829 11830 /** 11831 * <p>Cause an invalidate to happen on the next animation time step, typically the 11832 * next display frame.</p> 11833 * 11834 * <p>This method can be invoked from outside of the UI thread 11835 * only when this View is attached to a window.</p> 11836 * 11837 * @see #invalidate() 11838 */ 11839 public void postInvalidateOnAnimation() { 11840 // We try only with the AttachInfo because there's no point in invalidating 11841 // if we are not attached to our window 11842 final AttachInfo attachInfo = mAttachInfo; 11843 if (attachInfo != null) { 11844 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11845 } 11846 } 11847 11848 /** 11849 * <p>Cause an invalidate of the specified area to happen on the next animation 11850 * time step, typically the next display frame.</p> 11851 * 11852 * <p>This method can be invoked from outside of the UI thread 11853 * only when this View is attached to a window.</p> 11854 * 11855 * @param left The left coordinate of the rectangle to invalidate. 11856 * @param top The top coordinate of the rectangle to invalidate. 11857 * @param right The right coordinate of the rectangle to invalidate. 11858 * @param bottom The bottom coordinate of the rectangle to invalidate. 11859 * 11860 * @see #invalidate(int, int, int, int) 11861 * @see #invalidate(Rect) 11862 */ 11863 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11864 // We try only with the AttachInfo because there's no point in invalidating 11865 // if we are not attached to our window 11866 final AttachInfo attachInfo = mAttachInfo; 11867 if (attachInfo != null) { 11868 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11869 info.target = this; 11870 info.left = left; 11871 info.top = top; 11872 info.right = right; 11873 info.bottom = bottom; 11874 11875 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11876 } 11877 } 11878 11879 /** 11880 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11881 * This event is sent at most once every 11882 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11883 */ 11884 private void postSendViewScrolledAccessibilityEventCallback() { 11885 if (mSendViewScrolledAccessibilityEvent == null) { 11886 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11887 } 11888 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11889 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11890 postDelayed(mSendViewScrolledAccessibilityEvent, 11891 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11892 } 11893 } 11894 11895 /** 11896 * Called by a parent to request that a child update its values for mScrollX 11897 * and mScrollY if necessary. This will typically be done if the child is 11898 * animating a scroll using a {@link android.widget.Scroller Scroller} 11899 * object. 11900 */ 11901 public void computeScroll() { 11902 } 11903 11904 /** 11905 * <p>Indicate whether the horizontal edges are faded when the view is 11906 * scrolled horizontally.</p> 11907 * 11908 * @return true if the horizontal edges should are faded on scroll, false 11909 * otherwise 11910 * 11911 * @see #setHorizontalFadingEdgeEnabled(boolean) 11912 * 11913 * @attr ref android.R.styleable#View_requiresFadingEdge 11914 */ 11915 public boolean isHorizontalFadingEdgeEnabled() { 11916 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11917 } 11918 11919 /** 11920 * <p>Define whether the horizontal edges should be faded when this view 11921 * is scrolled horizontally.</p> 11922 * 11923 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11924 * be faded when the view is scrolled 11925 * horizontally 11926 * 11927 * @see #isHorizontalFadingEdgeEnabled() 11928 * 11929 * @attr ref android.R.styleable#View_requiresFadingEdge 11930 */ 11931 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11932 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11933 if (horizontalFadingEdgeEnabled) { 11934 initScrollCache(); 11935 } 11936 11937 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11938 } 11939 } 11940 11941 /** 11942 * <p>Indicate whether the vertical edges are faded when the view is 11943 * scrolled horizontally.</p> 11944 * 11945 * @return true if the vertical edges should are faded on scroll, false 11946 * otherwise 11947 * 11948 * @see #setVerticalFadingEdgeEnabled(boolean) 11949 * 11950 * @attr ref android.R.styleable#View_requiresFadingEdge 11951 */ 11952 public boolean isVerticalFadingEdgeEnabled() { 11953 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11954 } 11955 11956 /** 11957 * <p>Define whether the vertical edges should be faded when this view 11958 * is scrolled vertically.</p> 11959 * 11960 * @param verticalFadingEdgeEnabled true if the vertical edges should 11961 * be faded when the view is scrolled 11962 * vertically 11963 * 11964 * @see #isVerticalFadingEdgeEnabled() 11965 * 11966 * @attr ref android.R.styleable#View_requiresFadingEdge 11967 */ 11968 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11969 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11970 if (verticalFadingEdgeEnabled) { 11971 initScrollCache(); 11972 } 11973 11974 mViewFlags ^= FADING_EDGE_VERTICAL; 11975 } 11976 } 11977 11978 /** 11979 * Returns the strength, or intensity, of the top 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 top fade as a float between 0.0f and 1.0f 11987 */ 11988 protected float getTopFadingEdgeStrength() { 11989 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11990 } 11991 11992 /** 11993 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11994 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11995 * returns 0.0 or 1.0 but no value in between. 11996 * 11997 * Subclasses should override this method to provide a smoother fade transition 11998 * when scrolling occurs. 11999 * 12000 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 12001 */ 12002 protected float getBottomFadingEdgeStrength() { 12003 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 12004 computeVerticalScrollRange() ? 1.0f : 0.0f; 12005 } 12006 12007 /** 12008 * Returns the strength, or intensity, of the left 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 left fade as a float between 0.0f and 1.0f 12016 */ 12017 protected float getLeftFadingEdgeStrength() { 12018 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12019 } 12020 12021 /** 12022 * Returns the strength, or intensity, of the right faded edge. The strength is 12023 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12024 * returns 0.0 or 1.0 but no value in between. 12025 * 12026 * Subclasses should override this method to provide a smoother fade transition 12027 * when scrolling occurs. 12028 * 12029 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12030 */ 12031 protected float getRightFadingEdgeStrength() { 12032 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12033 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12034 } 12035 12036 /** 12037 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12038 * scrollbar is not drawn by default.</p> 12039 * 12040 * @return true if the horizontal scrollbar should be painted, false 12041 * otherwise 12042 * 12043 * @see #setHorizontalScrollBarEnabled(boolean) 12044 */ 12045 public boolean isHorizontalScrollBarEnabled() { 12046 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12047 } 12048 12049 /** 12050 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12051 * scrollbar is not drawn by default.</p> 12052 * 12053 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12054 * be painted 12055 * 12056 * @see #isHorizontalScrollBarEnabled() 12057 */ 12058 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12059 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12060 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12061 computeOpaqueFlags(); 12062 resolvePadding(); 12063 } 12064 } 12065 12066 /** 12067 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12068 * scrollbar is not drawn by default.</p> 12069 * 12070 * @return true if the vertical scrollbar should be painted, false 12071 * otherwise 12072 * 12073 * @see #setVerticalScrollBarEnabled(boolean) 12074 */ 12075 public boolean isVerticalScrollBarEnabled() { 12076 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12077 } 12078 12079 /** 12080 * <p>Define whether the vertical scrollbar should be drawn or not. The 12081 * scrollbar is not drawn by default.</p> 12082 * 12083 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12084 * be painted 12085 * 12086 * @see #isVerticalScrollBarEnabled() 12087 */ 12088 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12089 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12090 mViewFlags ^= SCROLLBARS_VERTICAL; 12091 computeOpaqueFlags(); 12092 resolvePadding(); 12093 } 12094 } 12095 12096 /** 12097 * @hide 12098 */ 12099 protected void recomputePadding() { 12100 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12101 } 12102 12103 /** 12104 * Define whether scrollbars will fade when the view is not scrolling. 12105 * 12106 * @param fadeScrollbars wheter to enable fading 12107 * 12108 * @attr ref android.R.styleable#View_fadeScrollbars 12109 */ 12110 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12111 initScrollCache(); 12112 final ScrollabilityCache scrollabilityCache = mScrollCache; 12113 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12114 if (fadeScrollbars) { 12115 scrollabilityCache.state = ScrollabilityCache.OFF; 12116 } else { 12117 scrollabilityCache.state = ScrollabilityCache.ON; 12118 } 12119 } 12120 12121 /** 12122 * 12123 * Returns true if scrollbars will fade when this view is not scrolling 12124 * 12125 * @return true if scrollbar fading is enabled 12126 * 12127 * @attr ref android.R.styleable#View_fadeScrollbars 12128 */ 12129 public boolean isScrollbarFadingEnabled() { 12130 return mScrollCache != null && mScrollCache.fadeScrollBars; 12131 } 12132 12133 /** 12134 * 12135 * Returns the delay before scrollbars fade. 12136 * 12137 * @return the delay before scrollbars fade 12138 * 12139 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12140 */ 12141 public int getScrollBarDefaultDelayBeforeFade() { 12142 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12143 mScrollCache.scrollBarDefaultDelayBeforeFade; 12144 } 12145 12146 /** 12147 * Define the delay before scrollbars fade. 12148 * 12149 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12150 * 12151 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12152 */ 12153 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12154 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12155 } 12156 12157 /** 12158 * 12159 * Returns the scrollbar fade duration. 12160 * 12161 * @return the scrollbar fade duration 12162 * 12163 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12164 */ 12165 public int getScrollBarFadeDuration() { 12166 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12167 mScrollCache.scrollBarFadeDuration; 12168 } 12169 12170 /** 12171 * Define the scrollbar fade duration. 12172 * 12173 * @param scrollBarFadeDuration - the scrollbar fade duration 12174 * 12175 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12176 */ 12177 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12178 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12179 } 12180 12181 /** 12182 * 12183 * Returns the scrollbar size. 12184 * 12185 * @return the scrollbar size 12186 * 12187 * @attr ref android.R.styleable#View_scrollbarSize 12188 */ 12189 public int getScrollBarSize() { 12190 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12191 mScrollCache.scrollBarSize; 12192 } 12193 12194 /** 12195 * Define the scrollbar size. 12196 * 12197 * @param scrollBarSize - the scrollbar size 12198 * 12199 * @attr ref android.R.styleable#View_scrollbarSize 12200 */ 12201 public void setScrollBarSize(int scrollBarSize) { 12202 getScrollCache().scrollBarSize = scrollBarSize; 12203 } 12204 12205 /** 12206 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12207 * inset. When inset, they add to the padding of the view. And the scrollbars 12208 * can be drawn inside the padding area or on the edge of the view. For example, 12209 * if a view has a background drawable and you want to draw the scrollbars 12210 * inside the padding specified by the drawable, you can use 12211 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12212 * appear at the edge of the view, ignoring the padding, then you can use 12213 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12214 * @param style the style of the scrollbars. Should be one of 12215 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12216 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12217 * @see #SCROLLBARS_INSIDE_OVERLAY 12218 * @see #SCROLLBARS_INSIDE_INSET 12219 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12220 * @see #SCROLLBARS_OUTSIDE_INSET 12221 * 12222 * @attr ref android.R.styleable#View_scrollbarStyle 12223 */ 12224 public void setScrollBarStyle(@ScrollBarStyle int style) { 12225 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12226 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12227 computeOpaqueFlags(); 12228 resolvePadding(); 12229 } 12230 } 12231 12232 /** 12233 * <p>Returns the current scrollbar style.</p> 12234 * @return the current scrollbar style 12235 * @see #SCROLLBARS_INSIDE_OVERLAY 12236 * @see #SCROLLBARS_INSIDE_INSET 12237 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12238 * @see #SCROLLBARS_OUTSIDE_INSET 12239 * 12240 * @attr ref android.R.styleable#View_scrollbarStyle 12241 */ 12242 @ViewDebug.ExportedProperty(mapping = { 12243 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12244 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12245 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12246 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12247 }) 12248 @ScrollBarStyle 12249 public int getScrollBarStyle() { 12250 return mViewFlags & SCROLLBARS_STYLE_MASK; 12251 } 12252 12253 /** 12254 * <p>Compute the horizontal range that the horizontal scrollbar 12255 * represents.</p> 12256 * 12257 * <p>The range is expressed in arbitrary units that must be the same as the 12258 * units used by {@link #computeHorizontalScrollExtent()} and 12259 * {@link #computeHorizontalScrollOffset()}.</p> 12260 * 12261 * <p>The default range is the drawing width of this view.</p> 12262 * 12263 * @return the total horizontal range represented by the horizontal 12264 * scrollbar 12265 * 12266 * @see #computeHorizontalScrollExtent() 12267 * @see #computeHorizontalScrollOffset() 12268 * @see android.widget.ScrollBarDrawable 12269 */ 12270 protected int computeHorizontalScrollRange() { 12271 return getWidth(); 12272 } 12273 12274 /** 12275 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12276 * within the horizontal range. This value is used to compute the position 12277 * of the thumb within the scrollbar's track.</p> 12278 * 12279 * <p>The range is expressed in arbitrary units that must be the same as the 12280 * units used by {@link #computeHorizontalScrollRange()} and 12281 * {@link #computeHorizontalScrollExtent()}.</p> 12282 * 12283 * <p>The default offset is the scroll offset of this view.</p> 12284 * 12285 * @return the horizontal offset of the scrollbar's thumb 12286 * 12287 * @see #computeHorizontalScrollRange() 12288 * @see #computeHorizontalScrollExtent() 12289 * @see android.widget.ScrollBarDrawable 12290 */ 12291 protected int computeHorizontalScrollOffset() { 12292 return mScrollX; 12293 } 12294 12295 /** 12296 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12297 * within the horizontal range. This value is used to compute the length 12298 * of the thumb within the scrollbar's track.</p> 12299 * 12300 * <p>The range is expressed in arbitrary units that must be the same as the 12301 * units used by {@link #computeHorizontalScrollRange()} and 12302 * {@link #computeHorizontalScrollOffset()}.</p> 12303 * 12304 * <p>The default extent is the drawing width of this view.</p> 12305 * 12306 * @return the horizontal extent of the scrollbar's thumb 12307 * 12308 * @see #computeHorizontalScrollRange() 12309 * @see #computeHorizontalScrollOffset() 12310 * @see android.widget.ScrollBarDrawable 12311 */ 12312 protected int computeHorizontalScrollExtent() { 12313 return getWidth(); 12314 } 12315 12316 /** 12317 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12318 * 12319 * <p>The range is expressed in arbitrary units that must be the same as the 12320 * units used by {@link #computeVerticalScrollExtent()} and 12321 * {@link #computeVerticalScrollOffset()}.</p> 12322 * 12323 * @return the total vertical range represented by the vertical scrollbar 12324 * 12325 * <p>The default range is the drawing height of this view.</p> 12326 * 12327 * @see #computeVerticalScrollExtent() 12328 * @see #computeVerticalScrollOffset() 12329 * @see android.widget.ScrollBarDrawable 12330 */ 12331 protected int computeVerticalScrollRange() { 12332 return getHeight(); 12333 } 12334 12335 /** 12336 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12337 * within the horizontal range. This value is used to compute the position 12338 * of the thumb within the scrollbar's track.</p> 12339 * 12340 * <p>The range is expressed in arbitrary units that must be the same as the 12341 * units used by {@link #computeVerticalScrollRange()} and 12342 * {@link #computeVerticalScrollExtent()}.</p> 12343 * 12344 * <p>The default offset is the scroll offset of this view.</p> 12345 * 12346 * @return the vertical offset of the scrollbar's thumb 12347 * 12348 * @see #computeVerticalScrollRange() 12349 * @see #computeVerticalScrollExtent() 12350 * @see android.widget.ScrollBarDrawable 12351 */ 12352 protected int computeVerticalScrollOffset() { 12353 return mScrollY; 12354 } 12355 12356 /** 12357 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12358 * within the vertical range. This value is used to compute the length 12359 * of the thumb within the scrollbar's track.</p> 12360 * 12361 * <p>The range is expressed in arbitrary units that must be the same as the 12362 * units used by {@link #computeVerticalScrollRange()} and 12363 * {@link #computeVerticalScrollOffset()}.</p> 12364 * 12365 * <p>The default extent is the drawing height of this view.</p> 12366 * 12367 * @return the vertical extent of the scrollbar's thumb 12368 * 12369 * @see #computeVerticalScrollRange() 12370 * @see #computeVerticalScrollOffset() 12371 * @see android.widget.ScrollBarDrawable 12372 */ 12373 protected int computeVerticalScrollExtent() { 12374 return getHeight(); 12375 } 12376 12377 /** 12378 * Check if this view can be scrolled horizontally in a certain direction. 12379 * 12380 * @param direction Negative to check scrolling left, positive to check scrolling right. 12381 * @return true if this view can be scrolled in the specified direction, false otherwise. 12382 */ 12383 public boolean canScrollHorizontally(int direction) { 12384 final int offset = computeHorizontalScrollOffset(); 12385 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12386 if (range == 0) return false; 12387 if (direction < 0) { 12388 return offset > 0; 12389 } else { 12390 return offset < range - 1; 12391 } 12392 } 12393 12394 /** 12395 * Check if this view can be scrolled vertically in a certain direction. 12396 * 12397 * @param direction Negative to check scrolling up, positive to check scrolling down. 12398 * @return true if this view can be scrolled in the specified direction, false otherwise. 12399 */ 12400 public boolean canScrollVertically(int direction) { 12401 final int offset = computeVerticalScrollOffset(); 12402 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12403 if (range == 0) return false; 12404 if (direction < 0) { 12405 return offset > 0; 12406 } else { 12407 return offset < range - 1; 12408 } 12409 } 12410 12411 /** 12412 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12413 * scrollbars are painted only if they have been awakened first.</p> 12414 * 12415 * @param canvas the canvas on which to draw the scrollbars 12416 * 12417 * @see #awakenScrollBars(int) 12418 */ 12419 protected final void onDrawScrollBars(Canvas canvas) { 12420 // scrollbars are drawn only when the animation is running 12421 final ScrollabilityCache cache = mScrollCache; 12422 if (cache != null) { 12423 12424 int state = cache.state; 12425 12426 if (state == ScrollabilityCache.OFF) { 12427 return; 12428 } 12429 12430 boolean invalidate = false; 12431 12432 if (state == ScrollabilityCache.FADING) { 12433 // We're fading -- get our fade interpolation 12434 if (cache.interpolatorValues == null) { 12435 cache.interpolatorValues = new float[1]; 12436 } 12437 12438 float[] values = cache.interpolatorValues; 12439 12440 // Stops the animation if we're done 12441 if (cache.scrollBarInterpolator.timeToValues(values) == 12442 Interpolator.Result.FREEZE_END) { 12443 cache.state = ScrollabilityCache.OFF; 12444 } else { 12445 cache.scrollBar.setAlpha(Math.round(values[0])); 12446 } 12447 12448 // This will make the scroll bars inval themselves after 12449 // drawing. We only want this when we're fading so that 12450 // we prevent excessive redraws 12451 invalidate = true; 12452 } else { 12453 // We're just on -- but we may have been fading before so 12454 // reset alpha 12455 cache.scrollBar.setAlpha(255); 12456 } 12457 12458 12459 final int viewFlags = mViewFlags; 12460 12461 final boolean drawHorizontalScrollBar = 12462 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12463 final boolean drawVerticalScrollBar = 12464 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12465 && !isVerticalScrollBarHidden(); 12466 12467 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12468 final int width = mRight - mLeft; 12469 final int height = mBottom - mTop; 12470 12471 final ScrollBarDrawable scrollBar = cache.scrollBar; 12472 12473 final int scrollX = mScrollX; 12474 final int scrollY = mScrollY; 12475 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12476 12477 int left; 12478 int top; 12479 int right; 12480 int bottom; 12481 12482 if (drawHorizontalScrollBar) { 12483 int size = scrollBar.getSize(false); 12484 if (size <= 0) { 12485 size = cache.scrollBarSize; 12486 } 12487 12488 scrollBar.setParameters(computeHorizontalScrollRange(), 12489 computeHorizontalScrollOffset(), 12490 computeHorizontalScrollExtent(), false); 12491 final int verticalScrollBarGap = drawVerticalScrollBar ? 12492 getVerticalScrollbarWidth() : 0; 12493 top = scrollY + height - size - (mUserPaddingBottom & inside); 12494 left = scrollX + (mPaddingLeft & inside); 12495 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12496 bottom = top + size; 12497 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12498 if (invalidate) { 12499 invalidate(left, top, right, bottom); 12500 } 12501 } 12502 12503 if (drawVerticalScrollBar) { 12504 int size = scrollBar.getSize(true); 12505 if (size <= 0) { 12506 size = cache.scrollBarSize; 12507 } 12508 12509 scrollBar.setParameters(computeVerticalScrollRange(), 12510 computeVerticalScrollOffset(), 12511 computeVerticalScrollExtent(), true); 12512 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12513 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12514 verticalScrollbarPosition = isLayoutRtl() ? 12515 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12516 } 12517 switch (verticalScrollbarPosition) { 12518 default: 12519 case SCROLLBAR_POSITION_RIGHT: 12520 left = scrollX + width - size - (mUserPaddingRight & inside); 12521 break; 12522 case SCROLLBAR_POSITION_LEFT: 12523 left = scrollX + (mUserPaddingLeft & inside); 12524 break; 12525 } 12526 top = scrollY + (mPaddingTop & inside); 12527 right = left + size; 12528 bottom = scrollY + height - (mUserPaddingBottom & inside); 12529 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12530 if (invalidate) { 12531 invalidate(left, top, right, bottom); 12532 } 12533 } 12534 } 12535 } 12536 } 12537 12538 /** 12539 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12540 * FastScroller is visible. 12541 * @return whether to temporarily hide the vertical scrollbar 12542 * @hide 12543 */ 12544 protected boolean isVerticalScrollBarHidden() { 12545 return false; 12546 } 12547 12548 /** 12549 * <p>Draw the horizontal scrollbar if 12550 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12551 * 12552 * @param canvas the canvas on which to draw the scrollbar 12553 * @param scrollBar the scrollbar's drawable 12554 * 12555 * @see #isHorizontalScrollBarEnabled() 12556 * @see #computeHorizontalScrollRange() 12557 * @see #computeHorizontalScrollExtent() 12558 * @see #computeHorizontalScrollOffset() 12559 * @see android.widget.ScrollBarDrawable 12560 * @hide 12561 */ 12562 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12563 int l, int t, int r, int b) { 12564 scrollBar.setBounds(l, t, r, b); 12565 scrollBar.draw(canvas); 12566 } 12567 12568 /** 12569 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12570 * returns true.</p> 12571 * 12572 * @param canvas the canvas on which to draw the scrollbar 12573 * @param scrollBar the scrollbar's drawable 12574 * 12575 * @see #isVerticalScrollBarEnabled() 12576 * @see #computeVerticalScrollRange() 12577 * @see #computeVerticalScrollExtent() 12578 * @see #computeVerticalScrollOffset() 12579 * @see android.widget.ScrollBarDrawable 12580 * @hide 12581 */ 12582 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12583 int l, int t, int r, int b) { 12584 scrollBar.setBounds(l, t, r, b); 12585 scrollBar.draw(canvas); 12586 } 12587 12588 /** 12589 * Implement this to do your drawing. 12590 * 12591 * @param canvas the canvas on which the background will be drawn 12592 */ 12593 protected void onDraw(Canvas canvas) { 12594 } 12595 12596 /* 12597 * Caller is responsible for calling requestLayout if necessary. 12598 * (This allows addViewInLayout to not request a new layout.) 12599 */ 12600 void assignParent(ViewParent parent) { 12601 if (mParent == null) { 12602 mParent = parent; 12603 } else if (parent == null) { 12604 mParent = null; 12605 } else { 12606 throw new RuntimeException("view " + this + " being added, but" 12607 + " it already has a parent"); 12608 } 12609 } 12610 12611 /** 12612 * This is called when the view is attached to a window. At this point it 12613 * has a Surface and will start drawing. Note that this function is 12614 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12615 * however it may be called any time before the first onDraw -- including 12616 * before or after {@link #onMeasure(int, int)}. 12617 * 12618 * @see #onDetachedFromWindow() 12619 */ 12620 protected void onAttachedToWindow() { 12621 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12622 mParent.requestTransparentRegion(this); 12623 } 12624 12625 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12626 initialAwakenScrollBars(); 12627 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12628 } 12629 12630 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12631 12632 jumpDrawablesToCurrentState(); 12633 12634 resetSubtreeAccessibilityStateChanged(); 12635 12636 if (isFocused()) { 12637 InputMethodManager imm = InputMethodManager.peekInstance(); 12638 imm.focusIn(this); 12639 } 12640 } 12641 12642 /** 12643 * Resolve all RTL related properties. 12644 * 12645 * @return true if resolution of RTL properties has been done 12646 * 12647 * @hide 12648 */ 12649 public boolean resolveRtlPropertiesIfNeeded() { 12650 if (!needRtlPropertiesResolution()) return false; 12651 12652 // Order is important here: LayoutDirection MUST be resolved first 12653 if (!isLayoutDirectionResolved()) { 12654 resolveLayoutDirection(); 12655 resolveLayoutParams(); 12656 } 12657 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12658 if (!isTextDirectionResolved()) { 12659 resolveTextDirection(); 12660 } 12661 if (!isTextAlignmentResolved()) { 12662 resolveTextAlignment(); 12663 } 12664 // Should resolve Drawables before Padding because we need the layout direction of the 12665 // Drawable to correctly resolve Padding. 12666 if (!isDrawablesResolved()) { 12667 resolveDrawables(); 12668 } 12669 if (!isPaddingResolved()) { 12670 resolvePadding(); 12671 } 12672 onRtlPropertiesChanged(getLayoutDirection()); 12673 return true; 12674 } 12675 12676 /** 12677 * Reset resolution of all RTL related properties. 12678 * 12679 * @hide 12680 */ 12681 public void resetRtlProperties() { 12682 resetResolvedLayoutDirection(); 12683 resetResolvedTextDirection(); 12684 resetResolvedTextAlignment(); 12685 resetResolvedPadding(); 12686 resetResolvedDrawables(); 12687 } 12688 12689 /** 12690 * @see #onScreenStateChanged(int) 12691 */ 12692 void dispatchScreenStateChanged(int screenState) { 12693 onScreenStateChanged(screenState); 12694 } 12695 12696 /** 12697 * This method is called whenever the state of the screen this view is 12698 * attached to changes. A state change will usually occurs when the screen 12699 * turns on or off (whether it happens automatically or the user does it 12700 * manually.) 12701 * 12702 * @param screenState The new state of the screen. Can be either 12703 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12704 */ 12705 public void onScreenStateChanged(int screenState) { 12706 } 12707 12708 /** 12709 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12710 */ 12711 private boolean hasRtlSupport() { 12712 return mContext.getApplicationInfo().hasRtlSupport(); 12713 } 12714 12715 /** 12716 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12717 * RTL not supported) 12718 */ 12719 private boolean isRtlCompatibilityMode() { 12720 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12721 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12722 } 12723 12724 /** 12725 * @return true if RTL properties need resolution. 12726 * 12727 */ 12728 private boolean needRtlPropertiesResolution() { 12729 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12730 } 12731 12732 /** 12733 * Called when any RTL property (layout direction or text direction or text alignment) has 12734 * been changed. 12735 * 12736 * Subclasses need to override this method to take care of cached information that depends on the 12737 * resolved layout direction, or to inform child views that inherit their layout direction. 12738 * 12739 * The default implementation does nothing. 12740 * 12741 * @param layoutDirection the direction of the layout 12742 * 12743 * @see #LAYOUT_DIRECTION_LTR 12744 * @see #LAYOUT_DIRECTION_RTL 12745 */ 12746 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12747 } 12748 12749 /** 12750 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12751 * that the parent directionality can and will be resolved before its children. 12752 * 12753 * @return true if resolution has been done, false otherwise. 12754 * 12755 * @hide 12756 */ 12757 public boolean resolveLayoutDirection() { 12758 // Clear any previous layout direction resolution 12759 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12760 12761 if (hasRtlSupport()) { 12762 // Set resolved depending on layout direction 12763 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12764 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12765 case LAYOUT_DIRECTION_INHERIT: 12766 // We cannot resolve yet. LTR is by default and let the resolution happen again 12767 // later to get the correct resolved value 12768 if (!canResolveLayoutDirection()) return false; 12769 12770 // Parent has not yet resolved, LTR is still the default 12771 try { 12772 if (!mParent.isLayoutDirectionResolved()) return false; 12773 12774 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12775 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12776 } 12777 } catch (AbstractMethodError e) { 12778 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12779 " does not fully implement ViewParent", e); 12780 } 12781 break; 12782 case LAYOUT_DIRECTION_RTL: 12783 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12784 break; 12785 case LAYOUT_DIRECTION_LOCALE: 12786 if((LAYOUT_DIRECTION_RTL == 12787 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12788 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12789 } 12790 break; 12791 default: 12792 // Nothing to do, LTR by default 12793 } 12794 } 12795 12796 // Set to resolved 12797 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12798 return true; 12799 } 12800 12801 /** 12802 * Check if layout direction resolution can be done. 12803 * 12804 * @return true if layout direction resolution can be done otherwise return false. 12805 */ 12806 public boolean canResolveLayoutDirection() { 12807 switch (getRawLayoutDirection()) { 12808 case LAYOUT_DIRECTION_INHERIT: 12809 if (mParent != null) { 12810 try { 12811 return mParent.canResolveLayoutDirection(); 12812 } catch (AbstractMethodError e) { 12813 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12814 " does not fully implement ViewParent", e); 12815 } 12816 } 12817 return false; 12818 12819 default: 12820 return true; 12821 } 12822 } 12823 12824 /** 12825 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12826 * {@link #onMeasure(int, int)}. 12827 * 12828 * @hide 12829 */ 12830 public void resetResolvedLayoutDirection() { 12831 // Reset the current resolved bits 12832 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12833 } 12834 12835 /** 12836 * @return true if the layout direction is inherited. 12837 * 12838 * @hide 12839 */ 12840 public boolean isLayoutDirectionInherited() { 12841 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12842 } 12843 12844 /** 12845 * @return true if layout direction has been resolved. 12846 */ 12847 public boolean isLayoutDirectionResolved() { 12848 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12849 } 12850 12851 /** 12852 * Return if padding has been resolved 12853 * 12854 * @hide 12855 */ 12856 boolean isPaddingResolved() { 12857 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12858 } 12859 12860 /** 12861 * Resolves padding depending on layout direction, if applicable, and 12862 * recomputes internal padding values to adjust for scroll bars. 12863 * 12864 * @hide 12865 */ 12866 public void resolvePadding() { 12867 final int resolvedLayoutDirection = getLayoutDirection(); 12868 12869 if (!isRtlCompatibilityMode()) { 12870 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12871 // If start / end padding are defined, they will be resolved (hence overriding) to 12872 // left / right or right / left depending on the resolved layout direction. 12873 // If start / end padding are not defined, use the left / right ones. 12874 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12875 Rect padding = sThreadLocal.get(); 12876 if (padding == null) { 12877 padding = new Rect(); 12878 sThreadLocal.set(padding); 12879 } 12880 mBackground.getPadding(padding); 12881 if (!mLeftPaddingDefined) { 12882 mUserPaddingLeftInitial = padding.left; 12883 } 12884 if (!mRightPaddingDefined) { 12885 mUserPaddingRightInitial = padding.right; 12886 } 12887 } 12888 switch (resolvedLayoutDirection) { 12889 case LAYOUT_DIRECTION_RTL: 12890 if (mUserPaddingStart != UNDEFINED_PADDING) { 12891 mUserPaddingRight = mUserPaddingStart; 12892 } else { 12893 mUserPaddingRight = mUserPaddingRightInitial; 12894 } 12895 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12896 mUserPaddingLeft = mUserPaddingEnd; 12897 } else { 12898 mUserPaddingLeft = mUserPaddingLeftInitial; 12899 } 12900 break; 12901 case LAYOUT_DIRECTION_LTR: 12902 default: 12903 if (mUserPaddingStart != UNDEFINED_PADDING) { 12904 mUserPaddingLeft = mUserPaddingStart; 12905 } else { 12906 mUserPaddingLeft = mUserPaddingLeftInitial; 12907 } 12908 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12909 mUserPaddingRight = mUserPaddingEnd; 12910 } else { 12911 mUserPaddingRight = mUserPaddingRightInitial; 12912 } 12913 } 12914 12915 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12916 } 12917 12918 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12919 onRtlPropertiesChanged(resolvedLayoutDirection); 12920 12921 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12922 } 12923 12924 /** 12925 * Reset the resolved layout direction. 12926 * 12927 * @hide 12928 */ 12929 public void resetResolvedPadding() { 12930 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12931 } 12932 12933 /** 12934 * This is called when the view is detached from a window. At this point it 12935 * no longer has a surface for drawing. 12936 * 12937 * @see #onAttachedToWindow() 12938 */ 12939 protected void onDetachedFromWindow() { 12940 } 12941 12942 /** 12943 * This is a framework-internal mirror of onDetachedFromWindow() that's called 12944 * after onDetachedFromWindow(). 12945 * 12946 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 12947 * The super method should be called at the end of the overriden method to ensure 12948 * subclasses are destroyed first 12949 * 12950 * @hide 12951 */ 12952 protected void onDetachedFromWindowInternal() { 12953 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12954 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12955 12956 removeUnsetPressCallback(); 12957 removeLongPressCallback(); 12958 removePerformClickCallback(); 12959 removeSendViewScrolledAccessibilityEventCallback(); 12960 stopNestedScroll(); 12961 12962 destroyDrawingCache(); 12963 12964 cleanupDraw(); 12965 mCurrentAnimation = null; 12966 } 12967 12968 private void cleanupDraw() { 12969 resetDisplayList(); 12970 if (mAttachInfo != null) { 12971 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12972 } 12973 } 12974 12975 /** 12976 * This method ensures the hardware renderer is in a valid state 12977 * before executing the specified action. 12978 * 12979 * This method will attempt to set a valid state even if the window 12980 * the renderer is attached to was destroyed. 12981 * 12982 * This method is not guaranteed to work. If the hardware renderer 12983 * does not exist or cannot be put in a valid state, this method 12984 * will not executed the specified action. 12985 * 12986 * The specified action is executed synchronously. 12987 * 12988 * @param action The action to execute after the renderer is in a valid state 12989 * 12990 * @return True if the specified Runnable was executed, false otherwise 12991 * 12992 * @hide 12993 */ 12994 public boolean executeHardwareAction(Runnable action) { 12995 //noinspection SimplifiableIfStatement 12996 if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) { 12997 return mAttachInfo.mHardwareRenderer.safelyRun(action); 12998 } 12999 return false; 13000 } 13001 13002 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 13003 } 13004 13005 /** 13006 * @return The number of times this view has been attached to a window 13007 */ 13008 protected int getWindowAttachCount() { 13009 return mWindowAttachCount; 13010 } 13011 13012 /** 13013 * Retrieve a unique token identifying the window this view is attached to. 13014 * @return Return the window's token for use in 13015 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13016 */ 13017 public IBinder getWindowToken() { 13018 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13019 } 13020 13021 /** 13022 * Retrieve the {@link WindowId} for the window this view is 13023 * currently attached to. 13024 */ 13025 public WindowId getWindowId() { 13026 if (mAttachInfo == null) { 13027 return null; 13028 } 13029 if (mAttachInfo.mWindowId == null) { 13030 try { 13031 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13032 mAttachInfo.mWindowToken); 13033 mAttachInfo.mWindowId = new WindowId( 13034 mAttachInfo.mIWindowId); 13035 } catch (RemoteException e) { 13036 } 13037 } 13038 return mAttachInfo.mWindowId; 13039 } 13040 13041 /** 13042 * Retrieve a unique token identifying the top-level "real" window of 13043 * the window that this view is attached to. That is, this is like 13044 * {@link #getWindowToken}, except if the window this view in is a panel 13045 * window (attached to another containing window), then the token of 13046 * the containing window is returned instead. 13047 * 13048 * @return Returns the associated window token, either 13049 * {@link #getWindowToken()} or the containing window's token. 13050 */ 13051 public IBinder getApplicationWindowToken() { 13052 AttachInfo ai = mAttachInfo; 13053 if (ai != null) { 13054 IBinder appWindowToken = ai.mPanelParentWindowToken; 13055 if (appWindowToken == null) { 13056 appWindowToken = ai.mWindowToken; 13057 } 13058 return appWindowToken; 13059 } 13060 return null; 13061 } 13062 13063 /** 13064 * Gets the logical display to which the view's window has been attached. 13065 * 13066 * @return The logical display, or null if the view is not currently attached to a window. 13067 */ 13068 public Display getDisplay() { 13069 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13070 } 13071 13072 /** 13073 * Retrieve private session object this view hierarchy is using to 13074 * communicate with the window manager. 13075 * @return the session object to communicate with the window manager 13076 */ 13077 /*package*/ IWindowSession getWindowSession() { 13078 return mAttachInfo != null ? mAttachInfo.mSession : null; 13079 } 13080 13081 /** 13082 * @param info the {@link android.view.View.AttachInfo} to associated with 13083 * this view 13084 */ 13085 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13086 //System.out.println("Attached! " + this); 13087 mAttachInfo = info; 13088 if (mOverlay != null) { 13089 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13090 } 13091 mWindowAttachCount++; 13092 // We will need to evaluate the drawable state at least once. 13093 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13094 if (mFloatingTreeObserver != null) { 13095 info.mTreeObserver.merge(mFloatingTreeObserver); 13096 mFloatingTreeObserver = null; 13097 } 13098 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13099 mAttachInfo.mScrollContainers.add(this); 13100 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13101 } 13102 performCollectViewAttributes(mAttachInfo, visibility); 13103 onAttachedToWindow(); 13104 13105 ListenerInfo li = mListenerInfo; 13106 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13107 li != null ? li.mOnAttachStateChangeListeners : null; 13108 if (listeners != null && listeners.size() > 0) { 13109 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13110 // perform the dispatching. The iterator is a safe guard against listeners that 13111 // could mutate the list by calling the various add/remove methods. This prevents 13112 // the array from being modified while we iterate it. 13113 for (OnAttachStateChangeListener listener : listeners) { 13114 listener.onViewAttachedToWindow(this); 13115 } 13116 } 13117 13118 int vis = info.mWindowVisibility; 13119 if (vis != GONE) { 13120 onWindowVisibilityChanged(vis); 13121 } 13122 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13123 // If nobody has evaluated the drawable state yet, then do it now. 13124 refreshDrawableState(); 13125 } 13126 needGlobalAttributesUpdate(false); 13127 } 13128 13129 void dispatchDetachedFromWindow() { 13130 AttachInfo info = mAttachInfo; 13131 if (info != null) { 13132 int vis = info.mWindowVisibility; 13133 if (vis != GONE) { 13134 onWindowVisibilityChanged(GONE); 13135 } 13136 } 13137 13138 onDetachedFromWindow(); 13139 onDetachedFromWindowInternal(); 13140 13141 ListenerInfo li = mListenerInfo; 13142 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13143 li != null ? li.mOnAttachStateChangeListeners : null; 13144 if (listeners != null && listeners.size() > 0) { 13145 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13146 // perform the dispatching. The iterator is a safe guard against listeners that 13147 // could mutate the list by calling the various add/remove methods. This prevents 13148 // the array from being modified while we iterate it. 13149 for (OnAttachStateChangeListener listener : listeners) { 13150 listener.onViewDetachedFromWindow(this); 13151 } 13152 } 13153 13154 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13155 mAttachInfo.mScrollContainers.remove(this); 13156 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13157 } 13158 13159 mAttachInfo = null; 13160 if (mOverlay != null) { 13161 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13162 } 13163 } 13164 13165 /** 13166 * Cancel any deferred high-level input events that were previously posted to the event queue. 13167 * 13168 * <p>Many views post high-level events such as click handlers to the event queue 13169 * to run deferred in order to preserve a desired user experience - clearing visible 13170 * pressed states before executing, etc. This method will abort any events of this nature 13171 * that are currently in flight.</p> 13172 * 13173 * <p>Custom views that generate their own high-level deferred input events should override 13174 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13175 * 13176 * <p>This will also cancel pending input events for any child views.</p> 13177 * 13178 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13179 * This will not impact newer events posted after this call that may occur as a result of 13180 * lower-level input events still waiting in the queue. If you are trying to prevent 13181 * double-submitted events for the duration of some sort of asynchronous transaction 13182 * you should also take other steps to protect against unexpected double inputs e.g. calling 13183 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13184 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13185 */ 13186 public final void cancelPendingInputEvents() { 13187 dispatchCancelPendingInputEvents(); 13188 } 13189 13190 /** 13191 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13192 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13193 */ 13194 void dispatchCancelPendingInputEvents() { 13195 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13196 onCancelPendingInputEvents(); 13197 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13198 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13199 " did not call through to super.onCancelPendingInputEvents()"); 13200 } 13201 } 13202 13203 /** 13204 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13205 * a parent view. 13206 * 13207 * <p>This method is responsible for removing any pending high-level input events that were 13208 * posted to the event queue to run later. Custom view classes that post their own deferred 13209 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13210 * {@link android.os.Handler} should override this method, call 13211 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13212 * </p> 13213 */ 13214 public void onCancelPendingInputEvents() { 13215 removePerformClickCallback(); 13216 cancelLongPress(); 13217 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13218 } 13219 13220 /** 13221 * Store this view hierarchy's frozen state into the given container. 13222 * 13223 * @param container The SparseArray in which to save the view's state. 13224 * 13225 * @see #restoreHierarchyState(android.util.SparseArray) 13226 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13227 * @see #onSaveInstanceState() 13228 */ 13229 public void saveHierarchyState(SparseArray<Parcelable> container) { 13230 dispatchSaveInstanceState(container); 13231 } 13232 13233 /** 13234 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13235 * this view and its children. May be overridden to modify how freezing happens to a 13236 * view's children; for example, some views may want to not store state for their children. 13237 * 13238 * @param container The SparseArray in which to save the view's state. 13239 * 13240 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13241 * @see #saveHierarchyState(android.util.SparseArray) 13242 * @see #onSaveInstanceState() 13243 */ 13244 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13245 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13246 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13247 Parcelable state = onSaveInstanceState(); 13248 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13249 throw new IllegalStateException( 13250 "Derived class did not call super.onSaveInstanceState()"); 13251 } 13252 if (state != null) { 13253 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13254 // + ": " + state); 13255 container.put(mID, state); 13256 } 13257 } 13258 } 13259 13260 /** 13261 * Hook allowing a view to generate a representation of its internal state 13262 * that can later be used to create a new instance with that same state. 13263 * This state should only contain information that is not persistent or can 13264 * not be reconstructed later. For example, you will never store your 13265 * current position on screen because that will be computed again when a 13266 * new instance of the view is placed in its view hierarchy. 13267 * <p> 13268 * Some examples of things you may store here: the current cursor position 13269 * in a text view (but usually not the text itself since that is stored in a 13270 * content provider or other persistent storage), the currently selected 13271 * item in a list view. 13272 * 13273 * @return Returns a Parcelable object containing the view's current dynamic 13274 * state, or null if there is nothing interesting to save. The 13275 * default implementation returns null. 13276 * @see #onRestoreInstanceState(android.os.Parcelable) 13277 * @see #saveHierarchyState(android.util.SparseArray) 13278 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13279 * @see #setSaveEnabled(boolean) 13280 */ 13281 protected Parcelable onSaveInstanceState() { 13282 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13283 return BaseSavedState.EMPTY_STATE; 13284 } 13285 13286 /** 13287 * Restore this view hierarchy's frozen state from the given container. 13288 * 13289 * @param container The SparseArray which holds previously frozen states. 13290 * 13291 * @see #saveHierarchyState(android.util.SparseArray) 13292 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13293 * @see #onRestoreInstanceState(android.os.Parcelable) 13294 */ 13295 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13296 dispatchRestoreInstanceState(container); 13297 } 13298 13299 /** 13300 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13301 * state for this view and its children. May be overridden to modify how restoring 13302 * happens to a view's children; for example, some views may want to not store state 13303 * for their children. 13304 * 13305 * @param container The SparseArray which holds previously saved state. 13306 * 13307 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13308 * @see #restoreHierarchyState(android.util.SparseArray) 13309 * @see #onRestoreInstanceState(android.os.Parcelable) 13310 */ 13311 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13312 if (mID != NO_ID) { 13313 Parcelable state = container.get(mID); 13314 if (state != null) { 13315 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13316 // + ": " + state); 13317 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13318 onRestoreInstanceState(state); 13319 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13320 throw new IllegalStateException( 13321 "Derived class did not call super.onRestoreInstanceState()"); 13322 } 13323 } 13324 } 13325 } 13326 13327 /** 13328 * Hook allowing a view to re-apply a representation of its internal state that had previously 13329 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13330 * null state. 13331 * 13332 * @param state The frozen state that had previously been returned by 13333 * {@link #onSaveInstanceState}. 13334 * 13335 * @see #onSaveInstanceState() 13336 * @see #restoreHierarchyState(android.util.SparseArray) 13337 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13338 */ 13339 protected void onRestoreInstanceState(Parcelable state) { 13340 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13341 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13342 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13343 + "received " + state.getClass().toString() + " instead. This usually happens " 13344 + "when two views of different type have the same id in the same hierarchy. " 13345 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13346 + "other views do not use the same id."); 13347 } 13348 } 13349 13350 /** 13351 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13352 * 13353 * @return the drawing start time in milliseconds 13354 */ 13355 public long getDrawingTime() { 13356 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13357 } 13358 13359 /** 13360 * <p>Enables or disables the duplication of the parent's state into this view. When 13361 * duplication is enabled, this view gets its drawable state from its parent rather 13362 * than from its own internal properties.</p> 13363 * 13364 * <p>Note: in the current implementation, setting this property to true after the 13365 * view was added to a ViewGroup might have no effect at all. This property should 13366 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13367 * 13368 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13369 * property is enabled, an exception will be thrown.</p> 13370 * 13371 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13372 * parent, these states should not be affected by this method.</p> 13373 * 13374 * @param enabled True to enable duplication of the parent's drawable state, false 13375 * to disable it. 13376 * 13377 * @see #getDrawableState() 13378 * @see #isDuplicateParentStateEnabled() 13379 */ 13380 public void setDuplicateParentStateEnabled(boolean enabled) { 13381 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13382 } 13383 13384 /** 13385 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13386 * 13387 * @return True if this view's drawable state is duplicated from the parent, 13388 * false otherwise 13389 * 13390 * @see #getDrawableState() 13391 * @see #setDuplicateParentStateEnabled(boolean) 13392 */ 13393 public boolean isDuplicateParentStateEnabled() { 13394 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13395 } 13396 13397 /** 13398 * <p>Specifies the type of layer backing this view. The layer can be 13399 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13400 * {@link #LAYER_TYPE_HARDWARE}.</p> 13401 * 13402 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13403 * instance that controls how the layer is composed on screen. The following 13404 * properties of the paint are taken into account when composing the layer:</p> 13405 * <ul> 13406 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13407 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13408 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13409 * </ul> 13410 * 13411 * <p>If this view has an alpha value set to < 1.0 by calling 13412 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13413 * by this view's alpha value.</p> 13414 * 13415 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13416 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13417 * for more information on when and how to use layers.</p> 13418 * 13419 * @param layerType The type of layer to use with this view, must be one of 13420 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13421 * {@link #LAYER_TYPE_HARDWARE} 13422 * @param paint The paint used to compose the layer. This argument is optional 13423 * and can be null. It is ignored when the layer type is 13424 * {@link #LAYER_TYPE_NONE} 13425 * 13426 * @see #getLayerType() 13427 * @see #LAYER_TYPE_NONE 13428 * @see #LAYER_TYPE_SOFTWARE 13429 * @see #LAYER_TYPE_HARDWARE 13430 * @see #setAlpha(float) 13431 * 13432 * @attr ref android.R.styleable#View_layerType 13433 */ 13434 public void setLayerType(int layerType, Paint paint) { 13435 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13436 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13437 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13438 } 13439 13440 boolean typeChanged = mRenderNode.setLayerType(layerType); 13441 13442 if (!typeChanged) { 13443 setLayerPaint(paint); 13444 return; 13445 } 13446 13447 // Destroy any previous software drawing cache if needed 13448 if (mLayerType == LAYER_TYPE_SOFTWARE) { 13449 destroyDrawingCache(); 13450 } 13451 13452 mLayerType = layerType; 13453 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 13454 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13455 mRenderNode.setLayerPaint(mLayerPaint); 13456 13457 // draw() behaves differently if we are on a layer, so we need to 13458 // invalidate() here 13459 invalidateParentCaches(); 13460 invalidate(true); 13461 } 13462 13463 /** 13464 * Updates the {@link Paint} object used with the current layer (used only if the current 13465 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13466 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13467 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13468 * ensure that the view gets redrawn immediately. 13469 * 13470 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13471 * instance that controls how the layer is composed on screen. The following 13472 * properties of the paint are taken into account when composing the layer:</p> 13473 * <ul> 13474 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13475 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13476 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13477 * </ul> 13478 * 13479 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13480 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13481 * 13482 * @param paint The paint used to compose the layer. This argument is optional 13483 * and can be null. It is ignored when the layer type is 13484 * {@link #LAYER_TYPE_NONE} 13485 * 13486 * @see #setLayerType(int, android.graphics.Paint) 13487 */ 13488 public void setLayerPaint(Paint paint) { 13489 int layerType = getLayerType(); 13490 if (layerType != LAYER_TYPE_NONE) { 13491 mLayerPaint = paint == null ? new Paint() : paint; 13492 if (layerType == LAYER_TYPE_HARDWARE) { 13493 if (mRenderNode.setLayerPaint(mLayerPaint)) { 13494 invalidateViewProperty(false, false); 13495 } 13496 } else { 13497 invalidate(); 13498 } 13499 } 13500 } 13501 13502 /** 13503 * Indicates whether this view has a static layer. A view with layer type 13504 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13505 * dynamic. 13506 */ 13507 boolean hasStaticLayer() { 13508 return true; 13509 } 13510 13511 /** 13512 * Indicates what type of layer is currently associated with this view. By default 13513 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13514 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13515 * for more information on the different types of layers. 13516 * 13517 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13518 * {@link #LAYER_TYPE_HARDWARE} 13519 * 13520 * @see #setLayerType(int, android.graphics.Paint) 13521 * @see #buildLayer() 13522 * @see #LAYER_TYPE_NONE 13523 * @see #LAYER_TYPE_SOFTWARE 13524 * @see #LAYER_TYPE_HARDWARE 13525 */ 13526 public int getLayerType() { 13527 return mLayerType; 13528 } 13529 13530 /** 13531 * Forces this view's layer to be created and this view to be rendered 13532 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13533 * invoking this method will have no effect. 13534 * 13535 * This method can for instance be used to render a view into its layer before 13536 * starting an animation. If this view is complex, rendering into the layer 13537 * before starting the animation will avoid skipping frames. 13538 * 13539 * @throws IllegalStateException If this view is not attached to a window 13540 * 13541 * @see #setLayerType(int, android.graphics.Paint) 13542 */ 13543 public void buildLayer() { 13544 if (mLayerType == LAYER_TYPE_NONE) return; 13545 13546 final AttachInfo attachInfo = mAttachInfo; 13547 if (attachInfo == null) { 13548 throw new IllegalStateException("This view must be attached to a window first"); 13549 } 13550 13551 if (getWidth() == 0 || getHeight() == 0) { 13552 return; 13553 } 13554 13555 switch (mLayerType) { 13556 case LAYER_TYPE_HARDWARE: 13557 // The only part of a hardware layer we can build in response to 13558 // this call is to ensure the display list is up to date. 13559 // The actual rendering of the display list into the layer must 13560 // be done at playback time 13561 updateDisplayListIfDirty(); 13562 break; 13563 case LAYER_TYPE_SOFTWARE: 13564 buildDrawingCache(true); 13565 break; 13566 } 13567 } 13568 13569 /** 13570 * If this View draws with a HardwareLayer, returns it. 13571 * Otherwise returns null 13572 * 13573 * TODO: Only TextureView uses this, can we eliminate it? 13574 */ 13575 HardwareLayer getHardwareLayer() { 13576 return null; 13577 } 13578 13579 /** 13580 * Destroys all hardware rendering resources. This method is invoked 13581 * when the system needs to reclaim resources. Upon execution of this 13582 * method, you should free any OpenGL resources created by the view. 13583 * 13584 * Note: you <strong>must</strong> call 13585 * <code>super.destroyHardwareResources()</code> when overriding 13586 * this method. 13587 * 13588 * @hide 13589 */ 13590 protected void destroyHardwareResources() { 13591 resetDisplayList(); 13592 } 13593 13594 /** 13595 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13596 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13597 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13598 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13599 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13600 * null.</p> 13601 * 13602 * <p>Enabling the drawing cache is similar to 13603 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13604 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13605 * drawing cache has no effect on rendering because the system uses a different mechanism 13606 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13607 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13608 * for information on how to enable software and hardware layers.</p> 13609 * 13610 * <p>This API can be used to manually generate 13611 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13612 * {@link #getDrawingCache()}.</p> 13613 * 13614 * @param enabled true to enable the drawing cache, false otherwise 13615 * 13616 * @see #isDrawingCacheEnabled() 13617 * @see #getDrawingCache() 13618 * @see #buildDrawingCache() 13619 * @see #setLayerType(int, android.graphics.Paint) 13620 */ 13621 public void setDrawingCacheEnabled(boolean enabled) { 13622 mCachingFailed = false; 13623 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13624 } 13625 13626 /** 13627 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13628 * 13629 * @return true if the drawing cache is enabled 13630 * 13631 * @see #setDrawingCacheEnabled(boolean) 13632 * @see #getDrawingCache() 13633 */ 13634 @ViewDebug.ExportedProperty(category = "drawing") 13635 public boolean isDrawingCacheEnabled() { 13636 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13637 } 13638 13639 /** 13640 * Debugging utility which recursively outputs the dirty state of a view and its 13641 * descendants. 13642 * 13643 * @hide 13644 */ 13645 @SuppressWarnings({"UnusedDeclaration"}) 13646 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13647 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13648 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13649 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13650 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13651 if (clear) { 13652 mPrivateFlags &= clearMask; 13653 } 13654 if (this instanceof ViewGroup) { 13655 ViewGroup parent = (ViewGroup) this; 13656 final int count = parent.getChildCount(); 13657 for (int i = 0; i < count; i++) { 13658 final View child = parent.getChildAt(i); 13659 child.outputDirtyFlags(indent + " ", clear, clearMask); 13660 } 13661 } 13662 } 13663 13664 /** 13665 * This method is used by ViewGroup to cause its children to restore or recreate their 13666 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13667 * to recreate its own display list, which would happen if it went through the normal 13668 * draw/dispatchDraw mechanisms. 13669 * 13670 * @hide 13671 */ 13672 protected void dispatchGetDisplayList() {} 13673 13674 /** 13675 * A view that is not attached or hardware accelerated cannot create a display list. 13676 * This method checks these conditions and returns the appropriate result. 13677 * 13678 * @return true if view has the ability to create a display list, false otherwise. 13679 * 13680 * @hide 13681 */ 13682 public boolean canHaveDisplayList() { 13683 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13684 } 13685 13686 private void updateDisplayListIfDirty() { 13687 final RenderNode renderNode = mRenderNode; 13688 if (!canHaveDisplayList()) { 13689 // can't populate RenderNode, don't try 13690 return; 13691 } 13692 13693 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13694 || !renderNode.isValid() 13695 || (mRecreateDisplayList)) { 13696 // Don't need to recreate the display list, just need to tell our 13697 // children to restore/recreate theirs 13698 if (renderNode.isValid() 13699 && !mRecreateDisplayList) { 13700 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13701 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13702 dispatchGetDisplayList(); 13703 13704 return; // no work needed 13705 } 13706 13707 // If we got here, we're recreating it. Mark it as such to ensure that 13708 // we copy in child display lists into ours in drawChild() 13709 mRecreateDisplayList = true; 13710 13711 int width = mRight - mLeft; 13712 int height = mBottom - mTop; 13713 int layerType = getLayerType(); 13714 13715 final HardwareCanvas canvas = renderNode.start(width, height); 13716 13717 try { 13718 final HardwareLayer layer = getHardwareLayer(); 13719 if (layer != null && layer.isValid()) { 13720 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13721 } else if (layerType == LAYER_TYPE_SOFTWARE) { 13722 buildDrawingCache(true); 13723 Bitmap cache = getDrawingCache(true); 13724 if (cache != null) { 13725 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13726 } 13727 } else { 13728 computeScroll(); 13729 13730 canvas.translate(-mScrollX, -mScrollY); 13731 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13732 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13733 13734 // Fast path for layouts with no backgrounds 13735 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13736 dispatchDraw(canvas); 13737 if (mOverlay != null && !mOverlay.isEmpty()) { 13738 mOverlay.getOverlayView().draw(canvas); 13739 } 13740 } else { 13741 draw(canvas); 13742 } 13743 } 13744 } finally { 13745 renderNode.end(canvas); 13746 setDisplayListProperties(renderNode); 13747 } 13748 } else { 13749 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13750 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13751 } 13752 } 13753 13754 /** 13755 * Returns a RenderNode with View draw content recorded, which can be 13756 * used to draw this view again without executing its draw method. 13757 * 13758 * @return A RenderNode ready to replay, or null if caching is not enabled. 13759 * 13760 * @hide 13761 */ 13762 public RenderNode getDisplayList() { 13763 updateDisplayListIfDirty(); 13764 return mRenderNode; 13765 } 13766 13767 private void resetDisplayList() { 13768 if (mRenderNode.isValid()) { 13769 mRenderNode.destroyDisplayListData(); 13770 } 13771 13772 if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) { 13773 mBackgroundDisplayList.destroyDisplayListData(); 13774 } 13775 } 13776 13777 /** 13778 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13779 * 13780 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13781 * 13782 * @see #getDrawingCache(boolean) 13783 */ 13784 public Bitmap getDrawingCache() { 13785 return getDrawingCache(false); 13786 } 13787 13788 /** 13789 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13790 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13791 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13792 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13793 * request the drawing cache by calling this method and draw it on screen if the 13794 * returned bitmap is not null.</p> 13795 * 13796 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13797 * this method will create a bitmap of the same size as this view. Because this bitmap 13798 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13799 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13800 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13801 * size than the view. This implies that your application must be able to handle this 13802 * size.</p> 13803 * 13804 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13805 * the current density of the screen when the application is in compatibility 13806 * mode. 13807 * 13808 * @return A bitmap representing this view or null if cache is disabled. 13809 * 13810 * @see #setDrawingCacheEnabled(boolean) 13811 * @see #isDrawingCacheEnabled() 13812 * @see #buildDrawingCache(boolean) 13813 * @see #destroyDrawingCache() 13814 */ 13815 public Bitmap getDrawingCache(boolean autoScale) { 13816 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13817 return null; 13818 } 13819 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13820 buildDrawingCache(autoScale); 13821 } 13822 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13823 } 13824 13825 /** 13826 * <p>Frees the resources used by the drawing cache. If you call 13827 * {@link #buildDrawingCache()} manually without calling 13828 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13829 * should cleanup the cache with this method afterwards.</p> 13830 * 13831 * @see #setDrawingCacheEnabled(boolean) 13832 * @see #buildDrawingCache() 13833 * @see #getDrawingCache() 13834 */ 13835 public void destroyDrawingCache() { 13836 if (mDrawingCache != null) { 13837 mDrawingCache.recycle(); 13838 mDrawingCache = null; 13839 } 13840 if (mUnscaledDrawingCache != null) { 13841 mUnscaledDrawingCache.recycle(); 13842 mUnscaledDrawingCache = null; 13843 } 13844 } 13845 13846 /** 13847 * Setting a solid background color for the drawing cache's bitmaps will improve 13848 * performance and memory usage. Note, though that this should only be used if this 13849 * view will always be drawn on top of a solid color. 13850 * 13851 * @param color The background color to use for the drawing cache's bitmap 13852 * 13853 * @see #setDrawingCacheEnabled(boolean) 13854 * @see #buildDrawingCache() 13855 * @see #getDrawingCache() 13856 */ 13857 public void setDrawingCacheBackgroundColor(int color) { 13858 if (color != mDrawingCacheBackgroundColor) { 13859 mDrawingCacheBackgroundColor = color; 13860 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13861 } 13862 } 13863 13864 /** 13865 * @see #setDrawingCacheBackgroundColor(int) 13866 * 13867 * @return The background color to used for the drawing cache's bitmap 13868 */ 13869 public int getDrawingCacheBackgroundColor() { 13870 return mDrawingCacheBackgroundColor; 13871 } 13872 13873 /** 13874 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13875 * 13876 * @see #buildDrawingCache(boolean) 13877 */ 13878 public void buildDrawingCache() { 13879 buildDrawingCache(false); 13880 } 13881 13882 /** 13883 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13884 * 13885 * <p>If you call {@link #buildDrawingCache()} manually without calling 13886 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13887 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13888 * 13889 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13890 * this method will create a bitmap of the same size as this view. Because this bitmap 13891 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13892 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13893 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13894 * size than the view. This implies that your application must be able to handle this 13895 * size.</p> 13896 * 13897 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13898 * you do not need the drawing cache bitmap, calling this method will increase memory 13899 * usage and cause the view to be rendered in software once, thus negatively impacting 13900 * performance.</p> 13901 * 13902 * @see #getDrawingCache() 13903 * @see #destroyDrawingCache() 13904 */ 13905 public void buildDrawingCache(boolean autoScale) { 13906 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13907 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13908 mCachingFailed = false; 13909 13910 int width = mRight - mLeft; 13911 int height = mBottom - mTop; 13912 13913 final AttachInfo attachInfo = mAttachInfo; 13914 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13915 13916 if (autoScale && scalingRequired) { 13917 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13918 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13919 } 13920 13921 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13922 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13923 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13924 13925 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13926 final long drawingCacheSize = 13927 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13928 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13929 if (width > 0 && height > 0) { 13930 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13931 + projectedBitmapSize + " bytes, only " 13932 + drawingCacheSize + " available"); 13933 } 13934 destroyDrawingCache(); 13935 mCachingFailed = true; 13936 return; 13937 } 13938 13939 boolean clear = true; 13940 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13941 13942 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13943 Bitmap.Config quality; 13944 if (!opaque) { 13945 // Never pick ARGB_4444 because it looks awful 13946 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13947 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13948 case DRAWING_CACHE_QUALITY_AUTO: 13949 case DRAWING_CACHE_QUALITY_LOW: 13950 case DRAWING_CACHE_QUALITY_HIGH: 13951 default: 13952 quality = Bitmap.Config.ARGB_8888; 13953 break; 13954 } 13955 } else { 13956 // Optimization for translucent windows 13957 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13958 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13959 } 13960 13961 // Try to cleanup memory 13962 if (bitmap != null) bitmap.recycle(); 13963 13964 try { 13965 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13966 width, height, quality); 13967 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 13968 if (autoScale) { 13969 mDrawingCache = bitmap; 13970 } else { 13971 mUnscaledDrawingCache = bitmap; 13972 } 13973 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 13974 } catch (OutOfMemoryError e) { 13975 // If there is not enough memory to create the bitmap cache, just 13976 // ignore the issue as bitmap caches are not required to draw the 13977 // view hierarchy 13978 if (autoScale) { 13979 mDrawingCache = null; 13980 } else { 13981 mUnscaledDrawingCache = null; 13982 } 13983 mCachingFailed = true; 13984 return; 13985 } 13986 13987 clear = drawingCacheBackgroundColor != 0; 13988 } 13989 13990 Canvas canvas; 13991 if (attachInfo != null) { 13992 canvas = attachInfo.mCanvas; 13993 if (canvas == null) { 13994 canvas = new Canvas(); 13995 } 13996 canvas.setBitmap(bitmap); 13997 // Temporarily clobber the cached Canvas in case one of our children 13998 // is also using a drawing cache. Without this, the children would 13999 // steal the canvas by attaching their own bitmap to it and bad, bad 14000 // thing would happen (invisible views, corrupted drawings, etc.) 14001 attachInfo.mCanvas = null; 14002 } else { 14003 // This case should hopefully never or seldom happen 14004 canvas = new Canvas(bitmap); 14005 } 14006 14007 if (clear) { 14008 bitmap.eraseColor(drawingCacheBackgroundColor); 14009 } 14010 14011 computeScroll(); 14012 final int restoreCount = canvas.save(); 14013 14014 if (autoScale && scalingRequired) { 14015 final float scale = attachInfo.mApplicationScale; 14016 canvas.scale(scale, scale); 14017 } 14018 14019 canvas.translate(-mScrollX, -mScrollY); 14020 14021 mPrivateFlags |= PFLAG_DRAWN; 14022 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14023 mLayerType != LAYER_TYPE_NONE) { 14024 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14025 } 14026 14027 // Fast path for layouts with no backgrounds 14028 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14029 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14030 dispatchDraw(canvas); 14031 if (mOverlay != null && !mOverlay.isEmpty()) { 14032 mOverlay.getOverlayView().draw(canvas); 14033 } 14034 } else { 14035 draw(canvas); 14036 } 14037 14038 canvas.restoreToCount(restoreCount); 14039 canvas.setBitmap(null); 14040 14041 if (attachInfo != null) { 14042 // Restore the cached Canvas for our siblings 14043 attachInfo.mCanvas = canvas; 14044 } 14045 } 14046 } 14047 14048 /** 14049 * Create a snapshot of the view into a bitmap. We should probably make 14050 * some form of this public, but should think about the API. 14051 */ 14052 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14053 int width = mRight - mLeft; 14054 int height = mBottom - mTop; 14055 14056 final AttachInfo attachInfo = mAttachInfo; 14057 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14058 width = (int) ((width * scale) + 0.5f); 14059 height = (int) ((height * scale) + 0.5f); 14060 14061 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14062 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14063 if (bitmap == null) { 14064 throw new OutOfMemoryError(); 14065 } 14066 14067 Resources resources = getResources(); 14068 if (resources != null) { 14069 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14070 } 14071 14072 Canvas canvas; 14073 if (attachInfo != null) { 14074 canvas = attachInfo.mCanvas; 14075 if (canvas == null) { 14076 canvas = new Canvas(); 14077 } 14078 canvas.setBitmap(bitmap); 14079 // Temporarily clobber the cached Canvas in case one of our children 14080 // is also using a drawing cache. Without this, the children would 14081 // steal the canvas by attaching their own bitmap to it and bad, bad 14082 // things would happen (invisible views, corrupted drawings, etc.) 14083 attachInfo.mCanvas = null; 14084 } else { 14085 // This case should hopefully never or seldom happen 14086 canvas = new Canvas(bitmap); 14087 } 14088 14089 if ((backgroundColor & 0xff000000) != 0) { 14090 bitmap.eraseColor(backgroundColor); 14091 } 14092 14093 computeScroll(); 14094 final int restoreCount = canvas.save(); 14095 canvas.scale(scale, scale); 14096 canvas.translate(-mScrollX, -mScrollY); 14097 14098 // Temporarily remove the dirty mask 14099 int flags = mPrivateFlags; 14100 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14101 14102 // Fast path for layouts with no backgrounds 14103 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14104 dispatchDraw(canvas); 14105 if (mOverlay != null && !mOverlay.isEmpty()) { 14106 mOverlay.getOverlayView().draw(canvas); 14107 } 14108 } else { 14109 draw(canvas); 14110 } 14111 14112 mPrivateFlags = flags; 14113 14114 canvas.restoreToCount(restoreCount); 14115 canvas.setBitmap(null); 14116 14117 if (attachInfo != null) { 14118 // Restore the cached Canvas for our siblings 14119 attachInfo.mCanvas = canvas; 14120 } 14121 14122 return bitmap; 14123 } 14124 14125 /** 14126 * Indicates whether this View is currently in edit mode. A View is usually 14127 * in edit mode when displayed within a developer tool. For instance, if 14128 * this View is being drawn by a visual user interface builder, this method 14129 * should return true. 14130 * 14131 * Subclasses should check the return value of this method to provide 14132 * different behaviors if their normal behavior might interfere with the 14133 * host environment. For instance: the class spawns a thread in its 14134 * constructor, the drawing code relies on device-specific features, etc. 14135 * 14136 * This method is usually checked in the drawing code of custom widgets. 14137 * 14138 * @return True if this View is in edit mode, false otherwise. 14139 */ 14140 public boolean isInEditMode() { 14141 return false; 14142 } 14143 14144 /** 14145 * If the View draws content inside its padding and enables fading edges, 14146 * it needs to support padding offsets. Padding offsets are added to the 14147 * fading edges to extend the length of the fade so that it covers pixels 14148 * drawn inside the padding. 14149 * 14150 * Subclasses of this class should override this method if they need 14151 * to draw content inside the padding. 14152 * 14153 * @return True if padding offset must be applied, false otherwise. 14154 * 14155 * @see #getLeftPaddingOffset() 14156 * @see #getRightPaddingOffset() 14157 * @see #getTopPaddingOffset() 14158 * @see #getBottomPaddingOffset() 14159 * 14160 * @since CURRENT 14161 */ 14162 protected boolean isPaddingOffsetRequired() { 14163 return false; 14164 } 14165 14166 /** 14167 * Amount by which to extend the left fading region. Called only when 14168 * {@link #isPaddingOffsetRequired()} returns true. 14169 * 14170 * @return The left padding offset in pixels. 14171 * 14172 * @see #isPaddingOffsetRequired() 14173 * 14174 * @since CURRENT 14175 */ 14176 protected int getLeftPaddingOffset() { 14177 return 0; 14178 } 14179 14180 /** 14181 * Amount by which to extend the right fading region. Called only when 14182 * {@link #isPaddingOffsetRequired()} returns true. 14183 * 14184 * @return The right padding offset in pixels. 14185 * 14186 * @see #isPaddingOffsetRequired() 14187 * 14188 * @since CURRENT 14189 */ 14190 protected int getRightPaddingOffset() { 14191 return 0; 14192 } 14193 14194 /** 14195 * Amount by which to extend the top fading region. Called only when 14196 * {@link #isPaddingOffsetRequired()} returns true. 14197 * 14198 * @return The top padding offset in pixels. 14199 * 14200 * @see #isPaddingOffsetRequired() 14201 * 14202 * @since CURRENT 14203 */ 14204 protected int getTopPaddingOffset() { 14205 return 0; 14206 } 14207 14208 /** 14209 * Amount by which to extend the bottom fading region. Called only when 14210 * {@link #isPaddingOffsetRequired()} returns true. 14211 * 14212 * @return The bottom padding offset in pixels. 14213 * 14214 * @see #isPaddingOffsetRequired() 14215 * 14216 * @since CURRENT 14217 */ 14218 protected int getBottomPaddingOffset() { 14219 return 0; 14220 } 14221 14222 /** 14223 * @hide 14224 * @param offsetRequired 14225 */ 14226 protected int getFadeTop(boolean offsetRequired) { 14227 int top = mPaddingTop; 14228 if (offsetRequired) top += getTopPaddingOffset(); 14229 return top; 14230 } 14231 14232 /** 14233 * @hide 14234 * @param offsetRequired 14235 */ 14236 protected int getFadeHeight(boolean offsetRequired) { 14237 int padding = mPaddingTop; 14238 if (offsetRequired) padding += getTopPaddingOffset(); 14239 return mBottom - mTop - mPaddingBottom - padding; 14240 } 14241 14242 /** 14243 * <p>Indicates whether this view is attached to a hardware accelerated 14244 * window or not.</p> 14245 * 14246 * <p>Even if this method returns true, it does not mean that every call 14247 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14248 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14249 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14250 * window is hardware accelerated, 14251 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14252 * return false, and this method will return true.</p> 14253 * 14254 * @return True if the view is attached to a window and the window is 14255 * hardware accelerated; false in any other case. 14256 */ 14257 public boolean isHardwareAccelerated() { 14258 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14259 } 14260 14261 /** 14262 * Sets a rectangular area on this view to which the view will be clipped 14263 * when it is drawn. Setting the value to null will remove the clip bounds 14264 * and the view will draw normally, using its full bounds. 14265 * 14266 * @param clipBounds The rectangular area, in the local coordinates of 14267 * this view, to which future drawing operations will be clipped. 14268 */ 14269 public void setClipBounds(Rect clipBounds) { 14270 if (clipBounds != null) { 14271 if (clipBounds.equals(mClipBounds)) { 14272 return; 14273 } 14274 if (mClipBounds == null) { 14275 invalidate(); 14276 mClipBounds = new Rect(clipBounds); 14277 } else { 14278 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14279 Math.min(mClipBounds.top, clipBounds.top), 14280 Math.max(mClipBounds.right, clipBounds.right), 14281 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14282 mClipBounds.set(clipBounds); 14283 } 14284 } else { 14285 if (mClipBounds != null) { 14286 invalidate(); 14287 mClipBounds = null; 14288 } 14289 } 14290 } 14291 14292 /** 14293 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14294 * 14295 * @return A copy of the current clip bounds if clip bounds are set, 14296 * otherwise null. 14297 */ 14298 public Rect getClipBounds() { 14299 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14300 } 14301 14302 /** 14303 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14304 * case of an active Animation being run on the view. 14305 */ 14306 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14307 Animation a, boolean scalingRequired) { 14308 Transformation invalidationTransform; 14309 final int flags = parent.mGroupFlags; 14310 final boolean initialized = a.isInitialized(); 14311 if (!initialized) { 14312 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14313 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14314 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14315 onAnimationStart(); 14316 } 14317 14318 final Transformation t = parent.getChildTransformation(); 14319 boolean more = a.getTransformation(drawingTime, t, 1f); 14320 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14321 if (parent.mInvalidationTransformation == null) { 14322 parent.mInvalidationTransformation = new Transformation(); 14323 } 14324 invalidationTransform = parent.mInvalidationTransformation; 14325 a.getTransformation(drawingTime, invalidationTransform, 1f); 14326 } else { 14327 invalidationTransform = t; 14328 } 14329 14330 if (more) { 14331 if (!a.willChangeBounds()) { 14332 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14333 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14334 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14335 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14336 // The child need to draw an animation, potentially offscreen, so 14337 // make sure we do not cancel invalidate requests 14338 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14339 parent.invalidate(mLeft, mTop, mRight, mBottom); 14340 } 14341 } else { 14342 if (parent.mInvalidateRegion == null) { 14343 parent.mInvalidateRegion = new RectF(); 14344 } 14345 final RectF region = parent.mInvalidateRegion; 14346 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14347 invalidationTransform); 14348 14349 // The child need to draw an animation, potentially offscreen, so 14350 // make sure we do not cancel invalidate requests 14351 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14352 14353 final int left = mLeft + (int) region.left; 14354 final int top = mTop + (int) region.top; 14355 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14356 top + (int) (region.height() + .5f)); 14357 } 14358 } 14359 return more; 14360 } 14361 14362 /** 14363 * This method is called by getDisplayList() when a display list is recorded for a View. 14364 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14365 */ 14366 void setDisplayListProperties(RenderNode renderNode) { 14367 if (renderNode != null) { 14368 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14369 if (mParent instanceof ViewGroup) { 14370 renderNode.setClipToBounds( 14371 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14372 } 14373 float alpha = 1; 14374 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14375 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14376 ViewGroup parentVG = (ViewGroup) mParent; 14377 final Transformation t = parentVG.getChildTransformation(); 14378 if (parentVG.getChildStaticTransformation(this, t)) { 14379 final int transformType = t.getTransformationType(); 14380 if (transformType != Transformation.TYPE_IDENTITY) { 14381 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14382 alpha = t.getAlpha(); 14383 } 14384 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14385 renderNode.setStaticMatrix(t.getMatrix()); 14386 } 14387 } 14388 } 14389 } 14390 if (mTransformationInfo != null) { 14391 alpha *= getFinalAlpha(); 14392 if (alpha < 1) { 14393 final int multipliedAlpha = (int) (255 * alpha); 14394 if (onSetAlpha(multipliedAlpha)) { 14395 alpha = 1; 14396 } 14397 } 14398 renderNode.setAlpha(alpha); 14399 } else if (alpha < 1) { 14400 renderNode.setAlpha(alpha); 14401 } 14402 } 14403 } 14404 14405 /** 14406 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14407 * This draw() method is an implementation detail and is not intended to be overridden or 14408 * to be called from anywhere else other than ViewGroup.drawChild(). 14409 */ 14410 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14411 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14412 boolean more = false; 14413 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14414 final int flags = parent.mGroupFlags; 14415 14416 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14417 parent.getChildTransformation().clear(); 14418 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14419 } 14420 14421 Transformation transformToApply = null; 14422 boolean concatMatrix = false; 14423 14424 boolean scalingRequired = false; 14425 boolean caching; 14426 int layerType = getLayerType(); 14427 14428 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14429 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14430 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14431 caching = true; 14432 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14433 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14434 } else { 14435 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14436 } 14437 14438 final Animation a = getAnimation(); 14439 if (a != null) { 14440 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14441 concatMatrix = a.willChangeTransformationMatrix(); 14442 if (concatMatrix) { 14443 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14444 } 14445 transformToApply = parent.getChildTransformation(); 14446 } else { 14447 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14448 // No longer animating: clear out old animation matrix 14449 mRenderNode.setAnimationMatrix(null); 14450 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14451 } 14452 if (!useDisplayListProperties && 14453 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14454 final Transformation t = parent.getChildTransformation(); 14455 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14456 if (hasTransform) { 14457 final int transformType = t.getTransformationType(); 14458 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14459 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14460 } 14461 } 14462 } 14463 14464 concatMatrix |= !childHasIdentityMatrix; 14465 14466 // Sets the flag as early as possible to allow draw() implementations 14467 // to call invalidate() successfully when doing animations 14468 mPrivateFlags |= PFLAG_DRAWN; 14469 14470 if (!concatMatrix && 14471 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14472 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14473 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14474 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14475 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14476 return more; 14477 } 14478 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14479 14480 if (hardwareAccelerated) { 14481 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14482 // retain the flag's value temporarily in the mRecreateDisplayList flag 14483 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14484 mPrivateFlags &= ~PFLAG_INVALIDATED; 14485 } 14486 14487 RenderNode displayList = null; 14488 Bitmap cache = null; 14489 boolean hasDisplayList = false; 14490 if (caching) { 14491 if (!hardwareAccelerated) { 14492 if (layerType != LAYER_TYPE_NONE) { 14493 layerType = LAYER_TYPE_SOFTWARE; 14494 buildDrawingCache(true); 14495 } 14496 cache = getDrawingCache(true); 14497 } else { 14498 switch (layerType) { 14499 case LAYER_TYPE_SOFTWARE: 14500 if (useDisplayListProperties) { 14501 hasDisplayList = canHaveDisplayList(); 14502 } else { 14503 buildDrawingCache(true); 14504 cache = getDrawingCache(true); 14505 } 14506 break; 14507 case LAYER_TYPE_HARDWARE: 14508 if (useDisplayListProperties) { 14509 hasDisplayList = canHaveDisplayList(); 14510 } 14511 break; 14512 case LAYER_TYPE_NONE: 14513 // Delay getting the display list until animation-driven alpha values are 14514 // set up and possibly passed on to the view 14515 hasDisplayList = canHaveDisplayList(); 14516 break; 14517 } 14518 } 14519 } 14520 useDisplayListProperties &= hasDisplayList; 14521 if (useDisplayListProperties) { 14522 displayList = getDisplayList(); 14523 if (!displayList.isValid()) { 14524 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14525 // to getDisplayList(), the display list will be marked invalid and we should not 14526 // try to use it again. 14527 displayList = null; 14528 hasDisplayList = false; 14529 useDisplayListProperties = false; 14530 } 14531 } 14532 14533 int sx = 0; 14534 int sy = 0; 14535 if (!hasDisplayList) { 14536 computeScroll(); 14537 sx = mScrollX; 14538 sy = mScrollY; 14539 } 14540 14541 final boolean hasNoCache = cache == null || hasDisplayList; 14542 final boolean offsetForScroll = cache == null && !hasDisplayList && 14543 layerType != LAYER_TYPE_HARDWARE; 14544 14545 int restoreTo = -1; 14546 if (!useDisplayListProperties || transformToApply != null) { 14547 restoreTo = canvas.save(); 14548 } 14549 if (offsetForScroll) { 14550 canvas.translate(mLeft - sx, mTop - sy); 14551 } else { 14552 if (!useDisplayListProperties) { 14553 canvas.translate(mLeft, mTop); 14554 } 14555 if (scalingRequired) { 14556 if (useDisplayListProperties) { 14557 // TODO: Might not need this if we put everything inside the DL 14558 restoreTo = canvas.save(); 14559 } 14560 // mAttachInfo cannot be null, otherwise scalingRequired == false 14561 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14562 canvas.scale(scale, scale); 14563 } 14564 } 14565 14566 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14567 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14568 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14569 if (transformToApply != null || !childHasIdentityMatrix) { 14570 int transX = 0; 14571 int transY = 0; 14572 14573 if (offsetForScroll) { 14574 transX = -sx; 14575 transY = -sy; 14576 } 14577 14578 if (transformToApply != null) { 14579 if (concatMatrix) { 14580 if (useDisplayListProperties) { 14581 displayList.setAnimationMatrix(transformToApply.getMatrix()); 14582 } else { 14583 // Undo the scroll translation, apply the transformation matrix, 14584 // then redo the scroll translate to get the correct result. 14585 canvas.translate(-transX, -transY); 14586 canvas.concat(transformToApply.getMatrix()); 14587 canvas.translate(transX, transY); 14588 } 14589 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14590 } 14591 14592 float transformAlpha = transformToApply.getAlpha(); 14593 if (transformAlpha < 1) { 14594 alpha *= transformAlpha; 14595 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14596 } 14597 } 14598 14599 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14600 canvas.translate(-transX, -transY); 14601 canvas.concat(getMatrix()); 14602 canvas.translate(transX, transY); 14603 } 14604 } 14605 14606 // Deal with alpha if it is or used to be <1 14607 if (alpha < 1 || 14608 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14609 if (alpha < 1) { 14610 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14611 } else { 14612 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14613 } 14614 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14615 if (hasNoCache) { 14616 final int multipliedAlpha = (int) (255 * alpha); 14617 if (!onSetAlpha(multipliedAlpha)) { 14618 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14619 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14620 layerType != LAYER_TYPE_NONE) { 14621 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14622 } 14623 if (useDisplayListProperties) { 14624 displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14625 } else if (layerType == LAYER_TYPE_NONE) { 14626 final int scrollX = hasDisplayList ? 0 : sx; 14627 final int scrollY = hasDisplayList ? 0 : sy; 14628 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14629 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14630 } 14631 } else { 14632 // Alpha is handled by the child directly, clobber the layer's alpha 14633 mPrivateFlags |= PFLAG_ALPHA_SET; 14634 } 14635 } 14636 } 14637 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14638 onSetAlpha(255); 14639 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14640 } 14641 14642 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14643 !useDisplayListProperties && cache == null) { 14644 if (offsetForScroll) { 14645 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14646 } else { 14647 if (!scalingRequired || cache == null) { 14648 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14649 } else { 14650 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14651 } 14652 } 14653 } 14654 14655 if (!useDisplayListProperties && hasDisplayList) { 14656 displayList = getDisplayList(); 14657 if (!displayList.isValid()) { 14658 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14659 // to getDisplayList(), the display list will be marked invalid and we should not 14660 // try to use it again. 14661 displayList = null; 14662 hasDisplayList = false; 14663 } 14664 } 14665 14666 if (hasNoCache) { 14667 boolean layerRendered = false; 14668 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14669 final HardwareLayer layer = getHardwareLayer(); 14670 if (layer != null && layer.isValid()) { 14671 mLayerPaint.setAlpha((int) (alpha * 255)); 14672 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14673 layerRendered = true; 14674 } else { 14675 final int scrollX = hasDisplayList ? 0 : sx; 14676 final int scrollY = hasDisplayList ? 0 : sy; 14677 canvas.saveLayer(scrollX, scrollY, 14678 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14679 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14680 } 14681 } 14682 14683 if (!layerRendered) { 14684 if (!hasDisplayList) { 14685 // Fast path for layouts with no backgrounds 14686 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14687 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14688 dispatchDraw(canvas); 14689 } else { 14690 draw(canvas); 14691 } 14692 } else { 14693 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14694 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14695 } 14696 } 14697 } else if (cache != null) { 14698 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14699 Paint cachePaint; 14700 14701 if (layerType == LAYER_TYPE_NONE) { 14702 cachePaint = parent.mCachePaint; 14703 if (cachePaint == null) { 14704 cachePaint = new Paint(); 14705 cachePaint.setDither(false); 14706 parent.mCachePaint = cachePaint; 14707 } 14708 if (alpha < 1) { 14709 cachePaint.setAlpha((int) (alpha * 255)); 14710 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14711 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14712 cachePaint.setAlpha(255); 14713 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14714 } 14715 } else { 14716 cachePaint = mLayerPaint; 14717 cachePaint.setAlpha((int) (alpha * 255)); 14718 } 14719 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14720 } 14721 14722 if (restoreTo >= 0) { 14723 canvas.restoreToCount(restoreTo); 14724 } 14725 14726 if (a != null && !more) { 14727 if (!hardwareAccelerated && !a.getFillAfter()) { 14728 onSetAlpha(255); 14729 } 14730 parent.finishAnimatingView(this, a); 14731 } 14732 14733 if (more && hardwareAccelerated) { 14734 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14735 // alpha animations should cause the child to recreate its display list 14736 invalidate(true); 14737 } 14738 } 14739 14740 mRecreateDisplayList = false; 14741 14742 return more; 14743 } 14744 14745 /** 14746 * Manually render this view (and all of its children) to the given Canvas. 14747 * The view must have already done a full layout before this function is 14748 * called. When implementing a view, implement 14749 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14750 * If you do need to override this method, call the superclass version. 14751 * 14752 * @param canvas The Canvas to which the View is rendered. 14753 */ 14754 public void draw(Canvas canvas) { 14755 if (mClipBounds != null) { 14756 canvas.clipRect(mClipBounds); 14757 } 14758 final int privateFlags = mPrivateFlags; 14759 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14760 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14761 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14762 14763 /* 14764 * Draw traversal performs several drawing steps which must be executed 14765 * in the appropriate order: 14766 * 14767 * 1. Draw the background 14768 * 2. If necessary, save the canvas' layers to prepare for fading 14769 * 3. Draw view's content 14770 * 4. Draw children 14771 * 5. If necessary, draw the fading edges and restore layers 14772 * 6. Draw decorations (scrollbars for instance) 14773 */ 14774 14775 // Step 1, draw the background, if needed 14776 int saveCount; 14777 14778 if (!dirtyOpaque) { 14779 drawBackground(canvas); 14780 } 14781 14782 // skip step 2 & 5 if possible (common case) 14783 final int viewFlags = mViewFlags; 14784 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14785 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14786 if (!verticalEdges && !horizontalEdges) { 14787 // Step 3, draw the content 14788 if (!dirtyOpaque) onDraw(canvas); 14789 14790 // Step 4, draw the children 14791 dispatchDraw(canvas); 14792 14793 // Step 6, draw decorations (scrollbars) 14794 onDrawScrollBars(canvas); 14795 14796 if (mOverlay != null && !mOverlay.isEmpty()) { 14797 mOverlay.getOverlayView().dispatchDraw(canvas); 14798 } 14799 14800 // we're done... 14801 return; 14802 } 14803 14804 /* 14805 * Here we do the full fledged routine... 14806 * (this is an uncommon case where speed matters less, 14807 * this is why we repeat some of the tests that have been 14808 * done above) 14809 */ 14810 14811 boolean drawTop = false; 14812 boolean drawBottom = false; 14813 boolean drawLeft = false; 14814 boolean drawRight = false; 14815 14816 float topFadeStrength = 0.0f; 14817 float bottomFadeStrength = 0.0f; 14818 float leftFadeStrength = 0.0f; 14819 float rightFadeStrength = 0.0f; 14820 14821 // Step 2, save the canvas' layers 14822 int paddingLeft = mPaddingLeft; 14823 14824 final boolean offsetRequired = isPaddingOffsetRequired(); 14825 if (offsetRequired) { 14826 paddingLeft += getLeftPaddingOffset(); 14827 } 14828 14829 int left = mScrollX + paddingLeft; 14830 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14831 int top = mScrollY + getFadeTop(offsetRequired); 14832 int bottom = top + getFadeHeight(offsetRequired); 14833 14834 if (offsetRequired) { 14835 right += getRightPaddingOffset(); 14836 bottom += getBottomPaddingOffset(); 14837 } 14838 14839 final ScrollabilityCache scrollabilityCache = mScrollCache; 14840 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14841 int length = (int) fadeHeight; 14842 14843 // clip the fade length if top and bottom fades overlap 14844 // overlapping fades produce odd-looking artifacts 14845 if (verticalEdges && (top + length > bottom - length)) { 14846 length = (bottom - top) / 2; 14847 } 14848 14849 // also clip horizontal fades if necessary 14850 if (horizontalEdges && (left + length > right - length)) { 14851 length = (right - left) / 2; 14852 } 14853 14854 if (verticalEdges) { 14855 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14856 drawTop = topFadeStrength * fadeHeight > 1.0f; 14857 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14858 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14859 } 14860 14861 if (horizontalEdges) { 14862 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14863 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14864 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14865 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14866 } 14867 14868 saveCount = canvas.getSaveCount(); 14869 14870 int solidColor = getSolidColor(); 14871 if (solidColor == 0) { 14872 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14873 14874 if (drawTop) { 14875 canvas.saveLayer(left, top, right, top + length, null, flags); 14876 } 14877 14878 if (drawBottom) { 14879 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14880 } 14881 14882 if (drawLeft) { 14883 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14884 } 14885 14886 if (drawRight) { 14887 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14888 } 14889 } else { 14890 scrollabilityCache.setFadeColor(solidColor); 14891 } 14892 14893 // Step 3, draw the content 14894 if (!dirtyOpaque) onDraw(canvas); 14895 14896 // Step 4, draw the children 14897 dispatchDraw(canvas); 14898 14899 // Step 5, draw the fade effect and restore layers 14900 final Paint p = scrollabilityCache.paint; 14901 final Matrix matrix = scrollabilityCache.matrix; 14902 final Shader fade = scrollabilityCache.shader; 14903 14904 if (drawTop) { 14905 matrix.setScale(1, fadeHeight * topFadeStrength); 14906 matrix.postTranslate(left, top); 14907 fade.setLocalMatrix(matrix); 14908 canvas.drawRect(left, top, right, top + length, p); 14909 } 14910 14911 if (drawBottom) { 14912 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14913 matrix.postRotate(180); 14914 matrix.postTranslate(left, bottom); 14915 fade.setLocalMatrix(matrix); 14916 canvas.drawRect(left, bottom - length, right, bottom, p); 14917 } 14918 14919 if (drawLeft) { 14920 matrix.setScale(1, fadeHeight * leftFadeStrength); 14921 matrix.postRotate(-90); 14922 matrix.postTranslate(left, top); 14923 fade.setLocalMatrix(matrix); 14924 canvas.drawRect(left, top, left + length, bottom, p); 14925 } 14926 14927 if (drawRight) { 14928 matrix.setScale(1, fadeHeight * rightFadeStrength); 14929 matrix.postRotate(90); 14930 matrix.postTranslate(right, top); 14931 fade.setLocalMatrix(matrix); 14932 canvas.drawRect(right - length, top, right, bottom, p); 14933 } 14934 14935 canvas.restoreToCount(saveCount); 14936 14937 // Step 6, draw decorations (scrollbars) 14938 onDrawScrollBars(canvas); 14939 14940 if (mOverlay != null && !mOverlay.isEmpty()) { 14941 mOverlay.getOverlayView().dispatchDraw(canvas); 14942 } 14943 } 14944 14945 /** 14946 * Draws the background onto the specified canvas. 14947 * 14948 * @param canvas Canvas on which to draw the background 14949 */ 14950 private void drawBackground(Canvas canvas) { 14951 final Drawable background = mBackground; 14952 if (background == null) { 14953 return; 14954 } 14955 14956 if (mBackgroundSizeChanged) { 14957 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14958 mBackgroundSizeChanged = false; 14959 queryOutlineFromBackgroundIfUndefined(); 14960 } 14961 14962 // Attempt to use a display list if requested. 14963 if (canvas.isHardwareAccelerated() && mAttachInfo != null 14964 && mAttachInfo.mHardwareRenderer != null) { 14965 mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList); 14966 14967 final RenderNode displayList = mBackgroundDisplayList; 14968 if (displayList != null && displayList.isValid()) { 14969 setBackgroundDisplayListProperties(displayList); 14970 ((HardwareCanvas) canvas).drawDisplayList(displayList); 14971 return; 14972 } 14973 } 14974 14975 final int scrollX = mScrollX; 14976 final int scrollY = mScrollY; 14977 if ((scrollX | scrollY) == 0) { 14978 background.draw(canvas); 14979 } else { 14980 canvas.translate(scrollX, scrollY); 14981 background.draw(canvas); 14982 canvas.translate(-scrollX, -scrollY); 14983 } 14984 } 14985 14986 /** 14987 * Set up background drawable display list properties. 14988 * 14989 * @param displayList Valid display list for the background drawable 14990 */ 14991 private void setBackgroundDisplayListProperties(RenderNode displayList) { 14992 displayList.setTranslationX(mScrollX); 14993 displayList.setTranslationY(mScrollY); 14994 } 14995 14996 /** 14997 * Creates a new display list or updates the existing display list for the 14998 * specified Drawable. 14999 * 15000 * @param drawable Drawable for which to create a display list 15001 * @param displayList Existing display list, or {@code null} 15002 * @return A valid display list for the specified drawable 15003 */ 15004 private RenderNode getDrawableDisplayList(Drawable drawable, RenderNode displayList) { 15005 if (displayList == null) { 15006 displayList = RenderNode.create(drawable.getClass().getName()); 15007 } 15008 15009 final Rect bounds = drawable.getBounds(); 15010 final int width = bounds.width(); 15011 final int height = bounds.height(); 15012 final HardwareCanvas canvas = displayList.start(width, height); 15013 try { 15014 drawable.draw(canvas); 15015 } finally { 15016 displayList.end(canvas); 15017 } 15018 15019 // Set up drawable properties that are view-independent. 15020 displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15021 displayList.setProjectBackwards(drawable.isProjected()); 15022 displayList.setProjectionReceiver(true); 15023 displayList.setClipToBounds(false); 15024 return displayList; 15025 } 15026 15027 /** 15028 * Returns the overlay for this view, creating it if it does not yet exist. 15029 * Adding drawables to the overlay will cause them to be displayed whenever 15030 * the view itself is redrawn. Objects in the overlay should be actively 15031 * managed: remove them when they should not be displayed anymore. The 15032 * overlay will always have the same size as its host view. 15033 * 15034 * <p>Note: Overlays do not currently work correctly with {@link 15035 * SurfaceView} or {@link TextureView}; contents in overlays for these 15036 * types of views may not display correctly.</p> 15037 * 15038 * @return The ViewOverlay object for this view. 15039 * @see ViewOverlay 15040 */ 15041 public ViewOverlay getOverlay() { 15042 if (mOverlay == null) { 15043 mOverlay = new ViewOverlay(mContext, this); 15044 } 15045 return mOverlay; 15046 } 15047 15048 /** 15049 * Override this if your view is known to always be drawn on top of a solid color background, 15050 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15051 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15052 * should be set to 0xFF. 15053 * 15054 * @see #setVerticalFadingEdgeEnabled(boolean) 15055 * @see #setHorizontalFadingEdgeEnabled(boolean) 15056 * 15057 * @return The known solid color background for this view, or 0 if the color may vary 15058 */ 15059 @ViewDebug.ExportedProperty(category = "drawing") 15060 public int getSolidColor() { 15061 return 0; 15062 } 15063 15064 /** 15065 * Build a human readable string representation of the specified view flags. 15066 * 15067 * @param flags the view flags to convert to a string 15068 * @return a String representing the supplied flags 15069 */ 15070 private static String printFlags(int flags) { 15071 String output = ""; 15072 int numFlags = 0; 15073 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15074 output += "TAKES_FOCUS"; 15075 numFlags++; 15076 } 15077 15078 switch (flags & VISIBILITY_MASK) { 15079 case INVISIBLE: 15080 if (numFlags > 0) { 15081 output += " "; 15082 } 15083 output += "INVISIBLE"; 15084 // USELESS HERE numFlags++; 15085 break; 15086 case GONE: 15087 if (numFlags > 0) { 15088 output += " "; 15089 } 15090 output += "GONE"; 15091 // USELESS HERE numFlags++; 15092 break; 15093 default: 15094 break; 15095 } 15096 return output; 15097 } 15098 15099 /** 15100 * Build a human readable string representation of the specified private 15101 * view flags. 15102 * 15103 * @param privateFlags the private view flags to convert to a string 15104 * @return a String representing the supplied flags 15105 */ 15106 private static String printPrivateFlags(int privateFlags) { 15107 String output = ""; 15108 int numFlags = 0; 15109 15110 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15111 output += "WANTS_FOCUS"; 15112 numFlags++; 15113 } 15114 15115 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15116 if (numFlags > 0) { 15117 output += " "; 15118 } 15119 output += "FOCUSED"; 15120 numFlags++; 15121 } 15122 15123 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15124 if (numFlags > 0) { 15125 output += " "; 15126 } 15127 output += "SELECTED"; 15128 numFlags++; 15129 } 15130 15131 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15132 if (numFlags > 0) { 15133 output += " "; 15134 } 15135 output += "IS_ROOT_NAMESPACE"; 15136 numFlags++; 15137 } 15138 15139 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15140 if (numFlags > 0) { 15141 output += " "; 15142 } 15143 output += "HAS_BOUNDS"; 15144 numFlags++; 15145 } 15146 15147 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15148 if (numFlags > 0) { 15149 output += " "; 15150 } 15151 output += "DRAWN"; 15152 // USELESS HERE numFlags++; 15153 } 15154 return output; 15155 } 15156 15157 /** 15158 * <p>Indicates whether or not this view's layout will be requested during 15159 * the next hierarchy layout pass.</p> 15160 * 15161 * @return true if the layout will be forced during next layout pass 15162 */ 15163 public boolean isLayoutRequested() { 15164 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15165 } 15166 15167 /** 15168 * Return true if o is a ViewGroup that is laying out using optical bounds. 15169 * @hide 15170 */ 15171 public static boolean isLayoutModeOptical(Object o) { 15172 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15173 } 15174 15175 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15176 Insets parentInsets = mParent instanceof View ? 15177 ((View) mParent).getOpticalInsets() : Insets.NONE; 15178 Insets childInsets = getOpticalInsets(); 15179 return setFrame( 15180 left + parentInsets.left - childInsets.left, 15181 top + parentInsets.top - childInsets.top, 15182 right + parentInsets.left + childInsets.right, 15183 bottom + parentInsets.top + childInsets.bottom); 15184 } 15185 15186 /** 15187 * Assign a size and position to a view and all of its 15188 * descendants 15189 * 15190 * <p>This is the second phase of the layout mechanism. 15191 * (The first is measuring). In this phase, each parent calls 15192 * layout on all of its children to position them. 15193 * This is typically done using the child measurements 15194 * that were stored in the measure pass().</p> 15195 * 15196 * <p>Derived classes should not override this method. 15197 * Derived classes with children should override 15198 * onLayout. In that method, they should 15199 * call layout on each of their children.</p> 15200 * 15201 * @param l Left position, relative to parent 15202 * @param t Top position, relative to parent 15203 * @param r Right position, relative to parent 15204 * @param b Bottom position, relative to parent 15205 */ 15206 @SuppressWarnings({"unchecked"}) 15207 public void layout(int l, int t, int r, int b) { 15208 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15209 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15210 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15211 } 15212 15213 int oldL = mLeft; 15214 int oldT = mTop; 15215 int oldB = mBottom; 15216 int oldR = mRight; 15217 15218 boolean changed = isLayoutModeOptical(mParent) ? 15219 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15220 15221 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15222 onLayout(changed, l, t, r, b); 15223 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15224 15225 ListenerInfo li = mListenerInfo; 15226 if (li != null && li.mOnLayoutChangeListeners != null) { 15227 ArrayList<OnLayoutChangeListener> listenersCopy = 15228 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15229 int numListeners = listenersCopy.size(); 15230 for (int i = 0; i < numListeners; ++i) { 15231 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15232 } 15233 } 15234 } 15235 15236 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15237 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15238 } 15239 15240 /** 15241 * Called from layout when this view should 15242 * assign a size and position to each of its children. 15243 * 15244 * Derived classes with children should override 15245 * this method and call layout on each of 15246 * their children. 15247 * @param changed This is a new size or position for this view 15248 * @param left Left position, relative to parent 15249 * @param top Top position, relative to parent 15250 * @param right Right position, relative to parent 15251 * @param bottom Bottom position, relative to parent 15252 */ 15253 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15254 } 15255 15256 /** 15257 * Assign a size and position to this view. 15258 * 15259 * This is called from layout. 15260 * 15261 * @param left Left position, relative to parent 15262 * @param top Top position, relative to parent 15263 * @param right Right position, relative to parent 15264 * @param bottom Bottom position, relative to parent 15265 * @return true if the new size and position are different than the 15266 * previous ones 15267 * {@hide} 15268 */ 15269 protected boolean setFrame(int left, int top, int right, int bottom) { 15270 boolean changed = false; 15271 15272 if (DBG) { 15273 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15274 + right + "," + bottom + ")"); 15275 } 15276 15277 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15278 changed = true; 15279 15280 // Remember our drawn bit 15281 int drawn = mPrivateFlags & PFLAG_DRAWN; 15282 15283 int oldWidth = mRight - mLeft; 15284 int oldHeight = mBottom - mTop; 15285 int newWidth = right - left; 15286 int newHeight = bottom - top; 15287 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15288 15289 // Invalidate our old position 15290 invalidate(sizeChanged); 15291 15292 mLeft = left; 15293 mTop = top; 15294 mRight = right; 15295 mBottom = bottom; 15296 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15297 15298 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15299 15300 15301 if (sizeChanged) { 15302 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15303 } 15304 15305 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15306 // If we are visible, force the DRAWN bit to on so that 15307 // this invalidate will go through (at least to our parent). 15308 // This is because someone may have invalidated this view 15309 // before this call to setFrame came in, thereby clearing 15310 // the DRAWN bit. 15311 mPrivateFlags |= PFLAG_DRAWN; 15312 invalidate(sizeChanged); 15313 // parent display list may need to be recreated based on a change in the bounds 15314 // of any child 15315 invalidateParentCaches(); 15316 } 15317 15318 // Reset drawn bit to original value (invalidate turns it off) 15319 mPrivateFlags |= drawn; 15320 15321 mBackgroundSizeChanged = true; 15322 15323 notifySubtreeAccessibilityStateChangedIfNeeded(); 15324 } 15325 return changed; 15326 } 15327 15328 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15329 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15330 if (mOverlay != null) { 15331 mOverlay.getOverlayView().setRight(newWidth); 15332 mOverlay.getOverlayView().setBottom(newHeight); 15333 } 15334 } 15335 15336 /** 15337 * Finalize inflating a view from XML. This is called as the last phase 15338 * of inflation, after all child views have been added. 15339 * 15340 * <p>Even if the subclass overrides onFinishInflate, they should always be 15341 * sure to call the super method, so that we get called. 15342 */ 15343 protected void onFinishInflate() { 15344 } 15345 15346 /** 15347 * Returns the resources associated with this view. 15348 * 15349 * @return Resources object. 15350 */ 15351 public Resources getResources() { 15352 return mResources; 15353 } 15354 15355 /** 15356 * Invalidates the specified Drawable. 15357 * 15358 * @param drawable the drawable to invalidate 15359 */ 15360 @Override 15361 public void invalidateDrawable(@NonNull Drawable drawable) { 15362 if (verifyDrawable(drawable)) { 15363 final Rect dirty = drawable.getDirtyBounds(); 15364 final int scrollX = mScrollX; 15365 final int scrollY = mScrollY; 15366 15367 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15368 dirty.right + scrollX, dirty.bottom + scrollY); 15369 15370 if (drawable == mBackground) { 15371 queryOutlineFromBackgroundIfUndefined(); 15372 } 15373 } 15374 } 15375 15376 /** 15377 * Schedules an action on a drawable to occur at a specified time. 15378 * 15379 * @param who the recipient of the action 15380 * @param what the action to run on the drawable 15381 * @param when the time at which the action must occur. Uses the 15382 * {@link SystemClock#uptimeMillis} timebase. 15383 */ 15384 @Override 15385 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15386 if (verifyDrawable(who) && what != null) { 15387 final long delay = when - SystemClock.uptimeMillis(); 15388 if (mAttachInfo != null) { 15389 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15390 Choreographer.CALLBACK_ANIMATION, what, who, 15391 Choreographer.subtractFrameDelay(delay)); 15392 } else { 15393 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15394 } 15395 } 15396 } 15397 15398 /** 15399 * Cancels a scheduled action on a drawable. 15400 * 15401 * @param who the recipient of the action 15402 * @param what the action to cancel 15403 */ 15404 @Override 15405 public void unscheduleDrawable(Drawable who, Runnable what) { 15406 if (verifyDrawable(who) && what != null) { 15407 if (mAttachInfo != null) { 15408 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15409 Choreographer.CALLBACK_ANIMATION, what, who); 15410 } 15411 ViewRootImpl.getRunQueue().removeCallbacks(what); 15412 } 15413 } 15414 15415 /** 15416 * Unschedule any events associated with the given Drawable. This can be 15417 * used when selecting a new Drawable into a view, so that the previous 15418 * one is completely unscheduled. 15419 * 15420 * @param who The Drawable to unschedule. 15421 * 15422 * @see #drawableStateChanged 15423 */ 15424 public void unscheduleDrawable(Drawable who) { 15425 if (mAttachInfo != null && who != null) { 15426 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15427 Choreographer.CALLBACK_ANIMATION, null, who); 15428 } 15429 } 15430 15431 /** 15432 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15433 * that the View directionality can and will be resolved before its Drawables. 15434 * 15435 * Will call {@link View#onResolveDrawables} when resolution is done. 15436 * 15437 * @hide 15438 */ 15439 protected void resolveDrawables() { 15440 // Drawables resolution may need to happen before resolving the layout direction (which is 15441 // done only during the measure() call). 15442 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15443 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15444 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15445 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15446 // direction to be resolved as its resolved value will be the same as its raw value. 15447 if (!isLayoutDirectionResolved() && 15448 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15449 return; 15450 } 15451 15452 final int layoutDirection = isLayoutDirectionResolved() ? 15453 getLayoutDirection() : getRawLayoutDirection(); 15454 15455 if (mBackground != null) { 15456 mBackground.setLayoutDirection(layoutDirection); 15457 } 15458 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15459 onResolveDrawables(layoutDirection); 15460 } 15461 15462 /** 15463 * Called when layout direction has been resolved. 15464 * 15465 * The default implementation does nothing. 15466 * 15467 * @param layoutDirection The resolved layout direction. 15468 * 15469 * @see #LAYOUT_DIRECTION_LTR 15470 * @see #LAYOUT_DIRECTION_RTL 15471 * 15472 * @hide 15473 */ 15474 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15475 } 15476 15477 /** 15478 * @hide 15479 */ 15480 protected void resetResolvedDrawables() { 15481 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15482 } 15483 15484 private boolean isDrawablesResolved() { 15485 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15486 } 15487 15488 /** 15489 * If your view subclass is displaying its own Drawable objects, it should 15490 * override this function and return true for any Drawable it is 15491 * displaying. This allows animations for those drawables to be 15492 * scheduled. 15493 * 15494 * <p>Be sure to call through to the super class when overriding this 15495 * function. 15496 * 15497 * @param who The Drawable to verify. Return true if it is one you are 15498 * displaying, else return the result of calling through to the 15499 * super class. 15500 * 15501 * @return boolean If true than the Drawable is being displayed in the 15502 * view; else false and it is not allowed to animate. 15503 * 15504 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15505 * @see #drawableStateChanged() 15506 */ 15507 protected boolean verifyDrawable(Drawable who) { 15508 return who == mBackground; 15509 } 15510 15511 /** 15512 * This function is called whenever the state of the view changes in such 15513 * a way that it impacts the state of drawables being shown. 15514 * <p> 15515 * If the View has a StateListAnimator, it will also be called to run necessary state 15516 * change animations. 15517 * <p> 15518 * Be sure to call through to the superclass when overriding this function. 15519 * 15520 * @see Drawable#setState(int[]) 15521 */ 15522 protected void drawableStateChanged() { 15523 final Drawable d = mBackground; 15524 if (d != null && d.isStateful()) { 15525 d.setState(getDrawableState()); 15526 } 15527 15528 if (mStateListAnimator != null) { 15529 mStateListAnimator.setState(getDrawableState()); 15530 } 15531 } 15532 15533 /** 15534 * Call this to force a view to update its drawable state. This will cause 15535 * drawableStateChanged to be called on this view. Views that are interested 15536 * in the new state should call getDrawableState. 15537 * 15538 * @see #drawableStateChanged 15539 * @see #getDrawableState 15540 */ 15541 public void refreshDrawableState() { 15542 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15543 drawableStateChanged(); 15544 15545 ViewParent parent = mParent; 15546 if (parent != null) { 15547 parent.childDrawableStateChanged(this); 15548 } 15549 } 15550 15551 /** 15552 * Return an array of resource IDs of the drawable states representing the 15553 * current state of the view. 15554 * 15555 * @return The current drawable state 15556 * 15557 * @see Drawable#setState(int[]) 15558 * @see #drawableStateChanged() 15559 * @see #onCreateDrawableState(int) 15560 */ 15561 public final int[] getDrawableState() { 15562 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15563 return mDrawableState; 15564 } else { 15565 mDrawableState = onCreateDrawableState(0); 15566 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15567 return mDrawableState; 15568 } 15569 } 15570 15571 /** 15572 * Generate the new {@link android.graphics.drawable.Drawable} state for 15573 * this view. This is called by the view 15574 * system when the cached Drawable state is determined to be invalid. To 15575 * retrieve the current state, you should use {@link #getDrawableState}. 15576 * 15577 * @param extraSpace if non-zero, this is the number of extra entries you 15578 * would like in the returned array in which you can place your own 15579 * states. 15580 * 15581 * @return Returns an array holding the current {@link Drawable} state of 15582 * the view. 15583 * 15584 * @see #mergeDrawableStates(int[], int[]) 15585 */ 15586 protected int[] onCreateDrawableState(int extraSpace) { 15587 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15588 mParent instanceof View) { 15589 return ((View) mParent).onCreateDrawableState(extraSpace); 15590 } 15591 15592 int[] drawableState; 15593 15594 int privateFlags = mPrivateFlags; 15595 15596 int viewStateIndex = 0; 15597 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15598 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15599 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15600 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15601 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15602 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15603 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15604 HardwareRenderer.isAvailable()) { 15605 // This is set if HW acceleration is requested, even if the current 15606 // process doesn't allow it. This is just to allow app preview 15607 // windows to better match their app. 15608 viewStateIndex |= VIEW_STATE_ACCELERATED; 15609 } 15610 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15611 15612 final int privateFlags2 = mPrivateFlags2; 15613 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15614 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15615 15616 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15617 15618 //noinspection ConstantIfStatement 15619 if (false) { 15620 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15621 Log.i("View", toString() 15622 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15623 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15624 + " fo=" + hasFocus() 15625 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15626 + " wf=" + hasWindowFocus() 15627 + ": " + Arrays.toString(drawableState)); 15628 } 15629 15630 if (extraSpace == 0) { 15631 return drawableState; 15632 } 15633 15634 final int[] fullState; 15635 if (drawableState != null) { 15636 fullState = new int[drawableState.length + extraSpace]; 15637 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15638 } else { 15639 fullState = new int[extraSpace]; 15640 } 15641 15642 return fullState; 15643 } 15644 15645 /** 15646 * Merge your own state values in <var>additionalState</var> into the base 15647 * state values <var>baseState</var> that were returned by 15648 * {@link #onCreateDrawableState(int)}. 15649 * 15650 * @param baseState The base state values returned by 15651 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15652 * own additional state values. 15653 * 15654 * @param additionalState The additional state values you would like 15655 * added to <var>baseState</var>; this array is not modified. 15656 * 15657 * @return As a convenience, the <var>baseState</var> array you originally 15658 * passed into the function is returned. 15659 * 15660 * @see #onCreateDrawableState(int) 15661 */ 15662 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15663 final int N = baseState.length; 15664 int i = N - 1; 15665 while (i >= 0 && baseState[i] == 0) { 15666 i--; 15667 } 15668 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15669 return baseState; 15670 } 15671 15672 /** 15673 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15674 * on all Drawable objects associated with this view. 15675 * <p> 15676 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 15677 * attached to this view. 15678 */ 15679 public void jumpDrawablesToCurrentState() { 15680 if (mBackground != null) { 15681 mBackground.jumpToCurrentState(); 15682 } 15683 if (mStateListAnimator != null) { 15684 mStateListAnimator.jumpToCurrentState(); 15685 } 15686 } 15687 15688 /** 15689 * Sets the background color for this view. 15690 * @param color the color of the background 15691 */ 15692 @RemotableViewMethod 15693 public void setBackgroundColor(int color) { 15694 if (mBackground instanceof ColorDrawable) { 15695 ((ColorDrawable) mBackground.mutate()).setColor(color); 15696 computeOpaqueFlags(); 15697 mBackgroundResource = 0; 15698 } else { 15699 setBackground(new ColorDrawable(color)); 15700 } 15701 } 15702 15703 /** 15704 * Set the background to a given resource. The resource should refer to 15705 * a Drawable object or 0 to remove the background. 15706 * @param resid The identifier of the resource. 15707 * 15708 * @attr ref android.R.styleable#View_background 15709 */ 15710 @RemotableViewMethod 15711 public void setBackgroundResource(int resid) { 15712 if (resid != 0 && resid == mBackgroundResource) { 15713 return; 15714 } 15715 15716 Drawable d = null; 15717 if (resid != 0) { 15718 d = mContext.getDrawable(resid); 15719 } 15720 setBackground(d); 15721 15722 mBackgroundResource = resid; 15723 } 15724 15725 /** 15726 * Set the background to a given Drawable, or remove the background. If the 15727 * background has padding, this View's padding is set to the background's 15728 * padding. However, when a background is removed, this View's padding isn't 15729 * touched. If setting the padding is desired, please use 15730 * {@link #setPadding(int, int, int, int)}. 15731 * 15732 * @param background The Drawable to use as the background, or null to remove the 15733 * background 15734 */ 15735 public void setBackground(Drawable background) { 15736 //noinspection deprecation 15737 setBackgroundDrawable(background); 15738 } 15739 15740 /** 15741 * @deprecated use {@link #setBackground(Drawable)} instead 15742 */ 15743 @Deprecated 15744 public void setBackgroundDrawable(Drawable background) { 15745 computeOpaqueFlags(); 15746 15747 if (background == mBackground) { 15748 return; 15749 } 15750 15751 boolean requestLayout = false; 15752 15753 mBackgroundResource = 0; 15754 15755 /* 15756 * Regardless of whether we're setting a new background or not, we want 15757 * to clear the previous drawable. 15758 */ 15759 if (mBackground != null) { 15760 mBackground.setCallback(null); 15761 unscheduleDrawable(mBackground); 15762 } 15763 15764 if (background != null) { 15765 Rect padding = sThreadLocal.get(); 15766 if (padding == null) { 15767 padding = new Rect(); 15768 sThreadLocal.set(padding); 15769 } 15770 resetResolvedDrawables(); 15771 background.setLayoutDirection(getLayoutDirection()); 15772 if (background.getPadding(padding)) { 15773 resetResolvedPadding(); 15774 switch (background.getLayoutDirection()) { 15775 case LAYOUT_DIRECTION_RTL: 15776 mUserPaddingLeftInitial = padding.right; 15777 mUserPaddingRightInitial = padding.left; 15778 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15779 break; 15780 case LAYOUT_DIRECTION_LTR: 15781 default: 15782 mUserPaddingLeftInitial = padding.left; 15783 mUserPaddingRightInitial = padding.right; 15784 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15785 } 15786 mLeftPaddingDefined = false; 15787 mRightPaddingDefined = false; 15788 } 15789 15790 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15791 // if it has a different minimum size, we should layout again 15792 if (mBackground == null 15793 || mBackground.getMinimumHeight() != background.getMinimumHeight() 15794 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15795 requestLayout = true; 15796 } 15797 15798 background.setCallback(this); 15799 if (background.isStateful()) { 15800 background.setState(getDrawableState()); 15801 } 15802 background.setVisible(getVisibility() == VISIBLE, false); 15803 mBackground = background; 15804 15805 applyBackgroundTint(); 15806 15807 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15808 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15809 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15810 requestLayout = true; 15811 } 15812 } else { 15813 /* Remove the background */ 15814 mBackground = null; 15815 15816 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15817 /* 15818 * This view ONLY drew the background before and we're removing 15819 * the background, so now it won't draw anything 15820 * (hence we SKIP_DRAW) 15821 */ 15822 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15823 mPrivateFlags |= PFLAG_SKIP_DRAW; 15824 } 15825 15826 /* 15827 * When the background is set, we try to apply its padding to this 15828 * View. When the background is removed, we don't touch this View's 15829 * padding. This is noted in the Javadocs. Hence, we don't need to 15830 * requestLayout(), the invalidate() below is sufficient. 15831 */ 15832 15833 // The old background's minimum size could have affected this 15834 // View's layout, so let's requestLayout 15835 requestLayout = true; 15836 } 15837 15838 computeOpaqueFlags(); 15839 15840 if (requestLayout) { 15841 requestLayout(); 15842 } 15843 15844 mBackgroundSizeChanged = true; 15845 invalidate(true); 15846 } 15847 15848 /** 15849 * Gets the background drawable 15850 * 15851 * @return The drawable used as the background for this view, if any. 15852 * 15853 * @see #setBackground(Drawable) 15854 * 15855 * @attr ref android.R.styleable#View_background 15856 */ 15857 public Drawable getBackground() { 15858 return mBackground; 15859 } 15860 15861 /** 15862 * Applies a tint to the background drawable. 15863 * <p> 15864 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 15865 * mutate the drawable and apply the specified tint and tint mode using 15866 * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}. 15867 * 15868 * @param tint the tint to apply, may be {@code null} to clear tint 15869 * @param tintMode the blending mode used to apply the tint, may be 15870 * {@code null} to clear tint 15871 * 15872 * @attr ref android.R.styleable#View_backgroundTint 15873 * @attr ref android.R.styleable#View_backgroundTintMode 15874 * @see Drawable#setTint(ColorStateList, PorterDuff.Mode) 15875 */ 15876 private void setBackgroundTint(@Nullable ColorStateList tint, 15877 @Nullable PorterDuff.Mode tintMode) { 15878 mBackgroundTint = tint; 15879 mBackgroundTintMode = tintMode; 15880 mHasBackgroundTint = true; 15881 15882 applyBackgroundTint(); 15883 } 15884 15885 /** 15886 * Applies a tint to the background drawable. Does not modify the current tint 15887 * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default. 15888 * <p> 15889 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 15890 * mutate the drawable and apply the specified tint and tint mode using 15891 * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}. 15892 * 15893 * @param tint the tint to apply, may be {@code null} to clear tint 15894 * 15895 * @attr ref android.R.styleable#View_backgroundTint 15896 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15897 */ 15898 public void setBackgroundTint(@Nullable ColorStateList tint) { 15899 setBackgroundTint(tint, mBackgroundTintMode); 15900 } 15901 15902 /** 15903 * @return the tint applied to the background drawable 15904 * @attr ref android.R.styleable#View_backgroundTint 15905 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15906 */ 15907 @Nullable 15908 public ColorStateList getBackgroundTint() { 15909 return mBackgroundTint; 15910 } 15911 15912 /** 15913 * Specifies the blending mode used to apply the tint specified by 15914 * {@link #setBackgroundTint(ColorStateList)}} to the background drawable. 15915 * The default mode is {@link PorterDuff.Mode#SRC_ATOP}. 15916 * 15917 * @param tintMode the blending mode used to apply the tint, may be 15918 * {@code null} to clear tint 15919 * @attr ref android.R.styleable#View_backgroundTintMode 15920 * @see #setBackgroundTint(ColorStateList) 15921 */ 15922 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 15923 setBackgroundTint(mBackgroundTint, tintMode); 15924 } 15925 15926 /** 15927 * @return the blending mode used to apply the tint to the background drawable 15928 * @attr ref android.R.styleable#View_backgroundTintMode 15929 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15930 */ 15931 @Nullable 15932 public PorterDuff.Mode getBackgroundTintMode() { 15933 return mBackgroundTintMode; 15934 } 15935 15936 private void applyBackgroundTint() { 15937 if (mBackground != null && mHasBackgroundTint) { 15938 mBackground = mBackground.mutate(); 15939 mBackground.setTint(mBackgroundTint, mBackgroundTintMode); 15940 } 15941 } 15942 15943 /** 15944 * Sets the padding. The view may add on the space required to display 15945 * the scrollbars, depending on the style and visibility of the scrollbars. 15946 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15947 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15948 * from the values set in this call. 15949 * 15950 * @attr ref android.R.styleable#View_padding 15951 * @attr ref android.R.styleable#View_paddingBottom 15952 * @attr ref android.R.styleable#View_paddingLeft 15953 * @attr ref android.R.styleable#View_paddingRight 15954 * @attr ref android.R.styleable#View_paddingTop 15955 * @param left the left padding in pixels 15956 * @param top the top padding in pixels 15957 * @param right the right padding in pixels 15958 * @param bottom the bottom padding in pixels 15959 */ 15960 public void setPadding(int left, int top, int right, int bottom) { 15961 resetResolvedPadding(); 15962 15963 mUserPaddingStart = UNDEFINED_PADDING; 15964 mUserPaddingEnd = UNDEFINED_PADDING; 15965 15966 mUserPaddingLeftInitial = left; 15967 mUserPaddingRightInitial = right; 15968 15969 mLeftPaddingDefined = true; 15970 mRightPaddingDefined = true; 15971 15972 internalSetPadding(left, top, right, bottom); 15973 } 15974 15975 /** 15976 * @hide 15977 */ 15978 protected void internalSetPadding(int left, int top, int right, int bottom) { 15979 mUserPaddingLeft = left; 15980 mUserPaddingRight = right; 15981 mUserPaddingBottom = bottom; 15982 15983 final int viewFlags = mViewFlags; 15984 boolean changed = false; 15985 15986 // Common case is there are no scroll bars. 15987 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15988 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15989 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15990 ? 0 : getVerticalScrollbarWidth(); 15991 switch (mVerticalScrollbarPosition) { 15992 case SCROLLBAR_POSITION_DEFAULT: 15993 if (isLayoutRtl()) { 15994 left += offset; 15995 } else { 15996 right += offset; 15997 } 15998 break; 15999 case SCROLLBAR_POSITION_RIGHT: 16000 right += offset; 16001 break; 16002 case SCROLLBAR_POSITION_LEFT: 16003 left += offset; 16004 break; 16005 } 16006 } 16007 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16008 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16009 ? 0 : getHorizontalScrollbarHeight(); 16010 } 16011 } 16012 16013 if (mPaddingLeft != left) { 16014 changed = true; 16015 mPaddingLeft = left; 16016 } 16017 if (mPaddingTop != top) { 16018 changed = true; 16019 mPaddingTop = top; 16020 } 16021 if (mPaddingRight != right) { 16022 changed = true; 16023 mPaddingRight = right; 16024 } 16025 if (mPaddingBottom != bottom) { 16026 changed = true; 16027 mPaddingBottom = bottom; 16028 } 16029 16030 if (changed) { 16031 requestLayout(); 16032 } 16033 } 16034 16035 /** 16036 * Sets the relative padding. The view may add on the space required to display 16037 * the scrollbars, depending on the style and visibility of the scrollbars. 16038 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16039 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16040 * from the values set in this call. 16041 * 16042 * @attr ref android.R.styleable#View_padding 16043 * @attr ref android.R.styleable#View_paddingBottom 16044 * @attr ref android.R.styleable#View_paddingStart 16045 * @attr ref android.R.styleable#View_paddingEnd 16046 * @attr ref android.R.styleable#View_paddingTop 16047 * @param start the start padding in pixels 16048 * @param top the top padding in pixels 16049 * @param end the end padding in pixels 16050 * @param bottom the bottom padding in pixels 16051 */ 16052 public void setPaddingRelative(int start, int top, int end, int bottom) { 16053 resetResolvedPadding(); 16054 16055 mUserPaddingStart = start; 16056 mUserPaddingEnd = end; 16057 mLeftPaddingDefined = true; 16058 mRightPaddingDefined = true; 16059 16060 switch(getLayoutDirection()) { 16061 case LAYOUT_DIRECTION_RTL: 16062 mUserPaddingLeftInitial = end; 16063 mUserPaddingRightInitial = start; 16064 internalSetPadding(end, top, start, bottom); 16065 break; 16066 case LAYOUT_DIRECTION_LTR: 16067 default: 16068 mUserPaddingLeftInitial = start; 16069 mUserPaddingRightInitial = end; 16070 internalSetPadding(start, top, end, bottom); 16071 } 16072 } 16073 16074 /** 16075 * Returns the top padding of this view. 16076 * 16077 * @return the top padding in pixels 16078 */ 16079 public int getPaddingTop() { 16080 return mPaddingTop; 16081 } 16082 16083 /** 16084 * Returns the bottom padding of this view. If there are inset and enabled 16085 * scrollbars, this value may include the space required to display the 16086 * scrollbars as well. 16087 * 16088 * @return the bottom padding in pixels 16089 */ 16090 public int getPaddingBottom() { 16091 return mPaddingBottom; 16092 } 16093 16094 /** 16095 * Returns the left padding of this view. If there are inset and enabled 16096 * scrollbars, this value may include the space required to display the 16097 * scrollbars as well. 16098 * 16099 * @return the left padding in pixels 16100 */ 16101 public int getPaddingLeft() { 16102 if (!isPaddingResolved()) { 16103 resolvePadding(); 16104 } 16105 return mPaddingLeft; 16106 } 16107 16108 /** 16109 * Returns the start padding of this view depending on its resolved layout direction. 16110 * If there are inset and enabled scrollbars, this value may include the space 16111 * required to display the scrollbars as well. 16112 * 16113 * @return the start padding in pixels 16114 */ 16115 public int getPaddingStart() { 16116 if (!isPaddingResolved()) { 16117 resolvePadding(); 16118 } 16119 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16120 mPaddingRight : mPaddingLeft; 16121 } 16122 16123 /** 16124 * Returns the right padding of this view. If there are inset and enabled 16125 * scrollbars, this value may include the space required to display the 16126 * scrollbars as well. 16127 * 16128 * @return the right padding in pixels 16129 */ 16130 public int getPaddingRight() { 16131 if (!isPaddingResolved()) { 16132 resolvePadding(); 16133 } 16134 return mPaddingRight; 16135 } 16136 16137 /** 16138 * Returns the end padding of this view depending on its resolved layout direction. 16139 * If there are inset and enabled scrollbars, this value may include the space 16140 * required to display the scrollbars as well. 16141 * 16142 * @return the end padding in pixels 16143 */ 16144 public int getPaddingEnd() { 16145 if (!isPaddingResolved()) { 16146 resolvePadding(); 16147 } 16148 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16149 mPaddingLeft : mPaddingRight; 16150 } 16151 16152 /** 16153 * Return if the padding as been set thru relative values 16154 * {@link #setPaddingRelative(int, int, int, int)} or thru 16155 * @attr ref android.R.styleable#View_paddingStart or 16156 * @attr ref android.R.styleable#View_paddingEnd 16157 * 16158 * @return true if the padding is relative or false if it is not. 16159 */ 16160 public boolean isPaddingRelative() { 16161 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16162 } 16163 16164 Insets computeOpticalInsets() { 16165 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16166 } 16167 16168 /** 16169 * @hide 16170 */ 16171 public void resetPaddingToInitialValues() { 16172 if (isRtlCompatibilityMode()) { 16173 mPaddingLeft = mUserPaddingLeftInitial; 16174 mPaddingRight = mUserPaddingRightInitial; 16175 return; 16176 } 16177 if (isLayoutRtl()) { 16178 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16179 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16180 } else { 16181 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16182 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16183 } 16184 } 16185 16186 /** 16187 * @hide 16188 */ 16189 public Insets getOpticalInsets() { 16190 if (mLayoutInsets == null) { 16191 mLayoutInsets = computeOpticalInsets(); 16192 } 16193 return mLayoutInsets; 16194 } 16195 16196 /** 16197 * Set this view's optical insets. 16198 * 16199 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16200 * property. Views that compute their own optical insets should call it as part of measurement. 16201 * This method does not request layout. If you are setting optical insets outside of 16202 * measure/layout itself you will want to call requestLayout() yourself. 16203 * </p> 16204 * @hide 16205 */ 16206 public void setOpticalInsets(Insets insets) { 16207 mLayoutInsets = insets; 16208 } 16209 16210 /** 16211 * Changes the selection state of this view. A view can be selected or not. 16212 * Note that selection is not the same as focus. Views are typically 16213 * selected in the context of an AdapterView like ListView or GridView; 16214 * the selected view is the view that is highlighted. 16215 * 16216 * @param selected true if the view must be selected, false otherwise 16217 */ 16218 public void setSelected(boolean selected) { 16219 //noinspection DoubleNegation 16220 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16221 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16222 if (!selected) resetPressedState(); 16223 invalidate(true); 16224 refreshDrawableState(); 16225 dispatchSetSelected(selected); 16226 notifyViewAccessibilityStateChangedIfNeeded( 16227 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16228 } 16229 } 16230 16231 /** 16232 * Dispatch setSelected to all of this View's children. 16233 * 16234 * @see #setSelected(boolean) 16235 * 16236 * @param selected The new selected state 16237 */ 16238 protected void dispatchSetSelected(boolean selected) { 16239 } 16240 16241 /** 16242 * Indicates the selection state of this view. 16243 * 16244 * @return true if the view is selected, false otherwise 16245 */ 16246 @ViewDebug.ExportedProperty 16247 public boolean isSelected() { 16248 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16249 } 16250 16251 /** 16252 * Changes the activated state of this view. A view can be activated or not. 16253 * Note that activation is not the same as selection. Selection is 16254 * a transient property, representing the view (hierarchy) the user is 16255 * currently interacting with. Activation is a longer-term state that the 16256 * user can move views in and out of. For example, in a list view with 16257 * single or multiple selection enabled, the views in the current selection 16258 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16259 * here.) The activated state is propagated down to children of the view it 16260 * is set on. 16261 * 16262 * @param activated true if the view must be activated, false otherwise 16263 */ 16264 public void setActivated(boolean activated) { 16265 //noinspection DoubleNegation 16266 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16267 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16268 invalidate(true); 16269 refreshDrawableState(); 16270 dispatchSetActivated(activated); 16271 } 16272 } 16273 16274 /** 16275 * Dispatch setActivated to all of this View's children. 16276 * 16277 * @see #setActivated(boolean) 16278 * 16279 * @param activated The new activated state 16280 */ 16281 protected void dispatchSetActivated(boolean activated) { 16282 } 16283 16284 /** 16285 * Indicates the activation state of this view. 16286 * 16287 * @return true if the view is activated, false otherwise 16288 */ 16289 @ViewDebug.ExportedProperty 16290 public boolean isActivated() { 16291 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16292 } 16293 16294 /** 16295 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16296 * observer can be used to get notifications when global events, like 16297 * layout, happen. 16298 * 16299 * The returned ViewTreeObserver observer is not guaranteed to remain 16300 * valid for the lifetime of this View. If the caller of this method keeps 16301 * a long-lived reference to ViewTreeObserver, it should always check for 16302 * the return value of {@link ViewTreeObserver#isAlive()}. 16303 * 16304 * @return The ViewTreeObserver for this view's hierarchy. 16305 */ 16306 public ViewTreeObserver getViewTreeObserver() { 16307 if (mAttachInfo != null) { 16308 return mAttachInfo.mTreeObserver; 16309 } 16310 if (mFloatingTreeObserver == null) { 16311 mFloatingTreeObserver = new ViewTreeObserver(); 16312 } 16313 return mFloatingTreeObserver; 16314 } 16315 16316 /** 16317 * <p>Finds the topmost view in the current view hierarchy.</p> 16318 * 16319 * @return the topmost view containing this view 16320 */ 16321 public View getRootView() { 16322 if (mAttachInfo != null) { 16323 final View v = mAttachInfo.mRootView; 16324 if (v != null) { 16325 return v; 16326 } 16327 } 16328 16329 View parent = this; 16330 16331 while (parent.mParent != null && parent.mParent instanceof View) { 16332 parent = (View) parent.mParent; 16333 } 16334 16335 return parent; 16336 } 16337 16338 /** 16339 * Transforms a motion event from view-local coordinates to on-screen 16340 * coordinates. 16341 * 16342 * @param ev the view-local motion event 16343 * @return false if the transformation could not be applied 16344 * @hide 16345 */ 16346 public boolean toGlobalMotionEvent(MotionEvent ev) { 16347 final AttachInfo info = mAttachInfo; 16348 if (info == null) { 16349 return false; 16350 } 16351 16352 final Matrix m = info.mTmpMatrix; 16353 m.set(Matrix.IDENTITY_MATRIX); 16354 transformMatrixToGlobal(m); 16355 ev.transform(m); 16356 return true; 16357 } 16358 16359 /** 16360 * Transforms a motion event from on-screen coordinates to view-local 16361 * coordinates. 16362 * 16363 * @param ev the on-screen motion event 16364 * @return false if the transformation could not be applied 16365 * @hide 16366 */ 16367 public boolean toLocalMotionEvent(MotionEvent ev) { 16368 final AttachInfo info = mAttachInfo; 16369 if (info == null) { 16370 return false; 16371 } 16372 16373 final Matrix m = info.mTmpMatrix; 16374 m.set(Matrix.IDENTITY_MATRIX); 16375 transformMatrixToLocal(m); 16376 ev.transform(m); 16377 return true; 16378 } 16379 16380 /** 16381 * Modifies the input matrix such that it maps view-local coordinates to 16382 * on-screen coordinates. 16383 * 16384 * @param m input matrix to modify 16385 */ 16386 void transformMatrixToGlobal(Matrix m) { 16387 final ViewParent parent = mParent; 16388 if (parent instanceof View) { 16389 final View vp = (View) parent; 16390 vp.transformMatrixToGlobal(m); 16391 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16392 } else if (parent instanceof ViewRootImpl) { 16393 final ViewRootImpl vr = (ViewRootImpl) parent; 16394 vr.transformMatrixToGlobal(m); 16395 m.postTranslate(0, -vr.mCurScrollY); 16396 } 16397 16398 m.postTranslate(mLeft, mTop); 16399 16400 if (!hasIdentityMatrix()) { 16401 m.postConcat(getMatrix()); 16402 } 16403 } 16404 16405 /** 16406 * Modifies the input matrix such that it maps on-screen coordinates to 16407 * view-local coordinates. 16408 * 16409 * @param m input matrix to modify 16410 */ 16411 void transformMatrixToLocal(Matrix m) { 16412 final ViewParent parent = mParent; 16413 if (parent instanceof View) { 16414 final View vp = (View) parent; 16415 vp.transformMatrixToLocal(m); 16416 m.preTranslate(vp.mScrollX, vp.mScrollY); 16417 } else if (parent instanceof ViewRootImpl) { 16418 final ViewRootImpl vr = (ViewRootImpl) parent; 16419 vr.transformMatrixToLocal(m); 16420 m.preTranslate(0, vr.mCurScrollY); 16421 } 16422 16423 m.preTranslate(-mLeft, -mTop); 16424 16425 if (!hasIdentityMatrix()) { 16426 m.preConcat(getInverseMatrix()); 16427 } 16428 } 16429 16430 /** 16431 * <p>Computes the coordinates of this view on the screen. The argument 16432 * must be an array of two integers. After the method returns, the array 16433 * contains the x and y location in that order.</p> 16434 * 16435 * @param location an array of two integers in which to hold the coordinates 16436 */ 16437 public void getLocationOnScreen(int[] location) { 16438 getLocationInWindow(location); 16439 16440 final AttachInfo info = mAttachInfo; 16441 if (info != null) { 16442 location[0] += info.mWindowLeft; 16443 location[1] += info.mWindowTop; 16444 } 16445 } 16446 16447 /** 16448 * <p>Computes the coordinates of this view in its window. The argument 16449 * must be an array of two integers. After the method returns, the array 16450 * contains the x and y location in that order.</p> 16451 * 16452 * @param location an array of two integers in which to hold the coordinates 16453 */ 16454 public void getLocationInWindow(int[] location) { 16455 if (location == null || location.length < 2) { 16456 throw new IllegalArgumentException("location must be an array of two integers"); 16457 } 16458 16459 if (mAttachInfo == null) { 16460 // When the view is not attached to a window, this method does not make sense 16461 location[0] = location[1] = 0; 16462 return; 16463 } 16464 16465 float[] position = mAttachInfo.mTmpTransformLocation; 16466 position[0] = position[1] = 0.0f; 16467 16468 if (!hasIdentityMatrix()) { 16469 getMatrix().mapPoints(position); 16470 } 16471 16472 position[0] += mLeft; 16473 position[1] += mTop; 16474 16475 ViewParent viewParent = mParent; 16476 while (viewParent instanceof View) { 16477 final View view = (View) viewParent; 16478 16479 position[0] -= view.mScrollX; 16480 position[1] -= view.mScrollY; 16481 16482 if (!view.hasIdentityMatrix()) { 16483 view.getMatrix().mapPoints(position); 16484 } 16485 16486 position[0] += view.mLeft; 16487 position[1] += view.mTop; 16488 16489 viewParent = view.mParent; 16490 } 16491 16492 if (viewParent instanceof ViewRootImpl) { 16493 // *cough* 16494 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16495 position[1] -= vr.mCurScrollY; 16496 } 16497 16498 location[0] = (int) (position[0] + 0.5f); 16499 location[1] = (int) (position[1] + 0.5f); 16500 } 16501 16502 /** 16503 * {@hide} 16504 * @param id the id of the view to be found 16505 * @return the view of the specified id, null if cannot be found 16506 */ 16507 protected View findViewTraversal(int id) { 16508 if (id == mID) { 16509 return this; 16510 } 16511 return null; 16512 } 16513 16514 /** 16515 * {@hide} 16516 * @param tag the tag of the view to be found 16517 * @return the view of specified tag, null if cannot be found 16518 */ 16519 protected View findViewWithTagTraversal(Object tag) { 16520 if (tag != null && tag.equals(mTag)) { 16521 return this; 16522 } 16523 return null; 16524 } 16525 16526 /** 16527 * {@hide} 16528 * @param predicate The predicate to evaluate. 16529 * @param childToSkip If not null, ignores this child during the recursive traversal. 16530 * @return The first view that matches the predicate or null. 16531 */ 16532 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16533 if (predicate.apply(this)) { 16534 return this; 16535 } 16536 return null; 16537 } 16538 16539 /** 16540 * Look for a child view with the given id. If this view has the given 16541 * id, return this view. 16542 * 16543 * @param id The id to search for. 16544 * @return The view that has the given id in the hierarchy or null 16545 */ 16546 public final View findViewById(int id) { 16547 if (id < 0) { 16548 return null; 16549 } 16550 return findViewTraversal(id); 16551 } 16552 16553 /** 16554 * Finds a view by its unuque and stable accessibility id. 16555 * 16556 * @param accessibilityId The searched accessibility id. 16557 * @return The found view. 16558 */ 16559 final View findViewByAccessibilityId(int accessibilityId) { 16560 if (accessibilityId < 0) { 16561 return null; 16562 } 16563 return findViewByAccessibilityIdTraversal(accessibilityId); 16564 } 16565 16566 /** 16567 * Performs the traversal to find a view by its unuque and stable accessibility id. 16568 * 16569 * <strong>Note:</strong>This method does not stop at the root namespace 16570 * boundary since the user can touch the screen at an arbitrary location 16571 * potentially crossing the root namespace bounday which will send an 16572 * accessibility event to accessibility services and they should be able 16573 * to obtain the event source. Also accessibility ids are guaranteed to be 16574 * unique in the window. 16575 * 16576 * @param accessibilityId The accessibility id. 16577 * @return The found view. 16578 * 16579 * @hide 16580 */ 16581 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16582 if (getAccessibilityViewId() == accessibilityId) { 16583 return this; 16584 } 16585 return null; 16586 } 16587 16588 /** 16589 * Look for a child view with the given tag. If this view has the given 16590 * tag, return this view. 16591 * 16592 * @param tag The tag to search for, using "tag.equals(getTag())". 16593 * @return The View that has the given tag in the hierarchy or null 16594 */ 16595 public final View findViewWithTag(Object tag) { 16596 if (tag == null) { 16597 return null; 16598 } 16599 return findViewWithTagTraversal(tag); 16600 } 16601 16602 /** 16603 * {@hide} 16604 * Look for a child view that matches the specified predicate. 16605 * If this view matches the predicate, return this view. 16606 * 16607 * @param predicate The predicate to evaluate. 16608 * @return The first view that matches the predicate or null. 16609 */ 16610 public final View findViewByPredicate(Predicate<View> predicate) { 16611 return findViewByPredicateTraversal(predicate, null); 16612 } 16613 16614 /** 16615 * {@hide} 16616 * Look for a child view that matches the specified predicate, 16617 * starting with the specified view and its descendents and then 16618 * recusively searching the ancestors and siblings of that view 16619 * until this view is reached. 16620 * 16621 * This method is useful in cases where the predicate does not match 16622 * a single unique view (perhaps multiple views use the same id) 16623 * and we are trying to find the view that is "closest" in scope to the 16624 * starting view. 16625 * 16626 * @param start The view to start from. 16627 * @param predicate The predicate to evaluate. 16628 * @return The first view that matches the predicate or null. 16629 */ 16630 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16631 View childToSkip = null; 16632 for (;;) { 16633 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16634 if (view != null || start == this) { 16635 return view; 16636 } 16637 16638 ViewParent parent = start.getParent(); 16639 if (parent == null || !(parent instanceof View)) { 16640 return null; 16641 } 16642 16643 childToSkip = start; 16644 start = (View) parent; 16645 } 16646 } 16647 16648 /** 16649 * Sets the identifier for this view. The identifier does not have to be 16650 * unique in this view's hierarchy. The identifier should be a positive 16651 * number. 16652 * 16653 * @see #NO_ID 16654 * @see #getId() 16655 * @see #findViewById(int) 16656 * 16657 * @param id a number used to identify the view 16658 * 16659 * @attr ref android.R.styleable#View_id 16660 */ 16661 public void setId(int id) { 16662 mID = id; 16663 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16664 mID = generateViewId(); 16665 } 16666 } 16667 16668 /** 16669 * {@hide} 16670 * 16671 * @param isRoot true if the view belongs to the root namespace, false 16672 * otherwise 16673 */ 16674 public void setIsRootNamespace(boolean isRoot) { 16675 if (isRoot) { 16676 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16677 } else { 16678 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16679 } 16680 } 16681 16682 /** 16683 * {@hide} 16684 * 16685 * @return true if the view belongs to the root namespace, false otherwise 16686 */ 16687 public boolean isRootNamespace() { 16688 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16689 } 16690 16691 /** 16692 * Returns this view's identifier. 16693 * 16694 * @return a positive integer used to identify the view or {@link #NO_ID} 16695 * if the view has no ID 16696 * 16697 * @see #setId(int) 16698 * @see #findViewById(int) 16699 * @attr ref android.R.styleable#View_id 16700 */ 16701 @ViewDebug.CapturedViewProperty 16702 public int getId() { 16703 return mID; 16704 } 16705 16706 /** 16707 * Returns this view's tag. 16708 * 16709 * @return the Object stored in this view as a tag, or {@code null} if not 16710 * set 16711 * 16712 * @see #setTag(Object) 16713 * @see #getTag(int) 16714 */ 16715 @ViewDebug.ExportedProperty 16716 public Object getTag() { 16717 return mTag; 16718 } 16719 16720 /** 16721 * Sets the tag associated with this view. A tag can be used to mark 16722 * a view in its hierarchy and does not have to be unique within the 16723 * hierarchy. Tags can also be used to store data within a view without 16724 * resorting to another data structure. 16725 * 16726 * @param tag an Object to tag the view with 16727 * 16728 * @see #getTag() 16729 * @see #setTag(int, Object) 16730 */ 16731 public void setTag(final Object tag) { 16732 mTag = tag; 16733 } 16734 16735 /** 16736 * Returns the tag associated with this view and the specified key. 16737 * 16738 * @param key The key identifying the tag 16739 * 16740 * @return the Object stored in this view as a tag, or {@code null} if not 16741 * set 16742 * 16743 * @see #setTag(int, Object) 16744 * @see #getTag() 16745 */ 16746 public Object getTag(int key) { 16747 if (mKeyedTags != null) return mKeyedTags.get(key); 16748 return null; 16749 } 16750 16751 /** 16752 * Sets a tag associated with this view and a key. A tag can be used 16753 * to mark a view in its hierarchy and does not have to be unique within 16754 * the hierarchy. Tags can also be used to store data within a view 16755 * without resorting to another data structure. 16756 * 16757 * The specified key should be an id declared in the resources of the 16758 * application to ensure it is unique (see the <a 16759 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16760 * Keys identified as belonging to 16761 * the Android framework or not associated with any package will cause 16762 * an {@link IllegalArgumentException} to be thrown. 16763 * 16764 * @param key The key identifying the tag 16765 * @param tag An Object to tag the view with 16766 * 16767 * @throws IllegalArgumentException If they specified key is not valid 16768 * 16769 * @see #setTag(Object) 16770 * @see #getTag(int) 16771 */ 16772 public void setTag(int key, final Object tag) { 16773 // If the package id is 0x00 or 0x01, it's either an undefined package 16774 // or a framework id 16775 if ((key >>> 24) < 2) { 16776 throw new IllegalArgumentException("The key must be an application-specific " 16777 + "resource id."); 16778 } 16779 16780 setKeyedTag(key, tag); 16781 } 16782 16783 /** 16784 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16785 * framework id. 16786 * 16787 * @hide 16788 */ 16789 public void setTagInternal(int key, Object tag) { 16790 if ((key >>> 24) != 0x1) { 16791 throw new IllegalArgumentException("The key must be a framework-specific " 16792 + "resource id."); 16793 } 16794 16795 setKeyedTag(key, tag); 16796 } 16797 16798 private void setKeyedTag(int key, Object tag) { 16799 if (mKeyedTags == null) { 16800 mKeyedTags = new SparseArray<Object>(2); 16801 } 16802 16803 mKeyedTags.put(key, tag); 16804 } 16805 16806 /** 16807 * Prints information about this view in the log output, with the tag 16808 * {@link #VIEW_LOG_TAG}. 16809 * 16810 * @hide 16811 */ 16812 public void debug() { 16813 debug(0); 16814 } 16815 16816 /** 16817 * Prints information about this view in the log output, with the tag 16818 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16819 * indentation defined by the <code>depth</code>. 16820 * 16821 * @param depth the indentation level 16822 * 16823 * @hide 16824 */ 16825 protected void debug(int depth) { 16826 String output = debugIndent(depth - 1); 16827 16828 output += "+ " + this; 16829 int id = getId(); 16830 if (id != -1) { 16831 output += " (id=" + id + ")"; 16832 } 16833 Object tag = getTag(); 16834 if (tag != null) { 16835 output += " (tag=" + tag + ")"; 16836 } 16837 Log.d(VIEW_LOG_TAG, output); 16838 16839 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16840 output = debugIndent(depth) + " FOCUSED"; 16841 Log.d(VIEW_LOG_TAG, output); 16842 } 16843 16844 output = debugIndent(depth); 16845 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16846 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16847 + "} "; 16848 Log.d(VIEW_LOG_TAG, output); 16849 16850 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16851 || mPaddingBottom != 0) { 16852 output = debugIndent(depth); 16853 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16854 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16855 Log.d(VIEW_LOG_TAG, output); 16856 } 16857 16858 output = debugIndent(depth); 16859 output += "mMeasureWidth=" + mMeasuredWidth + 16860 " mMeasureHeight=" + mMeasuredHeight; 16861 Log.d(VIEW_LOG_TAG, output); 16862 16863 output = debugIndent(depth); 16864 if (mLayoutParams == null) { 16865 output += "BAD! no layout params"; 16866 } else { 16867 output = mLayoutParams.debug(output); 16868 } 16869 Log.d(VIEW_LOG_TAG, output); 16870 16871 output = debugIndent(depth); 16872 output += "flags={"; 16873 output += View.printFlags(mViewFlags); 16874 output += "}"; 16875 Log.d(VIEW_LOG_TAG, output); 16876 16877 output = debugIndent(depth); 16878 output += "privateFlags={"; 16879 output += View.printPrivateFlags(mPrivateFlags); 16880 output += "}"; 16881 Log.d(VIEW_LOG_TAG, output); 16882 } 16883 16884 /** 16885 * Creates a string of whitespaces used for indentation. 16886 * 16887 * @param depth the indentation level 16888 * @return a String containing (depth * 2 + 3) * 2 white spaces 16889 * 16890 * @hide 16891 */ 16892 protected static String debugIndent(int depth) { 16893 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16894 for (int i = 0; i < (depth * 2) + 3; i++) { 16895 spaces.append(' ').append(' '); 16896 } 16897 return spaces.toString(); 16898 } 16899 16900 /** 16901 * <p>Return the offset of the widget's text baseline from the widget's top 16902 * boundary. If this widget does not support baseline alignment, this 16903 * method returns -1. </p> 16904 * 16905 * @return the offset of the baseline within the widget's bounds or -1 16906 * if baseline alignment is not supported 16907 */ 16908 @ViewDebug.ExportedProperty(category = "layout") 16909 public int getBaseline() { 16910 return -1; 16911 } 16912 16913 /** 16914 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16915 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16916 * a layout pass. 16917 * 16918 * @return whether the view hierarchy is currently undergoing a layout pass 16919 */ 16920 public boolean isInLayout() { 16921 ViewRootImpl viewRoot = getViewRootImpl(); 16922 return (viewRoot != null && viewRoot.isInLayout()); 16923 } 16924 16925 /** 16926 * Call this when something has changed which has invalidated the 16927 * layout of this view. This will schedule a layout pass of the view 16928 * tree. This should not be called while the view hierarchy is currently in a layout 16929 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16930 * end of the current layout pass (and then layout will run again) or after the current 16931 * frame is drawn and the next layout occurs. 16932 * 16933 * <p>Subclasses which override this method should call the superclass method to 16934 * handle possible request-during-layout errors correctly.</p> 16935 */ 16936 public void requestLayout() { 16937 if (mMeasureCache != null) mMeasureCache.clear(); 16938 16939 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16940 // Only trigger request-during-layout logic if this is the view requesting it, 16941 // not the views in its parent hierarchy 16942 ViewRootImpl viewRoot = getViewRootImpl(); 16943 if (viewRoot != null && viewRoot.isInLayout()) { 16944 if (!viewRoot.requestLayoutDuringLayout(this)) { 16945 return; 16946 } 16947 } 16948 mAttachInfo.mViewRequestingLayout = this; 16949 } 16950 16951 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16952 mPrivateFlags |= PFLAG_INVALIDATED; 16953 16954 if (mParent != null && !mParent.isLayoutRequested()) { 16955 mParent.requestLayout(); 16956 } 16957 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16958 mAttachInfo.mViewRequestingLayout = null; 16959 } 16960 } 16961 16962 /** 16963 * Forces this view to be laid out during the next layout pass. 16964 * This method does not call requestLayout() or forceLayout() 16965 * on the parent. 16966 */ 16967 public void forceLayout() { 16968 if (mMeasureCache != null) mMeasureCache.clear(); 16969 16970 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16971 mPrivateFlags |= PFLAG_INVALIDATED; 16972 } 16973 16974 /** 16975 * <p> 16976 * This is called to find out how big a view should be. The parent 16977 * supplies constraint information in the width and height parameters. 16978 * </p> 16979 * 16980 * <p> 16981 * The actual measurement work of a view is performed in 16982 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16983 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16984 * </p> 16985 * 16986 * 16987 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16988 * parent 16989 * @param heightMeasureSpec Vertical space requirements as imposed by the 16990 * parent 16991 * 16992 * @see #onMeasure(int, int) 16993 */ 16994 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16995 boolean optical = isLayoutModeOptical(this); 16996 if (optical != isLayoutModeOptical(mParent)) { 16997 Insets insets = getOpticalInsets(); 16998 int oWidth = insets.left + insets.right; 16999 int oHeight = insets.top + insets.bottom; 17000 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 17001 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 17002 } 17003 17004 // Suppress sign extension for the low bytes 17005 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 17006 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 17007 17008 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 17009 widthMeasureSpec != mOldWidthMeasureSpec || 17010 heightMeasureSpec != mOldHeightMeasureSpec) { 17011 17012 // first clears the measured dimension flag 17013 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 17014 17015 resolveRtlPropertiesIfNeeded(); 17016 17017 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 17018 mMeasureCache.indexOfKey(key); 17019 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17020 // measure ourselves, this should set the measured dimension flag back 17021 onMeasure(widthMeasureSpec, heightMeasureSpec); 17022 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17023 } else { 17024 long value = mMeasureCache.valueAt(cacheIndex); 17025 // Casting a long to int drops the high 32 bits, no mask needed 17026 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17027 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17028 } 17029 17030 // flag not set, setMeasuredDimension() was not invoked, we raise 17031 // an exception to warn the developer 17032 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17033 throw new IllegalStateException("onMeasure() did not set the" 17034 + " measured dimension by calling" 17035 + " setMeasuredDimension()"); 17036 } 17037 17038 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17039 } 17040 17041 mOldWidthMeasureSpec = widthMeasureSpec; 17042 mOldHeightMeasureSpec = heightMeasureSpec; 17043 17044 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17045 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17046 } 17047 17048 /** 17049 * <p> 17050 * Measure the view and its content to determine the measured width and the 17051 * measured height. This method is invoked by {@link #measure(int, int)} and 17052 * should be overriden by subclasses to provide accurate and efficient 17053 * measurement of their contents. 17054 * </p> 17055 * 17056 * <p> 17057 * <strong>CONTRACT:</strong> When overriding this method, you 17058 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17059 * measured width and height of this view. Failure to do so will trigger an 17060 * <code>IllegalStateException</code>, thrown by 17061 * {@link #measure(int, int)}. Calling the superclass' 17062 * {@link #onMeasure(int, int)} is a valid use. 17063 * </p> 17064 * 17065 * <p> 17066 * The base class implementation of measure defaults to the background size, 17067 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17068 * override {@link #onMeasure(int, int)} to provide better measurements of 17069 * their content. 17070 * </p> 17071 * 17072 * <p> 17073 * If this method is overridden, it is the subclass's responsibility to make 17074 * sure the measured height and width are at least the view's minimum height 17075 * and width ({@link #getSuggestedMinimumHeight()} and 17076 * {@link #getSuggestedMinimumWidth()}). 17077 * </p> 17078 * 17079 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17080 * The requirements are encoded with 17081 * {@link android.view.View.MeasureSpec}. 17082 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17083 * The requirements are encoded with 17084 * {@link android.view.View.MeasureSpec}. 17085 * 17086 * @see #getMeasuredWidth() 17087 * @see #getMeasuredHeight() 17088 * @see #setMeasuredDimension(int, int) 17089 * @see #getSuggestedMinimumHeight() 17090 * @see #getSuggestedMinimumWidth() 17091 * @see android.view.View.MeasureSpec#getMode(int) 17092 * @see android.view.View.MeasureSpec#getSize(int) 17093 */ 17094 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17095 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17096 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17097 } 17098 17099 /** 17100 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17101 * measured width and measured height. Failing to do so will trigger an 17102 * exception at measurement time.</p> 17103 * 17104 * @param measuredWidth The measured width of this view. May be a complex 17105 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17106 * {@link #MEASURED_STATE_TOO_SMALL}. 17107 * @param measuredHeight The measured height of this view. May be a complex 17108 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17109 * {@link #MEASURED_STATE_TOO_SMALL}. 17110 */ 17111 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17112 boolean optical = isLayoutModeOptical(this); 17113 if (optical != isLayoutModeOptical(mParent)) { 17114 Insets insets = getOpticalInsets(); 17115 int opticalWidth = insets.left + insets.right; 17116 int opticalHeight = insets.top + insets.bottom; 17117 17118 measuredWidth += optical ? opticalWidth : -opticalWidth; 17119 measuredHeight += optical ? opticalHeight : -opticalHeight; 17120 } 17121 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17122 } 17123 17124 /** 17125 * Sets the measured dimension without extra processing for things like optical bounds. 17126 * Useful for reapplying consistent values that have already been cooked with adjustments 17127 * for optical bounds, etc. such as those from the measurement cache. 17128 * 17129 * @param measuredWidth The measured width of this view. May be a complex 17130 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17131 * {@link #MEASURED_STATE_TOO_SMALL}. 17132 * @param measuredHeight The measured height of this view. May be a complex 17133 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17134 * {@link #MEASURED_STATE_TOO_SMALL}. 17135 */ 17136 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17137 mMeasuredWidth = measuredWidth; 17138 mMeasuredHeight = measuredHeight; 17139 17140 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17141 } 17142 17143 /** 17144 * Merge two states as returned by {@link #getMeasuredState()}. 17145 * @param curState The current state as returned from a view or the result 17146 * of combining multiple views. 17147 * @param newState The new view state to combine. 17148 * @return Returns a new integer reflecting the combination of the two 17149 * states. 17150 */ 17151 public static int combineMeasuredStates(int curState, int newState) { 17152 return curState | newState; 17153 } 17154 17155 /** 17156 * Version of {@link #resolveSizeAndState(int, int, int)} 17157 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17158 */ 17159 public static int resolveSize(int size, int measureSpec) { 17160 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17161 } 17162 17163 /** 17164 * Utility to reconcile a desired size and state, with constraints imposed 17165 * by a MeasureSpec. Will take the desired size, unless a different size 17166 * is imposed by the constraints. The returned value is a compound integer, 17167 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17168 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17169 * size is smaller than the size the view wants to be. 17170 * 17171 * @param size How big the view wants to be 17172 * @param measureSpec Constraints imposed by the parent 17173 * @return Size information bit mask as defined by 17174 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17175 */ 17176 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17177 int result = size; 17178 int specMode = MeasureSpec.getMode(measureSpec); 17179 int specSize = MeasureSpec.getSize(measureSpec); 17180 switch (specMode) { 17181 case MeasureSpec.UNSPECIFIED: 17182 result = size; 17183 break; 17184 case MeasureSpec.AT_MOST: 17185 if (specSize < size) { 17186 result = specSize | MEASURED_STATE_TOO_SMALL; 17187 } else { 17188 result = size; 17189 } 17190 break; 17191 case MeasureSpec.EXACTLY: 17192 result = specSize; 17193 break; 17194 } 17195 return result | (childMeasuredState&MEASURED_STATE_MASK); 17196 } 17197 17198 /** 17199 * Utility to return a default size. Uses the supplied size if the 17200 * MeasureSpec imposed no constraints. Will get larger if allowed 17201 * by the MeasureSpec. 17202 * 17203 * @param size Default size for this view 17204 * @param measureSpec Constraints imposed by the parent 17205 * @return The size this view should be. 17206 */ 17207 public static int getDefaultSize(int size, int measureSpec) { 17208 int result = size; 17209 int specMode = MeasureSpec.getMode(measureSpec); 17210 int specSize = MeasureSpec.getSize(measureSpec); 17211 17212 switch (specMode) { 17213 case MeasureSpec.UNSPECIFIED: 17214 result = size; 17215 break; 17216 case MeasureSpec.AT_MOST: 17217 case MeasureSpec.EXACTLY: 17218 result = specSize; 17219 break; 17220 } 17221 return result; 17222 } 17223 17224 /** 17225 * Returns the suggested minimum height that the view should use. This 17226 * returns the maximum of the view's minimum height 17227 * and the background's minimum height 17228 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17229 * <p> 17230 * When being used in {@link #onMeasure(int, int)}, the caller should still 17231 * ensure the returned height is within the requirements of the parent. 17232 * 17233 * @return The suggested minimum height of the view. 17234 */ 17235 protected int getSuggestedMinimumHeight() { 17236 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17237 17238 } 17239 17240 /** 17241 * Returns the suggested minimum width that the view should use. This 17242 * returns the maximum of the view's minimum width) 17243 * and the background's minimum width 17244 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17245 * <p> 17246 * When being used in {@link #onMeasure(int, int)}, the caller should still 17247 * ensure the returned width is within the requirements of the parent. 17248 * 17249 * @return The suggested minimum width of the view. 17250 */ 17251 protected int getSuggestedMinimumWidth() { 17252 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17253 } 17254 17255 /** 17256 * Returns the minimum height of the view. 17257 * 17258 * @return the minimum height the view will try to be. 17259 * 17260 * @see #setMinimumHeight(int) 17261 * 17262 * @attr ref android.R.styleable#View_minHeight 17263 */ 17264 public int getMinimumHeight() { 17265 return mMinHeight; 17266 } 17267 17268 /** 17269 * Sets the minimum height of the view. It is not guaranteed the view will 17270 * be able to achieve this minimum height (for example, if its parent layout 17271 * constrains it with less available height). 17272 * 17273 * @param minHeight The minimum height the view will try to be. 17274 * 17275 * @see #getMinimumHeight() 17276 * 17277 * @attr ref android.R.styleable#View_minHeight 17278 */ 17279 public void setMinimumHeight(int minHeight) { 17280 mMinHeight = minHeight; 17281 requestLayout(); 17282 } 17283 17284 /** 17285 * Returns the minimum width of the view. 17286 * 17287 * @return the minimum width the view will try to be. 17288 * 17289 * @see #setMinimumWidth(int) 17290 * 17291 * @attr ref android.R.styleable#View_minWidth 17292 */ 17293 public int getMinimumWidth() { 17294 return mMinWidth; 17295 } 17296 17297 /** 17298 * Sets the minimum width of the view. It is not guaranteed the view will 17299 * be able to achieve this minimum width (for example, if its parent layout 17300 * constrains it with less available width). 17301 * 17302 * @param minWidth The minimum width the view will try to be. 17303 * 17304 * @see #getMinimumWidth() 17305 * 17306 * @attr ref android.R.styleable#View_minWidth 17307 */ 17308 public void setMinimumWidth(int minWidth) { 17309 mMinWidth = minWidth; 17310 requestLayout(); 17311 17312 } 17313 17314 /** 17315 * Get the animation currently associated with this view. 17316 * 17317 * @return The animation that is currently playing or 17318 * scheduled to play for this view. 17319 */ 17320 public Animation getAnimation() { 17321 return mCurrentAnimation; 17322 } 17323 17324 /** 17325 * Start the specified animation now. 17326 * 17327 * @param animation the animation to start now 17328 */ 17329 public void startAnimation(Animation animation) { 17330 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17331 setAnimation(animation); 17332 invalidateParentCaches(); 17333 invalidate(true); 17334 } 17335 17336 /** 17337 * Cancels any animations for this view. 17338 */ 17339 public void clearAnimation() { 17340 if (mCurrentAnimation != null) { 17341 mCurrentAnimation.detach(); 17342 } 17343 mCurrentAnimation = null; 17344 invalidateParentIfNeeded(); 17345 } 17346 17347 /** 17348 * Sets the next animation to play for this view. 17349 * If you want the animation to play immediately, use 17350 * {@link #startAnimation(android.view.animation.Animation)} instead. 17351 * This method provides allows fine-grained 17352 * control over the start time and invalidation, but you 17353 * must make sure that 1) the animation has a start time set, and 17354 * 2) the view's parent (which controls animations on its children) 17355 * will be invalidated when the animation is supposed to 17356 * start. 17357 * 17358 * @param animation The next animation, or null. 17359 */ 17360 public void setAnimation(Animation animation) { 17361 mCurrentAnimation = animation; 17362 17363 if (animation != null) { 17364 // If the screen is off assume the animation start time is now instead of 17365 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17366 // would cause the animation to start when the screen turns back on 17367 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17368 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17369 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17370 } 17371 animation.reset(); 17372 } 17373 } 17374 17375 /** 17376 * Invoked by a parent ViewGroup to notify the start of the animation 17377 * currently associated with this view. If you override this method, 17378 * always call super.onAnimationStart(); 17379 * 17380 * @see #setAnimation(android.view.animation.Animation) 17381 * @see #getAnimation() 17382 */ 17383 protected void onAnimationStart() { 17384 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17385 } 17386 17387 /** 17388 * Invoked by a parent ViewGroup to notify the end of the animation 17389 * currently associated with this view. If you override this method, 17390 * always call super.onAnimationEnd(); 17391 * 17392 * @see #setAnimation(android.view.animation.Animation) 17393 * @see #getAnimation() 17394 */ 17395 protected void onAnimationEnd() { 17396 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17397 } 17398 17399 /** 17400 * Invoked if there is a Transform that involves alpha. Subclass that can 17401 * draw themselves with the specified alpha should return true, and then 17402 * respect that alpha when their onDraw() is called. If this returns false 17403 * then the view may be redirected to draw into an offscreen buffer to 17404 * fulfill the request, which will look fine, but may be slower than if the 17405 * subclass handles it internally. The default implementation returns false. 17406 * 17407 * @param alpha The alpha (0..255) to apply to the view's drawing 17408 * @return true if the view can draw with the specified alpha. 17409 */ 17410 protected boolean onSetAlpha(int alpha) { 17411 return false; 17412 } 17413 17414 /** 17415 * This is used by the RootView to perform an optimization when 17416 * the view hierarchy contains one or several SurfaceView. 17417 * SurfaceView is always considered transparent, but its children are not, 17418 * therefore all View objects remove themselves from the global transparent 17419 * region (passed as a parameter to this function). 17420 * 17421 * @param region The transparent region for this ViewAncestor (window). 17422 * 17423 * @return Returns true if the effective visibility of the view at this 17424 * point is opaque, regardless of the transparent region; returns false 17425 * if it is possible for underlying windows to be seen behind the view. 17426 * 17427 * {@hide} 17428 */ 17429 public boolean gatherTransparentRegion(Region region) { 17430 final AttachInfo attachInfo = mAttachInfo; 17431 if (region != null && attachInfo != null) { 17432 final int pflags = mPrivateFlags; 17433 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17434 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17435 // remove it from the transparent region. 17436 final int[] location = attachInfo.mTransparentLocation; 17437 getLocationInWindow(location); 17438 region.op(location[0], location[1], location[0] + mRight - mLeft, 17439 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17440 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 17441 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17442 // exists, so we remove the background drawable's non-transparent 17443 // parts from this transparent region. 17444 applyDrawableToTransparentRegion(mBackground, region); 17445 } 17446 } 17447 return true; 17448 } 17449 17450 /** 17451 * Play a sound effect for this view. 17452 * 17453 * <p>The framework will play sound effects for some built in actions, such as 17454 * clicking, but you may wish to play these effects in your widget, 17455 * for instance, for internal navigation. 17456 * 17457 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17458 * {@link #isSoundEffectsEnabled()} is true. 17459 * 17460 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17461 */ 17462 public void playSoundEffect(int soundConstant) { 17463 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17464 return; 17465 } 17466 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17467 } 17468 17469 /** 17470 * BZZZTT!!1! 17471 * 17472 * <p>Provide haptic feedback to the user for this view. 17473 * 17474 * <p>The framework will provide haptic feedback for some built in actions, 17475 * such as long presses, but you may wish to provide feedback for your 17476 * own widget. 17477 * 17478 * <p>The feedback will only be performed if 17479 * {@link #isHapticFeedbackEnabled()} is true. 17480 * 17481 * @param feedbackConstant One of the constants defined in 17482 * {@link HapticFeedbackConstants} 17483 */ 17484 public boolean performHapticFeedback(int feedbackConstant) { 17485 return performHapticFeedback(feedbackConstant, 0); 17486 } 17487 17488 /** 17489 * BZZZTT!!1! 17490 * 17491 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17492 * 17493 * @param feedbackConstant One of the constants defined in 17494 * {@link HapticFeedbackConstants} 17495 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17496 */ 17497 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17498 if (mAttachInfo == null) { 17499 return false; 17500 } 17501 //noinspection SimplifiableIfStatement 17502 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17503 && !isHapticFeedbackEnabled()) { 17504 return false; 17505 } 17506 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17507 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17508 } 17509 17510 /** 17511 * Request that the visibility of the status bar or other screen/window 17512 * decorations be changed. 17513 * 17514 * <p>This method is used to put the over device UI into temporary modes 17515 * where the user's attention is focused more on the application content, 17516 * by dimming or hiding surrounding system affordances. This is typically 17517 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17518 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17519 * to be placed behind the action bar (and with these flags other system 17520 * affordances) so that smooth transitions between hiding and showing them 17521 * can be done. 17522 * 17523 * <p>Two representative examples of the use of system UI visibility is 17524 * implementing a content browsing application (like a magazine reader) 17525 * and a video playing application. 17526 * 17527 * <p>The first code shows a typical implementation of a View in a content 17528 * browsing application. In this implementation, the application goes 17529 * into a content-oriented mode by hiding the status bar and action bar, 17530 * and putting the navigation elements into lights out mode. The user can 17531 * then interact with content while in this mode. Such an application should 17532 * provide an easy way for the user to toggle out of the mode (such as to 17533 * check information in the status bar or access notifications). In the 17534 * implementation here, this is done simply by tapping on the content. 17535 * 17536 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17537 * content} 17538 * 17539 * <p>This second code sample shows a typical implementation of a View 17540 * in a video playing application. In this situation, while the video is 17541 * playing the application would like to go into a complete full-screen mode, 17542 * to use as much of the display as possible for the video. When in this state 17543 * the user can not interact with the application; the system intercepts 17544 * touching on the screen to pop the UI out of full screen mode. See 17545 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17546 * 17547 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17548 * content} 17549 * 17550 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17551 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17552 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17553 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17554 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17555 */ 17556 public void setSystemUiVisibility(int visibility) { 17557 if (visibility != mSystemUiVisibility) { 17558 mSystemUiVisibility = visibility; 17559 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17560 mParent.recomputeViewAttributes(this); 17561 } 17562 } 17563 } 17564 17565 /** 17566 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17567 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17568 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17569 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17570 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17571 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17572 */ 17573 public int getSystemUiVisibility() { 17574 return mSystemUiVisibility; 17575 } 17576 17577 /** 17578 * Returns the current system UI visibility that is currently set for 17579 * the entire window. This is the combination of the 17580 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17581 * views in the window. 17582 */ 17583 public int getWindowSystemUiVisibility() { 17584 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17585 } 17586 17587 /** 17588 * Override to find out when the window's requested system UI visibility 17589 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17590 * This is different from the callbacks received through 17591 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17592 * in that this is only telling you about the local request of the window, 17593 * not the actual values applied by the system. 17594 */ 17595 public void onWindowSystemUiVisibilityChanged(int visible) { 17596 } 17597 17598 /** 17599 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17600 * the view hierarchy. 17601 */ 17602 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17603 onWindowSystemUiVisibilityChanged(visible); 17604 } 17605 17606 /** 17607 * Set a listener to receive callbacks when the visibility of the system bar changes. 17608 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17609 */ 17610 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17611 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17612 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17613 mParent.recomputeViewAttributes(this); 17614 } 17615 } 17616 17617 /** 17618 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17619 * the view hierarchy. 17620 */ 17621 public void dispatchSystemUiVisibilityChanged(int visibility) { 17622 ListenerInfo li = mListenerInfo; 17623 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17624 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17625 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17626 } 17627 } 17628 17629 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17630 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17631 if (val != mSystemUiVisibility) { 17632 setSystemUiVisibility(val); 17633 return true; 17634 } 17635 return false; 17636 } 17637 17638 /** @hide */ 17639 public void setDisabledSystemUiVisibility(int flags) { 17640 if (mAttachInfo != null) { 17641 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17642 mAttachInfo.mDisabledSystemUiVisibility = flags; 17643 if (mParent != null) { 17644 mParent.recomputeViewAttributes(this); 17645 } 17646 } 17647 } 17648 } 17649 17650 /** 17651 * Creates an image that the system displays during the drag and drop 17652 * operation. This is called a "drag shadow". The default implementation 17653 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17654 * appearance as the given View. The default also positions the center of the drag shadow 17655 * directly under the touch point. If no View is provided (the constructor with no parameters 17656 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17657 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17658 * default is an invisible drag shadow. 17659 * <p> 17660 * You are not required to use the View you provide to the constructor as the basis of the 17661 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17662 * anything you want as the drag shadow. 17663 * </p> 17664 * <p> 17665 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17666 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17667 * size and position of the drag shadow. It uses this data to construct a 17668 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17669 * so that your application can draw the shadow image in the Canvas. 17670 * </p> 17671 * 17672 * <div class="special reference"> 17673 * <h3>Developer Guides</h3> 17674 * <p>For a guide to implementing drag and drop features, read the 17675 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17676 * </div> 17677 */ 17678 public static class DragShadowBuilder { 17679 private final WeakReference<View> mView; 17680 17681 /** 17682 * Constructs a shadow image builder based on a View. By default, the resulting drag 17683 * shadow will have the same appearance and dimensions as the View, with the touch point 17684 * over the center of the View. 17685 * @param view A View. Any View in scope can be used. 17686 */ 17687 public DragShadowBuilder(View view) { 17688 mView = new WeakReference<View>(view); 17689 } 17690 17691 /** 17692 * Construct a shadow builder object with no associated View. This 17693 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17694 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17695 * to supply the drag shadow's dimensions and appearance without 17696 * reference to any View object. If they are not overridden, then the result is an 17697 * invisible drag shadow. 17698 */ 17699 public DragShadowBuilder() { 17700 mView = new WeakReference<View>(null); 17701 } 17702 17703 /** 17704 * Returns the View object that had been passed to the 17705 * {@link #View.DragShadowBuilder(View)} 17706 * constructor. If that View parameter was {@code null} or if the 17707 * {@link #View.DragShadowBuilder()} 17708 * constructor was used to instantiate the builder object, this method will return 17709 * null. 17710 * 17711 * @return The View object associate with this builder object. 17712 */ 17713 @SuppressWarnings({"JavadocReference"}) 17714 final public View getView() { 17715 return mView.get(); 17716 } 17717 17718 /** 17719 * Provides the metrics for the shadow image. These include the dimensions of 17720 * the shadow image, and the point within that shadow that should 17721 * be centered under the touch location while dragging. 17722 * <p> 17723 * The default implementation sets the dimensions of the shadow to be the 17724 * same as the dimensions of the View itself and centers the shadow under 17725 * the touch point. 17726 * </p> 17727 * 17728 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17729 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17730 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17731 * image. 17732 * 17733 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17734 * shadow image that should be underneath the touch point during the drag and drop 17735 * operation. Your application must set {@link android.graphics.Point#x} to the 17736 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17737 */ 17738 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17739 final View view = mView.get(); 17740 if (view != null) { 17741 shadowSize.set(view.getWidth(), view.getHeight()); 17742 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17743 } else { 17744 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17745 } 17746 } 17747 17748 /** 17749 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17750 * based on the dimensions it received from the 17751 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17752 * 17753 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17754 */ 17755 public void onDrawShadow(Canvas canvas) { 17756 final View view = mView.get(); 17757 if (view != null) { 17758 view.draw(canvas); 17759 } else { 17760 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17761 } 17762 } 17763 } 17764 17765 /** 17766 * Starts a drag and drop operation. When your application calls this method, it passes a 17767 * {@link android.view.View.DragShadowBuilder} object to the system. The 17768 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17769 * to get metrics for the drag shadow, and then calls the object's 17770 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17771 * <p> 17772 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17773 * drag events to all the View objects in your application that are currently visible. It does 17774 * this either by calling the View object's drag listener (an implementation of 17775 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17776 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17777 * Both are passed a {@link android.view.DragEvent} object that has a 17778 * {@link android.view.DragEvent#getAction()} value of 17779 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17780 * </p> 17781 * <p> 17782 * Your application can invoke startDrag() on any attached View object. The View object does not 17783 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17784 * be related to the View the user selected for dragging. 17785 * </p> 17786 * @param data A {@link android.content.ClipData} object pointing to the data to be 17787 * transferred by the drag and drop operation. 17788 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17789 * drag shadow. 17790 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17791 * drop operation. This Object is put into every DragEvent object sent by the system during the 17792 * current drag. 17793 * <p> 17794 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17795 * to the target Views. For example, it can contain flags that differentiate between a 17796 * a copy operation and a move operation. 17797 * </p> 17798 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17799 * so the parameter should be set to 0. 17800 * @return {@code true} if the method completes successfully, or 17801 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17802 * do a drag, and so no drag operation is in progress. 17803 */ 17804 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17805 Object myLocalState, int flags) { 17806 if (ViewDebug.DEBUG_DRAG) { 17807 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17808 } 17809 boolean okay = false; 17810 17811 Point shadowSize = new Point(); 17812 Point shadowTouchPoint = new Point(); 17813 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17814 17815 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17816 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17817 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17818 } 17819 17820 if (ViewDebug.DEBUG_DRAG) { 17821 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17822 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17823 } 17824 Surface surface = new Surface(); 17825 try { 17826 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17827 flags, shadowSize.x, shadowSize.y, surface); 17828 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17829 + " surface=" + surface); 17830 if (token != null) { 17831 Canvas canvas = surface.lockCanvas(null); 17832 try { 17833 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17834 shadowBuilder.onDrawShadow(canvas); 17835 } finally { 17836 surface.unlockCanvasAndPost(canvas); 17837 } 17838 17839 final ViewRootImpl root = getViewRootImpl(); 17840 17841 // Cache the local state object for delivery with DragEvents 17842 root.setLocalDragState(myLocalState); 17843 17844 // repurpose 'shadowSize' for the last touch point 17845 root.getLastTouchPoint(shadowSize); 17846 17847 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17848 shadowSize.x, shadowSize.y, 17849 shadowTouchPoint.x, shadowTouchPoint.y, data); 17850 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17851 17852 // Off and running! Release our local surface instance; the drag 17853 // shadow surface is now managed by the system process. 17854 surface.release(); 17855 } 17856 } catch (Exception e) { 17857 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17858 surface.destroy(); 17859 } 17860 17861 return okay; 17862 } 17863 17864 /** 17865 * Handles drag events sent by the system following a call to 17866 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17867 *<p> 17868 * When the system calls this method, it passes a 17869 * {@link android.view.DragEvent} object. A call to 17870 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17871 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17872 * operation. 17873 * @param event The {@link android.view.DragEvent} sent by the system. 17874 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17875 * in DragEvent, indicating the type of drag event represented by this object. 17876 * @return {@code true} if the method was successful, otherwise {@code false}. 17877 * <p> 17878 * The method should return {@code true} in response to an action type of 17879 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17880 * operation. 17881 * </p> 17882 * <p> 17883 * The method should also return {@code true} in response to an action type of 17884 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17885 * {@code false} if it didn't. 17886 * </p> 17887 */ 17888 public boolean onDragEvent(DragEvent event) { 17889 return false; 17890 } 17891 17892 /** 17893 * Detects if this View is enabled and has a drag event listener. 17894 * If both are true, then it calls the drag event listener with the 17895 * {@link android.view.DragEvent} it received. If the drag event listener returns 17896 * {@code true}, then dispatchDragEvent() returns {@code true}. 17897 * <p> 17898 * For all other cases, the method calls the 17899 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17900 * method and returns its result. 17901 * </p> 17902 * <p> 17903 * This ensures that a drag event is always consumed, even if the View does not have a drag 17904 * event listener. However, if the View has a listener and the listener returns true, then 17905 * onDragEvent() is not called. 17906 * </p> 17907 */ 17908 public boolean dispatchDragEvent(DragEvent event) { 17909 ListenerInfo li = mListenerInfo; 17910 //noinspection SimplifiableIfStatement 17911 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17912 && li.mOnDragListener.onDrag(this, event)) { 17913 return true; 17914 } 17915 return onDragEvent(event); 17916 } 17917 17918 boolean canAcceptDrag() { 17919 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17920 } 17921 17922 /** 17923 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17924 * it is ever exposed at all. 17925 * @hide 17926 */ 17927 public void onCloseSystemDialogs(String reason) { 17928 } 17929 17930 /** 17931 * Given a Drawable whose bounds have been set to draw into this view, 17932 * update a Region being computed for 17933 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17934 * that any non-transparent parts of the Drawable are removed from the 17935 * given transparent region. 17936 * 17937 * @param dr The Drawable whose transparency is to be applied to the region. 17938 * @param region A Region holding the current transparency information, 17939 * where any parts of the region that are set are considered to be 17940 * transparent. On return, this region will be modified to have the 17941 * transparency information reduced by the corresponding parts of the 17942 * Drawable that are not transparent. 17943 * {@hide} 17944 */ 17945 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17946 if (DBG) { 17947 Log.i("View", "Getting transparent region for: " + this); 17948 } 17949 final Region r = dr.getTransparentRegion(); 17950 final Rect db = dr.getBounds(); 17951 final AttachInfo attachInfo = mAttachInfo; 17952 if (r != null && attachInfo != null) { 17953 final int w = getRight()-getLeft(); 17954 final int h = getBottom()-getTop(); 17955 if (db.left > 0) { 17956 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17957 r.op(0, 0, db.left, h, Region.Op.UNION); 17958 } 17959 if (db.right < w) { 17960 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17961 r.op(db.right, 0, w, h, Region.Op.UNION); 17962 } 17963 if (db.top > 0) { 17964 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17965 r.op(0, 0, w, db.top, Region.Op.UNION); 17966 } 17967 if (db.bottom < h) { 17968 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17969 r.op(0, db.bottom, w, h, Region.Op.UNION); 17970 } 17971 final int[] location = attachInfo.mTransparentLocation; 17972 getLocationInWindow(location); 17973 r.translate(location[0], location[1]); 17974 region.op(r, Region.Op.INTERSECT); 17975 } else { 17976 region.op(db, Region.Op.DIFFERENCE); 17977 } 17978 } 17979 17980 private void checkForLongClick(int delayOffset) { 17981 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17982 mHasPerformedLongPress = false; 17983 17984 if (mPendingCheckForLongPress == null) { 17985 mPendingCheckForLongPress = new CheckForLongPress(); 17986 } 17987 mPendingCheckForLongPress.rememberWindowAttachCount(); 17988 postDelayed(mPendingCheckForLongPress, 17989 ViewConfiguration.getLongPressTimeout() - delayOffset); 17990 } 17991 } 17992 17993 /** 17994 * Inflate a view from an XML resource. This convenience method wraps the {@link 17995 * LayoutInflater} class, which provides a full range of options for view inflation. 17996 * 17997 * @param context The Context object for your activity or application. 17998 * @param resource The resource ID to inflate 17999 * @param root A view group that will be the parent. Used to properly inflate the 18000 * layout_* parameters. 18001 * @see LayoutInflater 18002 */ 18003 public static View inflate(Context context, int resource, ViewGroup root) { 18004 LayoutInflater factory = LayoutInflater.from(context); 18005 return factory.inflate(resource, root); 18006 } 18007 18008 /** 18009 * Scroll the view with standard behavior for scrolling beyond the normal 18010 * content boundaries. Views that call this method should override 18011 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 18012 * results of an over-scroll operation. 18013 * 18014 * Views can use this method to handle any touch or fling-based scrolling. 18015 * 18016 * @param deltaX Change in X in pixels 18017 * @param deltaY Change in Y in pixels 18018 * @param scrollX Current X scroll value in pixels before applying deltaX 18019 * @param scrollY Current Y scroll value in pixels before applying deltaY 18020 * @param scrollRangeX Maximum content scroll range along the X axis 18021 * @param scrollRangeY Maximum content scroll range along the Y axis 18022 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18023 * along the X axis. 18024 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18025 * along the Y axis. 18026 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18027 * @return true if scrolling was clamped to an over-scroll boundary along either 18028 * axis, false otherwise. 18029 */ 18030 @SuppressWarnings({"UnusedParameters"}) 18031 protected boolean overScrollBy(int deltaX, int deltaY, 18032 int scrollX, int scrollY, 18033 int scrollRangeX, int scrollRangeY, 18034 int maxOverScrollX, int maxOverScrollY, 18035 boolean isTouchEvent) { 18036 final int overScrollMode = mOverScrollMode; 18037 final boolean canScrollHorizontal = 18038 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18039 final boolean canScrollVertical = 18040 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18041 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18042 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18043 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18044 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18045 18046 int newScrollX = scrollX + deltaX; 18047 if (!overScrollHorizontal) { 18048 maxOverScrollX = 0; 18049 } 18050 18051 int newScrollY = scrollY + deltaY; 18052 if (!overScrollVertical) { 18053 maxOverScrollY = 0; 18054 } 18055 18056 // Clamp values if at the limits and record 18057 final int left = -maxOverScrollX; 18058 final int right = maxOverScrollX + scrollRangeX; 18059 final int top = -maxOverScrollY; 18060 final int bottom = maxOverScrollY + scrollRangeY; 18061 18062 boolean clampedX = false; 18063 if (newScrollX > right) { 18064 newScrollX = right; 18065 clampedX = true; 18066 } else if (newScrollX < left) { 18067 newScrollX = left; 18068 clampedX = true; 18069 } 18070 18071 boolean clampedY = false; 18072 if (newScrollY > bottom) { 18073 newScrollY = bottom; 18074 clampedY = true; 18075 } else if (newScrollY < top) { 18076 newScrollY = top; 18077 clampedY = true; 18078 } 18079 18080 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18081 18082 return clampedX || clampedY; 18083 } 18084 18085 /** 18086 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18087 * respond to the results of an over-scroll operation. 18088 * 18089 * @param scrollX New X scroll value in pixels 18090 * @param scrollY New Y scroll value in pixels 18091 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18092 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18093 */ 18094 protected void onOverScrolled(int scrollX, int scrollY, 18095 boolean clampedX, boolean clampedY) { 18096 // Intentionally empty. 18097 } 18098 18099 /** 18100 * Returns the over-scroll mode for this view. The result will be 18101 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18102 * (allow over-scrolling only if the view content is larger than the container), 18103 * or {@link #OVER_SCROLL_NEVER}. 18104 * 18105 * @return This view's over-scroll mode. 18106 */ 18107 public int getOverScrollMode() { 18108 return mOverScrollMode; 18109 } 18110 18111 /** 18112 * Set the over-scroll mode for this view. Valid over-scroll modes are 18113 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18114 * (allow over-scrolling only if the view content is larger than the container), 18115 * or {@link #OVER_SCROLL_NEVER}. 18116 * 18117 * Setting the over-scroll mode of a view will have an effect only if the 18118 * view is capable of scrolling. 18119 * 18120 * @param overScrollMode The new over-scroll mode for this view. 18121 */ 18122 public void setOverScrollMode(int overScrollMode) { 18123 if (overScrollMode != OVER_SCROLL_ALWAYS && 18124 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18125 overScrollMode != OVER_SCROLL_NEVER) { 18126 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18127 } 18128 mOverScrollMode = overScrollMode; 18129 } 18130 18131 /** 18132 * Enable or disable nested scrolling for this view. 18133 * 18134 * <p>If this property is set to true the view will be permitted to initiate nested 18135 * scrolling operations with a compatible parent view in the current hierarchy. If this 18136 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18137 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18138 * the nested scroll.</p> 18139 * 18140 * @param enabled true to enable nested scrolling, false to disable 18141 * 18142 * @see #isNestedScrollingEnabled() 18143 */ 18144 public void setNestedScrollingEnabled(boolean enabled) { 18145 if (enabled) { 18146 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18147 } else { 18148 stopNestedScroll(); 18149 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18150 } 18151 } 18152 18153 /** 18154 * Returns true if nested scrolling is enabled for this view. 18155 * 18156 * <p>If nested scrolling is enabled and this View class implementation supports it, 18157 * this view will act as a nested scrolling child view when applicable, forwarding data 18158 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18159 * parent.</p> 18160 * 18161 * @return true if nested scrolling is enabled 18162 * 18163 * @see #setNestedScrollingEnabled(boolean) 18164 */ 18165 public boolean isNestedScrollingEnabled() { 18166 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18167 PFLAG3_NESTED_SCROLLING_ENABLED; 18168 } 18169 18170 /** 18171 * Begin a nestable scroll operation along the given axes. 18172 * 18173 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18174 * 18175 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18176 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18177 * In the case of touch scrolling the nested scroll will be terminated automatically in 18178 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18179 * In the event of programmatic scrolling the caller must explicitly call 18180 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18181 * 18182 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18183 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18184 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18185 * 18186 * <p>At each incremental step of the scroll the caller should invoke 18187 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18188 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18189 * parent at least partially consumed the scroll and the caller should adjust the amount it 18190 * scrolls by.</p> 18191 * 18192 * <p>After applying the remainder of the scroll delta the caller should invoke 18193 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18194 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18195 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18196 * </p> 18197 * 18198 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18199 * {@link #SCROLL_AXIS_VERTICAL}. 18200 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18201 * the current gesture. 18202 * 18203 * @see #stopNestedScroll() 18204 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18205 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18206 */ 18207 public boolean startNestedScroll(int axes) { 18208 if (hasNestedScrollingParent()) { 18209 // Already in progress 18210 return true; 18211 } 18212 if (isNestedScrollingEnabled()) { 18213 ViewParent p = getParent(); 18214 View child = this; 18215 while (p != null) { 18216 try { 18217 if (p.onStartNestedScroll(child, this, axes)) { 18218 mNestedScrollingParent = p; 18219 p.onNestedScrollAccepted(child, this, axes); 18220 return true; 18221 } 18222 } catch (AbstractMethodError e) { 18223 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18224 "method onStartNestedScroll", e); 18225 // Allow the search upward to continue 18226 } 18227 if (p instanceof View) { 18228 child = (View) p; 18229 } 18230 p = p.getParent(); 18231 } 18232 } 18233 return false; 18234 } 18235 18236 /** 18237 * Stop a nested scroll in progress. 18238 * 18239 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18240 * 18241 * @see #startNestedScroll(int) 18242 */ 18243 public void stopNestedScroll() { 18244 if (mNestedScrollingParent != null) { 18245 mNestedScrollingParent.onStopNestedScroll(this); 18246 mNestedScrollingParent = null; 18247 } 18248 } 18249 18250 /** 18251 * Returns true if this view has a nested scrolling parent. 18252 * 18253 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18254 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18255 * 18256 * @return whether this view has a nested scrolling parent 18257 */ 18258 public boolean hasNestedScrollingParent() { 18259 return mNestedScrollingParent != null; 18260 } 18261 18262 /** 18263 * Dispatch one step of a nested scroll in progress. 18264 * 18265 * <p>Implementations of views that support nested scrolling should call this to report 18266 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18267 * is not currently in progress or nested scrolling is not 18268 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18269 * 18270 * <p>Compatible View implementations should also call 18271 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18272 * consuming a component of the scroll event themselves.</p> 18273 * 18274 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18275 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18276 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18277 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18278 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18279 * in local view coordinates of this view from before this operation 18280 * to after it completes. View implementations may use this to adjust 18281 * expected input coordinate tracking. 18282 * @return true if the event was dispatched, false if it could not be dispatched. 18283 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18284 */ 18285 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18286 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18287 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18288 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18289 int startX = 0; 18290 int startY = 0; 18291 if (offsetInWindow != null) { 18292 getLocationInWindow(offsetInWindow); 18293 startX = offsetInWindow[0]; 18294 startY = offsetInWindow[1]; 18295 } 18296 18297 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18298 dxUnconsumed, dyUnconsumed); 18299 18300 if (offsetInWindow != null) { 18301 getLocationInWindow(offsetInWindow); 18302 offsetInWindow[0] -= startX; 18303 offsetInWindow[1] -= startY; 18304 } 18305 return true; 18306 } else if (offsetInWindow != null) { 18307 // No motion, no dispatch. Keep offsetInWindow up to date. 18308 offsetInWindow[0] = 0; 18309 offsetInWindow[1] = 0; 18310 } 18311 } 18312 return false; 18313 } 18314 18315 /** 18316 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18317 * 18318 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18319 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18320 * scrolling operation to consume some or all of the scroll operation before the child view 18321 * consumes it.</p> 18322 * 18323 * @param dx Horizontal scroll distance in pixels 18324 * @param dy Vertical scroll distance in pixels 18325 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18326 * and consumed[1] the consumed dy. 18327 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18328 * in local view coordinates of this view from before this operation 18329 * to after it completes. View implementations may use this to adjust 18330 * expected input coordinate tracking. 18331 * @return true if the parent consumed some or all of the scroll delta 18332 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18333 */ 18334 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18335 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18336 if (dx != 0 || dy != 0) { 18337 int startX = 0; 18338 int startY = 0; 18339 if (offsetInWindow != null) { 18340 getLocationInWindow(offsetInWindow); 18341 startX = offsetInWindow[0]; 18342 startY = offsetInWindow[1]; 18343 } 18344 18345 if (consumed == null) { 18346 if (mTempNestedScrollConsumed == null) { 18347 mTempNestedScrollConsumed = new int[2]; 18348 } 18349 consumed = mTempNestedScrollConsumed; 18350 } 18351 consumed[0] = 0; 18352 consumed[1] = 0; 18353 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18354 18355 if (offsetInWindow != null) { 18356 getLocationInWindow(offsetInWindow); 18357 offsetInWindow[0] -= startX; 18358 offsetInWindow[1] -= startY; 18359 } 18360 return consumed[0] != 0 || consumed[1] != 0; 18361 } else if (offsetInWindow != null) { 18362 offsetInWindow[0] = 0; 18363 offsetInWindow[1] = 0; 18364 } 18365 } 18366 return false; 18367 } 18368 18369 /** 18370 * Dispatch a fling to a nested scrolling parent. 18371 * 18372 * <p>This method should be used to indicate that a nested scrolling child has detected 18373 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18374 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18375 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18376 * along a scrollable axis.</p> 18377 * 18378 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18379 * its own content, it can use this method to delegate the fling to its nested scrolling 18380 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18381 * 18382 * @param velocityX Horizontal fling velocity in pixels per second 18383 * @param velocityY Vertical fling velocity in pixels per second 18384 * @param consumed true if the child consumed the fling, false otherwise 18385 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18386 */ 18387 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18388 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18389 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18390 } 18391 return false; 18392 } 18393 18394 /** 18395 * Gets a scale factor that determines the distance the view should scroll 18396 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18397 * @return The vertical scroll scale factor. 18398 * @hide 18399 */ 18400 protected float getVerticalScrollFactor() { 18401 if (mVerticalScrollFactor == 0) { 18402 TypedValue outValue = new TypedValue(); 18403 if (!mContext.getTheme().resolveAttribute( 18404 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18405 throw new IllegalStateException( 18406 "Expected theme to define listPreferredItemHeight."); 18407 } 18408 mVerticalScrollFactor = outValue.getDimension( 18409 mContext.getResources().getDisplayMetrics()); 18410 } 18411 return mVerticalScrollFactor; 18412 } 18413 18414 /** 18415 * Gets a scale factor that determines the distance the view should scroll 18416 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18417 * @return The horizontal scroll scale factor. 18418 * @hide 18419 */ 18420 protected float getHorizontalScrollFactor() { 18421 // TODO: Should use something else. 18422 return getVerticalScrollFactor(); 18423 } 18424 18425 /** 18426 * Return the value specifying the text direction or policy that was set with 18427 * {@link #setTextDirection(int)}. 18428 * 18429 * @return the defined text direction. It can be one of: 18430 * 18431 * {@link #TEXT_DIRECTION_INHERIT}, 18432 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18433 * {@link #TEXT_DIRECTION_ANY_RTL}, 18434 * {@link #TEXT_DIRECTION_LTR}, 18435 * {@link #TEXT_DIRECTION_RTL}, 18436 * {@link #TEXT_DIRECTION_LOCALE} 18437 * 18438 * @attr ref android.R.styleable#View_textDirection 18439 * 18440 * @hide 18441 */ 18442 @ViewDebug.ExportedProperty(category = "text", mapping = { 18443 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18444 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18445 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18446 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18447 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18448 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18449 }) 18450 public int getRawTextDirection() { 18451 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18452 } 18453 18454 /** 18455 * Set the text direction. 18456 * 18457 * @param textDirection the direction to set. Should be one of: 18458 * 18459 * {@link #TEXT_DIRECTION_INHERIT}, 18460 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18461 * {@link #TEXT_DIRECTION_ANY_RTL}, 18462 * {@link #TEXT_DIRECTION_LTR}, 18463 * {@link #TEXT_DIRECTION_RTL}, 18464 * {@link #TEXT_DIRECTION_LOCALE} 18465 * 18466 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18467 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18468 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18469 * 18470 * @attr ref android.R.styleable#View_textDirection 18471 */ 18472 public void setTextDirection(int textDirection) { 18473 if (getRawTextDirection() != textDirection) { 18474 // Reset the current text direction and the resolved one 18475 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18476 resetResolvedTextDirection(); 18477 // Set the new text direction 18478 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18479 // Do resolution 18480 resolveTextDirection(); 18481 // Notify change 18482 onRtlPropertiesChanged(getLayoutDirection()); 18483 // Refresh 18484 requestLayout(); 18485 invalidate(true); 18486 } 18487 } 18488 18489 /** 18490 * Return the resolved text direction. 18491 * 18492 * @return the resolved text direction. Returns one of: 18493 * 18494 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18495 * {@link #TEXT_DIRECTION_ANY_RTL}, 18496 * {@link #TEXT_DIRECTION_LTR}, 18497 * {@link #TEXT_DIRECTION_RTL}, 18498 * {@link #TEXT_DIRECTION_LOCALE} 18499 * 18500 * @attr ref android.R.styleable#View_textDirection 18501 */ 18502 @ViewDebug.ExportedProperty(category = "text", mapping = { 18503 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18504 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18505 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18506 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18507 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18508 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18509 }) 18510 public int getTextDirection() { 18511 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18512 } 18513 18514 /** 18515 * Resolve the text direction. 18516 * 18517 * @return true if resolution has been done, false otherwise. 18518 * 18519 * @hide 18520 */ 18521 public boolean resolveTextDirection() { 18522 // Reset any previous text direction resolution 18523 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18524 18525 if (hasRtlSupport()) { 18526 // Set resolved text direction flag depending on text direction flag 18527 final int textDirection = getRawTextDirection(); 18528 switch(textDirection) { 18529 case TEXT_DIRECTION_INHERIT: 18530 if (!canResolveTextDirection()) { 18531 // We cannot do the resolution if there is no parent, so use the default one 18532 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18533 // Resolution will need to happen again later 18534 return false; 18535 } 18536 18537 // Parent has not yet resolved, so we still return the default 18538 try { 18539 if (!mParent.isTextDirectionResolved()) { 18540 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18541 // Resolution will need to happen again later 18542 return false; 18543 } 18544 } catch (AbstractMethodError e) { 18545 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18546 " does not fully implement ViewParent", e); 18547 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18548 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18549 return true; 18550 } 18551 18552 // Set current resolved direction to the same value as the parent's one 18553 int parentResolvedDirection; 18554 try { 18555 parentResolvedDirection = mParent.getTextDirection(); 18556 } catch (AbstractMethodError e) { 18557 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18558 " does not fully implement ViewParent", e); 18559 parentResolvedDirection = TEXT_DIRECTION_LTR; 18560 } 18561 switch (parentResolvedDirection) { 18562 case TEXT_DIRECTION_FIRST_STRONG: 18563 case TEXT_DIRECTION_ANY_RTL: 18564 case TEXT_DIRECTION_LTR: 18565 case TEXT_DIRECTION_RTL: 18566 case TEXT_DIRECTION_LOCALE: 18567 mPrivateFlags2 |= 18568 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18569 break; 18570 default: 18571 // Default resolved direction is "first strong" heuristic 18572 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18573 } 18574 break; 18575 case TEXT_DIRECTION_FIRST_STRONG: 18576 case TEXT_DIRECTION_ANY_RTL: 18577 case TEXT_DIRECTION_LTR: 18578 case TEXT_DIRECTION_RTL: 18579 case TEXT_DIRECTION_LOCALE: 18580 // Resolved direction is the same as text direction 18581 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18582 break; 18583 default: 18584 // Default resolved direction is "first strong" heuristic 18585 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18586 } 18587 } else { 18588 // Default resolved direction is "first strong" heuristic 18589 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18590 } 18591 18592 // Set to resolved 18593 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18594 return true; 18595 } 18596 18597 /** 18598 * Check if text direction resolution can be done. 18599 * 18600 * @return true if text direction resolution can be done otherwise return false. 18601 */ 18602 public boolean canResolveTextDirection() { 18603 switch (getRawTextDirection()) { 18604 case TEXT_DIRECTION_INHERIT: 18605 if (mParent != null) { 18606 try { 18607 return mParent.canResolveTextDirection(); 18608 } catch (AbstractMethodError e) { 18609 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18610 " does not fully implement ViewParent", e); 18611 } 18612 } 18613 return false; 18614 18615 default: 18616 return true; 18617 } 18618 } 18619 18620 /** 18621 * Reset resolved text direction. Text direction will be resolved during a call to 18622 * {@link #onMeasure(int, int)}. 18623 * 18624 * @hide 18625 */ 18626 public void resetResolvedTextDirection() { 18627 // Reset any previous text direction resolution 18628 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18629 // Set to default value 18630 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18631 } 18632 18633 /** 18634 * @return true if text direction is inherited. 18635 * 18636 * @hide 18637 */ 18638 public boolean isTextDirectionInherited() { 18639 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18640 } 18641 18642 /** 18643 * @return true if text direction is resolved. 18644 */ 18645 public boolean isTextDirectionResolved() { 18646 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18647 } 18648 18649 /** 18650 * Return the value specifying the text alignment or policy that was set with 18651 * {@link #setTextAlignment(int)}. 18652 * 18653 * @return the defined text alignment. It can be one of: 18654 * 18655 * {@link #TEXT_ALIGNMENT_INHERIT}, 18656 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18657 * {@link #TEXT_ALIGNMENT_CENTER}, 18658 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18659 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18660 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18661 * {@link #TEXT_ALIGNMENT_VIEW_END} 18662 * 18663 * @attr ref android.R.styleable#View_textAlignment 18664 * 18665 * @hide 18666 */ 18667 @ViewDebug.ExportedProperty(category = "text", mapping = { 18668 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18669 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18670 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18671 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18672 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18673 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18674 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18675 }) 18676 @TextAlignment 18677 public int getRawTextAlignment() { 18678 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18679 } 18680 18681 /** 18682 * Set the text alignment. 18683 * 18684 * @param textAlignment The text alignment to set. Should be one of 18685 * 18686 * {@link #TEXT_ALIGNMENT_INHERIT}, 18687 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18688 * {@link #TEXT_ALIGNMENT_CENTER}, 18689 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18690 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18691 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18692 * {@link #TEXT_ALIGNMENT_VIEW_END} 18693 * 18694 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18695 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18696 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18697 * 18698 * @attr ref android.R.styleable#View_textAlignment 18699 */ 18700 public void setTextAlignment(@TextAlignment int textAlignment) { 18701 if (textAlignment != getRawTextAlignment()) { 18702 // Reset the current and resolved text alignment 18703 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18704 resetResolvedTextAlignment(); 18705 // Set the new text alignment 18706 mPrivateFlags2 |= 18707 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18708 // Do resolution 18709 resolveTextAlignment(); 18710 // Notify change 18711 onRtlPropertiesChanged(getLayoutDirection()); 18712 // Refresh 18713 requestLayout(); 18714 invalidate(true); 18715 } 18716 } 18717 18718 /** 18719 * Return the resolved text alignment. 18720 * 18721 * @return the resolved text alignment. Returns one of: 18722 * 18723 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18724 * {@link #TEXT_ALIGNMENT_CENTER}, 18725 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18726 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18727 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18728 * {@link #TEXT_ALIGNMENT_VIEW_END} 18729 * 18730 * @attr ref android.R.styleable#View_textAlignment 18731 */ 18732 @ViewDebug.ExportedProperty(category = "text", mapping = { 18733 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18734 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18735 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18736 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18737 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18738 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18739 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18740 }) 18741 @TextAlignment 18742 public int getTextAlignment() { 18743 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18744 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18745 } 18746 18747 /** 18748 * Resolve the text alignment. 18749 * 18750 * @return true if resolution has been done, false otherwise. 18751 * 18752 * @hide 18753 */ 18754 public boolean resolveTextAlignment() { 18755 // Reset any previous text alignment resolution 18756 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18757 18758 if (hasRtlSupport()) { 18759 // Set resolved text alignment flag depending on text alignment flag 18760 final int textAlignment = getRawTextAlignment(); 18761 switch (textAlignment) { 18762 case TEXT_ALIGNMENT_INHERIT: 18763 // Check if we can resolve the text alignment 18764 if (!canResolveTextAlignment()) { 18765 // We cannot do the resolution if there is no parent so use the default 18766 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18767 // Resolution will need to happen again later 18768 return false; 18769 } 18770 18771 // Parent has not yet resolved, so we still return the default 18772 try { 18773 if (!mParent.isTextAlignmentResolved()) { 18774 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18775 // Resolution will need to happen again later 18776 return false; 18777 } 18778 } catch (AbstractMethodError e) { 18779 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18780 " does not fully implement ViewParent", e); 18781 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18782 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18783 return true; 18784 } 18785 18786 int parentResolvedTextAlignment; 18787 try { 18788 parentResolvedTextAlignment = mParent.getTextAlignment(); 18789 } catch (AbstractMethodError e) { 18790 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18791 " does not fully implement ViewParent", e); 18792 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18793 } 18794 switch (parentResolvedTextAlignment) { 18795 case TEXT_ALIGNMENT_GRAVITY: 18796 case TEXT_ALIGNMENT_TEXT_START: 18797 case TEXT_ALIGNMENT_TEXT_END: 18798 case TEXT_ALIGNMENT_CENTER: 18799 case TEXT_ALIGNMENT_VIEW_START: 18800 case TEXT_ALIGNMENT_VIEW_END: 18801 // Resolved text alignment is the same as the parent resolved 18802 // text alignment 18803 mPrivateFlags2 |= 18804 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18805 break; 18806 default: 18807 // Use default resolved text alignment 18808 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18809 } 18810 break; 18811 case TEXT_ALIGNMENT_GRAVITY: 18812 case TEXT_ALIGNMENT_TEXT_START: 18813 case TEXT_ALIGNMENT_TEXT_END: 18814 case TEXT_ALIGNMENT_CENTER: 18815 case TEXT_ALIGNMENT_VIEW_START: 18816 case TEXT_ALIGNMENT_VIEW_END: 18817 // Resolved text alignment is the same as text alignment 18818 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18819 break; 18820 default: 18821 // Use default resolved text alignment 18822 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18823 } 18824 } else { 18825 // Use default resolved text alignment 18826 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18827 } 18828 18829 // Set the resolved 18830 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18831 return true; 18832 } 18833 18834 /** 18835 * Check if text alignment resolution can be done. 18836 * 18837 * @return true if text alignment resolution can be done otherwise return false. 18838 */ 18839 public boolean canResolveTextAlignment() { 18840 switch (getRawTextAlignment()) { 18841 case TEXT_DIRECTION_INHERIT: 18842 if (mParent != null) { 18843 try { 18844 return mParent.canResolveTextAlignment(); 18845 } catch (AbstractMethodError e) { 18846 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18847 " does not fully implement ViewParent", e); 18848 } 18849 } 18850 return false; 18851 18852 default: 18853 return true; 18854 } 18855 } 18856 18857 /** 18858 * Reset resolved text alignment. Text alignment will be resolved during a call to 18859 * {@link #onMeasure(int, int)}. 18860 * 18861 * @hide 18862 */ 18863 public void resetResolvedTextAlignment() { 18864 // Reset any previous text alignment resolution 18865 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18866 // Set to default 18867 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18868 } 18869 18870 /** 18871 * @return true if text alignment is inherited. 18872 * 18873 * @hide 18874 */ 18875 public boolean isTextAlignmentInherited() { 18876 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18877 } 18878 18879 /** 18880 * @return true if text alignment is resolved. 18881 */ 18882 public boolean isTextAlignmentResolved() { 18883 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18884 } 18885 18886 /** 18887 * Generate a value suitable for use in {@link #setId(int)}. 18888 * This value will not collide with ID values generated at build time by aapt for R.id. 18889 * 18890 * @return a generated ID value 18891 */ 18892 public static int generateViewId() { 18893 for (;;) { 18894 final int result = sNextGeneratedId.get(); 18895 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18896 int newValue = result + 1; 18897 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18898 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18899 return result; 18900 } 18901 } 18902 } 18903 18904 /** 18905 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 18906 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 18907 * a normal View or a ViewGroup with 18908 * {@link android.view.ViewGroup#isTransitionGroup()} true. 18909 * @hide 18910 */ 18911 public void captureTransitioningViews(List<View> transitioningViews) { 18912 if (getVisibility() == View.VISIBLE) { 18913 transitioningViews.add(this); 18914 } 18915 } 18916 18917 /** 18918 * Adds all Views that have {@link #getViewName()} non-null to namedElements. 18919 * @param namedElements Will contain all Views in the hierarchy having a view name. 18920 * @hide 18921 */ 18922 public void findNamedViews(Map<String, View> namedElements) { 18923 if (getVisibility() == VISIBLE) { 18924 String viewName = getViewName(); 18925 if (viewName != null) { 18926 namedElements.put(viewName, this); 18927 } 18928 } 18929 } 18930 18931 // 18932 // Properties 18933 // 18934 /** 18935 * A Property wrapper around the <code>alpha</code> functionality handled by the 18936 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18937 */ 18938 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18939 @Override 18940 public void setValue(View object, float value) { 18941 object.setAlpha(value); 18942 } 18943 18944 @Override 18945 public Float get(View object) { 18946 return object.getAlpha(); 18947 } 18948 }; 18949 18950 /** 18951 * A Property wrapper around the <code>translationX</code> functionality handled by the 18952 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 18953 */ 18954 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 18955 @Override 18956 public void setValue(View object, float value) { 18957 object.setTranslationX(value); 18958 } 18959 18960 @Override 18961 public Float get(View object) { 18962 return object.getTranslationX(); 18963 } 18964 }; 18965 18966 /** 18967 * A Property wrapper around the <code>translationY</code> functionality handled by the 18968 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 18969 */ 18970 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 18971 @Override 18972 public void setValue(View object, float value) { 18973 object.setTranslationY(value); 18974 } 18975 18976 @Override 18977 public Float get(View object) { 18978 return object.getTranslationY(); 18979 } 18980 }; 18981 18982 /** 18983 * A Property wrapper around the <code>translationZ</code> functionality handled by the 18984 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 18985 */ 18986 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 18987 @Override 18988 public void setValue(View object, float value) { 18989 object.setTranslationZ(value); 18990 } 18991 18992 @Override 18993 public Float get(View object) { 18994 return object.getTranslationZ(); 18995 } 18996 }; 18997 18998 /** 18999 * A Property wrapper around the <code>x</code> functionality handled by the 19000 * {@link View#setX(float)} and {@link View#getX()} methods. 19001 */ 19002 public static final Property<View, Float> X = new FloatProperty<View>("x") { 19003 @Override 19004 public void setValue(View object, float value) { 19005 object.setX(value); 19006 } 19007 19008 @Override 19009 public Float get(View object) { 19010 return object.getX(); 19011 } 19012 }; 19013 19014 /** 19015 * A Property wrapper around the <code>y</code> functionality handled by the 19016 * {@link View#setY(float)} and {@link View#getY()} methods. 19017 */ 19018 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 19019 @Override 19020 public void setValue(View object, float value) { 19021 object.setY(value); 19022 } 19023 19024 @Override 19025 public Float get(View object) { 19026 return object.getY(); 19027 } 19028 }; 19029 19030 /** 19031 * A Property wrapper around the <code>z</code> functionality handled by the 19032 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19033 */ 19034 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19035 @Override 19036 public void setValue(View object, float value) { 19037 object.setZ(value); 19038 } 19039 19040 @Override 19041 public Float get(View object) { 19042 return object.getZ(); 19043 } 19044 }; 19045 19046 /** 19047 * A Property wrapper around the <code>rotation</code> functionality handled by the 19048 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19049 */ 19050 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19051 @Override 19052 public void setValue(View object, float value) { 19053 object.setRotation(value); 19054 } 19055 19056 @Override 19057 public Float get(View object) { 19058 return object.getRotation(); 19059 } 19060 }; 19061 19062 /** 19063 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19064 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19065 */ 19066 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19067 @Override 19068 public void setValue(View object, float value) { 19069 object.setRotationX(value); 19070 } 19071 19072 @Override 19073 public Float get(View object) { 19074 return object.getRotationX(); 19075 } 19076 }; 19077 19078 /** 19079 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19080 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19081 */ 19082 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19083 @Override 19084 public void setValue(View object, float value) { 19085 object.setRotationY(value); 19086 } 19087 19088 @Override 19089 public Float get(View object) { 19090 return object.getRotationY(); 19091 } 19092 }; 19093 19094 /** 19095 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19096 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19097 */ 19098 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19099 @Override 19100 public void setValue(View object, float value) { 19101 object.setScaleX(value); 19102 } 19103 19104 @Override 19105 public Float get(View object) { 19106 return object.getScaleX(); 19107 } 19108 }; 19109 19110 /** 19111 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19112 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19113 */ 19114 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19115 @Override 19116 public void setValue(View object, float value) { 19117 object.setScaleY(value); 19118 } 19119 19120 @Override 19121 public Float get(View object) { 19122 return object.getScaleY(); 19123 } 19124 }; 19125 19126 /** 19127 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19128 * Each MeasureSpec represents a requirement for either the width or the height. 19129 * A MeasureSpec is comprised of a size and a mode. There are three possible 19130 * modes: 19131 * <dl> 19132 * <dt>UNSPECIFIED</dt> 19133 * <dd> 19134 * The parent has not imposed any constraint on the child. It can be whatever size 19135 * it wants. 19136 * </dd> 19137 * 19138 * <dt>EXACTLY</dt> 19139 * <dd> 19140 * The parent has determined an exact size for the child. The child is going to be 19141 * given those bounds regardless of how big it wants to be. 19142 * </dd> 19143 * 19144 * <dt>AT_MOST</dt> 19145 * <dd> 19146 * The child can be as large as it wants up to the specified size. 19147 * </dd> 19148 * </dl> 19149 * 19150 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19151 * is provided to pack and unpack the <size, mode> tuple into the int. 19152 */ 19153 public static class MeasureSpec { 19154 private static final int MODE_SHIFT = 30; 19155 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19156 19157 /** 19158 * Measure specification mode: The parent has not imposed any constraint 19159 * on the child. It can be whatever size it wants. 19160 */ 19161 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19162 19163 /** 19164 * Measure specification mode: The parent has determined an exact size 19165 * for the child. The child is going to be given those bounds regardless 19166 * of how big it wants to be. 19167 */ 19168 public static final int EXACTLY = 1 << MODE_SHIFT; 19169 19170 /** 19171 * Measure specification mode: The child can be as large as it wants up 19172 * to the specified size. 19173 */ 19174 public static final int AT_MOST = 2 << MODE_SHIFT; 19175 19176 /** 19177 * Creates a measure specification based on the supplied size and mode. 19178 * 19179 * The mode must always be one of the following: 19180 * <ul> 19181 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19182 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19183 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19184 * </ul> 19185 * 19186 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19187 * implementation was such that the order of arguments did not matter 19188 * and overflow in either value could impact the resulting MeasureSpec. 19189 * {@link android.widget.RelativeLayout} was affected by this bug. 19190 * Apps targeting API levels greater than 17 will get the fixed, more strict 19191 * behavior.</p> 19192 * 19193 * @param size the size of the measure specification 19194 * @param mode the mode of the measure specification 19195 * @return the measure specification based on size and mode 19196 */ 19197 public static int makeMeasureSpec(int size, int mode) { 19198 if (sUseBrokenMakeMeasureSpec) { 19199 return size + mode; 19200 } else { 19201 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19202 } 19203 } 19204 19205 /** 19206 * Extracts the mode from the supplied measure specification. 19207 * 19208 * @param measureSpec the measure specification to extract the mode from 19209 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19210 * {@link android.view.View.MeasureSpec#AT_MOST} or 19211 * {@link android.view.View.MeasureSpec#EXACTLY} 19212 */ 19213 public static int getMode(int measureSpec) { 19214 return (measureSpec & MODE_MASK); 19215 } 19216 19217 /** 19218 * Extracts the size from the supplied measure specification. 19219 * 19220 * @param measureSpec the measure specification to extract the size from 19221 * @return the size in pixels defined in the supplied measure specification 19222 */ 19223 public static int getSize(int measureSpec) { 19224 return (measureSpec & ~MODE_MASK); 19225 } 19226 19227 static int adjust(int measureSpec, int delta) { 19228 final int mode = getMode(measureSpec); 19229 if (mode == UNSPECIFIED) { 19230 // No need to adjust size for UNSPECIFIED mode. 19231 return makeMeasureSpec(0, UNSPECIFIED); 19232 } 19233 int size = getSize(measureSpec) + delta; 19234 if (size < 0) { 19235 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19236 ") spec: " + toString(measureSpec) + " delta: " + delta); 19237 size = 0; 19238 } 19239 return makeMeasureSpec(size, mode); 19240 } 19241 19242 /** 19243 * Returns a String representation of the specified measure 19244 * specification. 19245 * 19246 * @param measureSpec the measure specification to convert to a String 19247 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19248 */ 19249 public static String toString(int measureSpec) { 19250 int mode = getMode(measureSpec); 19251 int size = getSize(measureSpec); 19252 19253 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19254 19255 if (mode == UNSPECIFIED) 19256 sb.append("UNSPECIFIED "); 19257 else if (mode == EXACTLY) 19258 sb.append("EXACTLY "); 19259 else if (mode == AT_MOST) 19260 sb.append("AT_MOST "); 19261 else 19262 sb.append(mode).append(" "); 19263 19264 sb.append(size); 19265 return sb.toString(); 19266 } 19267 } 19268 19269 private final class CheckForLongPress implements Runnable { 19270 private int mOriginalWindowAttachCount; 19271 19272 @Override 19273 public void run() { 19274 if (isPressed() && (mParent != null) 19275 && mOriginalWindowAttachCount == mWindowAttachCount) { 19276 if (performLongClick()) { 19277 mHasPerformedLongPress = true; 19278 } 19279 } 19280 } 19281 19282 public void rememberWindowAttachCount() { 19283 mOriginalWindowAttachCount = mWindowAttachCount; 19284 } 19285 } 19286 19287 private final class CheckForTap implements Runnable { 19288 public float x; 19289 public float y; 19290 19291 @Override 19292 public void run() { 19293 mPrivateFlags &= ~PFLAG_PREPRESSED; 19294 setPressed(true, x, y); 19295 checkForLongClick(ViewConfiguration.getTapTimeout()); 19296 } 19297 } 19298 19299 private final class PerformClick implements Runnable { 19300 @Override 19301 public void run() { 19302 performClick(); 19303 } 19304 } 19305 19306 /** @hide */ 19307 public void hackTurnOffWindowResizeAnim(boolean off) { 19308 mAttachInfo.mTurnOffWindowResizeAnim = off; 19309 } 19310 19311 /** 19312 * This method returns a ViewPropertyAnimator object, which can be used to animate 19313 * specific properties on this View. 19314 * 19315 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19316 */ 19317 public ViewPropertyAnimator animate() { 19318 if (mAnimator == null) { 19319 mAnimator = new ViewPropertyAnimator(this); 19320 } 19321 return mAnimator; 19322 } 19323 19324 /** 19325 * Sets the name of the View to be used to identify Views in Transitions. 19326 * Names should be unique in the View hierarchy. 19327 * 19328 * @param viewName The name of the View to uniquely identify it for Transitions. 19329 */ 19330 public final void setViewName(String viewName) { 19331 mViewName = viewName; 19332 } 19333 19334 /** 19335 * Returns the name of the View to be used to identify Views in Transitions. 19336 * Names should be unique in the View hierarchy. 19337 * 19338 * <p>This returns null if the View has not been given a name.</p> 19339 * 19340 * @return The name used of the View to be used to identify Views in Transitions or null 19341 * if no name has been given. 19342 */ 19343 public String getViewName() { 19344 return mViewName; 19345 } 19346 19347 /** 19348 * Interface definition for a callback to be invoked when a hardware key event is 19349 * dispatched to this view. The callback will be invoked before the key event is 19350 * given to the view. This is only useful for hardware keyboards; a software input 19351 * method has no obligation to trigger this listener. 19352 */ 19353 public interface OnKeyListener { 19354 /** 19355 * Called when a hardware key is dispatched to a view. This allows listeners to 19356 * get a chance to respond before the target view. 19357 * <p>Key presses in software keyboards will generally NOT trigger this method, 19358 * although some may elect to do so in some situations. Do not assume a 19359 * software input method has to be key-based; even if it is, it may use key presses 19360 * in a different way than you expect, so there is no way to reliably catch soft 19361 * input key presses. 19362 * 19363 * @param v The view the key has been dispatched to. 19364 * @param keyCode The code for the physical key that was pressed 19365 * @param event The KeyEvent object containing full information about 19366 * the event. 19367 * @return True if the listener has consumed the event, false otherwise. 19368 */ 19369 boolean onKey(View v, int keyCode, KeyEvent event); 19370 } 19371 19372 /** 19373 * Interface definition for a callback to be invoked when a touch event is 19374 * dispatched to this view. The callback will be invoked before the touch 19375 * event is given to the view. 19376 */ 19377 public interface OnTouchListener { 19378 /** 19379 * Called when a touch event is dispatched to a view. This allows listeners to 19380 * get a chance to respond before the target view. 19381 * 19382 * @param v The view the touch event has been dispatched to. 19383 * @param event The MotionEvent object containing full information about 19384 * the event. 19385 * @return True if the listener has consumed the event, false otherwise. 19386 */ 19387 boolean onTouch(View v, MotionEvent event); 19388 } 19389 19390 /** 19391 * Interface definition for a callback to be invoked when a hover event is 19392 * dispatched to this view. The callback will be invoked before the hover 19393 * event is given to the view. 19394 */ 19395 public interface OnHoverListener { 19396 /** 19397 * Called when a hover event is dispatched to a view. This allows listeners to 19398 * get a chance to respond before the target view. 19399 * 19400 * @param v The view the hover event has been dispatched to. 19401 * @param event The MotionEvent object containing full information about 19402 * the event. 19403 * @return True if the listener has consumed the event, false otherwise. 19404 */ 19405 boolean onHover(View v, MotionEvent event); 19406 } 19407 19408 /** 19409 * Interface definition for a callback to be invoked when a generic motion event is 19410 * dispatched to this view. The callback will be invoked before the generic motion 19411 * event is given to the view. 19412 */ 19413 public interface OnGenericMotionListener { 19414 /** 19415 * Called when a generic motion event is dispatched to a view. This allows listeners to 19416 * get a chance to respond before the target view. 19417 * 19418 * @param v The view the generic motion event has been dispatched to. 19419 * @param event The MotionEvent object containing full information about 19420 * the event. 19421 * @return True if the listener has consumed the event, false otherwise. 19422 */ 19423 boolean onGenericMotion(View v, MotionEvent event); 19424 } 19425 19426 /** 19427 * Interface definition for a callback to be invoked when a view has been clicked and held. 19428 */ 19429 public interface OnLongClickListener { 19430 /** 19431 * Called when a view has been clicked and held. 19432 * 19433 * @param v The view that was clicked and held. 19434 * 19435 * @return true if the callback consumed the long click, false otherwise. 19436 */ 19437 boolean onLongClick(View v); 19438 } 19439 19440 /** 19441 * Interface definition for a callback to be invoked when a drag is being dispatched 19442 * to this view. The callback will be invoked before the hosting view's own 19443 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19444 * onDrag(event) behavior, it should return 'false' from this callback. 19445 * 19446 * <div class="special reference"> 19447 * <h3>Developer Guides</h3> 19448 * <p>For a guide to implementing drag and drop features, read the 19449 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19450 * </div> 19451 */ 19452 public interface OnDragListener { 19453 /** 19454 * Called when a drag event is dispatched to a view. This allows listeners 19455 * to get a chance to override base View behavior. 19456 * 19457 * @param v The View that received the drag event. 19458 * @param event The {@link android.view.DragEvent} object for the drag event. 19459 * @return {@code true} if the drag event was handled successfully, or {@code false} 19460 * if the drag event was not handled. Note that {@code false} will trigger the View 19461 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19462 */ 19463 boolean onDrag(View v, DragEvent event); 19464 } 19465 19466 /** 19467 * Interface definition for a callback to be invoked when the focus state of 19468 * a view changed. 19469 */ 19470 public interface OnFocusChangeListener { 19471 /** 19472 * Called when the focus state of a view has changed. 19473 * 19474 * @param v The view whose state has changed. 19475 * @param hasFocus The new focus state of v. 19476 */ 19477 void onFocusChange(View v, boolean hasFocus); 19478 } 19479 19480 /** 19481 * Interface definition for a callback to be invoked when a view is clicked. 19482 */ 19483 public interface OnClickListener { 19484 /** 19485 * Called when a view has been clicked. 19486 * 19487 * @param v The view that was clicked. 19488 */ 19489 void onClick(View v); 19490 } 19491 19492 /** 19493 * Interface definition for a callback to be invoked when the context menu 19494 * for this view is being built. 19495 */ 19496 public interface OnCreateContextMenuListener { 19497 /** 19498 * Called when the context menu for this view is being built. It is not 19499 * safe to hold onto the menu after this method returns. 19500 * 19501 * @param menu The context menu that is being built 19502 * @param v The view for which the context menu is being built 19503 * @param menuInfo Extra information about the item for which the 19504 * context menu should be shown. This information will vary 19505 * depending on the class of v. 19506 */ 19507 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19508 } 19509 19510 /** 19511 * Interface definition for a callback to be invoked when the status bar changes 19512 * visibility. This reports <strong>global</strong> changes to the system UI 19513 * state, not what the application is requesting. 19514 * 19515 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19516 */ 19517 public interface OnSystemUiVisibilityChangeListener { 19518 /** 19519 * Called when the status bar changes visibility because of a call to 19520 * {@link View#setSystemUiVisibility(int)}. 19521 * 19522 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19523 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19524 * This tells you the <strong>global</strong> state of these UI visibility 19525 * flags, not what your app is currently applying. 19526 */ 19527 public void onSystemUiVisibilityChange(int visibility); 19528 } 19529 19530 /** 19531 * Interface definition for a callback to be invoked when this view is attached 19532 * or detached from its window. 19533 */ 19534 public interface OnAttachStateChangeListener { 19535 /** 19536 * Called when the view is attached to a window. 19537 * @param v The view that was attached 19538 */ 19539 public void onViewAttachedToWindow(View v); 19540 /** 19541 * Called when the view is detached from a window. 19542 * @param v The view that was detached 19543 */ 19544 public void onViewDetachedFromWindow(View v); 19545 } 19546 19547 /** 19548 * Listener for applying window insets on a view in a custom way. 19549 * 19550 * <p>Apps may choose to implement this interface if they want to apply custom policy 19551 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19552 * is set, its 19553 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19554 * method will be called instead of the View's own 19555 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19556 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19557 * the View's normal behavior as part of its own.</p> 19558 */ 19559 public interface OnApplyWindowInsetsListener { 19560 /** 19561 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19562 * on a View, this listener method will be called instead of the view's own 19563 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19564 * 19565 * @param v The view applying window insets 19566 * @param insets The insets to apply 19567 * @return The insets supplied, minus any insets that were consumed 19568 */ 19569 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19570 } 19571 19572 private final class UnsetPressedState implements Runnable { 19573 @Override 19574 public void run() { 19575 setPressed(false); 19576 } 19577 } 19578 19579 /** 19580 * Base class for derived classes that want to save and restore their own 19581 * state in {@link android.view.View#onSaveInstanceState()}. 19582 */ 19583 public static class BaseSavedState extends AbsSavedState { 19584 /** 19585 * Constructor used when reading from a parcel. Reads the state of the superclass. 19586 * 19587 * @param source 19588 */ 19589 public BaseSavedState(Parcel source) { 19590 super(source); 19591 } 19592 19593 /** 19594 * Constructor called by derived classes when creating their SavedState objects 19595 * 19596 * @param superState The state of the superclass of this view 19597 */ 19598 public BaseSavedState(Parcelable superState) { 19599 super(superState); 19600 } 19601 19602 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19603 new Parcelable.Creator<BaseSavedState>() { 19604 public BaseSavedState createFromParcel(Parcel in) { 19605 return new BaseSavedState(in); 19606 } 19607 19608 public BaseSavedState[] newArray(int size) { 19609 return new BaseSavedState[size]; 19610 } 19611 }; 19612 } 19613 19614 /** 19615 * A set of information given to a view when it is attached to its parent 19616 * window. 19617 */ 19618 final static class AttachInfo { 19619 interface Callbacks { 19620 void playSoundEffect(int effectId); 19621 boolean performHapticFeedback(int effectId, boolean always); 19622 } 19623 19624 /** 19625 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19626 * to a Handler. This class contains the target (View) to invalidate and 19627 * the coordinates of the dirty rectangle. 19628 * 19629 * For performance purposes, this class also implements a pool of up to 19630 * POOL_LIMIT objects that get reused. This reduces memory allocations 19631 * whenever possible. 19632 */ 19633 static class InvalidateInfo { 19634 private static final int POOL_LIMIT = 10; 19635 19636 private static final SynchronizedPool<InvalidateInfo> sPool = 19637 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19638 19639 View target; 19640 19641 int left; 19642 int top; 19643 int right; 19644 int bottom; 19645 19646 public static InvalidateInfo obtain() { 19647 InvalidateInfo instance = sPool.acquire(); 19648 return (instance != null) ? instance : new InvalidateInfo(); 19649 } 19650 19651 public void recycle() { 19652 target = null; 19653 sPool.release(this); 19654 } 19655 } 19656 19657 final IWindowSession mSession; 19658 19659 final IWindow mWindow; 19660 19661 final IBinder mWindowToken; 19662 19663 final Display mDisplay; 19664 19665 final Callbacks mRootCallbacks; 19666 19667 IWindowId mIWindowId; 19668 WindowId mWindowId; 19669 19670 /** 19671 * The top view of the hierarchy. 19672 */ 19673 View mRootView; 19674 19675 IBinder mPanelParentWindowToken; 19676 19677 boolean mHardwareAccelerated; 19678 boolean mHardwareAccelerationRequested; 19679 HardwareRenderer mHardwareRenderer; 19680 19681 /** 19682 * The state of the display to which the window is attached, as reported 19683 * by {@link Display#getState()}. Note that the display state constants 19684 * declared by {@link Display} do not exactly line up with the screen state 19685 * constants declared by {@link View} (there are more display states than 19686 * screen states). 19687 */ 19688 int mDisplayState = Display.STATE_UNKNOWN; 19689 19690 /** 19691 * Scale factor used by the compatibility mode 19692 */ 19693 float mApplicationScale; 19694 19695 /** 19696 * Indicates whether the application is in compatibility mode 19697 */ 19698 boolean mScalingRequired; 19699 19700 /** 19701 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19702 */ 19703 boolean mTurnOffWindowResizeAnim; 19704 19705 /** 19706 * Left position of this view's window 19707 */ 19708 int mWindowLeft; 19709 19710 /** 19711 * Top position of this view's window 19712 */ 19713 int mWindowTop; 19714 19715 /** 19716 * Indicates whether views need to use 32-bit drawing caches 19717 */ 19718 boolean mUse32BitDrawingCache; 19719 19720 /** 19721 * For windows that are full-screen but using insets to layout inside 19722 * of the screen areas, these are the current insets to appear inside 19723 * the overscan area of the display. 19724 */ 19725 final Rect mOverscanInsets = new Rect(); 19726 19727 /** 19728 * For windows that are full-screen but using insets to layout inside 19729 * of the screen decorations, these are the current insets for the 19730 * content of the window. 19731 */ 19732 final Rect mContentInsets = new Rect(); 19733 19734 /** 19735 * For windows that are full-screen but using insets to layout inside 19736 * of the screen decorations, these are the current insets for the 19737 * actual visible parts of the window. 19738 */ 19739 final Rect mVisibleInsets = new Rect(); 19740 19741 /** 19742 * The internal insets given by this window. This value is 19743 * supplied by the client (through 19744 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19745 * be given to the window manager when changed to be used in laying 19746 * out windows behind it. 19747 */ 19748 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19749 = new ViewTreeObserver.InternalInsetsInfo(); 19750 19751 /** 19752 * Set to true when mGivenInternalInsets is non-empty. 19753 */ 19754 boolean mHasNonEmptyGivenInternalInsets; 19755 19756 /** 19757 * All views in the window's hierarchy that serve as scroll containers, 19758 * used to determine if the window can be resized or must be panned 19759 * to adjust for a soft input area. 19760 */ 19761 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19762 19763 final KeyEvent.DispatcherState mKeyDispatchState 19764 = new KeyEvent.DispatcherState(); 19765 19766 /** 19767 * Indicates whether the view's window currently has the focus. 19768 */ 19769 boolean mHasWindowFocus; 19770 19771 /** 19772 * The current visibility of the window. 19773 */ 19774 int mWindowVisibility; 19775 19776 /** 19777 * Indicates the time at which drawing started to occur. 19778 */ 19779 long mDrawingTime; 19780 19781 /** 19782 * Indicates whether or not ignoring the DIRTY_MASK flags. 19783 */ 19784 boolean mIgnoreDirtyState; 19785 19786 /** 19787 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19788 * to avoid clearing that flag prematurely. 19789 */ 19790 boolean mSetIgnoreDirtyState = false; 19791 19792 /** 19793 * Indicates whether the view's window is currently in touch mode. 19794 */ 19795 boolean mInTouchMode; 19796 19797 /** 19798 * Indicates whether the view has requested unbuffered input dispatching for the current 19799 * event stream. 19800 */ 19801 boolean mUnbufferedDispatchRequested; 19802 19803 /** 19804 * Indicates that ViewAncestor should trigger a global layout change 19805 * the next time it performs a traversal 19806 */ 19807 boolean mRecomputeGlobalAttributes; 19808 19809 /** 19810 * Always report new attributes at next traversal. 19811 */ 19812 boolean mForceReportNewAttributes; 19813 19814 /** 19815 * Set during a traveral if any views want to keep the screen on. 19816 */ 19817 boolean mKeepScreenOn; 19818 19819 /** 19820 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19821 */ 19822 int mSystemUiVisibility; 19823 19824 /** 19825 * Hack to force certain system UI visibility flags to be cleared. 19826 */ 19827 int mDisabledSystemUiVisibility; 19828 19829 /** 19830 * Last global system UI visibility reported by the window manager. 19831 */ 19832 int mGlobalSystemUiVisibility; 19833 19834 /** 19835 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19836 * attached. 19837 */ 19838 boolean mHasSystemUiListeners; 19839 19840 /** 19841 * Set if the window has requested to extend into the overscan region 19842 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19843 */ 19844 boolean mOverscanRequested; 19845 19846 /** 19847 * Set if the visibility of any views has changed. 19848 */ 19849 boolean mViewVisibilityChanged; 19850 19851 /** 19852 * Set to true if a view has been scrolled. 19853 */ 19854 boolean mViewScrollChanged; 19855 19856 /** 19857 * Global to the view hierarchy used as a temporary for dealing with 19858 * x/y points in the transparent region computations. 19859 */ 19860 final int[] mTransparentLocation = new int[2]; 19861 19862 /** 19863 * Global to the view hierarchy used as a temporary for dealing with 19864 * x/y points in the ViewGroup.invalidateChild implementation. 19865 */ 19866 final int[] mInvalidateChildLocation = new int[2]; 19867 19868 /** 19869 * Global to the view hierarchy used as a temporary for dealng with 19870 * computing absolute on-screen location. 19871 */ 19872 final int[] mTmpLocation = new int[2]; 19873 19874 /** 19875 * Global to the view hierarchy used as a temporary for dealing with 19876 * x/y location when view is transformed. 19877 */ 19878 final float[] mTmpTransformLocation = new float[2]; 19879 19880 /** 19881 * The view tree observer used to dispatch global events like 19882 * layout, pre-draw, touch mode change, etc. 19883 */ 19884 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19885 19886 /** 19887 * A Canvas used by the view hierarchy to perform bitmap caching. 19888 */ 19889 Canvas mCanvas; 19890 19891 /** 19892 * The view root impl. 19893 */ 19894 final ViewRootImpl mViewRootImpl; 19895 19896 /** 19897 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19898 * handler can be used to pump events in the UI events queue. 19899 */ 19900 final Handler mHandler; 19901 19902 /** 19903 * Temporary for use in computing invalidate rectangles while 19904 * calling up the hierarchy. 19905 */ 19906 final Rect mTmpInvalRect = new Rect(); 19907 19908 /** 19909 * Temporary for use in computing hit areas with transformed views 19910 */ 19911 final RectF mTmpTransformRect = new RectF(); 19912 19913 /** 19914 * Temporary for use in transforming invalidation rect 19915 */ 19916 final Matrix mTmpMatrix = new Matrix(); 19917 19918 /** 19919 * Temporary for use in transforming invalidation rect 19920 */ 19921 final Transformation mTmpTransformation = new Transformation(); 19922 19923 /** 19924 * Temporary list for use in collecting focusable descendents of a view. 19925 */ 19926 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19927 19928 /** 19929 * The id of the window for accessibility purposes. 19930 */ 19931 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 19932 19933 /** 19934 * Flags related to accessibility processing. 19935 * 19936 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 19937 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 19938 */ 19939 int mAccessibilityFetchFlags; 19940 19941 /** 19942 * The drawable for highlighting accessibility focus. 19943 */ 19944 Drawable mAccessibilityFocusDrawable; 19945 19946 /** 19947 * Show where the margins, bounds and layout bounds are for each view. 19948 */ 19949 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 19950 19951 /** 19952 * Point used to compute visible regions. 19953 */ 19954 final Point mPoint = new Point(); 19955 19956 /** 19957 * Used to track which View originated a requestLayout() call, used when 19958 * requestLayout() is called during layout. 19959 */ 19960 View mViewRequestingLayout; 19961 19962 /** 19963 * Creates a new set of attachment information with the specified 19964 * events handler and thread. 19965 * 19966 * @param handler the events handler the view must use 19967 */ 19968 AttachInfo(IWindowSession session, IWindow window, Display display, 19969 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 19970 mSession = session; 19971 mWindow = window; 19972 mWindowToken = window.asBinder(); 19973 mDisplay = display; 19974 mViewRootImpl = viewRootImpl; 19975 mHandler = handler; 19976 mRootCallbacks = effectPlayer; 19977 } 19978 } 19979 19980 /** 19981 * <p>ScrollabilityCache holds various fields used by a View when scrolling 19982 * is supported. This avoids keeping too many unused fields in most 19983 * instances of View.</p> 19984 */ 19985 private static class ScrollabilityCache implements Runnable { 19986 19987 /** 19988 * Scrollbars are not visible 19989 */ 19990 public static final int OFF = 0; 19991 19992 /** 19993 * Scrollbars are visible 19994 */ 19995 public static final int ON = 1; 19996 19997 /** 19998 * Scrollbars are fading away 19999 */ 20000 public static final int FADING = 2; 20001 20002 public boolean fadeScrollBars; 20003 20004 public int fadingEdgeLength; 20005 public int scrollBarDefaultDelayBeforeFade; 20006 public int scrollBarFadeDuration; 20007 20008 public int scrollBarSize; 20009 public ScrollBarDrawable scrollBar; 20010 public float[] interpolatorValues; 20011 public View host; 20012 20013 public final Paint paint; 20014 public final Matrix matrix; 20015 public Shader shader; 20016 20017 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 20018 20019 private static final float[] OPAQUE = { 255 }; 20020 private static final float[] TRANSPARENT = { 0.0f }; 20021 20022 /** 20023 * When fading should start. This time moves into the future every time 20024 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20025 */ 20026 public long fadeStartTime; 20027 20028 20029 /** 20030 * The current state of the scrollbars: ON, OFF, or FADING 20031 */ 20032 public int state = OFF; 20033 20034 private int mLastColor; 20035 20036 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20037 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20038 scrollBarSize = configuration.getScaledScrollBarSize(); 20039 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20040 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20041 20042 paint = new Paint(); 20043 matrix = new Matrix(); 20044 // use use a height of 1, and then wack the matrix each time we 20045 // actually use it. 20046 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20047 paint.setShader(shader); 20048 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20049 20050 this.host = host; 20051 } 20052 20053 public void setFadeColor(int color) { 20054 if (color != mLastColor) { 20055 mLastColor = color; 20056 20057 if (color != 0) { 20058 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20059 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20060 paint.setShader(shader); 20061 // Restore the default transfer mode (src_over) 20062 paint.setXfermode(null); 20063 } else { 20064 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20065 paint.setShader(shader); 20066 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20067 } 20068 } 20069 } 20070 20071 public void run() { 20072 long now = AnimationUtils.currentAnimationTimeMillis(); 20073 if (now >= fadeStartTime) { 20074 20075 // the animation fades the scrollbars out by changing 20076 // the opacity (alpha) from fully opaque to fully 20077 // transparent 20078 int nextFrame = (int) now; 20079 int framesCount = 0; 20080 20081 Interpolator interpolator = scrollBarInterpolator; 20082 20083 // Start opaque 20084 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20085 20086 // End transparent 20087 nextFrame += scrollBarFadeDuration; 20088 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20089 20090 state = FADING; 20091 20092 // Kick off the fade animation 20093 host.invalidate(true); 20094 } 20095 } 20096 } 20097 20098 /** 20099 * Resuable callback for sending 20100 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20101 */ 20102 private class SendViewScrolledAccessibilityEvent implements Runnable { 20103 public volatile boolean mIsPending; 20104 20105 public void run() { 20106 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20107 mIsPending = false; 20108 } 20109 } 20110 20111 /** 20112 * <p> 20113 * This class represents a delegate that can be registered in a {@link View} 20114 * to enhance accessibility support via composition rather via inheritance. 20115 * It is specifically targeted to widget developers that extend basic View 20116 * classes i.e. classes in package android.view, that would like their 20117 * applications to be backwards compatible. 20118 * </p> 20119 * <div class="special reference"> 20120 * <h3>Developer Guides</h3> 20121 * <p>For more information about making applications accessible, read the 20122 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20123 * developer guide.</p> 20124 * </div> 20125 * <p> 20126 * A scenario in which a developer would like to use an accessibility delegate 20127 * is overriding a method introduced in a later API version then the minimal API 20128 * version supported by the application. For example, the method 20129 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20130 * in API version 4 when the accessibility APIs were first introduced. If a 20131 * developer would like his application to run on API version 4 devices (assuming 20132 * all other APIs used by the application are version 4 or lower) and take advantage 20133 * of this method, instead of overriding the method which would break the application's 20134 * backwards compatibility, he can override the corresponding method in this 20135 * delegate and register the delegate in the target View if the API version of 20136 * the system is high enough i.e. the API version is same or higher to the API 20137 * version that introduced 20138 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20139 * </p> 20140 * <p> 20141 * Here is an example implementation: 20142 * </p> 20143 * <code><pre><p> 20144 * if (Build.VERSION.SDK_INT >= 14) { 20145 * // If the API version is equal of higher than the version in 20146 * // which onInitializeAccessibilityNodeInfo was introduced we 20147 * // register a delegate with a customized implementation. 20148 * View view = findViewById(R.id.view_id); 20149 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20150 * public void onInitializeAccessibilityNodeInfo(View host, 20151 * AccessibilityNodeInfo info) { 20152 * // Let the default implementation populate the info. 20153 * super.onInitializeAccessibilityNodeInfo(host, info); 20154 * // Set some other information. 20155 * info.setEnabled(host.isEnabled()); 20156 * } 20157 * }); 20158 * } 20159 * </code></pre></p> 20160 * <p> 20161 * This delegate contains methods that correspond to the accessibility methods 20162 * in View. If a delegate has been specified the implementation in View hands 20163 * off handling to the corresponding method in this delegate. The default 20164 * implementation the delegate methods behaves exactly as the corresponding 20165 * method in View for the case of no accessibility delegate been set. Hence, 20166 * to customize the behavior of a View method, clients can override only the 20167 * corresponding delegate method without altering the behavior of the rest 20168 * accessibility related methods of the host view. 20169 * </p> 20170 */ 20171 public static class AccessibilityDelegate { 20172 20173 /** 20174 * Sends an accessibility event of the given type. If accessibility is not 20175 * enabled this method has no effect. 20176 * <p> 20177 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20178 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20179 * been set. 20180 * </p> 20181 * 20182 * @param host The View hosting the delegate. 20183 * @param eventType The type of the event to send. 20184 * 20185 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20186 */ 20187 public void sendAccessibilityEvent(View host, int eventType) { 20188 host.sendAccessibilityEventInternal(eventType); 20189 } 20190 20191 /** 20192 * Performs the specified accessibility action on the view. For 20193 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20194 * <p> 20195 * The default implementation behaves as 20196 * {@link View#performAccessibilityAction(int, Bundle) 20197 * View#performAccessibilityAction(int, Bundle)} for the case of 20198 * no accessibility delegate been set. 20199 * </p> 20200 * 20201 * @param action The action to perform. 20202 * @return Whether the action was performed. 20203 * 20204 * @see View#performAccessibilityAction(int, Bundle) 20205 * View#performAccessibilityAction(int, Bundle) 20206 */ 20207 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20208 return host.performAccessibilityActionInternal(action, args); 20209 } 20210 20211 /** 20212 * Sends an accessibility event. This method behaves exactly as 20213 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20214 * empty {@link AccessibilityEvent} and does not perform a check whether 20215 * accessibility is enabled. 20216 * <p> 20217 * The default implementation behaves as 20218 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20219 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20220 * the case of no accessibility delegate been set. 20221 * </p> 20222 * 20223 * @param host The View hosting the delegate. 20224 * @param event The event to send. 20225 * 20226 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20227 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20228 */ 20229 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20230 host.sendAccessibilityEventUncheckedInternal(event); 20231 } 20232 20233 /** 20234 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20235 * to its children for adding their text content to the event. 20236 * <p> 20237 * The default implementation behaves as 20238 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20239 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20240 * the case of no accessibility delegate been set. 20241 * </p> 20242 * 20243 * @param host The View hosting the delegate. 20244 * @param event The event. 20245 * @return True if the event population was completed. 20246 * 20247 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20248 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20249 */ 20250 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20251 return host.dispatchPopulateAccessibilityEventInternal(event); 20252 } 20253 20254 /** 20255 * Gives a chance to the host View to populate the accessibility event with its 20256 * text content. 20257 * <p> 20258 * The default implementation behaves as 20259 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20260 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20261 * the case of no accessibility delegate been set. 20262 * </p> 20263 * 20264 * @param host The View hosting the delegate. 20265 * @param event The accessibility event which to populate. 20266 * 20267 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20268 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20269 */ 20270 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20271 host.onPopulateAccessibilityEventInternal(event); 20272 } 20273 20274 /** 20275 * Initializes an {@link AccessibilityEvent} with information about the 20276 * the host View which is the event source. 20277 * <p> 20278 * The default implementation behaves as 20279 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20280 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20281 * the case of no accessibility delegate been set. 20282 * </p> 20283 * 20284 * @param host The View hosting the delegate. 20285 * @param event The event to initialize. 20286 * 20287 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20288 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20289 */ 20290 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20291 host.onInitializeAccessibilityEventInternal(event); 20292 } 20293 20294 /** 20295 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20296 * <p> 20297 * The default implementation behaves as 20298 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20299 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20300 * the case of no accessibility delegate been set. 20301 * </p> 20302 * 20303 * @param host The View hosting the delegate. 20304 * @param info The instance to initialize. 20305 * 20306 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20307 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20308 */ 20309 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20310 host.onInitializeAccessibilityNodeInfoInternal(info); 20311 } 20312 20313 /** 20314 * Called when a child of the host View has requested sending an 20315 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20316 * to augment the event. 20317 * <p> 20318 * The default implementation behaves as 20319 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20320 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20321 * the case of no accessibility delegate been set. 20322 * </p> 20323 * 20324 * @param host The View hosting the delegate. 20325 * @param child The child which requests sending the event. 20326 * @param event The event to be sent. 20327 * @return True if the event should be sent 20328 * 20329 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20330 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20331 */ 20332 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20333 AccessibilityEvent event) { 20334 return host.onRequestSendAccessibilityEventInternal(child, event); 20335 } 20336 20337 /** 20338 * Gets the provider for managing a virtual view hierarchy rooted at this View 20339 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20340 * that explore the window content. 20341 * <p> 20342 * The default implementation behaves as 20343 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20344 * the case of no accessibility delegate been set. 20345 * </p> 20346 * 20347 * @return The provider. 20348 * 20349 * @see AccessibilityNodeProvider 20350 */ 20351 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20352 return null; 20353 } 20354 20355 /** 20356 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20357 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20358 * This method is responsible for obtaining an accessibility node info from a 20359 * pool of reusable instances and calling 20360 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20361 * view to initialize the former. 20362 * <p> 20363 * <strong>Note:</strong> The client is responsible for recycling the obtained 20364 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20365 * creation. 20366 * </p> 20367 * <p> 20368 * The default implementation behaves as 20369 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20370 * the case of no accessibility delegate been set. 20371 * </p> 20372 * @return A populated {@link AccessibilityNodeInfo}. 20373 * 20374 * @see AccessibilityNodeInfo 20375 * 20376 * @hide 20377 */ 20378 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20379 return host.createAccessibilityNodeInfoInternal(); 20380 } 20381 } 20382 20383 private class MatchIdPredicate implements Predicate<View> { 20384 public int mId; 20385 20386 @Override 20387 public boolean apply(View view) { 20388 return (view.mID == mId); 20389 } 20390 } 20391 20392 private class MatchLabelForPredicate implements Predicate<View> { 20393 private int mLabeledId; 20394 20395 @Override 20396 public boolean apply(View view) { 20397 return (view.mLabelForId == mLabeledId); 20398 } 20399 } 20400 20401 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20402 private int mChangeTypes = 0; 20403 private boolean mPosted; 20404 private boolean mPostedWithDelay; 20405 private long mLastEventTimeMillis; 20406 20407 @Override 20408 public void run() { 20409 mPosted = false; 20410 mPostedWithDelay = false; 20411 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20412 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20413 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20414 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20415 event.setContentChangeTypes(mChangeTypes); 20416 sendAccessibilityEventUnchecked(event); 20417 } 20418 mChangeTypes = 0; 20419 } 20420 20421 public void runOrPost(int changeType) { 20422 mChangeTypes |= changeType; 20423 20424 // If this is a live region or the child of a live region, collect 20425 // all events from this frame and send them on the next frame. 20426 if (inLiveRegion()) { 20427 // If we're already posted with a delay, remove that. 20428 if (mPostedWithDelay) { 20429 removeCallbacks(this); 20430 mPostedWithDelay = false; 20431 } 20432 // Only post if we're not already posted. 20433 if (!mPosted) { 20434 post(this); 20435 mPosted = true; 20436 } 20437 return; 20438 } 20439 20440 if (mPosted) { 20441 return; 20442 } 20443 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20444 final long minEventIntevalMillis = 20445 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20446 if (timeSinceLastMillis >= minEventIntevalMillis) { 20447 removeCallbacks(this); 20448 run(); 20449 } else { 20450 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20451 mPosted = true; 20452 mPostedWithDelay = true; 20453 } 20454 } 20455 } 20456 20457 private boolean inLiveRegion() { 20458 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20459 return true; 20460 } 20461 20462 ViewParent parent = getParent(); 20463 while (parent instanceof View) { 20464 if (((View) parent).getAccessibilityLiveRegion() 20465 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20466 return true; 20467 } 20468 parent = parent.getParent(); 20469 } 20470 20471 return false; 20472 } 20473 20474 /** 20475 * Dump all private flags in readable format, useful for documentation and 20476 * sanity checking. 20477 */ 20478 private static void dumpFlags() { 20479 final HashMap<String, String> found = Maps.newHashMap(); 20480 try { 20481 for (Field field : View.class.getDeclaredFields()) { 20482 final int modifiers = field.getModifiers(); 20483 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20484 if (field.getType().equals(int.class)) { 20485 final int value = field.getInt(null); 20486 dumpFlag(found, field.getName(), value); 20487 } else if (field.getType().equals(int[].class)) { 20488 final int[] values = (int[]) field.get(null); 20489 for (int i = 0; i < values.length; i++) { 20490 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20491 } 20492 } 20493 } 20494 } 20495 } catch (IllegalAccessException e) { 20496 throw new RuntimeException(e); 20497 } 20498 20499 final ArrayList<String> keys = Lists.newArrayList(); 20500 keys.addAll(found.keySet()); 20501 Collections.sort(keys); 20502 for (String key : keys) { 20503 Log.d(VIEW_LOG_TAG, found.get(key)); 20504 } 20505 } 20506 20507 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20508 // Sort flags by prefix, then by bits, always keeping unique keys 20509 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20510 final int prefix = name.indexOf('_'); 20511 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20512 final String output = bits + " " + name; 20513 found.put(key, output); 20514 } 20515} 20516