View.java revision 05ee2bd617f50fe129cf36ae306e6059335e02aa
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.RevealAnimator; 20import android.animation.ValueAnimator; 21import android.annotation.IntDef; 22import android.annotation.NonNull; 23import android.annotation.Nullable; 24import android.content.ClipData; 25import android.content.Context; 26import android.content.res.Configuration; 27import android.content.res.Resources; 28import android.content.res.TypedArray; 29import android.graphics.Bitmap; 30import android.graphics.Canvas; 31import android.graphics.Insets; 32import android.graphics.Interpolator; 33import android.graphics.LinearGradient; 34import android.graphics.Matrix; 35import android.graphics.Outline; 36import android.graphics.Paint; 37import android.graphics.PixelFormat; 38import android.graphics.Point; 39import android.graphics.PorterDuff; 40import android.graphics.PorterDuffXfermode; 41import android.graphics.Rect; 42import android.graphics.RectF; 43import android.graphics.Region; 44import android.graphics.Shader; 45import android.graphics.drawable.ColorDrawable; 46import android.graphics.drawable.Drawable; 47import android.hardware.display.DisplayManagerGlobal; 48import android.os.Bundle; 49import android.os.Handler; 50import android.os.IBinder; 51import android.os.Parcel; 52import android.os.Parcelable; 53import android.os.RemoteException; 54import android.os.SystemClock; 55import android.os.SystemProperties; 56import android.text.TextUtils; 57import android.util.AttributeSet; 58import android.util.FloatProperty; 59import android.util.LayoutDirection; 60import android.util.Log; 61import android.util.LongSparseLongArray; 62import android.util.Pools.SynchronizedPool; 63import android.util.Property; 64import android.util.SparseArray; 65import android.util.SuperNotCalledException; 66import android.util.TypedValue; 67import android.view.ContextMenu.ContextMenuInfo; 68import android.view.AccessibilityIterators.TextSegmentIterator; 69import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 70import android.view.AccessibilityIterators.WordTextSegmentIterator; 71import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 72import android.view.accessibility.AccessibilityEvent; 73import android.view.accessibility.AccessibilityEventSource; 74import android.view.accessibility.AccessibilityManager; 75import android.view.accessibility.AccessibilityNodeInfo; 76import android.view.accessibility.AccessibilityNodeProvider; 77import android.view.animation.Animation; 78import android.view.animation.AnimationUtils; 79import android.view.animation.Transformation; 80import android.view.inputmethod.EditorInfo; 81import android.view.inputmethod.InputConnection; 82import android.view.inputmethod.InputMethodManager; 83import android.widget.ScrollBarDrawable; 84 85import static android.os.Build.VERSION_CODES.*; 86import static java.lang.Math.max; 87 88import com.android.internal.R; 89import com.android.internal.util.Predicate; 90import com.android.internal.view.menu.MenuBuilder; 91import com.google.android.collect.Lists; 92import com.google.android.collect.Maps; 93 94import java.lang.annotation.Retention; 95import java.lang.annotation.RetentionPolicy; 96import java.lang.ref.WeakReference; 97import java.lang.reflect.Field; 98import java.lang.reflect.InvocationTargetException; 99import java.lang.reflect.Method; 100import java.lang.reflect.Modifier; 101import java.util.ArrayList; 102import java.util.Arrays; 103import java.util.Collections; 104import java.util.HashMap; 105import java.util.List; 106import java.util.Locale; 107import java.util.Map; 108import java.util.concurrent.CopyOnWriteArrayList; 109import java.util.concurrent.atomic.AtomicInteger; 110 111/** 112 * <p> 113 * This class represents the basic building block for user interface components. A View 114 * occupies a rectangular area on the screen and is responsible for drawing and 115 * event handling. View is the base class for <em>widgets</em>, which are 116 * used to create interactive UI components (buttons, text fields, etc.). The 117 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 118 * are invisible containers that hold other Views (or other ViewGroups) and define 119 * their layout properties. 120 * </p> 121 * 122 * <div class="special reference"> 123 * <h3>Developer Guides</h3> 124 * <p>For information about using this class to develop your application's user interface, 125 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 126 * </div> 127 * 128 * <a name="Using"></a> 129 * <h3>Using Views</h3> 130 * <p> 131 * All of the views in a window are arranged in a single tree. You can add views 132 * either from code or by specifying a tree of views in one or more XML layout 133 * files. There are many specialized subclasses of views that act as controls or 134 * are capable of displaying text, images, or other content. 135 * </p> 136 * <p> 137 * Once you have created a tree of views, there are typically a few types of 138 * common operations you may wish to perform: 139 * <ul> 140 * <li><strong>Set properties:</strong> for example setting the text of a 141 * {@link android.widget.TextView}. The available properties and the methods 142 * that set them will vary among the different subclasses of views. Note that 143 * properties that are known at build time can be set in the XML layout 144 * files.</li> 145 * <li><strong>Set focus:</strong> The framework will handled moving focus in 146 * response to user input. To force focus to a specific view, call 147 * {@link #requestFocus}.</li> 148 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 149 * that will be notified when something interesting happens to the view. For 150 * example, all views will let you set a listener to be notified when the view 151 * gains or loses focus. You can register such a listener using 152 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 153 * Other view subclasses offer more specialized listeners. For example, a Button 154 * exposes a listener to notify clients when the button is clicked.</li> 155 * <li><strong>Set visibility:</strong> You can hide or show views using 156 * {@link #setVisibility(int)}.</li> 157 * </ul> 158 * </p> 159 * <p><em> 160 * Note: The Android framework is responsible for measuring, laying out and 161 * drawing views. You should not call methods that perform these actions on 162 * views yourself unless you are actually implementing a 163 * {@link android.view.ViewGroup}. 164 * </em></p> 165 * 166 * <a name="Lifecycle"></a> 167 * <h3>Implementing a Custom View</h3> 168 * 169 * <p> 170 * To implement a custom view, you will usually begin by providing overrides for 171 * some of the standard methods that the framework calls on all views. You do 172 * not need to override all of these methods. In fact, you can start by just 173 * overriding {@link #onDraw(android.graphics.Canvas)}. 174 * <table border="2" width="85%" align="center" cellpadding="5"> 175 * <thead> 176 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 177 * </thead> 178 * 179 * <tbody> 180 * <tr> 181 * <td rowspan="2">Creation</td> 182 * <td>Constructors</td> 183 * <td>There is a form of the constructor that are called when the view 184 * is created from code and a form that is called when the view is 185 * inflated from a layout file. The second form should parse and apply 186 * any attributes defined in the layout file. 187 * </td> 188 * </tr> 189 * <tr> 190 * <td><code>{@link #onFinishInflate()}</code></td> 191 * <td>Called after a view and all of its children has been inflated 192 * from XML.</td> 193 * </tr> 194 * 195 * <tr> 196 * <td rowspan="3">Layout</td> 197 * <td><code>{@link #onMeasure(int, int)}</code></td> 198 * <td>Called to determine the size requirements for this view and all 199 * of its children. 200 * </td> 201 * </tr> 202 * <tr> 203 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 204 * <td>Called when this view should assign a size and position to all 205 * of its children. 206 * </td> 207 * </tr> 208 * <tr> 209 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 210 * <td>Called when the size of this view has changed. 211 * </td> 212 * </tr> 213 * 214 * <tr> 215 * <td>Drawing</td> 216 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 217 * <td>Called when the view should render its content. 218 * </td> 219 * </tr> 220 * 221 * <tr> 222 * <td rowspan="4">Event processing</td> 223 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 224 * <td>Called when a new hardware key event occurs. 225 * </td> 226 * </tr> 227 * <tr> 228 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 229 * <td>Called when a hardware key up event occurs. 230 * </td> 231 * </tr> 232 * <tr> 233 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 234 * <td>Called when a trackball motion event occurs. 235 * </td> 236 * </tr> 237 * <tr> 238 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 239 * <td>Called when a touch screen motion event occurs. 240 * </td> 241 * </tr> 242 * 243 * <tr> 244 * <td rowspan="2">Focus</td> 245 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 246 * <td>Called when the view gains or loses focus. 247 * </td> 248 * </tr> 249 * 250 * <tr> 251 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 252 * <td>Called when the window containing the view gains or loses focus. 253 * </td> 254 * </tr> 255 * 256 * <tr> 257 * <td rowspan="3">Attaching</td> 258 * <td><code>{@link #onAttachedToWindow()}</code></td> 259 * <td>Called when the view is attached to a window. 260 * </td> 261 * </tr> 262 * 263 * <tr> 264 * <td><code>{@link #onDetachedFromWindow}</code></td> 265 * <td>Called when the view is detached from its window. 266 * </td> 267 * </tr> 268 * 269 * <tr> 270 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 271 * <td>Called when the visibility of the window containing the view 272 * has changed. 273 * </td> 274 * </tr> 275 * </tbody> 276 * 277 * </table> 278 * </p> 279 * 280 * <a name="IDs"></a> 281 * <h3>IDs</h3> 282 * Views may have an integer id associated with them. These ids are typically 283 * assigned in the layout XML files, and are used to find specific views within 284 * the view tree. A common pattern is to: 285 * <ul> 286 * <li>Define a Button in the layout file and assign it a unique ID. 287 * <pre> 288 * <Button 289 * android:id="@+id/my_button" 290 * android:layout_width="wrap_content" 291 * android:layout_height="wrap_content" 292 * android:text="@string/my_button_text"/> 293 * </pre></li> 294 * <li>From the onCreate method of an Activity, find the Button 295 * <pre class="prettyprint"> 296 * Button myButton = (Button) findViewById(R.id.my_button); 297 * </pre></li> 298 * </ul> 299 * <p> 300 * View IDs need not be unique throughout the tree, but it is good practice to 301 * ensure that they are at least unique within the part of the tree you are 302 * searching. 303 * </p> 304 * 305 * <a name="Position"></a> 306 * <h3>Position</h3> 307 * <p> 308 * The geometry of a view is that of a rectangle. A view has a location, 309 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 310 * two dimensions, expressed as a width and a height. The unit for location 311 * and dimensions is the pixel. 312 * </p> 313 * 314 * <p> 315 * It is possible to retrieve the location of a view by invoking the methods 316 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 317 * coordinate of the rectangle representing the view. The latter returns the 318 * top, or Y, coordinate of the rectangle representing the view. These methods 319 * both return the location of the view relative to its parent. For instance, 320 * when getLeft() returns 20, that means the view is located 20 pixels to the 321 * right of the left edge of its direct parent. 322 * </p> 323 * 324 * <p> 325 * In addition, several convenience methods are offered to avoid unnecessary 326 * computations, namely {@link #getRight()} and {@link #getBottom()}. 327 * These methods return the coordinates of the right and bottom edges of the 328 * rectangle representing the view. For instance, calling {@link #getRight()} 329 * is similar to the following computation: <code>getLeft() + getWidth()</code> 330 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 331 * </p> 332 * 333 * <a name="SizePaddingMargins"></a> 334 * <h3>Size, padding and margins</h3> 335 * <p> 336 * The size of a view is expressed with a width and a height. A view actually 337 * possess two pairs of width and height values. 338 * </p> 339 * 340 * <p> 341 * The first pair is known as <em>measured width</em> and 342 * <em>measured height</em>. These dimensions define how big a view wants to be 343 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 344 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 345 * and {@link #getMeasuredHeight()}. 346 * </p> 347 * 348 * <p> 349 * The second pair is simply known as <em>width</em> and <em>height</em>, or 350 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 351 * dimensions define the actual size of the view on screen, at drawing time and 352 * after layout. These values may, but do not have to, be different from the 353 * measured width and height. The width and height can be obtained by calling 354 * {@link #getWidth()} and {@link #getHeight()}. 355 * </p> 356 * 357 * <p> 358 * To measure its dimensions, a view takes into account its padding. The padding 359 * is expressed in pixels for the left, top, right and bottom parts of the view. 360 * Padding can be used to offset the content of the view by a specific amount of 361 * pixels. For instance, a left padding of 2 will push the view's content by 362 * 2 pixels to the right of the left edge. Padding can be set using the 363 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 364 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 365 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 366 * {@link #getPaddingEnd()}. 367 * </p> 368 * 369 * <p> 370 * Even though a view can define a padding, it does not provide any support for 371 * margins. However, view groups provide such a support. Refer to 372 * {@link android.view.ViewGroup} and 373 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 374 * </p> 375 * 376 * <a name="Layout"></a> 377 * <h3>Layout</h3> 378 * <p> 379 * Layout is a two pass process: a measure pass and a layout pass. The measuring 380 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 381 * of the view tree. Each view pushes dimension specifications down the tree 382 * during the recursion. At the end of the measure pass, every view has stored 383 * its measurements. The second pass happens in 384 * {@link #layout(int,int,int,int)} and is also top-down. During 385 * this pass each parent is responsible for positioning all of its children 386 * using the sizes computed in the measure pass. 387 * </p> 388 * 389 * <p> 390 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 391 * {@link #getMeasuredHeight()} values must be set, along with those for all of 392 * that view's descendants. A view's measured width and measured height values 393 * must respect the constraints imposed by the view's parents. This guarantees 394 * that at the end of the measure pass, all parents accept all of their 395 * children's measurements. A parent view may call measure() more than once on 396 * its children. For example, the parent may measure each child once with 397 * unspecified dimensions to find out how big they want to be, then call 398 * measure() on them again with actual numbers if the sum of all the children's 399 * unconstrained sizes is too big or too small. 400 * </p> 401 * 402 * <p> 403 * The measure pass uses two classes to communicate dimensions. The 404 * {@link MeasureSpec} class is used by views to tell their parents how they 405 * want to be measured and positioned. The base LayoutParams class just 406 * describes how big the view wants to be for both width and height. For each 407 * dimension, it can specify one of: 408 * <ul> 409 * <li> an exact number 410 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 411 * (minus padding) 412 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 413 * enclose its content (plus padding). 414 * </ul> 415 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 416 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 417 * an X and Y value. 418 * </p> 419 * 420 * <p> 421 * MeasureSpecs are used to push requirements down the tree from parent to 422 * child. A MeasureSpec can be in one of three modes: 423 * <ul> 424 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 425 * of a child view. For example, a LinearLayout may call measure() on its child 426 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 427 * tall the child view wants to be given a width of 240 pixels. 428 * <li>EXACTLY: This is used by the parent to impose an exact size on the 429 * child. The child must use this size, and guarantee that all of its 430 * descendants will fit within this size. 431 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 432 * child. The child must gurantee that it and all of its descendants will fit 433 * within this size. 434 * </ul> 435 * </p> 436 * 437 * <p> 438 * To intiate a layout, call {@link #requestLayout}. This method is typically 439 * called by a view on itself when it believes that is can no longer fit within 440 * its current bounds. 441 * </p> 442 * 443 * <a name="Drawing"></a> 444 * <h3>Drawing</h3> 445 * <p> 446 * Drawing is handled by walking the tree and rendering each view that 447 * intersects the invalid region. Because the tree is traversed in-order, 448 * this means that parents will draw before (i.e., behind) their children, with 449 * siblings drawn in the order they appear in the tree. 450 * If you set a background drawable for a View, then the View will draw it for you 451 * before calling back to its <code>onDraw()</code> method. 452 * </p> 453 * 454 * <p> 455 * Note that the framework will not draw views that are not in the invalid region. 456 * </p> 457 * 458 * <p> 459 * To force a view to draw, call {@link #invalidate()}. 460 * </p> 461 * 462 * <a name="EventHandlingThreading"></a> 463 * <h3>Event Handling and Threading</h3> 464 * <p> 465 * The basic cycle of a view is as follows: 466 * <ol> 467 * <li>An event comes in and is dispatched to the appropriate view. The view 468 * handles the event and notifies any listeners.</li> 469 * <li>If in the course of processing the event, the view's bounds may need 470 * to be changed, the view will call {@link #requestLayout()}.</li> 471 * <li>Similarly, if in the course of processing the event the view's appearance 472 * may need to be changed, the view will call {@link #invalidate()}.</li> 473 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 474 * the framework will take care of measuring, laying out, and drawing the tree 475 * as appropriate.</li> 476 * </ol> 477 * </p> 478 * 479 * <p><em>Note: The entire view tree is single threaded. You must always be on 480 * the UI thread when calling any method on any view.</em> 481 * If you are doing work on other threads and want to update the state of a view 482 * from that thread, you should use a {@link Handler}. 483 * </p> 484 * 485 * <a name="FocusHandling"></a> 486 * <h3>Focus Handling</h3> 487 * <p> 488 * The framework will handle routine focus movement in response to user input. 489 * This includes changing the focus as views are removed or hidden, or as new 490 * views become available. Views indicate their willingness to take focus 491 * through the {@link #isFocusable} method. To change whether a view can take 492 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 493 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 494 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 495 * </p> 496 * <p> 497 * Focus movement is based on an algorithm which finds the nearest neighbor in a 498 * given direction. In rare cases, the default algorithm may not match the 499 * intended behavior of the developer. In these situations, you can provide 500 * explicit overrides by using these XML attributes in the layout file: 501 * <pre> 502 * nextFocusDown 503 * nextFocusLeft 504 * nextFocusRight 505 * nextFocusUp 506 * </pre> 507 * </p> 508 * 509 * 510 * <p> 511 * To get a particular view to take focus, call {@link #requestFocus()}. 512 * </p> 513 * 514 * <a name="TouchMode"></a> 515 * <h3>Touch Mode</h3> 516 * <p> 517 * When a user is navigating a user interface via directional keys such as a D-pad, it is 518 * necessary to give focus to actionable items such as buttons so the user can see 519 * what will take input. If the device has touch capabilities, however, and the user 520 * begins interacting with the interface by touching it, it is no longer necessary to 521 * always highlight, or give focus to, a particular view. This motivates a mode 522 * for interaction named 'touch mode'. 523 * </p> 524 * <p> 525 * For a touch capable device, once the user touches the screen, the device 526 * will enter touch mode. From this point onward, only views for which 527 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 528 * Other views that are touchable, like buttons, will not take focus when touched; they will 529 * only fire the on click listeners. 530 * </p> 531 * <p> 532 * Any time a user hits a directional key, such as a D-pad direction, the view device will 533 * exit touch mode, and find a view to take focus, so that the user may resume interacting 534 * with the user interface without touching the screen again. 535 * </p> 536 * <p> 537 * The touch mode state is maintained across {@link android.app.Activity}s. Call 538 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 539 * </p> 540 * 541 * <a name="Scrolling"></a> 542 * <h3>Scrolling</h3> 543 * <p> 544 * The framework provides basic support for views that wish to internally 545 * scroll their content. This includes keeping track of the X and Y scroll 546 * offset as well as mechanisms for drawing scrollbars. See 547 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 548 * {@link #awakenScrollBars()} for more details. 549 * </p> 550 * 551 * <a name="Tags"></a> 552 * <h3>Tags</h3> 553 * <p> 554 * Unlike IDs, tags are not used to identify views. Tags are essentially an 555 * extra piece of information that can be associated with a view. They are most 556 * often used as a convenience to store data related to views in the views 557 * themselves rather than by putting them in a separate structure. 558 * </p> 559 * 560 * <a name="Properties"></a> 561 * <h3>Properties</h3> 562 * <p> 563 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 564 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 565 * available both in the {@link Property} form as well as in similarly-named setter/getter 566 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 567 * be used to set persistent state associated with these rendering-related properties on the view. 568 * The properties and methods can also be used in conjunction with 569 * {@link android.animation.Animator Animator}-based animations, described more in the 570 * <a href="#Animation">Animation</a> section. 571 * </p> 572 * 573 * <a name="Animation"></a> 574 * <h3>Animation</h3> 575 * <p> 576 * Starting with Android 3.0, the preferred way of animating views is to use the 577 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 578 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 579 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 580 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 581 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 582 * makes animating these View properties particularly easy and efficient. 583 * </p> 584 * <p> 585 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 586 * You can attach an {@link Animation} object to a view using 587 * {@link #setAnimation(Animation)} or 588 * {@link #startAnimation(Animation)}. The animation can alter the scale, 589 * rotation, translation and alpha of a view over time. If the animation is 590 * attached to a view that has children, the animation will affect the entire 591 * subtree rooted by that node. When an animation is started, the framework will 592 * take care of redrawing the appropriate views until the animation completes. 593 * </p> 594 * 595 * <a name="Security"></a> 596 * <h3>Security</h3> 597 * <p> 598 * Sometimes it is essential that an application be able to verify that an action 599 * is being performed with the full knowledge and consent of the user, such as 600 * granting a permission request, making a purchase or clicking on an advertisement. 601 * Unfortunately, a malicious application could try to spoof the user into 602 * performing these actions, unaware, by concealing the intended purpose of the view. 603 * As a remedy, the framework offers a touch filtering mechanism that can be used to 604 * improve the security of views that provide access to sensitive functionality. 605 * </p><p> 606 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 607 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 608 * will discard touches that are received whenever the view's window is obscured by 609 * another visible window. As a result, the view will not receive touches whenever a 610 * toast, dialog or other window appears above the view's window. 611 * </p><p> 612 * For more fine-grained control over security, consider overriding the 613 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 614 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 615 * </p> 616 * 617 * @attr ref android.R.styleable#View_alpha 618 * @attr ref android.R.styleable#View_background 619 * @attr ref android.R.styleable#View_clickable 620 * @attr ref android.R.styleable#View_contentDescription 621 * @attr ref android.R.styleable#View_drawingCacheQuality 622 * @attr ref android.R.styleable#View_duplicateParentState 623 * @attr ref android.R.styleable#View_id 624 * @attr ref android.R.styleable#View_requiresFadingEdge 625 * @attr ref android.R.styleable#View_fadeScrollbars 626 * @attr ref android.R.styleable#View_fadingEdgeLength 627 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 628 * @attr ref android.R.styleable#View_fitsSystemWindows 629 * @attr ref android.R.styleable#View_isScrollContainer 630 * @attr ref android.R.styleable#View_focusable 631 * @attr ref android.R.styleable#View_focusableInTouchMode 632 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 633 * @attr ref android.R.styleable#View_keepScreenOn 634 * @attr ref android.R.styleable#View_layerType 635 * @attr ref android.R.styleable#View_layoutDirection 636 * @attr ref android.R.styleable#View_longClickable 637 * @attr ref android.R.styleable#View_minHeight 638 * @attr ref android.R.styleable#View_minWidth 639 * @attr ref android.R.styleable#View_nextFocusDown 640 * @attr ref android.R.styleable#View_nextFocusLeft 641 * @attr ref android.R.styleable#View_nextFocusRight 642 * @attr ref android.R.styleable#View_nextFocusUp 643 * @attr ref android.R.styleable#View_onClick 644 * @attr ref android.R.styleable#View_padding 645 * @attr ref android.R.styleable#View_paddingBottom 646 * @attr ref android.R.styleable#View_paddingLeft 647 * @attr ref android.R.styleable#View_paddingRight 648 * @attr ref android.R.styleable#View_paddingTop 649 * @attr ref android.R.styleable#View_paddingStart 650 * @attr ref android.R.styleable#View_paddingEnd 651 * @attr ref android.R.styleable#View_saveEnabled 652 * @attr ref android.R.styleable#View_rotation 653 * @attr ref android.R.styleable#View_rotationX 654 * @attr ref android.R.styleable#View_rotationY 655 * @attr ref android.R.styleable#View_scaleX 656 * @attr ref android.R.styleable#View_scaleY 657 * @attr ref android.R.styleable#View_scrollX 658 * @attr ref android.R.styleable#View_scrollY 659 * @attr ref android.R.styleable#View_scrollbarSize 660 * @attr ref android.R.styleable#View_scrollbarStyle 661 * @attr ref android.R.styleable#View_scrollbars 662 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 663 * @attr ref android.R.styleable#View_scrollbarFadeDuration 664 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 665 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 666 * @attr ref android.R.styleable#View_scrollbarThumbVertical 667 * @attr ref android.R.styleable#View_scrollbarTrackVertical 668 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 669 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 670 * @attr ref android.R.styleable#View_sharedElementName 671 * @attr ref android.R.styleable#View_soundEffectsEnabled 672 * @attr ref android.R.styleable#View_tag 673 * @attr ref android.R.styleable#View_textAlignment 674 * @attr ref android.R.styleable#View_textDirection 675 * @attr ref android.R.styleable#View_transformPivotX 676 * @attr ref android.R.styleable#View_transformPivotY 677 * @attr ref android.R.styleable#View_translationX 678 * @attr ref android.R.styleable#View_translationY 679 * @attr ref android.R.styleable#View_translationZ 680 * @attr ref android.R.styleable#View_visibility 681 * 682 * @see android.view.ViewGroup 683 */ 684public class View implements Drawable.Callback, KeyEvent.Callback, 685 AccessibilityEventSource { 686 private static final boolean DBG = false; 687 688 /** 689 * The logging tag used by this class with android.util.Log. 690 */ 691 protected static final String VIEW_LOG_TAG = "View"; 692 693 /** 694 * When set to true, apps will draw debugging information about their layouts. 695 * 696 * @hide 697 */ 698 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 699 700 /** 701 * Used to mark a View that has no ID. 702 */ 703 public static final int NO_ID = -1; 704 705 /** 706 * Signals that compatibility booleans have been initialized according to 707 * target SDK versions. 708 */ 709 private static boolean sCompatibilityDone = false; 710 711 /** 712 * Use the old (broken) way of building MeasureSpecs. 713 */ 714 private static boolean sUseBrokenMakeMeasureSpec = false; 715 716 /** 717 * Ignore any optimizations using the measure cache. 718 */ 719 private static boolean sIgnoreMeasureCache = false; 720 721 /** 722 * Ignore the clipBounds of this view for the children. 723 */ 724 static boolean sIgnoreClipBoundsForChildren = false; 725 726 /** 727 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 728 * calling setFlags. 729 */ 730 private static final int NOT_FOCUSABLE = 0x00000000; 731 732 /** 733 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 734 * setFlags. 735 */ 736 private static final int FOCUSABLE = 0x00000001; 737 738 /** 739 * Mask for use with setFlags indicating bits used for focus. 740 */ 741 private static final int FOCUSABLE_MASK = 0x00000001; 742 743 /** 744 * This view will adjust its padding to fit sytem windows (e.g. status bar) 745 */ 746 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 747 748 /** @hide */ 749 @IntDef({VISIBLE, INVISIBLE, GONE}) 750 @Retention(RetentionPolicy.SOURCE) 751 public @interface Visibility {} 752 753 /** 754 * This view is visible. 755 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 756 * android:visibility}. 757 */ 758 public static final int VISIBLE = 0x00000000; 759 760 /** 761 * This view is invisible, but it still takes up space for layout purposes. 762 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 763 * android:visibility}. 764 */ 765 public static final int INVISIBLE = 0x00000004; 766 767 /** 768 * This view is invisible, and it doesn't take any space for layout 769 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 770 * android:visibility}. 771 */ 772 public static final int GONE = 0x00000008; 773 774 /** 775 * Mask for use with setFlags indicating bits used for visibility. 776 * {@hide} 777 */ 778 static final int VISIBILITY_MASK = 0x0000000C; 779 780 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 781 782 /** 783 * This view is enabled. Interpretation varies by subclass. 784 * Use with ENABLED_MASK when calling setFlags. 785 * {@hide} 786 */ 787 static final int ENABLED = 0x00000000; 788 789 /** 790 * This view is disabled. Interpretation varies by subclass. 791 * Use with ENABLED_MASK when calling setFlags. 792 * {@hide} 793 */ 794 static final int DISABLED = 0x00000020; 795 796 /** 797 * Mask for use with setFlags indicating bits used for indicating whether 798 * this view is enabled 799 * {@hide} 800 */ 801 static final int ENABLED_MASK = 0x00000020; 802 803 /** 804 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 805 * called and further optimizations will be performed. It is okay to have 806 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 807 * {@hide} 808 */ 809 static final int WILL_NOT_DRAW = 0x00000080; 810 811 /** 812 * Mask for use with setFlags indicating bits used for indicating whether 813 * this view is will draw 814 * {@hide} 815 */ 816 static final int DRAW_MASK = 0x00000080; 817 818 /** 819 * <p>This view doesn't show scrollbars.</p> 820 * {@hide} 821 */ 822 static final int SCROLLBARS_NONE = 0x00000000; 823 824 /** 825 * <p>This view shows horizontal scrollbars.</p> 826 * {@hide} 827 */ 828 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 829 830 /** 831 * <p>This view shows vertical scrollbars.</p> 832 * {@hide} 833 */ 834 static final int SCROLLBARS_VERTICAL = 0x00000200; 835 836 /** 837 * <p>Mask for use with setFlags indicating bits used for indicating which 838 * scrollbars are enabled.</p> 839 * {@hide} 840 */ 841 static final int SCROLLBARS_MASK = 0x00000300; 842 843 /** 844 * Indicates that the view should filter touches when its window is obscured. 845 * Refer to the class comments for more information about this security feature. 846 * {@hide} 847 */ 848 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 849 850 /** 851 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 852 * that they are optional and should be skipped if the window has 853 * requested system UI flags that ignore those insets for layout. 854 */ 855 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 856 857 /** 858 * <p>This view doesn't show fading edges.</p> 859 * {@hide} 860 */ 861 static final int FADING_EDGE_NONE = 0x00000000; 862 863 /** 864 * <p>This view shows horizontal fading edges.</p> 865 * {@hide} 866 */ 867 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 868 869 /** 870 * <p>This view shows vertical fading edges.</p> 871 * {@hide} 872 */ 873 static final int FADING_EDGE_VERTICAL = 0x00002000; 874 875 /** 876 * <p>Mask for use with setFlags indicating bits used for indicating which 877 * fading edges are enabled.</p> 878 * {@hide} 879 */ 880 static final int FADING_EDGE_MASK = 0x00003000; 881 882 /** 883 * <p>Indicates this view can be clicked. When clickable, a View reacts 884 * to clicks by notifying the OnClickListener.<p> 885 * {@hide} 886 */ 887 static final int CLICKABLE = 0x00004000; 888 889 /** 890 * <p>Indicates this view is caching its drawing into a bitmap.</p> 891 * {@hide} 892 */ 893 static final int DRAWING_CACHE_ENABLED = 0x00008000; 894 895 /** 896 * <p>Indicates that no icicle should be saved for this view.<p> 897 * {@hide} 898 */ 899 static final int SAVE_DISABLED = 0x000010000; 900 901 /** 902 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 903 * property.</p> 904 * {@hide} 905 */ 906 static final int SAVE_DISABLED_MASK = 0x000010000; 907 908 /** 909 * <p>Indicates that no drawing cache should ever be created for this view.<p> 910 * {@hide} 911 */ 912 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 913 914 /** 915 * <p>Indicates this view can take / keep focus when int touch mode.</p> 916 * {@hide} 917 */ 918 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 919 920 /** @hide */ 921 @Retention(RetentionPolicy.SOURCE) 922 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 923 public @interface DrawingCacheQuality {} 924 925 /** 926 * <p>Enables low quality mode for the drawing cache.</p> 927 */ 928 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 929 930 /** 931 * <p>Enables high quality mode for the drawing cache.</p> 932 */ 933 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 934 935 /** 936 * <p>Enables automatic quality mode for the drawing cache.</p> 937 */ 938 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 939 940 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 941 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 942 }; 943 944 /** 945 * <p>Mask for use with setFlags indicating bits used for the cache 946 * quality property.</p> 947 * {@hide} 948 */ 949 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 950 951 /** 952 * <p> 953 * Indicates this view can be long clicked. When long clickable, a View 954 * reacts to long clicks by notifying the OnLongClickListener or showing a 955 * context menu. 956 * </p> 957 * {@hide} 958 */ 959 static final int LONG_CLICKABLE = 0x00200000; 960 961 /** 962 * <p>Indicates that this view gets its drawable states from its direct parent 963 * and ignores its original internal states.</p> 964 * 965 * @hide 966 */ 967 static final int DUPLICATE_PARENT_STATE = 0x00400000; 968 969 /** @hide */ 970 @IntDef({ 971 SCROLLBARS_INSIDE_OVERLAY, 972 SCROLLBARS_INSIDE_INSET, 973 SCROLLBARS_OUTSIDE_OVERLAY, 974 SCROLLBARS_OUTSIDE_INSET 975 }) 976 @Retention(RetentionPolicy.SOURCE) 977 public @interface ScrollBarStyle {} 978 979 /** 980 * The scrollbar style to display the scrollbars inside the content area, 981 * without increasing the padding. The scrollbars will be overlaid with 982 * translucency on the view's content. 983 */ 984 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 985 986 /** 987 * The scrollbar style to display the scrollbars inside the padded area, 988 * increasing the padding of the view. The scrollbars will not overlap the 989 * content area of the view. 990 */ 991 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 992 993 /** 994 * The scrollbar style to display the scrollbars at the edge of the view, 995 * without increasing the padding. The scrollbars will be overlaid with 996 * translucency. 997 */ 998 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 999 1000 /** 1001 * The scrollbar style to display the scrollbars at the edge of the view, 1002 * increasing the padding of the view. The scrollbars will only overlap the 1003 * background, if any. 1004 */ 1005 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1006 1007 /** 1008 * Mask to check if the scrollbar style is overlay or inset. 1009 * {@hide} 1010 */ 1011 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1012 1013 /** 1014 * Mask to check if the scrollbar style is inside or outside. 1015 * {@hide} 1016 */ 1017 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1018 1019 /** 1020 * Mask for scrollbar style. 1021 * {@hide} 1022 */ 1023 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1024 1025 /** 1026 * View flag indicating that the screen should remain on while the 1027 * window containing this view is visible to the user. This effectively 1028 * takes care of automatically setting the WindowManager's 1029 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1030 */ 1031 public static final int KEEP_SCREEN_ON = 0x04000000; 1032 1033 /** 1034 * View flag indicating whether this view should have sound effects enabled 1035 * for events such as clicking and touching. 1036 */ 1037 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1038 1039 /** 1040 * View flag indicating whether this view should have haptic feedback 1041 * enabled for events such as long presses. 1042 */ 1043 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1044 1045 /** 1046 * <p>Indicates that the view hierarchy should stop saving state when 1047 * it reaches this view. If state saving is initiated immediately at 1048 * the view, it will be allowed. 1049 * {@hide} 1050 */ 1051 static final int PARENT_SAVE_DISABLED = 0x20000000; 1052 1053 /** 1054 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1055 * {@hide} 1056 */ 1057 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1058 1059 /** @hide */ 1060 @IntDef(flag = true, 1061 value = { 1062 FOCUSABLES_ALL, 1063 FOCUSABLES_TOUCH_MODE 1064 }) 1065 @Retention(RetentionPolicy.SOURCE) 1066 public @interface FocusableMode {} 1067 1068 /** 1069 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1070 * should add all focusable Views regardless if they are focusable in touch mode. 1071 */ 1072 public static final int FOCUSABLES_ALL = 0x00000000; 1073 1074 /** 1075 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1076 * should add only Views focusable in touch mode. 1077 */ 1078 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1079 1080 /** @hide */ 1081 @IntDef({ 1082 FOCUS_BACKWARD, 1083 FOCUS_FORWARD, 1084 FOCUS_LEFT, 1085 FOCUS_UP, 1086 FOCUS_RIGHT, 1087 FOCUS_DOWN 1088 }) 1089 @Retention(RetentionPolicy.SOURCE) 1090 public @interface FocusDirection {} 1091 1092 /** @hide */ 1093 @IntDef({ 1094 FOCUS_LEFT, 1095 FOCUS_UP, 1096 FOCUS_RIGHT, 1097 FOCUS_DOWN 1098 }) 1099 @Retention(RetentionPolicy.SOURCE) 1100 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1101 1102 /** 1103 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1104 * item. 1105 */ 1106 public static final int FOCUS_BACKWARD = 0x00000001; 1107 1108 /** 1109 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1110 * item. 1111 */ 1112 public static final int FOCUS_FORWARD = 0x00000002; 1113 1114 /** 1115 * Use with {@link #focusSearch(int)}. Move focus to the left. 1116 */ 1117 public static final int FOCUS_LEFT = 0x00000011; 1118 1119 /** 1120 * Use with {@link #focusSearch(int)}. Move focus up. 1121 */ 1122 public static final int FOCUS_UP = 0x00000021; 1123 1124 /** 1125 * Use with {@link #focusSearch(int)}. Move focus to the right. 1126 */ 1127 public static final int FOCUS_RIGHT = 0x00000042; 1128 1129 /** 1130 * Use with {@link #focusSearch(int)}. Move focus down. 1131 */ 1132 public static final int FOCUS_DOWN = 0x00000082; 1133 1134 /** 1135 * Bits of {@link #getMeasuredWidthAndState()} and 1136 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1137 */ 1138 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1139 1140 /** 1141 * Bits of {@link #getMeasuredWidthAndState()} and 1142 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1143 */ 1144 public static final int MEASURED_STATE_MASK = 0xff000000; 1145 1146 /** 1147 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1148 * for functions that combine both width and height into a single int, 1149 * such as {@link #getMeasuredState()} and the childState argument of 1150 * {@link #resolveSizeAndState(int, int, int)}. 1151 */ 1152 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1153 1154 /** 1155 * Bit of {@link #getMeasuredWidthAndState()} and 1156 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1157 * is smaller that the space the view would like to have. 1158 */ 1159 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1160 1161 /** 1162 * Base View state sets 1163 */ 1164 // Singles 1165 /** 1166 * Indicates the view has no states set. States are used with 1167 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1168 * view depending on its state. 1169 * 1170 * @see android.graphics.drawable.Drawable 1171 * @see #getDrawableState() 1172 */ 1173 protected static final int[] EMPTY_STATE_SET; 1174 /** 1175 * Indicates the view is enabled. States are used with 1176 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1177 * view depending on its state. 1178 * 1179 * @see android.graphics.drawable.Drawable 1180 * @see #getDrawableState() 1181 */ 1182 protected static final int[] ENABLED_STATE_SET; 1183 /** 1184 * Indicates the view is focused. States are used with 1185 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1186 * view depending on its state. 1187 * 1188 * @see android.graphics.drawable.Drawable 1189 * @see #getDrawableState() 1190 */ 1191 protected static final int[] FOCUSED_STATE_SET; 1192 /** 1193 * Indicates the view is selected. States are used with 1194 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1195 * view depending on its state. 1196 * 1197 * @see android.graphics.drawable.Drawable 1198 * @see #getDrawableState() 1199 */ 1200 protected static final int[] SELECTED_STATE_SET; 1201 /** 1202 * Indicates the view is pressed. States are used with 1203 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1204 * view depending on its state. 1205 * 1206 * @see android.graphics.drawable.Drawable 1207 * @see #getDrawableState() 1208 */ 1209 protected static final int[] PRESSED_STATE_SET; 1210 /** 1211 * Indicates the view's window has focus. States are used with 1212 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1213 * view depending on its state. 1214 * 1215 * @see android.graphics.drawable.Drawable 1216 * @see #getDrawableState() 1217 */ 1218 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1219 // Doubles 1220 /** 1221 * Indicates the view is enabled and has the focus. 1222 * 1223 * @see #ENABLED_STATE_SET 1224 * @see #FOCUSED_STATE_SET 1225 */ 1226 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1227 /** 1228 * Indicates the view is enabled and selected. 1229 * 1230 * @see #ENABLED_STATE_SET 1231 * @see #SELECTED_STATE_SET 1232 */ 1233 protected static final int[] ENABLED_SELECTED_STATE_SET; 1234 /** 1235 * Indicates the view is enabled and that its window has focus. 1236 * 1237 * @see #ENABLED_STATE_SET 1238 * @see #WINDOW_FOCUSED_STATE_SET 1239 */ 1240 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1241 /** 1242 * Indicates the view is focused and selected. 1243 * 1244 * @see #FOCUSED_STATE_SET 1245 * @see #SELECTED_STATE_SET 1246 */ 1247 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1248 /** 1249 * Indicates the view has the focus and that its window has the focus. 1250 * 1251 * @see #FOCUSED_STATE_SET 1252 * @see #WINDOW_FOCUSED_STATE_SET 1253 */ 1254 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1255 /** 1256 * Indicates the view is selected and that its window has the focus. 1257 * 1258 * @see #SELECTED_STATE_SET 1259 * @see #WINDOW_FOCUSED_STATE_SET 1260 */ 1261 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1262 // Triples 1263 /** 1264 * Indicates the view is enabled, focused and selected. 1265 * 1266 * @see #ENABLED_STATE_SET 1267 * @see #FOCUSED_STATE_SET 1268 * @see #SELECTED_STATE_SET 1269 */ 1270 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1271 /** 1272 * Indicates the view is enabled, focused and its window has the focus. 1273 * 1274 * @see #ENABLED_STATE_SET 1275 * @see #FOCUSED_STATE_SET 1276 * @see #WINDOW_FOCUSED_STATE_SET 1277 */ 1278 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1279 /** 1280 * Indicates the view is enabled, selected and its window has the focus. 1281 * 1282 * @see #ENABLED_STATE_SET 1283 * @see #SELECTED_STATE_SET 1284 * @see #WINDOW_FOCUSED_STATE_SET 1285 */ 1286 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1287 /** 1288 * Indicates the view is focused, selected and its window has the focus. 1289 * 1290 * @see #FOCUSED_STATE_SET 1291 * @see #SELECTED_STATE_SET 1292 * @see #WINDOW_FOCUSED_STATE_SET 1293 */ 1294 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1295 /** 1296 * Indicates the view is enabled, focused, selected and its window 1297 * has the focus. 1298 * 1299 * @see #ENABLED_STATE_SET 1300 * @see #FOCUSED_STATE_SET 1301 * @see #SELECTED_STATE_SET 1302 * @see #WINDOW_FOCUSED_STATE_SET 1303 */ 1304 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1305 /** 1306 * Indicates the view is pressed and its window has the focus. 1307 * 1308 * @see #PRESSED_STATE_SET 1309 * @see #WINDOW_FOCUSED_STATE_SET 1310 */ 1311 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1312 /** 1313 * Indicates the view is pressed and selected. 1314 * 1315 * @see #PRESSED_STATE_SET 1316 * @see #SELECTED_STATE_SET 1317 */ 1318 protected static final int[] PRESSED_SELECTED_STATE_SET; 1319 /** 1320 * Indicates the view is pressed, selected and its window has the focus. 1321 * 1322 * @see #PRESSED_STATE_SET 1323 * @see #SELECTED_STATE_SET 1324 * @see #WINDOW_FOCUSED_STATE_SET 1325 */ 1326 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1327 /** 1328 * Indicates the view is pressed and focused. 1329 * 1330 * @see #PRESSED_STATE_SET 1331 * @see #FOCUSED_STATE_SET 1332 */ 1333 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1334 /** 1335 * Indicates the view is pressed, focused and its window has the focus. 1336 * 1337 * @see #PRESSED_STATE_SET 1338 * @see #FOCUSED_STATE_SET 1339 * @see #WINDOW_FOCUSED_STATE_SET 1340 */ 1341 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1342 /** 1343 * Indicates the view is pressed, focused and selected. 1344 * 1345 * @see #PRESSED_STATE_SET 1346 * @see #SELECTED_STATE_SET 1347 * @see #FOCUSED_STATE_SET 1348 */ 1349 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1350 /** 1351 * Indicates the view is pressed, focused, selected and its window has the focus. 1352 * 1353 * @see #PRESSED_STATE_SET 1354 * @see #FOCUSED_STATE_SET 1355 * @see #SELECTED_STATE_SET 1356 * @see #WINDOW_FOCUSED_STATE_SET 1357 */ 1358 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1359 /** 1360 * Indicates the view is pressed and enabled. 1361 * 1362 * @see #PRESSED_STATE_SET 1363 * @see #ENABLED_STATE_SET 1364 */ 1365 protected static final int[] PRESSED_ENABLED_STATE_SET; 1366 /** 1367 * Indicates the view is pressed, enabled and its window has the focus. 1368 * 1369 * @see #PRESSED_STATE_SET 1370 * @see #ENABLED_STATE_SET 1371 * @see #WINDOW_FOCUSED_STATE_SET 1372 */ 1373 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1374 /** 1375 * Indicates the view is pressed, enabled and selected. 1376 * 1377 * @see #PRESSED_STATE_SET 1378 * @see #ENABLED_STATE_SET 1379 * @see #SELECTED_STATE_SET 1380 */ 1381 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1382 /** 1383 * Indicates the view is pressed, enabled, selected and its window has the 1384 * focus. 1385 * 1386 * @see #PRESSED_STATE_SET 1387 * @see #ENABLED_STATE_SET 1388 * @see #SELECTED_STATE_SET 1389 * @see #WINDOW_FOCUSED_STATE_SET 1390 */ 1391 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1392 /** 1393 * Indicates the view is pressed, enabled and focused. 1394 * 1395 * @see #PRESSED_STATE_SET 1396 * @see #ENABLED_STATE_SET 1397 * @see #FOCUSED_STATE_SET 1398 */ 1399 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1400 /** 1401 * Indicates the view is pressed, enabled, focused and its window has the 1402 * focus. 1403 * 1404 * @see #PRESSED_STATE_SET 1405 * @see #ENABLED_STATE_SET 1406 * @see #FOCUSED_STATE_SET 1407 * @see #WINDOW_FOCUSED_STATE_SET 1408 */ 1409 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1410 /** 1411 * Indicates the view is pressed, enabled, focused and selected. 1412 * 1413 * @see #PRESSED_STATE_SET 1414 * @see #ENABLED_STATE_SET 1415 * @see #SELECTED_STATE_SET 1416 * @see #FOCUSED_STATE_SET 1417 */ 1418 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1419 /** 1420 * Indicates the view is pressed, enabled, focused, selected and its window 1421 * has the focus. 1422 * 1423 * @see #PRESSED_STATE_SET 1424 * @see #ENABLED_STATE_SET 1425 * @see #SELECTED_STATE_SET 1426 * @see #FOCUSED_STATE_SET 1427 * @see #WINDOW_FOCUSED_STATE_SET 1428 */ 1429 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1430 1431 /** 1432 * The order here is very important to {@link #getDrawableState()} 1433 */ 1434 private static final int[][] VIEW_STATE_SETS; 1435 1436 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1437 static final int VIEW_STATE_SELECTED = 1 << 1; 1438 static final int VIEW_STATE_FOCUSED = 1 << 2; 1439 static final int VIEW_STATE_ENABLED = 1 << 3; 1440 static final int VIEW_STATE_PRESSED = 1 << 4; 1441 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1442 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1443 static final int VIEW_STATE_HOVERED = 1 << 7; 1444 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1445 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1446 1447 static final int[] VIEW_STATE_IDS = new int[] { 1448 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1449 R.attr.state_selected, VIEW_STATE_SELECTED, 1450 R.attr.state_focused, VIEW_STATE_FOCUSED, 1451 R.attr.state_enabled, VIEW_STATE_ENABLED, 1452 R.attr.state_pressed, VIEW_STATE_PRESSED, 1453 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1454 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1455 R.attr.state_hovered, VIEW_STATE_HOVERED, 1456 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1457 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1458 }; 1459 1460 static { 1461 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1462 throw new IllegalStateException( 1463 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1464 } 1465 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1466 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1467 int viewState = R.styleable.ViewDrawableStates[i]; 1468 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1469 if (VIEW_STATE_IDS[j] == viewState) { 1470 orderedIds[i * 2] = viewState; 1471 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1472 } 1473 } 1474 } 1475 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1476 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1477 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1478 int numBits = Integer.bitCount(i); 1479 int[] set = new int[numBits]; 1480 int pos = 0; 1481 for (int j = 0; j < orderedIds.length; j += 2) { 1482 if ((i & orderedIds[j+1]) != 0) { 1483 set[pos++] = orderedIds[j]; 1484 } 1485 } 1486 VIEW_STATE_SETS[i] = set; 1487 } 1488 1489 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1490 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1491 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1492 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1493 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1494 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1495 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1496 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1497 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1498 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1499 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1500 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1501 | VIEW_STATE_FOCUSED]; 1502 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1503 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1504 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1505 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1506 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1507 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1508 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1509 | VIEW_STATE_ENABLED]; 1510 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1511 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1512 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1513 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1514 | VIEW_STATE_ENABLED]; 1515 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1516 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1517 | VIEW_STATE_ENABLED]; 1518 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1519 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1520 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1521 1522 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1523 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1524 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1525 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1526 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1527 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1528 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1529 | VIEW_STATE_PRESSED]; 1530 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1531 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1532 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1533 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1534 | VIEW_STATE_PRESSED]; 1535 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1536 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1537 | VIEW_STATE_PRESSED]; 1538 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1539 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1540 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1541 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1542 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1543 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1544 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1545 | VIEW_STATE_PRESSED]; 1546 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1547 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1548 | VIEW_STATE_PRESSED]; 1549 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1550 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1551 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1552 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1553 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1554 | VIEW_STATE_PRESSED]; 1555 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1556 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1557 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1558 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1559 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1560 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1561 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1562 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1563 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1564 | VIEW_STATE_PRESSED]; 1565 } 1566 1567 /** 1568 * Accessibility event types that are dispatched for text population. 1569 */ 1570 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1571 AccessibilityEvent.TYPE_VIEW_CLICKED 1572 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1573 | AccessibilityEvent.TYPE_VIEW_SELECTED 1574 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1575 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1576 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1577 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1578 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1579 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1580 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1581 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1582 1583 /** 1584 * Temporary Rect currently for use in setBackground(). This will probably 1585 * be extended in the future to hold our own class with more than just 1586 * a Rect. :) 1587 */ 1588 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1589 1590 /** 1591 * Map used to store views' tags. 1592 */ 1593 private SparseArray<Object> mKeyedTags; 1594 1595 /** 1596 * The next available accessibility id. 1597 */ 1598 private static int sNextAccessibilityViewId; 1599 1600 /** 1601 * The animation currently associated with this view. 1602 * @hide 1603 */ 1604 protected Animation mCurrentAnimation = null; 1605 1606 /** 1607 * Width as measured during measure pass. 1608 * {@hide} 1609 */ 1610 @ViewDebug.ExportedProperty(category = "measurement") 1611 int mMeasuredWidth; 1612 1613 /** 1614 * Height as measured during measure pass. 1615 * {@hide} 1616 */ 1617 @ViewDebug.ExportedProperty(category = "measurement") 1618 int mMeasuredHeight; 1619 1620 /** 1621 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1622 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1623 * its display list. This flag, used only when hw accelerated, allows us to clear the 1624 * flag while retaining this information until it's needed (at getDisplayList() time and 1625 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1626 * 1627 * {@hide} 1628 */ 1629 boolean mRecreateDisplayList = false; 1630 1631 /** 1632 * The view's identifier. 1633 * {@hide} 1634 * 1635 * @see #setId(int) 1636 * @see #getId() 1637 */ 1638 @ViewDebug.ExportedProperty(resolveId = true) 1639 int mID = NO_ID; 1640 1641 /** 1642 * The stable ID of this view for accessibility purposes. 1643 */ 1644 int mAccessibilityViewId = NO_ID; 1645 1646 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1647 1648 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1649 1650 /** 1651 * The view's tag. 1652 * {@hide} 1653 * 1654 * @see #setTag(Object) 1655 * @see #getTag() 1656 */ 1657 protected Object mTag = null; 1658 1659 // for mPrivateFlags: 1660 /** {@hide} */ 1661 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1662 /** {@hide} */ 1663 static final int PFLAG_FOCUSED = 0x00000002; 1664 /** {@hide} */ 1665 static final int PFLAG_SELECTED = 0x00000004; 1666 /** {@hide} */ 1667 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1668 /** {@hide} */ 1669 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1670 /** {@hide} */ 1671 static final int PFLAG_DRAWN = 0x00000020; 1672 /** 1673 * When this flag is set, this view is running an animation on behalf of its 1674 * children and should therefore not cancel invalidate requests, even if they 1675 * lie outside of this view's bounds. 1676 * 1677 * {@hide} 1678 */ 1679 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1680 /** {@hide} */ 1681 static final int PFLAG_SKIP_DRAW = 0x00000080; 1682 /** {@hide} */ 1683 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1684 /** {@hide} */ 1685 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1686 /** {@hide} */ 1687 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1688 /** {@hide} */ 1689 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1690 /** {@hide} */ 1691 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1692 /** {@hide} */ 1693 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1694 1695 private static final int PFLAG_PRESSED = 0x00004000; 1696 1697 /** {@hide} */ 1698 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1699 /** 1700 * Flag used to indicate that this view should be drawn once more (and only once 1701 * more) after its animation has completed. 1702 * {@hide} 1703 */ 1704 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1705 1706 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1707 1708 /** 1709 * Indicates that the View returned true when onSetAlpha() was called and that 1710 * the alpha must be restored. 1711 * {@hide} 1712 */ 1713 static final int PFLAG_ALPHA_SET = 0x00040000; 1714 1715 /** 1716 * Set by {@link #setScrollContainer(boolean)}. 1717 */ 1718 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1719 1720 /** 1721 * Set by {@link #setScrollContainer(boolean)}. 1722 */ 1723 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1724 1725 /** 1726 * View flag indicating whether this view was invalidated (fully or partially.) 1727 * 1728 * @hide 1729 */ 1730 static final int PFLAG_DIRTY = 0x00200000; 1731 1732 /** 1733 * View flag indicating whether this view was invalidated by an opaque 1734 * invalidate request. 1735 * 1736 * @hide 1737 */ 1738 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1739 1740 /** 1741 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1742 * 1743 * @hide 1744 */ 1745 static final int PFLAG_DIRTY_MASK = 0x00600000; 1746 1747 /** 1748 * Indicates whether the background is opaque. 1749 * 1750 * @hide 1751 */ 1752 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1753 1754 /** 1755 * Indicates whether the scrollbars are opaque. 1756 * 1757 * @hide 1758 */ 1759 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1760 1761 /** 1762 * Indicates whether the view is opaque. 1763 * 1764 * @hide 1765 */ 1766 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1767 1768 /** 1769 * Indicates a prepressed state; 1770 * the short time between ACTION_DOWN and recognizing 1771 * a 'real' press. Prepressed is used to recognize quick taps 1772 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1773 * 1774 * @hide 1775 */ 1776 private static final int PFLAG_PREPRESSED = 0x02000000; 1777 1778 /** 1779 * Indicates whether the view is temporarily detached. 1780 * 1781 * @hide 1782 */ 1783 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1784 1785 /** 1786 * Indicates that we should awaken scroll bars once attached 1787 * 1788 * @hide 1789 */ 1790 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1791 1792 /** 1793 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1794 * @hide 1795 */ 1796 private static final int PFLAG_HOVERED = 0x10000000; 1797 1798 /** 1799 * no longer needed, should be reused 1800 */ 1801 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1802 1803 /** {@hide} */ 1804 static final int PFLAG_ACTIVATED = 0x40000000; 1805 1806 /** 1807 * Indicates that this view was specifically invalidated, not just dirtied because some 1808 * child view was invalidated. The flag is used to determine when we need to recreate 1809 * a view's display list (as opposed to just returning a reference to its existing 1810 * display list). 1811 * 1812 * @hide 1813 */ 1814 static final int PFLAG_INVALIDATED = 0x80000000; 1815 1816 /** 1817 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1818 * 1819 * |-------|-------|-------|-------| 1820 * 1 PFLAG2_DRAG_CAN_ACCEPT 1821 * 1 PFLAG2_DRAG_HOVERED 1822 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1823 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1824 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1825 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1826 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1827 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1828 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1829 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1830 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1831 * 111 PFLAG2_TEXT_DIRECTION_MASK 1832 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1833 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1834 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1835 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1836 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1837 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1838 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1839 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1840 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1841 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1842 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1843 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1844 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1845 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1846 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1847 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1848 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1849 * 1 PFLAG2_VIEW_QUICK_REJECTED 1850 * 1 PFLAG2_PADDING_RESOLVED 1851 * 1 PFLAG2_DRAWABLE_RESOLVED 1852 * 1 PFLAG2_HAS_TRANSIENT_STATE 1853 * |-------|-------|-------|-------| 1854 */ 1855 1856 /** 1857 * Indicates that this view has reported that it can accept the current drag's content. 1858 * Cleared when the drag operation concludes. 1859 * @hide 1860 */ 1861 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1862 1863 /** 1864 * Indicates that this view is currently directly under the drag location in a 1865 * drag-and-drop operation involving content that it can accept. Cleared when 1866 * the drag exits the view, or when the drag operation concludes. 1867 * @hide 1868 */ 1869 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1870 1871 /** @hide */ 1872 @IntDef({ 1873 LAYOUT_DIRECTION_LTR, 1874 LAYOUT_DIRECTION_RTL, 1875 LAYOUT_DIRECTION_INHERIT, 1876 LAYOUT_DIRECTION_LOCALE 1877 }) 1878 @Retention(RetentionPolicy.SOURCE) 1879 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1880 public @interface LayoutDir {} 1881 1882 /** @hide */ 1883 @IntDef({ 1884 LAYOUT_DIRECTION_LTR, 1885 LAYOUT_DIRECTION_RTL 1886 }) 1887 @Retention(RetentionPolicy.SOURCE) 1888 public @interface ResolvedLayoutDir {} 1889 1890 /** 1891 * Horizontal layout direction of this view is from Left to Right. 1892 * Use with {@link #setLayoutDirection}. 1893 */ 1894 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1895 1896 /** 1897 * Horizontal layout direction of this view is from Right to Left. 1898 * Use with {@link #setLayoutDirection}. 1899 */ 1900 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1901 1902 /** 1903 * Horizontal layout direction of this view is inherited from its parent. 1904 * Use with {@link #setLayoutDirection}. 1905 */ 1906 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1907 1908 /** 1909 * Horizontal layout direction of this view is from deduced from the default language 1910 * script for the locale. Use with {@link #setLayoutDirection}. 1911 */ 1912 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1913 1914 /** 1915 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1916 * @hide 1917 */ 1918 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1919 1920 /** 1921 * Mask for use with private flags indicating bits used for horizontal layout direction. 1922 * @hide 1923 */ 1924 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1925 1926 /** 1927 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1928 * right-to-left direction. 1929 * @hide 1930 */ 1931 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1932 1933 /** 1934 * Indicates whether the view horizontal layout direction has been resolved. 1935 * @hide 1936 */ 1937 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1938 1939 /** 1940 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1941 * @hide 1942 */ 1943 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1944 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1945 1946 /* 1947 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1948 * flag value. 1949 * @hide 1950 */ 1951 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1952 LAYOUT_DIRECTION_LTR, 1953 LAYOUT_DIRECTION_RTL, 1954 LAYOUT_DIRECTION_INHERIT, 1955 LAYOUT_DIRECTION_LOCALE 1956 }; 1957 1958 /** 1959 * Default horizontal layout direction. 1960 */ 1961 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1962 1963 /** 1964 * Default horizontal layout direction. 1965 * @hide 1966 */ 1967 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1968 1969 /** 1970 * Text direction is inherited thru {@link ViewGroup} 1971 */ 1972 public static final int TEXT_DIRECTION_INHERIT = 0; 1973 1974 /** 1975 * Text direction is using "first strong algorithm". The first strong directional character 1976 * determines the paragraph direction. If there is no strong directional character, the 1977 * paragraph direction is the view's resolved layout direction. 1978 */ 1979 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1980 1981 /** 1982 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1983 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1984 * If there are neither, the paragraph direction is the view's resolved layout direction. 1985 */ 1986 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1987 1988 /** 1989 * Text direction is forced to LTR. 1990 */ 1991 public static final int TEXT_DIRECTION_LTR = 3; 1992 1993 /** 1994 * Text direction is forced to RTL. 1995 */ 1996 public static final int TEXT_DIRECTION_RTL = 4; 1997 1998 /** 1999 * Text direction is coming from the system Locale. 2000 */ 2001 public static final int TEXT_DIRECTION_LOCALE = 5; 2002 2003 /** 2004 * Default text direction is inherited 2005 */ 2006 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2007 2008 /** 2009 * Default resolved text direction 2010 * @hide 2011 */ 2012 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2013 2014 /** 2015 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2016 * @hide 2017 */ 2018 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2019 2020 /** 2021 * Mask for use with private flags indicating bits used for text direction. 2022 * @hide 2023 */ 2024 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2025 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2026 2027 /** 2028 * Array of text direction flags for mapping attribute "textDirection" to correct 2029 * flag value. 2030 * @hide 2031 */ 2032 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2033 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2034 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2035 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2036 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2037 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2038 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2039 }; 2040 2041 /** 2042 * Indicates whether the view text direction has been resolved. 2043 * @hide 2044 */ 2045 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2046 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2047 2048 /** 2049 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2050 * @hide 2051 */ 2052 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2053 2054 /** 2055 * Mask for use with private flags indicating bits used for resolved text direction. 2056 * @hide 2057 */ 2058 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2059 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2060 2061 /** 2062 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2063 * @hide 2064 */ 2065 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2066 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2067 2068 /** @hide */ 2069 @IntDef({ 2070 TEXT_ALIGNMENT_INHERIT, 2071 TEXT_ALIGNMENT_GRAVITY, 2072 TEXT_ALIGNMENT_CENTER, 2073 TEXT_ALIGNMENT_TEXT_START, 2074 TEXT_ALIGNMENT_TEXT_END, 2075 TEXT_ALIGNMENT_VIEW_START, 2076 TEXT_ALIGNMENT_VIEW_END 2077 }) 2078 @Retention(RetentionPolicy.SOURCE) 2079 public @interface TextAlignment {} 2080 2081 /** 2082 * Default text alignment. The text alignment of this View is inherited from its parent. 2083 * Use with {@link #setTextAlignment(int)} 2084 */ 2085 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2086 2087 /** 2088 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2089 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2090 * 2091 * Use with {@link #setTextAlignment(int)} 2092 */ 2093 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2094 2095 /** 2096 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2097 * 2098 * Use with {@link #setTextAlignment(int)} 2099 */ 2100 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2101 2102 /** 2103 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2104 * 2105 * Use with {@link #setTextAlignment(int)} 2106 */ 2107 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2108 2109 /** 2110 * Center the paragraph, e.g. ALIGN_CENTER. 2111 * 2112 * Use with {@link #setTextAlignment(int)} 2113 */ 2114 public static final int TEXT_ALIGNMENT_CENTER = 4; 2115 2116 /** 2117 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2118 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2119 * 2120 * Use with {@link #setTextAlignment(int)} 2121 */ 2122 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2123 2124 /** 2125 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2126 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2127 * 2128 * Use with {@link #setTextAlignment(int)} 2129 */ 2130 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2131 2132 /** 2133 * Default text alignment is inherited 2134 */ 2135 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2136 2137 /** 2138 * Default resolved text alignment 2139 * @hide 2140 */ 2141 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2142 2143 /** 2144 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2145 * @hide 2146 */ 2147 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2148 2149 /** 2150 * Mask for use with private flags indicating bits used for text alignment. 2151 * @hide 2152 */ 2153 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2154 2155 /** 2156 * Array of text direction flags for mapping attribute "textAlignment" to correct 2157 * flag value. 2158 * @hide 2159 */ 2160 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2161 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2162 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2163 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2164 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2165 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2166 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2167 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2168 }; 2169 2170 /** 2171 * Indicates whether the view text alignment has been resolved. 2172 * @hide 2173 */ 2174 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2175 2176 /** 2177 * Bit shift to get the resolved text alignment. 2178 * @hide 2179 */ 2180 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2181 2182 /** 2183 * Mask for use with private flags indicating bits used for text alignment. 2184 * @hide 2185 */ 2186 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2187 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2188 2189 /** 2190 * Indicates whether if the view text alignment has been resolved to gravity 2191 */ 2192 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2193 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2194 2195 // Accessiblity constants for mPrivateFlags2 2196 2197 /** 2198 * Shift for the bits in {@link #mPrivateFlags2} related to the 2199 * "importantForAccessibility" attribute. 2200 */ 2201 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2202 2203 /** 2204 * Automatically determine whether a view is important for accessibility. 2205 */ 2206 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2207 2208 /** 2209 * The view is important for accessibility. 2210 */ 2211 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2212 2213 /** 2214 * The view is not important for accessibility. 2215 */ 2216 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2217 2218 /** 2219 * The view is not important for accessibility, nor are any of its 2220 * descendant views. 2221 */ 2222 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2223 2224 /** 2225 * The default whether the view is important for accessibility. 2226 */ 2227 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2228 2229 /** 2230 * Mask for obtainig the bits which specify how to determine 2231 * whether a view is important for accessibility. 2232 */ 2233 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2234 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2235 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2236 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2237 2238 /** 2239 * Shift for the bits in {@link #mPrivateFlags2} related to the 2240 * "accessibilityLiveRegion" attribute. 2241 */ 2242 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2243 2244 /** 2245 * Live region mode specifying that accessibility services should not 2246 * automatically announce changes to this view. This is the default live 2247 * region mode for most views. 2248 * <p> 2249 * Use with {@link #setAccessibilityLiveRegion(int)}. 2250 */ 2251 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2252 2253 /** 2254 * Live region mode specifying that accessibility services should announce 2255 * changes to this view. 2256 * <p> 2257 * Use with {@link #setAccessibilityLiveRegion(int)}. 2258 */ 2259 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2260 2261 /** 2262 * Live region mode specifying that accessibility services should interrupt 2263 * ongoing speech to immediately announce changes to this view. 2264 * <p> 2265 * Use with {@link #setAccessibilityLiveRegion(int)}. 2266 */ 2267 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2268 2269 /** 2270 * The default whether the view is important for accessibility. 2271 */ 2272 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2273 2274 /** 2275 * Mask for obtaining the bits which specify a view's accessibility live 2276 * region mode. 2277 */ 2278 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2279 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2280 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2281 2282 /** 2283 * Flag indicating whether a view has accessibility focus. 2284 */ 2285 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2286 2287 /** 2288 * Flag whether the accessibility state of the subtree rooted at this view changed. 2289 */ 2290 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2291 2292 /** 2293 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2294 * is used to check whether later changes to the view's transform should invalidate the 2295 * view to force the quickReject test to run again. 2296 */ 2297 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2298 2299 /** 2300 * Flag indicating that start/end padding has been resolved into left/right padding 2301 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2302 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2303 * during measurement. In some special cases this is required such as when an adapter-based 2304 * view measures prospective children without attaching them to a window. 2305 */ 2306 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2307 2308 /** 2309 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2310 */ 2311 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2312 2313 /** 2314 * Indicates that the view is tracking some sort of transient state 2315 * that the app should not need to be aware of, but that the framework 2316 * should take special care to preserve. 2317 */ 2318 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2319 2320 /** 2321 * Group of bits indicating that RTL properties resolution is done. 2322 */ 2323 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2324 PFLAG2_TEXT_DIRECTION_RESOLVED | 2325 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2326 PFLAG2_PADDING_RESOLVED | 2327 PFLAG2_DRAWABLE_RESOLVED; 2328 2329 // There are a couple of flags left in mPrivateFlags2 2330 2331 /* End of masks for mPrivateFlags2 */ 2332 2333 /** 2334 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2335 * 2336 * |-------|-------|-------|-------| 2337 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2338 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2339 * 1 PFLAG3_IS_LAID_OUT 2340 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2341 * 1 PFLAG3_CALLED_SUPER 2342 * |-------|-------|-------|-------| 2343 */ 2344 2345 /** 2346 * Flag indicating that view has a transform animation set on it. This is used to track whether 2347 * an animation is cleared between successive frames, in order to tell the associated 2348 * DisplayList to clear its animation matrix. 2349 */ 2350 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2351 2352 /** 2353 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2354 * animation is cleared between successive frames, in order to tell the associated 2355 * DisplayList to restore its alpha value. 2356 */ 2357 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2358 2359 /** 2360 * Flag indicating that the view has been through at least one layout since it 2361 * was last attached to a window. 2362 */ 2363 static final int PFLAG3_IS_LAID_OUT = 0x4; 2364 2365 /** 2366 * Flag indicating that a call to measure() was skipped and should be done 2367 * instead when layout() is invoked. 2368 */ 2369 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2370 2371 /** 2372 * Flag indicating that an overridden method correctly called down to 2373 * the superclass implementation as required by the API spec. 2374 */ 2375 static final int PFLAG3_CALLED_SUPER = 0x10; 2376 2377 /** 2378 * Flag indicating that a view's outline has been specifically defined. 2379 */ 2380 static final int PFLAG3_OUTLINE_DEFINED = 0x20; 2381 2382 /** 2383 * Flag indicating that we're in the process of applying window insets. 2384 */ 2385 static final int PFLAG3_APPLYING_INSETS = 0x40; 2386 2387 /** 2388 * Flag indicating that we're in the process of fitting system windows using the old method. 2389 */ 2390 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80; 2391 2392 /** 2393 * Flag indicating that nested scrolling is enabled for this view. 2394 * The view will optionally cooperate with views up its parent chain to allow for 2395 * integrated nested scrolling along the same axis. 2396 */ 2397 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x200; 2398 2399 /* End of masks for mPrivateFlags3 */ 2400 2401 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2402 2403 /** 2404 * Always allow a user to over-scroll this view, provided it is a 2405 * view that can scroll. 2406 * 2407 * @see #getOverScrollMode() 2408 * @see #setOverScrollMode(int) 2409 */ 2410 public static final int OVER_SCROLL_ALWAYS = 0; 2411 2412 /** 2413 * Allow a user to over-scroll this view only if the content is large 2414 * enough to meaningfully scroll, provided it is a view that can scroll. 2415 * 2416 * @see #getOverScrollMode() 2417 * @see #setOverScrollMode(int) 2418 */ 2419 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2420 2421 /** 2422 * Never allow a user to over-scroll this view. 2423 * 2424 * @see #getOverScrollMode() 2425 * @see #setOverScrollMode(int) 2426 */ 2427 public static final int OVER_SCROLL_NEVER = 2; 2428 2429 /** 2430 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2431 * requested the system UI (status bar) to be visible (the default). 2432 * 2433 * @see #setSystemUiVisibility(int) 2434 */ 2435 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2436 2437 /** 2438 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2439 * system UI to enter an unobtrusive "low profile" mode. 2440 * 2441 * <p>This is for use in games, book readers, video players, or any other 2442 * "immersive" application where the usual system chrome is deemed too distracting. 2443 * 2444 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2445 * 2446 * @see #setSystemUiVisibility(int) 2447 */ 2448 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2449 2450 /** 2451 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2452 * system navigation be temporarily hidden. 2453 * 2454 * <p>This is an even less obtrusive state than that called for by 2455 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2456 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2457 * those to disappear. This is useful (in conjunction with the 2458 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2459 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2460 * window flags) for displaying content using every last pixel on the display. 2461 * 2462 * <p>There is a limitation: because navigation controls are so important, the least user 2463 * interaction will cause them to reappear immediately. When this happens, both 2464 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2465 * so that both elements reappear at the same time. 2466 * 2467 * @see #setSystemUiVisibility(int) 2468 */ 2469 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2470 2471 /** 2472 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2473 * into the normal fullscreen mode so that its content can take over the screen 2474 * while still allowing the user to interact with the application. 2475 * 2476 * <p>This has the same visual effect as 2477 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2478 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2479 * meaning that non-critical screen decorations (such as the status bar) will be 2480 * hidden while the user is in the View's window, focusing the experience on 2481 * that content. Unlike the window flag, if you are using ActionBar in 2482 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2483 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2484 * hide the action bar. 2485 * 2486 * <p>This approach to going fullscreen is best used over the window flag when 2487 * it is a transient state -- that is, the application does this at certain 2488 * points in its user interaction where it wants to allow the user to focus 2489 * on content, but not as a continuous state. For situations where the application 2490 * would like to simply stay full screen the entire time (such as a game that 2491 * wants to take over the screen), the 2492 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2493 * is usually a better approach. The state set here will be removed by the system 2494 * in various situations (such as the user moving to another application) like 2495 * the other system UI states. 2496 * 2497 * <p>When using this flag, the application should provide some easy facility 2498 * for the user to go out of it. A common example would be in an e-book 2499 * reader, where tapping on the screen brings back whatever screen and UI 2500 * decorations that had been hidden while the user was immersed in reading 2501 * the book. 2502 * 2503 * @see #setSystemUiVisibility(int) 2504 */ 2505 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2506 2507 /** 2508 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2509 * flags, we would like a stable view of the content insets given to 2510 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2511 * will always represent the worst case that the application can expect 2512 * as a continuous state. In the stock Android UI this is the space for 2513 * the system bar, nav bar, and status bar, but not more transient elements 2514 * such as an input method. 2515 * 2516 * The stable layout your UI sees is based on the system UI modes you can 2517 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2518 * then you will get a stable layout for changes of the 2519 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2520 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2521 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2522 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2523 * with a stable layout. (Note that you should avoid using 2524 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2525 * 2526 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2527 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2528 * then a hidden status bar will be considered a "stable" state for purposes 2529 * here. This allows your UI to continually hide the status bar, while still 2530 * using the system UI flags to hide the action bar while still retaining 2531 * a stable layout. Note that changing the window fullscreen flag will never 2532 * provide a stable layout for a clean transition. 2533 * 2534 * <p>If you are using ActionBar in 2535 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2536 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2537 * insets it adds to those given to the application. 2538 */ 2539 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2540 2541 /** 2542 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2543 * to be layed out as if it has requested 2544 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2545 * allows it to avoid artifacts when switching in and out of that mode, at 2546 * the expense that some of its user interface may be covered by screen 2547 * decorations when they are shown. You can perform layout of your inner 2548 * UI elements to account for the navigation system UI through the 2549 * {@link #fitSystemWindows(Rect)} method. 2550 */ 2551 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2552 2553 /** 2554 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2555 * to be layed out as if it has requested 2556 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2557 * allows it to avoid artifacts when switching in and out of that mode, at 2558 * the expense that some of its user interface may be covered by screen 2559 * decorations when they are shown. You can perform layout of your inner 2560 * UI elements to account for non-fullscreen system UI through the 2561 * {@link #fitSystemWindows(Rect)} method. 2562 */ 2563 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2564 2565 /** 2566 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2567 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2568 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2569 * user interaction. 2570 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2571 * has an effect when used in combination with that flag.</p> 2572 */ 2573 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2574 2575 /** 2576 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2577 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2578 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2579 * experience while also hiding the system bars. If this flag is not set, 2580 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2581 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2582 * if the user swipes from the top of the screen. 2583 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2584 * system gestures, such as swiping from the top of the screen. These transient system bars 2585 * will overlay app’s content, may have some degree of transparency, and will automatically 2586 * hide after a short timeout. 2587 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2588 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2589 * with one or both of those flags.</p> 2590 */ 2591 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2592 2593 /** 2594 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2595 */ 2596 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2597 2598 /** 2599 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2600 */ 2601 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2602 2603 /** 2604 * @hide 2605 * 2606 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2607 * out of the public fields to keep the undefined bits out of the developer's way. 2608 * 2609 * Flag to make the status bar not expandable. Unless you also 2610 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2611 */ 2612 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2613 2614 /** 2615 * @hide 2616 * 2617 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2618 * out of the public fields to keep the undefined bits out of the developer's way. 2619 * 2620 * Flag to hide notification icons and scrolling ticker text. 2621 */ 2622 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2623 2624 /** 2625 * @hide 2626 * 2627 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2628 * out of the public fields to keep the undefined bits out of the developer's way. 2629 * 2630 * Flag to disable incoming notification alerts. This will not block 2631 * icons, but it will block sound, vibrating and other visual or aural notifications. 2632 */ 2633 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2634 2635 /** 2636 * @hide 2637 * 2638 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2639 * out of the public fields to keep the undefined bits out of the developer's way. 2640 * 2641 * Flag to hide only the scrolling ticker. Note that 2642 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2643 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2644 */ 2645 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2646 2647 /** 2648 * @hide 2649 * 2650 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2651 * out of the public fields to keep the undefined bits out of the developer's way. 2652 * 2653 * Flag to hide the center system info area. 2654 */ 2655 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2656 2657 /** 2658 * @hide 2659 * 2660 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2661 * out of the public fields to keep the undefined bits out of the developer's way. 2662 * 2663 * Flag to hide only the home button. Don't use this 2664 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2665 */ 2666 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2667 2668 /** 2669 * @hide 2670 * 2671 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2672 * out of the public fields to keep the undefined bits out of the developer's way. 2673 * 2674 * Flag to hide only the back button. Don't use this 2675 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2676 */ 2677 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2678 2679 /** 2680 * @hide 2681 * 2682 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2683 * out of the public fields to keep the undefined bits out of the developer's way. 2684 * 2685 * Flag to hide only the clock. You might use this if your activity has 2686 * its own clock making the status bar's clock redundant. 2687 */ 2688 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2689 2690 /** 2691 * @hide 2692 * 2693 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2694 * out of the public fields to keep the undefined bits out of the developer's way. 2695 * 2696 * Flag to hide only the recent apps button. Don't use this 2697 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2698 */ 2699 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2700 2701 /** 2702 * @hide 2703 * 2704 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2705 * out of the public fields to keep the undefined bits out of the developer's way. 2706 * 2707 * Flag to disable the global search gesture. Don't use this 2708 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2709 */ 2710 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2711 2712 /** 2713 * @hide 2714 * 2715 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2716 * out of the public fields to keep the undefined bits out of the developer's way. 2717 * 2718 * Flag to specify that the status bar is displayed in transient mode. 2719 */ 2720 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2721 2722 /** 2723 * @hide 2724 * 2725 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2726 * out of the public fields to keep the undefined bits out of the developer's way. 2727 * 2728 * Flag to specify that the navigation bar is displayed in transient mode. 2729 */ 2730 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2731 2732 /** 2733 * @hide 2734 * 2735 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2736 * out of the public fields to keep the undefined bits out of the developer's way. 2737 * 2738 * Flag to specify that the hidden status bar would like to be shown. 2739 */ 2740 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2741 2742 /** 2743 * @hide 2744 * 2745 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2746 * out of the public fields to keep the undefined bits out of the developer's way. 2747 * 2748 * Flag to specify that the hidden navigation bar would like to be shown. 2749 */ 2750 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2751 2752 /** 2753 * @hide 2754 * 2755 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2756 * out of the public fields to keep the undefined bits out of the developer's way. 2757 * 2758 * Flag to specify that the status bar is displayed in translucent mode. 2759 */ 2760 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2761 2762 /** 2763 * @hide 2764 * 2765 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2766 * out of the public fields to keep the undefined bits out of the developer's way. 2767 * 2768 * Flag to specify that the navigation bar is displayed in translucent mode. 2769 */ 2770 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2771 2772 /** 2773 * @hide 2774 */ 2775 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2776 2777 /** 2778 * These are the system UI flags that can be cleared by events outside 2779 * of an application. Currently this is just the ability to tap on the 2780 * screen while hiding the navigation bar to have it return. 2781 * @hide 2782 */ 2783 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2784 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2785 | SYSTEM_UI_FLAG_FULLSCREEN; 2786 2787 /** 2788 * Flags that can impact the layout in relation to system UI. 2789 */ 2790 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2791 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2792 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2793 2794 /** @hide */ 2795 @IntDef(flag = true, 2796 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2797 @Retention(RetentionPolicy.SOURCE) 2798 public @interface FindViewFlags {} 2799 2800 /** 2801 * Find views that render the specified text. 2802 * 2803 * @see #findViewsWithText(ArrayList, CharSequence, int) 2804 */ 2805 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2806 2807 /** 2808 * Find find views that contain the specified content description. 2809 * 2810 * @see #findViewsWithText(ArrayList, CharSequence, int) 2811 */ 2812 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2813 2814 /** 2815 * Find views that contain {@link AccessibilityNodeProvider}. Such 2816 * a View is a root of virtual view hierarchy and may contain the searched 2817 * text. If this flag is set Views with providers are automatically 2818 * added and it is a responsibility of the client to call the APIs of 2819 * the provider to determine whether the virtual tree rooted at this View 2820 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2821 * representing the virtual views with this text. 2822 * 2823 * @see #findViewsWithText(ArrayList, CharSequence, int) 2824 * 2825 * @hide 2826 */ 2827 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2828 2829 /** 2830 * The undefined cursor position. 2831 * 2832 * @hide 2833 */ 2834 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2835 2836 /** 2837 * Indicates that the screen has changed state and is now off. 2838 * 2839 * @see #onScreenStateChanged(int) 2840 */ 2841 public static final int SCREEN_STATE_OFF = 0x0; 2842 2843 /** 2844 * Indicates that the screen has changed state and is now on. 2845 * 2846 * @see #onScreenStateChanged(int) 2847 */ 2848 public static final int SCREEN_STATE_ON = 0x1; 2849 2850 /** 2851 * Indicates no axis of view scrolling. 2852 */ 2853 public static final int SCROLL_AXIS_NONE = 0; 2854 2855 /** 2856 * Indicates scrolling along the horizontal axis. 2857 */ 2858 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2859 2860 /** 2861 * Indicates scrolling along the vertical axis. 2862 */ 2863 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2864 2865 /** 2866 * Controls the over-scroll mode for this view. 2867 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2868 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2869 * and {@link #OVER_SCROLL_NEVER}. 2870 */ 2871 private int mOverScrollMode; 2872 2873 /** 2874 * The parent this view is attached to. 2875 * {@hide} 2876 * 2877 * @see #getParent() 2878 */ 2879 protected ViewParent mParent; 2880 2881 /** 2882 * {@hide} 2883 */ 2884 AttachInfo mAttachInfo; 2885 2886 /** 2887 * {@hide} 2888 */ 2889 @ViewDebug.ExportedProperty(flagMapping = { 2890 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2891 name = "FORCE_LAYOUT"), 2892 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2893 name = "LAYOUT_REQUIRED"), 2894 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2895 name = "DRAWING_CACHE_INVALID", outputIf = false), 2896 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2897 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2898 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2899 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2900 }) 2901 int mPrivateFlags; 2902 int mPrivateFlags2; 2903 int mPrivateFlags3; 2904 2905 /** 2906 * This view's request for the visibility of the status bar. 2907 * @hide 2908 */ 2909 @ViewDebug.ExportedProperty(flagMapping = { 2910 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2911 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2912 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2913 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2914 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2915 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2916 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2917 equals = SYSTEM_UI_FLAG_VISIBLE, 2918 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2919 }) 2920 int mSystemUiVisibility; 2921 2922 /** 2923 * Reference count for transient state. 2924 * @see #setHasTransientState(boolean) 2925 */ 2926 int mTransientStateCount = 0; 2927 2928 /** 2929 * Count of how many windows this view has been attached to. 2930 */ 2931 int mWindowAttachCount; 2932 2933 /** 2934 * The layout parameters associated with this view and used by the parent 2935 * {@link android.view.ViewGroup} to determine how this view should be 2936 * laid out. 2937 * {@hide} 2938 */ 2939 protected ViewGroup.LayoutParams mLayoutParams; 2940 2941 /** 2942 * The view flags hold various views states. 2943 * {@hide} 2944 */ 2945 @ViewDebug.ExportedProperty 2946 int mViewFlags; 2947 2948 static class TransformationInfo { 2949 /** 2950 * The transform matrix for the View. This transform is calculated internally 2951 * based on the translation, rotation, and scale properties. 2952 * 2953 * Do *not* use this variable directly; instead call getMatrix(), which will 2954 * load the value from the View's RenderNode. 2955 */ 2956 private final Matrix mMatrix = new Matrix(); 2957 2958 /** 2959 * The inverse transform matrix for the View. This transform is calculated 2960 * internally based on the translation, rotation, and scale properties. 2961 * 2962 * Do *not* use this variable directly; instead call getInverseMatrix(), 2963 * which will load the value from the View's RenderNode. 2964 */ 2965 private Matrix mInverseMatrix; 2966 2967 /** 2968 * The opacity of the View. This is a value from 0 to 1, where 0 means 2969 * completely transparent and 1 means completely opaque. 2970 */ 2971 @ViewDebug.ExportedProperty 2972 float mAlpha = 1f; 2973 2974 /** 2975 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2976 * property only used by transitions, which is composited with the other alpha 2977 * values to calculate the final visual alpha value. 2978 */ 2979 float mTransitionAlpha = 1f; 2980 } 2981 2982 TransformationInfo mTransformationInfo; 2983 2984 /** 2985 * Current clip bounds. to which all drawing of this view are constrained. 2986 */ 2987 Rect mClipBounds = null; 2988 2989 private boolean mLastIsOpaque; 2990 2991 /** 2992 * The distance in pixels from the left edge of this view's parent 2993 * to the left edge of this view. 2994 * {@hide} 2995 */ 2996 @ViewDebug.ExportedProperty(category = "layout") 2997 protected int mLeft; 2998 /** 2999 * The distance in pixels from the left edge of this view's parent 3000 * to the right edge of this view. 3001 * {@hide} 3002 */ 3003 @ViewDebug.ExportedProperty(category = "layout") 3004 protected int mRight; 3005 /** 3006 * The distance in pixels from the top edge of this view's parent 3007 * to the top edge of this view. 3008 * {@hide} 3009 */ 3010 @ViewDebug.ExportedProperty(category = "layout") 3011 protected int mTop; 3012 /** 3013 * The distance in pixels from the top edge of this view's parent 3014 * to the bottom edge of this view. 3015 * {@hide} 3016 */ 3017 @ViewDebug.ExportedProperty(category = "layout") 3018 protected int mBottom; 3019 3020 /** 3021 * The offset, in pixels, by which the content of this view is scrolled 3022 * horizontally. 3023 * {@hide} 3024 */ 3025 @ViewDebug.ExportedProperty(category = "scrolling") 3026 protected int mScrollX; 3027 /** 3028 * The offset, in pixels, by which the content of this view is scrolled 3029 * vertically. 3030 * {@hide} 3031 */ 3032 @ViewDebug.ExportedProperty(category = "scrolling") 3033 protected int mScrollY; 3034 3035 /** 3036 * The left padding in pixels, that is the distance in pixels between the 3037 * left edge of this view and the left edge of its content. 3038 * {@hide} 3039 */ 3040 @ViewDebug.ExportedProperty(category = "padding") 3041 protected int mPaddingLeft = 0; 3042 /** 3043 * The right padding in pixels, that is the distance in pixels between the 3044 * right edge of this view and the right edge of its content. 3045 * {@hide} 3046 */ 3047 @ViewDebug.ExportedProperty(category = "padding") 3048 protected int mPaddingRight = 0; 3049 /** 3050 * The top padding in pixels, that is the distance in pixels between the 3051 * top edge of this view and the top edge of its content. 3052 * {@hide} 3053 */ 3054 @ViewDebug.ExportedProperty(category = "padding") 3055 protected int mPaddingTop; 3056 /** 3057 * The bottom padding in pixels, that is the distance in pixels between the 3058 * bottom edge of this view and the bottom edge of its content. 3059 * {@hide} 3060 */ 3061 @ViewDebug.ExportedProperty(category = "padding") 3062 protected int mPaddingBottom; 3063 3064 /** 3065 * The layout insets in pixels, that is the distance in pixels between the 3066 * visible edges of this view its bounds. 3067 */ 3068 private Insets mLayoutInsets; 3069 3070 /** 3071 * Briefly describes the view and is primarily used for accessibility support. 3072 */ 3073 private CharSequence mContentDescription; 3074 3075 /** 3076 * Specifies the id of a view for which this view serves as a label for 3077 * accessibility purposes. 3078 */ 3079 private int mLabelForId = View.NO_ID; 3080 3081 /** 3082 * Predicate for matching labeled view id with its label for 3083 * accessibility purposes. 3084 */ 3085 private MatchLabelForPredicate mMatchLabelForPredicate; 3086 3087 /** 3088 * Predicate for matching a view by its id. 3089 */ 3090 private MatchIdPredicate mMatchIdPredicate; 3091 3092 /** 3093 * Cache the paddingRight set by the user to append to the scrollbar's size. 3094 * 3095 * @hide 3096 */ 3097 @ViewDebug.ExportedProperty(category = "padding") 3098 protected int mUserPaddingRight; 3099 3100 /** 3101 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3102 * 3103 * @hide 3104 */ 3105 @ViewDebug.ExportedProperty(category = "padding") 3106 protected int mUserPaddingBottom; 3107 3108 /** 3109 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3110 * 3111 * @hide 3112 */ 3113 @ViewDebug.ExportedProperty(category = "padding") 3114 protected int mUserPaddingLeft; 3115 3116 /** 3117 * Cache the paddingStart set by the user to append to the scrollbar's size. 3118 * 3119 */ 3120 @ViewDebug.ExportedProperty(category = "padding") 3121 int mUserPaddingStart; 3122 3123 /** 3124 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3125 * 3126 */ 3127 @ViewDebug.ExportedProperty(category = "padding") 3128 int mUserPaddingEnd; 3129 3130 /** 3131 * Cache initial left padding. 3132 * 3133 * @hide 3134 */ 3135 int mUserPaddingLeftInitial; 3136 3137 /** 3138 * Cache initial right padding. 3139 * 3140 * @hide 3141 */ 3142 int mUserPaddingRightInitial; 3143 3144 /** 3145 * Default undefined padding 3146 */ 3147 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3148 3149 /** 3150 * Cache if a left padding has been defined 3151 */ 3152 private boolean mLeftPaddingDefined = false; 3153 3154 /** 3155 * Cache if a right padding has been defined 3156 */ 3157 private boolean mRightPaddingDefined = false; 3158 3159 /** 3160 * @hide 3161 */ 3162 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3163 /** 3164 * @hide 3165 */ 3166 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3167 3168 private LongSparseLongArray mMeasureCache; 3169 3170 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3171 private Drawable mBackground; 3172 3173 /** 3174 * Display list used for backgrounds. 3175 * <p> 3176 * When non-null and valid, this is expected to contain an up-to-date copy 3177 * of the background drawable. It is cleared on temporary detach and reset 3178 * on cleanup. 3179 */ 3180 private RenderNode mBackgroundDisplayList; 3181 3182 private int mBackgroundResource; 3183 private boolean mBackgroundSizeChanged; 3184 3185 static class ListenerInfo { 3186 /** 3187 * Listener used to dispatch focus change events. 3188 * This field should be made private, so it is hidden from the SDK. 3189 * {@hide} 3190 */ 3191 protected OnFocusChangeListener mOnFocusChangeListener; 3192 3193 /** 3194 * Listeners for layout change events. 3195 */ 3196 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3197 3198 /** 3199 * Listeners for attach events. 3200 */ 3201 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3202 3203 /** 3204 * Listener used to dispatch click events. 3205 * This field should be made private, so it is hidden from the SDK. 3206 * {@hide} 3207 */ 3208 public OnClickListener mOnClickListener; 3209 3210 /** 3211 * Listener used to dispatch long click events. 3212 * This field should be made private, so it is hidden from the SDK. 3213 * {@hide} 3214 */ 3215 protected OnLongClickListener mOnLongClickListener; 3216 3217 /** 3218 * Listener used to build the context menu. 3219 * This field should be made private, so it is hidden from the SDK. 3220 * {@hide} 3221 */ 3222 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3223 3224 private OnKeyListener mOnKeyListener; 3225 3226 private OnTouchListener mOnTouchListener; 3227 3228 private OnHoverListener mOnHoverListener; 3229 3230 private OnGenericMotionListener mOnGenericMotionListener; 3231 3232 private OnDragListener mOnDragListener; 3233 3234 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3235 3236 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3237 } 3238 3239 ListenerInfo mListenerInfo; 3240 3241 /** 3242 * The application environment this view lives in. 3243 * This field should be made private, so it is hidden from the SDK. 3244 * {@hide} 3245 */ 3246 protected Context mContext; 3247 3248 private final Resources mResources; 3249 3250 private ScrollabilityCache mScrollCache; 3251 3252 private int[] mDrawableState = null; 3253 3254 /** 3255 * Stores the outline of the view, passed down to the DisplayList level for 3256 * defining shadow shape. 3257 */ 3258 private Outline mOutline; 3259 3260 /** 3261 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3262 * the user may specify which view to go to next. 3263 */ 3264 private int mNextFocusLeftId = View.NO_ID; 3265 3266 /** 3267 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3268 * the user may specify which view to go to next. 3269 */ 3270 private int mNextFocusRightId = View.NO_ID; 3271 3272 /** 3273 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3274 * the user may specify which view to go to next. 3275 */ 3276 private int mNextFocusUpId = View.NO_ID; 3277 3278 /** 3279 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3280 * the user may specify which view to go to next. 3281 */ 3282 private int mNextFocusDownId = View.NO_ID; 3283 3284 /** 3285 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3286 * the user may specify which view to go to next. 3287 */ 3288 int mNextFocusForwardId = View.NO_ID; 3289 3290 private CheckForLongPress mPendingCheckForLongPress; 3291 private CheckForTap mPendingCheckForTap = null; 3292 private PerformClick mPerformClick; 3293 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3294 3295 private UnsetPressedState mUnsetPressedState; 3296 3297 /** 3298 * Whether the long press's action has been invoked. The tap's action is invoked on the 3299 * up event while a long press is invoked as soon as the long press duration is reached, so 3300 * a long press could be performed before the tap is checked, in which case the tap's action 3301 * should not be invoked. 3302 */ 3303 private boolean mHasPerformedLongPress; 3304 3305 /** 3306 * The minimum height of the view. We'll try our best to have the height 3307 * of this view to at least this amount. 3308 */ 3309 @ViewDebug.ExportedProperty(category = "measurement") 3310 private int mMinHeight; 3311 3312 /** 3313 * The minimum width of the view. We'll try our best to have the width 3314 * of this view to at least this amount. 3315 */ 3316 @ViewDebug.ExportedProperty(category = "measurement") 3317 private int mMinWidth; 3318 3319 /** 3320 * The delegate to handle touch events that are physically in this view 3321 * but should be handled by another view. 3322 */ 3323 private TouchDelegate mTouchDelegate = null; 3324 3325 /** 3326 * Solid color to use as a background when creating the drawing cache. Enables 3327 * the cache to use 16 bit bitmaps instead of 32 bit. 3328 */ 3329 private int mDrawingCacheBackgroundColor = 0; 3330 3331 /** 3332 * Special tree observer used when mAttachInfo is null. 3333 */ 3334 private ViewTreeObserver mFloatingTreeObserver; 3335 3336 /** 3337 * Cache the touch slop from the context that created the view. 3338 */ 3339 private int mTouchSlop; 3340 3341 /** 3342 * Object that handles automatic animation of view properties. 3343 */ 3344 private ViewPropertyAnimator mAnimator = null; 3345 3346 /** 3347 * Flag indicating that a drag can cross window boundaries. When 3348 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3349 * with this flag set, all visible applications will be able to participate 3350 * in the drag operation and receive the dragged content. 3351 * 3352 * @hide 3353 */ 3354 public static final int DRAG_FLAG_GLOBAL = 1; 3355 3356 /** 3357 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3358 */ 3359 private float mVerticalScrollFactor; 3360 3361 /** 3362 * Position of the vertical scroll bar. 3363 */ 3364 private int mVerticalScrollbarPosition; 3365 3366 /** 3367 * Position the scroll bar at the default position as determined by the system. 3368 */ 3369 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3370 3371 /** 3372 * Position the scroll bar along the left edge. 3373 */ 3374 public static final int SCROLLBAR_POSITION_LEFT = 1; 3375 3376 /** 3377 * Position the scroll bar along the right edge. 3378 */ 3379 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3380 3381 /** 3382 * Indicates that the view does not have a layer. 3383 * 3384 * @see #getLayerType() 3385 * @see #setLayerType(int, android.graphics.Paint) 3386 * @see #LAYER_TYPE_SOFTWARE 3387 * @see #LAYER_TYPE_HARDWARE 3388 */ 3389 public static final int LAYER_TYPE_NONE = 0; 3390 3391 /** 3392 * <p>Indicates that the view has a software layer. A software layer is backed 3393 * by a bitmap and causes the view to be rendered using Android's software 3394 * rendering pipeline, even if hardware acceleration is enabled.</p> 3395 * 3396 * <p>Software layers have various usages:</p> 3397 * <p>When the application is not using hardware acceleration, a software layer 3398 * is useful to apply a specific color filter and/or blending mode and/or 3399 * translucency to a view and all its children.</p> 3400 * <p>When the application is using hardware acceleration, a software layer 3401 * is useful to render drawing primitives not supported by the hardware 3402 * accelerated pipeline. It can also be used to cache a complex view tree 3403 * into a texture and reduce the complexity of drawing operations. For instance, 3404 * when animating a complex view tree with a translation, a software layer can 3405 * be used to render the view tree only once.</p> 3406 * <p>Software layers should be avoided when the affected view tree updates 3407 * often. Every update will require to re-render the software layer, which can 3408 * potentially be slow (particularly when hardware acceleration is turned on 3409 * since the layer will have to be uploaded into a hardware texture after every 3410 * update.)</p> 3411 * 3412 * @see #getLayerType() 3413 * @see #setLayerType(int, android.graphics.Paint) 3414 * @see #LAYER_TYPE_NONE 3415 * @see #LAYER_TYPE_HARDWARE 3416 */ 3417 public static final int LAYER_TYPE_SOFTWARE = 1; 3418 3419 /** 3420 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3421 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3422 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3423 * rendering pipeline, but only if hardware acceleration is turned on for the 3424 * view hierarchy. When hardware acceleration is turned off, hardware layers 3425 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3426 * 3427 * <p>A hardware layer is useful to apply a specific color filter and/or 3428 * blending mode and/or translucency to a view and all its children.</p> 3429 * <p>A hardware layer can be used to cache a complex view tree into a 3430 * texture and reduce the complexity of drawing operations. For instance, 3431 * when animating a complex view tree with a translation, a hardware layer can 3432 * be used to render the view tree only once.</p> 3433 * <p>A hardware layer can also be used to increase the rendering quality when 3434 * rotation transformations are applied on a view. It can also be used to 3435 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3436 * 3437 * @see #getLayerType() 3438 * @see #setLayerType(int, android.graphics.Paint) 3439 * @see #LAYER_TYPE_NONE 3440 * @see #LAYER_TYPE_SOFTWARE 3441 */ 3442 public static final int LAYER_TYPE_HARDWARE = 2; 3443 3444 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3445 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3446 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3447 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3448 }) 3449 int mLayerType = LAYER_TYPE_NONE; 3450 Paint mLayerPaint; 3451 Rect mLocalDirtyRect; 3452 private HardwareLayer mHardwareLayer; 3453 3454 /** 3455 * Set to true when drawing cache is enabled and cannot be created. 3456 * 3457 * @hide 3458 */ 3459 public boolean mCachingFailed; 3460 private Bitmap mDrawingCache; 3461 private Bitmap mUnscaledDrawingCache; 3462 3463 /** 3464 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3465 * <p> 3466 * When non-null and valid, this is expected to contain an up-to-date copy 3467 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3468 * cleanup. 3469 */ 3470 final RenderNode mRenderNode; 3471 3472 /** 3473 * Set to true when the view is sending hover accessibility events because it 3474 * is the innermost hovered view. 3475 */ 3476 private boolean mSendingHoverAccessibilityEvents; 3477 3478 /** 3479 * Delegate for injecting accessibility functionality. 3480 */ 3481 AccessibilityDelegate mAccessibilityDelegate; 3482 3483 /** 3484 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3485 * and add/remove objects to/from the overlay directly through the Overlay methods. 3486 */ 3487 ViewOverlay mOverlay; 3488 3489 /** 3490 * The currently active parent view for receiving delegated nested scrolling events. 3491 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3492 * by {@link #stopNestedScroll()} at the same point where we clear 3493 * requestDisallowInterceptTouchEvent. 3494 */ 3495 private ViewParent mNestedScrollingParent; 3496 3497 /** 3498 * Consistency verifier for debugging purposes. 3499 * @hide 3500 */ 3501 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3502 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3503 new InputEventConsistencyVerifier(this, 0) : null; 3504 3505 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3506 3507 private int[] mTempNestedScrollConsumed; 3508 3509 /** 3510 * Simple constructor to use when creating a view from code. 3511 * 3512 * @param context The Context the view is running in, through which it can 3513 * access the current theme, resources, etc. 3514 */ 3515 public View(Context context) { 3516 mContext = context; 3517 mResources = context != null ? context.getResources() : null; 3518 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3519 // Set some flags defaults 3520 mPrivateFlags2 = 3521 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3522 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3523 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3524 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3525 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3526 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3527 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3528 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3529 mUserPaddingStart = UNDEFINED_PADDING; 3530 mUserPaddingEnd = UNDEFINED_PADDING; 3531 mRenderNode = RenderNode.create(getClass().getName()); 3532 3533 if (!sCompatibilityDone && context != null) { 3534 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3535 3536 // Older apps may need this compatibility hack for measurement. 3537 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3538 3539 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3540 // of whether a layout was requested on that View. 3541 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3542 3543 // Older apps may need this to ignore the clip bounds 3544 sIgnoreClipBoundsForChildren = targetSdkVersion < L; 3545 3546 sCompatibilityDone = true; 3547 } 3548 } 3549 3550 /** 3551 * Constructor that is called when inflating a view from XML. This is called 3552 * when a view is being constructed from an XML file, supplying attributes 3553 * that were specified in the XML file. This version uses a default style of 3554 * 0, so the only attribute values applied are those in the Context's Theme 3555 * and the given AttributeSet. 3556 * 3557 * <p> 3558 * The method onFinishInflate() will be called after all children have been 3559 * added. 3560 * 3561 * @param context The Context the view is running in, through which it can 3562 * access the current theme, resources, etc. 3563 * @param attrs The attributes of the XML tag that is inflating the view. 3564 * @see #View(Context, AttributeSet, int) 3565 */ 3566 public View(Context context, AttributeSet attrs) { 3567 this(context, attrs, 0); 3568 } 3569 3570 /** 3571 * Perform inflation from XML and apply a class-specific base style from a 3572 * theme attribute. This constructor of View allows subclasses to use their 3573 * own base style when they are inflating. For example, a Button class's 3574 * constructor would call this version of the super class constructor and 3575 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3576 * allows the theme's button style to modify all of the base view attributes 3577 * (in particular its background) as well as the Button class's attributes. 3578 * 3579 * @param context The Context the view is running in, through which it can 3580 * access the current theme, resources, etc. 3581 * @param attrs The attributes of the XML tag that is inflating the view. 3582 * @param defStyleAttr An attribute in the current theme that contains a 3583 * reference to a style resource that supplies default values for 3584 * the view. Can be 0 to not look for defaults. 3585 * @see #View(Context, AttributeSet) 3586 */ 3587 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3588 this(context, attrs, defStyleAttr, 0); 3589 } 3590 3591 /** 3592 * Perform inflation from XML and apply a class-specific base style from a 3593 * theme attribute or style resource. This constructor of View allows 3594 * subclasses to use their own base style when they are inflating. 3595 * <p> 3596 * When determining the final value of a particular attribute, there are 3597 * four inputs that come into play: 3598 * <ol> 3599 * <li>Any attribute values in the given AttributeSet. 3600 * <li>The style resource specified in the AttributeSet (named "style"). 3601 * <li>The default style specified by <var>defStyleAttr</var>. 3602 * <li>The default style specified by <var>defStyleRes</var>. 3603 * <li>The base values in this theme. 3604 * </ol> 3605 * <p> 3606 * Each of these inputs is considered in-order, with the first listed taking 3607 * precedence over the following ones. In other words, if in the 3608 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3609 * , then the button's text will <em>always</em> be black, regardless of 3610 * what is specified in any of the styles. 3611 * 3612 * @param context The Context the view is running in, through which it can 3613 * access the current theme, resources, etc. 3614 * @param attrs The attributes of the XML tag that is inflating the view. 3615 * @param defStyleAttr An attribute in the current theme that contains a 3616 * reference to a style resource that supplies default values for 3617 * the view. Can be 0 to not look for defaults. 3618 * @param defStyleRes A resource identifier of a style resource that 3619 * supplies default values for the view, used only if 3620 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3621 * to not look for defaults. 3622 * @see #View(Context, AttributeSet, int) 3623 */ 3624 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3625 this(context); 3626 3627 final TypedArray a = context.obtainStyledAttributes( 3628 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3629 3630 Drawable background = null; 3631 3632 int leftPadding = -1; 3633 int topPadding = -1; 3634 int rightPadding = -1; 3635 int bottomPadding = -1; 3636 int startPadding = UNDEFINED_PADDING; 3637 int endPadding = UNDEFINED_PADDING; 3638 3639 int padding = -1; 3640 3641 int viewFlagValues = 0; 3642 int viewFlagMasks = 0; 3643 3644 boolean setScrollContainer = false; 3645 3646 int x = 0; 3647 int y = 0; 3648 3649 float tx = 0; 3650 float ty = 0; 3651 float tz = 0; 3652 float elevation = 0; 3653 float rotation = 0; 3654 float rotationX = 0; 3655 float rotationY = 0; 3656 float sx = 1f; 3657 float sy = 1f; 3658 boolean transformSet = false; 3659 3660 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3661 int overScrollMode = mOverScrollMode; 3662 boolean initializeScrollbars = false; 3663 3664 boolean startPaddingDefined = false; 3665 boolean endPaddingDefined = false; 3666 boolean leftPaddingDefined = false; 3667 boolean rightPaddingDefined = false; 3668 3669 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3670 3671 final int N = a.getIndexCount(); 3672 for (int i = 0; i < N; i++) { 3673 int attr = a.getIndex(i); 3674 switch (attr) { 3675 case com.android.internal.R.styleable.View_background: 3676 background = a.getDrawable(attr); 3677 break; 3678 case com.android.internal.R.styleable.View_padding: 3679 padding = a.getDimensionPixelSize(attr, -1); 3680 mUserPaddingLeftInitial = padding; 3681 mUserPaddingRightInitial = padding; 3682 leftPaddingDefined = true; 3683 rightPaddingDefined = true; 3684 break; 3685 case com.android.internal.R.styleable.View_paddingLeft: 3686 leftPadding = a.getDimensionPixelSize(attr, -1); 3687 mUserPaddingLeftInitial = leftPadding; 3688 leftPaddingDefined = true; 3689 break; 3690 case com.android.internal.R.styleable.View_paddingTop: 3691 topPadding = a.getDimensionPixelSize(attr, -1); 3692 break; 3693 case com.android.internal.R.styleable.View_paddingRight: 3694 rightPadding = a.getDimensionPixelSize(attr, -1); 3695 mUserPaddingRightInitial = rightPadding; 3696 rightPaddingDefined = true; 3697 break; 3698 case com.android.internal.R.styleable.View_paddingBottom: 3699 bottomPadding = a.getDimensionPixelSize(attr, -1); 3700 break; 3701 case com.android.internal.R.styleable.View_paddingStart: 3702 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3703 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3704 break; 3705 case com.android.internal.R.styleable.View_paddingEnd: 3706 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3707 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3708 break; 3709 case com.android.internal.R.styleable.View_scrollX: 3710 x = a.getDimensionPixelOffset(attr, 0); 3711 break; 3712 case com.android.internal.R.styleable.View_scrollY: 3713 y = a.getDimensionPixelOffset(attr, 0); 3714 break; 3715 case com.android.internal.R.styleable.View_alpha: 3716 setAlpha(a.getFloat(attr, 1f)); 3717 break; 3718 case com.android.internal.R.styleable.View_transformPivotX: 3719 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3720 break; 3721 case com.android.internal.R.styleable.View_transformPivotY: 3722 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3723 break; 3724 case com.android.internal.R.styleable.View_translationX: 3725 tx = a.getDimensionPixelOffset(attr, 0); 3726 transformSet = true; 3727 break; 3728 case com.android.internal.R.styleable.View_translationY: 3729 ty = a.getDimensionPixelOffset(attr, 0); 3730 transformSet = true; 3731 break; 3732 case com.android.internal.R.styleable.View_translationZ: 3733 tz = a.getDimensionPixelOffset(attr, 0); 3734 transformSet = true; 3735 break; 3736 case com.android.internal.R.styleable.View_elevation: 3737 elevation = a.getDimensionPixelOffset(attr, 0); 3738 transformSet = true; 3739 break; 3740 case com.android.internal.R.styleable.View_rotation: 3741 rotation = a.getFloat(attr, 0); 3742 transformSet = true; 3743 break; 3744 case com.android.internal.R.styleable.View_rotationX: 3745 rotationX = a.getFloat(attr, 0); 3746 transformSet = true; 3747 break; 3748 case com.android.internal.R.styleable.View_rotationY: 3749 rotationY = a.getFloat(attr, 0); 3750 transformSet = true; 3751 break; 3752 case com.android.internal.R.styleable.View_scaleX: 3753 sx = a.getFloat(attr, 1f); 3754 transformSet = true; 3755 break; 3756 case com.android.internal.R.styleable.View_scaleY: 3757 sy = a.getFloat(attr, 1f); 3758 transformSet = true; 3759 break; 3760 case com.android.internal.R.styleable.View_id: 3761 mID = a.getResourceId(attr, NO_ID); 3762 break; 3763 case com.android.internal.R.styleable.View_tag: 3764 mTag = a.getText(attr); 3765 break; 3766 case com.android.internal.R.styleable.View_fitsSystemWindows: 3767 if (a.getBoolean(attr, false)) { 3768 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3769 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3770 } 3771 break; 3772 case com.android.internal.R.styleable.View_focusable: 3773 if (a.getBoolean(attr, false)) { 3774 viewFlagValues |= FOCUSABLE; 3775 viewFlagMasks |= FOCUSABLE_MASK; 3776 } 3777 break; 3778 case com.android.internal.R.styleable.View_focusableInTouchMode: 3779 if (a.getBoolean(attr, false)) { 3780 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3781 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3782 } 3783 break; 3784 case com.android.internal.R.styleable.View_clickable: 3785 if (a.getBoolean(attr, false)) { 3786 viewFlagValues |= CLICKABLE; 3787 viewFlagMasks |= CLICKABLE; 3788 } 3789 break; 3790 case com.android.internal.R.styleable.View_longClickable: 3791 if (a.getBoolean(attr, false)) { 3792 viewFlagValues |= LONG_CLICKABLE; 3793 viewFlagMasks |= LONG_CLICKABLE; 3794 } 3795 break; 3796 case com.android.internal.R.styleable.View_saveEnabled: 3797 if (!a.getBoolean(attr, true)) { 3798 viewFlagValues |= SAVE_DISABLED; 3799 viewFlagMasks |= SAVE_DISABLED_MASK; 3800 } 3801 break; 3802 case com.android.internal.R.styleable.View_duplicateParentState: 3803 if (a.getBoolean(attr, false)) { 3804 viewFlagValues |= DUPLICATE_PARENT_STATE; 3805 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3806 } 3807 break; 3808 case com.android.internal.R.styleable.View_visibility: 3809 final int visibility = a.getInt(attr, 0); 3810 if (visibility != 0) { 3811 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3812 viewFlagMasks |= VISIBILITY_MASK; 3813 } 3814 break; 3815 case com.android.internal.R.styleable.View_layoutDirection: 3816 // Clear any layout direction flags (included resolved bits) already set 3817 mPrivateFlags2 &= 3818 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3819 // Set the layout direction flags depending on the value of the attribute 3820 final int layoutDirection = a.getInt(attr, -1); 3821 final int value = (layoutDirection != -1) ? 3822 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3823 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3824 break; 3825 case com.android.internal.R.styleable.View_drawingCacheQuality: 3826 final int cacheQuality = a.getInt(attr, 0); 3827 if (cacheQuality != 0) { 3828 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3829 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3830 } 3831 break; 3832 case com.android.internal.R.styleable.View_contentDescription: 3833 setContentDescription(a.getString(attr)); 3834 break; 3835 case com.android.internal.R.styleable.View_labelFor: 3836 setLabelFor(a.getResourceId(attr, NO_ID)); 3837 break; 3838 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3839 if (!a.getBoolean(attr, true)) { 3840 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3841 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3842 } 3843 break; 3844 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3845 if (!a.getBoolean(attr, true)) { 3846 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3847 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3848 } 3849 break; 3850 case R.styleable.View_scrollbars: 3851 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3852 if (scrollbars != SCROLLBARS_NONE) { 3853 viewFlagValues |= scrollbars; 3854 viewFlagMasks |= SCROLLBARS_MASK; 3855 initializeScrollbars = true; 3856 } 3857 break; 3858 //noinspection deprecation 3859 case R.styleable.View_fadingEdge: 3860 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3861 // Ignore the attribute starting with ICS 3862 break; 3863 } 3864 // With builds < ICS, fall through and apply fading edges 3865 case R.styleable.View_requiresFadingEdge: 3866 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3867 if (fadingEdge != FADING_EDGE_NONE) { 3868 viewFlagValues |= fadingEdge; 3869 viewFlagMasks |= FADING_EDGE_MASK; 3870 initializeFadingEdge(a); 3871 } 3872 break; 3873 case R.styleable.View_scrollbarStyle: 3874 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3875 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3876 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3877 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3878 } 3879 break; 3880 case R.styleable.View_isScrollContainer: 3881 setScrollContainer = true; 3882 if (a.getBoolean(attr, false)) { 3883 setScrollContainer(true); 3884 } 3885 break; 3886 case com.android.internal.R.styleable.View_keepScreenOn: 3887 if (a.getBoolean(attr, false)) { 3888 viewFlagValues |= KEEP_SCREEN_ON; 3889 viewFlagMasks |= KEEP_SCREEN_ON; 3890 } 3891 break; 3892 case R.styleable.View_filterTouchesWhenObscured: 3893 if (a.getBoolean(attr, false)) { 3894 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3895 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3896 } 3897 break; 3898 case R.styleable.View_nextFocusLeft: 3899 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3900 break; 3901 case R.styleable.View_nextFocusRight: 3902 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3903 break; 3904 case R.styleable.View_nextFocusUp: 3905 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3906 break; 3907 case R.styleable.View_nextFocusDown: 3908 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3909 break; 3910 case R.styleable.View_nextFocusForward: 3911 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3912 break; 3913 case R.styleable.View_minWidth: 3914 mMinWidth = a.getDimensionPixelSize(attr, 0); 3915 break; 3916 case R.styleable.View_minHeight: 3917 mMinHeight = a.getDimensionPixelSize(attr, 0); 3918 break; 3919 case R.styleable.View_onClick: 3920 if (context.isRestricted()) { 3921 throw new IllegalStateException("The android:onClick attribute cannot " 3922 + "be used within a restricted context"); 3923 } 3924 3925 final String handlerName = a.getString(attr); 3926 if (handlerName != null) { 3927 setOnClickListener(new OnClickListener() { 3928 private Method mHandler; 3929 3930 public void onClick(View v) { 3931 if (mHandler == null) { 3932 try { 3933 mHandler = getContext().getClass().getMethod(handlerName, 3934 View.class); 3935 } catch (NoSuchMethodException e) { 3936 int id = getId(); 3937 String idText = id == NO_ID ? "" : " with id '" 3938 + getContext().getResources().getResourceEntryName( 3939 id) + "'"; 3940 throw new IllegalStateException("Could not find a method " + 3941 handlerName + "(View) in the activity " 3942 + getContext().getClass() + " for onClick handler" 3943 + " on view " + View.this.getClass() + idText, e); 3944 } 3945 } 3946 3947 try { 3948 mHandler.invoke(getContext(), View.this); 3949 } catch (IllegalAccessException e) { 3950 throw new IllegalStateException("Could not execute non " 3951 + "public method of the activity", e); 3952 } catch (InvocationTargetException e) { 3953 throw new IllegalStateException("Could not execute " 3954 + "method of the activity", e); 3955 } 3956 } 3957 }); 3958 } 3959 break; 3960 case R.styleable.View_overScrollMode: 3961 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3962 break; 3963 case R.styleable.View_verticalScrollbarPosition: 3964 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3965 break; 3966 case R.styleable.View_layerType: 3967 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3968 break; 3969 case R.styleable.View_textDirection: 3970 // Clear any text direction flag already set 3971 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3972 // Set the text direction flags depending on the value of the attribute 3973 final int textDirection = a.getInt(attr, -1); 3974 if (textDirection != -1) { 3975 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3976 } 3977 break; 3978 case R.styleable.View_textAlignment: 3979 // Clear any text alignment flag already set 3980 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3981 // Set the text alignment flag depending on the value of the attribute 3982 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3983 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 3984 break; 3985 case R.styleable.View_importantForAccessibility: 3986 setImportantForAccessibility(a.getInt(attr, 3987 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 3988 break; 3989 case R.styleable.View_accessibilityLiveRegion: 3990 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 3991 break; 3992 case R.styleable.View_sharedElementName: 3993 setSharedElementName(a.getString(attr)); 3994 break; 3995 case R.styleable.View_nestedScrollingEnabled: 3996 setNestedScrollingEnabled(a.getBoolean(attr, false)); 3997 break; 3998 } 3999 } 4000 4001 setOverScrollMode(overScrollMode); 4002 4003 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4004 // the resolved layout direction). Those cached values will be used later during padding 4005 // resolution. 4006 mUserPaddingStart = startPadding; 4007 mUserPaddingEnd = endPadding; 4008 4009 if (background != null) { 4010 setBackground(background); 4011 } 4012 4013 // setBackground above will record that padding is currently provided by the background. 4014 // If we have padding specified via xml, record that here instead and use it. 4015 mLeftPaddingDefined = leftPaddingDefined; 4016 mRightPaddingDefined = rightPaddingDefined; 4017 4018 if (padding >= 0) { 4019 leftPadding = padding; 4020 topPadding = padding; 4021 rightPadding = padding; 4022 bottomPadding = padding; 4023 mUserPaddingLeftInitial = padding; 4024 mUserPaddingRightInitial = padding; 4025 } 4026 4027 if (isRtlCompatibilityMode()) { 4028 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4029 // left / right padding are used if defined (meaning here nothing to do). If they are not 4030 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4031 // start / end and resolve them as left / right (layout direction is not taken into account). 4032 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4033 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4034 // defined. 4035 if (!mLeftPaddingDefined && startPaddingDefined) { 4036 leftPadding = startPadding; 4037 } 4038 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4039 if (!mRightPaddingDefined && endPaddingDefined) { 4040 rightPadding = endPadding; 4041 } 4042 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4043 } else { 4044 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4045 // values defined. Otherwise, left /right values are used. 4046 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4047 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4048 // defined. 4049 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4050 4051 if (mLeftPaddingDefined && !hasRelativePadding) { 4052 mUserPaddingLeftInitial = leftPadding; 4053 } 4054 if (mRightPaddingDefined && !hasRelativePadding) { 4055 mUserPaddingRightInitial = rightPadding; 4056 } 4057 } 4058 4059 internalSetPadding( 4060 mUserPaddingLeftInitial, 4061 topPadding >= 0 ? topPadding : mPaddingTop, 4062 mUserPaddingRightInitial, 4063 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4064 4065 if (viewFlagMasks != 0) { 4066 setFlags(viewFlagValues, viewFlagMasks); 4067 } 4068 4069 if (initializeScrollbars) { 4070 initializeScrollbars(a); 4071 } 4072 4073 a.recycle(); 4074 4075 // Needs to be called after mViewFlags is set 4076 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4077 recomputePadding(); 4078 } 4079 4080 if (x != 0 || y != 0) { 4081 scrollTo(x, y); 4082 } 4083 4084 if (transformSet) { 4085 setTranslationX(tx); 4086 setTranslationY(ty); 4087 setTranslationZ(tz); 4088 setElevation(elevation); 4089 setRotation(rotation); 4090 setRotationX(rotationX); 4091 setRotationY(rotationY); 4092 setScaleX(sx); 4093 setScaleY(sy); 4094 } 4095 4096 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4097 setScrollContainer(true); 4098 } 4099 4100 computeOpaqueFlags(); 4101 } 4102 4103 /** 4104 * Non-public constructor for use in testing 4105 */ 4106 View() { 4107 mResources = null; 4108 mRenderNode = RenderNode.create(getClass().getName()); 4109 } 4110 4111 public String toString() { 4112 StringBuilder out = new StringBuilder(128); 4113 out.append(getClass().getName()); 4114 out.append('{'); 4115 out.append(Integer.toHexString(System.identityHashCode(this))); 4116 out.append(' '); 4117 switch (mViewFlags&VISIBILITY_MASK) { 4118 case VISIBLE: out.append('V'); break; 4119 case INVISIBLE: out.append('I'); break; 4120 case GONE: out.append('G'); break; 4121 default: out.append('.'); break; 4122 } 4123 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4124 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4125 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4126 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4127 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4128 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4129 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4130 out.append(' '); 4131 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4132 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4133 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4134 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4135 out.append('p'); 4136 } else { 4137 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4138 } 4139 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4140 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4141 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4142 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4143 out.append(' '); 4144 out.append(mLeft); 4145 out.append(','); 4146 out.append(mTop); 4147 out.append('-'); 4148 out.append(mRight); 4149 out.append(','); 4150 out.append(mBottom); 4151 final int id = getId(); 4152 if (id != NO_ID) { 4153 out.append(" #"); 4154 out.append(Integer.toHexString(id)); 4155 final Resources r = mResources; 4156 if (Resources.resourceHasPackage(id) && r != null) { 4157 try { 4158 String pkgname; 4159 switch (id&0xff000000) { 4160 case 0x7f000000: 4161 pkgname="app"; 4162 break; 4163 case 0x01000000: 4164 pkgname="android"; 4165 break; 4166 default: 4167 pkgname = r.getResourcePackageName(id); 4168 break; 4169 } 4170 String typename = r.getResourceTypeName(id); 4171 String entryname = r.getResourceEntryName(id); 4172 out.append(" "); 4173 out.append(pkgname); 4174 out.append(":"); 4175 out.append(typename); 4176 out.append("/"); 4177 out.append(entryname); 4178 } catch (Resources.NotFoundException e) { 4179 } 4180 } 4181 } 4182 out.append("}"); 4183 return out.toString(); 4184 } 4185 4186 /** 4187 * <p> 4188 * Initializes the fading edges from a given set of styled attributes. This 4189 * method should be called by subclasses that need fading edges and when an 4190 * instance of these subclasses is created programmatically rather than 4191 * being inflated from XML. This method is automatically called when the XML 4192 * is inflated. 4193 * </p> 4194 * 4195 * @param a the styled attributes set to initialize the fading edges from 4196 */ 4197 protected void initializeFadingEdge(TypedArray a) { 4198 initScrollCache(); 4199 4200 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4201 R.styleable.View_fadingEdgeLength, 4202 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4203 } 4204 4205 /** 4206 * Returns the size of the vertical faded edges used to indicate that more 4207 * content in this view is visible. 4208 * 4209 * @return The size in pixels of the vertical faded edge or 0 if vertical 4210 * faded edges are not enabled for this view. 4211 * @attr ref android.R.styleable#View_fadingEdgeLength 4212 */ 4213 public int getVerticalFadingEdgeLength() { 4214 if (isVerticalFadingEdgeEnabled()) { 4215 ScrollabilityCache cache = mScrollCache; 4216 if (cache != null) { 4217 return cache.fadingEdgeLength; 4218 } 4219 } 4220 return 0; 4221 } 4222 4223 /** 4224 * Set the size of the faded edge used to indicate that more content in this 4225 * view is available. Will not change whether the fading edge is enabled; use 4226 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4227 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4228 * for the vertical or horizontal fading edges. 4229 * 4230 * @param length The size in pixels of the faded edge used to indicate that more 4231 * content in this view is visible. 4232 */ 4233 public void setFadingEdgeLength(int length) { 4234 initScrollCache(); 4235 mScrollCache.fadingEdgeLength = length; 4236 } 4237 4238 /** 4239 * Returns the size of the horizontal faded edges used to indicate that more 4240 * content in this view is visible. 4241 * 4242 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4243 * faded edges are not enabled for this view. 4244 * @attr ref android.R.styleable#View_fadingEdgeLength 4245 */ 4246 public int getHorizontalFadingEdgeLength() { 4247 if (isHorizontalFadingEdgeEnabled()) { 4248 ScrollabilityCache cache = mScrollCache; 4249 if (cache != null) { 4250 return cache.fadingEdgeLength; 4251 } 4252 } 4253 return 0; 4254 } 4255 4256 /** 4257 * Returns the width of the vertical scrollbar. 4258 * 4259 * @return The width in pixels of the vertical scrollbar or 0 if there 4260 * is no vertical scrollbar. 4261 */ 4262 public int getVerticalScrollbarWidth() { 4263 ScrollabilityCache cache = mScrollCache; 4264 if (cache != null) { 4265 ScrollBarDrawable scrollBar = cache.scrollBar; 4266 if (scrollBar != null) { 4267 int size = scrollBar.getSize(true); 4268 if (size <= 0) { 4269 size = cache.scrollBarSize; 4270 } 4271 return size; 4272 } 4273 return 0; 4274 } 4275 return 0; 4276 } 4277 4278 /** 4279 * Returns the height of the horizontal scrollbar. 4280 * 4281 * @return The height in pixels of the horizontal scrollbar or 0 if 4282 * there is no horizontal scrollbar. 4283 */ 4284 protected int getHorizontalScrollbarHeight() { 4285 ScrollabilityCache cache = mScrollCache; 4286 if (cache != null) { 4287 ScrollBarDrawable scrollBar = cache.scrollBar; 4288 if (scrollBar != null) { 4289 int size = scrollBar.getSize(false); 4290 if (size <= 0) { 4291 size = cache.scrollBarSize; 4292 } 4293 return size; 4294 } 4295 return 0; 4296 } 4297 return 0; 4298 } 4299 4300 /** 4301 * <p> 4302 * Initializes the scrollbars from a given set of styled attributes. This 4303 * method should be called by subclasses that need scrollbars and when an 4304 * instance of these subclasses is created programmatically rather than 4305 * being inflated from XML. This method is automatically called when the XML 4306 * is inflated. 4307 * </p> 4308 * 4309 * @param a the styled attributes set to initialize the scrollbars from 4310 */ 4311 protected void initializeScrollbars(TypedArray a) { 4312 initScrollCache(); 4313 4314 final ScrollabilityCache scrollabilityCache = mScrollCache; 4315 4316 if (scrollabilityCache.scrollBar == null) { 4317 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4318 } 4319 4320 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4321 4322 if (!fadeScrollbars) { 4323 scrollabilityCache.state = ScrollabilityCache.ON; 4324 } 4325 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4326 4327 4328 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4329 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4330 .getScrollBarFadeDuration()); 4331 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4332 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4333 ViewConfiguration.getScrollDefaultDelay()); 4334 4335 4336 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4337 com.android.internal.R.styleable.View_scrollbarSize, 4338 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4339 4340 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4341 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4342 4343 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4344 if (thumb != null) { 4345 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4346 } 4347 4348 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4349 false); 4350 if (alwaysDraw) { 4351 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4352 } 4353 4354 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4355 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4356 4357 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4358 if (thumb != null) { 4359 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4360 } 4361 4362 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4363 false); 4364 if (alwaysDraw) { 4365 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4366 } 4367 4368 // Apply layout direction to the new Drawables if needed 4369 final int layoutDirection = getLayoutDirection(); 4370 if (track != null) { 4371 track.setLayoutDirection(layoutDirection); 4372 } 4373 if (thumb != null) { 4374 thumb.setLayoutDirection(layoutDirection); 4375 } 4376 4377 // Re-apply user/background padding so that scrollbar(s) get added 4378 resolvePadding(); 4379 } 4380 4381 /** 4382 * <p> 4383 * Initalizes the scrollability cache if necessary. 4384 * </p> 4385 */ 4386 private void initScrollCache() { 4387 if (mScrollCache == null) { 4388 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4389 } 4390 } 4391 4392 private ScrollabilityCache getScrollCache() { 4393 initScrollCache(); 4394 return mScrollCache; 4395 } 4396 4397 /** 4398 * Set the position of the vertical scroll bar. Should be one of 4399 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4400 * {@link #SCROLLBAR_POSITION_RIGHT}. 4401 * 4402 * @param position Where the vertical scroll bar should be positioned. 4403 */ 4404 public void setVerticalScrollbarPosition(int position) { 4405 if (mVerticalScrollbarPosition != position) { 4406 mVerticalScrollbarPosition = position; 4407 computeOpaqueFlags(); 4408 resolvePadding(); 4409 } 4410 } 4411 4412 /** 4413 * @return The position where the vertical scroll bar will show, if applicable. 4414 * @see #setVerticalScrollbarPosition(int) 4415 */ 4416 public int getVerticalScrollbarPosition() { 4417 return mVerticalScrollbarPosition; 4418 } 4419 4420 ListenerInfo getListenerInfo() { 4421 if (mListenerInfo != null) { 4422 return mListenerInfo; 4423 } 4424 mListenerInfo = new ListenerInfo(); 4425 return mListenerInfo; 4426 } 4427 4428 /** 4429 * Register a callback to be invoked when focus of this view changed. 4430 * 4431 * @param l The callback that will run. 4432 */ 4433 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4434 getListenerInfo().mOnFocusChangeListener = l; 4435 } 4436 4437 /** 4438 * Add a listener that will be called when the bounds of the view change due to 4439 * layout processing. 4440 * 4441 * @param listener The listener that will be called when layout bounds change. 4442 */ 4443 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4444 ListenerInfo li = getListenerInfo(); 4445 if (li.mOnLayoutChangeListeners == null) { 4446 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4447 } 4448 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4449 li.mOnLayoutChangeListeners.add(listener); 4450 } 4451 } 4452 4453 /** 4454 * Remove a listener for layout changes. 4455 * 4456 * @param listener The listener for layout bounds change. 4457 */ 4458 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4459 ListenerInfo li = mListenerInfo; 4460 if (li == null || li.mOnLayoutChangeListeners == null) { 4461 return; 4462 } 4463 li.mOnLayoutChangeListeners.remove(listener); 4464 } 4465 4466 /** 4467 * Add a listener for attach state changes. 4468 * 4469 * This listener will be called whenever this view is attached or detached 4470 * from a window. Remove the listener using 4471 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4472 * 4473 * @param listener Listener to attach 4474 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4475 */ 4476 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4477 ListenerInfo li = getListenerInfo(); 4478 if (li.mOnAttachStateChangeListeners == null) { 4479 li.mOnAttachStateChangeListeners 4480 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4481 } 4482 li.mOnAttachStateChangeListeners.add(listener); 4483 } 4484 4485 /** 4486 * Remove a listener for attach state changes. The listener will receive no further 4487 * notification of window attach/detach events. 4488 * 4489 * @param listener Listener to remove 4490 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4491 */ 4492 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4493 ListenerInfo li = mListenerInfo; 4494 if (li == null || li.mOnAttachStateChangeListeners == null) { 4495 return; 4496 } 4497 li.mOnAttachStateChangeListeners.remove(listener); 4498 } 4499 4500 /** 4501 * Returns the focus-change callback registered for this view. 4502 * 4503 * @return The callback, or null if one is not registered. 4504 */ 4505 public OnFocusChangeListener getOnFocusChangeListener() { 4506 ListenerInfo li = mListenerInfo; 4507 return li != null ? li.mOnFocusChangeListener : null; 4508 } 4509 4510 /** 4511 * Register a callback to be invoked when this view is clicked. If this view is not 4512 * clickable, it becomes clickable. 4513 * 4514 * @param l The callback that will run 4515 * 4516 * @see #setClickable(boolean) 4517 */ 4518 public void setOnClickListener(OnClickListener l) { 4519 if (!isClickable()) { 4520 setClickable(true); 4521 } 4522 getListenerInfo().mOnClickListener = l; 4523 } 4524 4525 /** 4526 * Return whether this view has an attached OnClickListener. Returns 4527 * true if there is a listener, false if there is none. 4528 */ 4529 public boolean hasOnClickListeners() { 4530 ListenerInfo li = mListenerInfo; 4531 return (li != null && li.mOnClickListener != null); 4532 } 4533 4534 /** 4535 * Register a callback to be invoked when this view is clicked and held. If this view is not 4536 * long clickable, it becomes long clickable. 4537 * 4538 * @param l The callback that will run 4539 * 4540 * @see #setLongClickable(boolean) 4541 */ 4542 public void setOnLongClickListener(OnLongClickListener l) { 4543 if (!isLongClickable()) { 4544 setLongClickable(true); 4545 } 4546 getListenerInfo().mOnLongClickListener = l; 4547 } 4548 4549 /** 4550 * Register a callback to be invoked when the context menu for this view is 4551 * being built. If this view is not long clickable, it becomes long clickable. 4552 * 4553 * @param l The callback that will run 4554 * 4555 */ 4556 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4557 if (!isLongClickable()) { 4558 setLongClickable(true); 4559 } 4560 getListenerInfo().mOnCreateContextMenuListener = l; 4561 } 4562 4563 /** 4564 * Call this view's OnClickListener, if it is defined. Performs all normal 4565 * actions associated with clicking: reporting accessibility event, playing 4566 * a sound, etc. 4567 * 4568 * @return True there was an assigned OnClickListener that was called, false 4569 * otherwise is returned. 4570 */ 4571 public boolean performClick() { 4572 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4573 4574 ListenerInfo li = mListenerInfo; 4575 if (li != null && li.mOnClickListener != null) { 4576 playSoundEffect(SoundEffectConstants.CLICK); 4577 li.mOnClickListener.onClick(this); 4578 return true; 4579 } 4580 4581 return false; 4582 } 4583 4584 /** 4585 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4586 * this only calls the listener, and does not do any associated clicking 4587 * actions like reporting an accessibility event. 4588 * 4589 * @return True there was an assigned OnClickListener that was called, false 4590 * otherwise is returned. 4591 */ 4592 public boolean callOnClick() { 4593 ListenerInfo li = mListenerInfo; 4594 if (li != null && li.mOnClickListener != null) { 4595 li.mOnClickListener.onClick(this); 4596 return true; 4597 } 4598 return false; 4599 } 4600 4601 /** 4602 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4603 * OnLongClickListener did not consume the event. 4604 * 4605 * @return True if one of the above receivers consumed the event, false otherwise. 4606 */ 4607 public boolean performLongClick() { 4608 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4609 4610 boolean handled = false; 4611 ListenerInfo li = mListenerInfo; 4612 if (li != null && li.mOnLongClickListener != null) { 4613 handled = li.mOnLongClickListener.onLongClick(View.this); 4614 } 4615 if (!handled) { 4616 handled = showContextMenu(); 4617 } 4618 if (handled) { 4619 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4620 } 4621 return handled; 4622 } 4623 4624 /** 4625 * Performs button-related actions during a touch down event. 4626 * 4627 * @param event The event. 4628 * @return True if the down was consumed. 4629 * 4630 * @hide 4631 */ 4632 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4633 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4634 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4635 return true; 4636 } 4637 } 4638 return false; 4639 } 4640 4641 /** 4642 * Bring up the context menu for this view. 4643 * 4644 * @return Whether a context menu was displayed. 4645 */ 4646 public boolean showContextMenu() { 4647 return getParent().showContextMenuForChild(this); 4648 } 4649 4650 /** 4651 * Bring up the context menu for this view, referring to the item under the specified point. 4652 * 4653 * @param x The referenced x coordinate. 4654 * @param y The referenced y coordinate. 4655 * @param metaState The keyboard modifiers that were pressed. 4656 * @return Whether a context menu was displayed. 4657 * 4658 * @hide 4659 */ 4660 public boolean showContextMenu(float x, float y, int metaState) { 4661 return showContextMenu(); 4662 } 4663 4664 /** 4665 * Start an action mode. 4666 * 4667 * @param callback Callback that will control the lifecycle of the action mode 4668 * @return The new action mode if it is started, null otherwise 4669 * 4670 * @see ActionMode 4671 */ 4672 public ActionMode startActionMode(ActionMode.Callback callback) { 4673 ViewParent parent = getParent(); 4674 if (parent == null) return null; 4675 return parent.startActionModeForChild(this, callback); 4676 } 4677 4678 /** 4679 * Register a callback to be invoked when a hardware key is pressed in this view. 4680 * Key presses in software input methods will generally not trigger the methods of 4681 * this listener. 4682 * @param l the key listener to attach to this view 4683 */ 4684 public void setOnKeyListener(OnKeyListener l) { 4685 getListenerInfo().mOnKeyListener = l; 4686 } 4687 4688 /** 4689 * Register a callback to be invoked when a touch event is sent to this view. 4690 * @param l the touch listener to attach to this view 4691 */ 4692 public void setOnTouchListener(OnTouchListener l) { 4693 getListenerInfo().mOnTouchListener = l; 4694 } 4695 4696 /** 4697 * Register a callback to be invoked when a generic motion event is sent to this view. 4698 * @param l the generic motion listener to attach to this view 4699 */ 4700 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4701 getListenerInfo().mOnGenericMotionListener = l; 4702 } 4703 4704 /** 4705 * Register a callback to be invoked when a hover event is sent to this view. 4706 * @param l the hover listener to attach to this view 4707 */ 4708 public void setOnHoverListener(OnHoverListener l) { 4709 getListenerInfo().mOnHoverListener = l; 4710 } 4711 4712 /** 4713 * Register a drag event listener callback object for this View. The parameter is 4714 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4715 * View, the system calls the 4716 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4717 * @param l An implementation of {@link android.view.View.OnDragListener}. 4718 */ 4719 public void setOnDragListener(OnDragListener l) { 4720 getListenerInfo().mOnDragListener = l; 4721 } 4722 4723 /** 4724 * Give this view focus. This will cause 4725 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4726 * 4727 * Note: this does not check whether this {@link View} should get focus, it just 4728 * gives it focus no matter what. It should only be called internally by framework 4729 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4730 * 4731 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4732 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4733 * focus moved when requestFocus() is called. It may not always 4734 * apply, in which case use the default View.FOCUS_DOWN. 4735 * @param previouslyFocusedRect The rectangle of the view that had focus 4736 * prior in this View's coordinate system. 4737 */ 4738 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4739 if (DBG) { 4740 System.out.println(this + " requestFocus()"); 4741 } 4742 4743 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4744 mPrivateFlags |= PFLAG_FOCUSED; 4745 4746 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4747 4748 if (mParent != null) { 4749 mParent.requestChildFocus(this, this); 4750 } 4751 4752 if (mAttachInfo != null) { 4753 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4754 } 4755 4756 manageFocusHotspot(true, oldFocus); 4757 onFocusChanged(true, direction, previouslyFocusedRect); 4758 refreshDrawableState(); 4759 } 4760 } 4761 4762 /** 4763 * Forwards focus information to the background drawable, if necessary. When 4764 * the view is gaining focus, <code>v</code> is the previous focus holder. 4765 * When the view is losing focus, <code>v</code> is the next focus holder. 4766 * 4767 * @param focused whether this view is focused 4768 * @param v previous or the next focus holder, or null if none 4769 */ 4770 private void manageFocusHotspot(boolean focused, View v) { 4771 if (mBackground != null && mBackground.supportsHotspots()) { 4772 final Rect r = new Rect(); 4773 if (!focused && v != null) { 4774 v.getBoundsOnScreen(r); 4775 final int[] location = new int[2]; 4776 getLocationOnScreen(location); 4777 r.offset(-location[0], -location[1]); 4778 } else { 4779 r.set(0, 0, mRight - mLeft, mBottom - mTop); 4780 } 4781 4782 final float x = r.exactCenterX(); 4783 final float y = r.exactCenterY(); 4784 mBackground.setHotspot(R.attr.state_focused, x, y); 4785 4786 if (!focused) { 4787 mBackground.removeHotspot(R.attr.state_focused); 4788 } 4789 } 4790 } 4791 4792 /** 4793 * Request that a rectangle of this view be visible on the screen, 4794 * scrolling if necessary just enough. 4795 * 4796 * <p>A View should call this if it maintains some notion of which part 4797 * of its content is interesting. For example, a text editing view 4798 * should call this when its cursor moves. 4799 * 4800 * @param rectangle The rectangle. 4801 * @return Whether any parent scrolled. 4802 */ 4803 public boolean requestRectangleOnScreen(Rect rectangle) { 4804 return requestRectangleOnScreen(rectangle, false); 4805 } 4806 4807 /** 4808 * Request that a rectangle of this view be visible on the screen, 4809 * scrolling if necessary just enough. 4810 * 4811 * <p>A View should call this if it maintains some notion of which part 4812 * of its content is interesting. For example, a text editing view 4813 * should call this when its cursor moves. 4814 * 4815 * <p>When <code>immediate</code> is set to true, scrolling will not be 4816 * animated. 4817 * 4818 * @param rectangle The rectangle. 4819 * @param immediate True to forbid animated scrolling, false otherwise 4820 * @return Whether any parent scrolled. 4821 */ 4822 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4823 if (mParent == null) { 4824 return false; 4825 } 4826 4827 View child = this; 4828 4829 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4830 position.set(rectangle); 4831 4832 ViewParent parent = mParent; 4833 boolean scrolled = false; 4834 while (parent != null) { 4835 rectangle.set((int) position.left, (int) position.top, 4836 (int) position.right, (int) position.bottom); 4837 4838 scrolled |= parent.requestChildRectangleOnScreen(child, 4839 rectangle, immediate); 4840 4841 if (!child.hasIdentityMatrix()) { 4842 child.getMatrix().mapRect(position); 4843 } 4844 4845 position.offset(child.mLeft, child.mTop); 4846 4847 if (!(parent instanceof View)) { 4848 break; 4849 } 4850 4851 View parentView = (View) parent; 4852 4853 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4854 4855 child = parentView; 4856 parent = child.getParent(); 4857 } 4858 4859 return scrolled; 4860 } 4861 4862 /** 4863 * Called when this view wants to give up focus. If focus is cleared 4864 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4865 * <p> 4866 * <strong>Note:</strong> When a View clears focus the framework is trying 4867 * to give focus to the first focusable View from the top. Hence, if this 4868 * View is the first from the top that can take focus, then all callbacks 4869 * related to clearing focus will be invoked after wich the framework will 4870 * give focus to this view. 4871 * </p> 4872 */ 4873 public void clearFocus() { 4874 if (DBG) { 4875 System.out.println(this + " clearFocus()"); 4876 } 4877 4878 clearFocusInternal(null, true, true); 4879 } 4880 4881 /** 4882 * Clears focus from the view, optionally propagating the change up through 4883 * the parent hierarchy and requesting that the root view place new focus. 4884 * 4885 * @param propagate whether to propagate the change up through the parent 4886 * hierarchy 4887 * @param refocus when propagate is true, specifies whether to request the 4888 * root view place new focus 4889 */ 4890 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4891 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4892 mPrivateFlags &= ~PFLAG_FOCUSED; 4893 4894 if (propagate && mParent != null) { 4895 mParent.clearChildFocus(this); 4896 } 4897 4898 onFocusChanged(false, 0, null); 4899 4900 manageFocusHotspot(false, focused); 4901 refreshDrawableState(); 4902 4903 if (propagate && (!refocus || !rootViewRequestFocus())) { 4904 notifyGlobalFocusCleared(this); 4905 } 4906 } 4907 } 4908 4909 void notifyGlobalFocusCleared(View oldFocus) { 4910 if (oldFocus != null && mAttachInfo != null) { 4911 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4912 } 4913 } 4914 4915 boolean rootViewRequestFocus() { 4916 final View root = getRootView(); 4917 return root != null && root.requestFocus(); 4918 } 4919 4920 /** 4921 * Called internally by the view system when a new view is getting focus. 4922 * This is what clears the old focus. 4923 * <p> 4924 * <b>NOTE:</b> The parent view's focused child must be updated manually 4925 * after calling this method. Otherwise, the view hierarchy may be left in 4926 * an inconstent state. 4927 */ 4928 void unFocus(View focused) { 4929 if (DBG) { 4930 System.out.println(this + " unFocus()"); 4931 } 4932 4933 clearFocusInternal(focused, false, false); 4934 } 4935 4936 /** 4937 * Returns true if this view has focus iteself, or is the ancestor of the 4938 * view that has focus. 4939 * 4940 * @return True if this view has or contains focus, false otherwise. 4941 */ 4942 @ViewDebug.ExportedProperty(category = "focus") 4943 public boolean hasFocus() { 4944 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4945 } 4946 4947 /** 4948 * Returns true if this view is focusable or if it contains a reachable View 4949 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4950 * is a View whose parents do not block descendants focus. 4951 * 4952 * Only {@link #VISIBLE} views are considered focusable. 4953 * 4954 * @return True if the view is focusable or if the view contains a focusable 4955 * View, false otherwise. 4956 * 4957 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4958 */ 4959 public boolean hasFocusable() { 4960 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4961 } 4962 4963 /** 4964 * Called by the view system when the focus state of this view changes. 4965 * When the focus change event is caused by directional navigation, direction 4966 * and previouslyFocusedRect provide insight into where the focus is coming from. 4967 * When overriding, be sure to call up through to the super class so that 4968 * the standard focus handling will occur. 4969 * 4970 * @param gainFocus True if the View has focus; false otherwise. 4971 * @param direction The direction focus has moved when requestFocus() 4972 * is called to give this view focus. Values are 4973 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4974 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4975 * It may not always apply, in which case use the default. 4976 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4977 * system, of the previously focused view. If applicable, this will be 4978 * passed in as finer grained information about where the focus is coming 4979 * from (in addition to direction). Will be <code>null</code> otherwise. 4980 */ 4981 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 4982 @Nullable Rect previouslyFocusedRect) { 4983 if (gainFocus) { 4984 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4985 } else { 4986 notifyViewAccessibilityStateChangedIfNeeded( 4987 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 4988 } 4989 4990 InputMethodManager imm = InputMethodManager.peekInstance(); 4991 if (!gainFocus) { 4992 if (isPressed()) { 4993 setPressed(false); 4994 } 4995 if (imm != null && mAttachInfo != null 4996 && mAttachInfo.mHasWindowFocus) { 4997 imm.focusOut(this); 4998 } 4999 onFocusLost(); 5000 } else if (imm != null && mAttachInfo != null 5001 && mAttachInfo.mHasWindowFocus) { 5002 imm.focusIn(this); 5003 } 5004 5005 invalidate(true); 5006 ListenerInfo li = mListenerInfo; 5007 if (li != null && li.mOnFocusChangeListener != null) { 5008 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5009 } 5010 5011 if (mAttachInfo != null) { 5012 mAttachInfo.mKeyDispatchState.reset(this); 5013 } 5014 } 5015 5016 /** 5017 * Sends an accessibility event of the given type. If accessibility is 5018 * not enabled this method has no effect. The default implementation calls 5019 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5020 * to populate information about the event source (this View), then calls 5021 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5022 * populate the text content of the event source including its descendants, 5023 * and last calls 5024 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5025 * on its parent to resuest sending of the event to interested parties. 5026 * <p> 5027 * If an {@link AccessibilityDelegate} has been specified via calling 5028 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5029 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5030 * responsible for handling this call. 5031 * </p> 5032 * 5033 * @param eventType The type of the event to send, as defined by several types from 5034 * {@link android.view.accessibility.AccessibilityEvent}, such as 5035 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5036 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5037 * 5038 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5039 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5040 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5041 * @see AccessibilityDelegate 5042 */ 5043 public void sendAccessibilityEvent(int eventType) { 5044 if (mAccessibilityDelegate != null) { 5045 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5046 } else { 5047 sendAccessibilityEventInternal(eventType); 5048 } 5049 } 5050 5051 /** 5052 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5053 * {@link AccessibilityEvent} to make an announcement which is related to some 5054 * sort of a context change for which none of the events representing UI transitions 5055 * is a good fit. For example, announcing a new page in a book. If accessibility 5056 * is not enabled this method does nothing. 5057 * 5058 * @param text The announcement text. 5059 */ 5060 public void announceForAccessibility(CharSequence text) { 5061 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5062 AccessibilityEvent event = AccessibilityEvent.obtain( 5063 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5064 onInitializeAccessibilityEvent(event); 5065 event.getText().add(text); 5066 event.setContentDescription(null); 5067 mParent.requestSendAccessibilityEvent(this, event); 5068 } 5069 } 5070 5071 /** 5072 * @see #sendAccessibilityEvent(int) 5073 * 5074 * Note: Called from the default {@link AccessibilityDelegate}. 5075 */ 5076 void sendAccessibilityEventInternal(int eventType) { 5077 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5078 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5079 } 5080 } 5081 5082 /** 5083 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5084 * takes as an argument an empty {@link AccessibilityEvent} and does not 5085 * perform a check whether accessibility is enabled. 5086 * <p> 5087 * If an {@link AccessibilityDelegate} has been specified via calling 5088 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5089 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5090 * is responsible for handling this call. 5091 * </p> 5092 * 5093 * @param event The event to send. 5094 * 5095 * @see #sendAccessibilityEvent(int) 5096 */ 5097 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5098 if (mAccessibilityDelegate != null) { 5099 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5100 } else { 5101 sendAccessibilityEventUncheckedInternal(event); 5102 } 5103 } 5104 5105 /** 5106 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5107 * 5108 * Note: Called from the default {@link AccessibilityDelegate}. 5109 */ 5110 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5111 if (!isShown()) { 5112 return; 5113 } 5114 onInitializeAccessibilityEvent(event); 5115 // Only a subset of accessibility events populates text content. 5116 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5117 dispatchPopulateAccessibilityEvent(event); 5118 } 5119 // In the beginning we called #isShown(), so we know that getParent() is not null. 5120 getParent().requestSendAccessibilityEvent(this, event); 5121 } 5122 5123 /** 5124 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5125 * to its children for adding their text content to the event. Note that the 5126 * event text is populated in a separate dispatch path since we add to the 5127 * event not only the text of the source but also the text of all its descendants. 5128 * A typical implementation will call 5129 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5130 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5131 * on each child. Override this method if custom population of the event text 5132 * content is required. 5133 * <p> 5134 * If an {@link AccessibilityDelegate} has been specified via calling 5135 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5136 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5137 * is responsible for handling this call. 5138 * </p> 5139 * <p> 5140 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5141 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5142 * </p> 5143 * 5144 * @param event The event. 5145 * 5146 * @return True if the event population was completed. 5147 */ 5148 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5149 if (mAccessibilityDelegate != null) { 5150 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5151 } else { 5152 return dispatchPopulateAccessibilityEventInternal(event); 5153 } 5154 } 5155 5156 /** 5157 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5158 * 5159 * Note: Called from the default {@link AccessibilityDelegate}. 5160 */ 5161 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5162 onPopulateAccessibilityEvent(event); 5163 return false; 5164 } 5165 5166 /** 5167 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5168 * giving a chance to this View to populate the accessibility event with its 5169 * text content. While this method is free to modify event 5170 * attributes other than text content, doing so should normally be performed in 5171 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5172 * <p> 5173 * Example: Adding formatted date string to an accessibility event in addition 5174 * to the text added by the super implementation: 5175 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5176 * super.onPopulateAccessibilityEvent(event); 5177 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5178 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5179 * mCurrentDate.getTimeInMillis(), flags); 5180 * event.getText().add(selectedDateUtterance); 5181 * }</pre> 5182 * <p> 5183 * If an {@link AccessibilityDelegate} has been specified via calling 5184 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5185 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5186 * is responsible for handling this call. 5187 * </p> 5188 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5189 * information to the event, in case the default implementation has basic information to add. 5190 * </p> 5191 * 5192 * @param event The accessibility event which to populate. 5193 * 5194 * @see #sendAccessibilityEvent(int) 5195 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5196 */ 5197 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5198 if (mAccessibilityDelegate != null) { 5199 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5200 } else { 5201 onPopulateAccessibilityEventInternal(event); 5202 } 5203 } 5204 5205 /** 5206 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5207 * 5208 * Note: Called from the default {@link AccessibilityDelegate}. 5209 */ 5210 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5211 } 5212 5213 /** 5214 * Initializes an {@link AccessibilityEvent} with information about 5215 * this View which is the event source. In other words, the source of 5216 * an accessibility event is the view whose state change triggered firing 5217 * the event. 5218 * <p> 5219 * Example: Setting the password property of an event in addition 5220 * to properties set by the super implementation: 5221 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5222 * super.onInitializeAccessibilityEvent(event); 5223 * event.setPassword(true); 5224 * }</pre> 5225 * <p> 5226 * If an {@link AccessibilityDelegate} has been specified via calling 5227 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5228 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5229 * is responsible for handling this call. 5230 * </p> 5231 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5232 * information to the event, in case the default implementation has basic information to add. 5233 * </p> 5234 * @param event The event to initialize. 5235 * 5236 * @see #sendAccessibilityEvent(int) 5237 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5238 */ 5239 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5240 if (mAccessibilityDelegate != null) { 5241 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5242 } else { 5243 onInitializeAccessibilityEventInternal(event); 5244 } 5245 } 5246 5247 /** 5248 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5249 * 5250 * Note: Called from the default {@link AccessibilityDelegate}. 5251 */ 5252 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5253 event.setSource(this); 5254 event.setClassName(View.class.getName()); 5255 event.setPackageName(getContext().getPackageName()); 5256 event.setEnabled(isEnabled()); 5257 event.setContentDescription(mContentDescription); 5258 5259 switch (event.getEventType()) { 5260 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5261 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5262 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5263 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5264 event.setItemCount(focusablesTempList.size()); 5265 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5266 if (mAttachInfo != null) { 5267 focusablesTempList.clear(); 5268 } 5269 } break; 5270 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5271 CharSequence text = getIterableTextForAccessibility(); 5272 if (text != null && text.length() > 0) { 5273 event.setFromIndex(getAccessibilitySelectionStart()); 5274 event.setToIndex(getAccessibilitySelectionEnd()); 5275 event.setItemCount(text.length()); 5276 } 5277 } break; 5278 } 5279 } 5280 5281 /** 5282 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5283 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5284 * This method is responsible for obtaining an accessibility node info from a 5285 * pool of reusable instances and calling 5286 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5287 * initialize the former. 5288 * <p> 5289 * Note: The client is responsible for recycling the obtained instance by calling 5290 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5291 * </p> 5292 * 5293 * @return A populated {@link AccessibilityNodeInfo}. 5294 * 5295 * @see AccessibilityNodeInfo 5296 */ 5297 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5298 if (mAccessibilityDelegate != null) { 5299 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5300 } else { 5301 return createAccessibilityNodeInfoInternal(); 5302 } 5303 } 5304 5305 /** 5306 * @see #createAccessibilityNodeInfo() 5307 */ 5308 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5309 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5310 if (provider != null) { 5311 return provider.createAccessibilityNodeInfo(View.NO_ID); 5312 } else { 5313 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5314 onInitializeAccessibilityNodeInfo(info); 5315 return info; 5316 } 5317 } 5318 5319 /** 5320 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5321 * The base implementation sets: 5322 * <ul> 5323 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5324 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5325 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5326 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5327 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5328 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5329 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5330 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5331 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5332 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5333 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5334 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5335 * </ul> 5336 * <p> 5337 * Subclasses should override this method, call the super implementation, 5338 * and set additional attributes. 5339 * </p> 5340 * <p> 5341 * If an {@link AccessibilityDelegate} has been specified via calling 5342 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5343 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5344 * is responsible for handling this call. 5345 * </p> 5346 * 5347 * @param info The instance to initialize. 5348 */ 5349 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5350 if (mAccessibilityDelegate != null) { 5351 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5352 } else { 5353 onInitializeAccessibilityNodeInfoInternal(info); 5354 } 5355 } 5356 5357 /** 5358 * Gets the location of this view in screen coordintates. 5359 * 5360 * @param outRect The output location 5361 */ 5362 void getBoundsOnScreen(Rect outRect) { 5363 if (mAttachInfo == null) { 5364 return; 5365 } 5366 5367 RectF position = mAttachInfo.mTmpTransformRect; 5368 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5369 5370 if (!hasIdentityMatrix()) { 5371 getMatrix().mapRect(position); 5372 } 5373 5374 position.offset(mLeft, mTop); 5375 5376 ViewParent parent = mParent; 5377 while (parent instanceof View) { 5378 View parentView = (View) parent; 5379 5380 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5381 5382 if (!parentView.hasIdentityMatrix()) { 5383 parentView.getMatrix().mapRect(position); 5384 } 5385 5386 position.offset(parentView.mLeft, parentView.mTop); 5387 5388 parent = parentView.mParent; 5389 } 5390 5391 if (parent instanceof ViewRootImpl) { 5392 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5393 position.offset(0, -viewRootImpl.mCurScrollY); 5394 } 5395 5396 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5397 5398 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5399 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5400 } 5401 5402 /** 5403 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5404 * 5405 * Note: Called from the default {@link AccessibilityDelegate}. 5406 */ 5407 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5408 Rect bounds = mAttachInfo.mTmpInvalRect; 5409 5410 getDrawingRect(bounds); 5411 info.setBoundsInParent(bounds); 5412 5413 getBoundsOnScreen(bounds); 5414 info.setBoundsInScreen(bounds); 5415 5416 ViewParent parent = getParentForAccessibility(); 5417 if (parent instanceof View) { 5418 info.setParent((View) parent); 5419 } 5420 5421 if (mID != View.NO_ID) { 5422 View rootView = getRootView(); 5423 if (rootView == null) { 5424 rootView = this; 5425 } 5426 View label = rootView.findLabelForView(this, mID); 5427 if (label != null) { 5428 info.setLabeledBy(label); 5429 } 5430 5431 if ((mAttachInfo.mAccessibilityFetchFlags 5432 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5433 && Resources.resourceHasPackage(mID)) { 5434 try { 5435 String viewId = getResources().getResourceName(mID); 5436 info.setViewIdResourceName(viewId); 5437 } catch (Resources.NotFoundException nfe) { 5438 /* ignore */ 5439 } 5440 } 5441 } 5442 5443 if (mLabelForId != View.NO_ID) { 5444 View rootView = getRootView(); 5445 if (rootView == null) { 5446 rootView = this; 5447 } 5448 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5449 if (labeled != null) { 5450 info.setLabelFor(labeled); 5451 } 5452 } 5453 5454 info.setVisibleToUser(isVisibleToUser()); 5455 5456 info.setPackageName(mContext.getPackageName()); 5457 info.setClassName(View.class.getName()); 5458 info.setContentDescription(getContentDescription()); 5459 5460 info.setEnabled(isEnabled()); 5461 info.setClickable(isClickable()); 5462 info.setFocusable(isFocusable()); 5463 info.setFocused(isFocused()); 5464 info.setAccessibilityFocused(isAccessibilityFocused()); 5465 info.setSelected(isSelected()); 5466 info.setLongClickable(isLongClickable()); 5467 info.setLiveRegion(getAccessibilityLiveRegion()); 5468 5469 // TODO: These make sense only if we are in an AdapterView but all 5470 // views can be selected. Maybe from accessibility perspective 5471 // we should report as selectable view in an AdapterView. 5472 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5473 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5474 5475 if (isFocusable()) { 5476 if (isFocused()) { 5477 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5478 } else { 5479 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5480 } 5481 } 5482 5483 if (!isAccessibilityFocused()) { 5484 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5485 } else { 5486 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5487 } 5488 5489 if (isClickable() && isEnabled()) { 5490 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5491 } 5492 5493 if (isLongClickable() && isEnabled()) { 5494 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5495 } 5496 5497 CharSequence text = getIterableTextForAccessibility(); 5498 if (text != null && text.length() > 0) { 5499 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5500 5501 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5502 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5503 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5504 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5505 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5506 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5507 } 5508 } 5509 5510 private View findLabelForView(View view, int labeledId) { 5511 if (mMatchLabelForPredicate == null) { 5512 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5513 } 5514 mMatchLabelForPredicate.mLabeledId = labeledId; 5515 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5516 } 5517 5518 /** 5519 * Computes whether this view is visible to the user. Such a view is 5520 * attached, visible, all its predecessors are visible, it is not clipped 5521 * entirely by its predecessors, and has an alpha greater than zero. 5522 * 5523 * @return Whether the view is visible on the screen. 5524 * 5525 * @hide 5526 */ 5527 protected boolean isVisibleToUser() { 5528 return isVisibleToUser(null); 5529 } 5530 5531 /** 5532 * Computes whether the given portion of this view is visible to the user. 5533 * Such a view is attached, visible, all its predecessors are visible, 5534 * has an alpha greater than zero, and the specified portion is not 5535 * clipped entirely by its predecessors. 5536 * 5537 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5538 * <code>null</code>, and the entire view will be tested in this case. 5539 * When <code>true</code> is returned by the function, the actual visible 5540 * region will be stored in this parameter; that is, if boundInView is fully 5541 * contained within the view, no modification will be made, otherwise regions 5542 * outside of the visible area of the view will be clipped. 5543 * 5544 * @return Whether the specified portion of the view is visible on the screen. 5545 * 5546 * @hide 5547 */ 5548 protected boolean isVisibleToUser(Rect boundInView) { 5549 if (mAttachInfo != null) { 5550 // Attached to invisible window means this view is not visible. 5551 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5552 return false; 5553 } 5554 // An invisible predecessor or one with alpha zero means 5555 // that this view is not visible to the user. 5556 Object current = this; 5557 while (current instanceof View) { 5558 View view = (View) current; 5559 // We have attach info so this view is attached and there is no 5560 // need to check whether we reach to ViewRootImpl on the way up. 5561 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5562 view.getVisibility() != VISIBLE) { 5563 return false; 5564 } 5565 current = view.mParent; 5566 } 5567 // Check if the view is entirely covered by its predecessors. 5568 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5569 Point offset = mAttachInfo.mPoint; 5570 if (!getGlobalVisibleRect(visibleRect, offset)) { 5571 return false; 5572 } 5573 // Check if the visible portion intersects the rectangle of interest. 5574 if (boundInView != null) { 5575 visibleRect.offset(-offset.x, -offset.y); 5576 return boundInView.intersect(visibleRect); 5577 } 5578 return true; 5579 } 5580 return false; 5581 } 5582 5583 /** 5584 * Returns the delegate for implementing accessibility support via 5585 * composition. For more details see {@link AccessibilityDelegate}. 5586 * 5587 * @return The delegate, or null if none set. 5588 * 5589 * @hide 5590 */ 5591 public AccessibilityDelegate getAccessibilityDelegate() { 5592 return mAccessibilityDelegate; 5593 } 5594 5595 /** 5596 * Sets a delegate for implementing accessibility support via composition as 5597 * opposed to inheritance. The delegate's primary use is for implementing 5598 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5599 * 5600 * @param delegate The delegate instance. 5601 * 5602 * @see AccessibilityDelegate 5603 */ 5604 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5605 mAccessibilityDelegate = delegate; 5606 } 5607 5608 /** 5609 * Gets the provider for managing a virtual view hierarchy rooted at this View 5610 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5611 * that explore the window content. 5612 * <p> 5613 * If this method returns an instance, this instance is responsible for managing 5614 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5615 * View including the one representing the View itself. Similarly the returned 5616 * instance is responsible for performing accessibility actions on any virtual 5617 * view or the root view itself. 5618 * </p> 5619 * <p> 5620 * If an {@link AccessibilityDelegate} has been specified via calling 5621 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5622 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5623 * is responsible for handling this call. 5624 * </p> 5625 * 5626 * @return The provider. 5627 * 5628 * @see AccessibilityNodeProvider 5629 */ 5630 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5631 if (mAccessibilityDelegate != null) { 5632 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5633 } else { 5634 return null; 5635 } 5636 } 5637 5638 /** 5639 * Gets the unique identifier of this view on the screen for accessibility purposes. 5640 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5641 * 5642 * @return The view accessibility id. 5643 * 5644 * @hide 5645 */ 5646 public int getAccessibilityViewId() { 5647 if (mAccessibilityViewId == NO_ID) { 5648 mAccessibilityViewId = sNextAccessibilityViewId++; 5649 } 5650 return mAccessibilityViewId; 5651 } 5652 5653 /** 5654 * Gets the unique identifier of the window in which this View reseides. 5655 * 5656 * @return The window accessibility id. 5657 * 5658 * @hide 5659 */ 5660 public int getAccessibilityWindowId() { 5661 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5662 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5663 } 5664 5665 /** 5666 * Gets the {@link View} description. It briefly describes the view and is 5667 * primarily used for accessibility support. Set this property to enable 5668 * better accessibility support for your application. This is especially 5669 * true for views that do not have textual representation (For example, 5670 * ImageButton). 5671 * 5672 * @return The content description. 5673 * 5674 * @attr ref android.R.styleable#View_contentDescription 5675 */ 5676 @ViewDebug.ExportedProperty(category = "accessibility") 5677 public CharSequence getContentDescription() { 5678 return mContentDescription; 5679 } 5680 5681 /** 5682 * Sets the {@link View} description. It briefly describes the view and is 5683 * primarily used for accessibility support. Set this property to enable 5684 * better accessibility support for your application. This is especially 5685 * true for views that do not have textual representation (For example, 5686 * ImageButton). 5687 * 5688 * @param contentDescription The content description. 5689 * 5690 * @attr ref android.R.styleable#View_contentDescription 5691 */ 5692 @RemotableViewMethod 5693 public void setContentDescription(CharSequence contentDescription) { 5694 if (mContentDescription == null) { 5695 if (contentDescription == null) { 5696 return; 5697 } 5698 } else if (mContentDescription.equals(contentDescription)) { 5699 return; 5700 } 5701 mContentDescription = contentDescription; 5702 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5703 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5704 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5705 notifySubtreeAccessibilityStateChangedIfNeeded(); 5706 } else { 5707 notifyViewAccessibilityStateChangedIfNeeded( 5708 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5709 } 5710 } 5711 5712 /** 5713 * Gets the id of a view for which this view serves as a label for 5714 * accessibility purposes. 5715 * 5716 * @return The labeled view id. 5717 */ 5718 @ViewDebug.ExportedProperty(category = "accessibility") 5719 public int getLabelFor() { 5720 return mLabelForId; 5721 } 5722 5723 /** 5724 * Sets the id of a view for which this view serves as a label for 5725 * accessibility purposes. 5726 * 5727 * @param id The labeled view id. 5728 */ 5729 @RemotableViewMethod 5730 public void setLabelFor(int id) { 5731 mLabelForId = id; 5732 if (mLabelForId != View.NO_ID 5733 && mID == View.NO_ID) { 5734 mID = generateViewId(); 5735 } 5736 } 5737 5738 /** 5739 * Invoked whenever this view loses focus, either by losing window focus or by losing 5740 * focus within its window. This method can be used to clear any state tied to the 5741 * focus. For instance, if a button is held pressed with the trackball and the window 5742 * loses focus, this method can be used to cancel the press. 5743 * 5744 * Subclasses of View overriding this method should always call super.onFocusLost(). 5745 * 5746 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5747 * @see #onWindowFocusChanged(boolean) 5748 * 5749 * @hide pending API council approval 5750 */ 5751 protected void onFocusLost() { 5752 resetPressedState(); 5753 } 5754 5755 private void resetPressedState() { 5756 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5757 return; 5758 } 5759 5760 if (isPressed()) { 5761 setPressed(false); 5762 5763 if (!mHasPerformedLongPress) { 5764 removeLongPressCallback(); 5765 } 5766 } 5767 } 5768 5769 /** 5770 * Returns true if this view has focus 5771 * 5772 * @return True if this view has focus, false otherwise. 5773 */ 5774 @ViewDebug.ExportedProperty(category = "focus") 5775 public boolean isFocused() { 5776 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5777 } 5778 5779 /** 5780 * Find the view in the hierarchy rooted at this view that currently has 5781 * focus. 5782 * 5783 * @return The view that currently has focus, or null if no focused view can 5784 * be found. 5785 */ 5786 public View findFocus() { 5787 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5788 } 5789 5790 /** 5791 * Indicates whether this view is one of the set of scrollable containers in 5792 * its window. 5793 * 5794 * @return whether this view is one of the set of scrollable containers in 5795 * its window 5796 * 5797 * @attr ref android.R.styleable#View_isScrollContainer 5798 */ 5799 public boolean isScrollContainer() { 5800 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5801 } 5802 5803 /** 5804 * Change whether this view is one of the set of scrollable containers in 5805 * its window. This will be used to determine whether the window can 5806 * resize or must pan when a soft input area is open -- scrollable 5807 * containers allow the window to use resize mode since the container 5808 * will appropriately shrink. 5809 * 5810 * @attr ref android.R.styleable#View_isScrollContainer 5811 */ 5812 public void setScrollContainer(boolean isScrollContainer) { 5813 if (isScrollContainer) { 5814 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5815 mAttachInfo.mScrollContainers.add(this); 5816 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5817 } 5818 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5819 } else { 5820 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5821 mAttachInfo.mScrollContainers.remove(this); 5822 } 5823 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5824 } 5825 } 5826 5827 /** 5828 * Returns the quality of the drawing cache. 5829 * 5830 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5831 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5832 * 5833 * @see #setDrawingCacheQuality(int) 5834 * @see #setDrawingCacheEnabled(boolean) 5835 * @see #isDrawingCacheEnabled() 5836 * 5837 * @attr ref android.R.styleable#View_drawingCacheQuality 5838 */ 5839 @DrawingCacheQuality 5840 public int getDrawingCacheQuality() { 5841 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5842 } 5843 5844 /** 5845 * Set the drawing cache quality of this view. This value is used only when the 5846 * drawing cache is enabled 5847 * 5848 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5849 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5850 * 5851 * @see #getDrawingCacheQuality() 5852 * @see #setDrawingCacheEnabled(boolean) 5853 * @see #isDrawingCacheEnabled() 5854 * 5855 * @attr ref android.R.styleable#View_drawingCacheQuality 5856 */ 5857 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5858 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5859 } 5860 5861 /** 5862 * Returns whether the screen should remain on, corresponding to the current 5863 * value of {@link #KEEP_SCREEN_ON}. 5864 * 5865 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5866 * 5867 * @see #setKeepScreenOn(boolean) 5868 * 5869 * @attr ref android.R.styleable#View_keepScreenOn 5870 */ 5871 public boolean getKeepScreenOn() { 5872 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5873 } 5874 5875 /** 5876 * Controls whether the screen should remain on, modifying the 5877 * value of {@link #KEEP_SCREEN_ON}. 5878 * 5879 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5880 * 5881 * @see #getKeepScreenOn() 5882 * 5883 * @attr ref android.R.styleable#View_keepScreenOn 5884 */ 5885 public void setKeepScreenOn(boolean keepScreenOn) { 5886 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5887 } 5888 5889 /** 5890 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5891 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5892 * 5893 * @attr ref android.R.styleable#View_nextFocusLeft 5894 */ 5895 public int getNextFocusLeftId() { 5896 return mNextFocusLeftId; 5897 } 5898 5899 /** 5900 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5901 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5902 * decide automatically. 5903 * 5904 * @attr ref android.R.styleable#View_nextFocusLeft 5905 */ 5906 public void setNextFocusLeftId(int nextFocusLeftId) { 5907 mNextFocusLeftId = nextFocusLeftId; 5908 } 5909 5910 /** 5911 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5912 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5913 * 5914 * @attr ref android.R.styleable#View_nextFocusRight 5915 */ 5916 public int getNextFocusRightId() { 5917 return mNextFocusRightId; 5918 } 5919 5920 /** 5921 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5922 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5923 * decide automatically. 5924 * 5925 * @attr ref android.R.styleable#View_nextFocusRight 5926 */ 5927 public void setNextFocusRightId(int nextFocusRightId) { 5928 mNextFocusRightId = nextFocusRightId; 5929 } 5930 5931 /** 5932 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5933 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5934 * 5935 * @attr ref android.R.styleable#View_nextFocusUp 5936 */ 5937 public int getNextFocusUpId() { 5938 return mNextFocusUpId; 5939 } 5940 5941 /** 5942 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5943 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5944 * decide automatically. 5945 * 5946 * @attr ref android.R.styleable#View_nextFocusUp 5947 */ 5948 public void setNextFocusUpId(int nextFocusUpId) { 5949 mNextFocusUpId = nextFocusUpId; 5950 } 5951 5952 /** 5953 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5954 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5955 * 5956 * @attr ref android.R.styleable#View_nextFocusDown 5957 */ 5958 public int getNextFocusDownId() { 5959 return mNextFocusDownId; 5960 } 5961 5962 /** 5963 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5964 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5965 * decide automatically. 5966 * 5967 * @attr ref android.R.styleable#View_nextFocusDown 5968 */ 5969 public void setNextFocusDownId(int nextFocusDownId) { 5970 mNextFocusDownId = nextFocusDownId; 5971 } 5972 5973 /** 5974 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5975 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5976 * 5977 * @attr ref android.R.styleable#View_nextFocusForward 5978 */ 5979 public int getNextFocusForwardId() { 5980 return mNextFocusForwardId; 5981 } 5982 5983 /** 5984 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5985 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 5986 * decide automatically. 5987 * 5988 * @attr ref android.R.styleable#View_nextFocusForward 5989 */ 5990 public void setNextFocusForwardId(int nextFocusForwardId) { 5991 mNextFocusForwardId = nextFocusForwardId; 5992 } 5993 5994 /** 5995 * Returns the visibility of this view and all of its ancestors 5996 * 5997 * @return True if this view and all of its ancestors are {@link #VISIBLE} 5998 */ 5999 public boolean isShown() { 6000 View current = this; 6001 //noinspection ConstantConditions 6002 do { 6003 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6004 return false; 6005 } 6006 ViewParent parent = current.mParent; 6007 if (parent == null) { 6008 return false; // We are not attached to the view root 6009 } 6010 if (!(parent instanceof View)) { 6011 return true; 6012 } 6013 current = (View) parent; 6014 } while (current != null); 6015 6016 return false; 6017 } 6018 6019 /** 6020 * Called by the view hierarchy when the content insets for a window have 6021 * changed, to allow it to adjust its content to fit within those windows. 6022 * The content insets tell you the space that the status bar, input method, 6023 * and other system windows infringe on the application's window. 6024 * 6025 * <p>You do not normally need to deal with this function, since the default 6026 * window decoration given to applications takes care of applying it to the 6027 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6028 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6029 * and your content can be placed under those system elements. You can then 6030 * use this method within your view hierarchy if you have parts of your UI 6031 * which you would like to ensure are not being covered. 6032 * 6033 * <p>The default implementation of this method simply applies the content 6034 * insets to the view's padding, consuming that content (modifying the 6035 * insets to be 0), and returning true. This behavior is off by default, but can 6036 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6037 * 6038 * <p>This function's traversal down the hierarchy is depth-first. The same content 6039 * insets object is propagated down the hierarchy, so any changes made to it will 6040 * be seen by all following views (including potentially ones above in 6041 * the hierarchy since this is a depth-first traversal). The first view 6042 * that returns true will abort the entire traversal. 6043 * 6044 * <p>The default implementation works well for a situation where it is 6045 * used with a container that covers the entire window, allowing it to 6046 * apply the appropriate insets to its content on all edges. If you need 6047 * a more complicated layout (such as two different views fitting system 6048 * windows, one on the top of the window, and one on the bottom), 6049 * you can override the method and handle the insets however you would like. 6050 * Note that the insets provided by the framework are always relative to the 6051 * far edges of the window, not accounting for the location of the called view 6052 * within that window. (In fact when this method is called you do not yet know 6053 * where the layout will place the view, as it is done before layout happens.) 6054 * 6055 * <p>Note: unlike many View methods, there is no dispatch phase to this 6056 * call. If you are overriding it in a ViewGroup and want to allow the 6057 * call to continue to your children, you must be sure to call the super 6058 * implementation. 6059 * 6060 * <p>Here is a sample layout that makes use of fitting system windows 6061 * to have controls for a video view placed inside of the window decorations 6062 * that it hides and shows. This can be used with code like the second 6063 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6064 * 6065 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6066 * 6067 * @param insets Current content insets of the window. Prior to 6068 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6069 * the insets or else you and Android will be unhappy. 6070 * 6071 * @return {@code true} if this view applied the insets and it should not 6072 * continue propagating further down the hierarchy, {@code false} otherwise. 6073 * @see #getFitsSystemWindows() 6074 * @see #setFitsSystemWindows(boolean) 6075 * @see #setSystemUiVisibility(int) 6076 * 6077 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6078 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6079 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6080 * to implement handling their own insets. 6081 */ 6082 protected boolean fitSystemWindows(Rect insets) { 6083 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6084 // If we're not in the process of dispatching the newer apply insets call, 6085 // that means we're not in the compatibility path. Dispatch into the newer 6086 // apply insets path and take things from there. 6087 try { 6088 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6089 return !dispatchApplyWindowInsets(new WindowInsets(insets)).hasInsets(); 6090 } finally { 6091 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6092 } 6093 } else { 6094 // We're being called from the newer apply insets path. 6095 // Perform the standard fallback behavior. 6096 return fitSystemWindowsInt(insets); 6097 } 6098 } 6099 6100 private boolean fitSystemWindowsInt(Rect insets) { 6101 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6102 mUserPaddingStart = UNDEFINED_PADDING; 6103 mUserPaddingEnd = UNDEFINED_PADDING; 6104 Rect localInsets = sThreadLocal.get(); 6105 if (localInsets == null) { 6106 localInsets = new Rect(); 6107 sThreadLocal.set(localInsets); 6108 } 6109 boolean res = computeFitSystemWindows(insets, localInsets); 6110 mUserPaddingLeftInitial = localInsets.left; 6111 mUserPaddingRightInitial = localInsets.right; 6112 internalSetPadding(localInsets.left, localInsets.top, 6113 localInsets.right, localInsets.bottom); 6114 return res; 6115 } 6116 return false; 6117 } 6118 6119 /** 6120 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6121 * 6122 * <p>This method should be overridden by views that wish to apply a policy different from or 6123 * in addition to the default behavior. Clients that wish to force a view subtree 6124 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6125 * 6126 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6127 * it will be called during dispatch instead of this method. The listener may optionally 6128 * call this method from its own implementation if it wishes to apply the view's default 6129 * insets policy in addition to its own.</p> 6130 * 6131 * <p>Implementations of this method should either return the insets parameter unchanged 6132 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6133 * that this view applied itself. This allows new inset types added in future platform 6134 * versions to pass through existing implementations unchanged without being erroneously 6135 * consumed.</p> 6136 * 6137 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6138 * property is set then the view will consume the system window insets and apply them 6139 * as padding for the view.</p> 6140 * 6141 * @param insets Insets to apply 6142 * @return The supplied insets with any applied insets consumed 6143 */ 6144 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6145 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6146 // We weren't called from within a direct call to fitSystemWindows, 6147 // call into it as a fallback in case we're in a class that overrides it 6148 // and has logic to perform. 6149 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6150 return insets.consumeSystemWindowInsets(); 6151 } 6152 } else { 6153 // We were called from within a direct call to fitSystemWindows. 6154 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6155 return insets.consumeSystemWindowInsets(); 6156 } 6157 } 6158 return insets; 6159 } 6160 6161 /** 6162 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6163 * window insets to this view. The listener's 6164 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6165 * method will be called instead of the view's 6166 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6167 * 6168 * @param listener Listener to set 6169 * 6170 * @see #onApplyWindowInsets(WindowInsets) 6171 */ 6172 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6173 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6174 } 6175 6176 /** 6177 * Request to apply the given window insets to this view or another view in its subtree. 6178 * 6179 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6180 * obscured by window decorations or overlays. This can include the status and navigation bars, 6181 * action bars, input methods and more. New inset categories may be added in the future. 6182 * The method returns the insets provided minus any that were applied by this view or its 6183 * children.</p> 6184 * 6185 * <p>Clients wishing to provide custom behavior should override the 6186 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6187 * {@link OnApplyWindowInsetsListener} via the 6188 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6189 * method.</p> 6190 * 6191 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6192 * </p> 6193 * 6194 * @param insets Insets to apply 6195 * @return The provided insets minus the insets that were consumed 6196 */ 6197 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6198 try { 6199 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6200 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6201 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6202 } else { 6203 return onApplyWindowInsets(insets); 6204 } 6205 } finally { 6206 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6207 } 6208 } 6209 6210 /** 6211 * @hide Compute the insets that should be consumed by this view and the ones 6212 * that should propagate to those under it. 6213 */ 6214 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6215 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6216 || mAttachInfo == null 6217 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6218 && !mAttachInfo.mOverscanRequested)) { 6219 outLocalInsets.set(inoutInsets); 6220 inoutInsets.set(0, 0, 0, 0); 6221 return true; 6222 } else { 6223 // The application wants to take care of fitting system window for 6224 // the content... however we still need to take care of any overscan here. 6225 final Rect overscan = mAttachInfo.mOverscanInsets; 6226 outLocalInsets.set(overscan); 6227 inoutInsets.left -= overscan.left; 6228 inoutInsets.top -= overscan.top; 6229 inoutInsets.right -= overscan.right; 6230 inoutInsets.bottom -= overscan.bottom; 6231 return false; 6232 } 6233 } 6234 6235 /** 6236 * Sets whether or not this view should account for system screen decorations 6237 * such as the status bar and inset its content; that is, controlling whether 6238 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6239 * executed. See that method for more details. 6240 * 6241 * <p>Note that if you are providing your own implementation of 6242 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6243 * flag to true -- your implementation will be overriding the default 6244 * implementation that checks this flag. 6245 * 6246 * @param fitSystemWindows If true, then the default implementation of 6247 * {@link #fitSystemWindows(Rect)} will be executed. 6248 * 6249 * @attr ref android.R.styleable#View_fitsSystemWindows 6250 * @see #getFitsSystemWindows() 6251 * @see #fitSystemWindows(Rect) 6252 * @see #setSystemUiVisibility(int) 6253 */ 6254 public void setFitsSystemWindows(boolean fitSystemWindows) { 6255 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6256 } 6257 6258 /** 6259 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6260 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6261 * will be executed. 6262 * 6263 * @return {@code true} if the default implementation of 6264 * {@link #fitSystemWindows(Rect)} will be executed. 6265 * 6266 * @attr ref android.R.styleable#View_fitsSystemWindows 6267 * @see #setFitsSystemWindows(boolean) 6268 * @see #fitSystemWindows(Rect) 6269 * @see #setSystemUiVisibility(int) 6270 */ 6271 public boolean getFitsSystemWindows() { 6272 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6273 } 6274 6275 /** @hide */ 6276 public boolean fitsSystemWindows() { 6277 return getFitsSystemWindows(); 6278 } 6279 6280 /** 6281 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6282 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6283 */ 6284 public void requestFitSystemWindows() { 6285 if (mParent != null) { 6286 mParent.requestFitSystemWindows(); 6287 } 6288 } 6289 6290 /** 6291 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6292 */ 6293 public void requestApplyInsets() { 6294 requestFitSystemWindows(); 6295 } 6296 6297 /** 6298 * For use by PhoneWindow to make its own system window fitting optional. 6299 * @hide 6300 */ 6301 public void makeOptionalFitsSystemWindows() { 6302 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6303 } 6304 6305 /** 6306 * Returns the visibility status for this view. 6307 * 6308 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6309 * @attr ref android.R.styleable#View_visibility 6310 */ 6311 @ViewDebug.ExportedProperty(mapping = { 6312 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6313 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6314 @ViewDebug.IntToString(from = GONE, to = "GONE") 6315 }) 6316 @Visibility 6317 public int getVisibility() { 6318 return mViewFlags & VISIBILITY_MASK; 6319 } 6320 6321 /** 6322 * Set the enabled state of this view. 6323 * 6324 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6325 * @attr ref android.R.styleable#View_visibility 6326 */ 6327 @RemotableViewMethod 6328 public void setVisibility(@Visibility int visibility) { 6329 setFlags(visibility, VISIBILITY_MASK); 6330 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6331 } 6332 6333 /** 6334 * Returns the enabled status for this view. The interpretation of the 6335 * enabled state varies by subclass. 6336 * 6337 * @return True if this view is enabled, false otherwise. 6338 */ 6339 @ViewDebug.ExportedProperty 6340 public boolean isEnabled() { 6341 return (mViewFlags & ENABLED_MASK) == ENABLED; 6342 } 6343 6344 /** 6345 * Set the enabled state of this view. The interpretation of the enabled 6346 * state varies by subclass. 6347 * 6348 * @param enabled True if this view is enabled, false otherwise. 6349 */ 6350 @RemotableViewMethod 6351 public void setEnabled(boolean enabled) { 6352 if (enabled == isEnabled()) return; 6353 6354 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6355 6356 /* 6357 * The View most likely has to change its appearance, so refresh 6358 * the drawable state. 6359 */ 6360 refreshDrawableState(); 6361 6362 // Invalidate too, since the default behavior for views is to be 6363 // be drawn at 50% alpha rather than to change the drawable. 6364 invalidate(true); 6365 6366 if (!enabled) { 6367 cancelPendingInputEvents(); 6368 } 6369 } 6370 6371 /** 6372 * Set whether this view can receive the focus. 6373 * 6374 * Setting this to false will also ensure that this view is not focusable 6375 * in touch mode. 6376 * 6377 * @param focusable If true, this view can receive the focus. 6378 * 6379 * @see #setFocusableInTouchMode(boolean) 6380 * @attr ref android.R.styleable#View_focusable 6381 */ 6382 public void setFocusable(boolean focusable) { 6383 if (!focusable) { 6384 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6385 } 6386 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6387 } 6388 6389 /** 6390 * Set whether this view can receive focus while in touch mode. 6391 * 6392 * Setting this to true will also ensure that this view is focusable. 6393 * 6394 * @param focusableInTouchMode If true, this view can receive the focus while 6395 * in touch mode. 6396 * 6397 * @see #setFocusable(boolean) 6398 * @attr ref android.R.styleable#View_focusableInTouchMode 6399 */ 6400 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6401 // Focusable in touch mode should always be set before the focusable flag 6402 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6403 // which, in touch mode, will not successfully request focus on this view 6404 // because the focusable in touch mode flag is not set 6405 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6406 if (focusableInTouchMode) { 6407 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6408 } 6409 } 6410 6411 /** 6412 * Set whether this view should have sound effects enabled for events such as 6413 * clicking and touching. 6414 * 6415 * <p>You may wish to disable sound effects for a view if you already play sounds, 6416 * for instance, a dial key that plays dtmf tones. 6417 * 6418 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6419 * @see #isSoundEffectsEnabled() 6420 * @see #playSoundEffect(int) 6421 * @attr ref android.R.styleable#View_soundEffectsEnabled 6422 */ 6423 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6424 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6425 } 6426 6427 /** 6428 * @return whether this view should have sound effects enabled for events such as 6429 * clicking and touching. 6430 * 6431 * @see #setSoundEffectsEnabled(boolean) 6432 * @see #playSoundEffect(int) 6433 * @attr ref android.R.styleable#View_soundEffectsEnabled 6434 */ 6435 @ViewDebug.ExportedProperty 6436 public boolean isSoundEffectsEnabled() { 6437 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6438 } 6439 6440 /** 6441 * Set whether this view should have haptic feedback for events such as 6442 * long presses. 6443 * 6444 * <p>You may wish to disable haptic feedback if your view already controls 6445 * its own haptic feedback. 6446 * 6447 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6448 * @see #isHapticFeedbackEnabled() 6449 * @see #performHapticFeedback(int) 6450 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6451 */ 6452 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6453 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6454 } 6455 6456 /** 6457 * @return whether this view should have haptic feedback enabled for events 6458 * long presses. 6459 * 6460 * @see #setHapticFeedbackEnabled(boolean) 6461 * @see #performHapticFeedback(int) 6462 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6463 */ 6464 @ViewDebug.ExportedProperty 6465 public boolean isHapticFeedbackEnabled() { 6466 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6467 } 6468 6469 /** 6470 * Returns the layout direction for this view. 6471 * 6472 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6473 * {@link #LAYOUT_DIRECTION_RTL}, 6474 * {@link #LAYOUT_DIRECTION_INHERIT} or 6475 * {@link #LAYOUT_DIRECTION_LOCALE}. 6476 * 6477 * @attr ref android.R.styleable#View_layoutDirection 6478 * 6479 * @hide 6480 */ 6481 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6482 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6483 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6484 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6485 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6486 }) 6487 @LayoutDir 6488 public int getRawLayoutDirection() { 6489 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6490 } 6491 6492 /** 6493 * Set the layout direction for this view. This will propagate a reset of layout direction 6494 * resolution to the view's children and resolve layout direction for this view. 6495 * 6496 * @param layoutDirection the layout direction to set. Should be one of: 6497 * 6498 * {@link #LAYOUT_DIRECTION_LTR}, 6499 * {@link #LAYOUT_DIRECTION_RTL}, 6500 * {@link #LAYOUT_DIRECTION_INHERIT}, 6501 * {@link #LAYOUT_DIRECTION_LOCALE}. 6502 * 6503 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6504 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6505 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6506 * 6507 * @attr ref android.R.styleable#View_layoutDirection 6508 */ 6509 @RemotableViewMethod 6510 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6511 if (getRawLayoutDirection() != layoutDirection) { 6512 // Reset the current layout direction and the resolved one 6513 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6514 resetRtlProperties(); 6515 // Set the new layout direction (filtered) 6516 mPrivateFlags2 |= 6517 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6518 // We need to resolve all RTL properties as they all depend on layout direction 6519 resolveRtlPropertiesIfNeeded(); 6520 requestLayout(); 6521 invalidate(true); 6522 } 6523 } 6524 6525 /** 6526 * Returns the resolved layout direction for this view. 6527 * 6528 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6529 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6530 * 6531 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6532 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6533 * 6534 * @attr ref android.R.styleable#View_layoutDirection 6535 */ 6536 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6537 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6538 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6539 }) 6540 @ResolvedLayoutDir 6541 public int getLayoutDirection() { 6542 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6543 if (targetSdkVersion < JELLY_BEAN_MR1) { 6544 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6545 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6546 } 6547 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6548 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6549 } 6550 6551 /** 6552 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6553 * layout attribute and/or the inherited value from the parent 6554 * 6555 * @return true if the layout is right-to-left. 6556 * 6557 * @hide 6558 */ 6559 @ViewDebug.ExportedProperty(category = "layout") 6560 public boolean isLayoutRtl() { 6561 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6562 } 6563 6564 /** 6565 * Indicates whether the view is currently tracking transient state that the 6566 * app should not need to concern itself with saving and restoring, but that 6567 * the framework should take special note to preserve when possible. 6568 * 6569 * <p>A view with transient state cannot be trivially rebound from an external 6570 * data source, such as an adapter binding item views in a list. This may be 6571 * because the view is performing an animation, tracking user selection 6572 * of content, or similar.</p> 6573 * 6574 * @return true if the view has transient state 6575 */ 6576 @ViewDebug.ExportedProperty(category = "layout") 6577 public boolean hasTransientState() { 6578 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6579 } 6580 6581 /** 6582 * Set whether this view is currently tracking transient state that the 6583 * framework should attempt to preserve when possible. This flag is reference counted, 6584 * so every call to setHasTransientState(true) should be paired with a later call 6585 * to setHasTransientState(false). 6586 * 6587 * <p>A view with transient state cannot be trivially rebound from an external 6588 * data source, such as an adapter binding item views in a list. This may be 6589 * because the view is performing an animation, tracking user selection 6590 * of content, or similar.</p> 6591 * 6592 * @param hasTransientState true if this view has transient state 6593 */ 6594 public void setHasTransientState(boolean hasTransientState) { 6595 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6596 mTransientStateCount - 1; 6597 if (mTransientStateCount < 0) { 6598 mTransientStateCount = 0; 6599 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6600 "unmatched pair of setHasTransientState calls"); 6601 } else if ((hasTransientState && mTransientStateCount == 1) || 6602 (!hasTransientState && mTransientStateCount == 0)) { 6603 // update flag if we've just incremented up from 0 or decremented down to 0 6604 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6605 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6606 if (mParent != null) { 6607 try { 6608 mParent.childHasTransientStateChanged(this, hasTransientState); 6609 } catch (AbstractMethodError e) { 6610 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6611 " does not fully implement ViewParent", e); 6612 } 6613 } 6614 } 6615 } 6616 6617 /** 6618 * Returns true if this view is currently attached to a window. 6619 */ 6620 public boolean isAttachedToWindow() { 6621 return mAttachInfo != null; 6622 } 6623 6624 /** 6625 * Returns true if this view has been through at least one layout since it 6626 * was last attached to or detached from a window. 6627 */ 6628 public boolean isLaidOut() { 6629 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6630 } 6631 6632 /** 6633 * If this view doesn't do any drawing on its own, set this flag to 6634 * allow further optimizations. By default, this flag is not set on 6635 * View, but could be set on some View subclasses such as ViewGroup. 6636 * 6637 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6638 * you should clear this flag. 6639 * 6640 * @param willNotDraw whether or not this View draw on its own 6641 */ 6642 public void setWillNotDraw(boolean willNotDraw) { 6643 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6644 } 6645 6646 /** 6647 * Returns whether or not this View draws on its own. 6648 * 6649 * @return true if this view has nothing to draw, false otherwise 6650 */ 6651 @ViewDebug.ExportedProperty(category = "drawing") 6652 public boolean willNotDraw() { 6653 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6654 } 6655 6656 /** 6657 * When a View's drawing cache is enabled, drawing is redirected to an 6658 * offscreen bitmap. Some views, like an ImageView, must be able to 6659 * bypass this mechanism if they already draw a single bitmap, to avoid 6660 * unnecessary usage of the memory. 6661 * 6662 * @param willNotCacheDrawing true if this view does not cache its 6663 * drawing, false otherwise 6664 */ 6665 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6666 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6667 } 6668 6669 /** 6670 * Returns whether or not this View can cache its drawing or not. 6671 * 6672 * @return true if this view does not cache its drawing, false otherwise 6673 */ 6674 @ViewDebug.ExportedProperty(category = "drawing") 6675 public boolean willNotCacheDrawing() { 6676 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6677 } 6678 6679 /** 6680 * Indicates whether this view reacts to click events or not. 6681 * 6682 * @return true if the view is clickable, false otherwise 6683 * 6684 * @see #setClickable(boolean) 6685 * @attr ref android.R.styleable#View_clickable 6686 */ 6687 @ViewDebug.ExportedProperty 6688 public boolean isClickable() { 6689 return (mViewFlags & CLICKABLE) == CLICKABLE; 6690 } 6691 6692 /** 6693 * Enables or disables click events for this view. When a view 6694 * is clickable it will change its state to "pressed" on every click. 6695 * Subclasses should set the view clickable to visually react to 6696 * user's clicks. 6697 * 6698 * @param clickable true to make the view clickable, false otherwise 6699 * 6700 * @see #isClickable() 6701 * @attr ref android.R.styleable#View_clickable 6702 */ 6703 public void setClickable(boolean clickable) { 6704 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6705 } 6706 6707 /** 6708 * Indicates whether this view reacts to long click events or not. 6709 * 6710 * @return true if the view is long clickable, false otherwise 6711 * 6712 * @see #setLongClickable(boolean) 6713 * @attr ref android.R.styleable#View_longClickable 6714 */ 6715 public boolean isLongClickable() { 6716 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6717 } 6718 6719 /** 6720 * Enables or disables long click events for this view. When a view is long 6721 * clickable it reacts to the user holding down the button for a longer 6722 * duration than a tap. This event can either launch the listener or a 6723 * context menu. 6724 * 6725 * @param longClickable true to make the view long clickable, false otherwise 6726 * @see #isLongClickable() 6727 * @attr ref android.R.styleable#View_longClickable 6728 */ 6729 public void setLongClickable(boolean longClickable) { 6730 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6731 } 6732 6733 /** 6734 * Sets the pressed state for this view. 6735 * 6736 * @see #isClickable() 6737 * @see #setClickable(boolean) 6738 * 6739 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6740 * the View's internal state from a previously set "pressed" state. 6741 */ 6742 public void setPressed(boolean pressed) { 6743 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6744 6745 if (pressed) { 6746 mPrivateFlags |= PFLAG_PRESSED; 6747 } else { 6748 mPrivateFlags &= ~PFLAG_PRESSED; 6749 } 6750 6751 if (needsRefresh) { 6752 refreshDrawableState(); 6753 } 6754 dispatchSetPressed(pressed); 6755 } 6756 6757 /** 6758 * Dispatch setPressed to all of this View's children. 6759 * 6760 * @see #setPressed(boolean) 6761 * 6762 * @param pressed The new pressed state 6763 */ 6764 protected void dispatchSetPressed(boolean pressed) { 6765 } 6766 6767 /** 6768 * Indicates whether the view is currently in pressed state. Unless 6769 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6770 * the pressed state. 6771 * 6772 * @see #setPressed(boolean) 6773 * @see #isClickable() 6774 * @see #setClickable(boolean) 6775 * 6776 * @return true if the view is currently pressed, false otherwise 6777 */ 6778 public boolean isPressed() { 6779 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6780 } 6781 6782 /** 6783 * Indicates whether this view will save its state (that is, 6784 * whether its {@link #onSaveInstanceState} method will be called). 6785 * 6786 * @return Returns true if the view state saving is enabled, else false. 6787 * 6788 * @see #setSaveEnabled(boolean) 6789 * @attr ref android.R.styleable#View_saveEnabled 6790 */ 6791 public boolean isSaveEnabled() { 6792 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6793 } 6794 6795 /** 6796 * Controls whether the saving of this view's state is 6797 * enabled (that is, whether its {@link #onSaveInstanceState} method 6798 * will be called). Note that even if freezing is enabled, the 6799 * view still must have an id assigned to it (via {@link #setId(int)}) 6800 * for its state to be saved. This flag can only disable the 6801 * saving of this view; any child views may still have their state saved. 6802 * 6803 * @param enabled Set to false to <em>disable</em> state saving, or true 6804 * (the default) to allow it. 6805 * 6806 * @see #isSaveEnabled() 6807 * @see #setId(int) 6808 * @see #onSaveInstanceState() 6809 * @attr ref android.R.styleable#View_saveEnabled 6810 */ 6811 public void setSaveEnabled(boolean enabled) { 6812 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6813 } 6814 6815 /** 6816 * Gets whether the framework should discard touches when the view's 6817 * window is obscured by another visible window. 6818 * Refer to the {@link View} security documentation for more details. 6819 * 6820 * @return True if touch filtering is enabled. 6821 * 6822 * @see #setFilterTouchesWhenObscured(boolean) 6823 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6824 */ 6825 @ViewDebug.ExportedProperty 6826 public boolean getFilterTouchesWhenObscured() { 6827 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6828 } 6829 6830 /** 6831 * Sets whether the framework should discard touches when the view's 6832 * window is obscured by another visible window. 6833 * Refer to the {@link View} security documentation for more details. 6834 * 6835 * @param enabled True if touch filtering should be enabled. 6836 * 6837 * @see #getFilterTouchesWhenObscured 6838 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6839 */ 6840 public void setFilterTouchesWhenObscured(boolean enabled) { 6841 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 6842 FILTER_TOUCHES_WHEN_OBSCURED); 6843 } 6844 6845 /** 6846 * Indicates whether the entire hierarchy under this view will save its 6847 * state when a state saving traversal occurs from its parent. The default 6848 * is true; if false, these views will not be saved unless 6849 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6850 * 6851 * @return Returns true if the view state saving from parent is enabled, else false. 6852 * 6853 * @see #setSaveFromParentEnabled(boolean) 6854 */ 6855 public boolean isSaveFromParentEnabled() { 6856 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6857 } 6858 6859 /** 6860 * Controls whether the entire hierarchy under this view will save its 6861 * state when a state saving traversal occurs from its parent. The default 6862 * is true; if false, these views will not be saved unless 6863 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6864 * 6865 * @param enabled Set to false to <em>disable</em> state saving, or true 6866 * (the default) to allow it. 6867 * 6868 * @see #isSaveFromParentEnabled() 6869 * @see #setId(int) 6870 * @see #onSaveInstanceState() 6871 */ 6872 public void setSaveFromParentEnabled(boolean enabled) { 6873 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6874 } 6875 6876 6877 /** 6878 * Returns whether this View is able to take focus. 6879 * 6880 * @return True if this view can take focus, or false otherwise. 6881 * @attr ref android.R.styleable#View_focusable 6882 */ 6883 @ViewDebug.ExportedProperty(category = "focus") 6884 public final boolean isFocusable() { 6885 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6886 } 6887 6888 /** 6889 * When a view is focusable, it may not want to take focus when in touch mode. 6890 * For example, a button would like focus when the user is navigating via a D-pad 6891 * so that the user can click on it, but once the user starts touching the screen, 6892 * the button shouldn't take focus 6893 * @return Whether the view is focusable in touch mode. 6894 * @attr ref android.R.styleable#View_focusableInTouchMode 6895 */ 6896 @ViewDebug.ExportedProperty 6897 public final boolean isFocusableInTouchMode() { 6898 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6899 } 6900 6901 /** 6902 * Find the nearest view in the specified direction that can take focus. 6903 * This does not actually give focus to that view. 6904 * 6905 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6906 * 6907 * @return The nearest focusable in the specified direction, or null if none 6908 * can be found. 6909 */ 6910 public View focusSearch(@FocusRealDirection int direction) { 6911 if (mParent != null) { 6912 return mParent.focusSearch(this, direction); 6913 } else { 6914 return null; 6915 } 6916 } 6917 6918 /** 6919 * This method is the last chance for the focused view and its ancestors to 6920 * respond to an arrow key. This is called when the focused view did not 6921 * consume the key internally, nor could the view system find a new view in 6922 * the requested direction to give focus to. 6923 * 6924 * @param focused The currently focused view. 6925 * @param direction The direction focus wants to move. One of FOCUS_UP, 6926 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6927 * @return True if the this view consumed this unhandled move. 6928 */ 6929 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 6930 return false; 6931 } 6932 6933 /** 6934 * If a user manually specified the next view id for a particular direction, 6935 * use the root to look up the view. 6936 * @param root The root view of the hierarchy containing this view. 6937 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6938 * or FOCUS_BACKWARD. 6939 * @return The user specified next view, or null if there is none. 6940 */ 6941 View findUserSetNextFocus(View root, @FocusDirection int direction) { 6942 switch (direction) { 6943 case FOCUS_LEFT: 6944 if (mNextFocusLeftId == View.NO_ID) return null; 6945 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6946 case FOCUS_RIGHT: 6947 if (mNextFocusRightId == View.NO_ID) return null; 6948 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6949 case FOCUS_UP: 6950 if (mNextFocusUpId == View.NO_ID) return null; 6951 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6952 case FOCUS_DOWN: 6953 if (mNextFocusDownId == View.NO_ID) return null; 6954 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6955 case FOCUS_FORWARD: 6956 if (mNextFocusForwardId == View.NO_ID) return null; 6957 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6958 case FOCUS_BACKWARD: { 6959 if (mID == View.NO_ID) return null; 6960 final int id = mID; 6961 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6962 @Override 6963 public boolean apply(View t) { 6964 return t.mNextFocusForwardId == id; 6965 } 6966 }); 6967 } 6968 } 6969 return null; 6970 } 6971 6972 private View findViewInsideOutShouldExist(View root, int id) { 6973 if (mMatchIdPredicate == null) { 6974 mMatchIdPredicate = new MatchIdPredicate(); 6975 } 6976 mMatchIdPredicate.mId = id; 6977 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6978 if (result == null) { 6979 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6980 } 6981 return result; 6982 } 6983 6984 /** 6985 * Find and return all focusable views that are descendants of this view, 6986 * possibly including this view if it is focusable itself. 6987 * 6988 * @param direction The direction of the focus 6989 * @return A list of focusable views 6990 */ 6991 public ArrayList<View> getFocusables(@FocusDirection int direction) { 6992 ArrayList<View> result = new ArrayList<View>(24); 6993 addFocusables(result, direction); 6994 return result; 6995 } 6996 6997 /** 6998 * Add any focusable views that are descendants of this view (possibly 6999 * including this view if it is focusable itself) to views. If we are in touch mode, 7000 * only add views that are also focusable in touch mode. 7001 * 7002 * @param views Focusable views found so far 7003 * @param direction The direction of the focus 7004 */ 7005 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7006 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7007 } 7008 7009 /** 7010 * Adds any focusable views that are descendants of this view (possibly 7011 * including this view if it is focusable itself) to views. This method 7012 * adds all focusable views regardless if we are in touch mode or 7013 * only views focusable in touch mode if we are in touch mode or 7014 * only views that can take accessibility focus if accessibility is enabeld 7015 * depending on the focusable mode paramater. 7016 * 7017 * @param views Focusable views found so far or null if all we are interested is 7018 * the number of focusables. 7019 * @param direction The direction of the focus. 7020 * @param focusableMode The type of focusables to be added. 7021 * 7022 * @see #FOCUSABLES_ALL 7023 * @see #FOCUSABLES_TOUCH_MODE 7024 */ 7025 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7026 @FocusableMode int focusableMode) { 7027 if (views == null) { 7028 return; 7029 } 7030 if (!isFocusable()) { 7031 return; 7032 } 7033 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7034 && isInTouchMode() && !isFocusableInTouchMode()) { 7035 return; 7036 } 7037 views.add(this); 7038 } 7039 7040 /** 7041 * Finds the Views that contain given text. The containment is case insensitive. 7042 * The search is performed by either the text that the View renders or the content 7043 * description that describes the view for accessibility purposes and the view does 7044 * not render or both. Clients can specify how the search is to be performed via 7045 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7046 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7047 * 7048 * @param outViews The output list of matching Views. 7049 * @param searched The text to match against. 7050 * 7051 * @see #FIND_VIEWS_WITH_TEXT 7052 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7053 * @see #setContentDescription(CharSequence) 7054 */ 7055 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7056 @FindViewFlags int flags) { 7057 if (getAccessibilityNodeProvider() != null) { 7058 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7059 outViews.add(this); 7060 } 7061 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7062 && (searched != null && searched.length() > 0) 7063 && (mContentDescription != null && mContentDescription.length() > 0)) { 7064 String searchedLowerCase = searched.toString().toLowerCase(); 7065 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7066 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7067 outViews.add(this); 7068 } 7069 } 7070 } 7071 7072 /** 7073 * Find and return all touchable views that are descendants of this view, 7074 * possibly including this view if it is touchable itself. 7075 * 7076 * @return A list of touchable views 7077 */ 7078 public ArrayList<View> getTouchables() { 7079 ArrayList<View> result = new ArrayList<View>(); 7080 addTouchables(result); 7081 return result; 7082 } 7083 7084 /** 7085 * Add any touchable views that are descendants of this view (possibly 7086 * including this view if it is touchable itself) to views. 7087 * 7088 * @param views Touchable views found so far 7089 */ 7090 public void addTouchables(ArrayList<View> views) { 7091 final int viewFlags = mViewFlags; 7092 7093 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7094 && (viewFlags & ENABLED_MASK) == ENABLED) { 7095 views.add(this); 7096 } 7097 } 7098 7099 /** 7100 * Returns whether this View is accessibility focused. 7101 * 7102 * @return True if this View is accessibility focused. 7103 */ 7104 public boolean isAccessibilityFocused() { 7105 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7106 } 7107 7108 /** 7109 * Call this to try to give accessibility focus to this view. 7110 * 7111 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7112 * returns false or the view is no visible or the view already has accessibility 7113 * focus. 7114 * 7115 * See also {@link #focusSearch(int)}, which is what you call to say that you 7116 * have focus, and you want your parent to look for the next one. 7117 * 7118 * @return Whether this view actually took accessibility focus. 7119 * 7120 * @hide 7121 */ 7122 public boolean requestAccessibilityFocus() { 7123 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7124 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7125 return false; 7126 } 7127 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7128 return false; 7129 } 7130 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7131 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7132 ViewRootImpl viewRootImpl = getViewRootImpl(); 7133 if (viewRootImpl != null) { 7134 viewRootImpl.setAccessibilityFocus(this, null); 7135 } 7136 invalidate(); 7137 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7138 return true; 7139 } 7140 return false; 7141 } 7142 7143 /** 7144 * Call this to try to clear accessibility focus of this view. 7145 * 7146 * See also {@link #focusSearch(int)}, which is what you call to say that you 7147 * have focus, and you want your parent to look for the next one. 7148 * 7149 * @hide 7150 */ 7151 public void clearAccessibilityFocus() { 7152 clearAccessibilityFocusNoCallbacks(); 7153 // Clear the global reference of accessibility focus if this 7154 // view or any of its descendants had accessibility focus. 7155 ViewRootImpl viewRootImpl = getViewRootImpl(); 7156 if (viewRootImpl != null) { 7157 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7158 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7159 viewRootImpl.setAccessibilityFocus(null, null); 7160 } 7161 } 7162 } 7163 7164 private void sendAccessibilityHoverEvent(int eventType) { 7165 // Since we are not delivering to a client accessibility events from not 7166 // important views (unless the clinet request that) we need to fire the 7167 // event from the deepest view exposed to the client. As a consequence if 7168 // the user crosses a not exposed view the client will see enter and exit 7169 // of the exposed predecessor followed by and enter and exit of that same 7170 // predecessor when entering and exiting the not exposed descendant. This 7171 // is fine since the client has a clear idea which view is hovered at the 7172 // price of a couple more events being sent. This is a simple and 7173 // working solution. 7174 View source = this; 7175 while (true) { 7176 if (source.includeForAccessibility()) { 7177 source.sendAccessibilityEvent(eventType); 7178 return; 7179 } 7180 ViewParent parent = source.getParent(); 7181 if (parent instanceof View) { 7182 source = (View) parent; 7183 } else { 7184 return; 7185 } 7186 } 7187 } 7188 7189 /** 7190 * Clears accessibility focus without calling any callback methods 7191 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7192 * is used for clearing accessibility focus when giving this focus to 7193 * another view. 7194 */ 7195 void clearAccessibilityFocusNoCallbacks() { 7196 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7197 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7198 invalidate(); 7199 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7200 } 7201 } 7202 7203 /** 7204 * Call this to try to give focus to a specific view or to one of its 7205 * descendants. 7206 * 7207 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7208 * false), or if it is focusable and it is not focusable in touch mode 7209 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7210 * 7211 * See also {@link #focusSearch(int)}, which is what you call to say that you 7212 * have focus, and you want your parent to look for the next one. 7213 * 7214 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7215 * {@link #FOCUS_DOWN} and <code>null</code>. 7216 * 7217 * @return Whether this view or one of its descendants actually took focus. 7218 */ 7219 public final boolean requestFocus() { 7220 return requestFocus(View.FOCUS_DOWN); 7221 } 7222 7223 /** 7224 * Call this to try to give focus to a specific view or to one of its 7225 * descendants and give it a hint about what direction focus is heading. 7226 * 7227 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7228 * false), or if it is focusable and it is not focusable in touch mode 7229 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7230 * 7231 * See also {@link #focusSearch(int)}, which is what you call to say that you 7232 * have focus, and you want your parent to look for the next one. 7233 * 7234 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7235 * <code>null</code> set for the previously focused rectangle. 7236 * 7237 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7238 * @return Whether this view or one of its descendants actually took focus. 7239 */ 7240 public final boolean requestFocus(int direction) { 7241 return requestFocus(direction, null); 7242 } 7243 7244 /** 7245 * Call this to try to give focus to a specific view or to one of its descendants 7246 * and give it hints about the direction and a specific rectangle that the focus 7247 * is coming from. The rectangle can help give larger views a finer grained hint 7248 * about where focus is coming from, and therefore, where to show selection, or 7249 * forward focus change internally. 7250 * 7251 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7252 * false), or if it is focusable and it is not focusable in touch mode 7253 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7254 * 7255 * A View will not take focus if it is not visible. 7256 * 7257 * A View will not take focus if one of its parents has 7258 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7259 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7260 * 7261 * See also {@link #focusSearch(int)}, which is what you call to say that you 7262 * have focus, and you want your parent to look for the next one. 7263 * 7264 * You may wish to override this method if your custom {@link View} has an internal 7265 * {@link View} that it wishes to forward the request to. 7266 * 7267 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7268 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7269 * to give a finer grained hint about where focus is coming from. May be null 7270 * if there is no hint. 7271 * @return Whether this view or one of its descendants actually took focus. 7272 */ 7273 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7274 return requestFocusNoSearch(direction, previouslyFocusedRect); 7275 } 7276 7277 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7278 // need to be focusable 7279 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7280 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7281 return false; 7282 } 7283 7284 // need to be focusable in touch mode if in touch mode 7285 if (isInTouchMode() && 7286 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7287 return false; 7288 } 7289 7290 // need to not have any parents blocking us 7291 if (hasAncestorThatBlocksDescendantFocus()) { 7292 return false; 7293 } 7294 7295 handleFocusGainInternal(direction, previouslyFocusedRect); 7296 return true; 7297 } 7298 7299 /** 7300 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7301 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7302 * touch mode to request focus when they are touched. 7303 * 7304 * @return Whether this view or one of its descendants actually took focus. 7305 * 7306 * @see #isInTouchMode() 7307 * 7308 */ 7309 public final boolean requestFocusFromTouch() { 7310 // Leave touch mode if we need to 7311 if (isInTouchMode()) { 7312 ViewRootImpl viewRoot = getViewRootImpl(); 7313 if (viewRoot != null) { 7314 viewRoot.ensureTouchMode(false); 7315 } 7316 } 7317 return requestFocus(View.FOCUS_DOWN); 7318 } 7319 7320 /** 7321 * @return Whether any ancestor of this view blocks descendant focus. 7322 */ 7323 private boolean hasAncestorThatBlocksDescendantFocus() { 7324 ViewParent ancestor = mParent; 7325 while (ancestor instanceof ViewGroup) { 7326 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7327 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7328 return true; 7329 } else { 7330 ancestor = vgAncestor.getParent(); 7331 } 7332 } 7333 return false; 7334 } 7335 7336 /** 7337 * Gets the mode for determining whether this View is important for accessibility 7338 * which is if it fires accessibility events and if it is reported to 7339 * accessibility services that query the screen. 7340 * 7341 * @return The mode for determining whether a View is important for accessibility. 7342 * 7343 * @attr ref android.R.styleable#View_importantForAccessibility 7344 * 7345 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7346 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7347 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7348 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7349 */ 7350 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7351 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7352 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7353 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7354 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7355 to = "noHideDescendants") 7356 }) 7357 public int getImportantForAccessibility() { 7358 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7359 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7360 } 7361 7362 /** 7363 * Sets the live region mode for this view. This indicates to accessibility 7364 * services whether they should automatically notify the user about changes 7365 * to the view's content description or text, or to the content descriptions 7366 * or text of the view's children (where applicable). 7367 * <p> 7368 * For example, in a login screen with a TextView that displays an "incorrect 7369 * password" notification, that view should be marked as a live region with 7370 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7371 * <p> 7372 * To disable change notifications for this view, use 7373 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7374 * mode for most views. 7375 * <p> 7376 * To indicate that the user should be notified of changes, use 7377 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7378 * <p> 7379 * If the view's changes should interrupt ongoing speech and notify the user 7380 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7381 * 7382 * @param mode The live region mode for this view, one of: 7383 * <ul> 7384 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7385 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7386 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7387 * </ul> 7388 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7389 */ 7390 public void setAccessibilityLiveRegion(int mode) { 7391 if (mode != getAccessibilityLiveRegion()) { 7392 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7393 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7394 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7395 notifyViewAccessibilityStateChangedIfNeeded( 7396 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7397 } 7398 } 7399 7400 /** 7401 * Gets the live region mode for this View. 7402 * 7403 * @return The live region mode for the view. 7404 * 7405 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7406 * 7407 * @see #setAccessibilityLiveRegion(int) 7408 */ 7409 public int getAccessibilityLiveRegion() { 7410 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7411 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7412 } 7413 7414 /** 7415 * Sets how to determine whether this view is important for accessibility 7416 * which is if it fires accessibility events and if it is reported to 7417 * accessibility services that query the screen. 7418 * 7419 * @param mode How to determine whether this view is important for accessibility. 7420 * 7421 * @attr ref android.R.styleable#View_importantForAccessibility 7422 * 7423 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7424 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7425 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7426 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7427 */ 7428 public void setImportantForAccessibility(int mode) { 7429 final int oldMode = getImportantForAccessibility(); 7430 if (mode != oldMode) { 7431 // If we're moving between AUTO and another state, we might not need 7432 // to send a subtree changed notification. We'll store the computed 7433 // importance, since we'll need to check it later to make sure. 7434 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7435 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7436 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7437 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7438 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7439 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7440 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7441 notifySubtreeAccessibilityStateChangedIfNeeded(); 7442 } else { 7443 notifyViewAccessibilityStateChangedIfNeeded( 7444 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7445 } 7446 } 7447 } 7448 7449 /** 7450 * Computes whether this view should be exposed for accessibility. In 7451 * general, views that are interactive or provide information are exposed 7452 * while views that serve only as containers are hidden. 7453 * <p> 7454 * If an ancestor of this view has importance 7455 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7456 * returns <code>false</code>. 7457 * <p> 7458 * Otherwise, the value is computed according to the view's 7459 * {@link #getImportantForAccessibility()} value: 7460 * <ol> 7461 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7462 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7463 * </code> 7464 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7465 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7466 * view satisfies any of the following: 7467 * <ul> 7468 * <li>Is actionable, e.g. {@link #isClickable()}, 7469 * {@link #isLongClickable()}, or {@link #isFocusable()} 7470 * <li>Has an {@link AccessibilityDelegate} 7471 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7472 * {@link OnKeyListener}, etc. 7473 * <li>Is an accessibility live region, e.g. 7474 * {@link #getAccessibilityLiveRegion()} is not 7475 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7476 * </ul> 7477 * </ol> 7478 * 7479 * @return Whether the view is exposed for accessibility. 7480 * @see #setImportantForAccessibility(int) 7481 * @see #getImportantForAccessibility() 7482 */ 7483 public boolean isImportantForAccessibility() { 7484 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7485 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7486 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7487 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7488 return false; 7489 } 7490 7491 // Check parent mode to ensure we're not hidden. 7492 ViewParent parent = mParent; 7493 while (parent instanceof View) { 7494 if (((View) parent).getImportantForAccessibility() 7495 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7496 return false; 7497 } 7498 parent = parent.getParent(); 7499 } 7500 7501 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7502 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7503 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7504 } 7505 7506 /** 7507 * Gets the parent for accessibility purposes. Note that the parent for 7508 * accessibility is not necessary the immediate parent. It is the first 7509 * predecessor that is important for accessibility. 7510 * 7511 * @return The parent for accessibility purposes. 7512 */ 7513 public ViewParent getParentForAccessibility() { 7514 if (mParent instanceof View) { 7515 View parentView = (View) mParent; 7516 if (parentView.includeForAccessibility()) { 7517 return mParent; 7518 } else { 7519 return mParent.getParentForAccessibility(); 7520 } 7521 } 7522 return null; 7523 } 7524 7525 /** 7526 * Adds the children of a given View for accessibility. Since some Views are 7527 * not important for accessibility the children for accessibility are not 7528 * necessarily direct children of the view, rather they are the first level of 7529 * descendants important for accessibility. 7530 * 7531 * @param children The list of children for accessibility. 7532 */ 7533 public void addChildrenForAccessibility(ArrayList<View> children) { 7534 7535 } 7536 7537 /** 7538 * Whether to regard this view for accessibility. A view is regarded for 7539 * accessibility if it is important for accessibility or the querying 7540 * accessibility service has explicitly requested that view not 7541 * important for accessibility are regarded. 7542 * 7543 * @return Whether to regard the view for accessibility. 7544 * 7545 * @hide 7546 */ 7547 public boolean includeForAccessibility() { 7548 if (mAttachInfo != null) { 7549 return (mAttachInfo.mAccessibilityFetchFlags 7550 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7551 || isImportantForAccessibility(); 7552 } 7553 return false; 7554 } 7555 7556 /** 7557 * Returns whether the View is considered actionable from 7558 * accessibility perspective. Such view are important for 7559 * accessibility. 7560 * 7561 * @return True if the view is actionable for accessibility. 7562 * 7563 * @hide 7564 */ 7565 public boolean isActionableForAccessibility() { 7566 return (isClickable() || isLongClickable() || isFocusable()); 7567 } 7568 7569 /** 7570 * Returns whether the View has registered callbacks which makes it 7571 * important for accessibility. 7572 * 7573 * @return True if the view is actionable for accessibility. 7574 */ 7575 private boolean hasListenersForAccessibility() { 7576 ListenerInfo info = getListenerInfo(); 7577 return mTouchDelegate != null || info.mOnKeyListener != null 7578 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7579 || info.mOnHoverListener != null || info.mOnDragListener != null; 7580 } 7581 7582 /** 7583 * Notifies that the accessibility state of this view changed. The change 7584 * is local to this view and does not represent structural changes such 7585 * as children and parent. For example, the view became focusable. The 7586 * notification is at at most once every 7587 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7588 * to avoid unnecessary load to the system. Also once a view has a pending 7589 * notification this method is a NOP until the notification has been sent. 7590 * 7591 * @hide 7592 */ 7593 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7594 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7595 return; 7596 } 7597 if (mSendViewStateChangedAccessibilityEvent == null) { 7598 mSendViewStateChangedAccessibilityEvent = 7599 new SendViewStateChangedAccessibilityEvent(); 7600 } 7601 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7602 } 7603 7604 /** 7605 * Notifies that the accessibility state of this view changed. The change 7606 * is *not* local to this view and does represent structural changes such 7607 * as children and parent. For example, the view size changed. The 7608 * notification is at at most once every 7609 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7610 * to avoid unnecessary load to the system. Also once a view has a pending 7611 * notifucation this method is a NOP until the notification has been sent. 7612 * 7613 * @hide 7614 */ 7615 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7616 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7617 return; 7618 } 7619 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7620 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7621 if (mParent != null) { 7622 try { 7623 mParent.notifySubtreeAccessibilityStateChanged( 7624 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7625 } catch (AbstractMethodError e) { 7626 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7627 " does not fully implement ViewParent", e); 7628 } 7629 } 7630 } 7631 } 7632 7633 /** 7634 * Reset the flag indicating the accessibility state of the subtree rooted 7635 * at this view changed. 7636 */ 7637 void resetSubtreeAccessibilityStateChanged() { 7638 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7639 } 7640 7641 /** 7642 * Performs the specified accessibility action on the view. For 7643 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7644 * <p> 7645 * If an {@link AccessibilityDelegate} has been specified via calling 7646 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7647 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7648 * is responsible for handling this call. 7649 * </p> 7650 * 7651 * @param action The action to perform. 7652 * @param arguments Optional action arguments. 7653 * @return Whether the action was performed. 7654 */ 7655 public boolean performAccessibilityAction(int action, Bundle arguments) { 7656 if (mAccessibilityDelegate != null) { 7657 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7658 } else { 7659 return performAccessibilityActionInternal(action, arguments); 7660 } 7661 } 7662 7663 /** 7664 * @see #performAccessibilityAction(int, Bundle) 7665 * 7666 * Note: Called from the default {@link AccessibilityDelegate}. 7667 */ 7668 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7669 switch (action) { 7670 case AccessibilityNodeInfo.ACTION_CLICK: { 7671 if (isClickable()) { 7672 performClick(); 7673 return true; 7674 } 7675 } break; 7676 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7677 if (isLongClickable()) { 7678 performLongClick(); 7679 return true; 7680 } 7681 } break; 7682 case AccessibilityNodeInfo.ACTION_FOCUS: { 7683 if (!hasFocus()) { 7684 // Get out of touch mode since accessibility 7685 // wants to move focus around. 7686 getViewRootImpl().ensureTouchMode(false); 7687 return requestFocus(); 7688 } 7689 } break; 7690 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7691 if (hasFocus()) { 7692 clearFocus(); 7693 return !isFocused(); 7694 } 7695 } break; 7696 case AccessibilityNodeInfo.ACTION_SELECT: { 7697 if (!isSelected()) { 7698 setSelected(true); 7699 return isSelected(); 7700 } 7701 } break; 7702 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7703 if (isSelected()) { 7704 setSelected(false); 7705 return !isSelected(); 7706 } 7707 } break; 7708 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7709 if (!isAccessibilityFocused()) { 7710 return requestAccessibilityFocus(); 7711 } 7712 } break; 7713 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7714 if (isAccessibilityFocused()) { 7715 clearAccessibilityFocus(); 7716 return true; 7717 } 7718 } break; 7719 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7720 if (arguments != null) { 7721 final int granularity = arguments.getInt( 7722 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7723 final boolean extendSelection = arguments.getBoolean( 7724 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7725 return traverseAtGranularity(granularity, true, extendSelection); 7726 } 7727 } break; 7728 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7729 if (arguments != null) { 7730 final int granularity = arguments.getInt( 7731 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7732 final boolean extendSelection = arguments.getBoolean( 7733 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7734 return traverseAtGranularity(granularity, false, extendSelection); 7735 } 7736 } break; 7737 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7738 CharSequence text = getIterableTextForAccessibility(); 7739 if (text == null) { 7740 return false; 7741 } 7742 final int start = (arguments != null) ? arguments.getInt( 7743 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7744 final int end = (arguments != null) ? arguments.getInt( 7745 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7746 // Only cursor position can be specified (selection length == 0) 7747 if ((getAccessibilitySelectionStart() != start 7748 || getAccessibilitySelectionEnd() != end) 7749 && (start == end)) { 7750 setAccessibilitySelection(start, end); 7751 notifyViewAccessibilityStateChangedIfNeeded( 7752 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7753 return true; 7754 } 7755 } break; 7756 } 7757 return false; 7758 } 7759 7760 private boolean traverseAtGranularity(int granularity, boolean forward, 7761 boolean extendSelection) { 7762 CharSequence text = getIterableTextForAccessibility(); 7763 if (text == null || text.length() == 0) { 7764 return false; 7765 } 7766 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7767 if (iterator == null) { 7768 return false; 7769 } 7770 int current = getAccessibilitySelectionEnd(); 7771 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7772 current = forward ? 0 : text.length(); 7773 } 7774 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7775 if (range == null) { 7776 return false; 7777 } 7778 final int segmentStart = range[0]; 7779 final int segmentEnd = range[1]; 7780 int selectionStart; 7781 int selectionEnd; 7782 if (extendSelection && isAccessibilitySelectionExtendable()) { 7783 selectionStart = getAccessibilitySelectionStart(); 7784 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7785 selectionStart = forward ? segmentStart : segmentEnd; 7786 } 7787 selectionEnd = forward ? segmentEnd : segmentStart; 7788 } else { 7789 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7790 } 7791 setAccessibilitySelection(selectionStart, selectionEnd); 7792 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7793 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7794 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7795 return true; 7796 } 7797 7798 /** 7799 * Gets the text reported for accessibility purposes. 7800 * 7801 * @return The accessibility text. 7802 * 7803 * @hide 7804 */ 7805 public CharSequence getIterableTextForAccessibility() { 7806 return getContentDescription(); 7807 } 7808 7809 /** 7810 * Gets whether accessibility selection can be extended. 7811 * 7812 * @return If selection is extensible. 7813 * 7814 * @hide 7815 */ 7816 public boolean isAccessibilitySelectionExtendable() { 7817 return false; 7818 } 7819 7820 /** 7821 * @hide 7822 */ 7823 public int getAccessibilitySelectionStart() { 7824 return mAccessibilityCursorPosition; 7825 } 7826 7827 /** 7828 * @hide 7829 */ 7830 public int getAccessibilitySelectionEnd() { 7831 return getAccessibilitySelectionStart(); 7832 } 7833 7834 /** 7835 * @hide 7836 */ 7837 public void setAccessibilitySelection(int start, int end) { 7838 if (start == end && end == mAccessibilityCursorPosition) { 7839 return; 7840 } 7841 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7842 mAccessibilityCursorPosition = start; 7843 } else { 7844 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7845 } 7846 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7847 } 7848 7849 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7850 int fromIndex, int toIndex) { 7851 if (mParent == null) { 7852 return; 7853 } 7854 AccessibilityEvent event = AccessibilityEvent.obtain( 7855 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7856 onInitializeAccessibilityEvent(event); 7857 onPopulateAccessibilityEvent(event); 7858 event.setFromIndex(fromIndex); 7859 event.setToIndex(toIndex); 7860 event.setAction(action); 7861 event.setMovementGranularity(granularity); 7862 mParent.requestSendAccessibilityEvent(this, event); 7863 } 7864 7865 /** 7866 * @hide 7867 */ 7868 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7869 switch (granularity) { 7870 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7871 CharSequence text = getIterableTextForAccessibility(); 7872 if (text != null && text.length() > 0) { 7873 CharacterTextSegmentIterator iterator = 7874 CharacterTextSegmentIterator.getInstance( 7875 mContext.getResources().getConfiguration().locale); 7876 iterator.initialize(text.toString()); 7877 return iterator; 7878 } 7879 } break; 7880 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7881 CharSequence text = getIterableTextForAccessibility(); 7882 if (text != null && text.length() > 0) { 7883 WordTextSegmentIterator iterator = 7884 WordTextSegmentIterator.getInstance( 7885 mContext.getResources().getConfiguration().locale); 7886 iterator.initialize(text.toString()); 7887 return iterator; 7888 } 7889 } break; 7890 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7891 CharSequence text = getIterableTextForAccessibility(); 7892 if (text != null && text.length() > 0) { 7893 ParagraphTextSegmentIterator iterator = 7894 ParagraphTextSegmentIterator.getInstance(); 7895 iterator.initialize(text.toString()); 7896 return iterator; 7897 } 7898 } break; 7899 } 7900 return null; 7901 } 7902 7903 /** 7904 * @hide 7905 */ 7906 public void dispatchStartTemporaryDetach() { 7907 onStartTemporaryDetach(); 7908 } 7909 7910 /** 7911 * This is called when a container is going to temporarily detach a child, with 7912 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7913 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7914 * {@link #onDetachedFromWindow()} when the container is done. 7915 */ 7916 public void onStartTemporaryDetach() { 7917 removeUnsetPressCallback(); 7918 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7919 } 7920 7921 /** 7922 * @hide 7923 */ 7924 public void dispatchFinishTemporaryDetach() { 7925 onFinishTemporaryDetach(); 7926 } 7927 7928 /** 7929 * Called after {@link #onStartTemporaryDetach} when the container is done 7930 * changing the view. 7931 */ 7932 public void onFinishTemporaryDetach() { 7933 } 7934 7935 /** 7936 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7937 * for this view's window. Returns null if the view is not currently attached 7938 * to the window. Normally you will not need to use this directly, but 7939 * just use the standard high-level event callbacks like 7940 * {@link #onKeyDown(int, KeyEvent)}. 7941 */ 7942 public KeyEvent.DispatcherState getKeyDispatcherState() { 7943 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7944 } 7945 7946 /** 7947 * Dispatch a key event before it is processed by any input method 7948 * associated with the view hierarchy. This can be used to intercept 7949 * key events in special situations before the IME consumes them; a 7950 * typical example would be handling the BACK key to update the application's 7951 * UI instead of allowing the IME to see it and close itself. 7952 * 7953 * @param event The key event to be dispatched. 7954 * @return True if the event was handled, false otherwise. 7955 */ 7956 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7957 return onKeyPreIme(event.getKeyCode(), event); 7958 } 7959 7960 /** 7961 * Dispatch a key event to the next view on the focus path. This path runs 7962 * from the top of the view tree down to the currently focused view. If this 7963 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7964 * the next node down the focus path. This method also fires any key 7965 * listeners. 7966 * 7967 * @param event The key event to be dispatched. 7968 * @return True if the event was handled, false otherwise. 7969 */ 7970 public boolean dispatchKeyEvent(KeyEvent event) { 7971 if (mInputEventConsistencyVerifier != null) { 7972 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7973 } 7974 7975 // Give any attached key listener a first crack at the event. 7976 //noinspection SimplifiableIfStatement 7977 ListenerInfo li = mListenerInfo; 7978 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7979 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7980 return true; 7981 } 7982 7983 if (event.dispatch(this, mAttachInfo != null 7984 ? mAttachInfo.mKeyDispatchState : null, this)) { 7985 return true; 7986 } 7987 7988 if (mInputEventConsistencyVerifier != null) { 7989 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7990 } 7991 return false; 7992 } 7993 7994 /** 7995 * Dispatches a key shortcut event. 7996 * 7997 * @param event The key event to be dispatched. 7998 * @return True if the event was handled by the view, false otherwise. 7999 */ 8000 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8001 return onKeyShortcut(event.getKeyCode(), event); 8002 } 8003 8004 /** 8005 * Pass the touch screen motion event down to the target view, or this 8006 * view if it is the target. 8007 * 8008 * @param event The motion event to be dispatched. 8009 * @return True if the event was handled by the view, false otherwise. 8010 */ 8011 public boolean dispatchTouchEvent(MotionEvent event) { 8012 boolean result = false; 8013 8014 if (mInputEventConsistencyVerifier != null) { 8015 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8016 } 8017 8018 final int actionMasked = event.getActionMasked(); 8019 if (actionMasked == MotionEvent.ACTION_DOWN) { 8020 // Defensive cleanup for new gesture 8021 stopNestedScroll(); 8022 } 8023 8024 if (onFilterTouchEventForSecurity(event)) { 8025 //noinspection SimplifiableIfStatement 8026 ListenerInfo li = mListenerInfo; 8027 if (li != null && li.mOnTouchListener != null 8028 && (mViewFlags & ENABLED_MASK) == ENABLED 8029 && li.mOnTouchListener.onTouch(this, event)) { 8030 result = true; 8031 } 8032 8033 if (!result && onTouchEvent(event)) { 8034 result = true; 8035 } 8036 } 8037 8038 if (!result && mInputEventConsistencyVerifier != null) { 8039 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8040 } 8041 8042 // Clean up after nested scrolls if this is the end of a gesture; 8043 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8044 // of the gesture. 8045 if (actionMasked == MotionEvent.ACTION_UP || 8046 actionMasked == MotionEvent.ACTION_CANCEL || 8047 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8048 stopNestedScroll(); 8049 } 8050 8051 return result; 8052 } 8053 8054 /** 8055 * Filter the touch event to apply security policies. 8056 * 8057 * @param event The motion event to be filtered. 8058 * @return True if the event should be dispatched, false if the event should be dropped. 8059 * 8060 * @see #getFilterTouchesWhenObscured 8061 */ 8062 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8063 //noinspection RedundantIfStatement 8064 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8065 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8066 // Window is obscured, drop this touch. 8067 return false; 8068 } 8069 return true; 8070 } 8071 8072 /** 8073 * Pass a trackball motion event down to the focused view. 8074 * 8075 * @param event The motion event to be dispatched. 8076 * @return True if the event was handled by the view, false otherwise. 8077 */ 8078 public boolean dispatchTrackballEvent(MotionEvent event) { 8079 if (mInputEventConsistencyVerifier != null) { 8080 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8081 } 8082 8083 return onTrackballEvent(event); 8084 } 8085 8086 /** 8087 * Dispatch a generic motion event. 8088 * <p> 8089 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8090 * are delivered to the view under the pointer. All other generic motion events are 8091 * delivered to the focused view. Hover events are handled specially and are delivered 8092 * to {@link #onHoverEvent(MotionEvent)}. 8093 * </p> 8094 * 8095 * @param event The motion event to be dispatched. 8096 * @return True if the event was handled by the view, false otherwise. 8097 */ 8098 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8099 if (mInputEventConsistencyVerifier != null) { 8100 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8101 } 8102 8103 final int source = event.getSource(); 8104 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8105 final int action = event.getAction(); 8106 if (action == MotionEvent.ACTION_HOVER_ENTER 8107 || action == MotionEvent.ACTION_HOVER_MOVE 8108 || action == MotionEvent.ACTION_HOVER_EXIT) { 8109 if (dispatchHoverEvent(event)) { 8110 return true; 8111 } 8112 } else if (dispatchGenericPointerEvent(event)) { 8113 return true; 8114 } 8115 } else if (dispatchGenericFocusedEvent(event)) { 8116 return true; 8117 } 8118 8119 if (dispatchGenericMotionEventInternal(event)) { 8120 return true; 8121 } 8122 8123 if (mInputEventConsistencyVerifier != null) { 8124 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8125 } 8126 return false; 8127 } 8128 8129 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8130 //noinspection SimplifiableIfStatement 8131 ListenerInfo li = mListenerInfo; 8132 if (li != null && li.mOnGenericMotionListener != null 8133 && (mViewFlags & ENABLED_MASK) == ENABLED 8134 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8135 return true; 8136 } 8137 8138 if (onGenericMotionEvent(event)) { 8139 return true; 8140 } 8141 8142 if (mInputEventConsistencyVerifier != null) { 8143 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8144 } 8145 return false; 8146 } 8147 8148 /** 8149 * Dispatch a hover event. 8150 * <p> 8151 * Do not call this method directly. 8152 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8153 * </p> 8154 * 8155 * @param event The motion event to be dispatched. 8156 * @return True if the event was handled by the view, false otherwise. 8157 */ 8158 protected boolean dispatchHoverEvent(MotionEvent event) { 8159 ListenerInfo li = mListenerInfo; 8160 //noinspection SimplifiableIfStatement 8161 if (li != null && li.mOnHoverListener != null 8162 && (mViewFlags & ENABLED_MASK) == ENABLED 8163 && li.mOnHoverListener.onHover(this, event)) { 8164 return true; 8165 } 8166 8167 return onHoverEvent(event); 8168 } 8169 8170 /** 8171 * Returns true if the view has a child to which it has recently sent 8172 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8173 * it does not have a hovered child, then it must be the innermost hovered view. 8174 * @hide 8175 */ 8176 protected boolean hasHoveredChild() { 8177 return false; 8178 } 8179 8180 /** 8181 * Dispatch a generic motion event to the view under the first pointer. 8182 * <p> 8183 * Do not call this method directly. 8184 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8185 * </p> 8186 * 8187 * @param event The motion event to be dispatched. 8188 * @return True if the event was handled by the view, false otherwise. 8189 */ 8190 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8191 return false; 8192 } 8193 8194 /** 8195 * Dispatch a generic motion event to the currently focused view. 8196 * <p> 8197 * Do not call this method directly. 8198 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8199 * </p> 8200 * 8201 * @param event The motion event to be dispatched. 8202 * @return True if the event was handled by the view, false otherwise. 8203 */ 8204 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8205 return false; 8206 } 8207 8208 /** 8209 * Dispatch a pointer event. 8210 * <p> 8211 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8212 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8213 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8214 * and should not be expected to handle other pointing device features. 8215 * </p> 8216 * 8217 * @param event The motion event to be dispatched. 8218 * @return True if the event was handled by the view, false otherwise. 8219 * @hide 8220 */ 8221 public final boolean dispatchPointerEvent(MotionEvent event) { 8222 if (event.isTouchEvent()) { 8223 return dispatchTouchEvent(event); 8224 } else { 8225 return dispatchGenericMotionEvent(event); 8226 } 8227 } 8228 8229 /** 8230 * Called when the window containing this view gains or loses window focus. 8231 * ViewGroups should override to route to their children. 8232 * 8233 * @param hasFocus True if the window containing this view now has focus, 8234 * false otherwise. 8235 */ 8236 public void dispatchWindowFocusChanged(boolean hasFocus) { 8237 onWindowFocusChanged(hasFocus); 8238 } 8239 8240 /** 8241 * Called when the window containing this view gains or loses focus. Note 8242 * that this is separate from view focus: to receive key events, both 8243 * your view and its window must have focus. If a window is displayed 8244 * on top of yours that takes input focus, then your own window will lose 8245 * focus but the view focus will remain unchanged. 8246 * 8247 * @param hasWindowFocus True if the window containing this view now has 8248 * focus, false otherwise. 8249 */ 8250 public void onWindowFocusChanged(boolean hasWindowFocus) { 8251 InputMethodManager imm = InputMethodManager.peekInstance(); 8252 if (!hasWindowFocus) { 8253 if (isPressed()) { 8254 setPressed(false); 8255 } 8256 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8257 imm.focusOut(this); 8258 } 8259 removeLongPressCallback(); 8260 removeTapCallback(); 8261 onFocusLost(); 8262 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8263 imm.focusIn(this); 8264 } 8265 refreshDrawableState(); 8266 } 8267 8268 /** 8269 * Returns true if this view is in a window that currently has window focus. 8270 * Note that this is not the same as the view itself having focus. 8271 * 8272 * @return True if this view is in a window that currently has window focus. 8273 */ 8274 public boolean hasWindowFocus() { 8275 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8276 } 8277 8278 /** 8279 * Dispatch a view visibility change down the view hierarchy. 8280 * ViewGroups should override to route to their children. 8281 * @param changedView The view whose visibility changed. Could be 'this' or 8282 * an ancestor view. 8283 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8284 * {@link #INVISIBLE} or {@link #GONE}. 8285 */ 8286 protected void dispatchVisibilityChanged(@NonNull View changedView, 8287 @Visibility int visibility) { 8288 onVisibilityChanged(changedView, visibility); 8289 } 8290 8291 /** 8292 * Called when the visibility of the view or an ancestor of the view is changed. 8293 * @param changedView The view whose visibility changed. Could be 'this' or 8294 * an ancestor view. 8295 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8296 * {@link #INVISIBLE} or {@link #GONE}. 8297 */ 8298 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8299 if (visibility == VISIBLE) { 8300 if (mAttachInfo != null) { 8301 initialAwakenScrollBars(); 8302 } else { 8303 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8304 } 8305 } 8306 } 8307 8308 /** 8309 * Dispatch a hint about whether this view is displayed. For instance, when 8310 * a View moves out of the screen, it might receives a display hint indicating 8311 * the view is not displayed. Applications should not <em>rely</em> on this hint 8312 * as there is no guarantee that they will receive one. 8313 * 8314 * @param hint A hint about whether or not this view is displayed: 8315 * {@link #VISIBLE} or {@link #INVISIBLE}. 8316 */ 8317 public void dispatchDisplayHint(@Visibility int hint) { 8318 onDisplayHint(hint); 8319 } 8320 8321 /** 8322 * Gives this view a hint about whether is displayed or not. For instance, when 8323 * a View moves out of the screen, it might receives a display hint indicating 8324 * the view is not displayed. Applications should not <em>rely</em> on this hint 8325 * as there is no guarantee that they will receive one. 8326 * 8327 * @param hint A hint about whether or not this view is displayed: 8328 * {@link #VISIBLE} or {@link #INVISIBLE}. 8329 */ 8330 protected void onDisplayHint(@Visibility int hint) { 8331 } 8332 8333 /** 8334 * Dispatch a window visibility change down the view hierarchy. 8335 * ViewGroups should override to route to their children. 8336 * 8337 * @param visibility The new visibility of the window. 8338 * 8339 * @see #onWindowVisibilityChanged(int) 8340 */ 8341 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8342 onWindowVisibilityChanged(visibility); 8343 } 8344 8345 /** 8346 * Called when the window containing has change its visibility 8347 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8348 * that this tells you whether or not your window is being made visible 8349 * to the window manager; this does <em>not</em> tell you whether or not 8350 * your window is obscured by other windows on the screen, even if it 8351 * is itself visible. 8352 * 8353 * @param visibility The new visibility of the window. 8354 */ 8355 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8356 if (visibility == VISIBLE) { 8357 initialAwakenScrollBars(); 8358 } 8359 } 8360 8361 /** 8362 * Returns the current visibility of the window this view is attached to 8363 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8364 * 8365 * @return Returns the current visibility of the view's window. 8366 */ 8367 @Visibility 8368 public int getWindowVisibility() { 8369 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8370 } 8371 8372 /** 8373 * Retrieve the overall visible display size in which the window this view is 8374 * attached to has been positioned in. This takes into account screen 8375 * decorations above the window, for both cases where the window itself 8376 * is being position inside of them or the window is being placed under 8377 * then and covered insets are used for the window to position its content 8378 * inside. In effect, this tells you the available area where content can 8379 * be placed and remain visible to users. 8380 * 8381 * <p>This function requires an IPC back to the window manager to retrieve 8382 * the requested information, so should not be used in performance critical 8383 * code like drawing. 8384 * 8385 * @param outRect Filled in with the visible display frame. If the view 8386 * is not attached to a window, this is simply the raw display size. 8387 */ 8388 public void getWindowVisibleDisplayFrame(Rect outRect) { 8389 if (mAttachInfo != null) { 8390 try { 8391 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8392 } catch (RemoteException e) { 8393 return; 8394 } 8395 // XXX This is really broken, and probably all needs to be done 8396 // in the window manager, and we need to know more about whether 8397 // we want the area behind or in front of the IME. 8398 final Rect insets = mAttachInfo.mVisibleInsets; 8399 outRect.left += insets.left; 8400 outRect.top += insets.top; 8401 outRect.right -= insets.right; 8402 outRect.bottom -= insets.bottom; 8403 return; 8404 } 8405 // The view is not attached to a display so we don't have a context. 8406 // Make a best guess about the display size. 8407 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8408 d.getRectSize(outRect); 8409 } 8410 8411 /** 8412 * Dispatch a notification about a resource configuration change down 8413 * the view hierarchy. 8414 * ViewGroups should override to route to their children. 8415 * 8416 * @param newConfig The new resource configuration. 8417 * 8418 * @see #onConfigurationChanged(android.content.res.Configuration) 8419 */ 8420 public void dispatchConfigurationChanged(Configuration newConfig) { 8421 onConfigurationChanged(newConfig); 8422 } 8423 8424 /** 8425 * Called when the current configuration of the resources being used 8426 * by the application have changed. You can use this to decide when 8427 * to reload resources that can changed based on orientation and other 8428 * configuration characterstics. You only need to use this if you are 8429 * not relying on the normal {@link android.app.Activity} mechanism of 8430 * recreating the activity instance upon a configuration change. 8431 * 8432 * @param newConfig The new resource configuration. 8433 */ 8434 protected void onConfigurationChanged(Configuration newConfig) { 8435 } 8436 8437 /** 8438 * Private function to aggregate all per-view attributes in to the view 8439 * root. 8440 */ 8441 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8442 performCollectViewAttributes(attachInfo, visibility); 8443 } 8444 8445 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8446 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8447 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8448 attachInfo.mKeepScreenOn = true; 8449 } 8450 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8451 ListenerInfo li = mListenerInfo; 8452 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8453 attachInfo.mHasSystemUiListeners = true; 8454 } 8455 } 8456 } 8457 8458 void needGlobalAttributesUpdate(boolean force) { 8459 final AttachInfo ai = mAttachInfo; 8460 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8461 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8462 || ai.mHasSystemUiListeners) { 8463 ai.mRecomputeGlobalAttributes = true; 8464 } 8465 } 8466 } 8467 8468 /** 8469 * Returns whether the device is currently in touch mode. Touch mode is entered 8470 * once the user begins interacting with the device by touch, and affects various 8471 * things like whether focus is always visible to the user. 8472 * 8473 * @return Whether the device is in touch mode. 8474 */ 8475 @ViewDebug.ExportedProperty 8476 public boolean isInTouchMode() { 8477 if (mAttachInfo != null) { 8478 return mAttachInfo.mInTouchMode; 8479 } else { 8480 return ViewRootImpl.isInTouchMode(); 8481 } 8482 } 8483 8484 /** 8485 * Returns the context the view is running in, through which it can 8486 * access the current theme, resources, etc. 8487 * 8488 * @return The view's Context. 8489 */ 8490 @ViewDebug.CapturedViewProperty 8491 public final Context getContext() { 8492 return mContext; 8493 } 8494 8495 /** 8496 * Handle a key event before it is processed by any input method 8497 * associated with the view hierarchy. This can be used to intercept 8498 * key events in special situations before the IME consumes them; a 8499 * typical example would be handling the BACK key to update the application's 8500 * UI instead of allowing the IME to see it and close itself. 8501 * 8502 * @param keyCode The value in event.getKeyCode(). 8503 * @param event Description of the key event. 8504 * @return If you handled the event, return true. If you want to allow the 8505 * event to be handled by the next receiver, return false. 8506 */ 8507 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8508 return false; 8509 } 8510 8511 /** 8512 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8513 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8514 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8515 * is released, if the view is enabled and clickable. 8516 * 8517 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8518 * although some may elect to do so in some situations. Do not rely on this to 8519 * catch software key presses. 8520 * 8521 * @param keyCode A key code that represents the button pressed, from 8522 * {@link android.view.KeyEvent}. 8523 * @param event The KeyEvent object that defines the button action. 8524 */ 8525 public boolean onKeyDown(int keyCode, KeyEvent event) { 8526 boolean result = false; 8527 8528 if (KeyEvent.isConfirmKey(keyCode)) { 8529 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8530 return true; 8531 } 8532 // Long clickable items don't necessarily have to be clickable 8533 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8534 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8535 (event.getRepeatCount() == 0)) { 8536 setPressed(true); 8537 checkForLongClick(0); 8538 return true; 8539 } 8540 } 8541 return result; 8542 } 8543 8544 /** 8545 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8546 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8547 * the event). 8548 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8549 * although some may elect to do so in some situations. Do not rely on this to 8550 * catch software key presses. 8551 */ 8552 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8553 return false; 8554 } 8555 8556 /** 8557 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8558 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8559 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8560 * {@link KeyEvent#KEYCODE_ENTER} is released. 8561 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8562 * although some may elect to do so in some situations. Do not rely on this to 8563 * catch software key presses. 8564 * 8565 * @param keyCode A key code that represents the button pressed, from 8566 * {@link android.view.KeyEvent}. 8567 * @param event The KeyEvent object that defines the button action. 8568 */ 8569 public boolean onKeyUp(int keyCode, KeyEvent event) { 8570 if (KeyEvent.isConfirmKey(keyCode)) { 8571 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8572 return true; 8573 } 8574 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8575 setPressed(false); 8576 8577 if (!mHasPerformedLongPress) { 8578 // This is a tap, so remove the longpress check 8579 removeLongPressCallback(); 8580 return performClick(); 8581 } 8582 } 8583 } 8584 return false; 8585 } 8586 8587 /** 8588 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8589 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8590 * the event). 8591 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8592 * although some may elect to do so in some situations. Do not rely on this to 8593 * catch software key presses. 8594 * 8595 * @param keyCode A key code that represents the button pressed, from 8596 * {@link android.view.KeyEvent}. 8597 * @param repeatCount The number of times the action was made. 8598 * @param event The KeyEvent object that defines the button action. 8599 */ 8600 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8601 return false; 8602 } 8603 8604 /** 8605 * Called on the focused view when a key shortcut event is not handled. 8606 * Override this method to implement local key shortcuts for the View. 8607 * Key shortcuts can also be implemented by setting the 8608 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8609 * 8610 * @param keyCode The value in event.getKeyCode(). 8611 * @param event Description of the key event. 8612 * @return If you handled the event, return true. If you want to allow the 8613 * event to be handled by the next receiver, return false. 8614 */ 8615 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8616 return false; 8617 } 8618 8619 /** 8620 * Check whether the called view is a text editor, in which case it 8621 * would make sense to automatically display a soft input window for 8622 * it. Subclasses should override this if they implement 8623 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8624 * a call on that method would return a non-null InputConnection, and 8625 * they are really a first-class editor that the user would normally 8626 * start typing on when the go into a window containing your view. 8627 * 8628 * <p>The default implementation always returns false. This does 8629 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8630 * will not be called or the user can not otherwise perform edits on your 8631 * view; it is just a hint to the system that this is not the primary 8632 * purpose of this view. 8633 * 8634 * @return Returns true if this view is a text editor, else false. 8635 */ 8636 public boolean onCheckIsTextEditor() { 8637 return false; 8638 } 8639 8640 /** 8641 * Create a new InputConnection for an InputMethod to interact 8642 * with the view. The default implementation returns null, since it doesn't 8643 * support input methods. You can override this to implement such support. 8644 * This is only needed for views that take focus and text input. 8645 * 8646 * <p>When implementing this, you probably also want to implement 8647 * {@link #onCheckIsTextEditor()} to indicate you will return a 8648 * non-null InputConnection.</p> 8649 * 8650 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8651 * object correctly and in its entirety, so that the connected IME can rely 8652 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8653 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8654 * must be filled in with the correct cursor position for IMEs to work correctly 8655 * with your application.</p> 8656 * 8657 * @param outAttrs Fill in with attribute information about the connection. 8658 */ 8659 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8660 return null; 8661 } 8662 8663 /** 8664 * Called by the {@link android.view.inputmethod.InputMethodManager} 8665 * when a view who is not the current 8666 * input connection target is trying to make a call on the manager. The 8667 * default implementation returns false; you can override this to return 8668 * true for certain views if you are performing InputConnection proxying 8669 * to them. 8670 * @param view The View that is making the InputMethodManager call. 8671 * @return Return true to allow the call, false to reject. 8672 */ 8673 public boolean checkInputConnectionProxy(View view) { 8674 return false; 8675 } 8676 8677 /** 8678 * Show the context menu for this view. It is not safe to hold on to the 8679 * menu after returning from this method. 8680 * 8681 * You should normally not overload this method. Overload 8682 * {@link #onCreateContextMenu(ContextMenu)} or define an 8683 * {@link OnCreateContextMenuListener} to add items to the context menu. 8684 * 8685 * @param menu The context menu to populate 8686 */ 8687 public void createContextMenu(ContextMenu menu) { 8688 ContextMenuInfo menuInfo = getContextMenuInfo(); 8689 8690 // Sets the current menu info so all items added to menu will have 8691 // my extra info set. 8692 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8693 8694 onCreateContextMenu(menu); 8695 ListenerInfo li = mListenerInfo; 8696 if (li != null && li.mOnCreateContextMenuListener != null) { 8697 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8698 } 8699 8700 // Clear the extra information so subsequent items that aren't mine don't 8701 // have my extra info. 8702 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8703 8704 if (mParent != null) { 8705 mParent.createContextMenu(menu); 8706 } 8707 } 8708 8709 /** 8710 * Views should implement this if they have extra information to associate 8711 * with the context menu. The return result is supplied as a parameter to 8712 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8713 * callback. 8714 * 8715 * @return Extra information about the item for which the context menu 8716 * should be shown. This information will vary across different 8717 * subclasses of View. 8718 */ 8719 protected ContextMenuInfo getContextMenuInfo() { 8720 return null; 8721 } 8722 8723 /** 8724 * Views should implement this if the view itself is going to add items to 8725 * the context menu. 8726 * 8727 * @param menu the context menu to populate 8728 */ 8729 protected void onCreateContextMenu(ContextMenu menu) { 8730 } 8731 8732 /** 8733 * Implement this method to handle trackball motion events. The 8734 * <em>relative</em> movement of the trackball since the last event 8735 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8736 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8737 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8738 * they will often be fractional values, representing the more fine-grained 8739 * movement information available from a trackball). 8740 * 8741 * @param event The motion event. 8742 * @return True if the event was handled, false otherwise. 8743 */ 8744 public boolean onTrackballEvent(MotionEvent event) { 8745 return false; 8746 } 8747 8748 /** 8749 * Implement this method to handle generic motion events. 8750 * <p> 8751 * Generic motion events describe joystick movements, mouse hovers, track pad 8752 * touches, scroll wheel movements and other input events. The 8753 * {@link MotionEvent#getSource() source} of the motion event specifies 8754 * the class of input that was received. Implementations of this method 8755 * must examine the bits in the source before processing the event. 8756 * The following code example shows how this is done. 8757 * </p><p> 8758 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8759 * are delivered to the view under the pointer. All other generic motion events are 8760 * delivered to the focused view. 8761 * </p> 8762 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8763 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8764 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8765 * // process the joystick movement... 8766 * return true; 8767 * } 8768 * } 8769 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8770 * switch (event.getAction()) { 8771 * case MotionEvent.ACTION_HOVER_MOVE: 8772 * // process the mouse hover movement... 8773 * return true; 8774 * case MotionEvent.ACTION_SCROLL: 8775 * // process the scroll wheel movement... 8776 * return true; 8777 * } 8778 * } 8779 * return super.onGenericMotionEvent(event); 8780 * }</pre> 8781 * 8782 * @param event The generic motion event being processed. 8783 * @return True if the event was handled, false otherwise. 8784 */ 8785 public boolean onGenericMotionEvent(MotionEvent event) { 8786 return false; 8787 } 8788 8789 /** 8790 * Implement this method to handle hover events. 8791 * <p> 8792 * This method is called whenever a pointer is hovering into, over, or out of the 8793 * bounds of a view and the view is not currently being touched. 8794 * Hover events are represented as pointer events with action 8795 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8796 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8797 * </p> 8798 * <ul> 8799 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8800 * when the pointer enters the bounds of the view.</li> 8801 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8802 * when the pointer has already entered the bounds of the view and has moved.</li> 8803 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8804 * when the pointer has exited the bounds of the view or when the pointer is 8805 * about to go down due to a button click, tap, or similar user action that 8806 * causes the view to be touched.</li> 8807 * </ul> 8808 * <p> 8809 * The view should implement this method to return true to indicate that it is 8810 * handling the hover event, such as by changing its drawable state. 8811 * </p><p> 8812 * The default implementation calls {@link #setHovered} to update the hovered state 8813 * of the view when a hover enter or hover exit event is received, if the view 8814 * is enabled and is clickable. The default implementation also sends hover 8815 * accessibility events. 8816 * </p> 8817 * 8818 * @param event The motion event that describes the hover. 8819 * @return True if the view handled the hover event. 8820 * 8821 * @see #isHovered 8822 * @see #setHovered 8823 * @see #onHoverChanged 8824 */ 8825 public boolean onHoverEvent(MotionEvent event) { 8826 // The root view may receive hover (or touch) events that are outside the bounds of 8827 // the window. This code ensures that we only send accessibility events for 8828 // hovers that are actually within the bounds of the root view. 8829 final int action = event.getActionMasked(); 8830 if (!mSendingHoverAccessibilityEvents) { 8831 if ((action == MotionEvent.ACTION_HOVER_ENTER 8832 || action == MotionEvent.ACTION_HOVER_MOVE) 8833 && !hasHoveredChild() 8834 && pointInView(event.getX(), event.getY())) { 8835 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8836 mSendingHoverAccessibilityEvents = true; 8837 } 8838 } else { 8839 if (action == MotionEvent.ACTION_HOVER_EXIT 8840 || (action == MotionEvent.ACTION_MOVE 8841 && !pointInView(event.getX(), event.getY()))) { 8842 mSendingHoverAccessibilityEvents = false; 8843 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8844 } 8845 } 8846 8847 if (isHoverable()) { 8848 switch (action) { 8849 case MotionEvent.ACTION_HOVER_ENTER: 8850 setHovered(true); 8851 break; 8852 case MotionEvent.ACTION_HOVER_EXIT: 8853 setHovered(false); 8854 break; 8855 } 8856 8857 // Dispatch the event to onGenericMotionEvent before returning true. 8858 // This is to provide compatibility with existing applications that 8859 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8860 // break because of the new default handling for hoverable views 8861 // in onHoverEvent. 8862 // Note that onGenericMotionEvent will be called by default when 8863 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8864 dispatchGenericMotionEventInternal(event); 8865 // The event was already handled by calling setHovered(), so always 8866 // return true. 8867 return true; 8868 } 8869 8870 return false; 8871 } 8872 8873 /** 8874 * Returns true if the view should handle {@link #onHoverEvent} 8875 * by calling {@link #setHovered} to change its hovered state. 8876 * 8877 * @return True if the view is hoverable. 8878 */ 8879 private boolean isHoverable() { 8880 final int viewFlags = mViewFlags; 8881 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8882 return false; 8883 } 8884 8885 return (viewFlags & CLICKABLE) == CLICKABLE 8886 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8887 } 8888 8889 /** 8890 * Returns true if the view is currently hovered. 8891 * 8892 * @return True if the view is currently hovered. 8893 * 8894 * @see #setHovered 8895 * @see #onHoverChanged 8896 */ 8897 @ViewDebug.ExportedProperty 8898 public boolean isHovered() { 8899 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8900 } 8901 8902 /** 8903 * Sets whether the view is currently hovered. 8904 * <p> 8905 * Calling this method also changes the drawable state of the view. This 8906 * enables the view to react to hover by using different drawable resources 8907 * to change its appearance. 8908 * </p><p> 8909 * The {@link #onHoverChanged} method is called when the hovered state changes. 8910 * </p> 8911 * 8912 * @param hovered True if the view is hovered. 8913 * 8914 * @see #isHovered 8915 * @see #onHoverChanged 8916 */ 8917 public void setHovered(boolean hovered) { 8918 if (hovered) { 8919 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8920 mPrivateFlags |= PFLAG_HOVERED; 8921 refreshDrawableState(); 8922 onHoverChanged(true); 8923 } 8924 } else { 8925 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8926 mPrivateFlags &= ~PFLAG_HOVERED; 8927 refreshDrawableState(); 8928 onHoverChanged(false); 8929 } 8930 } 8931 } 8932 8933 /** 8934 * Implement this method to handle hover state changes. 8935 * <p> 8936 * This method is called whenever the hover state changes as a result of a 8937 * call to {@link #setHovered}. 8938 * </p> 8939 * 8940 * @param hovered The current hover state, as returned by {@link #isHovered}. 8941 * 8942 * @see #isHovered 8943 * @see #setHovered 8944 */ 8945 public void onHoverChanged(boolean hovered) { 8946 } 8947 8948 /** 8949 * Implement this method to handle touch screen motion events. 8950 * <p> 8951 * If this method is used to detect click actions, it is recommended that 8952 * the actions be performed by implementing and calling 8953 * {@link #performClick()}. This will ensure consistent system behavior, 8954 * including: 8955 * <ul> 8956 * <li>obeying click sound preferences 8957 * <li>dispatching OnClickListener calls 8958 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 8959 * accessibility features are enabled 8960 * </ul> 8961 * 8962 * @param event The motion event. 8963 * @return True if the event was handled, false otherwise. 8964 */ 8965 public boolean onTouchEvent(MotionEvent event) { 8966 final float x = event.getX(); 8967 final float y = event.getY(); 8968 final int viewFlags = mViewFlags; 8969 8970 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8971 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8972 clearHotspot(R.attr.state_pressed); 8973 setPressed(false); 8974 } 8975 // A disabled view that is clickable still consumes the touch 8976 // events, it just doesn't respond to them. 8977 return (((viewFlags & CLICKABLE) == CLICKABLE || 8978 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8979 } 8980 8981 if (mTouchDelegate != null) { 8982 if (mTouchDelegate.onTouchEvent(event)) { 8983 return true; 8984 } 8985 } 8986 8987 if (((viewFlags & CLICKABLE) == CLICKABLE || 8988 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8989 switch (event.getAction()) { 8990 case MotionEvent.ACTION_UP: 8991 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8992 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8993 // take focus if we don't have it already and we should in 8994 // touch mode. 8995 boolean focusTaken = false; 8996 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8997 focusTaken = requestFocus(); 8998 } 8999 9000 if (prepressed) { 9001 // The button is being released before we actually 9002 // showed it as pressed. Make it show the pressed 9003 // state now (before scheduling the click) to ensure 9004 // the user sees it. 9005 setHotspot(R.attr.state_pressed, x, y); 9006 setPressed(true); 9007 } 9008 9009 if (!mHasPerformedLongPress) { 9010 // This is a tap, so remove the longpress check 9011 removeLongPressCallback(); 9012 9013 // Only perform take click actions if we were in the pressed state 9014 if (!focusTaken) { 9015 // Use a Runnable and post this rather than calling 9016 // performClick directly. This lets other visual state 9017 // of the view update before click actions start. 9018 if (mPerformClick == null) { 9019 mPerformClick = new PerformClick(); 9020 } 9021 if (!post(mPerformClick)) { 9022 performClick(); 9023 } 9024 } 9025 } 9026 9027 if (mUnsetPressedState == null) { 9028 mUnsetPressedState = new UnsetPressedState(); 9029 } 9030 9031 if (prepressed) { 9032 postDelayed(mUnsetPressedState, 9033 ViewConfiguration.getPressedStateDuration()); 9034 } else if (!post(mUnsetPressedState)) { 9035 // If the post failed, unpress right now 9036 mUnsetPressedState.run(); 9037 } 9038 9039 removeTapCallback(); 9040 } else { 9041 clearHotspot(R.attr.state_pressed); 9042 } 9043 break; 9044 9045 case MotionEvent.ACTION_DOWN: 9046 mHasPerformedLongPress = false; 9047 9048 if (performButtonActionOnTouchDown(event)) { 9049 break; 9050 } 9051 9052 // Walk up the hierarchy to determine if we're inside a scrolling container. 9053 boolean isInScrollingContainer = isInScrollingContainer(); 9054 9055 // For views inside a scrolling container, delay the pressed feedback for 9056 // a short period in case this is a scroll. 9057 if (isInScrollingContainer) { 9058 mPrivateFlags |= PFLAG_PREPRESSED; 9059 if (mPendingCheckForTap == null) { 9060 mPendingCheckForTap = new CheckForTap(); 9061 } 9062 mPendingCheckForTap.x = event.getX(); 9063 mPendingCheckForTap.y = event.getY(); 9064 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9065 } else { 9066 // Not inside a scrolling container, so show the feedback right away 9067 setHotspot(R.attr.state_pressed, x, y); 9068 setPressed(true); 9069 checkForLongClick(0); 9070 } 9071 break; 9072 9073 case MotionEvent.ACTION_CANCEL: 9074 clearHotspot(R.attr.state_pressed); 9075 setPressed(false); 9076 removeTapCallback(); 9077 removeLongPressCallback(); 9078 break; 9079 9080 case MotionEvent.ACTION_MOVE: 9081 setHotspot(R.attr.state_pressed, x, y); 9082 9083 // Be lenient about moving outside of buttons 9084 if (!pointInView(x, y, mTouchSlop)) { 9085 // Outside button 9086 removeTapCallback(); 9087 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9088 // Remove any future long press/tap checks 9089 removeLongPressCallback(); 9090 9091 setPressed(false); 9092 } 9093 } 9094 break; 9095 } 9096 9097 return true; 9098 } 9099 9100 return false; 9101 } 9102 9103 private void setHotspot(int id, float x, float y) { 9104 final Drawable bg = mBackground; 9105 if (bg != null && bg.supportsHotspots()) { 9106 bg.setHotspot(id, x, y); 9107 } 9108 } 9109 9110 private void clearHotspot(int id) { 9111 final Drawable bg = mBackground; 9112 if (bg != null && bg.supportsHotspots()) { 9113 bg.removeHotspot(id); 9114 } 9115 } 9116 9117 /** 9118 * @hide 9119 */ 9120 public boolean isInScrollingContainer() { 9121 ViewParent p = getParent(); 9122 while (p != null && p instanceof ViewGroup) { 9123 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9124 return true; 9125 } 9126 p = p.getParent(); 9127 } 9128 return false; 9129 } 9130 9131 /** 9132 * Remove the longpress detection timer. 9133 */ 9134 private void removeLongPressCallback() { 9135 if (mPendingCheckForLongPress != null) { 9136 removeCallbacks(mPendingCheckForLongPress); 9137 } 9138 } 9139 9140 /** 9141 * Remove the pending click action 9142 */ 9143 private void removePerformClickCallback() { 9144 if (mPerformClick != null) { 9145 removeCallbacks(mPerformClick); 9146 } 9147 } 9148 9149 /** 9150 * Remove the prepress detection timer. 9151 */ 9152 private void removeUnsetPressCallback() { 9153 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9154 clearHotspot(R.attr.state_pressed); 9155 setPressed(false); 9156 removeCallbacks(mUnsetPressedState); 9157 } 9158 } 9159 9160 /** 9161 * Remove the tap detection timer. 9162 */ 9163 private void removeTapCallback() { 9164 if (mPendingCheckForTap != null) { 9165 mPrivateFlags &= ~PFLAG_PREPRESSED; 9166 removeCallbacks(mPendingCheckForTap); 9167 } 9168 } 9169 9170 /** 9171 * Cancels a pending long press. Your subclass can use this if you 9172 * want the context menu to come up if the user presses and holds 9173 * at the same place, but you don't want it to come up if they press 9174 * and then move around enough to cause scrolling. 9175 */ 9176 public void cancelLongPress() { 9177 removeLongPressCallback(); 9178 9179 /* 9180 * The prepressed state handled by the tap callback is a display 9181 * construct, but the tap callback will post a long press callback 9182 * less its own timeout. Remove it here. 9183 */ 9184 removeTapCallback(); 9185 } 9186 9187 /** 9188 * Remove the pending callback for sending a 9189 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9190 */ 9191 private void removeSendViewScrolledAccessibilityEventCallback() { 9192 if (mSendViewScrolledAccessibilityEvent != null) { 9193 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9194 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9195 } 9196 } 9197 9198 /** 9199 * Sets the TouchDelegate for this View. 9200 */ 9201 public void setTouchDelegate(TouchDelegate delegate) { 9202 mTouchDelegate = delegate; 9203 } 9204 9205 /** 9206 * Gets the TouchDelegate for this View. 9207 */ 9208 public TouchDelegate getTouchDelegate() { 9209 return mTouchDelegate; 9210 } 9211 9212 /** 9213 * Set flags controlling behavior of this view. 9214 * 9215 * @param flags Constant indicating the value which should be set 9216 * @param mask Constant indicating the bit range that should be changed 9217 */ 9218 void setFlags(int flags, int mask) { 9219 final boolean accessibilityEnabled = 9220 AccessibilityManager.getInstance(mContext).isEnabled(); 9221 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9222 9223 int old = mViewFlags; 9224 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9225 9226 int changed = mViewFlags ^ old; 9227 if (changed == 0) { 9228 return; 9229 } 9230 int privateFlags = mPrivateFlags; 9231 9232 /* Check if the FOCUSABLE bit has changed */ 9233 if (((changed & FOCUSABLE_MASK) != 0) && 9234 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9235 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9236 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9237 /* Give up focus if we are no longer focusable */ 9238 clearFocus(); 9239 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9240 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9241 /* 9242 * Tell the view system that we are now available to take focus 9243 * if no one else already has it. 9244 */ 9245 if (mParent != null) mParent.focusableViewAvailable(this); 9246 } 9247 } 9248 9249 final int newVisibility = flags & VISIBILITY_MASK; 9250 if (newVisibility == VISIBLE) { 9251 if ((changed & VISIBILITY_MASK) != 0) { 9252 /* 9253 * If this view is becoming visible, invalidate it in case it changed while 9254 * it was not visible. Marking it drawn ensures that the invalidation will 9255 * go through. 9256 */ 9257 mPrivateFlags |= PFLAG_DRAWN; 9258 invalidate(true); 9259 9260 needGlobalAttributesUpdate(true); 9261 9262 // a view becoming visible is worth notifying the parent 9263 // about in case nothing has focus. even if this specific view 9264 // isn't focusable, it may contain something that is, so let 9265 // the root view try to give this focus if nothing else does. 9266 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9267 mParent.focusableViewAvailable(this); 9268 } 9269 } 9270 } 9271 9272 /* Check if the GONE bit has changed */ 9273 if ((changed & GONE) != 0) { 9274 needGlobalAttributesUpdate(false); 9275 requestLayout(); 9276 9277 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9278 if (hasFocus()) clearFocus(); 9279 clearAccessibilityFocus(); 9280 destroyDrawingCache(); 9281 if (mParent instanceof View) { 9282 // GONE views noop invalidation, so invalidate the parent 9283 ((View) mParent).invalidate(true); 9284 } 9285 // Mark the view drawn to ensure that it gets invalidated properly the next 9286 // time it is visible and gets invalidated 9287 mPrivateFlags |= PFLAG_DRAWN; 9288 } 9289 if (mAttachInfo != null) { 9290 mAttachInfo.mViewVisibilityChanged = true; 9291 } 9292 } 9293 9294 /* Check if the VISIBLE bit has changed */ 9295 if ((changed & INVISIBLE) != 0) { 9296 needGlobalAttributesUpdate(false); 9297 /* 9298 * If this view is becoming invisible, set the DRAWN flag so that 9299 * the next invalidate() will not be skipped. 9300 */ 9301 mPrivateFlags |= PFLAG_DRAWN; 9302 9303 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9304 // root view becoming invisible shouldn't clear focus and accessibility focus 9305 if (getRootView() != this) { 9306 if (hasFocus()) clearFocus(); 9307 clearAccessibilityFocus(); 9308 } 9309 } 9310 if (mAttachInfo != null) { 9311 mAttachInfo.mViewVisibilityChanged = true; 9312 } 9313 } 9314 9315 if ((changed & VISIBILITY_MASK) != 0) { 9316 // If the view is invisible, cleanup its display list to free up resources 9317 if (newVisibility != VISIBLE && mAttachInfo != null) { 9318 cleanupDraw(); 9319 } 9320 9321 if (mParent instanceof ViewGroup) { 9322 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9323 (changed & VISIBILITY_MASK), newVisibility); 9324 ((View) mParent).invalidate(true); 9325 } else if (mParent != null) { 9326 mParent.invalidateChild(this, null); 9327 } 9328 dispatchVisibilityChanged(this, newVisibility); 9329 9330 notifySubtreeAccessibilityStateChangedIfNeeded(); 9331 } 9332 9333 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9334 destroyDrawingCache(); 9335 } 9336 9337 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9338 destroyDrawingCache(); 9339 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9340 invalidateParentCaches(); 9341 } 9342 9343 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9344 destroyDrawingCache(); 9345 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9346 } 9347 9348 if ((changed & DRAW_MASK) != 0) { 9349 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9350 if (mBackground != null) { 9351 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9352 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9353 } else { 9354 mPrivateFlags |= PFLAG_SKIP_DRAW; 9355 } 9356 } else { 9357 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9358 } 9359 requestLayout(); 9360 invalidate(true); 9361 } 9362 9363 if ((changed & KEEP_SCREEN_ON) != 0) { 9364 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9365 mParent.recomputeViewAttributes(this); 9366 } 9367 } 9368 9369 if (accessibilityEnabled) { 9370 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9371 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9372 if (oldIncludeForAccessibility != includeForAccessibility()) { 9373 notifySubtreeAccessibilityStateChangedIfNeeded(); 9374 } else { 9375 notifyViewAccessibilityStateChangedIfNeeded( 9376 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9377 } 9378 } else if ((changed & ENABLED_MASK) != 0) { 9379 notifyViewAccessibilityStateChangedIfNeeded( 9380 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9381 } 9382 } 9383 } 9384 9385 /** 9386 * Change the view's z order in the tree, so it's on top of other sibling 9387 * views. This ordering change may affect layout, if the parent container 9388 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9389 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9390 * method should be followed by calls to {@link #requestLayout()} and 9391 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9392 * with the new child ordering. 9393 * 9394 * @see ViewGroup#bringChildToFront(View) 9395 */ 9396 public void bringToFront() { 9397 if (mParent != null) { 9398 mParent.bringChildToFront(this); 9399 } 9400 } 9401 9402 /** 9403 * This is called in response to an internal scroll in this view (i.e., the 9404 * view scrolled its own contents). This is typically as a result of 9405 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9406 * called. 9407 * 9408 * @param l Current horizontal scroll origin. 9409 * @param t Current vertical scroll origin. 9410 * @param oldl Previous horizontal scroll origin. 9411 * @param oldt Previous vertical scroll origin. 9412 */ 9413 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9414 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9415 postSendViewScrolledAccessibilityEventCallback(); 9416 } 9417 9418 mBackgroundSizeChanged = true; 9419 9420 final AttachInfo ai = mAttachInfo; 9421 if (ai != null) { 9422 ai.mViewScrollChanged = true; 9423 } 9424 } 9425 9426 /** 9427 * Interface definition for a callback to be invoked when the layout bounds of a view 9428 * changes due to layout processing. 9429 */ 9430 public interface OnLayoutChangeListener { 9431 /** 9432 * Called when the layout bounds of a view changes due to layout processing. 9433 * 9434 * @param v The view whose bounds have changed. 9435 * @param left The new value of the view's left property. 9436 * @param top The new value of the view's top property. 9437 * @param right The new value of the view's right property. 9438 * @param bottom The new value of the view's bottom property. 9439 * @param oldLeft The previous value of the view's left property. 9440 * @param oldTop The previous value of the view's top property. 9441 * @param oldRight The previous value of the view's right property. 9442 * @param oldBottom The previous value of the view's bottom property. 9443 */ 9444 void onLayoutChange(View v, int left, int top, int right, int bottom, 9445 int oldLeft, int oldTop, int oldRight, int oldBottom); 9446 } 9447 9448 /** 9449 * This is called during layout when the size of this view has changed. If 9450 * you were just added to the view hierarchy, you're called with the old 9451 * values of 0. 9452 * 9453 * @param w Current width of this view. 9454 * @param h Current height of this view. 9455 * @param oldw Old width of this view. 9456 * @param oldh Old height of this view. 9457 */ 9458 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9459 } 9460 9461 /** 9462 * Called by draw to draw the child views. This may be overridden 9463 * by derived classes to gain control just before its children are drawn 9464 * (but after its own view has been drawn). 9465 * @param canvas the canvas on which to draw the view 9466 */ 9467 protected void dispatchDraw(Canvas canvas) { 9468 9469 } 9470 9471 /** 9472 * Gets the parent of this view. Note that the parent is a 9473 * ViewParent and not necessarily a View. 9474 * 9475 * @return Parent of this view. 9476 */ 9477 public final ViewParent getParent() { 9478 return mParent; 9479 } 9480 9481 /** 9482 * Set the horizontal scrolled position of your view. This will cause a call to 9483 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9484 * invalidated. 9485 * @param value the x position to scroll to 9486 */ 9487 public void setScrollX(int value) { 9488 scrollTo(value, mScrollY); 9489 } 9490 9491 /** 9492 * Set the vertical scrolled position of your view. This will cause a call to 9493 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9494 * invalidated. 9495 * @param value the y position to scroll to 9496 */ 9497 public void setScrollY(int value) { 9498 scrollTo(mScrollX, value); 9499 } 9500 9501 /** 9502 * Return the scrolled left position of this view. This is the left edge of 9503 * the displayed part of your view. You do not need to draw any pixels 9504 * farther left, since those are outside of the frame of your view on 9505 * screen. 9506 * 9507 * @return The left edge of the displayed part of your view, in pixels. 9508 */ 9509 public final int getScrollX() { 9510 return mScrollX; 9511 } 9512 9513 /** 9514 * Return the scrolled top position of this view. This is the top edge of 9515 * the displayed part of your view. You do not need to draw any pixels above 9516 * it, since those are outside of the frame of your view on screen. 9517 * 9518 * @return The top edge of the displayed part of your view, in pixels. 9519 */ 9520 public final int getScrollY() { 9521 return mScrollY; 9522 } 9523 9524 /** 9525 * Return the width of the your view. 9526 * 9527 * @return The width of your view, in pixels. 9528 */ 9529 @ViewDebug.ExportedProperty(category = "layout") 9530 public final int getWidth() { 9531 return mRight - mLeft; 9532 } 9533 9534 /** 9535 * Return the height of your view. 9536 * 9537 * @return The height of your view, in pixels. 9538 */ 9539 @ViewDebug.ExportedProperty(category = "layout") 9540 public final int getHeight() { 9541 return mBottom - mTop; 9542 } 9543 9544 /** 9545 * Return the visible drawing bounds of your view. Fills in the output 9546 * rectangle with the values from getScrollX(), getScrollY(), 9547 * getWidth(), and getHeight(). These bounds do not account for any 9548 * transformation properties currently set on the view, such as 9549 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9550 * 9551 * @param outRect The (scrolled) drawing bounds of the view. 9552 */ 9553 public void getDrawingRect(Rect outRect) { 9554 outRect.left = mScrollX; 9555 outRect.top = mScrollY; 9556 outRect.right = mScrollX + (mRight - mLeft); 9557 outRect.bottom = mScrollY + (mBottom - mTop); 9558 } 9559 9560 /** 9561 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9562 * raw width component (that is the result is masked by 9563 * {@link #MEASURED_SIZE_MASK}). 9564 * 9565 * @return The raw measured width of this view. 9566 */ 9567 public final int getMeasuredWidth() { 9568 return mMeasuredWidth & MEASURED_SIZE_MASK; 9569 } 9570 9571 /** 9572 * Return the full width measurement information for this view as computed 9573 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9574 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9575 * This should be used during measurement and layout calculations only. Use 9576 * {@link #getWidth()} to see how wide a view is after layout. 9577 * 9578 * @return The measured width of this view as a bit mask. 9579 */ 9580 public final int getMeasuredWidthAndState() { 9581 return mMeasuredWidth; 9582 } 9583 9584 /** 9585 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9586 * raw width component (that is the result is masked by 9587 * {@link #MEASURED_SIZE_MASK}). 9588 * 9589 * @return The raw measured height of this view. 9590 */ 9591 public final int getMeasuredHeight() { 9592 return mMeasuredHeight & MEASURED_SIZE_MASK; 9593 } 9594 9595 /** 9596 * Return the full height measurement information for this view as computed 9597 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9598 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9599 * This should be used during measurement and layout calculations only. Use 9600 * {@link #getHeight()} to see how wide a view is after layout. 9601 * 9602 * @return The measured width of this view as a bit mask. 9603 */ 9604 public final int getMeasuredHeightAndState() { 9605 return mMeasuredHeight; 9606 } 9607 9608 /** 9609 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9610 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9611 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9612 * and the height component is at the shifted bits 9613 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9614 */ 9615 public final int getMeasuredState() { 9616 return (mMeasuredWidth&MEASURED_STATE_MASK) 9617 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9618 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9619 } 9620 9621 /** 9622 * The transform matrix of this view, which is calculated based on the current 9623 * roation, scale, and pivot properties. 9624 * 9625 * @see #getRotation() 9626 * @see #getScaleX() 9627 * @see #getScaleY() 9628 * @see #getPivotX() 9629 * @see #getPivotY() 9630 * @return The current transform matrix for the view 9631 */ 9632 public Matrix getMatrix() { 9633 ensureTransformationInfo(); 9634 final Matrix matrix = mTransformationInfo.mMatrix; 9635 mRenderNode.getMatrix(matrix); 9636 return matrix; 9637 } 9638 9639 /** 9640 * Returns true if the transform matrix is the identity matrix. 9641 * Recomputes the matrix if necessary. 9642 * 9643 * @return True if the transform matrix is the identity matrix, false otherwise. 9644 */ 9645 final boolean hasIdentityMatrix() { 9646 return mRenderNode.hasIdentityMatrix(); 9647 } 9648 9649 void ensureTransformationInfo() { 9650 if (mTransformationInfo == null) { 9651 mTransformationInfo = new TransformationInfo(); 9652 } 9653 } 9654 9655 /** 9656 * Utility method to retrieve the inverse of the current mMatrix property. 9657 * We cache the matrix to avoid recalculating it when transform properties 9658 * have not changed. 9659 * 9660 * @return The inverse of the current matrix of this view. 9661 */ 9662 final Matrix getInverseMatrix() { 9663 ensureTransformationInfo(); 9664 if (mTransformationInfo.mInverseMatrix == null) { 9665 mTransformationInfo.mInverseMatrix = new Matrix(); 9666 } 9667 final Matrix matrix = mTransformationInfo.mInverseMatrix; 9668 mRenderNode.getInverseMatrix(matrix); 9669 return matrix; 9670 } 9671 9672 /** 9673 * Gets the distance along the Z axis from the camera to this view. 9674 * 9675 * @see #setCameraDistance(float) 9676 * 9677 * @return The distance along the Z axis. 9678 */ 9679 public float getCameraDistance() { 9680 final float dpi = mResources.getDisplayMetrics().densityDpi; 9681 return -(mRenderNode.getCameraDistance() * dpi); 9682 } 9683 9684 /** 9685 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9686 * views are drawn) from the camera to this view. The camera's distance 9687 * affects 3D transformations, for instance rotations around the X and Y 9688 * axis. If the rotationX or rotationY properties are changed and this view is 9689 * large (more than half the size of the screen), it is recommended to always 9690 * use a camera distance that's greater than the height (X axis rotation) or 9691 * the width (Y axis rotation) of this view.</p> 9692 * 9693 * <p>The distance of the camera from the view plane can have an affect on the 9694 * perspective distortion of the view when it is rotated around the x or y axis. 9695 * For example, a large distance will result in a large viewing angle, and there 9696 * will not be much perspective distortion of the view as it rotates. A short 9697 * distance may cause much more perspective distortion upon rotation, and can 9698 * also result in some drawing artifacts if the rotated view ends up partially 9699 * behind the camera (which is why the recommendation is to use a distance at 9700 * least as far as the size of the view, if the view is to be rotated.)</p> 9701 * 9702 * <p>The distance is expressed in "depth pixels." The default distance depends 9703 * on the screen density. For instance, on a medium density display, the 9704 * default distance is 1280. On a high density display, the default distance 9705 * is 1920.</p> 9706 * 9707 * <p>If you want to specify a distance that leads to visually consistent 9708 * results across various densities, use the following formula:</p> 9709 * <pre> 9710 * float scale = context.getResources().getDisplayMetrics().density; 9711 * view.setCameraDistance(distance * scale); 9712 * </pre> 9713 * 9714 * <p>The density scale factor of a high density display is 1.5, 9715 * and 1920 = 1280 * 1.5.</p> 9716 * 9717 * @param distance The distance in "depth pixels", if negative the opposite 9718 * value is used 9719 * 9720 * @see #setRotationX(float) 9721 * @see #setRotationY(float) 9722 */ 9723 public void setCameraDistance(float distance) { 9724 final float dpi = mResources.getDisplayMetrics().densityDpi; 9725 9726 invalidateViewProperty(true, false); 9727 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 9728 invalidateViewProperty(false, false); 9729 9730 invalidateParentIfNeededAndWasQuickRejected(); 9731 } 9732 9733 /** 9734 * The degrees that the view is rotated around the pivot point. 9735 * 9736 * @see #setRotation(float) 9737 * @see #getPivotX() 9738 * @see #getPivotY() 9739 * 9740 * @return The degrees of rotation. 9741 */ 9742 @ViewDebug.ExportedProperty(category = "drawing") 9743 public float getRotation() { 9744 return mRenderNode.getRotation(); 9745 } 9746 9747 /** 9748 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9749 * result in clockwise rotation. 9750 * 9751 * @param rotation The degrees of rotation. 9752 * 9753 * @see #getRotation() 9754 * @see #getPivotX() 9755 * @see #getPivotY() 9756 * @see #setRotationX(float) 9757 * @see #setRotationY(float) 9758 * 9759 * @attr ref android.R.styleable#View_rotation 9760 */ 9761 public void setRotation(float rotation) { 9762 if (rotation != getRotation()) { 9763 // Double-invalidation is necessary to capture view's old and new areas 9764 invalidateViewProperty(true, false); 9765 mRenderNode.setRotation(rotation); 9766 invalidateViewProperty(false, true); 9767 9768 invalidateParentIfNeededAndWasQuickRejected(); 9769 } 9770 } 9771 9772 /** 9773 * The degrees that the view is rotated around the vertical axis through the pivot point. 9774 * 9775 * @see #getPivotX() 9776 * @see #getPivotY() 9777 * @see #setRotationY(float) 9778 * 9779 * @return The degrees of Y rotation. 9780 */ 9781 @ViewDebug.ExportedProperty(category = "drawing") 9782 public float getRotationY() { 9783 return mRenderNode.getRotationY(); 9784 } 9785 9786 /** 9787 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9788 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9789 * down the y axis. 9790 * 9791 * When rotating large views, it is recommended to adjust the camera distance 9792 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9793 * 9794 * @param rotationY The degrees of Y rotation. 9795 * 9796 * @see #getRotationY() 9797 * @see #getPivotX() 9798 * @see #getPivotY() 9799 * @see #setRotation(float) 9800 * @see #setRotationX(float) 9801 * @see #setCameraDistance(float) 9802 * 9803 * @attr ref android.R.styleable#View_rotationY 9804 */ 9805 public void setRotationY(float rotationY) { 9806 if (rotationY != getRotationY()) { 9807 invalidateViewProperty(true, false); 9808 mRenderNode.setRotationY(rotationY); 9809 invalidateViewProperty(false, true); 9810 9811 invalidateParentIfNeededAndWasQuickRejected(); 9812 } 9813 } 9814 9815 /** 9816 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9817 * 9818 * @see #getPivotX() 9819 * @see #getPivotY() 9820 * @see #setRotationX(float) 9821 * 9822 * @return The degrees of X rotation. 9823 */ 9824 @ViewDebug.ExportedProperty(category = "drawing") 9825 public float getRotationX() { 9826 return mRenderNode.getRotationX(); 9827 } 9828 9829 /** 9830 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9831 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9832 * x axis. 9833 * 9834 * When rotating large views, it is recommended to adjust the camera distance 9835 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9836 * 9837 * @param rotationX The degrees of X rotation. 9838 * 9839 * @see #getRotationX() 9840 * @see #getPivotX() 9841 * @see #getPivotY() 9842 * @see #setRotation(float) 9843 * @see #setRotationY(float) 9844 * @see #setCameraDistance(float) 9845 * 9846 * @attr ref android.R.styleable#View_rotationX 9847 */ 9848 public void setRotationX(float rotationX) { 9849 if (rotationX != getRotationX()) { 9850 invalidateViewProperty(true, false); 9851 mRenderNode.setRotationX(rotationX); 9852 invalidateViewProperty(false, true); 9853 9854 invalidateParentIfNeededAndWasQuickRejected(); 9855 } 9856 } 9857 9858 /** 9859 * The amount that the view is scaled in x around the pivot point, as a proportion of 9860 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9861 * 9862 * <p>By default, this is 1.0f. 9863 * 9864 * @see #getPivotX() 9865 * @see #getPivotY() 9866 * @return The scaling factor. 9867 */ 9868 @ViewDebug.ExportedProperty(category = "drawing") 9869 public float getScaleX() { 9870 return mRenderNode.getScaleX(); 9871 } 9872 9873 /** 9874 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9875 * the view's unscaled width. A value of 1 means that no scaling is applied. 9876 * 9877 * @param scaleX The scaling factor. 9878 * @see #getPivotX() 9879 * @see #getPivotY() 9880 * 9881 * @attr ref android.R.styleable#View_scaleX 9882 */ 9883 public void setScaleX(float scaleX) { 9884 if (scaleX != getScaleX()) { 9885 invalidateViewProperty(true, false); 9886 mRenderNode.setScaleX(scaleX); 9887 invalidateViewProperty(false, true); 9888 9889 invalidateParentIfNeededAndWasQuickRejected(); 9890 } 9891 } 9892 9893 /** 9894 * The amount that the view is scaled in y around the pivot point, as a proportion of 9895 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9896 * 9897 * <p>By default, this is 1.0f. 9898 * 9899 * @see #getPivotX() 9900 * @see #getPivotY() 9901 * @return The scaling factor. 9902 */ 9903 @ViewDebug.ExportedProperty(category = "drawing") 9904 public float getScaleY() { 9905 return mRenderNode.getScaleY(); 9906 } 9907 9908 /** 9909 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9910 * the view's unscaled width. A value of 1 means that no scaling is applied. 9911 * 9912 * @param scaleY The scaling factor. 9913 * @see #getPivotX() 9914 * @see #getPivotY() 9915 * 9916 * @attr ref android.R.styleable#View_scaleY 9917 */ 9918 public void setScaleY(float scaleY) { 9919 if (scaleY != getScaleY()) { 9920 invalidateViewProperty(true, false); 9921 mRenderNode.setScaleY(scaleY); 9922 invalidateViewProperty(false, true); 9923 9924 invalidateParentIfNeededAndWasQuickRejected(); 9925 } 9926 } 9927 9928 /** 9929 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9930 * and {@link #setScaleX(float) scaled}. 9931 * 9932 * @see #getRotation() 9933 * @see #getScaleX() 9934 * @see #getScaleY() 9935 * @see #getPivotY() 9936 * @return The x location of the pivot point. 9937 * 9938 * @attr ref android.R.styleable#View_transformPivotX 9939 */ 9940 @ViewDebug.ExportedProperty(category = "drawing") 9941 public float getPivotX() { 9942 return mRenderNode.getPivotX(); 9943 } 9944 9945 /** 9946 * Sets the x location of the point around which the view is 9947 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9948 * By default, the pivot point is centered on the object. 9949 * Setting this property disables this behavior and causes the view to use only the 9950 * explicitly set pivotX and pivotY values. 9951 * 9952 * @param pivotX The x location of the pivot point. 9953 * @see #getRotation() 9954 * @see #getScaleX() 9955 * @see #getScaleY() 9956 * @see #getPivotY() 9957 * 9958 * @attr ref android.R.styleable#View_transformPivotX 9959 */ 9960 public void setPivotX(float pivotX) { 9961 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 9962 invalidateViewProperty(true, false); 9963 mRenderNode.setPivotX(pivotX); 9964 invalidateViewProperty(false, true); 9965 9966 invalidateParentIfNeededAndWasQuickRejected(); 9967 } 9968 } 9969 9970 /** 9971 * The y location of the point around which the view is {@link #setRotation(float) rotated} 9972 * and {@link #setScaleY(float) scaled}. 9973 * 9974 * @see #getRotation() 9975 * @see #getScaleX() 9976 * @see #getScaleY() 9977 * @see #getPivotY() 9978 * @return The y location of the pivot point. 9979 * 9980 * @attr ref android.R.styleable#View_transformPivotY 9981 */ 9982 @ViewDebug.ExportedProperty(category = "drawing") 9983 public float getPivotY() { 9984 return mRenderNode.getPivotY(); 9985 } 9986 9987 /** 9988 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 9989 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 9990 * Setting this property disables this behavior and causes the view to use only the 9991 * explicitly set pivotX and pivotY values. 9992 * 9993 * @param pivotY The y location of the pivot point. 9994 * @see #getRotation() 9995 * @see #getScaleX() 9996 * @see #getScaleY() 9997 * @see #getPivotY() 9998 * 9999 * @attr ref android.R.styleable#View_transformPivotY 10000 */ 10001 public void setPivotY(float pivotY) { 10002 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10003 invalidateViewProperty(true, false); 10004 mRenderNode.setPivotY(pivotY); 10005 invalidateViewProperty(false, true); 10006 10007 invalidateParentIfNeededAndWasQuickRejected(); 10008 } 10009 } 10010 10011 /** 10012 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10013 * completely transparent and 1 means the view is completely opaque. 10014 * 10015 * <p>By default this is 1.0f. 10016 * @return The opacity of the view. 10017 */ 10018 @ViewDebug.ExportedProperty(category = "drawing") 10019 public float getAlpha() { 10020 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10021 } 10022 10023 /** 10024 * Returns whether this View has content which overlaps. 10025 * 10026 * <p>This function, intended to be overridden by specific View types, is an optimization when 10027 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10028 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10029 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10030 * directly. An example of overlapping rendering is a TextView with a background image, such as 10031 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10032 * ImageView with only the foreground image. The default implementation returns true; subclasses 10033 * should override if they have cases which can be optimized.</p> 10034 * 10035 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10036 * necessitates that a View return true if it uses the methods internally without passing the 10037 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10038 * 10039 * @return true if the content in this view might overlap, false otherwise. 10040 */ 10041 public boolean hasOverlappingRendering() { 10042 return true; 10043 } 10044 10045 /** 10046 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10047 * completely transparent and 1 means the view is completely opaque.</p> 10048 * 10049 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10050 * performance implications, especially for large views. It is best to use the alpha property 10051 * sparingly and transiently, as in the case of fading animations.</p> 10052 * 10053 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10054 * strongly recommended for performance reasons to either override 10055 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10056 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10057 * 10058 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10059 * responsible for applying the opacity itself.</p> 10060 * 10061 * <p>Note that if the view is backed by a 10062 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10063 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10064 * 1.0 will supercede the alpha of the layer paint.</p> 10065 * 10066 * @param alpha The opacity of the view. 10067 * 10068 * @see #hasOverlappingRendering() 10069 * @see #setLayerType(int, android.graphics.Paint) 10070 * 10071 * @attr ref android.R.styleable#View_alpha 10072 */ 10073 public void setAlpha(float alpha) { 10074 ensureTransformationInfo(); 10075 if (mTransformationInfo.mAlpha != alpha) { 10076 mTransformationInfo.mAlpha = alpha; 10077 if (onSetAlpha((int) (alpha * 255))) { 10078 mPrivateFlags |= PFLAG_ALPHA_SET; 10079 // subclass is handling alpha - don't optimize rendering cache invalidation 10080 invalidateParentCaches(); 10081 invalidate(true); 10082 } else { 10083 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10084 invalidateViewProperty(true, false); 10085 mRenderNode.setAlpha(getFinalAlpha()); 10086 } 10087 } 10088 } 10089 10090 /** 10091 * Faster version of setAlpha() which performs the same steps except there are 10092 * no calls to invalidate(). The caller of this function should perform proper invalidation 10093 * on the parent and this object. The return value indicates whether the subclass handles 10094 * alpha (the return value for onSetAlpha()). 10095 * 10096 * @param alpha The new value for the alpha property 10097 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10098 * the new value for the alpha property is different from the old value 10099 */ 10100 boolean setAlphaNoInvalidation(float alpha) { 10101 ensureTransformationInfo(); 10102 if (mTransformationInfo.mAlpha != alpha) { 10103 mTransformationInfo.mAlpha = alpha; 10104 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10105 if (subclassHandlesAlpha) { 10106 mPrivateFlags |= PFLAG_ALPHA_SET; 10107 return true; 10108 } else { 10109 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10110 mRenderNode.setAlpha(getFinalAlpha()); 10111 } 10112 } 10113 return false; 10114 } 10115 10116 /** 10117 * This property is hidden and intended only for use by the Fade transition, which 10118 * animates it to produce a visual translucency that does not side-effect (or get 10119 * affected by) the real alpha property. This value is composited with the other 10120 * alpha value (and the AlphaAnimation value, when that is present) to produce 10121 * a final visual translucency result, which is what is passed into the DisplayList. 10122 * 10123 * @hide 10124 */ 10125 public void setTransitionAlpha(float alpha) { 10126 ensureTransformationInfo(); 10127 if (mTransformationInfo.mTransitionAlpha != alpha) { 10128 mTransformationInfo.mTransitionAlpha = alpha; 10129 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10130 invalidateViewProperty(true, false); 10131 mRenderNode.setAlpha(getFinalAlpha()); 10132 } 10133 } 10134 10135 /** 10136 * Calculates the visual alpha of this view, which is a combination of the actual 10137 * alpha value and the transitionAlpha value (if set). 10138 */ 10139 private float getFinalAlpha() { 10140 if (mTransformationInfo != null) { 10141 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10142 } 10143 return 1; 10144 } 10145 10146 /** 10147 * This property is hidden and intended only for use by the Fade transition, which 10148 * animates it to produce a visual translucency that does not side-effect (or get 10149 * affected by) the real alpha property. This value is composited with the other 10150 * alpha value (and the AlphaAnimation value, when that is present) to produce 10151 * a final visual translucency result, which is what is passed into the DisplayList. 10152 * 10153 * @hide 10154 */ 10155 public float getTransitionAlpha() { 10156 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10157 } 10158 10159 /** 10160 * Top position of this view relative to its parent. 10161 * 10162 * @return The top of this view, in pixels. 10163 */ 10164 @ViewDebug.CapturedViewProperty 10165 public final int getTop() { 10166 return mTop; 10167 } 10168 10169 /** 10170 * Sets the top position of this view relative to its parent. This method is meant to be called 10171 * by the layout system and should not generally be called otherwise, because the property 10172 * may be changed at any time by the layout. 10173 * 10174 * @param top The top of this view, in pixels. 10175 */ 10176 public final void setTop(int top) { 10177 if (top != mTop) { 10178 final boolean matrixIsIdentity = hasIdentityMatrix(); 10179 if (matrixIsIdentity) { 10180 if (mAttachInfo != null) { 10181 int minTop; 10182 int yLoc; 10183 if (top < mTop) { 10184 minTop = top; 10185 yLoc = top - mTop; 10186 } else { 10187 minTop = mTop; 10188 yLoc = 0; 10189 } 10190 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10191 } 10192 } else { 10193 // Double-invalidation is necessary to capture view's old and new areas 10194 invalidate(true); 10195 } 10196 10197 int width = mRight - mLeft; 10198 int oldHeight = mBottom - mTop; 10199 10200 mTop = top; 10201 mRenderNode.setTop(mTop); 10202 10203 sizeChange(width, mBottom - mTop, width, oldHeight); 10204 10205 if (!matrixIsIdentity) { 10206 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10207 invalidate(true); 10208 } 10209 mBackgroundSizeChanged = true; 10210 invalidateParentIfNeeded(); 10211 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10212 // View was rejected last time it was drawn by its parent; this may have changed 10213 invalidateParentIfNeeded(); 10214 } 10215 } 10216 } 10217 10218 /** 10219 * Bottom position of this view relative to its parent. 10220 * 10221 * @return The bottom of this view, in pixels. 10222 */ 10223 @ViewDebug.CapturedViewProperty 10224 public final int getBottom() { 10225 return mBottom; 10226 } 10227 10228 /** 10229 * True if this view has changed since the last time being drawn. 10230 * 10231 * @return The dirty state of this view. 10232 */ 10233 public boolean isDirty() { 10234 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10235 } 10236 10237 /** 10238 * Sets the bottom position of this view relative to its parent. This method is meant to be 10239 * called by the layout system and should not generally be called otherwise, because the 10240 * property may be changed at any time by the layout. 10241 * 10242 * @param bottom The bottom of this view, in pixels. 10243 */ 10244 public final void setBottom(int bottom) { 10245 if (bottom != mBottom) { 10246 final boolean matrixIsIdentity = hasIdentityMatrix(); 10247 if (matrixIsIdentity) { 10248 if (mAttachInfo != null) { 10249 int maxBottom; 10250 if (bottom < mBottom) { 10251 maxBottom = mBottom; 10252 } else { 10253 maxBottom = bottom; 10254 } 10255 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10256 } 10257 } else { 10258 // Double-invalidation is necessary to capture view's old and new areas 10259 invalidate(true); 10260 } 10261 10262 int width = mRight - mLeft; 10263 int oldHeight = mBottom - mTop; 10264 10265 mBottom = bottom; 10266 mRenderNode.setBottom(mBottom); 10267 10268 sizeChange(width, mBottom - mTop, width, oldHeight); 10269 10270 if (!matrixIsIdentity) { 10271 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10272 invalidate(true); 10273 } 10274 mBackgroundSizeChanged = true; 10275 invalidateParentIfNeeded(); 10276 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10277 // View was rejected last time it was drawn by its parent; this may have changed 10278 invalidateParentIfNeeded(); 10279 } 10280 } 10281 } 10282 10283 /** 10284 * Left position of this view relative to its parent. 10285 * 10286 * @return The left edge of this view, in pixels. 10287 */ 10288 @ViewDebug.CapturedViewProperty 10289 public final int getLeft() { 10290 return mLeft; 10291 } 10292 10293 /** 10294 * Sets the left position of this view relative to its parent. This method is meant to be called 10295 * by the layout system and should not generally be called otherwise, because the property 10296 * may be changed at any time by the layout. 10297 * 10298 * @param left The left of this view, in pixels. 10299 */ 10300 public final void setLeft(int left) { 10301 if (left != mLeft) { 10302 final boolean matrixIsIdentity = hasIdentityMatrix(); 10303 if (matrixIsIdentity) { 10304 if (mAttachInfo != null) { 10305 int minLeft; 10306 int xLoc; 10307 if (left < mLeft) { 10308 minLeft = left; 10309 xLoc = left - mLeft; 10310 } else { 10311 minLeft = mLeft; 10312 xLoc = 0; 10313 } 10314 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10315 } 10316 } else { 10317 // Double-invalidation is necessary to capture view's old and new areas 10318 invalidate(true); 10319 } 10320 10321 int oldWidth = mRight - mLeft; 10322 int height = mBottom - mTop; 10323 10324 mLeft = left; 10325 mRenderNode.setLeft(left); 10326 10327 sizeChange(mRight - mLeft, height, oldWidth, height); 10328 10329 if (!matrixIsIdentity) { 10330 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10331 invalidate(true); 10332 } 10333 mBackgroundSizeChanged = true; 10334 invalidateParentIfNeeded(); 10335 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10336 // View was rejected last time it was drawn by its parent; this may have changed 10337 invalidateParentIfNeeded(); 10338 } 10339 } 10340 } 10341 10342 /** 10343 * Right position of this view relative to its parent. 10344 * 10345 * @return The right edge of this view, in pixels. 10346 */ 10347 @ViewDebug.CapturedViewProperty 10348 public final int getRight() { 10349 return mRight; 10350 } 10351 10352 /** 10353 * Sets the right position of this view relative to its parent. This method is meant to be called 10354 * by the layout system and should not generally be called otherwise, because the property 10355 * may be changed at any time by the layout. 10356 * 10357 * @param right The right of this view, in pixels. 10358 */ 10359 public final void setRight(int right) { 10360 if (right != mRight) { 10361 final boolean matrixIsIdentity = hasIdentityMatrix(); 10362 if (matrixIsIdentity) { 10363 if (mAttachInfo != null) { 10364 int maxRight; 10365 if (right < mRight) { 10366 maxRight = mRight; 10367 } else { 10368 maxRight = right; 10369 } 10370 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10371 } 10372 } else { 10373 // Double-invalidation is necessary to capture view's old and new areas 10374 invalidate(true); 10375 } 10376 10377 int oldWidth = mRight - mLeft; 10378 int height = mBottom - mTop; 10379 10380 mRight = right; 10381 mRenderNode.setRight(mRight); 10382 10383 sizeChange(mRight - mLeft, height, oldWidth, height); 10384 10385 if (!matrixIsIdentity) { 10386 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10387 invalidate(true); 10388 } 10389 mBackgroundSizeChanged = true; 10390 invalidateParentIfNeeded(); 10391 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10392 // View was rejected last time it was drawn by its parent; this may have changed 10393 invalidateParentIfNeeded(); 10394 } 10395 } 10396 } 10397 10398 /** 10399 * The visual x position of this view, in pixels. This is equivalent to the 10400 * {@link #setTranslationX(float) translationX} property plus the current 10401 * {@link #getLeft() left} property. 10402 * 10403 * @return The visual x position of this view, in pixels. 10404 */ 10405 @ViewDebug.ExportedProperty(category = "drawing") 10406 public float getX() { 10407 return mLeft + getTranslationX(); 10408 } 10409 10410 /** 10411 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10412 * {@link #setTranslationX(float) translationX} property to be the difference between 10413 * the x value passed in and the current {@link #getLeft() left} property. 10414 * 10415 * @param x The visual x position of this view, in pixels. 10416 */ 10417 public void setX(float x) { 10418 setTranslationX(x - mLeft); 10419 } 10420 10421 /** 10422 * The visual y position of this view, in pixels. This is equivalent to the 10423 * {@link #setTranslationY(float) translationY} property plus the current 10424 * {@link #getTop() top} property. 10425 * 10426 * @return The visual y position of this view, in pixels. 10427 */ 10428 @ViewDebug.ExportedProperty(category = "drawing") 10429 public float getY() { 10430 return mTop + getTranslationY(); 10431 } 10432 10433 /** 10434 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10435 * {@link #setTranslationY(float) translationY} property to be the difference between 10436 * the y value passed in and the current {@link #getTop() top} property. 10437 * 10438 * @param y The visual y position of this view, in pixels. 10439 */ 10440 public void setY(float y) { 10441 setTranslationY(y - mTop); 10442 } 10443 10444 /** 10445 * The visual z position of this view, in pixels. This is equivalent to the 10446 * {@link #setTranslationZ(float) translationZ} property plus the current 10447 * {@link #getElevation() elevation} property. 10448 * 10449 * @return The visual z position of this view, in pixels. 10450 */ 10451 @ViewDebug.ExportedProperty(category = "drawing") 10452 public float getZ() { 10453 return getElevation() + getTranslationZ(); 10454 } 10455 10456 /** 10457 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10458 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10459 * the x value passed in and the current {@link #getElevation() elevation} property. 10460 * 10461 * @param z The visual z position of this view, in pixels. 10462 */ 10463 public void setZ(float z) { 10464 setTranslationZ(z - getElevation()); 10465 } 10466 10467 @ViewDebug.ExportedProperty(category = "drawing") 10468 public float getElevation() { 10469 return mRenderNode.getElevation(); 10470 } 10471 10472 /** 10473 * Sets the base depth location of this view. 10474 * 10475 * @attr ref android.R.styleable#View_elevation 10476 */ 10477 public void setElevation(float elevation) { 10478 if (elevation != getElevation()) { 10479 invalidateViewProperty(true, false); 10480 mRenderNode.setElevation(elevation); 10481 invalidateViewProperty(false, true); 10482 10483 invalidateParentIfNeededAndWasQuickRejected(); 10484 } 10485 } 10486 10487 /** 10488 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10489 * This position is post-layout, in addition to wherever the object's 10490 * layout placed it. 10491 * 10492 * @return The horizontal position of this view relative to its left position, in pixels. 10493 */ 10494 @ViewDebug.ExportedProperty(category = "drawing") 10495 public float getTranslationX() { 10496 return mRenderNode.getTranslationX(); 10497 } 10498 10499 /** 10500 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10501 * This effectively positions the object post-layout, in addition to wherever the object's 10502 * layout placed it. 10503 * 10504 * @param translationX The horizontal position of this view relative to its left position, 10505 * in pixels. 10506 * 10507 * @attr ref android.R.styleable#View_translationX 10508 */ 10509 public void setTranslationX(float translationX) { 10510 if (translationX != getTranslationX()) { 10511 invalidateViewProperty(true, false); 10512 mRenderNode.setTranslationX(translationX); 10513 invalidateViewProperty(false, true); 10514 10515 invalidateParentIfNeededAndWasQuickRejected(); 10516 } 10517 } 10518 10519 /** 10520 * The vertical location of this view relative to its {@link #getTop() top} position. 10521 * This position is post-layout, in addition to wherever the object's 10522 * layout placed it. 10523 * 10524 * @return The vertical position of this view relative to its top position, 10525 * in pixels. 10526 */ 10527 @ViewDebug.ExportedProperty(category = "drawing") 10528 public float getTranslationY() { 10529 return mRenderNode.getTranslationY(); 10530 } 10531 10532 /** 10533 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10534 * This effectively positions the object post-layout, in addition to wherever the object's 10535 * layout placed it. 10536 * 10537 * @param translationY The vertical position of this view relative to its top position, 10538 * in pixels. 10539 * 10540 * @attr ref android.R.styleable#View_translationY 10541 */ 10542 public void setTranslationY(float translationY) { 10543 if (translationY != getTranslationY()) { 10544 invalidateViewProperty(true, false); 10545 mRenderNode.setTranslationY(translationY); 10546 invalidateViewProperty(false, true); 10547 10548 invalidateParentIfNeededAndWasQuickRejected(); 10549 } 10550 } 10551 10552 /** 10553 * The depth location of this view relative to its {@link #getElevation() elevation}. 10554 * 10555 * @return The depth of this view relative to its elevation. 10556 */ 10557 @ViewDebug.ExportedProperty(category = "drawing") 10558 public float getTranslationZ() { 10559 return mRenderNode.getTranslationZ(); 10560 } 10561 10562 /** 10563 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 10564 * 10565 * @attr ref android.R.styleable#View_translationZ 10566 */ 10567 public void setTranslationZ(float translationZ) { 10568 if (translationZ != getTranslationZ()) { 10569 invalidateViewProperty(true, false); 10570 mRenderNode.setTranslationZ(translationZ); 10571 invalidateViewProperty(false, true); 10572 10573 invalidateParentIfNeededAndWasQuickRejected(); 10574 } 10575 } 10576 10577 /** 10578 * Returns a ValueAnimator which can animate a clipping circle. 10579 * <p> 10580 * The View will be clipped to the animating circle. 10581 * <p> 10582 * Any shadow cast by the View will respect the circular clip from this animator. 10583 * 10584 * @param centerX The x coordinate of the center of the animating circle. 10585 * @param centerY The y coordinate of the center of the animating circle. 10586 * @param startRadius The starting radius of the animating circle. 10587 * @param endRadius The ending radius of the animating circle. 10588 */ 10589 public final ValueAnimator createRevealAnimator(int centerX, int centerY, 10590 float startRadius, float endRadius) { 10591 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10592 startRadius, endRadius, false); 10593 } 10594 10595 /** 10596 * Returns a ValueAnimator which can animate a clearing circle. 10597 * <p> 10598 * The View is prevented from drawing within the circle, so the content 10599 * behind the View shows through. 10600 * 10601 * @param centerX The x coordinate of the center of the animating circle. 10602 * @param centerY The y coordinate of the center of the animating circle. 10603 * @param startRadius The starting radius of the animating circle. 10604 * @param endRadius The ending radius of the animating circle. 10605 * 10606 * @hide 10607 */ 10608 public final ValueAnimator createClearCircleAnimator(int centerX, int centerY, 10609 float startRadius, float endRadius) { 10610 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10611 startRadius, endRadius, true); 10612 } 10613 10614 /** 10615 * Sets the outline of the view, which defines the shape of the shadow it 10616 * casts. 10617 * <p> 10618 * If the outline is not set or is null, shadows will be cast from the 10619 * bounds of the View. 10620 * 10621 * @param outline The new outline of the view. 10622 * Must be {@link android.graphics.Outline#isValid() valid.} 10623 */ 10624 public void setOutline(@Nullable Outline outline) { 10625 if (outline != null && !outline.isValid()) { 10626 throw new IllegalArgumentException("Outline must not be invalid"); 10627 } 10628 10629 mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED; 10630 10631 if (outline == null) { 10632 mOutline = null; 10633 } else { 10634 // always copy the path since caller may reuse 10635 if (mOutline == null) { 10636 mOutline = new Outline(); 10637 } 10638 mOutline.set(outline); 10639 } 10640 mRenderNode.setOutline(mOutline); 10641 } 10642 10643 // TODO: remove 10644 public final boolean getClipToOutline() { return false; } 10645 public void setClipToOutline(boolean clipToOutline) {} 10646 10647 private void queryOutlineFromBackgroundIfUndefined() { 10648 if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) { 10649 // Outline not currently defined, query from background 10650 if (mOutline == null) { 10651 mOutline = new Outline(); 10652 } else { 10653 //invalidate outline, to ensure background calculates it 10654 mOutline.set(null); 10655 } 10656 if (mBackground.getOutline(mOutline)) { 10657 if (!mOutline.isValid()) { 10658 throw new IllegalStateException("Background drawable failed to build outline"); 10659 } 10660 mRenderNode.setOutline(mOutline); 10661 } else { 10662 mRenderNode.setOutline(null); 10663 } 10664 } 10665 } 10666 10667 /** 10668 * Private API to be used for reveal animation 10669 * 10670 * @hide 10671 */ 10672 public void setRevealClip(boolean shouldClip, boolean inverseClip, 10673 float x, float y, float radius) { 10674 mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius); 10675 // TODO: Handle this invalidate in a better way, or purely in native. 10676 invalidate(); 10677 } 10678 10679 /** 10680 * Hit rectangle in parent's coordinates 10681 * 10682 * @param outRect The hit rectangle of the view. 10683 */ 10684 public void getHitRect(Rect outRect) { 10685 if (hasIdentityMatrix() || mAttachInfo == null) { 10686 outRect.set(mLeft, mTop, mRight, mBottom); 10687 } else { 10688 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10689 tmpRect.set(0, 0, getWidth(), getHeight()); 10690 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 10691 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10692 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10693 } 10694 } 10695 10696 /** 10697 * Determines whether the given point, in local coordinates is inside the view. 10698 */ 10699 /*package*/ final boolean pointInView(float localX, float localY) { 10700 return localX >= 0 && localX < (mRight - mLeft) 10701 && localY >= 0 && localY < (mBottom - mTop); 10702 } 10703 10704 /** 10705 * Utility method to determine whether the given point, in local coordinates, 10706 * is inside the view, where the area of the view is expanded by the slop factor. 10707 * This method is called while processing touch-move events to determine if the event 10708 * is still within the view. 10709 * 10710 * @hide 10711 */ 10712 public boolean pointInView(float localX, float localY, float slop) { 10713 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10714 localY < ((mBottom - mTop) + slop); 10715 } 10716 10717 /** 10718 * When a view has focus and the user navigates away from it, the next view is searched for 10719 * starting from the rectangle filled in by this method. 10720 * 10721 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10722 * of the view. However, if your view maintains some idea of internal selection, 10723 * such as a cursor, or a selected row or column, you should override this method and 10724 * fill in a more specific rectangle. 10725 * 10726 * @param r The rectangle to fill in, in this view's coordinates. 10727 */ 10728 public void getFocusedRect(Rect r) { 10729 getDrawingRect(r); 10730 } 10731 10732 /** 10733 * If some part of this view is not clipped by any of its parents, then 10734 * return that area in r in global (root) coordinates. To convert r to local 10735 * coordinates (without taking possible View rotations into account), offset 10736 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10737 * If the view is completely clipped or translated out, return false. 10738 * 10739 * @param r If true is returned, r holds the global coordinates of the 10740 * visible portion of this view. 10741 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10742 * between this view and its root. globalOffet may be null. 10743 * @return true if r is non-empty (i.e. part of the view is visible at the 10744 * root level. 10745 */ 10746 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10747 int width = mRight - mLeft; 10748 int height = mBottom - mTop; 10749 if (width > 0 && height > 0) { 10750 r.set(0, 0, width, height); 10751 if (globalOffset != null) { 10752 globalOffset.set(-mScrollX, -mScrollY); 10753 } 10754 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10755 } 10756 return false; 10757 } 10758 10759 public final boolean getGlobalVisibleRect(Rect r) { 10760 return getGlobalVisibleRect(r, null); 10761 } 10762 10763 public final boolean getLocalVisibleRect(Rect r) { 10764 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10765 if (getGlobalVisibleRect(r, offset)) { 10766 r.offset(-offset.x, -offset.y); // make r local 10767 return true; 10768 } 10769 return false; 10770 } 10771 10772 /** 10773 * Offset this view's vertical location by the specified number of pixels. 10774 * 10775 * @param offset the number of pixels to offset the view by 10776 */ 10777 public void offsetTopAndBottom(int offset) { 10778 if (offset != 0) { 10779 final boolean matrixIsIdentity = hasIdentityMatrix(); 10780 if (matrixIsIdentity) { 10781 if (isHardwareAccelerated()) { 10782 invalidateViewProperty(false, false); 10783 } else { 10784 final ViewParent p = mParent; 10785 if (p != null && mAttachInfo != null) { 10786 final Rect r = mAttachInfo.mTmpInvalRect; 10787 int minTop; 10788 int maxBottom; 10789 int yLoc; 10790 if (offset < 0) { 10791 minTop = mTop + offset; 10792 maxBottom = mBottom; 10793 yLoc = offset; 10794 } else { 10795 minTop = mTop; 10796 maxBottom = mBottom + offset; 10797 yLoc = 0; 10798 } 10799 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10800 p.invalidateChild(this, r); 10801 } 10802 } 10803 } else { 10804 invalidateViewProperty(false, false); 10805 } 10806 10807 mTop += offset; 10808 mBottom += offset; 10809 mRenderNode.offsetTopAndBottom(offset); 10810 if (isHardwareAccelerated()) { 10811 invalidateViewProperty(false, false); 10812 } else { 10813 if (!matrixIsIdentity) { 10814 invalidateViewProperty(false, true); 10815 } 10816 invalidateParentIfNeeded(); 10817 } 10818 } 10819 } 10820 10821 /** 10822 * Offset this view's horizontal location by the specified amount of pixels. 10823 * 10824 * @param offset the number of pixels to offset the view by 10825 */ 10826 public void offsetLeftAndRight(int offset) { 10827 if (offset != 0) { 10828 final boolean matrixIsIdentity = hasIdentityMatrix(); 10829 if (matrixIsIdentity) { 10830 if (isHardwareAccelerated()) { 10831 invalidateViewProperty(false, false); 10832 } else { 10833 final ViewParent p = mParent; 10834 if (p != null && mAttachInfo != null) { 10835 final Rect r = mAttachInfo.mTmpInvalRect; 10836 int minLeft; 10837 int maxRight; 10838 if (offset < 0) { 10839 minLeft = mLeft + offset; 10840 maxRight = mRight; 10841 } else { 10842 minLeft = mLeft; 10843 maxRight = mRight + offset; 10844 } 10845 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10846 p.invalidateChild(this, r); 10847 } 10848 } 10849 } else { 10850 invalidateViewProperty(false, false); 10851 } 10852 10853 mLeft += offset; 10854 mRight += offset; 10855 mRenderNode.offsetLeftAndRight(offset); 10856 if (isHardwareAccelerated()) { 10857 invalidateViewProperty(false, false); 10858 } else { 10859 if (!matrixIsIdentity) { 10860 invalidateViewProperty(false, true); 10861 } 10862 invalidateParentIfNeeded(); 10863 } 10864 } 10865 } 10866 10867 /** 10868 * Get the LayoutParams associated with this view. All views should have 10869 * layout parameters. These supply parameters to the <i>parent</i> of this 10870 * view specifying how it should be arranged. There are many subclasses of 10871 * ViewGroup.LayoutParams, and these correspond to the different subclasses 10872 * of ViewGroup that are responsible for arranging their children. 10873 * 10874 * This method may return null if this View is not attached to a parent 10875 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 10876 * was not invoked successfully. When a View is attached to a parent 10877 * ViewGroup, this method must not return null. 10878 * 10879 * @return The LayoutParams associated with this view, or null if no 10880 * parameters have been set yet 10881 */ 10882 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 10883 public ViewGroup.LayoutParams getLayoutParams() { 10884 return mLayoutParams; 10885 } 10886 10887 /** 10888 * Set the layout parameters associated with this view. These supply 10889 * parameters to the <i>parent</i> of this view specifying how it should be 10890 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 10891 * correspond to the different subclasses of ViewGroup that are responsible 10892 * for arranging their children. 10893 * 10894 * @param params The layout parameters for this view, cannot be null 10895 */ 10896 public void setLayoutParams(ViewGroup.LayoutParams params) { 10897 if (params == null) { 10898 throw new NullPointerException("Layout parameters cannot be null"); 10899 } 10900 mLayoutParams = params; 10901 resolveLayoutParams(); 10902 if (mParent instanceof ViewGroup) { 10903 ((ViewGroup) mParent).onSetLayoutParams(this, params); 10904 } 10905 requestLayout(); 10906 } 10907 10908 /** 10909 * Resolve the layout parameters depending on the resolved layout direction 10910 * 10911 * @hide 10912 */ 10913 public void resolveLayoutParams() { 10914 if (mLayoutParams != null) { 10915 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 10916 } 10917 } 10918 10919 /** 10920 * Set the scrolled position of your view. This will cause a call to 10921 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10922 * invalidated. 10923 * @param x the x position to scroll to 10924 * @param y the y position to scroll to 10925 */ 10926 public void scrollTo(int x, int y) { 10927 if (mScrollX != x || mScrollY != y) { 10928 int oldX = mScrollX; 10929 int oldY = mScrollY; 10930 mScrollX = x; 10931 mScrollY = y; 10932 invalidateParentCaches(); 10933 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 10934 if (!awakenScrollBars()) { 10935 postInvalidateOnAnimation(); 10936 } 10937 } 10938 } 10939 10940 /** 10941 * Move the scrolled position of your view. This will cause a call to 10942 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10943 * invalidated. 10944 * @param x the amount of pixels to scroll by horizontally 10945 * @param y the amount of pixels to scroll by vertically 10946 */ 10947 public void scrollBy(int x, int y) { 10948 scrollTo(mScrollX + x, mScrollY + y); 10949 } 10950 10951 /** 10952 * <p>Trigger the scrollbars to draw. When invoked this method starts an 10953 * animation to fade the scrollbars out after a default delay. If a subclass 10954 * provides animated scrolling, the start delay should equal the duration 10955 * of the scrolling animation.</p> 10956 * 10957 * <p>The animation starts only if at least one of the scrollbars is 10958 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 10959 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10960 * this method returns true, and false otherwise. If the animation is 10961 * started, this method calls {@link #invalidate()}; in that case the 10962 * caller should not call {@link #invalidate()}.</p> 10963 * 10964 * <p>This method should be invoked every time a subclass directly updates 10965 * the scroll parameters.</p> 10966 * 10967 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 10968 * and {@link #scrollTo(int, int)}.</p> 10969 * 10970 * @return true if the animation is played, false otherwise 10971 * 10972 * @see #awakenScrollBars(int) 10973 * @see #scrollBy(int, int) 10974 * @see #scrollTo(int, int) 10975 * @see #isHorizontalScrollBarEnabled() 10976 * @see #isVerticalScrollBarEnabled() 10977 * @see #setHorizontalScrollBarEnabled(boolean) 10978 * @see #setVerticalScrollBarEnabled(boolean) 10979 */ 10980 protected boolean awakenScrollBars() { 10981 return mScrollCache != null && 10982 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 10983 } 10984 10985 /** 10986 * Trigger the scrollbars to draw. 10987 * This method differs from awakenScrollBars() only in its default duration. 10988 * initialAwakenScrollBars() will show the scroll bars for longer than 10989 * usual to give the user more of a chance to notice them. 10990 * 10991 * @return true if the animation is played, false otherwise. 10992 */ 10993 private boolean initialAwakenScrollBars() { 10994 return mScrollCache != null && 10995 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 10996 } 10997 10998 /** 10999 * <p> 11000 * Trigger the scrollbars to draw. When invoked this method starts an 11001 * animation to fade the scrollbars out after a fixed delay. If a subclass 11002 * provides animated scrolling, the start delay should equal the duration of 11003 * the scrolling animation. 11004 * </p> 11005 * 11006 * <p> 11007 * The animation starts only if at least one of the scrollbars is enabled, 11008 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11009 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11010 * this method returns true, and false otherwise. If the animation is 11011 * started, this method calls {@link #invalidate()}; in that case the caller 11012 * should not call {@link #invalidate()}. 11013 * </p> 11014 * 11015 * <p> 11016 * This method should be invoked everytime a subclass directly updates the 11017 * scroll parameters. 11018 * </p> 11019 * 11020 * @param startDelay the delay, in milliseconds, after which the animation 11021 * should start; when the delay is 0, the animation starts 11022 * immediately 11023 * @return true if the animation is played, false otherwise 11024 * 11025 * @see #scrollBy(int, int) 11026 * @see #scrollTo(int, int) 11027 * @see #isHorizontalScrollBarEnabled() 11028 * @see #isVerticalScrollBarEnabled() 11029 * @see #setHorizontalScrollBarEnabled(boolean) 11030 * @see #setVerticalScrollBarEnabled(boolean) 11031 */ 11032 protected boolean awakenScrollBars(int startDelay) { 11033 return awakenScrollBars(startDelay, true); 11034 } 11035 11036 /** 11037 * <p> 11038 * Trigger the scrollbars to draw. When invoked this method starts an 11039 * animation to fade the scrollbars out after a fixed delay. If a subclass 11040 * provides animated scrolling, the start delay should equal the duration of 11041 * the scrolling animation. 11042 * </p> 11043 * 11044 * <p> 11045 * The animation starts only if at least one of the scrollbars is enabled, 11046 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11047 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11048 * this method returns true, and false otherwise. If the animation is 11049 * started, this method calls {@link #invalidate()} if the invalidate parameter 11050 * is set to true; in that case the caller 11051 * should not call {@link #invalidate()}. 11052 * </p> 11053 * 11054 * <p> 11055 * This method should be invoked everytime a subclass directly updates the 11056 * scroll parameters. 11057 * </p> 11058 * 11059 * @param startDelay the delay, in milliseconds, after which the animation 11060 * should start; when the delay is 0, the animation starts 11061 * immediately 11062 * 11063 * @param invalidate Wheter this method should call invalidate 11064 * 11065 * @return true if the animation is played, false otherwise 11066 * 11067 * @see #scrollBy(int, int) 11068 * @see #scrollTo(int, int) 11069 * @see #isHorizontalScrollBarEnabled() 11070 * @see #isVerticalScrollBarEnabled() 11071 * @see #setHorizontalScrollBarEnabled(boolean) 11072 * @see #setVerticalScrollBarEnabled(boolean) 11073 */ 11074 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11075 final ScrollabilityCache scrollCache = mScrollCache; 11076 11077 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11078 return false; 11079 } 11080 11081 if (scrollCache.scrollBar == null) { 11082 scrollCache.scrollBar = new ScrollBarDrawable(); 11083 } 11084 11085 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11086 11087 if (invalidate) { 11088 // Invalidate to show the scrollbars 11089 postInvalidateOnAnimation(); 11090 } 11091 11092 if (scrollCache.state == ScrollabilityCache.OFF) { 11093 // FIXME: this is copied from WindowManagerService. 11094 // We should get this value from the system when it 11095 // is possible to do so. 11096 final int KEY_REPEAT_FIRST_DELAY = 750; 11097 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11098 } 11099 11100 // Tell mScrollCache when we should start fading. This may 11101 // extend the fade start time if one was already scheduled 11102 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11103 scrollCache.fadeStartTime = fadeStartTime; 11104 scrollCache.state = ScrollabilityCache.ON; 11105 11106 // Schedule our fader to run, unscheduling any old ones first 11107 if (mAttachInfo != null) { 11108 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11109 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11110 } 11111 11112 return true; 11113 } 11114 11115 return false; 11116 } 11117 11118 /** 11119 * Do not invalidate views which are not visible and which are not running an animation. They 11120 * will not get drawn and they should not set dirty flags as if they will be drawn 11121 */ 11122 private boolean skipInvalidate() { 11123 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11124 (!(mParent instanceof ViewGroup) || 11125 !((ViewGroup) mParent).isViewTransitioning(this)); 11126 } 11127 11128 /** 11129 * Mark the area defined by dirty as needing to be drawn. If the view is 11130 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11131 * point in the future. 11132 * <p> 11133 * This must be called from a UI thread. To call from a non-UI thread, call 11134 * {@link #postInvalidate()}. 11135 * <p> 11136 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11137 * {@code dirty}. 11138 * 11139 * @param dirty the rectangle representing the bounds of the dirty region 11140 */ 11141 public void invalidate(Rect dirty) { 11142 final int scrollX = mScrollX; 11143 final int scrollY = mScrollY; 11144 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11145 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11146 } 11147 11148 /** 11149 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11150 * coordinates of the dirty rect are relative to the view. If the view is 11151 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11152 * point in the future. 11153 * <p> 11154 * This must be called from a UI thread. To call from a non-UI thread, call 11155 * {@link #postInvalidate()}. 11156 * 11157 * @param l the left position of the dirty region 11158 * @param t the top position of the dirty region 11159 * @param r the right position of the dirty region 11160 * @param b the bottom position of the dirty region 11161 */ 11162 public void invalidate(int l, int t, int r, int b) { 11163 final int scrollX = mScrollX; 11164 final int scrollY = mScrollY; 11165 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11166 } 11167 11168 /** 11169 * Invalidate the whole view. If the view is visible, 11170 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11171 * the future. 11172 * <p> 11173 * This must be called from a UI thread. To call from a non-UI thread, call 11174 * {@link #postInvalidate()}. 11175 */ 11176 public void invalidate() { 11177 invalidate(true); 11178 } 11179 11180 /** 11181 * This is where the invalidate() work actually happens. A full invalidate() 11182 * causes the drawing cache to be invalidated, but this function can be 11183 * called with invalidateCache set to false to skip that invalidation step 11184 * for cases that do not need it (for example, a component that remains at 11185 * the same dimensions with the same content). 11186 * 11187 * @param invalidateCache Whether the drawing cache for this view should be 11188 * invalidated as well. This is usually true for a full 11189 * invalidate, but may be set to false if the View's contents or 11190 * dimensions have not changed. 11191 */ 11192 void invalidate(boolean invalidateCache) { 11193 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11194 } 11195 11196 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11197 boolean fullInvalidate) { 11198 if (skipInvalidate()) { 11199 return; 11200 } 11201 11202 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11203 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11204 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11205 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11206 if (fullInvalidate) { 11207 mLastIsOpaque = isOpaque(); 11208 mPrivateFlags &= ~PFLAG_DRAWN; 11209 } 11210 11211 mPrivateFlags |= PFLAG_DIRTY; 11212 11213 if (invalidateCache) { 11214 mPrivateFlags |= PFLAG_INVALIDATED; 11215 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11216 } 11217 11218 // Propagate the damage rectangle to the parent view. 11219 final AttachInfo ai = mAttachInfo; 11220 final ViewParent p = mParent; 11221 if (p != null && ai != null && l < r && t < b) { 11222 final Rect damage = ai.mTmpInvalRect; 11223 damage.set(l, t, r, b); 11224 p.invalidateChild(this, damage); 11225 } 11226 11227 // Damage the entire projection receiver, if necessary. 11228 if (mBackground != null && mBackground.isProjected()) { 11229 final View receiver = getProjectionReceiver(); 11230 if (receiver != null) { 11231 receiver.damageInParent(); 11232 } 11233 } 11234 11235 // Damage the entire IsolatedZVolume recieving this view's shadow. 11236 if (isHardwareAccelerated() && getZ() != 0) { 11237 damageShadowReceiver(); 11238 } 11239 } 11240 } 11241 11242 /** 11243 * @return this view's projection receiver, or {@code null} if none exists 11244 */ 11245 private View getProjectionReceiver() { 11246 ViewParent p = getParent(); 11247 while (p != null && p instanceof View) { 11248 final View v = (View) p; 11249 if (v.isProjectionReceiver()) { 11250 return v; 11251 } 11252 p = p.getParent(); 11253 } 11254 11255 return null; 11256 } 11257 11258 /** 11259 * @return whether the view is a projection receiver 11260 */ 11261 private boolean isProjectionReceiver() { 11262 return mBackground != null; 11263 } 11264 11265 /** 11266 * Damage area of the screen that can be covered by this View's shadow. 11267 * 11268 * This method will guarantee that any changes to shadows cast by a View 11269 * are damaged on the screen for future redraw. 11270 */ 11271 private void damageShadowReceiver() { 11272 final AttachInfo ai = mAttachInfo; 11273 if (ai != null) { 11274 ViewParent p = getParent(); 11275 if (p != null && p instanceof ViewGroup) { 11276 final ViewGroup vg = (ViewGroup) p; 11277 vg.damageInParent(); 11278 } 11279 } 11280 } 11281 11282 /** 11283 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11284 * set any flags or handle all of the cases handled by the default invalidation methods. 11285 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11286 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11287 * walk up the hierarchy, transforming the dirty rect as necessary. 11288 * 11289 * The method also handles normal invalidation logic if display list properties are not 11290 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11291 * backup approach, to handle these cases used in the various property-setting methods. 11292 * 11293 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11294 * are not being used in this view 11295 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11296 * list properties are not being used in this view 11297 */ 11298 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11299 if (!isHardwareAccelerated() 11300 || !mRenderNode.isValid() 11301 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11302 if (invalidateParent) { 11303 invalidateParentCaches(); 11304 } 11305 if (forceRedraw) { 11306 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11307 } 11308 invalidate(false); 11309 } else { 11310 damageInParent(); 11311 } 11312 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11313 damageShadowReceiver(); 11314 } 11315 } 11316 11317 /** 11318 * Tells the parent view to damage this view's bounds. 11319 * 11320 * @hide 11321 */ 11322 protected void damageInParent() { 11323 final AttachInfo ai = mAttachInfo; 11324 final ViewParent p = mParent; 11325 if (p != null && ai != null) { 11326 final Rect r = ai.mTmpInvalRect; 11327 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11328 if (mParent instanceof ViewGroup) { 11329 ((ViewGroup) mParent).damageChild(this, r); 11330 } else { 11331 mParent.invalidateChild(this, r); 11332 } 11333 } 11334 } 11335 11336 /** 11337 * Utility method to transform a given Rect by the current matrix of this view. 11338 */ 11339 void transformRect(final Rect rect) { 11340 if (!getMatrix().isIdentity()) { 11341 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11342 boundingRect.set(rect); 11343 getMatrix().mapRect(boundingRect); 11344 rect.set((int) Math.floor(boundingRect.left), 11345 (int) Math.floor(boundingRect.top), 11346 (int) Math.ceil(boundingRect.right), 11347 (int) Math.ceil(boundingRect.bottom)); 11348 } 11349 } 11350 11351 /** 11352 * Used to indicate that the parent of this view should clear its caches. This functionality 11353 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11354 * which is necessary when various parent-managed properties of the view change, such as 11355 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11356 * clears the parent caches and does not causes an invalidate event. 11357 * 11358 * @hide 11359 */ 11360 protected void invalidateParentCaches() { 11361 if (mParent instanceof View) { 11362 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11363 } 11364 } 11365 11366 /** 11367 * Used to indicate that the parent of this view should be invalidated. This functionality 11368 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11369 * which is necessary when various parent-managed properties of the view change, such as 11370 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11371 * an invalidation event to the parent. 11372 * 11373 * @hide 11374 */ 11375 protected void invalidateParentIfNeeded() { 11376 if (isHardwareAccelerated() && mParent instanceof View) { 11377 ((View) mParent).invalidate(true); 11378 } 11379 } 11380 11381 /** 11382 * @hide 11383 */ 11384 protected void invalidateParentIfNeededAndWasQuickRejected() { 11385 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11386 // View was rejected last time it was drawn by its parent; this may have changed 11387 invalidateParentIfNeeded(); 11388 } 11389 } 11390 11391 /** 11392 * Indicates whether this View is opaque. An opaque View guarantees that it will 11393 * draw all the pixels overlapping its bounds using a fully opaque color. 11394 * 11395 * Subclasses of View should override this method whenever possible to indicate 11396 * whether an instance is opaque. Opaque Views are treated in a special way by 11397 * the View hierarchy, possibly allowing it to perform optimizations during 11398 * invalidate/draw passes. 11399 * 11400 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11401 */ 11402 @ViewDebug.ExportedProperty(category = "drawing") 11403 public boolean isOpaque() { 11404 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11405 getFinalAlpha() >= 1.0f; 11406 } 11407 11408 /** 11409 * @hide 11410 */ 11411 protected void computeOpaqueFlags() { 11412 // Opaque if: 11413 // - Has a background 11414 // - Background is opaque 11415 // - Doesn't have scrollbars or scrollbars overlay 11416 11417 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11418 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11419 } else { 11420 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11421 } 11422 11423 final int flags = mViewFlags; 11424 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11425 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11426 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11427 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11428 } else { 11429 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11430 } 11431 } 11432 11433 /** 11434 * @hide 11435 */ 11436 protected boolean hasOpaqueScrollbars() { 11437 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11438 } 11439 11440 /** 11441 * @return A handler associated with the thread running the View. This 11442 * handler can be used to pump events in the UI events queue. 11443 */ 11444 public Handler getHandler() { 11445 final AttachInfo attachInfo = mAttachInfo; 11446 if (attachInfo != null) { 11447 return attachInfo.mHandler; 11448 } 11449 return null; 11450 } 11451 11452 /** 11453 * Gets the view root associated with the View. 11454 * @return The view root, or null if none. 11455 * @hide 11456 */ 11457 public ViewRootImpl getViewRootImpl() { 11458 if (mAttachInfo != null) { 11459 return mAttachInfo.mViewRootImpl; 11460 } 11461 return null; 11462 } 11463 11464 /** 11465 * @hide 11466 */ 11467 public HardwareRenderer getHardwareRenderer() { 11468 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11469 } 11470 11471 /** 11472 * <p>Causes the Runnable to be added to the message queue. 11473 * The runnable will be run on the user interface thread.</p> 11474 * 11475 * @param action The Runnable that will be executed. 11476 * 11477 * @return Returns true if the Runnable was successfully placed in to the 11478 * message queue. Returns false on failure, usually because the 11479 * looper processing the message queue is exiting. 11480 * 11481 * @see #postDelayed 11482 * @see #removeCallbacks 11483 */ 11484 public boolean post(Runnable action) { 11485 final AttachInfo attachInfo = mAttachInfo; 11486 if (attachInfo != null) { 11487 return attachInfo.mHandler.post(action); 11488 } 11489 // Assume that post will succeed later 11490 ViewRootImpl.getRunQueue().post(action); 11491 return true; 11492 } 11493 11494 /** 11495 * <p>Causes the Runnable to be added to the message queue, to be run 11496 * after the specified amount of time elapses. 11497 * The runnable will be run on the user interface thread.</p> 11498 * 11499 * @param action The Runnable that will be executed. 11500 * @param delayMillis The delay (in milliseconds) until the Runnable 11501 * will be executed. 11502 * 11503 * @return true if the Runnable was successfully placed in to the 11504 * message queue. Returns false on failure, usually because the 11505 * looper processing the message queue is exiting. Note that a 11506 * result of true does not mean the Runnable will be processed -- 11507 * if the looper is quit before the delivery time of the message 11508 * occurs then the message will be dropped. 11509 * 11510 * @see #post 11511 * @see #removeCallbacks 11512 */ 11513 public boolean postDelayed(Runnable action, long delayMillis) { 11514 final AttachInfo attachInfo = mAttachInfo; 11515 if (attachInfo != null) { 11516 return attachInfo.mHandler.postDelayed(action, delayMillis); 11517 } 11518 // Assume that post will succeed later 11519 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11520 return true; 11521 } 11522 11523 /** 11524 * <p>Causes the Runnable to execute on the next animation time step. 11525 * The runnable will be run on the user interface thread.</p> 11526 * 11527 * @param action The Runnable that will be executed. 11528 * 11529 * @see #postOnAnimationDelayed 11530 * @see #removeCallbacks 11531 */ 11532 public void postOnAnimation(Runnable action) { 11533 final AttachInfo attachInfo = mAttachInfo; 11534 if (attachInfo != null) { 11535 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11536 Choreographer.CALLBACK_ANIMATION, action, null); 11537 } else { 11538 // Assume that post will succeed later 11539 ViewRootImpl.getRunQueue().post(action); 11540 } 11541 } 11542 11543 /** 11544 * <p>Causes the Runnable to execute on the next animation time step, 11545 * after the specified amount of time elapses. 11546 * The runnable will be run on the user interface thread.</p> 11547 * 11548 * @param action The Runnable that will be executed. 11549 * @param delayMillis The delay (in milliseconds) until the Runnable 11550 * will be executed. 11551 * 11552 * @see #postOnAnimation 11553 * @see #removeCallbacks 11554 */ 11555 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11556 final AttachInfo attachInfo = mAttachInfo; 11557 if (attachInfo != null) { 11558 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11559 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11560 } else { 11561 // Assume that post will succeed later 11562 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11563 } 11564 } 11565 11566 /** 11567 * <p>Removes the specified Runnable from the message queue.</p> 11568 * 11569 * @param action The Runnable to remove from the message handling queue 11570 * 11571 * @return true if this view could ask the Handler to remove the Runnable, 11572 * false otherwise. When the returned value is true, the Runnable 11573 * may or may not have been actually removed from the message queue 11574 * (for instance, if the Runnable was not in the queue already.) 11575 * 11576 * @see #post 11577 * @see #postDelayed 11578 * @see #postOnAnimation 11579 * @see #postOnAnimationDelayed 11580 */ 11581 public boolean removeCallbacks(Runnable action) { 11582 if (action != null) { 11583 final AttachInfo attachInfo = mAttachInfo; 11584 if (attachInfo != null) { 11585 attachInfo.mHandler.removeCallbacks(action); 11586 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11587 Choreographer.CALLBACK_ANIMATION, action, null); 11588 } 11589 // Assume that post will succeed later 11590 ViewRootImpl.getRunQueue().removeCallbacks(action); 11591 } 11592 return true; 11593 } 11594 11595 /** 11596 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11597 * Use this to invalidate the View from a non-UI thread.</p> 11598 * 11599 * <p>This method can be invoked from outside of the UI thread 11600 * only when this View is attached to a window.</p> 11601 * 11602 * @see #invalidate() 11603 * @see #postInvalidateDelayed(long) 11604 */ 11605 public void postInvalidate() { 11606 postInvalidateDelayed(0); 11607 } 11608 11609 /** 11610 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11611 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11612 * 11613 * <p>This method can be invoked from outside of the UI thread 11614 * only when this View is attached to a window.</p> 11615 * 11616 * @param left The left coordinate of the rectangle to invalidate. 11617 * @param top The top coordinate of the rectangle to invalidate. 11618 * @param right The right coordinate of the rectangle to invalidate. 11619 * @param bottom The bottom coordinate of the rectangle to invalidate. 11620 * 11621 * @see #invalidate(int, int, int, int) 11622 * @see #invalidate(Rect) 11623 * @see #postInvalidateDelayed(long, int, int, int, int) 11624 */ 11625 public void postInvalidate(int left, int top, int right, int bottom) { 11626 postInvalidateDelayed(0, left, top, right, bottom); 11627 } 11628 11629 /** 11630 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11631 * loop. Waits for the specified amount of time.</p> 11632 * 11633 * <p>This method can be invoked from outside of the UI thread 11634 * only when this View is attached to a window.</p> 11635 * 11636 * @param delayMilliseconds the duration in milliseconds to delay the 11637 * invalidation by 11638 * 11639 * @see #invalidate() 11640 * @see #postInvalidate() 11641 */ 11642 public void postInvalidateDelayed(long delayMilliseconds) { 11643 // We try only with the AttachInfo because there's no point in invalidating 11644 // if we are not attached to our window 11645 final AttachInfo attachInfo = mAttachInfo; 11646 if (attachInfo != null) { 11647 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11648 } 11649 } 11650 11651 /** 11652 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11653 * through the event loop. Waits for the specified amount of time.</p> 11654 * 11655 * <p>This method can be invoked from outside of the UI thread 11656 * only when this View is attached to a window.</p> 11657 * 11658 * @param delayMilliseconds the duration in milliseconds to delay the 11659 * invalidation by 11660 * @param left The left coordinate of the rectangle to invalidate. 11661 * @param top The top coordinate of the rectangle to invalidate. 11662 * @param right The right coordinate of the rectangle to invalidate. 11663 * @param bottom The bottom coordinate of the rectangle to invalidate. 11664 * 11665 * @see #invalidate(int, int, int, int) 11666 * @see #invalidate(Rect) 11667 * @see #postInvalidate(int, int, int, int) 11668 */ 11669 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11670 int right, int bottom) { 11671 11672 // We try only with the AttachInfo because there's no point in invalidating 11673 // if we are not attached to our window 11674 final AttachInfo attachInfo = mAttachInfo; 11675 if (attachInfo != null) { 11676 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11677 info.target = this; 11678 info.left = left; 11679 info.top = top; 11680 info.right = right; 11681 info.bottom = bottom; 11682 11683 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11684 } 11685 } 11686 11687 /** 11688 * <p>Cause an invalidate to happen on the next animation time step, typically the 11689 * next display frame.</p> 11690 * 11691 * <p>This method can be invoked from outside of the UI thread 11692 * only when this View is attached to a window.</p> 11693 * 11694 * @see #invalidate() 11695 */ 11696 public void postInvalidateOnAnimation() { 11697 // We try only with the AttachInfo because there's no point in invalidating 11698 // if we are not attached to our window 11699 final AttachInfo attachInfo = mAttachInfo; 11700 if (attachInfo != null) { 11701 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11702 } 11703 } 11704 11705 /** 11706 * <p>Cause an invalidate of the specified area to happen on the next animation 11707 * time step, typically the next display frame.</p> 11708 * 11709 * <p>This method can be invoked from outside of the UI thread 11710 * only when this View is attached to a window.</p> 11711 * 11712 * @param left The left coordinate of the rectangle to invalidate. 11713 * @param top The top coordinate of the rectangle to invalidate. 11714 * @param right The right coordinate of the rectangle to invalidate. 11715 * @param bottom The bottom coordinate of the rectangle to invalidate. 11716 * 11717 * @see #invalidate(int, int, int, int) 11718 * @see #invalidate(Rect) 11719 */ 11720 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11721 // We try only with the AttachInfo because there's no point in invalidating 11722 // if we are not attached to our window 11723 final AttachInfo attachInfo = mAttachInfo; 11724 if (attachInfo != null) { 11725 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11726 info.target = this; 11727 info.left = left; 11728 info.top = top; 11729 info.right = right; 11730 info.bottom = bottom; 11731 11732 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11733 } 11734 } 11735 11736 /** 11737 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11738 * This event is sent at most once every 11739 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11740 */ 11741 private void postSendViewScrolledAccessibilityEventCallback() { 11742 if (mSendViewScrolledAccessibilityEvent == null) { 11743 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11744 } 11745 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11746 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11747 postDelayed(mSendViewScrolledAccessibilityEvent, 11748 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11749 } 11750 } 11751 11752 /** 11753 * Called by a parent to request that a child update its values for mScrollX 11754 * and mScrollY if necessary. This will typically be done if the child is 11755 * animating a scroll using a {@link android.widget.Scroller Scroller} 11756 * object. 11757 */ 11758 public void computeScroll() { 11759 } 11760 11761 /** 11762 * <p>Indicate whether the horizontal edges are faded when the view is 11763 * scrolled horizontally.</p> 11764 * 11765 * @return true if the horizontal edges should are faded on scroll, false 11766 * otherwise 11767 * 11768 * @see #setHorizontalFadingEdgeEnabled(boolean) 11769 * 11770 * @attr ref android.R.styleable#View_requiresFadingEdge 11771 */ 11772 public boolean isHorizontalFadingEdgeEnabled() { 11773 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11774 } 11775 11776 /** 11777 * <p>Define whether the horizontal edges should be faded when this view 11778 * is scrolled horizontally.</p> 11779 * 11780 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11781 * be faded when the view is scrolled 11782 * horizontally 11783 * 11784 * @see #isHorizontalFadingEdgeEnabled() 11785 * 11786 * @attr ref android.R.styleable#View_requiresFadingEdge 11787 */ 11788 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11789 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11790 if (horizontalFadingEdgeEnabled) { 11791 initScrollCache(); 11792 } 11793 11794 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11795 } 11796 } 11797 11798 /** 11799 * <p>Indicate whether the vertical edges are faded when the view is 11800 * scrolled horizontally.</p> 11801 * 11802 * @return true if the vertical edges should are faded on scroll, false 11803 * otherwise 11804 * 11805 * @see #setVerticalFadingEdgeEnabled(boolean) 11806 * 11807 * @attr ref android.R.styleable#View_requiresFadingEdge 11808 */ 11809 public boolean isVerticalFadingEdgeEnabled() { 11810 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11811 } 11812 11813 /** 11814 * <p>Define whether the vertical edges should be faded when this view 11815 * is scrolled vertically.</p> 11816 * 11817 * @param verticalFadingEdgeEnabled true if the vertical edges should 11818 * be faded when the view is scrolled 11819 * vertically 11820 * 11821 * @see #isVerticalFadingEdgeEnabled() 11822 * 11823 * @attr ref android.R.styleable#View_requiresFadingEdge 11824 */ 11825 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11826 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11827 if (verticalFadingEdgeEnabled) { 11828 initScrollCache(); 11829 } 11830 11831 mViewFlags ^= FADING_EDGE_VERTICAL; 11832 } 11833 } 11834 11835 /** 11836 * Returns the strength, or intensity, of the top faded edge. The strength is 11837 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11838 * returns 0.0 or 1.0 but no value in between. 11839 * 11840 * Subclasses should override this method to provide a smoother fade transition 11841 * when scrolling occurs. 11842 * 11843 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11844 */ 11845 protected float getTopFadingEdgeStrength() { 11846 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11847 } 11848 11849 /** 11850 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11851 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11852 * returns 0.0 or 1.0 but no value in between. 11853 * 11854 * Subclasses should override this method to provide a smoother fade transition 11855 * when scrolling occurs. 11856 * 11857 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11858 */ 11859 protected float getBottomFadingEdgeStrength() { 11860 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11861 computeVerticalScrollRange() ? 1.0f : 0.0f; 11862 } 11863 11864 /** 11865 * Returns the strength, or intensity, of the left faded edge. The strength is 11866 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11867 * returns 0.0 or 1.0 but no value in between. 11868 * 11869 * Subclasses should override this method to provide a smoother fade transition 11870 * when scrolling occurs. 11871 * 11872 * @return the intensity of the left fade as a float between 0.0f and 1.0f 11873 */ 11874 protected float getLeftFadingEdgeStrength() { 11875 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 11876 } 11877 11878 /** 11879 * Returns the strength, or intensity, of the right faded edge. The strength is 11880 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11881 * returns 0.0 or 1.0 but no value in between. 11882 * 11883 * Subclasses should override this method to provide a smoother fade transition 11884 * when scrolling occurs. 11885 * 11886 * @return the intensity of the right fade as a float between 0.0f and 1.0f 11887 */ 11888 protected float getRightFadingEdgeStrength() { 11889 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 11890 computeHorizontalScrollRange() ? 1.0f : 0.0f; 11891 } 11892 11893 /** 11894 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 11895 * scrollbar is not drawn by default.</p> 11896 * 11897 * @return true if the horizontal scrollbar should be painted, false 11898 * otherwise 11899 * 11900 * @see #setHorizontalScrollBarEnabled(boolean) 11901 */ 11902 public boolean isHorizontalScrollBarEnabled() { 11903 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11904 } 11905 11906 /** 11907 * <p>Define whether the horizontal scrollbar should be drawn or not. The 11908 * scrollbar is not drawn by default.</p> 11909 * 11910 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 11911 * be painted 11912 * 11913 * @see #isHorizontalScrollBarEnabled() 11914 */ 11915 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 11916 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 11917 mViewFlags ^= SCROLLBARS_HORIZONTAL; 11918 computeOpaqueFlags(); 11919 resolvePadding(); 11920 } 11921 } 11922 11923 /** 11924 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 11925 * scrollbar is not drawn by default.</p> 11926 * 11927 * @return true if the vertical scrollbar should be painted, false 11928 * otherwise 11929 * 11930 * @see #setVerticalScrollBarEnabled(boolean) 11931 */ 11932 public boolean isVerticalScrollBarEnabled() { 11933 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 11934 } 11935 11936 /** 11937 * <p>Define whether the vertical scrollbar should be drawn or not. The 11938 * scrollbar is not drawn by default.</p> 11939 * 11940 * @param verticalScrollBarEnabled true if the vertical scrollbar should 11941 * be painted 11942 * 11943 * @see #isVerticalScrollBarEnabled() 11944 */ 11945 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 11946 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 11947 mViewFlags ^= SCROLLBARS_VERTICAL; 11948 computeOpaqueFlags(); 11949 resolvePadding(); 11950 } 11951 } 11952 11953 /** 11954 * @hide 11955 */ 11956 protected void recomputePadding() { 11957 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 11958 } 11959 11960 /** 11961 * Define whether scrollbars will fade when the view is not scrolling. 11962 * 11963 * @param fadeScrollbars wheter to enable fading 11964 * 11965 * @attr ref android.R.styleable#View_fadeScrollbars 11966 */ 11967 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 11968 initScrollCache(); 11969 final ScrollabilityCache scrollabilityCache = mScrollCache; 11970 scrollabilityCache.fadeScrollBars = fadeScrollbars; 11971 if (fadeScrollbars) { 11972 scrollabilityCache.state = ScrollabilityCache.OFF; 11973 } else { 11974 scrollabilityCache.state = ScrollabilityCache.ON; 11975 } 11976 } 11977 11978 /** 11979 * 11980 * Returns true if scrollbars will fade when this view is not scrolling 11981 * 11982 * @return true if scrollbar fading is enabled 11983 * 11984 * @attr ref android.R.styleable#View_fadeScrollbars 11985 */ 11986 public boolean isScrollbarFadingEnabled() { 11987 return mScrollCache != null && mScrollCache.fadeScrollBars; 11988 } 11989 11990 /** 11991 * 11992 * Returns the delay before scrollbars fade. 11993 * 11994 * @return the delay before scrollbars fade 11995 * 11996 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11997 */ 11998 public int getScrollBarDefaultDelayBeforeFade() { 11999 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12000 mScrollCache.scrollBarDefaultDelayBeforeFade; 12001 } 12002 12003 /** 12004 * Define the delay before scrollbars fade. 12005 * 12006 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12007 * 12008 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12009 */ 12010 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12011 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12012 } 12013 12014 /** 12015 * 12016 * Returns the scrollbar fade duration. 12017 * 12018 * @return the scrollbar fade duration 12019 * 12020 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12021 */ 12022 public int getScrollBarFadeDuration() { 12023 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12024 mScrollCache.scrollBarFadeDuration; 12025 } 12026 12027 /** 12028 * Define the scrollbar fade duration. 12029 * 12030 * @param scrollBarFadeDuration - the scrollbar fade duration 12031 * 12032 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12033 */ 12034 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12035 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12036 } 12037 12038 /** 12039 * 12040 * Returns the scrollbar size. 12041 * 12042 * @return the scrollbar size 12043 * 12044 * @attr ref android.R.styleable#View_scrollbarSize 12045 */ 12046 public int getScrollBarSize() { 12047 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12048 mScrollCache.scrollBarSize; 12049 } 12050 12051 /** 12052 * Define the scrollbar size. 12053 * 12054 * @param scrollBarSize - the scrollbar size 12055 * 12056 * @attr ref android.R.styleable#View_scrollbarSize 12057 */ 12058 public void setScrollBarSize(int scrollBarSize) { 12059 getScrollCache().scrollBarSize = scrollBarSize; 12060 } 12061 12062 /** 12063 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12064 * inset. When inset, they add to the padding of the view. And the scrollbars 12065 * can be drawn inside the padding area or on the edge of the view. For example, 12066 * if a view has a background drawable and you want to draw the scrollbars 12067 * inside the padding specified by the drawable, you can use 12068 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12069 * appear at the edge of the view, ignoring the padding, then you can use 12070 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12071 * @param style the style of the scrollbars. Should be one of 12072 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12073 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12074 * @see #SCROLLBARS_INSIDE_OVERLAY 12075 * @see #SCROLLBARS_INSIDE_INSET 12076 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12077 * @see #SCROLLBARS_OUTSIDE_INSET 12078 * 12079 * @attr ref android.R.styleable#View_scrollbarStyle 12080 */ 12081 public void setScrollBarStyle(@ScrollBarStyle int style) { 12082 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12083 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12084 computeOpaqueFlags(); 12085 resolvePadding(); 12086 } 12087 } 12088 12089 /** 12090 * <p>Returns the current scrollbar style.</p> 12091 * @return the current scrollbar style 12092 * @see #SCROLLBARS_INSIDE_OVERLAY 12093 * @see #SCROLLBARS_INSIDE_INSET 12094 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12095 * @see #SCROLLBARS_OUTSIDE_INSET 12096 * 12097 * @attr ref android.R.styleable#View_scrollbarStyle 12098 */ 12099 @ViewDebug.ExportedProperty(mapping = { 12100 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12101 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12102 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12103 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12104 }) 12105 @ScrollBarStyle 12106 public int getScrollBarStyle() { 12107 return mViewFlags & SCROLLBARS_STYLE_MASK; 12108 } 12109 12110 /** 12111 * <p>Compute the horizontal range that the horizontal scrollbar 12112 * represents.</p> 12113 * 12114 * <p>The range is expressed in arbitrary units that must be the same as the 12115 * units used by {@link #computeHorizontalScrollExtent()} and 12116 * {@link #computeHorizontalScrollOffset()}.</p> 12117 * 12118 * <p>The default range is the drawing width of this view.</p> 12119 * 12120 * @return the total horizontal range represented by the horizontal 12121 * scrollbar 12122 * 12123 * @see #computeHorizontalScrollExtent() 12124 * @see #computeHorizontalScrollOffset() 12125 * @see android.widget.ScrollBarDrawable 12126 */ 12127 protected int computeHorizontalScrollRange() { 12128 return getWidth(); 12129 } 12130 12131 /** 12132 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12133 * within the horizontal range. This value is used to compute the position 12134 * of the thumb within the scrollbar's track.</p> 12135 * 12136 * <p>The range is expressed in arbitrary units that must be the same as the 12137 * units used by {@link #computeHorizontalScrollRange()} and 12138 * {@link #computeHorizontalScrollExtent()}.</p> 12139 * 12140 * <p>The default offset is the scroll offset of this view.</p> 12141 * 12142 * @return the horizontal offset of the scrollbar's thumb 12143 * 12144 * @see #computeHorizontalScrollRange() 12145 * @see #computeHorizontalScrollExtent() 12146 * @see android.widget.ScrollBarDrawable 12147 */ 12148 protected int computeHorizontalScrollOffset() { 12149 return mScrollX; 12150 } 12151 12152 /** 12153 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12154 * within the horizontal range. This value is used to compute the length 12155 * of the thumb within the scrollbar's track.</p> 12156 * 12157 * <p>The range is expressed in arbitrary units that must be the same as the 12158 * units used by {@link #computeHorizontalScrollRange()} and 12159 * {@link #computeHorizontalScrollOffset()}.</p> 12160 * 12161 * <p>The default extent is the drawing width of this view.</p> 12162 * 12163 * @return the horizontal extent of the scrollbar's thumb 12164 * 12165 * @see #computeHorizontalScrollRange() 12166 * @see #computeHorizontalScrollOffset() 12167 * @see android.widget.ScrollBarDrawable 12168 */ 12169 protected int computeHorizontalScrollExtent() { 12170 return getWidth(); 12171 } 12172 12173 /** 12174 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12175 * 12176 * <p>The range is expressed in arbitrary units that must be the same as the 12177 * units used by {@link #computeVerticalScrollExtent()} and 12178 * {@link #computeVerticalScrollOffset()}.</p> 12179 * 12180 * @return the total vertical range represented by the vertical scrollbar 12181 * 12182 * <p>The default range is the drawing height of this view.</p> 12183 * 12184 * @see #computeVerticalScrollExtent() 12185 * @see #computeVerticalScrollOffset() 12186 * @see android.widget.ScrollBarDrawable 12187 */ 12188 protected int computeVerticalScrollRange() { 12189 return getHeight(); 12190 } 12191 12192 /** 12193 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12194 * within the horizontal range. This value is used to compute the position 12195 * of the thumb within the scrollbar's track.</p> 12196 * 12197 * <p>The range is expressed in arbitrary units that must be the same as the 12198 * units used by {@link #computeVerticalScrollRange()} and 12199 * {@link #computeVerticalScrollExtent()}.</p> 12200 * 12201 * <p>The default offset is the scroll offset of this view.</p> 12202 * 12203 * @return the vertical offset of the scrollbar's thumb 12204 * 12205 * @see #computeVerticalScrollRange() 12206 * @see #computeVerticalScrollExtent() 12207 * @see android.widget.ScrollBarDrawable 12208 */ 12209 protected int computeVerticalScrollOffset() { 12210 return mScrollY; 12211 } 12212 12213 /** 12214 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12215 * within the vertical range. This value is used to compute the length 12216 * of the thumb within the scrollbar's track.</p> 12217 * 12218 * <p>The range is expressed in arbitrary units that must be the same as the 12219 * units used by {@link #computeVerticalScrollRange()} and 12220 * {@link #computeVerticalScrollOffset()}.</p> 12221 * 12222 * <p>The default extent is the drawing height of this view.</p> 12223 * 12224 * @return the vertical extent of the scrollbar's thumb 12225 * 12226 * @see #computeVerticalScrollRange() 12227 * @see #computeVerticalScrollOffset() 12228 * @see android.widget.ScrollBarDrawable 12229 */ 12230 protected int computeVerticalScrollExtent() { 12231 return getHeight(); 12232 } 12233 12234 /** 12235 * Check if this view can be scrolled horizontally in a certain direction. 12236 * 12237 * @param direction Negative to check scrolling left, positive to check scrolling right. 12238 * @return true if this view can be scrolled in the specified direction, false otherwise. 12239 */ 12240 public boolean canScrollHorizontally(int direction) { 12241 final int offset = computeHorizontalScrollOffset(); 12242 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12243 if (range == 0) return false; 12244 if (direction < 0) { 12245 return offset > 0; 12246 } else { 12247 return offset < range - 1; 12248 } 12249 } 12250 12251 /** 12252 * Check if this view can be scrolled vertically in a certain direction. 12253 * 12254 * @param direction Negative to check scrolling up, positive to check scrolling down. 12255 * @return true if this view can be scrolled in the specified direction, false otherwise. 12256 */ 12257 public boolean canScrollVertically(int direction) { 12258 final int offset = computeVerticalScrollOffset(); 12259 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12260 if (range == 0) return false; 12261 if (direction < 0) { 12262 return offset > 0; 12263 } else { 12264 return offset < range - 1; 12265 } 12266 } 12267 12268 /** 12269 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12270 * scrollbars are painted only if they have been awakened first.</p> 12271 * 12272 * @param canvas the canvas on which to draw the scrollbars 12273 * 12274 * @see #awakenScrollBars(int) 12275 */ 12276 protected final void onDrawScrollBars(Canvas canvas) { 12277 // scrollbars are drawn only when the animation is running 12278 final ScrollabilityCache cache = mScrollCache; 12279 if (cache != null) { 12280 12281 int state = cache.state; 12282 12283 if (state == ScrollabilityCache.OFF) { 12284 return; 12285 } 12286 12287 boolean invalidate = false; 12288 12289 if (state == ScrollabilityCache.FADING) { 12290 // We're fading -- get our fade interpolation 12291 if (cache.interpolatorValues == null) { 12292 cache.interpolatorValues = new float[1]; 12293 } 12294 12295 float[] values = cache.interpolatorValues; 12296 12297 // Stops the animation if we're done 12298 if (cache.scrollBarInterpolator.timeToValues(values) == 12299 Interpolator.Result.FREEZE_END) { 12300 cache.state = ScrollabilityCache.OFF; 12301 } else { 12302 cache.scrollBar.setAlpha(Math.round(values[0])); 12303 } 12304 12305 // This will make the scroll bars inval themselves after 12306 // drawing. We only want this when we're fading so that 12307 // we prevent excessive redraws 12308 invalidate = true; 12309 } else { 12310 // We're just on -- but we may have been fading before so 12311 // reset alpha 12312 cache.scrollBar.setAlpha(255); 12313 } 12314 12315 12316 final int viewFlags = mViewFlags; 12317 12318 final boolean drawHorizontalScrollBar = 12319 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12320 final boolean drawVerticalScrollBar = 12321 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12322 && !isVerticalScrollBarHidden(); 12323 12324 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12325 final int width = mRight - mLeft; 12326 final int height = mBottom - mTop; 12327 12328 final ScrollBarDrawable scrollBar = cache.scrollBar; 12329 12330 final int scrollX = mScrollX; 12331 final int scrollY = mScrollY; 12332 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12333 12334 int left; 12335 int top; 12336 int right; 12337 int bottom; 12338 12339 if (drawHorizontalScrollBar) { 12340 int size = scrollBar.getSize(false); 12341 if (size <= 0) { 12342 size = cache.scrollBarSize; 12343 } 12344 12345 scrollBar.setParameters(computeHorizontalScrollRange(), 12346 computeHorizontalScrollOffset(), 12347 computeHorizontalScrollExtent(), false); 12348 final int verticalScrollBarGap = drawVerticalScrollBar ? 12349 getVerticalScrollbarWidth() : 0; 12350 top = scrollY + height - size - (mUserPaddingBottom & inside); 12351 left = scrollX + (mPaddingLeft & inside); 12352 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12353 bottom = top + size; 12354 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12355 if (invalidate) { 12356 invalidate(left, top, right, bottom); 12357 } 12358 } 12359 12360 if (drawVerticalScrollBar) { 12361 int size = scrollBar.getSize(true); 12362 if (size <= 0) { 12363 size = cache.scrollBarSize; 12364 } 12365 12366 scrollBar.setParameters(computeVerticalScrollRange(), 12367 computeVerticalScrollOffset(), 12368 computeVerticalScrollExtent(), true); 12369 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12370 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12371 verticalScrollbarPosition = isLayoutRtl() ? 12372 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12373 } 12374 switch (verticalScrollbarPosition) { 12375 default: 12376 case SCROLLBAR_POSITION_RIGHT: 12377 left = scrollX + width - size - (mUserPaddingRight & inside); 12378 break; 12379 case SCROLLBAR_POSITION_LEFT: 12380 left = scrollX + (mUserPaddingLeft & inside); 12381 break; 12382 } 12383 top = scrollY + (mPaddingTop & inside); 12384 right = left + size; 12385 bottom = scrollY + height - (mUserPaddingBottom & inside); 12386 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12387 if (invalidate) { 12388 invalidate(left, top, right, bottom); 12389 } 12390 } 12391 } 12392 } 12393 } 12394 12395 /** 12396 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12397 * FastScroller is visible. 12398 * @return whether to temporarily hide the vertical scrollbar 12399 * @hide 12400 */ 12401 protected boolean isVerticalScrollBarHidden() { 12402 return false; 12403 } 12404 12405 /** 12406 * <p>Draw the horizontal scrollbar if 12407 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12408 * 12409 * @param canvas the canvas on which to draw the scrollbar 12410 * @param scrollBar the scrollbar's drawable 12411 * 12412 * @see #isHorizontalScrollBarEnabled() 12413 * @see #computeHorizontalScrollRange() 12414 * @see #computeHorizontalScrollExtent() 12415 * @see #computeHorizontalScrollOffset() 12416 * @see android.widget.ScrollBarDrawable 12417 * @hide 12418 */ 12419 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12420 int l, int t, int r, int b) { 12421 scrollBar.setBounds(l, t, r, b); 12422 scrollBar.draw(canvas); 12423 } 12424 12425 /** 12426 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12427 * returns true.</p> 12428 * 12429 * @param canvas the canvas on which to draw the scrollbar 12430 * @param scrollBar the scrollbar's drawable 12431 * 12432 * @see #isVerticalScrollBarEnabled() 12433 * @see #computeVerticalScrollRange() 12434 * @see #computeVerticalScrollExtent() 12435 * @see #computeVerticalScrollOffset() 12436 * @see android.widget.ScrollBarDrawable 12437 * @hide 12438 */ 12439 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12440 int l, int t, int r, int b) { 12441 scrollBar.setBounds(l, t, r, b); 12442 scrollBar.draw(canvas); 12443 } 12444 12445 /** 12446 * Implement this to do your drawing. 12447 * 12448 * @param canvas the canvas on which the background will be drawn 12449 */ 12450 protected void onDraw(Canvas canvas) { 12451 } 12452 12453 /* 12454 * Caller is responsible for calling requestLayout if necessary. 12455 * (This allows addViewInLayout to not request a new layout.) 12456 */ 12457 void assignParent(ViewParent parent) { 12458 if (mParent == null) { 12459 mParent = parent; 12460 } else if (parent == null) { 12461 mParent = null; 12462 } else { 12463 throw new RuntimeException("view " + this + " being added, but" 12464 + " it already has a parent"); 12465 } 12466 } 12467 12468 /** 12469 * This is called when the view is attached to a window. At this point it 12470 * has a Surface and will start drawing. Note that this function is 12471 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12472 * however it may be called any time before the first onDraw -- including 12473 * before or after {@link #onMeasure(int, int)}. 12474 * 12475 * @see #onDetachedFromWindow() 12476 */ 12477 protected void onAttachedToWindow() { 12478 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12479 mParent.requestTransparentRegion(this); 12480 } 12481 12482 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12483 initialAwakenScrollBars(); 12484 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12485 } 12486 12487 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12488 12489 jumpDrawablesToCurrentState(); 12490 12491 resetSubtreeAccessibilityStateChanged(); 12492 12493 if (isFocused()) { 12494 InputMethodManager imm = InputMethodManager.peekInstance(); 12495 imm.focusIn(this); 12496 } 12497 } 12498 12499 /** 12500 * Resolve all RTL related properties. 12501 * 12502 * @return true if resolution of RTL properties has been done 12503 * 12504 * @hide 12505 */ 12506 public boolean resolveRtlPropertiesIfNeeded() { 12507 if (!needRtlPropertiesResolution()) return false; 12508 12509 // Order is important here: LayoutDirection MUST be resolved first 12510 if (!isLayoutDirectionResolved()) { 12511 resolveLayoutDirection(); 12512 resolveLayoutParams(); 12513 } 12514 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12515 if (!isTextDirectionResolved()) { 12516 resolveTextDirection(); 12517 } 12518 if (!isTextAlignmentResolved()) { 12519 resolveTextAlignment(); 12520 } 12521 // Should resolve Drawables before Padding because we need the layout direction of the 12522 // Drawable to correctly resolve Padding. 12523 if (!isDrawablesResolved()) { 12524 resolveDrawables(); 12525 } 12526 if (!isPaddingResolved()) { 12527 resolvePadding(); 12528 } 12529 onRtlPropertiesChanged(getLayoutDirection()); 12530 return true; 12531 } 12532 12533 /** 12534 * Reset resolution of all RTL related properties. 12535 * 12536 * @hide 12537 */ 12538 public void resetRtlProperties() { 12539 resetResolvedLayoutDirection(); 12540 resetResolvedTextDirection(); 12541 resetResolvedTextAlignment(); 12542 resetResolvedPadding(); 12543 resetResolvedDrawables(); 12544 } 12545 12546 /** 12547 * @see #onScreenStateChanged(int) 12548 */ 12549 void dispatchScreenStateChanged(int screenState) { 12550 onScreenStateChanged(screenState); 12551 } 12552 12553 /** 12554 * This method is called whenever the state of the screen this view is 12555 * attached to changes. A state change will usually occurs when the screen 12556 * turns on or off (whether it happens automatically or the user does it 12557 * manually.) 12558 * 12559 * @param screenState The new state of the screen. Can be either 12560 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12561 */ 12562 public void onScreenStateChanged(int screenState) { 12563 } 12564 12565 /** 12566 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12567 */ 12568 private boolean hasRtlSupport() { 12569 return mContext.getApplicationInfo().hasRtlSupport(); 12570 } 12571 12572 /** 12573 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12574 * RTL not supported) 12575 */ 12576 private boolean isRtlCompatibilityMode() { 12577 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12578 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12579 } 12580 12581 /** 12582 * @return true if RTL properties need resolution. 12583 * 12584 */ 12585 private boolean needRtlPropertiesResolution() { 12586 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12587 } 12588 12589 /** 12590 * Called when any RTL property (layout direction or text direction or text alignment) has 12591 * been changed. 12592 * 12593 * Subclasses need to override this method to take care of cached information that depends on the 12594 * resolved layout direction, or to inform child views that inherit their layout direction. 12595 * 12596 * The default implementation does nothing. 12597 * 12598 * @param layoutDirection the direction of the layout 12599 * 12600 * @see #LAYOUT_DIRECTION_LTR 12601 * @see #LAYOUT_DIRECTION_RTL 12602 */ 12603 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12604 } 12605 12606 /** 12607 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12608 * that the parent directionality can and will be resolved before its children. 12609 * 12610 * @return true if resolution has been done, false otherwise. 12611 * 12612 * @hide 12613 */ 12614 public boolean resolveLayoutDirection() { 12615 // Clear any previous layout direction resolution 12616 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12617 12618 if (hasRtlSupport()) { 12619 // Set resolved depending on layout direction 12620 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12621 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12622 case LAYOUT_DIRECTION_INHERIT: 12623 // We cannot resolve yet. LTR is by default and let the resolution happen again 12624 // later to get the correct resolved value 12625 if (!canResolveLayoutDirection()) return false; 12626 12627 // Parent has not yet resolved, LTR is still the default 12628 try { 12629 if (!mParent.isLayoutDirectionResolved()) return false; 12630 12631 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12632 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12633 } 12634 } catch (AbstractMethodError e) { 12635 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12636 " does not fully implement ViewParent", e); 12637 } 12638 break; 12639 case LAYOUT_DIRECTION_RTL: 12640 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12641 break; 12642 case LAYOUT_DIRECTION_LOCALE: 12643 if((LAYOUT_DIRECTION_RTL == 12644 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12645 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12646 } 12647 break; 12648 default: 12649 // Nothing to do, LTR by default 12650 } 12651 } 12652 12653 // Set to resolved 12654 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12655 return true; 12656 } 12657 12658 /** 12659 * Check if layout direction resolution can be done. 12660 * 12661 * @return true if layout direction resolution can be done otherwise return false. 12662 */ 12663 public boolean canResolveLayoutDirection() { 12664 switch (getRawLayoutDirection()) { 12665 case LAYOUT_DIRECTION_INHERIT: 12666 if (mParent != null) { 12667 try { 12668 return mParent.canResolveLayoutDirection(); 12669 } catch (AbstractMethodError e) { 12670 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12671 " does not fully implement ViewParent", e); 12672 } 12673 } 12674 return false; 12675 12676 default: 12677 return true; 12678 } 12679 } 12680 12681 /** 12682 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12683 * {@link #onMeasure(int, int)}. 12684 * 12685 * @hide 12686 */ 12687 public void resetResolvedLayoutDirection() { 12688 // Reset the current resolved bits 12689 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12690 } 12691 12692 /** 12693 * @return true if the layout direction is inherited. 12694 * 12695 * @hide 12696 */ 12697 public boolean isLayoutDirectionInherited() { 12698 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12699 } 12700 12701 /** 12702 * @return true if layout direction has been resolved. 12703 */ 12704 public boolean isLayoutDirectionResolved() { 12705 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12706 } 12707 12708 /** 12709 * Return if padding has been resolved 12710 * 12711 * @hide 12712 */ 12713 boolean isPaddingResolved() { 12714 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12715 } 12716 12717 /** 12718 * Resolves padding depending on layout direction, if applicable, and 12719 * recomputes internal padding values to adjust for scroll bars. 12720 * 12721 * @hide 12722 */ 12723 public void resolvePadding() { 12724 final int resolvedLayoutDirection = getLayoutDirection(); 12725 12726 if (!isRtlCompatibilityMode()) { 12727 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12728 // If start / end padding are defined, they will be resolved (hence overriding) to 12729 // left / right or right / left depending on the resolved layout direction. 12730 // If start / end padding are not defined, use the left / right ones. 12731 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12732 Rect padding = sThreadLocal.get(); 12733 if (padding == null) { 12734 padding = new Rect(); 12735 sThreadLocal.set(padding); 12736 } 12737 mBackground.getPadding(padding); 12738 if (!mLeftPaddingDefined) { 12739 mUserPaddingLeftInitial = padding.left; 12740 } 12741 if (!mRightPaddingDefined) { 12742 mUserPaddingRightInitial = padding.right; 12743 } 12744 } 12745 switch (resolvedLayoutDirection) { 12746 case LAYOUT_DIRECTION_RTL: 12747 if (mUserPaddingStart != UNDEFINED_PADDING) { 12748 mUserPaddingRight = mUserPaddingStart; 12749 } else { 12750 mUserPaddingRight = mUserPaddingRightInitial; 12751 } 12752 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12753 mUserPaddingLeft = mUserPaddingEnd; 12754 } else { 12755 mUserPaddingLeft = mUserPaddingLeftInitial; 12756 } 12757 break; 12758 case LAYOUT_DIRECTION_LTR: 12759 default: 12760 if (mUserPaddingStart != UNDEFINED_PADDING) { 12761 mUserPaddingLeft = mUserPaddingStart; 12762 } else { 12763 mUserPaddingLeft = mUserPaddingLeftInitial; 12764 } 12765 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12766 mUserPaddingRight = mUserPaddingEnd; 12767 } else { 12768 mUserPaddingRight = mUserPaddingRightInitial; 12769 } 12770 } 12771 12772 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12773 } 12774 12775 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12776 onRtlPropertiesChanged(resolvedLayoutDirection); 12777 12778 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12779 } 12780 12781 /** 12782 * Reset the resolved layout direction. 12783 * 12784 * @hide 12785 */ 12786 public void resetResolvedPadding() { 12787 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12788 } 12789 12790 /** 12791 * This is called when the view is detached from a window. At this point it 12792 * no longer has a surface for drawing. 12793 * 12794 * @see #onAttachedToWindow() 12795 */ 12796 protected void onDetachedFromWindow() { 12797 } 12798 12799 /** 12800 * This is a framework-internal mirror of onDetachedFromWindow() that's called 12801 * after onDetachedFromWindow(). 12802 * 12803 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 12804 * The super method should be called at the end of the overriden method to ensure 12805 * subclasses are destroyed first 12806 * 12807 * @hide 12808 */ 12809 protected void onDetachedFromWindowInternal() { 12810 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12811 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12812 12813 if (mBackground != null) { 12814 mBackground.clearHotspots(); 12815 } 12816 12817 removeUnsetPressCallback(); 12818 removeLongPressCallback(); 12819 removePerformClickCallback(); 12820 removeSendViewScrolledAccessibilityEventCallback(); 12821 stopNestedScroll(); 12822 12823 destroyDrawingCache(); 12824 destroyLayer(false); 12825 12826 cleanupDraw(); 12827 12828 mCurrentAnimation = null; 12829 } 12830 12831 private void cleanupDraw() { 12832 resetDisplayList(); 12833 if (mAttachInfo != null) { 12834 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12835 } 12836 } 12837 12838 /** 12839 * This method ensures the hardware renderer is in a valid state 12840 * before executing the specified action. 12841 * 12842 * This method will attempt to set a valid state even if the window 12843 * the renderer is attached to was destroyed. 12844 * 12845 * This method is not guaranteed to work. If the hardware renderer 12846 * does not exist or cannot be put in a valid state, this method 12847 * will not executed the specified action. 12848 * 12849 * The specified action is executed synchronously. 12850 * 12851 * @param action The action to execute after the renderer is in a valid state 12852 * 12853 * @return True if the specified Runnable was executed, false otherwise 12854 * 12855 * @hide 12856 */ 12857 public boolean executeHardwareAction(Runnable action) { 12858 //noinspection SimplifiableIfStatement 12859 if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) { 12860 return mAttachInfo.mHardwareRenderer.safelyRun(action); 12861 } 12862 return false; 12863 } 12864 12865 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12866 } 12867 12868 /** 12869 * @return The number of times this view has been attached to a window 12870 */ 12871 protected int getWindowAttachCount() { 12872 return mWindowAttachCount; 12873 } 12874 12875 /** 12876 * Retrieve a unique token identifying the window this view is attached to. 12877 * @return Return the window's token for use in 12878 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 12879 */ 12880 public IBinder getWindowToken() { 12881 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 12882 } 12883 12884 /** 12885 * Retrieve the {@link WindowId} for the window this view is 12886 * currently attached to. 12887 */ 12888 public WindowId getWindowId() { 12889 if (mAttachInfo == null) { 12890 return null; 12891 } 12892 if (mAttachInfo.mWindowId == null) { 12893 try { 12894 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 12895 mAttachInfo.mWindowToken); 12896 mAttachInfo.mWindowId = new WindowId( 12897 mAttachInfo.mIWindowId); 12898 } catch (RemoteException e) { 12899 } 12900 } 12901 return mAttachInfo.mWindowId; 12902 } 12903 12904 /** 12905 * Retrieve a unique token identifying the top-level "real" window of 12906 * the window that this view is attached to. That is, this is like 12907 * {@link #getWindowToken}, except if the window this view in is a panel 12908 * window (attached to another containing window), then the token of 12909 * the containing window is returned instead. 12910 * 12911 * @return Returns the associated window token, either 12912 * {@link #getWindowToken()} or the containing window's token. 12913 */ 12914 public IBinder getApplicationWindowToken() { 12915 AttachInfo ai = mAttachInfo; 12916 if (ai != null) { 12917 IBinder appWindowToken = ai.mPanelParentWindowToken; 12918 if (appWindowToken == null) { 12919 appWindowToken = ai.mWindowToken; 12920 } 12921 return appWindowToken; 12922 } 12923 return null; 12924 } 12925 12926 /** 12927 * Gets the logical display to which the view's window has been attached. 12928 * 12929 * @return The logical display, or null if the view is not currently attached to a window. 12930 */ 12931 public Display getDisplay() { 12932 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 12933 } 12934 12935 /** 12936 * Retrieve private session object this view hierarchy is using to 12937 * communicate with the window manager. 12938 * @return the session object to communicate with the window manager 12939 */ 12940 /*package*/ IWindowSession getWindowSession() { 12941 return mAttachInfo != null ? mAttachInfo.mSession : null; 12942 } 12943 12944 /** 12945 * @param info the {@link android.view.View.AttachInfo} to associated with 12946 * this view 12947 */ 12948 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 12949 //System.out.println("Attached! " + this); 12950 mAttachInfo = info; 12951 if (mOverlay != null) { 12952 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 12953 } 12954 mWindowAttachCount++; 12955 // We will need to evaluate the drawable state at least once. 12956 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 12957 if (mFloatingTreeObserver != null) { 12958 info.mTreeObserver.merge(mFloatingTreeObserver); 12959 mFloatingTreeObserver = null; 12960 } 12961 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 12962 mAttachInfo.mScrollContainers.add(this); 12963 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 12964 } 12965 performCollectViewAttributes(mAttachInfo, visibility); 12966 onAttachedToWindow(); 12967 12968 ListenerInfo li = mListenerInfo; 12969 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12970 li != null ? li.mOnAttachStateChangeListeners : null; 12971 if (listeners != null && listeners.size() > 0) { 12972 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12973 // perform the dispatching. The iterator is a safe guard against listeners that 12974 // could mutate the list by calling the various add/remove methods. This prevents 12975 // the array from being modified while we iterate it. 12976 for (OnAttachStateChangeListener listener : listeners) { 12977 listener.onViewAttachedToWindow(this); 12978 } 12979 } 12980 12981 int vis = info.mWindowVisibility; 12982 if (vis != GONE) { 12983 onWindowVisibilityChanged(vis); 12984 } 12985 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 12986 // If nobody has evaluated the drawable state yet, then do it now. 12987 refreshDrawableState(); 12988 } 12989 needGlobalAttributesUpdate(false); 12990 } 12991 12992 void dispatchDetachedFromWindow() { 12993 AttachInfo info = mAttachInfo; 12994 if (info != null) { 12995 int vis = info.mWindowVisibility; 12996 if (vis != GONE) { 12997 onWindowVisibilityChanged(GONE); 12998 } 12999 } 13000 13001 onDetachedFromWindow(); 13002 onDetachedFromWindowInternal(); 13003 13004 ListenerInfo li = mListenerInfo; 13005 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13006 li != null ? li.mOnAttachStateChangeListeners : null; 13007 if (listeners != null && listeners.size() > 0) { 13008 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13009 // perform the dispatching. The iterator is a safe guard against listeners that 13010 // could mutate the list by calling the various add/remove methods. This prevents 13011 // the array from being modified while we iterate it. 13012 for (OnAttachStateChangeListener listener : listeners) { 13013 listener.onViewDetachedFromWindow(this); 13014 } 13015 } 13016 13017 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13018 mAttachInfo.mScrollContainers.remove(this); 13019 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13020 } 13021 13022 mAttachInfo = null; 13023 if (mOverlay != null) { 13024 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13025 } 13026 } 13027 13028 /** 13029 * Cancel any deferred high-level input events that were previously posted to the event queue. 13030 * 13031 * <p>Many views post high-level events such as click handlers to the event queue 13032 * to run deferred in order to preserve a desired user experience - clearing visible 13033 * pressed states before executing, etc. This method will abort any events of this nature 13034 * that are currently in flight.</p> 13035 * 13036 * <p>Custom views that generate their own high-level deferred input events should override 13037 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13038 * 13039 * <p>This will also cancel pending input events for any child views.</p> 13040 * 13041 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13042 * This will not impact newer events posted after this call that may occur as a result of 13043 * lower-level input events still waiting in the queue. If you are trying to prevent 13044 * double-submitted events for the duration of some sort of asynchronous transaction 13045 * you should also take other steps to protect against unexpected double inputs e.g. calling 13046 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13047 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13048 */ 13049 public final void cancelPendingInputEvents() { 13050 dispatchCancelPendingInputEvents(); 13051 } 13052 13053 /** 13054 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13055 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13056 */ 13057 void dispatchCancelPendingInputEvents() { 13058 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13059 onCancelPendingInputEvents(); 13060 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13061 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13062 " did not call through to super.onCancelPendingInputEvents()"); 13063 } 13064 } 13065 13066 /** 13067 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13068 * a parent view. 13069 * 13070 * <p>This method is responsible for removing any pending high-level input events that were 13071 * posted to the event queue to run later. Custom view classes that post their own deferred 13072 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13073 * {@link android.os.Handler} should override this method, call 13074 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13075 * </p> 13076 */ 13077 public void onCancelPendingInputEvents() { 13078 removePerformClickCallback(); 13079 cancelLongPress(); 13080 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13081 } 13082 13083 /** 13084 * Store this view hierarchy's frozen state into the given container. 13085 * 13086 * @param container The SparseArray in which to save the view's state. 13087 * 13088 * @see #restoreHierarchyState(android.util.SparseArray) 13089 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13090 * @see #onSaveInstanceState() 13091 */ 13092 public void saveHierarchyState(SparseArray<Parcelable> container) { 13093 dispatchSaveInstanceState(container); 13094 } 13095 13096 /** 13097 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13098 * this view and its children. May be overridden to modify how freezing happens to a 13099 * view's children; for example, some views may want to not store state for their children. 13100 * 13101 * @param container The SparseArray in which to save the view's state. 13102 * 13103 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13104 * @see #saveHierarchyState(android.util.SparseArray) 13105 * @see #onSaveInstanceState() 13106 */ 13107 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13108 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13109 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13110 Parcelable state = onSaveInstanceState(); 13111 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13112 throw new IllegalStateException( 13113 "Derived class did not call super.onSaveInstanceState()"); 13114 } 13115 if (state != null) { 13116 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13117 // + ": " + state); 13118 container.put(mID, state); 13119 } 13120 } 13121 } 13122 13123 /** 13124 * Hook allowing a view to generate a representation of its internal state 13125 * that can later be used to create a new instance with that same state. 13126 * This state should only contain information that is not persistent or can 13127 * not be reconstructed later. For example, you will never store your 13128 * current position on screen because that will be computed again when a 13129 * new instance of the view is placed in its view hierarchy. 13130 * <p> 13131 * Some examples of things you may store here: the current cursor position 13132 * in a text view (but usually not the text itself since that is stored in a 13133 * content provider or other persistent storage), the currently selected 13134 * item in a list view. 13135 * 13136 * @return Returns a Parcelable object containing the view's current dynamic 13137 * state, or null if there is nothing interesting to save. The 13138 * default implementation returns null. 13139 * @see #onRestoreInstanceState(android.os.Parcelable) 13140 * @see #saveHierarchyState(android.util.SparseArray) 13141 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13142 * @see #setSaveEnabled(boolean) 13143 */ 13144 protected Parcelable onSaveInstanceState() { 13145 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13146 return BaseSavedState.EMPTY_STATE; 13147 } 13148 13149 /** 13150 * Restore this view hierarchy's frozen state from the given container. 13151 * 13152 * @param container The SparseArray which holds previously frozen states. 13153 * 13154 * @see #saveHierarchyState(android.util.SparseArray) 13155 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13156 * @see #onRestoreInstanceState(android.os.Parcelable) 13157 */ 13158 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13159 dispatchRestoreInstanceState(container); 13160 } 13161 13162 /** 13163 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13164 * state for this view and its children. May be overridden to modify how restoring 13165 * happens to a view's children; for example, some views may want to not store state 13166 * for their children. 13167 * 13168 * @param container The SparseArray which holds previously saved state. 13169 * 13170 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13171 * @see #restoreHierarchyState(android.util.SparseArray) 13172 * @see #onRestoreInstanceState(android.os.Parcelable) 13173 */ 13174 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13175 if (mID != NO_ID) { 13176 Parcelable state = container.get(mID); 13177 if (state != null) { 13178 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13179 // + ": " + state); 13180 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13181 onRestoreInstanceState(state); 13182 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13183 throw new IllegalStateException( 13184 "Derived class did not call super.onRestoreInstanceState()"); 13185 } 13186 } 13187 } 13188 } 13189 13190 /** 13191 * Hook allowing a view to re-apply a representation of its internal state that had previously 13192 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13193 * null state. 13194 * 13195 * @param state The frozen state that had previously been returned by 13196 * {@link #onSaveInstanceState}. 13197 * 13198 * @see #onSaveInstanceState() 13199 * @see #restoreHierarchyState(android.util.SparseArray) 13200 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13201 */ 13202 protected void onRestoreInstanceState(Parcelable state) { 13203 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13204 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13205 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13206 + "received " + state.getClass().toString() + " instead. This usually happens " 13207 + "when two views of different type have the same id in the same hierarchy. " 13208 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13209 + "other views do not use the same id."); 13210 } 13211 } 13212 13213 /** 13214 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13215 * 13216 * @return the drawing start time in milliseconds 13217 */ 13218 public long getDrawingTime() { 13219 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13220 } 13221 13222 /** 13223 * <p>Enables or disables the duplication of the parent's state into this view. When 13224 * duplication is enabled, this view gets its drawable state from its parent rather 13225 * than from its own internal properties.</p> 13226 * 13227 * <p>Note: in the current implementation, setting this property to true after the 13228 * view was added to a ViewGroup might have no effect at all. This property should 13229 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13230 * 13231 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13232 * property is enabled, an exception will be thrown.</p> 13233 * 13234 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13235 * parent, these states should not be affected by this method.</p> 13236 * 13237 * @param enabled True to enable duplication of the parent's drawable state, false 13238 * to disable it. 13239 * 13240 * @see #getDrawableState() 13241 * @see #isDuplicateParentStateEnabled() 13242 */ 13243 public void setDuplicateParentStateEnabled(boolean enabled) { 13244 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13245 } 13246 13247 /** 13248 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13249 * 13250 * @return True if this view's drawable state is duplicated from the parent, 13251 * false otherwise 13252 * 13253 * @see #getDrawableState() 13254 * @see #setDuplicateParentStateEnabled(boolean) 13255 */ 13256 public boolean isDuplicateParentStateEnabled() { 13257 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13258 } 13259 13260 /** 13261 * <p>Specifies the type of layer backing this view. The layer can be 13262 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13263 * {@link #LAYER_TYPE_HARDWARE}.</p> 13264 * 13265 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13266 * instance that controls how the layer is composed on screen. The following 13267 * properties of the paint are taken into account when composing the layer:</p> 13268 * <ul> 13269 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13270 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13271 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13272 * </ul> 13273 * 13274 * <p>If this view has an alpha value set to < 1.0 by calling 13275 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13276 * by this view's alpha value.</p> 13277 * 13278 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13279 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13280 * for more information on when and how to use layers.</p> 13281 * 13282 * @param layerType The type of layer to use with this view, must be one of 13283 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13284 * {@link #LAYER_TYPE_HARDWARE} 13285 * @param paint The paint used to compose the layer. This argument is optional 13286 * and can be null. It is ignored when the layer type is 13287 * {@link #LAYER_TYPE_NONE} 13288 * 13289 * @see #getLayerType() 13290 * @see #LAYER_TYPE_NONE 13291 * @see #LAYER_TYPE_SOFTWARE 13292 * @see #LAYER_TYPE_HARDWARE 13293 * @see #setAlpha(float) 13294 * 13295 * @attr ref android.R.styleable#View_layerType 13296 */ 13297 public void setLayerType(int layerType, Paint paint) { 13298 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13299 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13300 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13301 } 13302 13303 if (layerType == mLayerType) { 13304 setLayerPaint(paint); 13305 return; 13306 } 13307 13308 // Destroy any previous software drawing cache if needed 13309 switch (mLayerType) { 13310 case LAYER_TYPE_HARDWARE: 13311 destroyLayer(false); 13312 // fall through - non-accelerated views may use software layer mechanism instead 13313 case LAYER_TYPE_SOFTWARE: 13314 destroyDrawingCache(); 13315 break; 13316 default: 13317 break; 13318 } 13319 13320 mLayerType = layerType; 13321 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 13322 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13323 mLocalDirtyRect = layerDisabled ? null : new Rect(); 13324 13325 invalidateParentCaches(); 13326 invalidate(true); 13327 } 13328 13329 /** 13330 * Updates the {@link Paint} object used with the current layer (used only if the current 13331 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13332 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13333 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13334 * ensure that the view gets redrawn immediately. 13335 * 13336 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13337 * instance that controls how the layer is composed on screen. The following 13338 * properties of the paint are taken into account when composing the layer:</p> 13339 * <ul> 13340 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13341 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13342 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13343 * </ul> 13344 * 13345 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13346 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13347 * 13348 * @param paint The paint used to compose the layer. This argument is optional 13349 * and can be null. It is ignored when the layer type is 13350 * {@link #LAYER_TYPE_NONE} 13351 * 13352 * @see #setLayerType(int, android.graphics.Paint) 13353 */ 13354 public void setLayerPaint(Paint paint) { 13355 int layerType = getLayerType(); 13356 if (layerType != LAYER_TYPE_NONE) { 13357 mLayerPaint = paint == null ? new Paint() : paint; 13358 if (layerType == LAYER_TYPE_HARDWARE) { 13359 HardwareLayer layer = getHardwareLayer(); 13360 if (layer != null) { 13361 layer.setLayerPaint(mLayerPaint); 13362 } 13363 invalidateViewProperty(false, false); 13364 } else { 13365 invalidate(); 13366 } 13367 } 13368 } 13369 13370 /** 13371 * Indicates whether this view has a static layer. A view with layer type 13372 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13373 * dynamic. 13374 */ 13375 boolean hasStaticLayer() { 13376 return true; 13377 } 13378 13379 /** 13380 * Indicates what type of layer is currently associated with this view. By default 13381 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13382 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13383 * for more information on the different types of layers. 13384 * 13385 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13386 * {@link #LAYER_TYPE_HARDWARE} 13387 * 13388 * @see #setLayerType(int, android.graphics.Paint) 13389 * @see #buildLayer() 13390 * @see #LAYER_TYPE_NONE 13391 * @see #LAYER_TYPE_SOFTWARE 13392 * @see #LAYER_TYPE_HARDWARE 13393 */ 13394 public int getLayerType() { 13395 return mLayerType; 13396 } 13397 13398 /** 13399 * Forces this view's layer to be created and this view to be rendered 13400 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13401 * invoking this method will have no effect. 13402 * 13403 * This method can for instance be used to render a view into its layer before 13404 * starting an animation. If this view is complex, rendering into the layer 13405 * before starting the animation will avoid skipping frames. 13406 * 13407 * @throws IllegalStateException If this view is not attached to a window 13408 * 13409 * @see #setLayerType(int, android.graphics.Paint) 13410 */ 13411 public void buildLayer() { 13412 if (mLayerType == LAYER_TYPE_NONE) return; 13413 13414 final AttachInfo attachInfo = mAttachInfo; 13415 if (attachInfo == null) { 13416 throw new IllegalStateException("This view must be attached to a window first"); 13417 } 13418 13419 switch (mLayerType) { 13420 case LAYER_TYPE_HARDWARE: 13421 getHardwareLayer(); 13422 // TODO: We need a better way to handle this case 13423 // If views have registered pre-draw listeners they need 13424 // to be notified before we build the layer. Those listeners 13425 // may however rely on other events to happen first so we 13426 // cannot just invoke them here until they don't cancel the 13427 // current frame 13428 if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) { 13429 attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates(); 13430 } 13431 break; 13432 case LAYER_TYPE_SOFTWARE: 13433 buildDrawingCache(true); 13434 break; 13435 } 13436 } 13437 13438 /** 13439 * <p>Returns a hardware layer that can be used to draw this view again 13440 * without executing its draw method.</p> 13441 * 13442 * @return A HardwareLayer ready to render, or null if an error occurred. 13443 */ 13444 HardwareLayer getHardwareLayer() { 13445 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 13446 !mAttachInfo.mHardwareRenderer.isEnabled()) { 13447 return null; 13448 } 13449 13450 final int width = mRight - mLeft; 13451 final int height = mBottom - mTop; 13452 13453 if (width == 0 || height == 0) { 13454 return null; 13455 } 13456 13457 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 13458 if (mHardwareLayer == null) { 13459 mHardwareLayer = mAttachInfo.mHardwareRenderer.createDisplayListLayer( 13460 width, height); 13461 mLocalDirtyRect.set(0, 0, width, height); 13462 } else if (mHardwareLayer.isValid()) { 13463 // This should not be necessary but applications that change 13464 // the parameters of their background drawable without calling 13465 // this.setBackground(Drawable) can leave the view in a bad state 13466 // (for instance isOpaque() returns true, but the background is 13467 // not opaque.) 13468 computeOpaqueFlags(); 13469 13470 if (mHardwareLayer.prepare(width, height, isOpaque())) { 13471 mLocalDirtyRect.set(0, 0, width, height); 13472 } 13473 } 13474 13475 // The layer is not valid if the underlying GPU resources cannot be allocated 13476 mHardwareLayer.flushChanges(); 13477 if (!mHardwareLayer.isValid()) { 13478 return null; 13479 } 13480 13481 mHardwareLayer.setLayerPaint(mLayerPaint); 13482 RenderNode displayList = mHardwareLayer.startRecording(); 13483 updateDisplayListIfDirty(displayList, true); 13484 mHardwareLayer.endRecording(mLocalDirtyRect); 13485 mLocalDirtyRect.setEmpty(); 13486 } 13487 13488 return mHardwareLayer; 13489 } 13490 13491 /** 13492 * Destroys this View's hardware layer if possible. 13493 * 13494 * @return True if the layer was destroyed, false otherwise. 13495 * 13496 * @see #setLayerType(int, android.graphics.Paint) 13497 * @see #LAYER_TYPE_HARDWARE 13498 */ 13499 boolean destroyLayer(boolean valid) { 13500 if (mHardwareLayer != null) { 13501 mHardwareLayer.destroy(); 13502 mHardwareLayer = null; 13503 13504 invalidate(true); 13505 invalidateParentCaches(); 13506 return true; 13507 } 13508 return false; 13509 } 13510 13511 /** 13512 * Destroys all hardware rendering resources. This method is invoked 13513 * when the system needs to reclaim resources. Upon execution of this 13514 * method, you should free any OpenGL resources created by the view. 13515 * 13516 * Note: you <strong>must</strong> call 13517 * <code>super.destroyHardwareResources()</code> when overriding 13518 * this method. 13519 * 13520 * @hide 13521 */ 13522 protected void destroyHardwareResources() { 13523 resetDisplayList(); 13524 destroyLayer(true); 13525 } 13526 13527 /** 13528 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13529 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13530 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13531 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13532 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13533 * null.</p> 13534 * 13535 * <p>Enabling the drawing cache is similar to 13536 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13537 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13538 * drawing cache has no effect on rendering because the system uses a different mechanism 13539 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13540 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13541 * for information on how to enable software and hardware layers.</p> 13542 * 13543 * <p>This API can be used to manually generate 13544 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13545 * {@link #getDrawingCache()}.</p> 13546 * 13547 * @param enabled true to enable the drawing cache, false otherwise 13548 * 13549 * @see #isDrawingCacheEnabled() 13550 * @see #getDrawingCache() 13551 * @see #buildDrawingCache() 13552 * @see #setLayerType(int, android.graphics.Paint) 13553 */ 13554 public void setDrawingCacheEnabled(boolean enabled) { 13555 mCachingFailed = false; 13556 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13557 } 13558 13559 /** 13560 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13561 * 13562 * @return true if the drawing cache is enabled 13563 * 13564 * @see #setDrawingCacheEnabled(boolean) 13565 * @see #getDrawingCache() 13566 */ 13567 @ViewDebug.ExportedProperty(category = "drawing") 13568 public boolean isDrawingCacheEnabled() { 13569 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13570 } 13571 13572 /** 13573 * Debugging utility which recursively outputs the dirty state of a view and its 13574 * descendants. 13575 * 13576 * @hide 13577 */ 13578 @SuppressWarnings({"UnusedDeclaration"}) 13579 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13580 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13581 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13582 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13583 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13584 if (clear) { 13585 mPrivateFlags &= clearMask; 13586 } 13587 if (this instanceof ViewGroup) { 13588 ViewGroup parent = (ViewGroup) this; 13589 final int count = parent.getChildCount(); 13590 for (int i = 0; i < count; i++) { 13591 final View child = parent.getChildAt(i); 13592 child.outputDirtyFlags(indent + " ", clear, clearMask); 13593 } 13594 } 13595 } 13596 13597 /** 13598 * This method is used by ViewGroup to cause its children to restore or recreate their 13599 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13600 * to recreate its own display list, which would happen if it went through the normal 13601 * draw/dispatchDraw mechanisms. 13602 * 13603 * @hide 13604 */ 13605 protected void dispatchGetDisplayList() {} 13606 13607 /** 13608 * A view that is not attached or hardware accelerated cannot create a display list. 13609 * This method checks these conditions and returns the appropriate result. 13610 * 13611 * @return true if view has the ability to create a display list, false otherwise. 13612 * 13613 * @hide 13614 */ 13615 public boolean canHaveDisplayList() { 13616 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13617 } 13618 13619 /** 13620 * Returns a DisplayList. If the incoming displayList is null, one will be created. 13621 * Otherwise, the same display list will be returned (after having been rendered into 13622 * along the way, depending on the invalidation state of the view). 13623 * 13624 * @param renderNode The previous version of this displayList, could be null. 13625 * @param isLayer Whether the requester of the display list is a layer. If so, 13626 * the view will avoid creating a layer inside the resulting display list. 13627 * @return A new or reused DisplayList object. 13628 */ 13629 private void updateDisplayListIfDirty(@NonNull RenderNode renderNode, boolean isLayer) { 13630 if (renderNode == null) { 13631 throw new IllegalArgumentException("RenderNode must not be null"); 13632 } 13633 if (!canHaveDisplayList()) { 13634 // can't populate RenderNode, don't try 13635 return; 13636 } 13637 13638 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13639 || !renderNode.isValid() 13640 || (!isLayer && mRecreateDisplayList)) { 13641 // Don't need to recreate the display list, just need to tell our 13642 // children to restore/recreate theirs 13643 if (renderNode.isValid() 13644 && !isLayer 13645 && !mRecreateDisplayList) { 13646 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13647 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13648 dispatchGetDisplayList(); 13649 13650 return; // no work needed 13651 } 13652 13653 if (!isLayer) { 13654 // If we got here, we're recreating it. Mark it as such to ensure that 13655 // we copy in child display lists into ours in drawChild() 13656 mRecreateDisplayList = true; 13657 } 13658 13659 boolean caching = false; 13660 int width = mRight - mLeft; 13661 int height = mBottom - mTop; 13662 int layerType = getLayerType(); 13663 13664 final HardwareCanvas canvas = renderNode.start(width, height); 13665 13666 try { 13667 if (!isLayer && layerType != LAYER_TYPE_NONE) { 13668 if (layerType == LAYER_TYPE_HARDWARE) { 13669 final HardwareLayer layer = getHardwareLayer(); 13670 if (layer != null && layer.isValid()) { 13671 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13672 } else { 13673 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 13674 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 13675 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13676 } 13677 caching = true; 13678 } else { 13679 buildDrawingCache(true); 13680 Bitmap cache = getDrawingCache(true); 13681 if (cache != null) { 13682 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13683 caching = true; 13684 } 13685 } 13686 } else { 13687 13688 computeScroll(); 13689 13690 canvas.translate(-mScrollX, -mScrollY); 13691 if (!isLayer) { 13692 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13693 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13694 } 13695 13696 // Fast path for layouts with no backgrounds 13697 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13698 dispatchDraw(canvas); 13699 if (mOverlay != null && !mOverlay.isEmpty()) { 13700 mOverlay.getOverlayView().draw(canvas); 13701 } 13702 } else { 13703 draw(canvas); 13704 } 13705 } 13706 } finally { 13707 renderNode.end(canvas); 13708 renderNode.setCaching(caching); 13709 if (isLayer) { 13710 renderNode.setLeftTopRightBottom(0, 0, width, height); 13711 } else { 13712 setDisplayListProperties(renderNode); 13713 } 13714 } 13715 } else if (!isLayer) { 13716 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13717 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13718 } 13719 } 13720 13721 /** 13722 * Returns a RenderNode with View draw content recorded, which can be 13723 * used to draw this view again without executing its draw method. 13724 * 13725 * @return A RenderNode ready to replay, or null if caching is not enabled. 13726 * 13727 * @hide 13728 */ 13729 public RenderNode getDisplayList() { 13730 updateDisplayListIfDirty(mRenderNode, false); 13731 return mRenderNode; 13732 } 13733 13734 private void resetDisplayList() { 13735 if (mRenderNode.isValid()) { 13736 mRenderNode.destroyDisplayListData(); 13737 } 13738 13739 if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) { 13740 mBackgroundDisplayList.destroyDisplayListData(); 13741 } 13742 } 13743 13744 /** 13745 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13746 * 13747 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13748 * 13749 * @see #getDrawingCache(boolean) 13750 */ 13751 public Bitmap getDrawingCache() { 13752 return getDrawingCache(false); 13753 } 13754 13755 /** 13756 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13757 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13758 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13759 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13760 * request the drawing cache by calling this method and draw it on screen if the 13761 * returned bitmap is not null.</p> 13762 * 13763 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13764 * this method will create a bitmap of the same size as this view. Because this bitmap 13765 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13766 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13767 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13768 * size than the view. This implies that your application must be able to handle this 13769 * size.</p> 13770 * 13771 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13772 * the current density of the screen when the application is in compatibility 13773 * mode. 13774 * 13775 * @return A bitmap representing this view or null if cache is disabled. 13776 * 13777 * @see #setDrawingCacheEnabled(boolean) 13778 * @see #isDrawingCacheEnabled() 13779 * @see #buildDrawingCache(boolean) 13780 * @see #destroyDrawingCache() 13781 */ 13782 public Bitmap getDrawingCache(boolean autoScale) { 13783 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13784 return null; 13785 } 13786 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13787 buildDrawingCache(autoScale); 13788 } 13789 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13790 } 13791 13792 /** 13793 * <p>Frees the resources used by the drawing cache. If you call 13794 * {@link #buildDrawingCache()} manually without calling 13795 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13796 * should cleanup the cache with this method afterwards.</p> 13797 * 13798 * @see #setDrawingCacheEnabled(boolean) 13799 * @see #buildDrawingCache() 13800 * @see #getDrawingCache() 13801 */ 13802 public void destroyDrawingCache() { 13803 if (mDrawingCache != null) { 13804 mDrawingCache.recycle(); 13805 mDrawingCache = null; 13806 } 13807 if (mUnscaledDrawingCache != null) { 13808 mUnscaledDrawingCache.recycle(); 13809 mUnscaledDrawingCache = null; 13810 } 13811 } 13812 13813 /** 13814 * Setting a solid background color for the drawing cache's bitmaps will improve 13815 * performance and memory usage. Note, though that this should only be used if this 13816 * view will always be drawn on top of a solid color. 13817 * 13818 * @param color The background color to use for the drawing cache's bitmap 13819 * 13820 * @see #setDrawingCacheEnabled(boolean) 13821 * @see #buildDrawingCache() 13822 * @see #getDrawingCache() 13823 */ 13824 public void setDrawingCacheBackgroundColor(int color) { 13825 if (color != mDrawingCacheBackgroundColor) { 13826 mDrawingCacheBackgroundColor = color; 13827 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13828 } 13829 } 13830 13831 /** 13832 * @see #setDrawingCacheBackgroundColor(int) 13833 * 13834 * @return The background color to used for the drawing cache's bitmap 13835 */ 13836 public int getDrawingCacheBackgroundColor() { 13837 return mDrawingCacheBackgroundColor; 13838 } 13839 13840 /** 13841 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13842 * 13843 * @see #buildDrawingCache(boolean) 13844 */ 13845 public void buildDrawingCache() { 13846 buildDrawingCache(false); 13847 } 13848 13849 /** 13850 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13851 * 13852 * <p>If you call {@link #buildDrawingCache()} manually without calling 13853 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13854 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13855 * 13856 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13857 * this method will create a bitmap of the same size as this view. Because this bitmap 13858 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13859 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13860 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13861 * size than the view. This implies that your application must be able to handle this 13862 * size.</p> 13863 * 13864 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13865 * you do not need the drawing cache bitmap, calling this method will increase memory 13866 * usage and cause the view to be rendered in software once, thus negatively impacting 13867 * performance.</p> 13868 * 13869 * @see #getDrawingCache() 13870 * @see #destroyDrawingCache() 13871 */ 13872 public void buildDrawingCache(boolean autoScale) { 13873 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13874 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13875 mCachingFailed = false; 13876 13877 int width = mRight - mLeft; 13878 int height = mBottom - mTop; 13879 13880 final AttachInfo attachInfo = mAttachInfo; 13881 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13882 13883 if (autoScale && scalingRequired) { 13884 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13885 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13886 } 13887 13888 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13889 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13890 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13891 13892 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13893 final long drawingCacheSize = 13894 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13895 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13896 if (width > 0 && height > 0) { 13897 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13898 + projectedBitmapSize + " bytes, only " 13899 + drawingCacheSize + " available"); 13900 } 13901 destroyDrawingCache(); 13902 mCachingFailed = true; 13903 return; 13904 } 13905 13906 boolean clear = true; 13907 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13908 13909 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13910 Bitmap.Config quality; 13911 if (!opaque) { 13912 // Never pick ARGB_4444 because it looks awful 13913 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13914 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13915 case DRAWING_CACHE_QUALITY_AUTO: 13916 case DRAWING_CACHE_QUALITY_LOW: 13917 case DRAWING_CACHE_QUALITY_HIGH: 13918 default: 13919 quality = Bitmap.Config.ARGB_8888; 13920 break; 13921 } 13922 } else { 13923 // Optimization for translucent windows 13924 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13925 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13926 } 13927 13928 // Try to cleanup memory 13929 if (bitmap != null) bitmap.recycle(); 13930 13931 try { 13932 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13933 width, height, quality); 13934 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 13935 if (autoScale) { 13936 mDrawingCache = bitmap; 13937 } else { 13938 mUnscaledDrawingCache = bitmap; 13939 } 13940 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 13941 } catch (OutOfMemoryError e) { 13942 // If there is not enough memory to create the bitmap cache, just 13943 // ignore the issue as bitmap caches are not required to draw the 13944 // view hierarchy 13945 if (autoScale) { 13946 mDrawingCache = null; 13947 } else { 13948 mUnscaledDrawingCache = null; 13949 } 13950 mCachingFailed = true; 13951 return; 13952 } 13953 13954 clear = drawingCacheBackgroundColor != 0; 13955 } 13956 13957 Canvas canvas; 13958 if (attachInfo != null) { 13959 canvas = attachInfo.mCanvas; 13960 if (canvas == null) { 13961 canvas = new Canvas(); 13962 } 13963 canvas.setBitmap(bitmap); 13964 // Temporarily clobber the cached Canvas in case one of our children 13965 // is also using a drawing cache. Without this, the children would 13966 // steal the canvas by attaching their own bitmap to it and bad, bad 13967 // thing would happen (invisible views, corrupted drawings, etc.) 13968 attachInfo.mCanvas = null; 13969 } else { 13970 // This case should hopefully never or seldom happen 13971 canvas = new Canvas(bitmap); 13972 } 13973 13974 if (clear) { 13975 bitmap.eraseColor(drawingCacheBackgroundColor); 13976 } 13977 13978 computeScroll(); 13979 final int restoreCount = canvas.save(); 13980 13981 if (autoScale && scalingRequired) { 13982 final float scale = attachInfo.mApplicationScale; 13983 canvas.scale(scale, scale); 13984 } 13985 13986 canvas.translate(-mScrollX, -mScrollY); 13987 13988 mPrivateFlags |= PFLAG_DRAWN; 13989 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 13990 mLayerType != LAYER_TYPE_NONE) { 13991 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 13992 } 13993 13994 // Fast path for layouts with no backgrounds 13995 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13996 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13997 dispatchDraw(canvas); 13998 if (mOverlay != null && !mOverlay.isEmpty()) { 13999 mOverlay.getOverlayView().draw(canvas); 14000 } 14001 } else { 14002 draw(canvas); 14003 } 14004 14005 canvas.restoreToCount(restoreCount); 14006 canvas.setBitmap(null); 14007 14008 if (attachInfo != null) { 14009 // Restore the cached Canvas for our siblings 14010 attachInfo.mCanvas = canvas; 14011 } 14012 } 14013 } 14014 14015 /** 14016 * Create a snapshot of the view into a bitmap. We should probably make 14017 * some form of this public, but should think about the API. 14018 */ 14019 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14020 int width = mRight - mLeft; 14021 int height = mBottom - mTop; 14022 14023 final AttachInfo attachInfo = mAttachInfo; 14024 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14025 width = (int) ((width * scale) + 0.5f); 14026 height = (int) ((height * scale) + 0.5f); 14027 14028 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14029 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14030 if (bitmap == null) { 14031 throw new OutOfMemoryError(); 14032 } 14033 14034 Resources resources = getResources(); 14035 if (resources != null) { 14036 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14037 } 14038 14039 Canvas canvas; 14040 if (attachInfo != null) { 14041 canvas = attachInfo.mCanvas; 14042 if (canvas == null) { 14043 canvas = new Canvas(); 14044 } 14045 canvas.setBitmap(bitmap); 14046 // Temporarily clobber the cached Canvas in case one of our children 14047 // is also using a drawing cache. Without this, the children would 14048 // steal the canvas by attaching their own bitmap to it and bad, bad 14049 // things would happen (invisible views, corrupted drawings, etc.) 14050 attachInfo.mCanvas = null; 14051 } else { 14052 // This case should hopefully never or seldom happen 14053 canvas = new Canvas(bitmap); 14054 } 14055 14056 if ((backgroundColor & 0xff000000) != 0) { 14057 bitmap.eraseColor(backgroundColor); 14058 } 14059 14060 computeScroll(); 14061 final int restoreCount = canvas.save(); 14062 canvas.scale(scale, scale); 14063 canvas.translate(-mScrollX, -mScrollY); 14064 14065 // Temporarily remove the dirty mask 14066 int flags = mPrivateFlags; 14067 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14068 14069 // Fast path for layouts with no backgrounds 14070 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14071 dispatchDraw(canvas); 14072 if (mOverlay != null && !mOverlay.isEmpty()) { 14073 mOverlay.getOverlayView().draw(canvas); 14074 } 14075 } else { 14076 draw(canvas); 14077 } 14078 14079 mPrivateFlags = flags; 14080 14081 canvas.restoreToCount(restoreCount); 14082 canvas.setBitmap(null); 14083 14084 if (attachInfo != null) { 14085 // Restore the cached Canvas for our siblings 14086 attachInfo.mCanvas = canvas; 14087 } 14088 14089 return bitmap; 14090 } 14091 14092 /** 14093 * Indicates whether this View is currently in edit mode. A View is usually 14094 * in edit mode when displayed within a developer tool. For instance, if 14095 * this View is being drawn by a visual user interface builder, this method 14096 * should return true. 14097 * 14098 * Subclasses should check the return value of this method to provide 14099 * different behaviors if their normal behavior might interfere with the 14100 * host environment. For instance: the class spawns a thread in its 14101 * constructor, the drawing code relies on device-specific features, etc. 14102 * 14103 * This method is usually checked in the drawing code of custom widgets. 14104 * 14105 * @return True if this View is in edit mode, false otherwise. 14106 */ 14107 public boolean isInEditMode() { 14108 return false; 14109 } 14110 14111 /** 14112 * If the View draws content inside its padding and enables fading edges, 14113 * it needs to support padding offsets. Padding offsets are added to the 14114 * fading edges to extend the length of the fade so that it covers pixels 14115 * drawn inside the padding. 14116 * 14117 * Subclasses of this class should override this method if they need 14118 * to draw content inside the padding. 14119 * 14120 * @return True if padding offset must be applied, false otherwise. 14121 * 14122 * @see #getLeftPaddingOffset() 14123 * @see #getRightPaddingOffset() 14124 * @see #getTopPaddingOffset() 14125 * @see #getBottomPaddingOffset() 14126 * 14127 * @since CURRENT 14128 */ 14129 protected boolean isPaddingOffsetRequired() { 14130 return false; 14131 } 14132 14133 /** 14134 * Amount by which to extend the left fading region. Called only when 14135 * {@link #isPaddingOffsetRequired()} returns true. 14136 * 14137 * @return The left padding offset in pixels. 14138 * 14139 * @see #isPaddingOffsetRequired() 14140 * 14141 * @since CURRENT 14142 */ 14143 protected int getLeftPaddingOffset() { 14144 return 0; 14145 } 14146 14147 /** 14148 * Amount by which to extend the right fading region. Called only when 14149 * {@link #isPaddingOffsetRequired()} returns true. 14150 * 14151 * @return The right padding offset in pixels. 14152 * 14153 * @see #isPaddingOffsetRequired() 14154 * 14155 * @since CURRENT 14156 */ 14157 protected int getRightPaddingOffset() { 14158 return 0; 14159 } 14160 14161 /** 14162 * Amount by which to extend the top fading region. Called only when 14163 * {@link #isPaddingOffsetRequired()} returns true. 14164 * 14165 * @return The top padding offset in pixels. 14166 * 14167 * @see #isPaddingOffsetRequired() 14168 * 14169 * @since CURRENT 14170 */ 14171 protected int getTopPaddingOffset() { 14172 return 0; 14173 } 14174 14175 /** 14176 * Amount by which to extend the bottom fading region. Called only when 14177 * {@link #isPaddingOffsetRequired()} returns true. 14178 * 14179 * @return The bottom padding offset in pixels. 14180 * 14181 * @see #isPaddingOffsetRequired() 14182 * 14183 * @since CURRENT 14184 */ 14185 protected int getBottomPaddingOffset() { 14186 return 0; 14187 } 14188 14189 /** 14190 * @hide 14191 * @param offsetRequired 14192 */ 14193 protected int getFadeTop(boolean offsetRequired) { 14194 int top = mPaddingTop; 14195 if (offsetRequired) top += getTopPaddingOffset(); 14196 return top; 14197 } 14198 14199 /** 14200 * @hide 14201 * @param offsetRequired 14202 */ 14203 protected int getFadeHeight(boolean offsetRequired) { 14204 int padding = mPaddingTop; 14205 if (offsetRequired) padding += getTopPaddingOffset(); 14206 return mBottom - mTop - mPaddingBottom - padding; 14207 } 14208 14209 /** 14210 * <p>Indicates whether this view is attached to a hardware accelerated 14211 * window or not.</p> 14212 * 14213 * <p>Even if this method returns true, it does not mean that every call 14214 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14215 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14216 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14217 * window is hardware accelerated, 14218 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14219 * return false, and this method will return true.</p> 14220 * 14221 * @return True if the view is attached to a window and the window is 14222 * hardware accelerated; false in any other case. 14223 */ 14224 public boolean isHardwareAccelerated() { 14225 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14226 } 14227 14228 /** 14229 * Sets a rectangular area on this view to which the view will be clipped 14230 * when it is drawn. Setting the value to null will remove the clip bounds 14231 * and the view will draw normally, using its full bounds. 14232 * 14233 * @param clipBounds The rectangular area, in the local coordinates of 14234 * this view, to which future drawing operations will be clipped. 14235 */ 14236 public void setClipBounds(Rect clipBounds) { 14237 if (clipBounds != null) { 14238 if (clipBounds.equals(mClipBounds)) { 14239 return; 14240 } 14241 if (mClipBounds == null) { 14242 invalidate(); 14243 mClipBounds = new Rect(clipBounds); 14244 } else { 14245 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14246 Math.min(mClipBounds.top, clipBounds.top), 14247 Math.max(mClipBounds.right, clipBounds.right), 14248 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14249 mClipBounds.set(clipBounds); 14250 } 14251 } else { 14252 if (mClipBounds != null) { 14253 invalidate(); 14254 mClipBounds = null; 14255 } 14256 } 14257 } 14258 14259 /** 14260 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14261 * 14262 * @return A copy of the current clip bounds if clip bounds are set, 14263 * otherwise null. 14264 */ 14265 public Rect getClipBounds() { 14266 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14267 } 14268 14269 /** 14270 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14271 * case of an active Animation being run on the view. 14272 */ 14273 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14274 Animation a, boolean scalingRequired) { 14275 Transformation invalidationTransform; 14276 final int flags = parent.mGroupFlags; 14277 final boolean initialized = a.isInitialized(); 14278 if (!initialized) { 14279 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14280 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14281 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14282 onAnimationStart(); 14283 } 14284 14285 final Transformation t = parent.getChildTransformation(); 14286 boolean more = a.getTransformation(drawingTime, t, 1f); 14287 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14288 if (parent.mInvalidationTransformation == null) { 14289 parent.mInvalidationTransformation = new Transformation(); 14290 } 14291 invalidationTransform = parent.mInvalidationTransformation; 14292 a.getTransformation(drawingTime, invalidationTransform, 1f); 14293 } else { 14294 invalidationTransform = t; 14295 } 14296 14297 if (more) { 14298 if (!a.willChangeBounds()) { 14299 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14300 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14301 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14302 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14303 // The child need to draw an animation, potentially offscreen, so 14304 // make sure we do not cancel invalidate requests 14305 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14306 parent.invalidate(mLeft, mTop, mRight, mBottom); 14307 } 14308 } else { 14309 if (parent.mInvalidateRegion == null) { 14310 parent.mInvalidateRegion = new RectF(); 14311 } 14312 final RectF region = parent.mInvalidateRegion; 14313 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14314 invalidationTransform); 14315 14316 // The child need to draw an animation, potentially offscreen, so 14317 // make sure we do not cancel invalidate requests 14318 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14319 14320 final int left = mLeft + (int) region.left; 14321 final int top = mTop + (int) region.top; 14322 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14323 top + (int) (region.height() + .5f)); 14324 } 14325 } 14326 return more; 14327 } 14328 14329 /** 14330 * This method is called by getDisplayList() when a display list is recorded for a View. 14331 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14332 */ 14333 void setDisplayListProperties(RenderNode renderNode) { 14334 if (renderNode != null) { 14335 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14336 if (mParent instanceof ViewGroup) { 14337 renderNode.setClipToBounds( 14338 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14339 } 14340 float alpha = 1; 14341 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14342 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14343 ViewGroup parentVG = (ViewGroup) mParent; 14344 final Transformation t = parentVG.getChildTransformation(); 14345 if (parentVG.getChildStaticTransformation(this, t)) { 14346 final int transformType = t.getTransformationType(); 14347 if (transformType != Transformation.TYPE_IDENTITY) { 14348 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14349 alpha = t.getAlpha(); 14350 } 14351 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14352 renderNode.setStaticMatrix(t.getMatrix()); 14353 } 14354 } 14355 } 14356 } 14357 if (mTransformationInfo != null) { 14358 alpha *= getFinalAlpha(); 14359 if (alpha < 1) { 14360 final int multipliedAlpha = (int) (255 * alpha); 14361 if (onSetAlpha(multipliedAlpha)) { 14362 alpha = 1; 14363 } 14364 } 14365 renderNode.setAlpha(alpha); 14366 } else if (alpha < 1) { 14367 renderNode.setAlpha(alpha); 14368 } 14369 } 14370 } 14371 14372 /** 14373 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14374 * This draw() method is an implementation detail and is not intended to be overridden or 14375 * to be called from anywhere else other than ViewGroup.drawChild(). 14376 */ 14377 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14378 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14379 boolean more = false; 14380 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14381 final int flags = parent.mGroupFlags; 14382 14383 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14384 parent.getChildTransformation().clear(); 14385 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14386 } 14387 14388 Transformation transformToApply = null; 14389 boolean concatMatrix = false; 14390 14391 boolean scalingRequired = false; 14392 boolean caching; 14393 int layerType = getLayerType(); 14394 14395 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14396 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14397 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14398 caching = true; 14399 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14400 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14401 } else { 14402 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14403 } 14404 14405 final Animation a = getAnimation(); 14406 if (a != null) { 14407 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14408 concatMatrix = a.willChangeTransformationMatrix(); 14409 if (concatMatrix) { 14410 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14411 } 14412 transformToApply = parent.getChildTransformation(); 14413 } else { 14414 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14415 // No longer animating: clear out old animation matrix 14416 mRenderNode.setAnimationMatrix(null); 14417 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14418 } 14419 if (!useDisplayListProperties && 14420 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14421 final Transformation t = parent.getChildTransformation(); 14422 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14423 if (hasTransform) { 14424 final int transformType = t.getTransformationType(); 14425 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14426 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14427 } 14428 } 14429 } 14430 14431 concatMatrix |= !childHasIdentityMatrix; 14432 14433 // Sets the flag as early as possible to allow draw() implementations 14434 // to call invalidate() successfully when doing animations 14435 mPrivateFlags |= PFLAG_DRAWN; 14436 14437 if (!concatMatrix && 14438 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14439 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14440 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14441 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14442 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14443 return more; 14444 } 14445 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14446 14447 if (hardwareAccelerated) { 14448 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14449 // retain the flag's value temporarily in the mRecreateDisplayList flag 14450 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14451 mPrivateFlags &= ~PFLAG_INVALIDATED; 14452 } 14453 14454 RenderNode displayList = null; 14455 Bitmap cache = null; 14456 boolean hasDisplayList = false; 14457 if (caching) { 14458 if (!hardwareAccelerated) { 14459 if (layerType != LAYER_TYPE_NONE) { 14460 layerType = LAYER_TYPE_SOFTWARE; 14461 buildDrawingCache(true); 14462 } 14463 cache = getDrawingCache(true); 14464 } else { 14465 switch (layerType) { 14466 case LAYER_TYPE_SOFTWARE: 14467 if (useDisplayListProperties) { 14468 hasDisplayList = canHaveDisplayList(); 14469 } else { 14470 buildDrawingCache(true); 14471 cache = getDrawingCache(true); 14472 } 14473 break; 14474 case LAYER_TYPE_HARDWARE: 14475 if (useDisplayListProperties) { 14476 hasDisplayList = canHaveDisplayList(); 14477 } 14478 break; 14479 case LAYER_TYPE_NONE: 14480 // Delay getting the display list until animation-driven alpha values are 14481 // set up and possibly passed on to the view 14482 hasDisplayList = canHaveDisplayList(); 14483 break; 14484 } 14485 } 14486 } 14487 useDisplayListProperties &= hasDisplayList; 14488 if (useDisplayListProperties) { 14489 displayList = getDisplayList(); 14490 if (!displayList.isValid()) { 14491 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14492 // to getDisplayList(), the display list will be marked invalid and we should not 14493 // try to use it again. 14494 displayList = null; 14495 hasDisplayList = false; 14496 useDisplayListProperties = false; 14497 } 14498 } 14499 14500 int sx = 0; 14501 int sy = 0; 14502 if (!hasDisplayList) { 14503 computeScroll(); 14504 sx = mScrollX; 14505 sy = mScrollY; 14506 } 14507 14508 final boolean hasNoCache = cache == null || hasDisplayList; 14509 final boolean offsetForScroll = cache == null && !hasDisplayList && 14510 layerType != LAYER_TYPE_HARDWARE; 14511 14512 int restoreTo = -1; 14513 if (!useDisplayListProperties || transformToApply != null) { 14514 restoreTo = canvas.save(); 14515 } 14516 if (offsetForScroll) { 14517 canvas.translate(mLeft - sx, mTop - sy); 14518 } else { 14519 if (!useDisplayListProperties) { 14520 canvas.translate(mLeft, mTop); 14521 } 14522 if (scalingRequired) { 14523 if (useDisplayListProperties) { 14524 // TODO: Might not need this if we put everything inside the DL 14525 restoreTo = canvas.save(); 14526 } 14527 // mAttachInfo cannot be null, otherwise scalingRequired == false 14528 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14529 canvas.scale(scale, scale); 14530 } 14531 } 14532 14533 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14534 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14535 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14536 if (transformToApply != null || !childHasIdentityMatrix) { 14537 int transX = 0; 14538 int transY = 0; 14539 14540 if (offsetForScroll) { 14541 transX = -sx; 14542 transY = -sy; 14543 } 14544 14545 if (transformToApply != null) { 14546 if (concatMatrix) { 14547 if (useDisplayListProperties) { 14548 displayList.setAnimationMatrix(transformToApply.getMatrix()); 14549 } else { 14550 // Undo the scroll translation, apply the transformation matrix, 14551 // then redo the scroll translate to get the correct result. 14552 canvas.translate(-transX, -transY); 14553 canvas.concat(transformToApply.getMatrix()); 14554 canvas.translate(transX, transY); 14555 } 14556 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14557 } 14558 14559 float transformAlpha = transformToApply.getAlpha(); 14560 if (transformAlpha < 1) { 14561 alpha *= transformAlpha; 14562 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14563 } 14564 } 14565 14566 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14567 canvas.translate(-transX, -transY); 14568 canvas.concat(getMatrix()); 14569 canvas.translate(transX, transY); 14570 } 14571 } 14572 14573 // Deal with alpha if it is or used to be <1 14574 if (alpha < 1 || 14575 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14576 if (alpha < 1) { 14577 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14578 } else { 14579 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14580 } 14581 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14582 if (hasNoCache) { 14583 final int multipliedAlpha = (int) (255 * alpha); 14584 if (!onSetAlpha(multipliedAlpha)) { 14585 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14586 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14587 layerType != LAYER_TYPE_NONE) { 14588 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14589 } 14590 if (useDisplayListProperties) { 14591 displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14592 } else if (layerType == LAYER_TYPE_NONE) { 14593 final int scrollX = hasDisplayList ? 0 : sx; 14594 final int scrollY = hasDisplayList ? 0 : sy; 14595 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14596 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14597 } 14598 } else { 14599 // Alpha is handled by the child directly, clobber the layer's alpha 14600 mPrivateFlags |= PFLAG_ALPHA_SET; 14601 } 14602 } 14603 } 14604 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14605 onSetAlpha(255); 14606 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14607 } 14608 14609 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14610 !useDisplayListProperties && cache == null) { 14611 if (offsetForScroll) { 14612 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14613 } else { 14614 if (!scalingRequired || cache == null) { 14615 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14616 } else { 14617 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14618 } 14619 } 14620 } 14621 14622 if (!useDisplayListProperties && hasDisplayList) { 14623 displayList = getDisplayList(); 14624 if (!displayList.isValid()) { 14625 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14626 // to getDisplayList(), the display list will be marked invalid and we should not 14627 // try to use it again. 14628 displayList = null; 14629 hasDisplayList = false; 14630 } 14631 } 14632 14633 if (hasNoCache) { 14634 boolean layerRendered = false; 14635 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14636 final HardwareLayer layer = getHardwareLayer(); 14637 if (layer != null && layer.isValid()) { 14638 mLayerPaint.setAlpha((int) (alpha * 255)); 14639 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14640 layerRendered = true; 14641 } else { 14642 final int scrollX = hasDisplayList ? 0 : sx; 14643 final int scrollY = hasDisplayList ? 0 : sy; 14644 canvas.saveLayer(scrollX, scrollY, 14645 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14646 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14647 } 14648 } 14649 14650 if (!layerRendered) { 14651 if (!hasDisplayList) { 14652 // Fast path for layouts with no backgrounds 14653 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14654 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14655 dispatchDraw(canvas); 14656 } else { 14657 draw(canvas); 14658 } 14659 } else { 14660 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14661 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14662 } 14663 } 14664 } else if (cache != null) { 14665 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14666 Paint cachePaint; 14667 14668 if (layerType == LAYER_TYPE_NONE) { 14669 cachePaint = parent.mCachePaint; 14670 if (cachePaint == null) { 14671 cachePaint = new Paint(); 14672 cachePaint.setDither(false); 14673 parent.mCachePaint = cachePaint; 14674 } 14675 if (alpha < 1) { 14676 cachePaint.setAlpha((int) (alpha * 255)); 14677 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14678 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14679 cachePaint.setAlpha(255); 14680 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14681 } 14682 } else { 14683 cachePaint = mLayerPaint; 14684 cachePaint.setAlpha((int) (alpha * 255)); 14685 } 14686 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14687 } 14688 14689 if (restoreTo >= 0) { 14690 canvas.restoreToCount(restoreTo); 14691 } 14692 14693 if (a != null && !more) { 14694 if (!hardwareAccelerated && !a.getFillAfter()) { 14695 onSetAlpha(255); 14696 } 14697 parent.finishAnimatingView(this, a); 14698 } 14699 14700 if (more && hardwareAccelerated) { 14701 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14702 // alpha animations should cause the child to recreate its display list 14703 invalidate(true); 14704 } 14705 } 14706 14707 mRecreateDisplayList = false; 14708 14709 return more; 14710 } 14711 14712 /** 14713 * Manually render this view (and all of its children) to the given Canvas. 14714 * The view must have already done a full layout before this function is 14715 * called. When implementing a view, implement 14716 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14717 * If you do need to override this method, call the superclass version. 14718 * 14719 * @param canvas The Canvas to which the View is rendered. 14720 */ 14721 public void draw(Canvas canvas) { 14722 if (mClipBounds != null) { 14723 canvas.clipRect(mClipBounds); 14724 } 14725 final int privateFlags = mPrivateFlags; 14726 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14727 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14728 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14729 14730 /* 14731 * Draw traversal performs several drawing steps which must be executed 14732 * in the appropriate order: 14733 * 14734 * 1. Draw the background 14735 * 2. If necessary, save the canvas' layers to prepare for fading 14736 * 3. Draw view's content 14737 * 4. Draw children 14738 * 5. If necessary, draw the fading edges and restore layers 14739 * 6. Draw decorations (scrollbars for instance) 14740 */ 14741 14742 // Step 1, draw the background, if needed 14743 int saveCount; 14744 14745 if (!dirtyOpaque) { 14746 drawBackground(canvas); 14747 } 14748 14749 // skip step 2 & 5 if possible (common case) 14750 final int viewFlags = mViewFlags; 14751 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14752 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14753 if (!verticalEdges && !horizontalEdges) { 14754 // Step 3, draw the content 14755 if (!dirtyOpaque) onDraw(canvas); 14756 14757 // Step 4, draw the children 14758 dispatchDraw(canvas); 14759 14760 // Step 6, draw decorations (scrollbars) 14761 onDrawScrollBars(canvas); 14762 14763 if (mOverlay != null && !mOverlay.isEmpty()) { 14764 mOverlay.getOverlayView().dispatchDraw(canvas); 14765 } 14766 14767 // we're done... 14768 return; 14769 } 14770 14771 /* 14772 * Here we do the full fledged routine... 14773 * (this is an uncommon case where speed matters less, 14774 * this is why we repeat some of the tests that have been 14775 * done above) 14776 */ 14777 14778 boolean drawTop = false; 14779 boolean drawBottom = false; 14780 boolean drawLeft = false; 14781 boolean drawRight = false; 14782 14783 float topFadeStrength = 0.0f; 14784 float bottomFadeStrength = 0.0f; 14785 float leftFadeStrength = 0.0f; 14786 float rightFadeStrength = 0.0f; 14787 14788 // Step 2, save the canvas' layers 14789 int paddingLeft = mPaddingLeft; 14790 14791 final boolean offsetRequired = isPaddingOffsetRequired(); 14792 if (offsetRequired) { 14793 paddingLeft += getLeftPaddingOffset(); 14794 } 14795 14796 int left = mScrollX + paddingLeft; 14797 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14798 int top = mScrollY + getFadeTop(offsetRequired); 14799 int bottom = top + getFadeHeight(offsetRequired); 14800 14801 if (offsetRequired) { 14802 right += getRightPaddingOffset(); 14803 bottom += getBottomPaddingOffset(); 14804 } 14805 14806 final ScrollabilityCache scrollabilityCache = mScrollCache; 14807 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14808 int length = (int) fadeHeight; 14809 14810 // clip the fade length if top and bottom fades overlap 14811 // overlapping fades produce odd-looking artifacts 14812 if (verticalEdges && (top + length > bottom - length)) { 14813 length = (bottom - top) / 2; 14814 } 14815 14816 // also clip horizontal fades if necessary 14817 if (horizontalEdges && (left + length > right - length)) { 14818 length = (right - left) / 2; 14819 } 14820 14821 if (verticalEdges) { 14822 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14823 drawTop = topFadeStrength * fadeHeight > 1.0f; 14824 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14825 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14826 } 14827 14828 if (horizontalEdges) { 14829 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14830 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14831 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14832 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14833 } 14834 14835 saveCount = canvas.getSaveCount(); 14836 14837 int solidColor = getSolidColor(); 14838 if (solidColor == 0) { 14839 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14840 14841 if (drawTop) { 14842 canvas.saveLayer(left, top, right, top + length, null, flags); 14843 } 14844 14845 if (drawBottom) { 14846 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14847 } 14848 14849 if (drawLeft) { 14850 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14851 } 14852 14853 if (drawRight) { 14854 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14855 } 14856 } else { 14857 scrollabilityCache.setFadeColor(solidColor); 14858 } 14859 14860 // Step 3, draw the content 14861 if (!dirtyOpaque) onDraw(canvas); 14862 14863 // Step 4, draw the children 14864 dispatchDraw(canvas); 14865 14866 // Step 5, draw the fade effect and restore layers 14867 final Paint p = scrollabilityCache.paint; 14868 final Matrix matrix = scrollabilityCache.matrix; 14869 final Shader fade = scrollabilityCache.shader; 14870 14871 if (drawTop) { 14872 matrix.setScale(1, fadeHeight * topFadeStrength); 14873 matrix.postTranslate(left, top); 14874 fade.setLocalMatrix(matrix); 14875 canvas.drawRect(left, top, right, top + length, p); 14876 } 14877 14878 if (drawBottom) { 14879 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14880 matrix.postRotate(180); 14881 matrix.postTranslate(left, bottom); 14882 fade.setLocalMatrix(matrix); 14883 canvas.drawRect(left, bottom - length, right, bottom, p); 14884 } 14885 14886 if (drawLeft) { 14887 matrix.setScale(1, fadeHeight * leftFadeStrength); 14888 matrix.postRotate(-90); 14889 matrix.postTranslate(left, top); 14890 fade.setLocalMatrix(matrix); 14891 canvas.drawRect(left, top, left + length, bottom, p); 14892 } 14893 14894 if (drawRight) { 14895 matrix.setScale(1, fadeHeight * rightFadeStrength); 14896 matrix.postRotate(90); 14897 matrix.postTranslate(right, top); 14898 fade.setLocalMatrix(matrix); 14899 canvas.drawRect(right - length, top, right, bottom, p); 14900 } 14901 14902 canvas.restoreToCount(saveCount); 14903 14904 // Step 6, draw decorations (scrollbars) 14905 onDrawScrollBars(canvas); 14906 14907 if (mOverlay != null && !mOverlay.isEmpty()) { 14908 mOverlay.getOverlayView().dispatchDraw(canvas); 14909 } 14910 } 14911 14912 /** 14913 * Draws the background onto the specified canvas. 14914 * 14915 * @param canvas Canvas on which to draw the background 14916 */ 14917 private void drawBackground(Canvas canvas) { 14918 final Drawable background = mBackground; 14919 if (background == null) { 14920 return; 14921 } 14922 14923 if (mBackgroundSizeChanged) { 14924 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14925 mBackgroundSizeChanged = false; 14926 queryOutlineFromBackgroundIfUndefined(); 14927 } 14928 14929 // Attempt to use a display list if requested. 14930 if (canvas.isHardwareAccelerated() && mAttachInfo != null 14931 && mAttachInfo.mHardwareRenderer != null) { 14932 mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList); 14933 14934 final RenderNode displayList = mBackgroundDisplayList; 14935 if (displayList != null && displayList.isValid()) { 14936 setBackgroundDisplayListProperties(displayList); 14937 ((HardwareCanvas) canvas).drawDisplayList(displayList); 14938 return; 14939 } 14940 } 14941 14942 final int scrollX = mScrollX; 14943 final int scrollY = mScrollY; 14944 if ((scrollX | scrollY) == 0) { 14945 background.draw(canvas); 14946 } else { 14947 canvas.translate(scrollX, scrollY); 14948 background.draw(canvas); 14949 canvas.translate(-scrollX, -scrollY); 14950 } 14951 } 14952 14953 /** 14954 * Set up background drawable display list properties. 14955 * 14956 * @param displayList Valid display list for the background drawable 14957 */ 14958 private void setBackgroundDisplayListProperties(RenderNode displayList) { 14959 displayList.setTranslationX(mScrollX); 14960 displayList.setTranslationY(mScrollY); 14961 } 14962 14963 /** 14964 * Creates a new display list or updates the existing display list for the 14965 * specified Drawable. 14966 * 14967 * @param drawable Drawable for which to create a display list 14968 * @param displayList Existing display list, or {@code null} 14969 * @return A valid display list for the specified drawable 14970 */ 14971 private RenderNode getDrawableDisplayList(Drawable drawable, RenderNode displayList) { 14972 if (displayList == null) { 14973 displayList = RenderNode.create(drawable.getClass().getName()); 14974 } 14975 14976 final Rect bounds = drawable.getBounds(); 14977 final int width = bounds.width(); 14978 final int height = bounds.height(); 14979 final HardwareCanvas canvas = displayList.start(width, height); 14980 try { 14981 drawable.draw(canvas); 14982 } finally { 14983 displayList.end(canvas); 14984 } 14985 14986 // Set up drawable properties that are view-independent. 14987 displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 14988 displayList.setProjectBackwards(drawable.isProjected()); 14989 displayList.setProjectionReceiver(true); 14990 displayList.setClipToBounds(false); 14991 return displayList; 14992 } 14993 14994 /** 14995 * Returns the overlay for this view, creating it if it does not yet exist. 14996 * Adding drawables to the overlay will cause them to be displayed whenever 14997 * the view itself is redrawn. Objects in the overlay should be actively 14998 * managed: remove them when they should not be displayed anymore. The 14999 * overlay will always have the same size as its host view. 15000 * 15001 * <p>Note: Overlays do not currently work correctly with {@link 15002 * SurfaceView} or {@link TextureView}; contents in overlays for these 15003 * types of views may not display correctly.</p> 15004 * 15005 * @return The ViewOverlay object for this view. 15006 * @see ViewOverlay 15007 */ 15008 public ViewOverlay getOverlay() { 15009 if (mOverlay == null) { 15010 mOverlay = new ViewOverlay(mContext, this); 15011 } 15012 return mOverlay; 15013 } 15014 15015 /** 15016 * Override this if your view is known to always be drawn on top of a solid color background, 15017 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15018 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15019 * should be set to 0xFF. 15020 * 15021 * @see #setVerticalFadingEdgeEnabled(boolean) 15022 * @see #setHorizontalFadingEdgeEnabled(boolean) 15023 * 15024 * @return The known solid color background for this view, or 0 if the color may vary 15025 */ 15026 @ViewDebug.ExportedProperty(category = "drawing") 15027 public int getSolidColor() { 15028 return 0; 15029 } 15030 15031 /** 15032 * Build a human readable string representation of the specified view flags. 15033 * 15034 * @param flags the view flags to convert to a string 15035 * @return a String representing the supplied flags 15036 */ 15037 private static String printFlags(int flags) { 15038 String output = ""; 15039 int numFlags = 0; 15040 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15041 output += "TAKES_FOCUS"; 15042 numFlags++; 15043 } 15044 15045 switch (flags & VISIBILITY_MASK) { 15046 case INVISIBLE: 15047 if (numFlags > 0) { 15048 output += " "; 15049 } 15050 output += "INVISIBLE"; 15051 // USELESS HERE numFlags++; 15052 break; 15053 case GONE: 15054 if (numFlags > 0) { 15055 output += " "; 15056 } 15057 output += "GONE"; 15058 // USELESS HERE numFlags++; 15059 break; 15060 default: 15061 break; 15062 } 15063 return output; 15064 } 15065 15066 /** 15067 * Build a human readable string representation of the specified private 15068 * view flags. 15069 * 15070 * @param privateFlags the private view flags to convert to a string 15071 * @return a String representing the supplied flags 15072 */ 15073 private static String printPrivateFlags(int privateFlags) { 15074 String output = ""; 15075 int numFlags = 0; 15076 15077 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15078 output += "WANTS_FOCUS"; 15079 numFlags++; 15080 } 15081 15082 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15083 if (numFlags > 0) { 15084 output += " "; 15085 } 15086 output += "FOCUSED"; 15087 numFlags++; 15088 } 15089 15090 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15091 if (numFlags > 0) { 15092 output += " "; 15093 } 15094 output += "SELECTED"; 15095 numFlags++; 15096 } 15097 15098 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15099 if (numFlags > 0) { 15100 output += " "; 15101 } 15102 output += "IS_ROOT_NAMESPACE"; 15103 numFlags++; 15104 } 15105 15106 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15107 if (numFlags > 0) { 15108 output += " "; 15109 } 15110 output += "HAS_BOUNDS"; 15111 numFlags++; 15112 } 15113 15114 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15115 if (numFlags > 0) { 15116 output += " "; 15117 } 15118 output += "DRAWN"; 15119 // USELESS HERE numFlags++; 15120 } 15121 return output; 15122 } 15123 15124 /** 15125 * <p>Indicates whether or not this view's layout will be requested during 15126 * the next hierarchy layout pass.</p> 15127 * 15128 * @return true if the layout will be forced during next layout pass 15129 */ 15130 public boolean isLayoutRequested() { 15131 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15132 } 15133 15134 /** 15135 * Return true if o is a ViewGroup that is laying out using optical bounds. 15136 * @hide 15137 */ 15138 public static boolean isLayoutModeOptical(Object o) { 15139 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15140 } 15141 15142 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15143 Insets parentInsets = mParent instanceof View ? 15144 ((View) mParent).getOpticalInsets() : Insets.NONE; 15145 Insets childInsets = getOpticalInsets(); 15146 return setFrame( 15147 left + parentInsets.left - childInsets.left, 15148 top + parentInsets.top - childInsets.top, 15149 right + parentInsets.left + childInsets.right, 15150 bottom + parentInsets.top + childInsets.bottom); 15151 } 15152 15153 /** 15154 * Assign a size and position to a view and all of its 15155 * descendants 15156 * 15157 * <p>This is the second phase of the layout mechanism. 15158 * (The first is measuring). In this phase, each parent calls 15159 * layout on all of its children to position them. 15160 * This is typically done using the child measurements 15161 * that were stored in the measure pass().</p> 15162 * 15163 * <p>Derived classes should not override this method. 15164 * Derived classes with children should override 15165 * onLayout. In that method, they should 15166 * call layout on each of their children.</p> 15167 * 15168 * @param l Left position, relative to parent 15169 * @param t Top position, relative to parent 15170 * @param r Right position, relative to parent 15171 * @param b Bottom position, relative to parent 15172 */ 15173 @SuppressWarnings({"unchecked"}) 15174 public void layout(int l, int t, int r, int b) { 15175 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15176 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15177 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15178 } 15179 15180 int oldL = mLeft; 15181 int oldT = mTop; 15182 int oldB = mBottom; 15183 int oldR = mRight; 15184 15185 boolean changed = isLayoutModeOptical(mParent) ? 15186 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15187 15188 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15189 onLayout(changed, l, t, r, b); 15190 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15191 15192 ListenerInfo li = mListenerInfo; 15193 if (li != null && li.mOnLayoutChangeListeners != null) { 15194 ArrayList<OnLayoutChangeListener> listenersCopy = 15195 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15196 int numListeners = listenersCopy.size(); 15197 for (int i = 0; i < numListeners; ++i) { 15198 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15199 } 15200 } 15201 } 15202 15203 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15204 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15205 } 15206 15207 /** 15208 * Called from layout when this view should 15209 * assign a size and position to each of its children. 15210 * 15211 * Derived classes with children should override 15212 * this method and call layout on each of 15213 * their children. 15214 * @param changed This is a new size or position for this view 15215 * @param left Left position, relative to parent 15216 * @param top Top position, relative to parent 15217 * @param right Right position, relative to parent 15218 * @param bottom Bottom position, relative to parent 15219 */ 15220 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15221 } 15222 15223 /** 15224 * Assign a size and position to this view. 15225 * 15226 * This is called from layout. 15227 * 15228 * @param left Left position, relative to parent 15229 * @param top Top position, relative to parent 15230 * @param right Right position, relative to parent 15231 * @param bottom Bottom position, relative to parent 15232 * @return true if the new size and position are different than the 15233 * previous ones 15234 * {@hide} 15235 */ 15236 protected boolean setFrame(int left, int top, int right, int bottom) { 15237 boolean changed = false; 15238 15239 if (DBG) { 15240 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15241 + right + "," + bottom + ")"); 15242 } 15243 15244 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15245 changed = true; 15246 15247 // Remember our drawn bit 15248 int drawn = mPrivateFlags & PFLAG_DRAWN; 15249 15250 int oldWidth = mRight - mLeft; 15251 int oldHeight = mBottom - mTop; 15252 int newWidth = right - left; 15253 int newHeight = bottom - top; 15254 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15255 15256 // Invalidate our old position 15257 invalidate(sizeChanged); 15258 15259 mLeft = left; 15260 mTop = top; 15261 mRight = right; 15262 mBottom = bottom; 15263 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15264 15265 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15266 15267 15268 if (sizeChanged) { 15269 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15270 } 15271 15272 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15273 // If we are visible, force the DRAWN bit to on so that 15274 // this invalidate will go through (at least to our parent). 15275 // This is because someone may have invalidated this view 15276 // before this call to setFrame came in, thereby clearing 15277 // the DRAWN bit. 15278 mPrivateFlags |= PFLAG_DRAWN; 15279 invalidate(sizeChanged); 15280 // parent display list may need to be recreated based on a change in the bounds 15281 // of any child 15282 invalidateParentCaches(); 15283 } 15284 15285 // Reset drawn bit to original value (invalidate turns it off) 15286 mPrivateFlags |= drawn; 15287 15288 mBackgroundSizeChanged = true; 15289 15290 notifySubtreeAccessibilityStateChangedIfNeeded(); 15291 } 15292 return changed; 15293 } 15294 15295 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15296 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15297 if (mOverlay != null) { 15298 mOverlay.getOverlayView().setRight(newWidth); 15299 mOverlay.getOverlayView().setBottom(newHeight); 15300 } 15301 } 15302 15303 /** 15304 * Finalize inflating a view from XML. This is called as the last phase 15305 * of inflation, after all child views have been added. 15306 * 15307 * <p>Even if the subclass overrides onFinishInflate, they should always be 15308 * sure to call the super method, so that we get called. 15309 */ 15310 protected void onFinishInflate() { 15311 } 15312 15313 /** 15314 * Returns the resources associated with this view. 15315 * 15316 * @return Resources object. 15317 */ 15318 public Resources getResources() { 15319 return mResources; 15320 } 15321 15322 /** 15323 * Invalidates the specified Drawable. 15324 * 15325 * @param drawable the drawable to invalidate 15326 */ 15327 @Override 15328 public void invalidateDrawable(@NonNull Drawable drawable) { 15329 if (verifyDrawable(drawable)) { 15330 final Rect dirty = drawable.getDirtyBounds(); 15331 final int scrollX = mScrollX; 15332 final int scrollY = mScrollY; 15333 15334 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15335 dirty.right + scrollX, dirty.bottom + scrollY); 15336 15337 if (drawable == mBackground) { 15338 queryOutlineFromBackgroundIfUndefined(); 15339 } 15340 } 15341 } 15342 15343 /** 15344 * Schedules an action on a drawable to occur at a specified time. 15345 * 15346 * @param who the recipient of the action 15347 * @param what the action to run on the drawable 15348 * @param when the time at which the action must occur. Uses the 15349 * {@link SystemClock#uptimeMillis} timebase. 15350 */ 15351 @Override 15352 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15353 if (verifyDrawable(who) && what != null) { 15354 final long delay = when - SystemClock.uptimeMillis(); 15355 if (mAttachInfo != null) { 15356 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15357 Choreographer.CALLBACK_ANIMATION, what, who, 15358 Choreographer.subtractFrameDelay(delay)); 15359 } else { 15360 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15361 } 15362 } 15363 } 15364 15365 /** 15366 * Cancels a scheduled action on a drawable. 15367 * 15368 * @param who the recipient of the action 15369 * @param what the action to cancel 15370 */ 15371 @Override 15372 public void unscheduleDrawable(Drawable who, Runnable what) { 15373 if (verifyDrawable(who) && what != null) { 15374 if (mAttachInfo != null) { 15375 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15376 Choreographer.CALLBACK_ANIMATION, what, who); 15377 } 15378 ViewRootImpl.getRunQueue().removeCallbacks(what); 15379 } 15380 } 15381 15382 /** 15383 * Unschedule any events associated with the given Drawable. This can be 15384 * used when selecting a new Drawable into a view, so that the previous 15385 * one is completely unscheduled. 15386 * 15387 * @param who The Drawable to unschedule. 15388 * 15389 * @see #drawableStateChanged 15390 */ 15391 public void unscheduleDrawable(Drawable who) { 15392 if (mAttachInfo != null && who != null) { 15393 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15394 Choreographer.CALLBACK_ANIMATION, null, who); 15395 } 15396 } 15397 15398 /** 15399 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15400 * that the View directionality can and will be resolved before its Drawables. 15401 * 15402 * Will call {@link View#onResolveDrawables} when resolution is done. 15403 * 15404 * @hide 15405 */ 15406 protected void resolveDrawables() { 15407 // Drawables resolution may need to happen before resolving the layout direction (which is 15408 // done only during the measure() call). 15409 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15410 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15411 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15412 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15413 // direction to be resolved as its resolved value will be the same as its raw value. 15414 if (!isLayoutDirectionResolved() && 15415 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15416 return; 15417 } 15418 15419 final int layoutDirection = isLayoutDirectionResolved() ? 15420 getLayoutDirection() : getRawLayoutDirection(); 15421 15422 if (mBackground != null) { 15423 mBackground.setLayoutDirection(layoutDirection); 15424 } 15425 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15426 onResolveDrawables(layoutDirection); 15427 } 15428 15429 /** 15430 * Called when layout direction has been resolved. 15431 * 15432 * The default implementation does nothing. 15433 * 15434 * @param layoutDirection The resolved layout direction. 15435 * 15436 * @see #LAYOUT_DIRECTION_LTR 15437 * @see #LAYOUT_DIRECTION_RTL 15438 * 15439 * @hide 15440 */ 15441 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15442 } 15443 15444 /** 15445 * @hide 15446 */ 15447 protected void resetResolvedDrawables() { 15448 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15449 } 15450 15451 private boolean isDrawablesResolved() { 15452 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15453 } 15454 15455 /** 15456 * If your view subclass is displaying its own Drawable objects, it should 15457 * override this function and return true for any Drawable it is 15458 * displaying. This allows animations for those drawables to be 15459 * scheduled. 15460 * 15461 * <p>Be sure to call through to the super class when overriding this 15462 * function. 15463 * 15464 * @param who The Drawable to verify. Return true if it is one you are 15465 * displaying, else return the result of calling through to the 15466 * super class. 15467 * 15468 * @return boolean If true than the Drawable is being displayed in the 15469 * view; else false and it is not allowed to animate. 15470 * 15471 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15472 * @see #drawableStateChanged() 15473 */ 15474 protected boolean verifyDrawable(Drawable who) { 15475 return who == mBackground; 15476 } 15477 15478 /** 15479 * This function is called whenever the state of the view changes in such 15480 * a way that it impacts the state of drawables being shown. 15481 * 15482 * <p>Be sure to call through to the superclass when overriding this 15483 * function. 15484 * 15485 * @see Drawable#setState(int[]) 15486 */ 15487 protected void drawableStateChanged() { 15488 final Drawable d = mBackground; 15489 if (d != null && d.isStateful()) { 15490 d.setState(getDrawableState()); 15491 } 15492 } 15493 15494 /** 15495 * Call this to force a view to update its drawable state. This will cause 15496 * drawableStateChanged to be called on this view. Views that are interested 15497 * in the new state should call getDrawableState. 15498 * 15499 * @see #drawableStateChanged 15500 * @see #getDrawableState 15501 */ 15502 public void refreshDrawableState() { 15503 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15504 drawableStateChanged(); 15505 15506 ViewParent parent = mParent; 15507 if (parent != null) { 15508 parent.childDrawableStateChanged(this); 15509 } 15510 } 15511 15512 /** 15513 * Return an array of resource IDs of the drawable states representing the 15514 * current state of the view. 15515 * 15516 * @return The current drawable state 15517 * 15518 * @see Drawable#setState(int[]) 15519 * @see #drawableStateChanged() 15520 * @see #onCreateDrawableState(int) 15521 */ 15522 public final int[] getDrawableState() { 15523 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15524 return mDrawableState; 15525 } else { 15526 mDrawableState = onCreateDrawableState(0); 15527 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15528 return mDrawableState; 15529 } 15530 } 15531 15532 /** 15533 * Generate the new {@link android.graphics.drawable.Drawable} state for 15534 * this view. This is called by the view 15535 * system when the cached Drawable state is determined to be invalid. To 15536 * retrieve the current state, you should use {@link #getDrawableState}. 15537 * 15538 * @param extraSpace if non-zero, this is the number of extra entries you 15539 * would like in the returned array in which you can place your own 15540 * states. 15541 * 15542 * @return Returns an array holding the current {@link Drawable} state of 15543 * the view. 15544 * 15545 * @see #mergeDrawableStates(int[], int[]) 15546 */ 15547 protected int[] onCreateDrawableState(int extraSpace) { 15548 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15549 mParent instanceof View) { 15550 return ((View) mParent).onCreateDrawableState(extraSpace); 15551 } 15552 15553 int[] drawableState; 15554 15555 int privateFlags = mPrivateFlags; 15556 15557 int viewStateIndex = 0; 15558 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15559 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15560 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15561 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15562 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15563 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15564 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15565 HardwareRenderer.isAvailable()) { 15566 // This is set if HW acceleration is requested, even if the current 15567 // process doesn't allow it. This is just to allow app preview 15568 // windows to better match their app. 15569 viewStateIndex |= VIEW_STATE_ACCELERATED; 15570 } 15571 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15572 15573 final int privateFlags2 = mPrivateFlags2; 15574 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15575 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15576 15577 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15578 15579 //noinspection ConstantIfStatement 15580 if (false) { 15581 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15582 Log.i("View", toString() 15583 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15584 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15585 + " fo=" + hasFocus() 15586 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15587 + " wf=" + hasWindowFocus() 15588 + ": " + Arrays.toString(drawableState)); 15589 } 15590 15591 if (extraSpace == 0) { 15592 return drawableState; 15593 } 15594 15595 final int[] fullState; 15596 if (drawableState != null) { 15597 fullState = new int[drawableState.length + extraSpace]; 15598 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15599 } else { 15600 fullState = new int[extraSpace]; 15601 } 15602 15603 return fullState; 15604 } 15605 15606 /** 15607 * Merge your own state values in <var>additionalState</var> into the base 15608 * state values <var>baseState</var> that were returned by 15609 * {@link #onCreateDrawableState(int)}. 15610 * 15611 * @param baseState The base state values returned by 15612 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15613 * own additional state values. 15614 * 15615 * @param additionalState The additional state values you would like 15616 * added to <var>baseState</var>; this array is not modified. 15617 * 15618 * @return As a convenience, the <var>baseState</var> array you originally 15619 * passed into the function is returned. 15620 * 15621 * @see #onCreateDrawableState(int) 15622 */ 15623 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15624 final int N = baseState.length; 15625 int i = N - 1; 15626 while (i >= 0 && baseState[i] == 0) { 15627 i--; 15628 } 15629 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15630 return baseState; 15631 } 15632 15633 /** 15634 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15635 * on all Drawable objects associated with this view. 15636 */ 15637 public void jumpDrawablesToCurrentState() { 15638 if (mBackground != null) { 15639 mBackground.jumpToCurrentState(); 15640 } 15641 } 15642 15643 /** 15644 * Sets the background color for this view. 15645 * @param color the color of the background 15646 */ 15647 @RemotableViewMethod 15648 public void setBackgroundColor(int color) { 15649 if (mBackground instanceof ColorDrawable) { 15650 ((ColorDrawable) mBackground.mutate()).setColor(color); 15651 computeOpaqueFlags(); 15652 mBackgroundResource = 0; 15653 } else { 15654 setBackground(new ColorDrawable(color)); 15655 } 15656 } 15657 15658 /** 15659 * Set the background to a given resource. The resource should refer to 15660 * a Drawable object or 0 to remove the background. 15661 * @param resid The identifier of the resource. 15662 * 15663 * @attr ref android.R.styleable#View_background 15664 */ 15665 @RemotableViewMethod 15666 public void setBackgroundResource(int resid) { 15667 if (resid != 0 && resid == mBackgroundResource) { 15668 return; 15669 } 15670 15671 Drawable d= null; 15672 if (resid != 0) { 15673 d = mContext.getDrawable(resid); 15674 } 15675 setBackground(d); 15676 15677 mBackgroundResource = resid; 15678 } 15679 15680 /** 15681 * Set the background to a given Drawable, or remove the background. If the 15682 * background has padding, this View's padding is set to the background's 15683 * padding. However, when a background is removed, this View's padding isn't 15684 * touched. If setting the padding is desired, please use 15685 * {@link #setPadding(int, int, int, int)}. 15686 * 15687 * @param background The Drawable to use as the background, or null to remove the 15688 * background 15689 */ 15690 public void setBackground(Drawable background) { 15691 //noinspection deprecation 15692 setBackgroundDrawable(background); 15693 } 15694 15695 /** 15696 * @deprecated use {@link #setBackground(Drawable)} instead 15697 */ 15698 @Deprecated 15699 public void setBackgroundDrawable(Drawable background) { 15700 computeOpaqueFlags(); 15701 15702 if (background == mBackground) { 15703 return; 15704 } 15705 15706 boolean requestLayout = false; 15707 15708 mBackgroundResource = 0; 15709 15710 /* 15711 * Regardless of whether we're setting a new background or not, we want 15712 * to clear the previous drawable. 15713 */ 15714 if (mBackground != null) { 15715 mBackground.setCallback(null); 15716 unscheduleDrawable(mBackground); 15717 } 15718 15719 if (background != null) { 15720 Rect padding = sThreadLocal.get(); 15721 if (padding == null) { 15722 padding = new Rect(); 15723 sThreadLocal.set(padding); 15724 } 15725 resetResolvedDrawables(); 15726 background.setLayoutDirection(getLayoutDirection()); 15727 if (background.getPadding(padding)) { 15728 resetResolvedPadding(); 15729 switch (background.getLayoutDirection()) { 15730 case LAYOUT_DIRECTION_RTL: 15731 mUserPaddingLeftInitial = padding.right; 15732 mUserPaddingRightInitial = padding.left; 15733 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15734 break; 15735 case LAYOUT_DIRECTION_LTR: 15736 default: 15737 mUserPaddingLeftInitial = padding.left; 15738 mUserPaddingRightInitial = padding.right; 15739 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15740 } 15741 mLeftPaddingDefined = false; 15742 mRightPaddingDefined = false; 15743 } 15744 15745 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15746 // if it has a different minimum size, we should layout again 15747 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 15748 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15749 requestLayout = true; 15750 } 15751 15752 background.setCallback(this); 15753 if (background.isStateful()) { 15754 background.setState(getDrawableState()); 15755 } 15756 background.setVisible(getVisibility() == VISIBLE, false); 15757 mBackground = background; 15758 15759 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15760 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15761 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15762 requestLayout = true; 15763 } 15764 } else { 15765 /* Remove the background */ 15766 mBackground = null; 15767 15768 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15769 /* 15770 * This view ONLY drew the background before and we're removing 15771 * the background, so now it won't draw anything 15772 * (hence we SKIP_DRAW) 15773 */ 15774 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15775 mPrivateFlags |= PFLAG_SKIP_DRAW; 15776 } 15777 15778 /* 15779 * When the background is set, we try to apply its padding to this 15780 * View. When the background is removed, we don't touch this View's 15781 * padding. This is noted in the Javadocs. Hence, we don't need to 15782 * requestLayout(), the invalidate() below is sufficient. 15783 */ 15784 15785 // The old background's minimum size could have affected this 15786 // View's layout, so let's requestLayout 15787 requestLayout = true; 15788 } 15789 15790 computeOpaqueFlags(); 15791 15792 if (requestLayout) { 15793 requestLayout(); 15794 } 15795 15796 mBackgroundSizeChanged = true; 15797 invalidate(true); 15798 } 15799 15800 /** 15801 * Gets the background drawable 15802 * 15803 * @return The drawable used as the background for this view, if any. 15804 * 15805 * @see #setBackground(Drawable) 15806 * 15807 * @attr ref android.R.styleable#View_background 15808 */ 15809 public Drawable getBackground() { 15810 return mBackground; 15811 } 15812 15813 /** 15814 * Sets the padding. The view may add on the space required to display 15815 * the scrollbars, depending on the style and visibility of the scrollbars. 15816 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15817 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15818 * from the values set in this call. 15819 * 15820 * @attr ref android.R.styleable#View_padding 15821 * @attr ref android.R.styleable#View_paddingBottom 15822 * @attr ref android.R.styleable#View_paddingLeft 15823 * @attr ref android.R.styleable#View_paddingRight 15824 * @attr ref android.R.styleable#View_paddingTop 15825 * @param left the left padding in pixels 15826 * @param top the top padding in pixels 15827 * @param right the right padding in pixels 15828 * @param bottom the bottom padding in pixels 15829 */ 15830 public void setPadding(int left, int top, int right, int bottom) { 15831 resetResolvedPadding(); 15832 15833 mUserPaddingStart = UNDEFINED_PADDING; 15834 mUserPaddingEnd = UNDEFINED_PADDING; 15835 15836 mUserPaddingLeftInitial = left; 15837 mUserPaddingRightInitial = right; 15838 15839 mLeftPaddingDefined = true; 15840 mRightPaddingDefined = true; 15841 15842 internalSetPadding(left, top, right, bottom); 15843 } 15844 15845 /** 15846 * @hide 15847 */ 15848 protected void internalSetPadding(int left, int top, int right, int bottom) { 15849 mUserPaddingLeft = left; 15850 mUserPaddingRight = right; 15851 mUserPaddingBottom = bottom; 15852 15853 final int viewFlags = mViewFlags; 15854 boolean changed = false; 15855 15856 // Common case is there are no scroll bars. 15857 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15858 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15859 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15860 ? 0 : getVerticalScrollbarWidth(); 15861 switch (mVerticalScrollbarPosition) { 15862 case SCROLLBAR_POSITION_DEFAULT: 15863 if (isLayoutRtl()) { 15864 left += offset; 15865 } else { 15866 right += offset; 15867 } 15868 break; 15869 case SCROLLBAR_POSITION_RIGHT: 15870 right += offset; 15871 break; 15872 case SCROLLBAR_POSITION_LEFT: 15873 left += offset; 15874 break; 15875 } 15876 } 15877 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 15878 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 15879 ? 0 : getHorizontalScrollbarHeight(); 15880 } 15881 } 15882 15883 if (mPaddingLeft != left) { 15884 changed = true; 15885 mPaddingLeft = left; 15886 } 15887 if (mPaddingTop != top) { 15888 changed = true; 15889 mPaddingTop = top; 15890 } 15891 if (mPaddingRight != right) { 15892 changed = true; 15893 mPaddingRight = right; 15894 } 15895 if (mPaddingBottom != bottom) { 15896 changed = true; 15897 mPaddingBottom = bottom; 15898 } 15899 15900 if (changed) { 15901 requestLayout(); 15902 } 15903 } 15904 15905 /** 15906 * Sets the relative padding. The view may add on the space required to display 15907 * the scrollbars, depending on the style and visibility of the scrollbars. 15908 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 15909 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 15910 * from the values set in this call. 15911 * 15912 * @attr ref android.R.styleable#View_padding 15913 * @attr ref android.R.styleable#View_paddingBottom 15914 * @attr ref android.R.styleable#View_paddingStart 15915 * @attr ref android.R.styleable#View_paddingEnd 15916 * @attr ref android.R.styleable#View_paddingTop 15917 * @param start the start padding in pixels 15918 * @param top the top padding in pixels 15919 * @param end the end padding in pixels 15920 * @param bottom the bottom padding in pixels 15921 */ 15922 public void setPaddingRelative(int start, int top, int end, int bottom) { 15923 resetResolvedPadding(); 15924 15925 mUserPaddingStart = start; 15926 mUserPaddingEnd = end; 15927 mLeftPaddingDefined = true; 15928 mRightPaddingDefined = true; 15929 15930 switch(getLayoutDirection()) { 15931 case LAYOUT_DIRECTION_RTL: 15932 mUserPaddingLeftInitial = end; 15933 mUserPaddingRightInitial = start; 15934 internalSetPadding(end, top, start, bottom); 15935 break; 15936 case LAYOUT_DIRECTION_LTR: 15937 default: 15938 mUserPaddingLeftInitial = start; 15939 mUserPaddingRightInitial = end; 15940 internalSetPadding(start, top, end, bottom); 15941 } 15942 } 15943 15944 /** 15945 * Returns the top padding of this view. 15946 * 15947 * @return the top padding in pixels 15948 */ 15949 public int getPaddingTop() { 15950 return mPaddingTop; 15951 } 15952 15953 /** 15954 * Returns the bottom padding of this view. If there are inset and enabled 15955 * scrollbars, this value may include the space required to display the 15956 * scrollbars as well. 15957 * 15958 * @return the bottom padding in pixels 15959 */ 15960 public int getPaddingBottom() { 15961 return mPaddingBottom; 15962 } 15963 15964 /** 15965 * Returns the left padding of this view. If there are inset and enabled 15966 * scrollbars, this value may include the space required to display the 15967 * scrollbars as well. 15968 * 15969 * @return the left padding in pixels 15970 */ 15971 public int getPaddingLeft() { 15972 if (!isPaddingResolved()) { 15973 resolvePadding(); 15974 } 15975 return mPaddingLeft; 15976 } 15977 15978 /** 15979 * Returns the start padding of this view depending on its resolved layout direction. 15980 * If there are inset and enabled scrollbars, this value may include the space 15981 * required to display the scrollbars as well. 15982 * 15983 * @return the start padding in pixels 15984 */ 15985 public int getPaddingStart() { 15986 if (!isPaddingResolved()) { 15987 resolvePadding(); 15988 } 15989 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 15990 mPaddingRight : mPaddingLeft; 15991 } 15992 15993 /** 15994 * Returns the right padding of this view. If there are inset and enabled 15995 * scrollbars, this value may include the space required to display the 15996 * scrollbars as well. 15997 * 15998 * @return the right padding in pixels 15999 */ 16000 public int getPaddingRight() { 16001 if (!isPaddingResolved()) { 16002 resolvePadding(); 16003 } 16004 return mPaddingRight; 16005 } 16006 16007 /** 16008 * Returns the end padding of this view depending on its resolved layout direction. 16009 * If there are inset and enabled scrollbars, this value may include the space 16010 * required to display the scrollbars as well. 16011 * 16012 * @return the end padding in pixels 16013 */ 16014 public int getPaddingEnd() { 16015 if (!isPaddingResolved()) { 16016 resolvePadding(); 16017 } 16018 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16019 mPaddingLeft : mPaddingRight; 16020 } 16021 16022 /** 16023 * Return if the padding as been set thru relative values 16024 * {@link #setPaddingRelative(int, int, int, int)} or thru 16025 * @attr ref android.R.styleable#View_paddingStart or 16026 * @attr ref android.R.styleable#View_paddingEnd 16027 * 16028 * @return true if the padding is relative or false if it is not. 16029 */ 16030 public boolean isPaddingRelative() { 16031 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16032 } 16033 16034 Insets computeOpticalInsets() { 16035 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16036 } 16037 16038 /** 16039 * @hide 16040 */ 16041 public void resetPaddingToInitialValues() { 16042 if (isRtlCompatibilityMode()) { 16043 mPaddingLeft = mUserPaddingLeftInitial; 16044 mPaddingRight = mUserPaddingRightInitial; 16045 return; 16046 } 16047 if (isLayoutRtl()) { 16048 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16049 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16050 } else { 16051 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16052 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16053 } 16054 } 16055 16056 /** 16057 * @hide 16058 */ 16059 public Insets getOpticalInsets() { 16060 if (mLayoutInsets == null) { 16061 mLayoutInsets = computeOpticalInsets(); 16062 } 16063 return mLayoutInsets; 16064 } 16065 16066 /** 16067 * Changes the selection state of this view. A view can be selected or not. 16068 * Note that selection is not the same as focus. Views are typically 16069 * selected in the context of an AdapterView like ListView or GridView; 16070 * the selected view is the view that is highlighted. 16071 * 16072 * @param selected true if the view must be selected, false otherwise 16073 */ 16074 public void setSelected(boolean selected) { 16075 //noinspection DoubleNegation 16076 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16077 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16078 if (!selected) resetPressedState(); 16079 invalidate(true); 16080 refreshDrawableState(); 16081 dispatchSetSelected(selected); 16082 notifyViewAccessibilityStateChangedIfNeeded( 16083 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16084 } 16085 } 16086 16087 /** 16088 * Dispatch setSelected to all of this View's children. 16089 * 16090 * @see #setSelected(boolean) 16091 * 16092 * @param selected The new selected state 16093 */ 16094 protected void dispatchSetSelected(boolean selected) { 16095 } 16096 16097 /** 16098 * Indicates the selection state of this view. 16099 * 16100 * @return true if the view is selected, false otherwise 16101 */ 16102 @ViewDebug.ExportedProperty 16103 public boolean isSelected() { 16104 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16105 } 16106 16107 /** 16108 * Changes the activated state of this view. A view can be activated or not. 16109 * Note that activation is not the same as selection. Selection is 16110 * a transient property, representing the view (hierarchy) the user is 16111 * currently interacting with. Activation is a longer-term state that the 16112 * user can move views in and out of. For example, in a list view with 16113 * single or multiple selection enabled, the views in the current selection 16114 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16115 * here.) The activated state is propagated down to children of the view it 16116 * is set on. 16117 * 16118 * @param activated true if the view must be activated, false otherwise 16119 */ 16120 public void setActivated(boolean activated) { 16121 //noinspection DoubleNegation 16122 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16123 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16124 invalidate(true); 16125 refreshDrawableState(); 16126 dispatchSetActivated(activated); 16127 } 16128 } 16129 16130 /** 16131 * Dispatch setActivated to all of this View's children. 16132 * 16133 * @see #setActivated(boolean) 16134 * 16135 * @param activated The new activated state 16136 */ 16137 protected void dispatchSetActivated(boolean activated) { 16138 } 16139 16140 /** 16141 * Indicates the activation state of this view. 16142 * 16143 * @return true if the view is activated, false otherwise 16144 */ 16145 @ViewDebug.ExportedProperty 16146 public boolean isActivated() { 16147 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16148 } 16149 16150 /** 16151 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16152 * observer can be used to get notifications when global events, like 16153 * layout, happen. 16154 * 16155 * The returned ViewTreeObserver observer is not guaranteed to remain 16156 * valid for the lifetime of this View. If the caller of this method keeps 16157 * a long-lived reference to ViewTreeObserver, it should always check for 16158 * the return value of {@link ViewTreeObserver#isAlive()}. 16159 * 16160 * @return The ViewTreeObserver for this view's hierarchy. 16161 */ 16162 public ViewTreeObserver getViewTreeObserver() { 16163 if (mAttachInfo != null) { 16164 return mAttachInfo.mTreeObserver; 16165 } 16166 if (mFloatingTreeObserver == null) { 16167 mFloatingTreeObserver = new ViewTreeObserver(); 16168 } 16169 return mFloatingTreeObserver; 16170 } 16171 16172 /** 16173 * <p>Finds the topmost view in the current view hierarchy.</p> 16174 * 16175 * @return the topmost view containing this view 16176 */ 16177 public View getRootView() { 16178 if (mAttachInfo != null) { 16179 final View v = mAttachInfo.mRootView; 16180 if (v != null) { 16181 return v; 16182 } 16183 } 16184 16185 View parent = this; 16186 16187 while (parent.mParent != null && parent.mParent instanceof View) { 16188 parent = (View) parent.mParent; 16189 } 16190 16191 return parent; 16192 } 16193 16194 /** 16195 * Transforms a motion event from view-local coordinates to on-screen 16196 * coordinates. 16197 * 16198 * @param ev the view-local motion event 16199 * @return false if the transformation could not be applied 16200 * @hide 16201 */ 16202 public boolean toGlobalMotionEvent(MotionEvent ev) { 16203 final AttachInfo info = mAttachInfo; 16204 if (info == null) { 16205 return false; 16206 } 16207 16208 final Matrix m = info.mTmpMatrix; 16209 m.set(Matrix.IDENTITY_MATRIX); 16210 transformMatrixToGlobal(m); 16211 ev.transform(m); 16212 return true; 16213 } 16214 16215 /** 16216 * Transforms a motion event from on-screen coordinates to view-local 16217 * coordinates. 16218 * 16219 * @param ev the on-screen motion event 16220 * @return false if the transformation could not be applied 16221 * @hide 16222 */ 16223 public boolean toLocalMotionEvent(MotionEvent ev) { 16224 final AttachInfo info = mAttachInfo; 16225 if (info == null) { 16226 return false; 16227 } 16228 16229 final Matrix m = info.mTmpMatrix; 16230 m.set(Matrix.IDENTITY_MATRIX); 16231 transformMatrixToLocal(m); 16232 ev.transform(m); 16233 return true; 16234 } 16235 16236 /** 16237 * Modifies the input matrix such that it maps view-local coordinates to 16238 * on-screen coordinates. 16239 * 16240 * @param m input matrix to modify 16241 */ 16242 void transformMatrixToGlobal(Matrix m) { 16243 final ViewParent parent = mParent; 16244 if (parent instanceof View) { 16245 final View vp = (View) parent; 16246 vp.transformMatrixToGlobal(m); 16247 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16248 } else if (parent instanceof ViewRootImpl) { 16249 final ViewRootImpl vr = (ViewRootImpl) parent; 16250 vr.transformMatrixToGlobal(m); 16251 m.postTranslate(0, -vr.mCurScrollY); 16252 } 16253 16254 m.postTranslate(mLeft, mTop); 16255 16256 if (!hasIdentityMatrix()) { 16257 m.postConcat(getMatrix()); 16258 } 16259 } 16260 16261 /** 16262 * Modifies the input matrix such that it maps on-screen coordinates to 16263 * view-local coordinates. 16264 * 16265 * @param m input matrix to modify 16266 */ 16267 void transformMatrixToLocal(Matrix m) { 16268 final ViewParent parent = mParent; 16269 if (parent instanceof View) { 16270 final View vp = (View) parent; 16271 vp.transformMatrixToLocal(m); 16272 m.preTranslate(vp.mScrollX, vp.mScrollY); 16273 } else if (parent instanceof ViewRootImpl) { 16274 final ViewRootImpl vr = (ViewRootImpl) parent; 16275 vr.transformMatrixToLocal(m); 16276 m.preTranslate(0, vr.mCurScrollY); 16277 } 16278 16279 m.preTranslate(-mLeft, -mTop); 16280 16281 if (!hasIdentityMatrix()) { 16282 m.preConcat(getInverseMatrix()); 16283 } 16284 } 16285 16286 /** 16287 * <p>Computes the coordinates of this view on the screen. The argument 16288 * must be an array of two integers. After the method returns, the array 16289 * contains the x and y location in that order.</p> 16290 * 16291 * @param location an array of two integers in which to hold the coordinates 16292 */ 16293 public void getLocationOnScreen(int[] location) { 16294 getLocationInWindow(location); 16295 16296 final AttachInfo info = mAttachInfo; 16297 if (info != null) { 16298 location[0] += info.mWindowLeft; 16299 location[1] += info.mWindowTop; 16300 } 16301 } 16302 16303 /** 16304 * <p>Computes the coordinates of this view in its window. The argument 16305 * must be an array of two integers. After the method returns, the array 16306 * contains the x and y location in that order.</p> 16307 * 16308 * @param location an array of two integers in which to hold the coordinates 16309 */ 16310 public void getLocationInWindow(int[] location) { 16311 if (location == null || location.length < 2) { 16312 throw new IllegalArgumentException("location must be an array of two integers"); 16313 } 16314 16315 if (mAttachInfo == null) { 16316 // When the view is not attached to a window, this method does not make sense 16317 location[0] = location[1] = 0; 16318 return; 16319 } 16320 16321 float[] position = mAttachInfo.mTmpTransformLocation; 16322 position[0] = position[1] = 0.0f; 16323 16324 if (!hasIdentityMatrix()) { 16325 getMatrix().mapPoints(position); 16326 } 16327 16328 position[0] += mLeft; 16329 position[1] += mTop; 16330 16331 ViewParent viewParent = mParent; 16332 while (viewParent instanceof View) { 16333 final View view = (View) viewParent; 16334 16335 position[0] -= view.mScrollX; 16336 position[1] -= view.mScrollY; 16337 16338 if (!view.hasIdentityMatrix()) { 16339 view.getMatrix().mapPoints(position); 16340 } 16341 16342 position[0] += view.mLeft; 16343 position[1] += view.mTop; 16344 16345 viewParent = view.mParent; 16346 } 16347 16348 if (viewParent instanceof ViewRootImpl) { 16349 // *cough* 16350 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16351 position[1] -= vr.mCurScrollY; 16352 } 16353 16354 location[0] = (int) (position[0] + 0.5f); 16355 location[1] = (int) (position[1] + 0.5f); 16356 } 16357 16358 /** 16359 * {@hide} 16360 * @param id the id of the view to be found 16361 * @return the view of the specified id, null if cannot be found 16362 */ 16363 protected View findViewTraversal(int id) { 16364 if (id == mID) { 16365 return this; 16366 } 16367 return null; 16368 } 16369 16370 /** 16371 * {@hide} 16372 * @param tag the tag of the view to be found 16373 * @return the view of specified tag, null if cannot be found 16374 */ 16375 protected View findViewWithTagTraversal(Object tag) { 16376 if (tag != null && tag.equals(mTag)) { 16377 return this; 16378 } 16379 return null; 16380 } 16381 16382 /** 16383 * {@hide} 16384 * @param predicate The predicate to evaluate. 16385 * @param childToSkip If not null, ignores this child during the recursive traversal. 16386 * @return The first view that matches the predicate or null. 16387 */ 16388 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16389 if (predicate.apply(this)) { 16390 return this; 16391 } 16392 return null; 16393 } 16394 16395 /** 16396 * Look for a child view with the given id. If this view has the given 16397 * id, return this view. 16398 * 16399 * @param id The id to search for. 16400 * @return The view that has the given id in the hierarchy or null 16401 */ 16402 public final View findViewById(int id) { 16403 if (id < 0) { 16404 return null; 16405 } 16406 return findViewTraversal(id); 16407 } 16408 16409 /** 16410 * Finds a view by its unuque and stable accessibility id. 16411 * 16412 * @param accessibilityId The searched accessibility id. 16413 * @return The found view. 16414 */ 16415 final View findViewByAccessibilityId(int accessibilityId) { 16416 if (accessibilityId < 0) { 16417 return null; 16418 } 16419 return findViewByAccessibilityIdTraversal(accessibilityId); 16420 } 16421 16422 /** 16423 * Performs the traversal to find a view by its unuque and stable accessibility id. 16424 * 16425 * <strong>Note:</strong>This method does not stop at the root namespace 16426 * boundary since the user can touch the screen at an arbitrary location 16427 * potentially crossing the root namespace bounday which will send an 16428 * accessibility event to accessibility services and they should be able 16429 * to obtain the event source. Also accessibility ids are guaranteed to be 16430 * unique in the window. 16431 * 16432 * @param accessibilityId The accessibility id. 16433 * @return The found view. 16434 * 16435 * @hide 16436 */ 16437 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16438 if (getAccessibilityViewId() == accessibilityId) { 16439 return this; 16440 } 16441 return null; 16442 } 16443 16444 /** 16445 * Look for a child view with the given tag. If this view has the given 16446 * tag, return this view. 16447 * 16448 * @param tag The tag to search for, using "tag.equals(getTag())". 16449 * @return The View that has the given tag in the hierarchy or null 16450 */ 16451 public final View findViewWithTag(Object tag) { 16452 if (tag == null) { 16453 return null; 16454 } 16455 return findViewWithTagTraversal(tag); 16456 } 16457 16458 /** 16459 * {@hide} 16460 * Look for a child view that matches the specified predicate. 16461 * If this view matches the predicate, return this view. 16462 * 16463 * @param predicate The predicate to evaluate. 16464 * @return The first view that matches the predicate or null. 16465 */ 16466 public final View findViewByPredicate(Predicate<View> predicate) { 16467 return findViewByPredicateTraversal(predicate, null); 16468 } 16469 16470 /** 16471 * {@hide} 16472 * Look for a child view that matches the specified predicate, 16473 * starting with the specified view and its descendents and then 16474 * recusively searching the ancestors and siblings of that view 16475 * until this view is reached. 16476 * 16477 * This method is useful in cases where the predicate does not match 16478 * a single unique view (perhaps multiple views use the same id) 16479 * and we are trying to find the view that is "closest" in scope to the 16480 * starting view. 16481 * 16482 * @param start The view to start from. 16483 * @param predicate The predicate to evaluate. 16484 * @return The first view that matches the predicate or null. 16485 */ 16486 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16487 View childToSkip = null; 16488 for (;;) { 16489 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16490 if (view != null || start == this) { 16491 return view; 16492 } 16493 16494 ViewParent parent = start.getParent(); 16495 if (parent == null || !(parent instanceof View)) { 16496 return null; 16497 } 16498 16499 childToSkip = start; 16500 start = (View) parent; 16501 } 16502 } 16503 16504 /** 16505 * Sets the identifier for this view. The identifier does not have to be 16506 * unique in this view's hierarchy. The identifier should be a positive 16507 * number. 16508 * 16509 * @see #NO_ID 16510 * @see #getId() 16511 * @see #findViewById(int) 16512 * 16513 * @param id a number used to identify the view 16514 * 16515 * @attr ref android.R.styleable#View_id 16516 */ 16517 public void setId(int id) { 16518 mID = id; 16519 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16520 mID = generateViewId(); 16521 } 16522 } 16523 16524 /** 16525 * {@hide} 16526 * 16527 * @param isRoot true if the view belongs to the root namespace, false 16528 * otherwise 16529 */ 16530 public void setIsRootNamespace(boolean isRoot) { 16531 if (isRoot) { 16532 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16533 } else { 16534 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16535 } 16536 } 16537 16538 /** 16539 * {@hide} 16540 * 16541 * @return true if the view belongs to the root namespace, false otherwise 16542 */ 16543 public boolean isRootNamespace() { 16544 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16545 } 16546 16547 /** 16548 * Returns this view's identifier. 16549 * 16550 * @return a positive integer used to identify the view or {@link #NO_ID} 16551 * if the view has no ID 16552 * 16553 * @see #setId(int) 16554 * @see #findViewById(int) 16555 * @attr ref android.R.styleable#View_id 16556 */ 16557 @ViewDebug.CapturedViewProperty 16558 public int getId() { 16559 return mID; 16560 } 16561 16562 /** 16563 * Returns this view's tag. 16564 * 16565 * @return the Object stored in this view as a tag, or {@code null} if not 16566 * set 16567 * 16568 * @see #setTag(Object) 16569 * @see #getTag(int) 16570 */ 16571 @ViewDebug.ExportedProperty 16572 public Object getTag() { 16573 return mTag; 16574 } 16575 16576 /** 16577 * Sets the tag associated with this view. A tag can be used to mark 16578 * a view in its hierarchy and does not have to be unique within the 16579 * hierarchy. Tags can also be used to store data within a view without 16580 * resorting to another data structure. 16581 * 16582 * @param tag an Object to tag the view with 16583 * 16584 * @see #getTag() 16585 * @see #setTag(int, Object) 16586 */ 16587 public void setTag(final Object tag) { 16588 mTag = tag; 16589 } 16590 16591 /** 16592 * Returns the tag associated with this view and the specified key. 16593 * 16594 * @param key The key identifying the tag 16595 * 16596 * @return the Object stored in this view as a tag, or {@code null} if not 16597 * set 16598 * 16599 * @see #setTag(int, Object) 16600 * @see #getTag() 16601 */ 16602 public Object getTag(int key) { 16603 if (mKeyedTags != null) return mKeyedTags.get(key); 16604 return null; 16605 } 16606 16607 /** 16608 * Sets a tag associated with this view and a key. A tag can be used 16609 * to mark a view in its hierarchy and does not have to be unique within 16610 * the hierarchy. Tags can also be used to store data within a view 16611 * without resorting to another data structure. 16612 * 16613 * The specified key should be an id declared in the resources of the 16614 * application to ensure it is unique (see the <a 16615 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16616 * Keys identified as belonging to 16617 * the Android framework or not associated with any package will cause 16618 * an {@link IllegalArgumentException} to be thrown. 16619 * 16620 * @param key The key identifying the tag 16621 * @param tag An Object to tag the view with 16622 * 16623 * @throws IllegalArgumentException If they specified key is not valid 16624 * 16625 * @see #setTag(Object) 16626 * @see #getTag(int) 16627 */ 16628 public void setTag(int key, final Object tag) { 16629 // If the package id is 0x00 or 0x01, it's either an undefined package 16630 // or a framework id 16631 if ((key >>> 24) < 2) { 16632 throw new IllegalArgumentException("The key must be an application-specific " 16633 + "resource id."); 16634 } 16635 16636 setKeyedTag(key, tag); 16637 } 16638 16639 /** 16640 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16641 * framework id. 16642 * 16643 * @hide 16644 */ 16645 public void setTagInternal(int key, Object tag) { 16646 if ((key >>> 24) != 0x1) { 16647 throw new IllegalArgumentException("The key must be a framework-specific " 16648 + "resource id."); 16649 } 16650 16651 setKeyedTag(key, tag); 16652 } 16653 16654 private void setKeyedTag(int key, Object tag) { 16655 if (mKeyedTags == null) { 16656 mKeyedTags = new SparseArray<Object>(2); 16657 } 16658 16659 mKeyedTags.put(key, tag); 16660 } 16661 16662 /** 16663 * Prints information about this view in the log output, with the tag 16664 * {@link #VIEW_LOG_TAG}. 16665 * 16666 * @hide 16667 */ 16668 public void debug() { 16669 debug(0); 16670 } 16671 16672 /** 16673 * Prints information about this view in the log output, with the tag 16674 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16675 * indentation defined by the <code>depth</code>. 16676 * 16677 * @param depth the indentation level 16678 * 16679 * @hide 16680 */ 16681 protected void debug(int depth) { 16682 String output = debugIndent(depth - 1); 16683 16684 output += "+ " + this; 16685 int id = getId(); 16686 if (id != -1) { 16687 output += " (id=" + id + ")"; 16688 } 16689 Object tag = getTag(); 16690 if (tag != null) { 16691 output += " (tag=" + tag + ")"; 16692 } 16693 Log.d(VIEW_LOG_TAG, output); 16694 16695 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16696 output = debugIndent(depth) + " FOCUSED"; 16697 Log.d(VIEW_LOG_TAG, output); 16698 } 16699 16700 output = debugIndent(depth); 16701 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16702 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16703 + "} "; 16704 Log.d(VIEW_LOG_TAG, output); 16705 16706 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16707 || mPaddingBottom != 0) { 16708 output = debugIndent(depth); 16709 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16710 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16711 Log.d(VIEW_LOG_TAG, output); 16712 } 16713 16714 output = debugIndent(depth); 16715 output += "mMeasureWidth=" + mMeasuredWidth + 16716 " mMeasureHeight=" + mMeasuredHeight; 16717 Log.d(VIEW_LOG_TAG, output); 16718 16719 output = debugIndent(depth); 16720 if (mLayoutParams == null) { 16721 output += "BAD! no layout params"; 16722 } else { 16723 output = mLayoutParams.debug(output); 16724 } 16725 Log.d(VIEW_LOG_TAG, output); 16726 16727 output = debugIndent(depth); 16728 output += "flags={"; 16729 output += View.printFlags(mViewFlags); 16730 output += "}"; 16731 Log.d(VIEW_LOG_TAG, output); 16732 16733 output = debugIndent(depth); 16734 output += "privateFlags={"; 16735 output += View.printPrivateFlags(mPrivateFlags); 16736 output += "}"; 16737 Log.d(VIEW_LOG_TAG, output); 16738 } 16739 16740 /** 16741 * Creates a string of whitespaces used for indentation. 16742 * 16743 * @param depth the indentation level 16744 * @return a String containing (depth * 2 + 3) * 2 white spaces 16745 * 16746 * @hide 16747 */ 16748 protected static String debugIndent(int depth) { 16749 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16750 for (int i = 0; i < (depth * 2) + 3; i++) { 16751 spaces.append(' ').append(' '); 16752 } 16753 return spaces.toString(); 16754 } 16755 16756 /** 16757 * <p>Return the offset of the widget's text baseline from the widget's top 16758 * boundary. If this widget does not support baseline alignment, this 16759 * method returns -1. </p> 16760 * 16761 * @return the offset of the baseline within the widget's bounds or -1 16762 * if baseline alignment is not supported 16763 */ 16764 @ViewDebug.ExportedProperty(category = "layout") 16765 public int getBaseline() { 16766 return -1; 16767 } 16768 16769 /** 16770 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16771 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16772 * a layout pass. 16773 * 16774 * @return whether the view hierarchy is currently undergoing a layout pass 16775 */ 16776 public boolean isInLayout() { 16777 ViewRootImpl viewRoot = getViewRootImpl(); 16778 return (viewRoot != null && viewRoot.isInLayout()); 16779 } 16780 16781 /** 16782 * Call this when something has changed which has invalidated the 16783 * layout of this view. This will schedule a layout pass of the view 16784 * tree. This should not be called while the view hierarchy is currently in a layout 16785 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16786 * end of the current layout pass (and then layout will run again) or after the current 16787 * frame is drawn and the next layout occurs. 16788 * 16789 * <p>Subclasses which override this method should call the superclass method to 16790 * handle possible request-during-layout errors correctly.</p> 16791 */ 16792 public void requestLayout() { 16793 if (mMeasureCache != null) mMeasureCache.clear(); 16794 16795 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16796 // Only trigger request-during-layout logic if this is the view requesting it, 16797 // not the views in its parent hierarchy 16798 ViewRootImpl viewRoot = getViewRootImpl(); 16799 if (viewRoot != null && viewRoot.isInLayout()) { 16800 if (!viewRoot.requestLayoutDuringLayout(this)) { 16801 return; 16802 } 16803 } 16804 mAttachInfo.mViewRequestingLayout = this; 16805 } 16806 16807 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16808 mPrivateFlags |= PFLAG_INVALIDATED; 16809 16810 if (mParent != null && !mParent.isLayoutRequested()) { 16811 mParent.requestLayout(); 16812 } 16813 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16814 mAttachInfo.mViewRequestingLayout = null; 16815 } 16816 } 16817 16818 /** 16819 * Forces this view to be laid out during the next layout pass. 16820 * This method does not call requestLayout() or forceLayout() 16821 * on the parent. 16822 */ 16823 public void forceLayout() { 16824 if (mMeasureCache != null) mMeasureCache.clear(); 16825 16826 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16827 mPrivateFlags |= PFLAG_INVALIDATED; 16828 } 16829 16830 /** 16831 * <p> 16832 * This is called to find out how big a view should be. The parent 16833 * supplies constraint information in the width and height parameters. 16834 * </p> 16835 * 16836 * <p> 16837 * The actual measurement work of a view is performed in 16838 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16839 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16840 * </p> 16841 * 16842 * 16843 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16844 * parent 16845 * @param heightMeasureSpec Vertical space requirements as imposed by the 16846 * parent 16847 * 16848 * @see #onMeasure(int, int) 16849 */ 16850 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16851 boolean optical = isLayoutModeOptical(this); 16852 if (optical != isLayoutModeOptical(mParent)) { 16853 Insets insets = getOpticalInsets(); 16854 int oWidth = insets.left + insets.right; 16855 int oHeight = insets.top + insets.bottom; 16856 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 16857 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 16858 } 16859 16860 // Suppress sign extension for the low bytes 16861 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 16862 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 16863 16864 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 16865 widthMeasureSpec != mOldWidthMeasureSpec || 16866 heightMeasureSpec != mOldHeightMeasureSpec) { 16867 16868 // first clears the measured dimension flag 16869 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 16870 16871 resolveRtlPropertiesIfNeeded(); 16872 16873 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 16874 mMeasureCache.indexOfKey(key); 16875 if (cacheIndex < 0 || sIgnoreMeasureCache) { 16876 // measure ourselves, this should set the measured dimension flag back 16877 onMeasure(widthMeasureSpec, heightMeasureSpec); 16878 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16879 } else { 16880 long value = mMeasureCache.valueAt(cacheIndex); 16881 // Casting a long to int drops the high 32 bits, no mask needed 16882 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 16883 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16884 } 16885 16886 // flag not set, setMeasuredDimension() was not invoked, we raise 16887 // an exception to warn the developer 16888 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 16889 throw new IllegalStateException("onMeasure() did not set the" 16890 + " measured dimension by calling" 16891 + " setMeasuredDimension()"); 16892 } 16893 16894 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 16895 } 16896 16897 mOldWidthMeasureSpec = widthMeasureSpec; 16898 mOldHeightMeasureSpec = heightMeasureSpec; 16899 16900 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 16901 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 16902 } 16903 16904 /** 16905 * <p> 16906 * Measure the view and its content to determine the measured width and the 16907 * measured height. This method is invoked by {@link #measure(int, int)} and 16908 * should be overriden by subclasses to provide accurate and efficient 16909 * measurement of their contents. 16910 * </p> 16911 * 16912 * <p> 16913 * <strong>CONTRACT:</strong> When overriding this method, you 16914 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 16915 * measured width and height of this view. Failure to do so will trigger an 16916 * <code>IllegalStateException</code>, thrown by 16917 * {@link #measure(int, int)}. Calling the superclass' 16918 * {@link #onMeasure(int, int)} is a valid use. 16919 * </p> 16920 * 16921 * <p> 16922 * The base class implementation of measure defaults to the background size, 16923 * unless a larger size is allowed by the MeasureSpec. Subclasses should 16924 * override {@link #onMeasure(int, int)} to provide better measurements of 16925 * their content. 16926 * </p> 16927 * 16928 * <p> 16929 * If this method is overridden, it is the subclass's responsibility to make 16930 * sure the measured height and width are at least the view's minimum height 16931 * and width ({@link #getSuggestedMinimumHeight()} and 16932 * {@link #getSuggestedMinimumWidth()}). 16933 * </p> 16934 * 16935 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 16936 * The requirements are encoded with 16937 * {@link android.view.View.MeasureSpec}. 16938 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 16939 * The requirements are encoded with 16940 * {@link android.view.View.MeasureSpec}. 16941 * 16942 * @see #getMeasuredWidth() 16943 * @see #getMeasuredHeight() 16944 * @see #setMeasuredDimension(int, int) 16945 * @see #getSuggestedMinimumHeight() 16946 * @see #getSuggestedMinimumWidth() 16947 * @see android.view.View.MeasureSpec#getMode(int) 16948 * @see android.view.View.MeasureSpec#getSize(int) 16949 */ 16950 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 16951 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 16952 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 16953 } 16954 16955 /** 16956 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 16957 * measured width and measured height. Failing to do so will trigger an 16958 * exception at measurement time.</p> 16959 * 16960 * @param measuredWidth The measured width of this view. May be a complex 16961 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16962 * {@link #MEASURED_STATE_TOO_SMALL}. 16963 * @param measuredHeight The measured height of this view. May be a complex 16964 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16965 * {@link #MEASURED_STATE_TOO_SMALL}. 16966 */ 16967 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 16968 boolean optical = isLayoutModeOptical(this); 16969 if (optical != isLayoutModeOptical(mParent)) { 16970 Insets insets = getOpticalInsets(); 16971 int opticalWidth = insets.left + insets.right; 16972 int opticalHeight = insets.top + insets.bottom; 16973 16974 measuredWidth += optical ? opticalWidth : -opticalWidth; 16975 measuredHeight += optical ? opticalHeight : -opticalHeight; 16976 } 16977 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 16978 } 16979 16980 /** 16981 * Sets the measured dimension without extra processing for things like optical bounds. 16982 * Useful for reapplying consistent values that have already been cooked with adjustments 16983 * for optical bounds, etc. such as those from the measurement cache. 16984 * 16985 * @param measuredWidth The measured width of this view. May be a complex 16986 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16987 * {@link #MEASURED_STATE_TOO_SMALL}. 16988 * @param measuredHeight The measured height of this view. May be a complex 16989 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16990 * {@link #MEASURED_STATE_TOO_SMALL}. 16991 */ 16992 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 16993 mMeasuredWidth = measuredWidth; 16994 mMeasuredHeight = measuredHeight; 16995 16996 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 16997 } 16998 16999 /** 17000 * Merge two states as returned by {@link #getMeasuredState()}. 17001 * @param curState The current state as returned from a view or the result 17002 * of combining multiple views. 17003 * @param newState The new view state to combine. 17004 * @return Returns a new integer reflecting the combination of the two 17005 * states. 17006 */ 17007 public static int combineMeasuredStates(int curState, int newState) { 17008 return curState | newState; 17009 } 17010 17011 /** 17012 * Version of {@link #resolveSizeAndState(int, int, int)} 17013 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17014 */ 17015 public static int resolveSize(int size, int measureSpec) { 17016 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17017 } 17018 17019 /** 17020 * Utility to reconcile a desired size and state, with constraints imposed 17021 * by a MeasureSpec. Will take the desired size, unless a different size 17022 * is imposed by the constraints. The returned value is a compound integer, 17023 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17024 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17025 * size is smaller than the size the view wants to be. 17026 * 17027 * @param size How big the view wants to be 17028 * @param measureSpec Constraints imposed by the parent 17029 * @return Size information bit mask as defined by 17030 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17031 */ 17032 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17033 int result = size; 17034 int specMode = MeasureSpec.getMode(measureSpec); 17035 int specSize = MeasureSpec.getSize(measureSpec); 17036 switch (specMode) { 17037 case MeasureSpec.UNSPECIFIED: 17038 result = size; 17039 break; 17040 case MeasureSpec.AT_MOST: 17041 if (specSize < size) { 17042 result = specSize | MEASURED_STATE_TOO_SMALL; 17043 } else { 17044 result = size; 17045 } 17046 break; 17047 case MeasureSpec.EXACTLY: 17048 result = specSize; 17049 break; 17050 } 17051 return result | (childMeasuredState&MEASURED_STATE_MASK); 17052 } 17053 17054 /** 17055 * Utility to return a default size. Uses the supplied size if the 17056 * MeasureSpec imposed no constraints. Will get larger if allowed 17057 * by the MeasureSpec. 17058 * 17059 * @param size Default size for this view 17060 * @param measureSpec Constraints imposed by the parent 17061 * @return The size this view should be. 17062 */ 17063 public static int getDefaultSize(int size, int measureSpec) { 17064 int result = size; 17065 int specMode = MeasureSpec.getMode(measureSpec); 17066 int specSize = MeasureSpec.getSize(measureSpec); 17067 17068 switch (specMode) { 17069 case MeasureSpec.UNSPECIFIED: 17070 result = size; 17071 break; 17072 case MeasureSpec.AT_MOST: 17073 case MeasureSpec.EXACTLY: 17074 result = specSize; 17075 break; 17076 } 17077 return result; 17078 } 17079 17080 /** 17081 * Returns the suggested minimum height that the view should use. This 17082 * returns the maximum of the view's minimum height 17083 * and the background's minimum height 17084 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17085 * <p> 17086 * When being used in {@link #onMeasure(int, int)}, the caller should still 17087 * ensure the returned height is within the requirements of the parent. 17088 * 17089 * @return The suggested minimum height of the view. 17090 */ 17091 protected int getSuggestedMinimumHeight() { 17092 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17093 17094 } 17095 17096 /** 17097 * Returns the suggested minimum width that the view should use. This 17098 * returns the maximum of the view's minimum width) 17099 * and the background's minimum width 17100 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17101 * <p> 17102 * When being used in {@link #onMeasure(int, int)}, the caller should still 17103 * ensure the returned width is within the requirements of the parent. 17104 * 17105 * @return The suggested minimum width of the view. 17106 */ 17107 protected int getSuggestedMinimumWidth() { 17108 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17109 } 17110 17111 /** 17112 * Returns the minimum height of the view. 17113 * 17114 * @return the minimum height the view will try to be. 17115 * 17116 * @see #setMinimumHeight(int) 17117 * 17118 * @attr ref android.R.styleable#View_minHeight 17119 */ 17120 public int getMinimumHeight() { 17121 return mMinHeight; 17122 } 17123 17124 /** 17125 * Sets the minimum height of the view. It is not guaranteed the view will 17126 * be able to achieve this minimum height (for example, if its parent layout 17127 * constrains it with less available height). 17128 * 17129 * @param minHeight The minimum height the view will try to be. 17130 * 17131 * @see #getMinimumHeight() 17132 * 17133 * @attr ref android.R.styleable#View_minHeight 17134 */ 17135 public void setMinimumHeight(int minHeight) { 17136 mMinHeight = minHeight; 17137 requestLayout(); 17138 } 17139 17140 /** 17141 * Returns the minimum width of the view. 17142 * 17143 * @return the minimum width the view will try to be. 17144 * 17145 * @see #setMinimumWidth(int) 17146 * 17147 * @attr ref android.R.styleable#View_minWidth 17148 */ 17149 public int getMinimumWidth() { 17150 return mMinWidth; 17151 } 17152 17153 /** 17154 * Sets the minimum width of the view. It is not guaranteed the view will 17155 * be able to achieve this minimum width (for example, if its parent layout 17156 * constrains it with less available width). 17157 * 17158 * @param minWidth The minimum width the view will try to be. 17159 * 17160 * @see #getMinimumWidth() 17161 * 17162 * @attr ref android.R.styleable#View_minWidth 17163 */ 17164 public void setMinimumWidth(int minWidth) { 17165 mMinWidth = minWidth; 17166 requestLayout(); 17167 17168 } 17169 17170 /** 17171 * Get the animation currently associated with this view. 17172 * 17173 * @return The animation that is currently playing or 17174 * scheduled to play for this view. 17175 */ 17176 public Animation getAnimation() { 17177 return mCurrentAnimation; 17178 } 17179 17180 /** 17181 * Start the specified animation now. 17182 * 17183 * @param animation the animation to start now 17184 */ 17185 public void startAnimation(Animation animation) { 17186 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17187 setAnimation(animation); 17188 invalidateParentCaches(); 17189 invalidate(true); 17190 } 17191 17192 /** 17193 * Cancels any animations for this view. 17194 */ 17195 public void clearAnimation() { 17196 if (mCurrentAnimation != null) { 17197 mCurrentAnimation.detach(); 17198 } 17199 mCurrentAnimation = null; 17200 invalidateParentIfNeeded(); 17201 } 17202 17203 /** 17204 * Sets the next animation to play for this view. 17205 * If you want the animation to play immediately, use 17206 * {@link #startAnimation(android.view.animation.Animation)} instead. 17207 * This method provides allows fine-grained 17208 * control over the start time and invalidation, but you 17209 * must make sure that 1) the animation has a start time set, and 17210 * 2) the view's parent (which controls animations on its children) 17211 * will be invalidated when the animation is supposed to 17212 * start. 17213 * 17214 * @param animation The next animation, or null. 17215 */ 17216 public void setAnimation(Animation animation) { 17217 mCurrentAnimation = animation; 17218 17219 if (animation != null) { 17220 // If the screen is off assume the animation start time is now instead of 17221 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17222 // would cause the animation to start when the screen turns back on 17223 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17224 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17225 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17226 } 17227 animation.reset(); 17228 } 17229 } 17230 17231 /** 17232 * Invoked by a parent ViewGroup to notify the start of the animation 17233 * currently associated with this view. If you override this method, 17234 * always call super.onAnimationStart(); 17235 * 17236 * @see #setAnimation(android.view.animation.Animation) 17237 * @see #getAnimation() 17238 */ 17239 protected void onAnimationStart() { 17240 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17241 } 17242 17243 /** 17244 * Invoked by a parent ViewGroup to notify the end of the animation 17245 * currently associated with this view. If you override this method, 17246 * always call super.onAnimationEnd(); 17247 * 17248 * @see #setAnimation(android.view.animation.Animation) 17249 * @see #getAnimation() 17250 */ 17251 protected void onAnimationEnd() { 17252 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17253 } 17254 17255 /** 17256 * Invoked if there is a Transform that involves alpha. Subclass that can 17257 * draw themselves with the specified alpha should return true, and then 17258 * respect that alpha when their onDraw() is called. If this returns false 17259 * then the view may be redirected to draw into an offscreen buffer to 17260 * fulfill the request, which will look fine, but may be slower than if the 17261 * subclass handles it internally. The default implementation returns false. 17262 * 17263 * @param alpha The alpha (0..255) to apply to the view's drawing 17264 * @return true if the view can draw with the specified alpha. 17265 */ 17266 protected boolean onSetAlpha(int alpha) { 17267 return false; 17268 } 17269 17270 /** 17271 * This is used by the RootView to perform an optimization when 17272 * the view hierarchy contains one or several SurfaceView. 17273 * SurfaceView is always considered transparent, but its children are not, 17274 * therefore all View objects remove themselves from the global transparent 17275 * region (passed as a parameter to this function). 17276 * 17277 * @param region The transparent region for this ViewAncestor (window). 17278 * 17279 * @return Returns true if the effective visibility of the view at this 17280 * point is opaque, regardless of the transparent region; returns false 17281 * if it is possible for underlying windows to be seen behind the view. 17282 * 17283 * {@hide} 17284 */ 17285 public boolean gatherTransparentRegion(Region region) { 17286 final AttachInfo attachInfo = mAttachInfo; 17287 if (region != null && attachInfo != null) { 17288 final int pflags = mPrivateFlags; 17289 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17290 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17291 // remove it from the transparent region. 17292 final int[] location = attachInfo.mTransparentLocation; 17293 getLocationInWindow(location); 17294 region.op(location[0], location[1], location[0] + mRight - mLeft, 17295 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17296 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 17297 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17298 // exists, so we remove the background drawable's non-transparent 17299 // parts from this transparent region. 17300 applyDrawableToTransparentRegion(mBackground, region); 17301 } 17302 } 17303 return true; 17304 } 17305 17306 /** 17307 * Play a sound effect for this view. 17308 * 17309 * <p>The framework will play sound effects for some built in actions, such as 17310 * clicking, but you may wish to play these effects in your widget, 17311 * for instance, for internal navigation. 17312 * 17313 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17314 * {@link #isSoundEffectsEnabled()} is true. 17315 * 17316 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17317 */ 17318 public void playSoundEffect(int soundConstant) { 17319 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17320 return; 17321 } 17322 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17323 } 17324 17325 /** 17326 * BZZZTT!!1! 17327 * 17328 * <p>Provide haptic feedback to the user for this view. 17329 * 17330 * <p>The framework will provide haptic feedback for some built in actions, 17331 * such as long presses, but you may wish to provide feedback for your 17332 * own widget. 17333 * 17334 * <p>The feedback will only be performed if 17335 * {@link #isHapticFeedbackEnabled()} is true. 17336 * 17337 * @param feedbackConstant One of the constants defined in 17338 * {@link HapticFeedbackConstants} 17339 */ 17340 public boolean performHapticFeedback(int feedbackConstant) { 17341 return performHapticFeedback(feedbackConstant, 0); 17342 } 17343 17344 /** 17345 * BZZZTT!!1! 17346 * 17347 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17348 * 17349 * @param feedbackConstant One of the constants defined in 17350 * {@link HapticFeedbackConstants} 17351 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17352 */ 17353 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17354 if (mAttachInfo == null) { 17355 return false; 17356 } 17357 //noinspection SimplifiableIfStatement 17358 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17359 && !isHapticFeedbackEnabled()) { 17360 return false; 17361 } 17362 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17363 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17364 } 17365 17366 /** 17367 * Request that the visibility of the status bar or other screen/window 17368 * decorations be changed. 17369 * 17370 * <p>This method is used to put the over device UI into temporary modes 17371 * where the user's attention is focused more on the application content, 17372 * by dimming or hiding surrounding system affordances. This is typically 17373 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17374 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17375 * to be placed behind the action bar (and with these flags other system 17376 * affordances) so that smooth transitions between hiding and showing them 17377 * can be done. 17378 * 17379 * <p>Two representative examples of the use of system UI visibility is 17380 * implementing a content browsing application (like a magazine reader) 17381 * and a video playing application. 17382 * 17383 * <p>The first code shows a typical implementation of a View in a content 17384 * browsing application. In this implementation, the application goes 17385 * into a content-oriented mode by hiding the status bar and action bar, 17386 * and putting the navigation elements into lights out mode. The user can 17387 * then interact with content while in this mode. Such an application should 17388 * provide an easy way for the user to toggle out of the mode (such as to 17389 * check information in the status bar or access notifications). In the 17390 * implementation here, this is done simply by tapping on the content. 17391 * 17392 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17393 * content} 17394 * 17395 * <p>This second code sample shows a typical implementation of a View 17396 * in a video playing application. In this situation, while the video is 17397 * playing the application would like to go into a complete full-screen mode, 17398 * to use as much of the display as possible for the video. When in this state 17399 * the user can not interact with the application; the system intercepts 17400 * touching on the screen to pop the UI out of full screen mode. See 17401 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17402 * 17403 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17404 * content} 17405 * 17406 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17407 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17408 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17409 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17410 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17411 */ 17412 public void setSystemUiVisibility(int visibility) { 17413 if (visibility != mSystemUiVisibility) { 17414 mSystemUiVisibility = visibility; 17415 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17416 mParent.recomputeViewAttributes(this); 17417 } 17418 } 17419 } 17420 17421 /** 17422 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17423 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17424 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17425 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17426 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17427 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17428 */ 17429 public int getSystemUiVisibility() { 17430 return mSystemUiVisibility; 17431 } 17432 17433 /** 17434 * Returns the current system UI visibility that is currently set for 17435 * the entire window. This is the combination of the 17436 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17437 * views in the window. 17438 */ 17439 public int getWindowSystemUiVisibility() { 17440 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17441 } 17442 17443 /** 17444 * Override to find out when the window's requested system UI visibility 17445 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17446 * This is different from the callbacks received through 17447 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17448 * in that this is only telling you about the local request of the window, 17449 * not the actual values applied by the system. 17450 */ 17451 public void onWindowSystemUiVisibilityChanged(int visible) { 17452 } 17453 17454 /** 17455 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17456 * the view hierarchy. 17457 */ 17458 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17459 onWindowSystemUiVisibilityChanged(visible); 17460 } 17461 17462 /** 17463 * Set a listener to receive callbacks when the visibility of the system bar changes. 17464 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17465 */ 17466 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17467 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17468 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17469 mParent.recomputeViewAttributes(this); 17470 } 17471 } 17472 17473 /** 17474 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17475 * the view hierarchy. 17476 */ 17477 public void dispatchSystemUiVisibilityChanged(int visibility) { 17478 ListenerInfo li = mListenerInfo; 17479 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17480 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17481 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17482 } 17483 } 17484 17485 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17486 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17487 if (val != mSystemUiVisibility) { 17488 setSystemUiVisibility(val); 17489 return true; 17490 } 17491 return false; 17492 } 17493 17494 /** @hide */ 17495 public void setDisabledSystemUiVisibility(int flags) { 17496 if (mAttachInfo != null) { 17497 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17498 mAttachInfo.mDisabledSystemUiVisibility = flags; 17499 if (mParent != null) { 17500 mParent.recomputeViewAttributes(this); 17501 } 17502 } 17503 } 17504 } 17505 17506 /** 17507 * Creates an image that the system displays during the drag and drop 17508 * operation. This is called a "drag shadow". The default implementation 17509 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17510 * appearance as the given View. The default also positions the center of the drag shadow 17511 * directly under the touch point. If no View is provided (the constructor with no parameters 17512 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17513 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17514 * default is an invisible drag shadow. 17515 * <p> 17516 * You are not required to use the View you provide to the constructor as the basis of the 17517 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17518 * anything you want as the drag shadow. 17519 * </p> 17520 * <p> 17521 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17522 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17523 * size and position of the drag shadow. It uses this data to construct a 17524 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17525 * so that your application can draw the shadow image in the Canvas. 17526 * </p> 17527 * 17528 * <div class="special reference"> 17529 * <h3>Developer Guides</h3> 17530 * <p>For a guide to implementing drag and drop features, read the 17531 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17532 * </div> 17533 */ 17534 public static class DragShadowBuilder { 17535 private final WeakReference<View> mView; 17536 17537 /** 17538 * Constructs a shadow image builder based on a View. By default, the resulting drag 17539 * shadow will have the same appearance and dimensions as the View, with the touch point 17540 * over the center of the View. 17541 * @param view A View. Any View in scope can be used. 17542 */ 17543 public DragShadowBuilder(View view) { 17544 mView = new WeakReference<View>(view); 17545 } 17546 17547 /** 17548 * Construct a shadow builder object with no associated View. This 17549 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17550 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17551 * to supply the drag shadow's dimensions and appearance without 17552 * reference to any View object. If they are not overridden, then the result is an 17553 * invisible drag shadow. 17554 */ 17555 public DragShadowBuilder() { 17556 mView = new WeakReference<View>(null); 17557 } 17558 17559 /** 17560 * Returns the View object that had been passed to the 17561 * {@link #View.DragShadowBuilder(View)} 17562 * constructor. If that View parameter was {@code null} or if the 17563 * {@link #View.DragShadowBuilder()} 17564 * constructor was used to instantiate the builder object, this method will return 17565 * null. 17566 * 17567 * @return The View object associate with this builder object. 17568 */ 17569 @SuppressWarnings({"JavadocReference"}) 17570 final public View getView() { 17571 return mView.get(); 17572 } 17573 17574 /** 17575 * Provides the metrics for the shadow image. These include the dimensions of 17576 * the shadow image, and the point within that shadow that should 17577 * be centered under the touch location while dragging. 17578 * <p> 17579 * The default implementation sets the dimensions of the shadow to be the 17580 * same as the dimensions of the View itself and centers the shadow under 17581 * the touch point. 17582 * </p> 17583 * 17584 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17585 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17586 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17587 * image. 17588 * 17589 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17590 * shadow image that should be underneath the touch point during the drag and drop 17591 * operation. Your application must set {@link android.graphics.Point#x} to the 17592 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17593 */ 17594 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17595 final View view = mView.get(); 17596 if (view != null) { 17597 shadowSize.set(view.getWidth(), view.getHeight()); 17598 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17599 } else { 17600 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17601 } 17602 } 17603 17604 /** 17605 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17606 * based on the dimensions it received from the 17607 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17608 * 17609 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17610 */ 17611 public void onDrawShadow(Canvas canvas) { 17612 final View view = mView.get(); 17613 if (view != null) { 17614 view.draw(canvas); 17615 } else { 17616 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17617 } 17618 } 17619 } 17620 17621 /** 17622 * Starts a drag and drop operation. When your application calls this method, it passes a 17623 * {@link android.view.View.DragShadowBuilder} object to the system. The 17624 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17625 * to get metrics for the drag shadow, and then calls the object's 17626 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17627 * <p> 17628 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17629 * drag events to all the View objects in your application that are currently visible. It does 17630 * this either by calling the View object's drag listener (an implementation of 17631 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17632 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17633 * Both are passed a {@link android.view.DragEvent} object that has a 17634 * {@link android.view.DragEvent#getAction()} value of 17635 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17636 * </p> 17637 * <p> 17638 * Your application can invoke startDrag() on any attached View object. The View object does not 17639 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17640 * be related to the View the user selected for dragging. 17641 * </p> 17642 * @param data A {@link android.content.ClipData} object pointing to the data to be 17643 * transferred by the drag and drop operation. 17644 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17645 * drag shadow. 17646 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17647 * drop operation. This Object is put into every DragEvent object sent by the system during the 17648 * current drag. 17649 * <p> 17650 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17651 * to the target Views. For example, it can contain flags that differentiate between a 17652 * a copy operation and a move operation. 17653 * </p> 17654 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17655 * so the parameter should be set to 0. 17656 * @return {@code true} if the method completes successfully, or 17657 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17658 * do a drag, and so no drag operation is in progress. 17659 */ 17660 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17661 Object myLocalState, int flags) { 17662 if (ViewDebug.DEBUG_DRAG) { 17663 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17664 } 17665 boolean okay = false; 17666 17667 Point shadowSize = new Point(); 17668 Point shadowTouchPoint = new Point(); 17669 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17670 17671 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17672 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17673 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17674 } 17675 17676 if (ViewDebug.DEBUG_DRAG) { 17677 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17678 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17679 } 17680 Surface surface = new Surface(); 17681 try { 17682 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17683 flags, shadowSize.x, shadowSize.y, surface); 17684 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17685 + " surface=" + surface); 17686 if (token != null) { 17687 Canvas canvas = surface.lockCanvas(null); 17688 try { 17689 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17690 shadowBuilder.onDrawShadow(canvas); 17691 } finally { 17692 surface.unlockCanvasAndPost(canvas); 17693 } 17694 17695 final ViewRootImpl root = getViewRootImpl(); 17696 17697 // Cache the local state object for delivery with DragEvents 17698 root.setLocalDragState(myLocalState); 17699 17700 // repurpose 'shadowSize' for the last touch point 17701 root.getLastTouchPoint(shadowSize); 17702 17703 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17704 shadowSize.x, shadowSize.y, 17705 shadowTouchPoint.x, shadowTouchPoint.y, data); 17706 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17707 17708 // Off and running! Release our local surface instance; the drag 17709 // shadow surface is now managed by the system process. 17710 surface.release(); 17711 } 17712 } catch (Exception e) { 17713 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17714 surface.destroy(); 17715 } 17716 17717 return okay; 17718 } 17719 17720 /** 17721 * Handles drag events sent by the system following a call to 17722 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17723 *<p> 17724 * When the system calls this method, it passes a 17725 * {@link android.view.DragEvent} object. A call to 17726 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17727 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17728 * operation. 17729 * @param event The {@link android.view.DragEvent} sent by the system. 17730 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17731 * in DragEvent, indicating the type of drag event represented by this object. 17732 * @return {@code true} if the method was successful, otherwise {@code false}. 17733 * <p> 17734 * The method should return {@code true} in response to an action type of 17735 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17736 * operation. 17737 * </p> 17738 * <p> 17739 * The method should also return {@code true} in response to an action type of 17740 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17741 * {@code false} if it didn't. 17742 * </p> 17743 */ 17744 public boolean onDragEvent(DragEvent event) { 17745 return false; 17746 } 17747 17748 /** 17749 * Detects if this View is enabled and has a drag event listener. 17750 * If both are true, then it calls the drag event listener with the 17751 * {@link android.view.DragEvent} it received. If the drag event listener returns 17752 * {@code true}, then dispatchDragEvent() returns {@code true}. 17753 * <p> 17754 * For all other cases, the method calls the 17755 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17756 * method and returns its result. 17757 * </p> 17758 * <p> 17759 * This ensures that a drag event is always consumed, even if the View does not have a drag 17760 * event listener. However, if the View has a listener and the listener returns true, then 17761 * onDragEvent() is not called. 17762 * </p> 17763 */ 17764 public boolean dispatchDragEvent(DragEvent event) { 17765 ListenerInfo li = mListenerInfo; 17766 //noinspection SimplifiableIfStatement 17767 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17768 && li.mOnDragListener.onDrag(this, event)) { 17769 return true; 17770 } 17771 return onDragEvent(event); 17772 } 17773 17774 boolean canAcceptDrag() { 17775 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17776 } 17777 17778 /** 17779 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17780 * it is ever exposed at all. 17781 * @hide 17782 */ 17783 public void onCloseSystemDialogs(String reason) { 17784 } 17785 17786 /** 17787 * Given a Drawable whose bounds have been set to draw into this view, 17788 * update a Region being computed for 17789 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17790 * that any non-transparent parts of the Drawable are removed from the 17791 * given transparent region. 17792 * 17793 * @param dr The Drawable whose transparency is to be applied to the region. 17794 * @param region A Region holding the current transparency information, 17795 * where any parts of the region that are set are considered to be 17796 * transparent. On return, this region will be modified to have the 17797 * transparency information reduced by the corresponding parts of the 17798 * Drawable that are not transparent. 17799 * {@hide} 17800 */ 17801 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17802 if (DBG) { 17803 Log.i("View", "Getting transparent region for: " + this); 17804 } 17805 final Region r = dr.getTransparentRegion(); 17806 final Rect db = dr.getBounds(); 17807 final AttachInfo attachInfo = mAttachInfo; 17808 if (r != null && attachInfo != null) { 17809 final int w = getRight()-getLeft(); 17810 final int h = getBottom()-getTop(); 17811 if (db.left > 0) { 17812 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17813 r.op(0, 0, db.left, h, Region.Op.UNION); 17814 } 17815 if (db.right < w) { 17816 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17817 r.op(db.right, 0, w, h, Region.Op.UNION); 17818 } 17819 if (db.top > 0) { 17820 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17821 r.op(0, 0, w, db.top, Region.Op.UNION); 17822 } 17823 if (db.bottom < h) { 17824 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17825 r.op(0, db.bottom, w, h, Region.Op.UNION); 17826 } 17827 final int[] location = attachInfo.mTransparentLocation; 17828 getLocationInWindow(location); 17829 r.translate(location[0], location[1]); 17830 region.op(r, Region.Op.INTERSECT); 17831 } else { 17832 region.op(db, Region.Op.DIFFERENCE); 17833 } 17834 } 17835 17836 private void checkForLongClick(int delayOffset) { 17837 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17838 mHasPerformedLongPress = false; 17839 17840 if (mPendingCheckForLongPress == null) { 17841 mPendingCheckForLongPress = new CheckForLongPress(); 17842 } 17843 mPendingCheckForLongPress.rememberWindowAttachCount(); 17844 postDelayed(mPendingCheckForLongPress, 17845 ViewConfiguration.getLongPressTimeout() - delayOffset); 17846 } 17847 } 17848 17849 /** 17850 * Inflate a view from an XML resource. This convenience method wraps the {@link 17851 * LayoutInflater} class, which provides a full range of options for view inflation. 17852 * 17853 * @param context The Context object for your activity or application. 17854 * @param resource The resource ID to inflate 17855 * @param root A view group that will be the parent. Used to properly inflate the 17856 * layout_* parameters. 17857 * @see LayoutInflater 17858 */ 17859 public static View inflate(Context context, int resource, ViewGroup root) { 17860 LayoutInflater factory = LayoutInflater.from(context); 17861 return factory.inflate(resource, root); 17862 } 17863 17864 /** 17865 * Scroll the view with standard behavior for scrolling beyond the normal 17866 * content boundaries. Views that call this method should override 17867 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 17868 * results of an over-scroll operation. 17869 * 17870 * Views can use this method to handle any touch or fling-based scrolling. 17871 * 17872 * @param deltaX Change in X in pixels 17873 * @param deltaY Change in Y in pixels 17874 * @param scrollX Current X scroll value in pixels before applying deltaX 17875 * @param scrollY Current Y scroll value in pixels before applying deltaY 17876 * @param scrollRangeX Maximum content scroll range along the X axis 17877 * @param scrollRangeY Maximum content scroll range along the Y axis 17878 * @param maxOverScrollX Number of pixels to overscroll by in either direction 17879 * along the X axis. 17880 * @param maxOverScrollY Number of pixels to overscroll by in either direction 17881 * along the Y axis. 17882 * @param isTouchEvent true if this scroll operation is the result of a touch event. 17883 * @return true if scrolling was clamped to an over-scroll boundary along either 17884 * axis, false otherwise. 17885 */ 17886 @SuppressWarnings({"UnusedParameters"}) 17887 protected boolean overScrollBy(int deltaX, int deltaY, 17888 int scrollX, int scrollY, 17889 int scrollRangeX, int scrollRangeY, 17890 int maxOverScrollX, int maxOverScrollY, 17891 boolean isTouchEvent) { 17892 final int overScrollMode = mOverScrollMode; 17893 final boolean canScrollHorizontal = 17894 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 17895 final boolean canScrollVertical = 17896 computeVerticalScrollRange() > computeVerticalScrollExtent(); 17897 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 17898 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 17899 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 17900 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 17901 17902 int newScrollX = scrollX + deltaX; 17903 if (!overScrollHorizontal) { 17904 maxOverScrollX = 0; 17905 } 17906 17907 int newScrollY = scrollY + deltaY; 17908 if (!overScrollVertical) { 17909 maxOverScrollY = 0; 17910 } 17911 17912 // Clamp values if at the limits and record 17913 final int left = -maxOverScrollX; 17914 final int right = maxOverScrollX + scrollRangeX; 17915 final int top = -maxOverScrollY; 17916 final int bottom = maxOverScrollY + scrollRangeY; 17917 17918 boolean clampedX = false; 17919 if (newScrollX > right) { 17920 newScrollX = right; 17921 clampedX = true; 17922 } else if (newScrollX < left) { 17923 newScrollX = left; 17924 clampedX = true; 17925 } 17926 17927 boolean clampedY = false; 17928 if (newScrollY > bottom) { 17929 newScrollY = bottom; 17930 clampedY = true; 17931 } else if (newScrollY < top) { 17932 newScrollY = top; 17933 clampedY = true; 17934 } 17935 17936 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 17937 17938 return clampedX || clampedY; 17939 } 17940 17941 /** 17942 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 17943 * respond to the results of an over-scroll operation. 17944 * 17945 * @param scrollX New X scroll value in pixels 17946 * @param scrollY New Y scroll value in pixels 17947 * @param clampedX True if scrollX was clamped to an over-scroll boundary 17948 * @param clampedY True if scrollY was clamped to an over-scroll boundary 17949 */ 17950 protected void onOverScrolled(int scrollX, int scrollY, 17951 boolean clampedX, boolean clampedY) { 17952 // Intentionally empty. 17953 } 17954 17955 /** 17956 * Returns the over-scroll mode for this view. The result will be 17957 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17958 * (allow over-scrolling only if the view content is larger than the container), 17959 * or {@link #OVER_SCROLL_NEVER}. 17960 * 17961 * @return This view's over-scroll mode. 17962 */ 17963 public int getOverScrollMode() { 17964 return mOverScrollMode; 17965 } 17966 17967 /** 17968 * Set the over-scroll mode for this view. Valid over-scroll modes are 17969 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17970 * (allow over-scrolling only if the view content is larger than the container), 17971 * or {@link #OVER_SCROLL_NEVER}. 17972 * 17973 * Setting the over-scroll mode of a view will have an effect only if the 17974 * view is capable of scrolling. 17975 * 17976 * @param overScrollMode The new over-scroll mode for this view. 17977 */ 17978 public void setOverScrollMode(int overScrollMode) { 17979 if (overScrollMode != OVER_SCROLL_ALWAYS && 17980 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 17981 overScrollMode != OVER_SCROLL_NEVER) { 17982 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 17983 } 17984 mOverScrollMode = overScrollMode; 17985 } 17986 17987 /** 17988 * Enable or disable nested scrolling for this view. 17989 * 17990 * <p>If this property is set to true the view will be permitted to initiate nested 17991 * scrolling operations with a compatible parent view in the current hierarchy. If this 17992 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 17993 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 17994 * the nested scroll.</p> 17995 * 17996 * @param enabled true to enable nested scrolling, false to disable 17997 * 17998 * @see #isNestedScrollingEnabled() 17999 */ 18000 public void setNestedScrollingEnabled(boolean enabled) { 18001 if (enabled) { 18002 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18003 } else { 18004 stopNestedScroll(); 18005 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18006 } 18007 } 18008 18009 /** 18010 * Returns true if nested scrolling is enabled for this view. 18011 * 18012 * <p>If nested scrolling is enabled and this View class implementation supports it, 18013 * this view will act as a nested scrolling child view when applicable, forwarding data 18014 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18015 * parent.</p> 18016 * 18017 * @return true if nested scrolling is enabled 18018 * 18019 * @see #setNestedScrollingEnabled(boolean) 18020 */ 18021 public boolean isNestedScrollingEnabled() { 18022 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18023 PFLAG3_NESTED_SCROLLING_ENABLED; 18024 } 18025 18026 /** 18027 * Begin a nestable scroll operation along the given axes. 18028 * 18029 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18030 * 18031 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18032 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18033 * In the case of touch scrolling the nested scroll will be terminated automatically in 18034 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18035 * In the event of programmatic scrolling the caller must explicitly call 18036 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18037 * 18038 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18039 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18040 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18041 * 18042 * <p>At each incremental step of the scroll the caller should invoke 18043 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18044 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18045 * parent at least partially consumed the scroll and the caller should adjust the amount it 18046 * scrolls by.</p> 18047 * 18048 * <p>After applying the remainder of the scroll delta the caller should invoke 18049 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18050 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18051 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18052 * </p> 18053 * 18054 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18055 * {@link #SCROLL_AXIS_VERTICAL}. 18056 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18057 * the current gesture. 18058 * 18059 * @see #stopNestedScroll() 18060 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18061 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18062 */ 18063 public boolean startNestedScroll(int axes) { 18064 if (hasNestedScrollingParent()) { 18065 // Already in progress 18066 return true; 18067 } 18068 if (isNestedScrollingEnabled()) { 18069 ViewParent p = getParent(); 18070 View child = this; 18071 while (p != null) { 18072 try { 18073 if (p.onStartNestedScroll(child, this, axes)) { 18074 mNestedScrollingParent = p; 18075 p.onNestedScrollAccepted(child, this, axes); 18076 return true; 18077 } 18078 } catch (AbstractMethodError e) { 18079 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18080 "method onStartNestedScroll", e); 18081 // Allow the search upward to continue 18082 } 18083 if (p instanceof View) { 18084 child = (View) p; 18085 } 18086 p = p.getParent(); 18087 } 18088 } 18089 return false; 18090 } 18091 18092 /** 18093 * Stop a nested scroll in progress. 18094 * 18095 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18096 * 18097 * @see #startNestedScroll(int) 18098 */ 18099 public void stopNestedScroll() { 18100 if (mNestedScrollingParent != null) { 18101 mNestedScrollingParent.onStopNestedScroll(this); 18102 mNestedScrollingParent = null; 18103 } 18104 } 18105 18106 /** 18107 * Returns true if this view has a nested scrolling parent. 18108 * 18109 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18110 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18111 * 18112 * @return whether this view has a nested scrolling parent 18113 */ 18114 public boolean hasNestedScrollingParent() { 18115 return mNestedScrollingParent != null; 18116 } 18117 18118 /** 18119 * Dispatch one step of a nested scroll in progress. 18120 * 18121 * <p>Implementations of views that support nested scrolling should call this to report 18122 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18123 * is not currently in progress or nested scrolling is not 18124 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18125 * 18126 * <p>Compatible View implementations should also call 18127 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18128 * consuming a component of the scroll event themselves.</p> 18129 * 18130 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18131 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18132 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18133 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18134 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18135 * in local view coordinates of this view from before this operation 18136 * to after it completes. View implementations may use this to adjust 18137 * expected input coordinate tracking. 18138 * @return true if the event was dispatched, false if it could not be dispatched. 18139 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18140 */ 18141 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18142 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18143 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18144 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18145 int startX = 0; 18146 int startY = 0; 18147 if (offsetInWindow != null) { 18148 getLocationInWindow(offsetInWindow); 18149 startX = offsetInWindow[0]; 18150 startY = offsetInWindow[1]; 18151 } 18152 18153 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18154 dxUnconsumed, dyUnconsumed); 18155 18156 if (offsetInWindow != null) { 18157 getLocationInWindow(offsetInWindow); 18158 offsetInWindow[0] -= startX; 18159 offsetInWindow[1] -= startY; 18160 } 18161 return true; 18162 } else if (offsetInWindow != null) { 18163 // No motion, no dispatch. Keep offsetInWindow up to date. 18164 offsetInWindow[0] = 0; 18165 offsetInWindow[1] = 0; 18166 } 18167 } 18168 return false; 18169 } 18170 18171 /** 18172 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18173 * 18174 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18175 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18176 * scrolling operation to consume some or all of the scroll operation before the child view 18177 * consumes it.</p> 18178 * 18179 * @param dx Horizontal scroll distance in pixels 18180 * @param dy Vertical scroll distance in pixels 18181 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18182 * and consumed[1] the consumed dy. 18183 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18184 * in local view coordinates of this view from before this operation 18185 * to after it completes. View implementations may use this to adjust 18186 * expected input coordinate tracking. 18187 * @return true if the parent consumed some or all of the scroll delta 18188 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18189 */ 18190 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18191 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18192 if (dx != 0 || dy != 0) { 18193 int startX = 0; 18194 int startY = 0; 18195 if (offsetInWindow != null) { 18196 getLocationInWindow(offsetInWindow); 18197 startX = offsetInWindow[0]; 18198 startY = offsetInWindow[1]; 18199 } 18200 18201 if (consumed == null) { 18202 if (mTempNestedScrollConsumed == null) { 18203 mTempNestedScrollConsumed = new int[2]; 18204 } 18205 consumed = mTempNestedScrollConsumed; 18206 } 18207 consumed[0] = 0; 18208 consumed[1] = 0; 18209 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18210 18211 if (offsetInWindow != null) { 18212 getLocationInWindow(offsetInWindow); 18213 offsetInWindow[0] -= startX; 18214 offsetInWindow[1] -= startY; 18215 } 18216 return consumed[0] != 0 || consumed[1] != 0; 18217 } else if (offsetInWindow != null) { 18218 offsetInWindow[0] = 0; 18219 offsetInWindow[1] = 0; 18220 } 18221 } 18222 return false; 18223 } 18224 18225 /** 18226 * Dispatch a fling to a nested scrolling parent. 18227 * 18228 * <p>This method should be used to indicate that a nested scrolling child has detected 18229 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18230 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18231 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18232 * along a scrollable axis.</p> 18233 * 18234 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18235 * its own content, it can use this method to delegate the fling to its nested scrolling 18236 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18237 * 18238 * @param velocityX Horizontal fling velocity in pixels per second 18239 * @param velocityY Vertical fling velocity in pixels per second 18240 * @param consumed true if the child consumed the fling, false otherwise 18241 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18242 */ 18243 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18244 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18245 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18246 } 18247 return false; 18248 } 18249 18250 /** 18251 * Gets a scale factor that determines the distance the view should scroll 18252 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18253 * @return The vertical scroll scale factor. 18254 * @hide 18255 */ 18256 protected float getVerticalScrollFactor() { 18257 if (mVerticalScrollFactor == 0) { 18258 TypedValue outValue = new TypedValue(); 18259 if (!mContext.getTheme().resolveAttribute( 18260 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18261 throw new IllegalStateException( 18262 "Expected theme to define listPreferredItemHeight."); 18263 } 18264 mVerticalScrollFactor = outValue.getDimension( 18265 mContext.getResources().getDisplayMetrics()); 18266 } 18267 return mVerticalScrollFactor; 18268 } 18269 18270 /** 18271 * Gets a scale factor that determines the distance the view should scroll 18272 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18273 * @return The horizontal scroll scale factor. 18274 * @hide 18275 */ 18276 protected float getHorizontalScrollFactor() { 18277 // TODO: Should use something else. 18278 return getVerticalScrollFactor(); 18279 } 18280 18281 /** 18282 * Return the value specifying the text direction or policy that was set with 18283 * {@link #setTextDirection(int)}. 18284 * 18285 * @return the defined text direction. It can be one of: 18286 * 18287 * {@link #TEXT_DIRECTION_INHERIT}, 18288 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18289 * {@link #TEXT_DIRECTION_ANY_RTL}, 18290 * {@link #TEXT_DIRECTION_LTR}, 18291 * {@link #TEXT_DIRECTION_RTL}, 18292 * {@link #TEXT_DIRECTION_LOCALE} 18293 * 18294 * @attr ref android.R.styleable#View_textDirection 18295 * 18296 * @hide 18297 */ 18298 @ViewDebug.ExportedProperty(category = "text", mapping = { 18299 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18300 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18301 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18302 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18303 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18304 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18305 }) 18306 public int getRawTextDirection() { 18307 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18308 } 18309 18310 /** 18311 * Set the text direction. 18312 * 18313 * @param textDirection the direction to set. Should be one of: 18314 * 18315 * {@link #TEXT_DIRECTION_INHERIT}, 18316 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18317 * {@link #TEXT_DIRECTION_ANY_RTL}, 18318 * {@link #TEXT_DIRECTION_LTR}, 18319 * {@link #TEXT_DIRECTION_RTL}, 18320 * {@link #TEXT_DIRECTION_LOCALE} 18321 * 18322 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18323 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18324 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18325 * 18326 * @attr ref android.R.styleable#View_textDirection 18327 */ 18328 public void setTextDirection(int textDirection) { 18329 if (getRawTextDirection() != textDirection) { 18330 // Reset the current text direction and the resolved one 18331 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18332 resetResolvedTextDirection(); 18333 // Set the new text direction 18334 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18335 // Do resolution 18336 resolveTextDirection(); 18337 // Notify change 18338 onRtlPropertiesChanged(getLayoutDirection()); 18339 // Refresh 18340 requestLayout(); 18341 invalidate(true); 18342 } 18343 } 18344 18345 /** 18346 * Return the resolved text direction. 18347 * 18348 * @return the resolved text direction. Returns one of: 18349 * 18350 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18351 * {@link #TEXT_DIRECTION_ANY_RTL}, 18352 * {@link #TEXT_DIRECTION_LTR}, 18353 * {@link #TEXT_DIRECTION_RTL}, 18354 * {@link #TEXT_DIRECTION_LOCALE} 18355 * 18356 * @attr ref android.R.styleable#View_textDirection 18357 */ 18358 @ViewDebug.ExportedProperty(category = "text", mapping = { 18359 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18360 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18361 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18362 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18363 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18364 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18365 }) 18366 public int getTextDirection() { 18367 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18368 } 18369 18370 /** 18371 * Resolve the text direction. 18372 * 18373 * @return true if resolution has been done, false otherwise. 18374 * 18375 * @hide 18376 */ 18377 public boolean resolveTextDirection() { 18378 // Reset any previous text direction resolution 18379 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18380 18381 if (hasRtlSupport()) { 18382 // Set resolved text direction flag depending on text direction flag 18383 final int textDirection = getRawTextDirection(); 18384 switch(textDirection) { 18385 case TEXT_DIRECTION_INHERIT: 18386 if (!canResolveTextDirection()) { 18387 // We cannot do the resolution if there is no parent, so use the default one 18388 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18389 // Resolution will need to happen again later 18390 return false; 18391 } 18392 18393 // Parent has not yet resolved, so we still return the default 18394 try { 18395 if (!mParent.isTextDirectionResolved()) { 18396 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18397 // Resolution will need to happen again later 18398 return false; 18399 } 18400 } catch (AbstractMethodError e) { 18401 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18402 " does not fully implement ViewParent", e); 18403 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18404 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18405 return true; 18406 } 18407 18408 // Set current resolved direction to the same value as the parent's one 18409 int parentResolvedDirection; 18410 try { 18411 parentResolvedDirection = mParent.getTextDirection(); 18412 } catch (AbstractMethodError e) { 18413 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18414 " does not fully implement ViewParent", e); 18415 parentResolvedDirection = TEXT_DIRECTION_LTR; 18416 } 18417 switch (parentResolvedDirection) { 18418 case TEXT_DIRECTION_FIRST_STRONG: 18419 case TEXT_DIRECTION_ANY_RTL: 18420 case TEXT_DIRECTION_LTR: 18421 case TEXT_DIRECTION_RTL: 18422 case TEXT_DIRECTION_LOCALE: 18423 mPrivateFlags2 |= 18424 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18425 break; 18426 default: 18427 // Default resolved direction is "first strong" heuristic 18428 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18429 } 18430 break; 18431 case TEXT_DIRECTION_FIRST_STRONG: 18432 case TEXT_DIRECTION_ANY_RTL: 18433 case TEXT_DIRECTION_LTR: 18434 case TEXT_DIRECTION_RTL: 18435 case TEXT_DIRECTION_LOCALE: 18436 // Resolved direction is the same as text direction 18437 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18438 break; 18439 default: 18440 // Default resolved direction is "first strong" heuristic 18441 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18442 } 18443 } else { 18444 // Default resolved direction is "first strong" heuristic 18445 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18446 } 18447 18448 // Set to resolved 18449 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18450 return true; 18451 } 18452 18453 /** 18454 * Check if text direction resolution can be done. 18455 * 18456 * @return true if text direction resolution can be done otherwise return false. 18457 */ 18458 public boolean canResolveTextDirection() { 18459 switch (getRawTextDirection()) { 18460 case TEXT_DIRECTION_INHERIT: 18461 if (mParent != null) { 18462 try { 18463 return mParent.canResolveTextDirection(); 18464 } catch (AbstractMethodError e) { 18465 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18466 " does not fully implement ViewParent", e); 18467 } 18468 } 18469 return false; 18470 18471 default: 18472 return true; 18473 } 18474 } 18475 18476 /** 18477 * Reset resolved text direction. Text direction will be resolved during a call to 18478 * {@link #onMeasure(int, int)}. 18479 * 18480 * @hide 18481 */ 18482 public void resetResolvedTextDirection() { 18483 // Reset any previous text direction resolution 18484 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18485 // Set to default value 18486 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18487 } 18488 18489 /** 18490 * @return true if text direction is inherited. 18491 * 18492 * @hide 18493 */ 18494 public boolean isTextDirectionInherited() { 18495 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18496 } 18497 18498 /** 18499 * @return true if text direction is resolved. 18500 */ 18501 public boolean isTextDirectionResolved() { 18502 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18503 } 18504 18505 /** 18506 * Return the value specifying the text alignment or policy that was set with 18507 * {@link #setTextAlignment(int)}. 18508 * 18509 * @return the defined text alignment. It can be one of: 18510 * 18511 * {@link #TEXT_ALIGNMENT_INHERIT}, 18512 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18513 * {@link #TEXT_ALIGNMENT_CENTER}, 18514 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18515 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18516 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18517 * {@link #TEXT_ALIGNMENT_VIEW_END} 18518 * 18519 * @attr ref android.R.styleable#View_textAlignment 18520 * 18521 * @hide 18522 */ 18523 @ViewDebug.ExportedProperty(category = "text", mapping = { 18524 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18525 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18526 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18527 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18528 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18529 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18530 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18531 }) 18532 @TextAlignment 18533 public int getRawTextAlignment() { 18534 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18535 } 18536 18537 /** 18538 * Set the text alignment. 18539 * 18540 * @param textAlignment The text alignment to set. Should be one of 18541 * 18542 * {@link #TEXT_ALIGNMENT_INHERIT}, 18543 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18544 * {@link #TEXT_ALIGNMENT_CENTER}, 18545 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18546 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18547 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18548 * {@link #TEXT_ALIGNMENT_VIEW_END} 18549 * 18550 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18551 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18552 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18553 * 18554 * @attr ref android.R.styleable#View_textAlignment 18555 */ 18556 public void setTextAlignment(@TextAlignment int textAlignment) { 18557 if (textAlignment != getRawTextAlignment()) { 18558 // Reset the current and resolved text alignment 18559 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18560 resetResolvedTextAlignment(); 18561 // Set the new text alignment 18562 mPrivateFlags2 |= 18563 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18564 // Do resolution 18565 resolveTextAlignment(); 18566 // Notify change 18567 onRtlPropertiesChanged(getLayoutDirection()); 18568 // Refresh 18569 requestLayout(); 18570 invalidate(true); 18571 } 18572 } 18573 18574 /** 18575 * Return the resolved text alignment. 18576 * 18577 * @return the resolved text alignment. Returns one of: 18578 * 18579 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18580 * {@link #TEXT_ALIGNMENT_CENTER}, 18581 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18582 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18583 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18584 * {@link #TEXT_ALIGNMENT_VIEW_END} 18585 * 18586 * @attr ref android.R.styleable#View_textAlignment 18587 */ 18588 @ViewDebug.ExportedProperty(category = "text", mapping = { 18589 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18590 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18591 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18592 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18593 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18594 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18595 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18596 }) 18597 @TextAlignment 18598 public int getTextAlignment() { 18599 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18600 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18601 } 18602 18603 /** 18604 * Resolve the text alignment. 18605 * 18606 * @return true if resolution has been done, false otherwise. 18607 * 18608 * @hide 18609 */ 18610 public boolean resolveTextAlignment() { 18611 // Reset any previous text alignment resolution 18612 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18613 18614 if (hasRtlSupport()) { 18615 // Set resolved text alignment flag depending on text alignment flag 18616 final int textAlignment = getRawTextAlignment(); 18617 switch (textAlignment) { 18618 case TEXT_ALIGNMENT_INHERIT: 18619 // Check if we can resolve the text alignment 18620 if (!canResolveTextAlignment()) { 18621 // We cannot do the resolution if there is no parent so use the default 18622 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18623 // Resolution will need to happen again later 18624 return false; 18625 } 18626 18627 // Parent has not yet resolved, so we still return the default 18628 try { 18629 if (!mParent.isTextAlignmentResolved()) { 18630 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18631 // Resolution will need to happen again later 18632 return false; 18633 } 18634 } catch (AbstractMethodError e) { 18635 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18636 " does not fully implement ViewParent", e); 18637 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18638 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18639 return true; 18640 } 18641 18642 int parentResolvedTextAlignment; 18643 try { 18644 parentResolvedTextAlignment = mParent.getTextAlignment(); 18645 } catch (AbstractMethodError e) { 18646 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18647 " does not fully implement ViewParent", e); 18648 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18649 } 18650 switch (parentResolvedTextAlignment) { 18651 case TEXT_ALIGNMENT_GRAVITY: 18652 case TEXT_ALIGNMENT_TEXT_START: 18653 case TEXT_ALIGNMENT_TEXT_END: 18654 case TEXT_ALIGNMENT_CENTER: 18655 case TEXT_ALIGNMENT_VIEW_START: 18656 case TEXT_ALIGNMENT_VIEW_END: 18657 // Resolved text alignment is the same as the parent resolved 18658 // text alignment 18659 mPrivateFlags2 |= 18660 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18661 break; 18662 default: 18663 // Use default resolved text alignment 18664 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18665 } 18666 break; 18667 case TEXT_ALIGNMENT_GRAVITY: 18668 case TEXT_ALIGNMENT_TEXT_START: 18669 case TEXT_ALIGNMENT_TEXT_END: 18670 case TEXT_ALIGNMENT_CENTER: 18671 case TEXT_ALIGNMENT_VIEW_START: 18672 case TEXT_ALIGNMENT_VIEW_END: 18673 // Resolved text alignment is the same as text alignment 18674 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18675 break; 18676 default: 18677 // Use default resolved text alignment 18678 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18679 } 18680 } else { 18681 // Use default resolved text alignment 18682 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18683 } 18684 18685 // Set the resolved 18686 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18687 return true; 18688 } 18689 18690 /** 18691 * Check if text alignment resolution can be done. 18692 * 18693 * @return true if text alignment resolution can be done otherwise return false. 18694 */ 18695 public boolean canResolveTextAlignment() { 18696 switch (getRawTextAlignment()) { 18697 case TEXT_DIRECTION_INHERIT: 18698 if (mParent != null) { 18699 try { 18700 return mParent.canResolveTextAlignment(); 18701 } catch (AbstractMethodError e) { 18702 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18703 " does not fully implement ViewParent", e); 18704 } 18705 } 18706 return false; 18707 18708 default: 18709 return true; 18710 } 18711 } 18712 18713 /** 18714 * Reset resolved text alignment. Text alignment will be resolved during a call to 18715 * {@link #onMeasure(int, int)}. 18716 * 18717 * @hide 18718 */ 18719 public void resetResolvedTextAlignment() { 18720 // Reset any previous text alignment resolution 18721 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18722 // Set to default 18723 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18724 } 18725 18726 /** 18727 * @return true if text alignment is inherited. 18728 * 18729 * @hide 18730 */ 18731 public boolean isTextAlignmentInherited() { 18732 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18733 } 18734 18735 /** 18736 * @return true if text alignment is resolved. 18737 */ 18738 public boolean isTextAlignmentResolved() { 18739 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18740 } 18741 18742 /** 18743 * Generate a value suitable for use in {@link #setId(int)}. 18744 * This value will not collide with ID values generated at build time by aapt for R.id. 18745 * 18746 * @return a generated ID value 18747 */ 18748 public static int generateViewId() { 18749 for (;;) { 18750 final int result = sNextGeneratedId.get(); 18751 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18752 int newValue = result + 1; 18753 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18754 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18755 return result; 18756 } 18757 } 18758 } 18759 18760 /** 18761 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 18762 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 18763 * a normal View or a ViewGroup with 18764 * {@link android.view.ViewGroup#isTransitionGroup()} true. 18765 * @hide 18766 */ 18767 public void captureTransitioningViews(List<View> transitioningViews) { 18768 if (getVisibility() == View.VISIBLE) { 18769 transitioningViews.add(this); 18770 } 18771 } 18772 18773 /** 18774 * Adds all Views that have {@link #getSharedElementName()} non-null to sharedElements. 18775 * @param sharedElements Will contain all Views in the hierarchy having a shared element name. 18776 * @hide 18777 */ 18778 public void findSharedElements(Map<String, View> sharedElements) { 18779 if (getVisibility() == VISIBLE) { 18780 String sharedElementName = getSharedElementName(); 18781 if (sharedElementName != null) { 18782 sharedElements.put(sharedElementName, this); 18783 } 18784 } 18785 } 18786 18787 // 18788 // Properties 18789 // 18790 /** 18791 * A Property wrapper around the <code>alpha</code> functionality handled by the 18792 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18793 */ 18794 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18795 @Override 18796 public void setValue(View object, float value) { 18797 object.setAlpha(value); 18798 } 18799 18800 @Override 18801 public Float get(View object) { 18802 return object.getAlpha(); 18803 } 18804 }; 18805 18806 /** 18807 * A Property wrapper around the <code>translationX</code> functionality handled by the 18808 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 18809 */ 18810 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 18811 @Override 18812 public void setValue(View object, float value) { 18813 object.setTranslationX(value); 18814 } 18815 18816 @Override 18817 public Float get(View object) { 18818 return object.getTranslationX(); 18819 } 18820 }; 18821 18822 /** 18823 * A Property wrapper around the <code>translationY</code> functionality handled by the 18824 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 18825 */ 18826 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 18827 @Override 18828 public void setValue(View object, float value) { 18829 object.setTranslationY(value); 18830 } 18831 18832 @Override 18833 public Float get(View object) { 18834 return object.getTranslationY(); 18835 } 18836 }; 18837 18838 /** 18839 * A Property wrapper around the <code>translationZ</code> functionality handled by the 18840 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 18841 */ 18842 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 18843 @Override 18844 public void setValue(View object, float value) { 18845 object.setTranslationZ(value); 18846 } 18847 18848 @Override 18849 public Float get(View object) { 18850 return object.getTranslationZ(); 18851 } 18852 }; 18853 18854 /** 18855 * A Property wrapper around the <code>x</code> functionality handled by the 18856 * {@link View#setX(float)} and {@link View#getX()} methods. 18857 */ 18858 public static final Property<View, Float> X = new FloatProperty<View>("x") { 18859 @Override 18860 public void setValue(View object, float value) { 18861 object.setX(value); 18862 } 18863 18864 @Override 18865 public Float get(View object) { 18866 return object.getX(); 18867 } 18868 }; 18869 18870 /** 18871 * A Property wrapper around the <code>y</code> functionality handled by the 18872 * {@link View#setY(float)} and {@link View#getY()} methods. 18873 */ 18874 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 18875 @Override 18876 public void setValue(View object, float value) { 18877 object.setY(value); 18878 } 18879 18880 @Override 18881 public Float get(View object) { 18882 return object.getY(); 18883 } 18884 }; 18885 18886 /** 18887 * A Property wrapper around the <code>z</code> functionality handled by the 18888 * {@link View#setZ(float)} and {@link View#getZ()} methods. 18889 */ 18890 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 18891 @Override 18892 public void setValue(View object, float value) { 18893 object.setZ(value); 18894 } 18895 18896 @Override 18897 public Float get(View object) { 18898 return object.getZ(); 18899 } 18900 }; 18901 18902 /** 18903 * A Property wrapper around the <code>rotation</code> functionality handled by the 18904 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 18905 */ 18906 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 18907 @Override 18908 public void setValue(View object, float value) { 18909 object.setRotation(value); 18910 } 18911 18912 @Override 18913 public Float get(View object) { 18914 return object.getRotation(); 18915 } 18916 }; 18917 18918 /** 18919 * A Property wrapper around the <code>rotationX</code> functionality handled by the 18920 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 18921 */ 18922 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 18923 @Override 18924 public void setValue(View object, float value) { 18925 object.setRotationX(value); 18926 } 18927 18928 @Override 18929 public Float get(View object) { 18930 return object.getRotationX(); 18931 } 18932 }; 18933 18934 /** 18935 * A Property wrapper around the <code>rotationY</code> functionality handled by the 18936 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 18937 */ 18938 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 18939 @Override 18940 public void setValue(View object, float value) { 18941 object.setRotationY(value); 18942 } 18943 18944 @Override 18945 public Float get(View object) { 18946 return object.getRotationY(); 18947 } 18948 }; 18949 18950 /** 18951 * A Property wrapper around the <code>scaleX</code> functionality handled by the 18952 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 18953 */ 18954 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 18955 @Override 18956 public void setValue(View object, float value) { 18957 object.setScaleX(value); 18958 } 18959 18960 @Override 18961 public Float get(View object) { 18962 return object.getScaleX(); 18963 } 18964 }; 18965 18966 /** 18967 * A Property wrapper around the <code>scaleY</code> functionality handled by the 18968 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 18969 */ 18970 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 18971 @Override 18972 public void setValue(View object, float value) { 18973 object.setScaleY(value); 18974 } 18975 18976 @Override 18977 public Float get(View object) { 18978 return object.getScaleY(); 18979 } 18980 }; 18981 18982 /** 18983 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 18984 * Each MeasureSpec represents a requirement for either the width or the height. 18985 * A MeasureSpec is comprised of a size and a mode. There are three possible 18986 * modes: 18987 * <dl> 18988 * <dt>UNSPECIFIED</dt> 18989 * <dd> 18990 * The parent has not imposed any constraint on the child. It can be whatever size 18991 * it wants. 18992 * </dd> 18993 * 18994 * <dt>EXACTLY</dt> 18995 * <dd> 18996 * The parent has determined an exact size for the child. The child is going to be 18997 * given those bounds regardless of how big it wants to be. 18998 * </dd> 18999 * 19000 * <dt>AT_MOST</dt> 19001 * <dd> 19002 * The child can be as large as it wants up to the specified size. 19003 * </dd> 19004 * </dl> 19005 * 19006 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19007 * is provided to pack and unpack the <size, mode> tuple into the int. 19008 */ 19009 public static class MeasureSpec { 19010 private static final int MODE_SHIFT = 30; 19011 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19012 19013 /** 19014 * Measure specification mode: The parent has not imposed any constraint 19015 * on the child. It can be whatever size it wants. 19016 */ 19017 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19018 19019 /** 19020 * Measure specification mode: The parent has determined an exact size 19021 * for the child. The child is going to be given those bounds regardless 19022 * of how big it wants to be. 19023 */ 19024 public static final int EXACTLY = 1 << MODE_SHIFT; 19025 19026 /** 19027 * Measure specification mode: The child can be as large as it wants up 19028 * to the specified size. 19029 */ 19030 public static final int AT_MOST = 2 << MODE_SHIFT; 19031 19032 /** 19033 * Creates a measure specification based on the supplied size and mode. 19034 * 19035 * The mode must always be one of the following: 19036 * <ul> 19037 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19038 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19039 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19040 * </ul> 19041 * 19042 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19043 * implementation was such that the order of arguments did not matter 19044 * and overflow in either value could impact the resulting MeasureSpec. 19045 * {@link android.widget.RelativeLayout} was affected by this bug. 19046 * Apps targeting API levels greater than 17 will get the fixed, more strict 19047 * behavior.</p> 19048 * 19049 * @param size the size of the measure specification 19050 * @param mode the mode of the measure specification 19051 * @return the measure specification based on size and mode 19052 */ 19053 public static int makeMeasureSpec(int size, int mode) { 19054 if (sUseBrokenMakeMeasureSpec) { 19055 return size + mode; 19056 } else { 19057 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19058 } 19059 } 19060 19061 /** 19062 * Extracts the mode from the supplied measure specification. 19063 * 19064 * @param measureSpec the measure specification to extract the mode from 19065 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19066 * {@link android.view.View.MeasureSpec#AT_MOST} or 19067 * {@link android.view.View.MeasureSpec#EXACTLY} 19068 */ 19069 public static int getMode(int measureSpec) { 19070 return (measureSpec & MODE_MASK); 19071 } 19072 19073 /** 19074 * Extracts the size from the supplied measure specification. 19075 * 19076 * @param measureSpec the measure specification to extract the size from 19077 * @return the size in pixels defined in the supplied measure specification 19078 */ 19079 public static int getSize(int measureSpec) { 19080 return (measureSpec & ~MODE_MASK); 19081 } 19082 19083 static int adjust(int measureSpec, int delta) { 19084 final int mode = getMode(measureSpec); 19085 if (mode == UNSPECIFIED) { 19086 // No need to adjust size for UNSPECIFIED mode. 19087 return makeMeasureSpec(0, UNSPECIFIED); 19088 } 19089 int size = getSize(measureSpec) + delta; 19090 if (size < 0) { 19091 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19092 ") spec: " + toString(measureSpec) + " delta: " + delta); 19093 size = 0; 19094 } 19095 return makeMeasureSpec(size, mode); 19096 } 19097 19098 /** 19099 * Returns a String representation of the specified measure 19100 * specification. 19101 * 19102 * @param measureSpec the measure specification to convert to a String 19103 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19104 */ 19105 public static String toString(int measureSpec) { 19106 int mode = getMode(measureSpec); 19107 int size = getSize(measureSpec); 19108 19109 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19110 19111 if (mode == UNSPECIFIED) 19112 sb.append("UNSPECIFIED "); 19113 else if (mode == EXACTLY) 19114 sb.append("EXACTLY "); 19115 else if (mode == AT_MOST) 19116 sb.append("AT_MOST "); 19117 else 19118 sb.append(mode).append(" "); 19119 19120 sb.append(size); 19121 return sb.toString(); 19122 } 19123 } 19124 19125 private final class CheckForLongPress implements Runnable { 19126 private int mOriginalWindowAttachCount; 19127 19128 @Override 19129 public void run() { 19130 if (isPressed() && (mParent != null) 19131 && mOriginalWindowAttachCount == mWindowAttachCount) { 19132 if (performLongClick()) { 19133 mHasPerformedLongPress = true; 19134 } 19135 } 19136 } 19137 19138 public void rememberWindowAttachCount() { 19139 mOriginalWindowAttachCount = mWindowAttachCount; 19140 } 19141 } 19142 19143 private final class CheckForTap implements Runnable { 19144 public float x; 19145 public float y; 19146 19147 @Override 19148 public void run() { 19149 mPrivateFlags &= ~PFLAG_PREPRESSED; 19150 setHotspot(R.attr.state_pressed, x, y); 19151 setPressed(true); 19152 checkForLongClick(ViewConfiguration.getTapTimeout()); 19153 } 19154 } 19155 19156 private final class PerformClick implements Runnable { 19157 @Override 19158 public void run() { 19159 performClick(); 19160 } 19161 } 19162 19163 /** @hide */ 19164 public void hackTurnOffWindowResizeAnim(boolean off) { 19165 mAttachInfo.mTurnOffWindowResizeAnim = off; 19166 } 19167 19168 /** 19169 * This method returns a ViewPropertyAnimator object, which can be used to animate 19170 * specific properties on this View. 19171 * 19172 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19173 */ 19174 public ViewPropertyAnimator animate() { 19175 if (mAnimator == null) { 19176 mAnimator = new ViewPropertyAnimator(this); 19177 } 19178 return mAnimator; 19179 } 19180 19181 /** 19182 * Specifies that the shared name of the View to be shared with another Activity. 19183 * When transitioning between Activities, the name links a UI element in the starting 19184 * Activity to UI element in the called Activity. Names should be unique in the 19185 * View hierarchy. 19186 * 19187 * @param sharedElementName The cross-Activity View identifier. The called Activity will use 19188 * the name to match the location with a View in its layout. 19189 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(android.os.Bundle) 19190 */ 19191 public void setSharedElementName(String sharedElementName) { 19192 setTagInternal(com.android.internal.R.id.shared_element_name, sharedElementName); 19193 } 19194 19195 /** 19196 * Returns the shared name of the View to be shared with another Activity. 19197 * When transitioning between Activities, the name links a UI element in the starting 19198 * Activity to UI element in the called Activity. Names should be unique in the 19199 * View hierarchy. 19200 * 19201 * <p>This returns null if the View is not a shared element or the name if it is.</p> 19202 * 19203 * @return The name used for this View for cross-Activity transitions or null if 19204 * this View has not been identified as shared. 19205 */ 19206 public String getSharedElementName() { 19207 return (String) getTag(com.android.internal.R.id.shared_element_name); 19208 } 19209 19210 /** 19211 * Interface definition for a callback to be invoked when a hardware key event is 19212 * dispatched to this view. The callback will be invoked before the key event is 19213 * given to the view. This is only useful for hardware keyboards; a software input 19214 * method has no obligation to trigger this listener. 19215 */ 19216 public interface OnKeyListener { 19217 /** 19218 * Called when a hardware key is dispatched to a view. This allows listeners to 19219 * get a chance to respond before the target view. 19220 * <p>Key presses in software keyboards will generally NOT trigger this method, 19221 * although some may elect to do so in some situations. Do not assume a 19222 * software input method has to be key-based; even if it is, it may use key presses 19223 * in a different way than you expect, so there is no way to reliably catch soft 19224 * input key presses. 19225 * 19226 * @param v The view the key has been dispatched to. 19227 * @param keyCode The code for the physical key that was pressed 19228 * @param event The KeyEvent object containing full information about 19229 * the event. 19230 * @return True if the listener has consumed the event, false otherwise. 19231 */ 19232 boolean onKey(View v, int keyCode, KeyEvent event); 19233 } 19234 19235 /** 19236 * Interface definition for a callback to be invoked when a touch event is 19237 * dispatched to this view. The callback will be invoked before the touch 19238 * event is given to the view. 19239 */ 19240 public interface OnTouchListener { 19241 /** 19242 * Called when a touch event is dispatched to a view. This allows listeners to 19243 * get a chance to respond before the target view. 19244 * 19245 * @param v The view the touch event has been dispatched to. 19246 * @param event The MotionEvent object containing full information about 19247 * the event. 19248 * @return True if the listener has consumed the event, false otherwise. 19249 */ 19250 boolean onTouch(View v, MotionEvent event); 19251 } 19252 19253 /** 19254 * Interface definition for a callback to be invoked when a hover event is 19255 * dispatched to this view. The callback will be invoked before the hover 19256 * event is given to the view. 19257 */ 19258 public interface OnHoverListener { 19259 /** 19260 * Called when a hover event is dispatched to a view. This allows listeners to 19261 * get a chance to respond before the target view. 19262 * 19263 * @param v The view the hover event has been dispatched to. 19264 * @param event The MotionEvent object containing full information about 19265 * the event. 19266 * @return True if the listener has consumed the event, false otherwise. 19267 */ 19268 boolean onHover(View v, MotionEvent event); 19269 } 19270 19271 /** 19272 * Interface definition for a callback to be invoked when a generic motion event is 19273 * dispatched to this view. The callback will be invoked before the generic motion 19274 * event is given to the view. 19275 */ 19276 public interface OnGenericMotionListener { 19277 /** 19278 * Called when a generic motion event is dispatched to a view. This allows listeners to 19279 * get a chance to respond before the target view. 19280 * 19281 * @param v The view the generic motion event has been dispatched to. 19282 * @param event The MotionEvent object containing full information about 19283 * the event. 19284 * @return True if the listener has consumed the event, false otherwise. 19285 */ 19286 boolean onGenericMotion(View v, MotionEvent event); 19287 } 19288 19289 /** 19290 * Interface definition for a callback to be invoked when a view has been clicked and held. 19291 */ 19292 public interface OnLongClickListener { 19293 /** 19294 * Called when a view has been clicked and held. 19295 * 19296 * @param v The view that was clicked and held. 19297 * 19298 * @return true if the callback consumed the long click, false otherwise. 19299 */ 19300 boolean onLongClick(View v); 19301 } 19302 19303 /** 19304 * Interface definition for a callback to be invoked when a drag is being dispatched 19305 * to this view. The callback will be invoked before the hosting view's own 19306 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19307 * onDrag(event) behavior, it should return 'false' from this callback. 19308 * 19309 * <div class="special reference"> 19310 * <h3>Developer Guides</h3> 19311 * <p>For a guide to implementing drag and drop features, read the 19312 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19313 * </div> 19314 */ 19315 public interface OnDragListener { 19316 /** 19317 * Called when a drag event is dispatched to a view. This allows listeners 19318 * to get a chance to override base View behavior. 19319 * 19320 * @param v The View that received the drag event. 19321 * @param event The {@link android.view.DragEvent} object for the drag event. 19322 * @return {@code true} if the drag event was handled successfully, or {@code false} 19323 * if the drag event was not handled. Note that {@code false} will trigger the View 19324 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19325 */ 19326 boolean onDrag(View v, DragEvent event); 19327 } 19328 19329 /** 19330 * Interface definition for a callback to be invoked when the focus state of 19331 * a view changed. 19332 */ 19333 public interface OnFocusChangeListener { 19334 /** 19335 * Called when the focus state of a view has changed. 19336 * 19337 * @param v The view whose state has changed. 19338 * @param hasFocus The new focus state of v. 19339 */ 19340 void onFocusChange(View v, boolean hasFocus); 19341 } 19342 19343 /** 19344 * Interface definition for a callback to be invoked when a view is clicked. 19345 */ 19346 public interface OnClickListener { 19347 /** 19348 * Called when a view has been clicked. 19349 * 19350 * @param v The view that was clicked. 19351 */ 19352 void onClick(View v); 19353 } 19354 19355 /** 19356 * Interface definition for a callback to be invoked when the context menu 19357 * for this view is being built. 19358 */ 19359 public interface OnCreateContextMenuListener { 19360 /** 19361 * Called when the context menu for this view is being built. It is not 19362 * safe to hold onto the menu after this method returns. 19363 * 19364 * @param menu The context menu that is being built 19365 * @param v The view for which the context menu is being built 19366 * @param menuInfo Extra information about the item for which the 19367 * context menu should be shown. This information will vary 19368 * depending on the class of v. 19369 */ 19370 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19371 } 19372 19373 /** 19374 * Interface definition for a callback to be invoked when the status bar changes 19375 * visibility. This reports <strong>global</strong> changes to the system UI 19376 * state, not what the application is requesting. 19377 * 19378 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19379 */ 19380 public interface OnSystemUiVisibilityChangeListener { 19381 /** 19382 * Called when the status bar changes visibility because of a call to 19383 * {@link View#setSystemUiVisibility(int)}. 19384 * 19385 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19386 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19387 * This tells you the <strong>global</strong> state of these UI visibility 19388 * flags, not what your app is currently applying. 19389 */ 19390 public void onSystemUiVisibilityChange(int visibility); 19391 } 19392 19393 /** 19394 * Interface definition for a callback to be invoked when this view is attached 19395 * or detached from its window. 19396 */ 19397 public interface OnAttachStateChangeListener { 19398 /** 19399 * Called when the view is attached to a window. 19400 * @param v The view that was attached 19401 */ 19402 public void onViewAttachedToWindow(View v); 19403 /** 19404 * Called when the view is detached from a window. 19405 * @param v The view that was detached 19406 */ 19407 public void onViewDetachedFromWindow(View v); 19408 } 19409 19410 /** 19411 * Listener for applying window insets on a view in a custom way. 19412 * 19413 * <p>Apps may choose to implement this interface if they want to apply custom policy 19414 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19415 * is set, its 19416 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19417 * method will be called instead of the View's own 19418 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19419 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19420 * the View's normal behavior as part of its own.</p> 19421 */ 19422 public interface OnApplyWindowInsetsListener { 19423 /** 19424 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19425 * on a View, this listener method will be called instead of the view's own 19426 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19427 * 19428 * @param v The view applying window insets 19429 * @param insets The insets to apply 19430 * @return The insets supplied, minus any insets that were consumed 19431 */ 19432 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19433 } 19434 19435 private final class UnsetPressedState implements Runnable { 19436 @Override 19437 public void run() { 19438 clearHotspot(R.attr.state_pressed); 19439 setPressed(false); 19440 } 19441 } 19442 19443 /** 19444 * Base class for derived classes that want to save and restore their own 19445 * state in {@link android.view.View#onSaveInstanceState()}. 19446 */ 19447 public static class BaseSavedState extends AbsSavedState { 19448 /** 19449 * Constructor used when reading from a parcel. Reads the state of the superclass. 19450 * 19451 * @param source 19452 */ 19453 public BaseSavedState(Parcel source) { 19454 super(source); 19455 } 19456 19457 /** 19458 * Constructor called by derived classes when creating their SavedState objects 19459 * 19460 * @param superState The state of the superclass of this view 19461 */ 19462 public BaseSavedState(Parcelable superState) { 19463 super(superState); 19464 } 19465 19466 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19467 new Parcelable.Creator<BaseSavedState>() { 19468 public BaseSavedState createFromParcel(Parcel in) { 19469 return new BaseSavedState(in); 19470 } 19471 19472 public BaseSavedState[] newArray(int size) { 19473 return new BaseSavedState[size]; 19474 } 19475 }; 19476 } 19477 19478 /** 19479 * A set of information given to a view when it is attached to its parent 19480 * window. 19481 */ 19482 final static class AttachInfo { 19483 interface Callbacks { 19484 void playSoundEffect(int effectId); 19485 boolean performHapticFeedback(int effectId, boolean always); 19486 } 19487 19488 /** 19489 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19490 * to a Handler. This class contains the target (View) to invalidate and 19491 * the coordinates of the dirty rectangle. 19492 * 19493 * For performance purposes, this class also implements a pool of up to 19494 * POOL_LIMIT objects that get reused. This reduces memory allocations 19495 * whenever possible. 19496 */ 19497 static class InvalidateInfo { 19498 private static final int POOL_LIMIT = 10; 19499 19500 private static final SynchronizedPool<InvalidateInfo> sPool = 19501 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19502 19503 View target; 19504 19505 int left; 19506 int top; 19507 int right; 19508 int bottom; 19509 19510 public static InvalidateInfo obtain() { 19511 InvalidateInfo instance = sPool.acquire(); 19512 return (instance != null) ? instance : new InvalidateInfo(); 19513 } 19514 19515 public void recycle() { 19516 target = null; 19517 sPool.release(this); 19518 } 19519 } 19520 19521 final IWindowSession mSession; 19522 19523 final IWindow mWindow; 19524 19525 final IBinder mWindowToken; 19526 19527 final Display mDisplay; 19528 19529 final Callbacks mRootCallbacks; 19530 19531 IWindowId mIWindowId; 19532 WindowId mWindowId; 19533 19534 /** 19535 * The top view of the hierarchy. 19536 */ 19537 View mRootView; 19538 19539 IBinder mPanelParentWindowToken; 19540 19541 boolean mHardwareAccelerated; 19542 boolean mHardwareAccelerationRequested; 19543 HardwareRenderer mHardwareRenderer; 19544 19545 /** 19546 * The state of the display to which the window is attached, as reported 19547 * by {@link Display#getState()}. Note that the display state constants 19548 * declared by {@link Display} do not exactly line up with the screen state 19549 * constants declared by {@link View} (there are more display states than 19550 * screen states). 19551 */ 19552 int mDisplayState = Display.STATE_UNKNOWN; 19553 19554 /** 19555 * Scale factor used by the compatibility mode 19556 */ 19557 float mApplicationScale; 19558 19559 /** 19560 * Indicates whether the application is in compatibility mode 19561 */ 19562 boolean mScalingRequired; 19563 19564 /** 19565 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19566 */ 19567 boolean mTurnOffWindowResizeAnim; 19568 19569 /** 19570 * Left position of this view's window 19571 */ 19572 int mWindowLeft; 19573 19574 /** 19575 * Top position of this view's window 19576 */ 19577 int mWindowTop; 19578 19579 /** 19580 * Indicates whether views need to use 32-bit drawing caches 19581 */ 19582 boolean mUse32BitDrawingCache; 19583 19584 /** 19585 * For windows that are full-screen but using insets to layout inside 19586 * of the screen areas, these are the current insets to appear inside 19587 * the overscan area of the display. 19588 */ 19589 final Rect mOverscanInsets = new Rect(); 19590 19591 /** 19592 * For windows that are full-screen but using insets to layout inside 19593 * of the screen decorations, these are the current insets for the 19594 * content of the window. 19595 */ 19596 final Rect mContentInsets = new Rect(); 19597 19598 /** 19599 * For windows that are full-screen but using insets to layout inside 19600 * of the screen decorations, these are the current insets for the 19601 * actual visible parts of the window. 19602 */ 19603 final Rect mVisibleInsets = new Rect(); 19604 19605 /** 19606 * The internal insets given by this window. This value is 19607 * supplied by the client (through 19608 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19609 * be given to the window manager when changed to be used in laying 19610 * out windows behind it. 19611 */ 19612 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19613 = new ViewTreeObserver.InternalInsetsInfo(); 19614 19615 /** 19616 * Set to true when mGivenInternalInsets is non-empty. 19617 */ 19618 boolean mHasNonEmptyGivenInternalInsets; 19619 19620 /** 19621 * All views in the window's hierarchy that serve as scroll containers, 19622 * used to determine if the window can be resized or must be panned 19623 * to adjust for a soft input area. 19624 */ 19625 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19626 19627 final KeyEvent.DispatcherState mKeyDispatchState 19628 = new KeyEvent.DispatcherState(); 19629 19630 /** 19631 * Indicates whether the view's window currently has the focus. 19632 */ 19633 boolean mHasWindowFocus; 19634 19635 /** 19636 * The current visibility of the window. 19637 */ 19638 int mWindowVisibility; 19639 19640 /** 19641 * Indicates the time at which drawing started to occur. 19642 */ 19643 long mDrawingTime; 19644 19645 /** 19646 * Indicates whether or not ignoring the DIRTY_MASK flags. 19647 */ 19648 boolean mIgnoreDirtyState; 19649 19650 /** 19651 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19652 * to avoid clearing that flag prematurely. 19653 */ 19654 boolean mSetIgnoreDirtyState = false; 19655 19656 /** 19657 * Indicates whether the view's window is currently in touch mode. 19658 */ 19659 boolean mInTouchMode; 19660 19661 /** 19662 * Indicates that ViewAncestor should trigger a global layout change 19663 * the next time it performs a traversal 19664 */ 19665 boolean mRecomputeGlobalAttributes; 19666 19667 /** 19668 * Always report new attributes at next traversal. 19669 */ 19670 boolean mForceReportNewAttributes; 19671 19672 /** 19673 * Set during a traveral if any views want to keep the screen on. 19674 */ 19675 boolean mKeepScreenOn; 19676 19677 /** 19678 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19679 */ 19680 int mSystemUiVisibility; 19681 19682 /** 19683 * Hack to force certain system UI visibility flags to be cleared. 19684 */ 19685 int mDisabledSystemUiVisibility; 19686 19687 /** 19688 * Last global system UI visibility reported by the window manager. 19689 */ 19690 int mGlobalSystemUiVisibility; 19691 19692 /** 19693 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19694 * attached. 19695 */ 19696 boolean mHasSystemUiListeners; 19697 19698 /** 19699 * Set if the window has requested to extend into the overscan region 19700 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19701 */ 19702 boolean mOverscanRequested; 19703 19704 /** 19705 * Set if the visibility of any views has changed. 19706 */ 19707 boolean mViewVisibilityChanged; 19708 19709 /** 19710 * Set to true if a view has been scrolled. 19711 */ 19712 boolean mViewScrollChanged; 19713 19714 /** 19715 * Global to the view hierarchy used as a temporary for dealing with 19716 * x/y points in the transparent region computations. 19717 */ 19718 final int[] mTransparentLocation = new int[2]; 19719 19720 /** 19721 * Global to the view hierarchy used as a temporary for dealing with 19722 * x/y points in the ViewGroup.invalidateChild implementation. 19723 */ 19724 final int[] mInvalidateChildLocation = new int[2]; 19725 19726 19727 /** 19728 * Global to the view hierarchy used as a temporary for dealing with 19729 * x/y location when view is transformed. 19730 */ 19731 final float[] mTmpTransformLocation = new float[2]; 19732 19733 /** 19734 * The view tree observer used to dispatch global events like 19735 * layout, pre-draw, touch mode change, etc. 19736 */ 19737 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19738 19739 /** 19740 * A Canvas used by the view hierarchy to perform bitmap caching. 19741 */ 19742 Canvas mCanvas; 19743 19744 /** 19745 * The view root impl. 19746 */ 19747 final ViewRootImpl mViewRootImpl; 19748 19749 /** 19750 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19751 * handler can be used to pump events in the UI events queue. 19752 */ 19753 final Handler mHandler; 19754 19755 /** 19756 * Temporary for use in computing invalidate rectangles while 19757 * calling up the hierarchy. 19758 */ 19759 final Rect mTmpInvalRect = new Rect(); 19760 19761 /** 19762 * Temporary for use in computing hit areas with transformed views 19763 */ 19764 final RectF mTmpTransformRect = new RectF(); 19765 19766 /** 19767 * Temporary for use in transforming invalidation rect 19768 */ 19769 final Matrix mTmpMatrix = new Matrix(); 19770 19771 /** 19772 * Temporary for use in transforming invalidation rect 19773 */ 19774 final Transformation mTmpTransformation = new Transformation(); 19775 19776 /** 19777 * Temporary list for use in collecting focusable descendents of a view. 19778 */ 19779 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19780 19781 /** 19782 * The id of the window for accessibility purposes. 19783 */ 19784 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 19785 19786 /** 19787 * Flags related to accessibility processing. 19788 * 19789 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 19790 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 19791 */ 19792 int mAccessibilityFetchFlags; 19793 19794 /** 19795 * The drawable for highlighting accessibility focus. 19796 */ 19797 Drawable mAccessibilityFocusDrawable; 19798 19799 /** 19800 * Show where the margins, bounds and layout bounds are for each view. 19801 */ 19802 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 19803 19804 /** 19805 * Point used to compute visible regions. 19806 */ 19807 final Point mPoint = new Point(); 19808 19809 /** 19810 * Used to track which View originated a requestLayout() call, used when 19811 * requestLayout() is called during layout. 19812 */ 19813 View mViewRequestingLayout; 19814 19815 /** 19816 * Creates a new set of attachment information with the specified 19817 * events handler and thread. 19818 * 19819 * @param handler the events handler the view must use 19820 */ 19821 AttachInfo(IWindowSession session, IWindow window, Display display, 19822 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 19823 mSession = session; 19824 mWindow = window; 19825 mWindowToken = window.asBinder(); 19826 mDisplay = display; 19827 mViewRootImpl = viewRootImpl; 19828 mHandler = handler; 19829 mRootCallbacks = effectPlayer; 19830 } 19831 } 19832 19833 /** 19834 * <p>ScrollabilityCache holds various fields used by a View when scrolling 19835 * is supported. This avoids keeping too many unused fields in most 19836 * instances of View.</p> 19837 */ 19838 private static class ScrollabilityCache implements Runnable { 19839 19840 /** 19841 * Scrollbars are not visible 19842 */ 19843 public static final int OFF = 0; 19844 19845 /** 19846 * Scrollbars are visible 19847 */ 19848 public static final int ON = 1; 19849 19850 /** 19851 * Scrollbars are fading away 19852 */ 19853 public static final int FADING = 2; 19854 19855 public boolean fadeScrollBars; 19856 19857 public int fadingEdgeLength; 19858 public int scrollBarDefaultDelayBeforeFade; 19859 public int scrollBarFadeDuration; 19860 19861 public int scrollBarSize; 19862 public ScrollBarDrawable scrollBar; 19863 public float[] interpolatorValues; 19864 public View host; 19865 19866 public final Paint paint; 19867 public final Matrix matrix; 19868 public Shader shader; 19869 19870 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 19871 19872 private static final float[] OPAQUE = { 255 }; 19873 private static final float[] TRANSPARENT = { 0.0f }; 19874 19875 /** 19876 * When fading should start. This time moves into the future every time 19877 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 19878 */ 19879 public long fadeStartTime; 19880 19881 19882 /** 19883 * The current state of the scrollbars: ON, OFF, or FADING 19884 */ 19885 public int state = OFF; 19886 19887 private int mLastColor; 19888 19889 public ScrollabilityCache(ViewConfiguration configuration, View host) { 19890 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 19891 scrollBarSize = configuration.getScaledScrollBarSize(); 19892 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 19893 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 19894 19895 paint = new Paint(); 19896 matrix = new Matrix(); 19897 // use use a height of 1, and then wack the matrix each time we 19898 // actually use it. 19899 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 19900 paint.setShader(shader); 19901 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 19902 19903 this.host = host; 19904 } 19905 19906 public void setFadeColor(int color) { 19907 if (color != mLastColor) { 19908 mLastColor = color; 19909 19910 if (color != 0) { 19911 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 19912 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 19913 paint.setShader(shader); 19914 // Restore the default transfer mode (src_over) 19915 paint.setXfermode(null); 19916 } else { 19917 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 19918 paint.setShader(shader); 19919 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 19920 } 19921 } 19922 } 19923 19924 public void run() { 19925 long now = AnimationUtils.currentAnimationTimeMillis(); 19926 if (now >= fadeStartTime) { 19927 19928 // the animation fades the scrollbars out by changing 19929 // the opacity (alpha) from fully opaque to fully 19930 // transparent 19931 int nextFrame = (int) now; 19932 int framesCount = 0; 19933 19934 Interpolator interpolator = scrollBarInterpolator; 19935 19936 // Start opaque 19937 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 19938 19939 // End transparent 19940 nextFrame += scrollBarFadeDuration; 19941 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 19942 19943 state = FADING; 19944 19945 // Kick off the fade animation 19946 host.invalidate(true); 19947 } 19948 } 19949 } 19950 19951 /** 19952 * Resuable callback for sending 19953 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 19954 */ 19955 private class SendViewScrolledAccessibilityEvent implements Runnable { 19956 public volatile boolean mIsPending; 19957 19958 public void run() { 19959 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 19960 mIsPending = false; 19961 } 19962 } 19963 19964 /** 19965 * <p> 19966 * This class represents a delegate that can be registered in a {@link View} 19967 * to enhance accessibility support via composition rather via inheritance. 19968 * It is specifically targeted to widget developers that extend basic View 19969 * classes i.e. classes in package android.view, that would like their 19970 * applications to be backwards compatible. 19971 * </p> 19972 * <div class="special reference"> 19973 * <h3>Developer Guides</h3> 19974 * <p>For more information about making applications accessible, read the 19975 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 19976 * developer guide.</p> 19977 * </div> 19978 * <p> 19979 * A scenario in which a developer would like to use an accessibility delegate 19980 * is overriding a method introduced in a later API version then the minimal API 19981 * version supported by the application. For example, the method 19982 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 19983 * in API version 4 when the accessibility APIs were first introduced. If a 19984 * developer would like his application to run on API version 4 devices (assuming 19985 * all other APIs used by the application are version 4 or lower) and take advantage 19986 * of this method, instead of overriding the method which would break the application's 19987 * backwards compatibility, he can override the corresponding method in this 19988 * delegate and register the delegate in the target View if the API version of 19989 * the system is high enough i.e. the API version is same or higher to the API 19990 * version that introduced 19991 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 19992 * </p> 19993 * <p> 19994 * Here is an example implementation: 19995 * </p> 19996 * <code><pre><p> 19997 * if (Build.VERSION.SDK_INT >= 14) { 19998 * // If the API version is equal of higher than the version in 19999 * // which onInitializeAccessibilityNodeInfo was introduced we 20000 * // register a delegate with a customized implementation. 20001 * View view = findViewById(R.id.view_id); 20002 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20003 * public void onInitializeAccessibilityNodeInfo(View host, 20004 * AccessibilityNodeInfo info) { 20005 * // Let the default implementation populate the info. 20006 * super.onInitializeAccessibilityNodeInfo(host, info); 20007 * // Set some other information. 20008 * info.setEnabled(host.isEnabled()); 20009 * } 20010 * }); 20011 * } 20012 * </code></pre></p> 20013 * <p> 20014 * This delegate contains methods that correspond to the accessibility methods 20015 * in View. If a delegate has been specified the implementation in View hands 20016 * off handling to the corresponding method in this delegate. The default 20017 * implementation the delegate methods behaves exactly as the corresponding 20018 * method in View for the case of no accessibility delegate been set. Hence, 20019 * to customize the behavior of a View method, clients can override only the 20020 * corresponding delegate method without altering the behavior of the rest 20021 * accessibility related methods of the host view. 20022 * </p> 20023 */ 20024 public static class AccessibilityDelegate { 20025 20026 /** 20027 * Sends an accessibility event of the given type. If accessibility is not 20028 * enabled this method has no effect. 20029 * <p> 20030 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20031 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20032 * been set. 20033 * </p> 20034 * 20035 * @param host The View hosting the delegate. 20036 * @param eventType The type of the event to send. 20037 * 20038 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20039 */ 20040 public void sendAccessibilityEvent(View host, int eventType) { 20041 host.sendAccessibilityEventInternal(eventType); 20042 } 20043 20044 /** 20045 * Performs the specified accessibility action on the view. For 20046 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20047 * <p> 20048 * The default implementation behaves as 20049 * {@link View#performAccessibilityAction(int, Bundle) 20050 * View#performAccessibilityAction(int, Bundle)} for the case of 20051 * no accessibility delegate been set. 20052 * </p> 20053 * 20054 * @param action The action to perform. 20055 * @return Whether the action was performed. 20056 * 20057 * @see View#performAccessibilityAction(int, Bundle) 20058 * View#performAccessibilityAction(int, Bundle) 20059 */ 20060 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20061 return host.performAccessibilityActionInternal(action, args); 20062 } 20063 20064 /** 20065 * Sends an accessibility event. This method behaves exactly as 20066 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20067 * empty {@link AccessibilityEvent} and does not perform a check whether 20068 * accessibility is enabled. 20069 * <p> 20070 * The default implementation behaves as 20071 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20072 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20073 * the case of no accessibility delegate been set. 20074 * </p> 20075 * 20076 * @param host The View hosting the delegate. 20077 * @param event The event to send. 20078 * 20079 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20080 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20081 */ 20082 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20083 host.sendAccessibilityEventUncheckedInternal(event); 20084 } 20085 20086 /** 20087 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20088 * to its children for adding their text content to the event. 20089 * <p> 20090 * The default implementation behaves as 20091 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20092 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20093 * the case of no accessibility delegate been set. 20094 * </p> 20095 * 20096 * @param host The View hosting the delegate. 20097 * @param event The event. 20098 * @return True if the event population was completed. 20099 * 20100 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20101 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20102 */ 20103 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20104 return host.dispatchPopulateAccessibilityEventInternal(event); 20105 } 20106 20107 /** 20108 * Gives a chance to the host View to populate the accessibility event with its 20109 * text content. 20110 * <p> 20111 * The default implementation behaves as 20112 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20113 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20114 * the case of no accessibility delegate been set. 20115 * </p> 20116 * 20117 * @param host The View hosting the delegate. 20118 * @param event The accessibility event which to populate. 20119 * 20120 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20121 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20122 */ 20123 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20124 host.onPopulateAccessibilityEventInternal(event); 20125 } 20126 20127 /** 20128 * Initializes an {@link AccessibilityEvent} with information about the 20129 * the host View which is the event source. 20130 * <p> 20131 * The default implementation behaves as 20132 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20133 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20134 * the case of no accessibility delegate been set. 20135 * </p> 20136 * 20137 * @param host The View hosting the delegate. 20138 * @param event The event to initialize. 20139 * 20140 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20141 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20142 */ 20143 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20144 host.onInitializeAccessibilityEventInternal(event); 20145 } 20146 20147 /** 20148 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20149 * <p> 20150 * The default implementation behaves as 20151 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20152 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20153 * the case of no accessibility delegate been set. 20154 * </p> 20155 * 20156 * @param host The View hosting the delegate. 20157 * @param info The instance to initialize. 20158 * 20159 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20160 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20161 */ 20162 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20163 host.onInitializeAccessibilityNodeInfoInternal(info); 20164 } 20165 20166 /** 20167 * Called when a child of the host View has requested sending an 20168 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20169 * to augment the event. 20170 * <p> 20171 * The default implementation behaves as 20172 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20173 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20174 * the case of no accessibility delegate been set. 20175 * </p> 20176 * 20177 * @param host The View hosting the delegate. 20178 * @param child The child which requests sending the event. 20179 * @param event The event to be sent. 20180 * @return True if the event should be sent 20181 * 20182 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20183 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20184 */ 20185 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20186 AccessibilityEvent event) { 20187 return host.onRequestSendAccessibilityEventInternal(child, event); 20188 } 20189 20190 /** 20191 * Gets the provider for managing a virtual view hierarchy rooted at this View 20192 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20193 * that explore the window content. 20194 * <p> 20195 * The default implementation behaves as 20196 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20197 * the case of no accessibility delegate been set. 20198 * </p> 20199 * 20200 * @return The provider. 20201 * 20202 * @see AccessibilityNodeProvider 20203 */ 20204 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20205 return null; 20206 } 20207 20208 /** 20209 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20210 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20211 * This method is responsible for obtaining an accessibility node info from a 20212 * pool of reusable instances and calling 20213 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20214 * view to initialize the former. 20215 * <p> 20216 * <strong>Note:</strong> The client is responsible for recycling the obtained 20217 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20218 * creation. 20219 * </p> 20220 * <p> 20221 * The default implementation behaves as 20222 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20223 * the case of no accessibility delegate been set. 20224 * </p> 20225 * @return A populated {@link AccessibilityNodeInfo}. 20226 * 20227 * @see AccessibilityNodeInfo 20228 * 20229 * @hide 20230 */ 20231 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20232 return host.createAccessibilityNodeInfoInternal(); 20233 } 20234 } 20235 20236 private class MatchIdPredicate implements Predicate<View> { 20237 public int mId; 20238 20239 @Override 20240 public boolean apply(View view) { 20241 return (view.mID == mId); 20242 } 20243 } 20244 20245 private class MatchLabelForPredicate implements Predicate<View> { 20246 private int mLabeledId; 20247 20248 @Override 20249 public boolean apply(View view) { 20250 return (view.mLabelForId == mLabeledId); 20251 } 20252 } 20253 20254 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20255 private int mChangeTypes = 0; 20256 private boolean mPosted; 20257 private boolean mPostedWithDelay; 20258 private long mLastEventTimeMillis; 20259 20260 @Override 20261 public void run() { 20262 mPosted = false; 20263 mPostedWithDelay = false; 20264 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20265 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20266 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20267 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20268 event.setContentChangeTypes(mChangeTypes); 20269 sendAccessibilityEventUnchecked(event); 20270 } 20271 mChangeTypes = 0; 20272 } 20273 20274 public void runOrPost(int changeType) { 20275 mChangeTypes |= changeType; 20276 20277 // If this is a live region or the child of a live region, collect 20278 // all events from this frame and send them on the next frame. 20279 if (inLiveRegion()) { 20280 // If we're already posted with a delay, remove that. 20281 if (mPostedWithDelay) { 20282 removeCallbacks(this); 20283 mPostedWithDelay = false; 20284 } 20285 // Only post if we're not already posted. 20286 if (!mPosted) { 20287 post(this); 20288 mPosted = true; 20289 } 20290 return; 20291 } 20292 20293 if (mPosted) { 20294 return; 20295 } 20296 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20297 final long minEventIntevalMillis = 20298 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20299 if (timeSinceLastMillis >= minEventIntevalMillis) { 20300 removeCallbacks(this); 20301 run(); 20302 } else { 20303 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20304 mPosted = true; 20305 mPostedWithDelay = true; 20306 } 20307 } 20308 } 20309 20310 private boolean inLiveRegion() { 20311 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20312 return true; 20313 } 20314 20315 ViewParent parent = getParent(); 20316 while (parent instanceof View) { 20317 if (((View) parent).getAccessibilityLiveRegion() 20318 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20319 return true; 20320 } 20321 parent = parent.getParent(); 20322 } 20323 20324 return false; 20325 } 20326 20327 /** 20328 * Dump all private flags in readable format, useful for documentation and 20329 * sanity checking. 20330 */ 20331 private static void dumpFlags() { 20332 final HashMap<String, String> found = Maps.newHashMap(); 20333 try { 20334 for (Field field : View.class.getDeclaredFields()) { 20335 final int modifiers = field.getModifiers(); 20336 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20337 if (field.getType().equals(int.class)) { 20338 final int value = field.getInt(null); 20339 dumpFlag(found, field.getName(), value); 20340 } else if (field.getType().equals(int[].class)) { 20341 final int[] values = (int[]) field.get(null); 20342 for (int i = 0; i < values.length; i++) { 20343 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20344 } 20345 } 20346 } 20347 } 20348 } catch (IllegalAccessException e) { 20349 throw new RuntimeException(e); 20350 } 20351 20352 final ArrayList<String> keys = Lists.newArrayList(); 20353 keys.addAll(found.keySet()); 20354 Collections.sort(keys); 20355 for (String key : keys) { 20356 Log.d(VIEW_LOG_TAG, found.get(key)); 20357 } 20358 } 20359 20360 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20361 // Sort flags by prefix, then by bits, always keeping unique keys 20362 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20363 final int prefix = name.indexOf('_'); 20364 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20365 final String output = bits + " " + name; 20366 found.put(key, output); 20367 } 20368} 20369