View.java revision 889fc94ffa70633e510e812b9da86723f4eee384
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.animation.AnimatorInflater; 20import android.animation.RevealAnimator; 21import android.animation.StateListAnimator; 22import android.animation.ValueAnimator; 23import android.annotation.IntDef; 24import android.annotation.NonNull; 25import android.annotation.Nullable; 26import android.content.ClipData; 27import android.content.Context; 28import android.content.res.ColorStateList; 29import android.content.res.Configuration; 30import android.content.res.Resources; 31import android.content.res.TypedArray; 32import android.graphics.Bitmap; 33import android.graphics.Canvas; 34import android.graphics.Insets; 35import android.graphics.Interpolator; 36import android.graphics.LinearGradient; 37import android.graphics.Matrix; 38import android.graphics.Outline; 39import android.graphics.Paint; 40import android.graphics.PixelFormat; 41import android.graphics.Point; 42import android.graphics.PorterDuff; 43import android.graphics.PorterDuffXfermode; 44import android.graphics.Rect; 45import android.graphics.RectF; 46import android.graphics.Region; 47import android.graphics.Shader; 48import android.graphics.drawable.ColorDrawable; 49import android.graphics.drawable.Drawable; 50import android.hardware.display.DisplayManagerGlobal; 51import android.os.Bundle; 52import android.os.Handler; 53import android.os.IBinder; 54import android.os.Parcel; 55import android.os.Parcelable; 56import android.os.RemoteException; 57import android.os.SystemClock; 58import android.os.SystemProperties; 59import android.text.TextUtils; 60import android.util.AttributeSet; 61import android.util.FloatProperty; 62import android.util.LayoutDirection; 63import android.util.Log; 64import android.util.LongSparseLongArray; 65import android.util.Pools.SynchronizedPool; 66import android.util.Property; 67import android.util.SparseArray; 68import android.util.SuperNotCalledException; 69import android.util.TypedValue; 70import android.view.ContextMenu.ContextMenuInfo; 71import android.view.AccessibilityIterators.TextSegmentIterator; 72import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 73import android.view.AccessibilityIterators.WordTextSegmentIterator; 74import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 75import android.view.accessibility.AccessibilityEvent; 76import android.view.accessibility.AccessibilityEventSource; 77import android.view.accessibility.AccessibilityManager; 78import android.view.accessibility.AccessibilityNodeInfo; 79import android.view.accessibility.AccessibilityNodeProvider; 80import android.view.animation.Animation; 81import android.view.animation.AnimationUtils; 82import android.view.animation.Transformation; 83import android.view.inputmethod.EditorInfo; 84import android.view.inputmethod.InputConnection; 85import android.view.inputmethod.InputMethodManager; 86import android.widget.ScrollBarDrawable; 87 88import static android.os.Build.VERSION_CODES.*; 89import static java.lang.Math.max; 90 91import com.android.internal.R; 92import com.android.internal.util.Predicate; 93import com.android.internal.view.menu.MenuBuilder; 94 95import com.google.android.collect.Lists; 96import com.google.android.collect.Maps; 97 98import java.lang.annotation.Retention; 99import java.lang.annotation.RetentionPolicy; 100import java.lang.ref.WeakReference; 101import java.lang.reflect.Field; 102import java.lang.reflect.InvocationTargetException; 103import java.lang.reflect.Method; 104import java.lang.reflect.Modifier; 105import java.util.ArrayList; 106import java.util.Arrays; 107import java.util.Collections; 108import java.util.HashMap; 109import java.util.List; 110import java.util.Locale; 111import java.util.Map; 112import java.util.concurrent.CopyOnWriteArrayList; 113import java.util.concurrent.atomic.AtomicInteger; 114 115/** 116 * <p> 117 * This class represents the basic building block for user interface components. A View 118 * occupies a rectangular area on the screen and is responsible for drawing and 119 * event handling. View is the base class for <em>widgets</em>, which are 120 * used to create interactive UI components (buttons, text fields, etc.). The 121 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 122 * are invisible containers that hold other Views (or other ViewGroups) and define 123 * their layout properties. 124 * </p> 125 * 126 * <div class="special reference"> 127 * <h3>Developer Guides</h3> 128 * <p>For information about using this class to develop your application's user interface, 129 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 130 * </div> 131 * 132 * <a name="Using"></a> 133 * <h3>Using Views</h3> 134 * <p> 135 * All of the views in a window are arranged in a single tree. You can add views 136 * either from code or by specifying a tree of views in one or more XML layout 137 * files. There are many specialized subclasses of views that act as controls or 138 * are capable of displaying text, images, or other content. 139 * </p> 140 * <p> 141 * Once you have created a tree of views, there are typically a few types of 142 * common operations you may wish to perform: 143 * <ul> 144 * <li><strong>Set properties:</strong> for example setting the text of a 145 * {@link android.widget.TextView}. The available properties and the methods 146 * that set them will vary among the different subclasses of views. Note that 147 * properties that are known at build time can be set in the XML layout 148 * files.</li> 149 * <li><strong>Set focus:</strong> The framework will handled moving focus in 150 * response to user input. To force focus to a specific view, call 151 * {@link #requestFocus}.</li> 152 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 153 * that will be notified when something interesting happens to the view. For 154 * example, all views will let you set a listener to be notified when the view 155 * gains or loses focus. You can register such a listener using 156 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 157 * Other view subclasses offer more specialized listeners. For example, a Button 158 * exposes a listener to notify clients when the button is clicked.</li> 159 * <li><strong>Set visibility:</strong> You can hide or show views using 160 * {@link #setVisibility(int)}.</li> 161 * </ul> 162 * </p> 163 * <p><em> 164 * Note: The Android framework is responsible for measuring, laying out and 165 * drawing views. You should not call methods that perform these actions on 166 * views yourself unless you are actually implementing a 167 * {@link android.view.ViewGroup}. 168 * </em></p> 169 * 170 * <a name="Lifecycle"></a> 171 * <h3>Implementing a Custom View</h3> 172 * 173 * <p> 174 * To implement a custom view, you will usually begin by providing overrides for 175 * some of the standard methods that the framework calls on all views. You do 176 * not need to override all of these methods. In fact, you can start by just 177 * overriding {@link #onDraw(android.graphics.Canvas)}. 178 * <table border="2" width="85%" align="center" cellpadding="5"> 179 * <thead> 180 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 181 * </thead> 182 * 183 * <tbody> 184 * <tr> 185 * <td rowspan="2">Creation</td> 186 * <td>Constructors</td> 187 * <td>There is a form of the constructor that are called when the view 188 * is created from code and a form that is called when the view is 189 * inflated from a layout file. The second form should parse and apply 190 * any attributes defined in the layout file. 191 * </td> 192 * </tr> 193 * <tr> 194 * <td><code>{@link #onFinishInflate()}</code></td> 195 * <td>Called after a view and all of its children has been inflated 196 * from XML.</td> 197 * </tr> 198 * 199 * <tr> 200 * <td rowspan="3">Layout</td> 201 * <td><code>{@link #onMeasure(int, int)}</code></td> 202 * <td>Called to determine the size requirements for this view and all 203 * of its children. 204 * </td> 205 * </tr> 206 * <tr> 207 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 208 * <td>Called when this view should assign a size and position to all 209 * of its children. 210 * </td> 211 * </tr> 212 * <tr> 213 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 214 * <td>Called when the size of this view has changed. 215 * </td> 216 * </tr> 217 * 218 * <tr> 219 * <td>Drawing</td> 220 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 221 * <td>Called when the view should render its content. 222 * </td> 223 * </tr> 224 * 225 * <tr> 226 * <td rowspan="4">Event processing</td> 227 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 228 * <td>Called when a new hardware key event occurs. 229 * </td> 230 * </tr> 231 * <tr> 232 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 233 * <td>Called when a hardware key up event occurs. 234 * </td> 235 * </tr> 236 * <tr> 237 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 238 * <td>Called when a trackball motion event occurs. 239 * </td> 240 * </tr> 241 * <tr> 242 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 243 * <td>Called when a touch screen motion event occurs. 244 * </td> 245 * </tr> 246 * 247 * <tr> 248 * <td rowspan="2">Focus</td> 249 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 250 * <td>Called when the view gains or loses focus. 251 * </td> 252 * </tr> 253 * 254 * <tr> 255 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 256 * <td>Called when the window containing the view gains or loses focus. 257 * </td> 258 * </tr> 259 * 260 * <tr> 261 * <td rowspan="3">Attaching</td> 262 * <td><code>{@link #onAttachedToWindow()}</code></td> 263 * <td>Called when the view is attached to a window. 264 * </td> 265 * </tr> 266 * 267 * <tr> 268 * <td><code>{@link #onDetachedFromWindow}</code></td> 269 * <td>Called when the view is detached from its window. 270 * </td> 271 * </tr> 272 * 273 * <tr> 274 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 275 * <td>Called when the visibility of the window containing the view 276 * has changed. 277 * </td> 278 * </tr> 279 * </tbody> 280 * 281 * </table> 282 * </p> 283 * 284 * <a name="IDs"></a> 285 * <h3>IDs</h3> 286 * Views may have an integer id associated with them. These ids are typically 287 * assigned in the layout XML files, and are used to find specific views within 288 * the view tree. A common pattern is to: 289 * <ul> 290 * <li>Define a Button in the layout file and assign it a unique ID. 291 * <pre> 292 * <Button 293 * android:id="@+id/my_button" 294 * android:layout_width="wrap_content" 295 * android:layout_height="wrap_content" 296 * android:text="@string/my_button_text"/> 297 * </pre></li> 298 * <li>From the onCreate method of an Activity, find the Button 299 * <pre class="prettyprint"> 300 * Button myButton = (Button) findViewById(R.id.my_button); 301 * </pre></li> 302 * </ul> 303 * <p> 304 * View IDs need not be unique throughout the tree, but it is good practice to 305 * ensure that they are at least unique within the part of the tree you are 306 * searching. 307 * </p> 308 * 309 * <a name="Position"></a> 310 * <h3>Position</h3> 311 * <p> 312 * The geometry of a view is that of a rectangle. A view has a location, 313 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 314 * two dimensions, expressed as a width and a height. The unit for location 315 * and dimensions is the pixel. 316 * </p> 317 * 318 * <p> 319 * It is possible to retrieve the location of a view by invoking the methods 320 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 321 * coordinate of the rectangle representing the view. The latter returns the 322 * top, or Y, coordinate of the rectangle representing the view. These methods 323 * both return the location of the view relative to its parent. For instance, 324 * when getLeft() returns 20, that means the view is located 20 pixels to the 325 * right of the left edge of its direct parent. 326 * </p> 327 * 328 * <p> 329 * In addition, several convenience methods are offered to avoid unnecessary 330 * computations, namely {@link #getRight()} and {@link #getBottom()}. 331 * These methods return the coordinates of the right and bottom edges of the 332 * rectangle representing the view. For instance, calling {@link #getRight()} 333 * is similar to the following computation: <code>getLeft() + getWidth()</code> 334 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 335 * </p> 336 * 337 * <a name="SizePaddingMargins"></a> 338 * <h3>Size, padding and margins</h3> 339 * <p> 340 * The size of a view is expressed with a width and a height. A view actually 341 * possess two pairs of width and height values. 342 * </p> 343 * 344 * <p> 345 * The first pair is known as <em>measured width</em> and 346 * <em>measured height</em>. These dimensions define how big a view wants to be 347 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 348 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 349 * and {@link #getMeasuredHeight()}. 350 * </p> 351 * 352 * <p> 353 * The second pair is simply known as <em>width</em> and <em>height</em>, or 354 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 355 * dimensions define the actual size of the view on screen, at drawing time and 356 * after layout. These values may, but do not have to, be different from the 357 * measured width and height. The width and height can be obtained by calling 358 * {@link #getWidth()} and {@link #getHeight()}. 359 * </p> 360 * 361 * <p> 362 * To measure its dimensions, a view takes into account its padding. The padding 363 * is expressed in pixels for the left, top, right and bottom parts of the view. 364 * Padding can be used to offset the content of the view by a specific amount of 365 * pixels. For instance, a left padding of 2 will push the view's content by 366 * 2 pixels to the right of the left edge. Padding can be set using the 367 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 368 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 369 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 370 * {@link #getPaddingEnd()}. 371 * </p> 372 * 373 * <p> 374 * Even though a view can define a padding, it does not provide any support for 375 * margins. However, view groups provide such a support. Refer to 376 * {@link android.view.ViewGroup} and 377 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 378 * </p> 379 * 380 * <a name="Layout"></a> 381 * <h3>Layout</h3> 382 * <p> 383 * Layout is a two pass process: a measure pass and a layout pass. The measuring 384 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 385 * of the view tree. Each view pushes dimension specifications down the tree 386 * during the recursion. At the end of the measure pass, every view has stored 387 * its measurements. The second pass happens in 388 * {@link #layout(int,int,int,int)} and is also top-down. During 389 * this pass each parent is responsible for positioning all of its children 390 * using the sizes computed in the measure pass. 391 * </p> 392 * 393 * <p> 394 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 395 * {@link #getMeasuredHeight()} values must be set, along with those for all of 396 * that view's descendants. A view's measured width and measured height values 397 * must respect the constraints imposed by the view's parents. This guarantees 398 * that at the end of the measure pass, all parents accept all of their 399 * children's measurements. A parent view may call measure() more than once on 400 * its children. For example, the parent may measure each child once with 401 * unspecified dimensions to find out how big they want to be, then call 402 * measure() on them again with actual numbers if the sum of all the children's 403 * unconstrained sizes is too big or too small. 404 * </p> 405 * 406 * <p> 407 * The measure pass uses two classes to communicate dimensions. The 408 * {@link MeasureSpec} class is used by views to tell their parents how they 409 * want to be measured and positioned. The base LayoutParams class just 410 * describes how big the view wants to be for both width and height. For each 411 * dimension, it can specify one of: 412 * <ul> 413 * <li> an exact number 414 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 415 * (minus padding) 416 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 417 * enclose its content (plus padding). 418 * </ul> 419 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 420 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 421 * an X and Y value. 422 * </p> 423 * 424 * <p> 425 * MeasureSpecs are used to push requirements down the tree from parent to 426 * child. A MeasureSpec can be in one of three modes: 427 * <ul> 428 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 429 * of a child view. For example, a LinearLayout may call measure() on its child 430 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 431 * tall the child view wants to be given a width of 240 pixels. 432 * <li>EXACTLY: This is used by the parent to impose an exact size on the 433 * child. The child must use this size, and guarantee that all of its 434 * descendants will fit within this size. 435 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 436 * child. The child must guarantee that it and all of its descendants will fit 437 * within this size. 438 * </ul> 439 * </p> 440 * 441 * <p> 442 * To intiate a layout, call {@link #requestLayout}. This method is typically 443 * called by a view on itself when it believes that is can no longer fit within 444 * its current bounds. 445 * </p> 446 * 447 * <a name="Drawing"></a> 448 * <h3>Drawing</h3> 449 * <p> 450 * Drawing is handled by walking the tree and rendering each view that 451 * intersects the invalid region. Because the tree is traversed in-order, 452 * this means that parents will draw before (i.e., behind) their children, with 453 * siblings drawn in the order they appear in the tree. 454 * If you set a background drawable for a View, then the View will draw it for you 455 * before calling back to its <code>onDraw()</code> method. 456 * </p> 457 * 458 * <p> 459 * Note that the framework will not draw views that are not in the invalid region. 460 * </p> 461 * 462 * <p> 463 * To force a view to draw, call {@link #invalidate()}. 464 * </p> 465 * 466 * <a name="EventHandlingThreading"></a> 467 * <h3>Event Handling and Threading</h3> 468 * <p> 469 * The basic cycle of a view is as follows: 470 * <ol> 471 * <li>An event comes in and is dispatched to the appropriate view. The view 472 * handles the event and notifies any listeners.</li> 473 * <li>If in the course of processing the event, the view's bounds may need 474 * to be changed, the view will call {@link #requestLayout()}.</li> 475 * <li>Similarly, if in the course of processing the event the view's appearance 476 * may need to be changed, the view will call {@link #invalidate()}.</li> 477 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 478 * the framework will take care of measuring, laying out, and drawing the tree 479 * as appropriate.</li> 480 * </ol> 481 * </p> 482 * 483 * <p><em>Note: The entire view tree is single threaded. You must always be on 484 * the UI thread when calling any method on any view.</em> 485 * If you are doing work on other threads and want to update the state of a view 486 * from that thread, you should use a {@link Handler}. 487 * </p> 488 * 489 * <a name="FocusHandling"></a> 490 * <h3>Focus Handling</h3> 491 * <p> 492 * The framework will handle routine focus movement in response to user input. 493 * This includes changing the focus as views are removed or hidden, or as new 494 * views become available. Views indicate their willingness to take focus 495 * through the {@link #isFocusable} method. To change whether a view can take 496 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 497 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 498 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 499 * </p> 500 * <p> 501 * Focus movement is based on an algorithm which finds the nearest neighbor in a 502 * given direction. In rare cases, the default algorithm may not match the 503 * intended behavior of the developer. In these situations, you can provide 504 * explicit overrides by using these XML attributes in the layout file: 505 * <pre> 506 * nextFocusDown 507 * nextFocusLeft 508 * nextFocusRight 509 * nextFocusUp 510 * </pre> 511 * </p> 512 * 513 * 514 * <p> 515 * To get a particular view to take focus, call {@link #requestFocus()}. 516 * </p> 517 * 518 * <a name="TouchMode"></a> 519 * <h3>Touch Mode</h3> 520 * <p> 521 * When a user is navigating a user interface via directional keys such as a D-pad, it is 522 * necessary to give focus to actionable items such as buttons so the user can see 523 * what will take input. If the device has touch capabilities, however, and the user 524 * begins interacting with the interface by touching it, it is no longer necessary to 525 * always highlight, or give focus to, a particular view. This motivates a mode 526 * for interaction named 'touch mode'. 527 * </p> 528 * <p> 529 * For a touch capable device, once the user touches the screen, the device 530 * will enter touch mode. From this point onward, only views for which 531 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 532 * Other views that are touchable, like buttons, will not take focus when touched; they will 533 * only fire the on click listeners. 534 * </p> 535 * <p> 536 * Any time a user hits a directional key, such as a D-pad direction, the view device will 537 * exit touch mode, and find a view to take focus, so that the user may resume interacting 538 * with the user interface without touching the screen again. 539 * </p> 540 * <p> 541 * The touch mode state is maintained across {@link android.app.Activity}s. Call 542 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 543 * </p> 544 * 545 * <a name="Scrolling"></a> 546 * <h3>Scrolling</h3> 547 * <p> 548 * The framework provides basic support for views that wish to internally 549 * scroll their content. This includes keeping track of the X and Y scroll 550 * offset as well as mechanisms for drawing scrollbars. See 551 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 552 * {@link #awakenScrollBars()} for more details. 553 * </p> 554 * 555 * <a name="Tags"></a> 556 * <h3>Tags</h3> 557 * <p> 558 * Unlike IDs, tags are not used to identify views. Tags are essentially an 559 * extra piece of information that can be associated with a view. They are most 560 * often used as a convenience to store data related to views in the views 561 * themselves rather than by putting them in a separate structure. 562 * </p> 563 * 564 * <a name="Properties"></a> 565 * <h3>Properties</h3> 566 * <p> 567 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 568 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 569 * available both in the {@link Property} form as well as in similarly-named setter/getter 570 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 571 * be used to set persistent state associated with these rendering-related properties on the view. 572 * The properties and methods can also be used in conjunction with 573 * {@link android.animation.Animator Animator}-based animations, described more in the 574 * <a href="#Animation">Animation</a> section. 575 * </p> 576 * 577 * <a name="Animation"></a> 578 * <h3>Animation</h3> 579 * <p> 580 * Starting with Android 3.0, the preferred way of animating views is to use the 581 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 582 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 583 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 584 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 585 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 586 * makes animating these View properties particularly easy and efficient. 587 * </p> 588 * <p> 589 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 590 * You can attach an {@link Animation} object to a view using 591 * {@link #setAnimation(Animation)} or 592 * {@link #startAnimation(Animation)}. The animation can alter the scale, 593 * rotation, translation and alpha of a view over time. If the animation is 594 * attached to a view that has children, the animation will affect the entire 595 * subtree rooted by that node. When an animation is started, the framework will 596 * take care of redrawing the appropriate views until the animation completes. 597 * </p> 598 * 599 * <a name="Security"></a> 600 * <h3>Security</h3> 601 * <p> 602 * Sometimes it is essential that an application be able to verify that an action 603 * is being performed with the full knowledge and consent of the user, such as 604 * granting a permission request, making a purchase or clicking on an advertisement. 605 * Unfortunately, a malicious application could try to spoof the user into 606 * performing these actions, unaware, by concealing the intended purpose of the view. 607 * As a remedy, the framework offers a touch filtering mechanism that can be used to 608 * improve the security of views that provide access to sensitive functionality. 609 * </p><p> 610 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 611 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 612 * will discard touches that are received whenever the view's window is obscured by 613 * another visible window. As a result, the view will not receive touches whenever a 614 * toast, dialog or other window appears above the view's window. 615 * </p><p> 616 * For more fine-grained control over security, consider overriding the 617 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 618 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 619 * </p> 620 * 621 * @attr ref android.R.styleable#View_alpha 622 * @attr ref android.R.styleable#View_background 623 * @attr ref android.R.styleable#View_clickable 624 * @attr ref android.R.styleable#View_contentDescription 625 * @attr ref android.R.styleable#View_drawingCacheQuality 626 * @attr ref android.R.styleable#View_duplicateParentState 627 * @attr ref android.R.styleable#View_id 628 * @attr ref android.R.styleable#View_requiresFadingEdge 629 * @attr ref android.R.styleable#View_fadeScrollbars 630 * @attr ref android.R.styleable#View_fadingEdgeLength 631 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 632 * @attr ref android.R.styleable#View_fitsSystemWindows 633 * @attr ref android.R.styleable#View_isScrollContainer 634 * @attr ref android.R.styleable#View_focusable 635 * @attr ref android.R.styleable#View_focusableInTouchMode 636 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 637 * @attr ref android.R.styleable#View_keepScreenOn 638 * @attr ref android.R.styleable#View_layerType 639 * @attr ref android.R.styleable#View_layoutDirection 640 * @attr ref android.R.styleable#View_longClickable 641 * @attr ref android.R.styleable#View_minHeight 642 * @attr ref android.R.styleable#View_minWidth 643 * @attr ref android.R.styleable#View_nextFocusDown 644 * @attr ref android.R.styleable#View_nextFocusLeft 645 * @attr ref android.R.styleable#View_nextFocusRight 646 * @attr ref android.R.styleable#View_nextFocusUp 647 * @attr ref android.R.styleable#View_onClick 648 * @attr ref android.R.styleable#View_padding 649 * @attr ref android.R.styleable#View_paddingBottom 650 * @attr ref android.R.styleable#View_paddingLeft 651 * @attr ref android.R.styleable#View_paddingRight 652 * @attr ref android.R.styleable#View_paddingTop 653 * @attr ref android.R.styleable#View_paddingStart 654 * @attr ref android.R.styleable#View_paddingEnd 655 * @attr ref android.R.styleable#View_saveEnabled 656 * @attr ref android.R.styleable#View_rotation 657 * @attr ref android.R.styleable#View_rotationX 658 * @attr ref android.R.styleable#View_rotationY 659 * @attr ref android.R.styleable#View_scaleX 660 * @attr ref android.R.styleable#View_scaleY 661 * @attr ref android.R.styleable#View_scrollX 662 * @attr ref android.R.styleable#View_scrollY 663 * @attr ref android.R.styleable#View_scrollbarSize 664 * @attr ref android.R.styleable#View_scrollbarStyle 665 * @attr ref android.R.styleable#View_scrollbars 666 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 667 * @attr ref android.R.styleable#View_scrollbarFadeDuration 668 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 669 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 670 * @attr ref android.R.styleable#View_scrollbarThumbVertical 671 * @attr ref android.R.styleable#View_scrollbarTrackVertical 672 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 673 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 674 * @attr ref android.R.styleable#View_stateListAnimator 675 * @attr ref android.R.styleable#View_transitionName 676 * @attr ref android.R.styleable#View_soundEffectsEnabled 677 * @attr ref android.R.styleable#View_tag 678 * @attr ref android.R.styleable#View_textAlignment 679 * @attr ref android.R.styleable#View_textDirection 680 * @attr ref android.R.styleable#View_transformPivotX 681 * @attr ref android.R.styleable#View_transformPivotY 682 * @attr ref android.R.styleable#View_translationX 683 * @attr ref android.R.styleable#View_translationY 684 * @attr ref android.R.styleable#View_translationZ 685 * @attr ref android.R.styleable#View_visibility 686 * 687 * @see android.view.ViewGroup 688 */ 689public class View implements Drawable.Callback, KeyEvent.Callback, 690 AccessibilityEventSource { 691 private static final boolean DBG = false; 692 693 /** 694 * The logging tag used by this class with android.util.Log. 695 */ 696 protected static final String VIEW_LOG_TAG = "View"; 697 698 /** 699 * When set to true, apps will draw debugging information about their layouts. 700 * 701 * @hide 702 */ 703 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 704 705 /** 706 * Used to mark a View that has no ID. 707 */ 708 public static final int NO_ID = -1; 709 710 /** 711 * Signals that compatibility booleans have been initialized according to 712 * target SDK versions. 713 */ 714 private static boolean sCompatibilityDone = false; 715 716 /** 717 * Use the old (broken) way of building MeasureSpecs. 718 */ 719 private static boolean sUseBrokenMakeMeasureSpec = false; 720 721 /** 722 * Ignore any optimizations using the measure cache. 723 */ 724 private static boolean sIgnoreMeasureCache = false; 725 726 /** 727 * Ignore the clipBounds of this view for the children. 728 */ 729 static boolean sIgnoreClipBoundsForChildren = false; 730 731 /** 732 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 733 * calling setFlags. 734 */ 735 private static final int NOT_FOCUSABLE = 0x00000000; 736 737 /** 738 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 739 * setFlags. 740 */ 741 private static final int FOCUSABLE = 0x00000001; 742 743 /** 744 * Mask for use with setFlags indicating bits used for focus. 745 */ 746 private static final int FOCUSABLE_MASK = 0x00000001; 747 748 /** 749 * This view will adjust its padding to fit sytem windows (e.g. status bar) 750 */ 751 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 752 753 /** @hide */ 754 @IntDef({VISIBLE, INVISIBLE, GONE}) 755 @Retention(RetentionPolicy.SOURCE) 756 public @interface Visibility {} 757 758 /** 759 * This view is visible. 760 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 761 * android:visibility}. 762 */ 763 public static final int VISIBLE = 0x00000000; 764 765 /** 766 * This view is invisible, but it still takes up space for layout purposes. 767 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 768 * android:visibility}. 769 */ 770 public static final int INVISIBLE = 0x00000004; 771 772 /** 773 * This view is invisible, and it doesn't take any space for layout 774 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 775 * android:visibility}. 776 */ 777 public static final int GONE = 0x00000008; 778 779 /** 780 * Mask for use with setFlags indicating bits used for visibility. 781 * {@hide} 782 */ 783 static final int VISIBILITY_MASK = 0x0000000C; 784 785 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 786 787 /** 788 * This view is enabled. Interpretation varies by subclass. 789 * Use with ENABLED_MASK when calling setFlags. 790 * {@hide} 791 */ 792 static final int ENABLED = 0x00000000; 793 794 /** 795 * This view is disabled. Interpretation varies by subclass. 796 * Use with ENABLED_MASK when calling setFlags. 797 * {@hide} 798 */ 799 static final int DISABLED = 0x00000020; 800 801 /** 802 * Mask for use with setFlags indicating bits used for indicating whether 803 * this view is enabled 804 * {@hide} 805 */ 806 static final int ENABLED_MASK = 0x00000020; 807 808 /** 809 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 810 * called and further optimizations will be performed. It is okay to have 811 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 812 * {@hide} 813 */ 814 static final int WILL_NOT_DRAW = 0x00000080; 815 816 /** 817 * Mask for use with setFlags indicating bits used for indicating whether 818 * this view is will draw 819 * {@hide} 820 */ 821 static final int DRAW_MASK = 0x00000080; 822 823 /** 824 * <p>This view doesn't show scrollbars.</p> 825 * {@hide} 826 */ 827 static final int SCROLLBARS_NONE = 0x00000000; 828 829 /** 830 * <p>This view shows horizontal scrollbars.</p> 831 * {@hide} 832 */ 833 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 834 835 /** 836 * <p>This view shows vertical scrollbars.</p> 837 * {@hide} 838 */ 839 static final int SCROLLBARS_VERTICAL = 0x00000200; 840 841 /** 842 * <p>Mask for use with setFlags indicating bits used for indicating which 843 * scrollbars are enabled.</p> 844 * {@hide} 845 */ 846 static final int SCROLLBARS_MASK = 0x00000300; 847 848 /** 849 * Indicates that the view should filter touches when its window is obscured. 850 * Refer to the class comments for more information about this security feature. 851 * {@hide} 852 */ 853 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 854 855 /** 856 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 857 * that they are optional and should be skipped if the window has 858 * requested system UI flags that ignore those insets for layout. 859 */ 860 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 861 862 /** 863 * <p>This view doesn't show fading edges.</p> 864 * {@hide} 865 */ 866 static final int FADING_EDGE_NONE = 0x00000000; 867 868 /** 869 * <p>This view shows horizontal fading edges.</p> 870 * {@hide} 871 */ 872 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 873 874 /** 875 * <p>This view shows vertical fading edges.</p> 876 * {@hide} 877 */ 878 static final int FADING_EDGE_VERTICAL = 0x00002000; 879 880 /** 881 * <p>Mask for use with setFlags indicating bits used for indicating which 882 * fading edges are enabled.</p> 883 * {@hide} 884 */ 885 static final int FADING_EDGE_MASK = 0x00003000; 886 887 /** 888 * <p>Indicates this view can be clicked. When clickable, a View reacts 889 * to clicks by notifying the OnClickListener.<p> 890 * {@hide} 891 */ 892 static final int CLICKABLE = 0x00004000; 893 894 /** 895 * <p>Indicates this view is caching its drawing into a bitmap.</p> 896 * {@hide} 897 */ 898 static final int DRAWING_CACHE_ENABLED = 0x00008000; 899 900 /** 901 * <p>Indicates that no icicle should be saved for this view.<p> 902 * {@hide} 903 */ 904 static final int SAVE_DISABLED = 0x000010000; 905 906 /** 907 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 908 * property.</p> 909 * {@hide} 910 */ 911 static final int SAVE_DISABLED_MASK = 0x000010000; 912 913 /** 914 * <p>Indicates that no drawing cache should ever be created for this view.<p> 915 * {@hide} 916 */ 917 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 918 919 /** 920 * <p>Indicates this view can take / keep focus when int touch mode.</p> 921 * {@hide} 922 */ 923 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 924 925 /** @hide */ 926 @Retention(RetentionPolicy.SOURCE) 927 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 928 public @interface DrawingCacheQuality {} 929 930 /** 931 * <p>Enables low quality mode for the drawing cache.</p> 932 */ 933 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 934 935 /** 936 * <p>Enables high quality mode for the drawing cache.</p> 937 */ 938 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 939 940 /** 941 * <p>Enables automatic quality mode for the drawing cache.</p> 942 */ 943 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 944 945 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 946 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 947 }; 948 949 /** 950 * <p>Mask for use with setFlags indicating bits used for the cache 951 * quality property.</p> 952 * {@hide} 953 */ 954 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 955 956 /** 957 * <p> 958 * Indicates this view can be long clicked. When long clickable, a View 959 * reacts to long clicks by notifying the OnLongClickListener or showing a 960 * context menu. 961 * </p> 962 * {@hide} 963 */ 964 static final int LONG_CLICKABLE = 0x00200000; 965 966 /** 967 * <p>Indicates that this view gets its drawable states from its direct parent 968 * and ignores its original internal states.</p> 969 * 970 * @hide 971 */ 972 static final int DUPLICATE_PARENT_STATE = 0x00400000; 973 974 /** @hide */ 975 @IntDef({ 976 SCROLLBARS_INSIDE_OVERLAY, 977 SCROLLBARS_INSIDE_INSET, 978 SCROLLBARS_OUTSIDE_OVERLAY, 979 SCROLLBARS_OUTSIDE_INSET 980 }) 981 @Retention(RetentionPolicy.SOURCE) 982 public @interface ScrollBarStyle {} 983 984 /** 985 * The scrollbar style to display the scrollbars inside the content area, 986 * without increasing the padding. The scrollbars will be overlaid with 987 * translucency on the view's content. 988 */ 989 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 990 991 /** 992 * The scrollbar style to display the scrollbars inside the padded area, 993 * increasing the padding of the view. The scrollbars will not overlap the 994 * content area of the view. 995 */ 996 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 997 998 /** 999 * The scrollbar style to display the scrollbars at the edge of the view, 1000 * without increasing the padding. The scrollbars will be overlaid with 1001 * translucency. 1002 */ 1003 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1004 1005 /** 1006 * The scrollbar style to display the scrollbars at the edge of the view, 1007 * increasing the padding of the view. The scrollbars will only overlap the 1008 * background, if any. 1009 */ 1010 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1011 1012 /** 1013 * Mask to check if the scrollbar style is overlay or inset. 1014 * {@hide} 1015 */ 1016 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1017 1018 /** 1019 * Mask to check if the scrollbar style is inside or outside. 1020 * {@hide} 1021 */ 1022 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1023 1024 /** 1025 * Mask for scrollbar style. 1026 * {@hide} 1027 */ 1028 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1029 1030 /** 1031 * View flag indicating that the screen should remain on while the 1032 * window containing this view is visible to the user. This effectively 1033 * takes care of automatically setting the WindowManager's 1034 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1035 */ 1036 public static final int KEEP_SCREEN_ON = 0x04000000; 1037 1038 /** 1039 * View flag indicating whether this view should have sound effects enabled 1040 * for events such as clicking and touching. 1041 */ 1042 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1043 1044 /** 1045 * View flag indicating whether this view should have haptic feedback 1046 * enabled for events such as long presses. 1047 */ 1048 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1049 1050 /** 1051 * <p>Indicates that the view hierarchy should stop saving state when 1052 * it reaches this view. If state saving is initiated immediately at 1053 * the view, it will be allowed. 1054 * {@hide} 1055 */ 1056 static final int PARENT_SAVE_DISABLED = 0x20000000; 1057 1058 /** 1059 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1060 * {@hide} 1061 */ 1062 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1063 1064 /** @hide */ 1065 @IntDef(flag = true, 1066 value = { 1067 FOCUSABLES_ALL, 1068 FOCUSABLES_TOUCH_MODE 1069 }) 1070 @Retention(RetentionPolicy.SOURCE) 1071 public @interface FocusableMode {} 1072 1073 /** 1074 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1075 * should add all focusable Views regardless if they are focusable in touch mode. 1076 */ 1077 public static final int FOCUSABLES_ALL = 0x00000000; 1078 1079 /** 1080 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1081 * should add only Views focusable in touch mode. 1082 */ 1083 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1084 1085 /** @hide */ 1086 @IntDef({ 1087 FOCUS_BACKWARD, 1088 FOCUS_FORWARD, 1089 FOCUS_LEFT, 1090 FOCUS_UP, 1091 FOCUS_RIGHT, 1092 FOCUS_DOWN 1093 }) 1094 @Retention(RetentionPolicy.SOURCE) 1095 public @interface FocusDirection {} 1096 1097 /** @hide */ 1098 @IntDef({ 1099 FOCUS_LEFT, 1100 FOCUS_UP, 1101 FOCUS_RIGHT, 1102 FOCUS_DOWN 1103 }) 1104 @Retention(RetentionPolicy.SOURCE) 1105 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1106 1107 /** 1108 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1109 * item. 1110 */ 1111 public static final int FOCUS_BACKWARD = 0x00000001; 1112 1113 /** 1114 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1115 * item. 1116 */ 1117 public static final int FOCUS_FORWARD = 0x00000002; 1118 1119 /** 1120 * Use with {@link #focusSearch(int)}. Move focus to the left. 1121 */ 1122 public static final int FOCUS_LEFT = 0x00000011; 1123 1124 /** 1125 * Use with {@link #focusSearch(int)}. Move focus up. 1126 */ 1127 public static final int FOCUS_UP = 0x00000021; 1128 1129 /** 1130 * Use with {@link #focusSearch(int)}. Move focus to the right. 1131 */ 1132 public static final int FOCUS_RIGHT = 0x00000042; 1133 1134 /** 1135 * Use with {@link #focusSearch(int)}. Move focus down. 1136 */ 1137 public static final int FOCUS_DOWN = 0x00000082; 1138 1139 /** 1140 * Bits of {@link #getMeasuredWidthAndState()} and 1141 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1142 */ 1143 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1144 1145 /** 1146 * Bits of {@link #getMeasuredWidthAndState()} and 1147 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1148 */ 1149 public static final int MEASURED_STATE_MASK = 0xff000000; 1150 1151 /** 1152 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1153 * for functions that combine both width and height into a single int, 1154 * such as {@link #getMeasuredState()} and the childState argument of 1155 * {@link #resolveSizeAndState(int, int, int)}. 1156 */ 1157 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1158 1159 /** 1160 * Bit of {@link #getMeasuredWidthAndState()} and 1161 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1162 * is smaller that the space the view would like to have. 1163 */ 1164 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1165 1166 /** 1167 * Base View state sets 1168 */ 1169 // Singles 1170 /** 1171 * Indicates the view has no states set. States are used with 1172 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1173 * view depending on its state. 1174 * 1175 * @see android.graphics.drawable.Drawable 1176 * @see #getDrawableState() 1177 */ 1178 protected static final int[] EMPTY_STATE_SET; 1179 /** 1180 * Indicates the view is enabled. States are used with 1181 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1182 * view depending on its state. 1183 * 1184 * @see android.graphics.drawable.Drawable 1185 * @see #getDrawableState() 1186 */ 1187 protected static final int[] ENABLED_STATE_SET; 1188 /** 1189 * Indicates the view is focused. States are used with 1190 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1191 * view depending on its state. 1192 * 1193 * @see android.graphics.drawable.Drawable 1194 * @see #getDrawableState() 1195 */ 1196 protected static final int[] FOCUSED_STATE_SET; 1197 /** 1198 * Indicates the view is selected. States are used with 1199 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1200 * view depending on its state. 1201 * 1202 * @see android.graphics.drawable.Drawable 1203 * @see #getDrawableState() 1204 */ 1205 protected static final int[] SELECTED_STATE_SET; 1206 /** 1207 * Indicates the view is pressed. States are used with 1208 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1209 * view depending on its state. 1210 * 1211 * @see android.graphics.drawable.Drawable 1212 * @see #getDrawableState() 1213 */ 1214 protected static final int[] PRESSED_STATE_SET; 1215 /** 1216 * Indicates the view's window has focus. States are used with 1217 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1218 * view depending on its state. 1219 * 1220 * @see android.graphics.drawable.Drawable 1221 * @see #getDrawableState() 1222 */ 1223 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1224 // Doubles 1225 /** 1226 * Indicates the view is enabled and has the focus. 1227 * 1228 * @see #ENABLED_STATE_SET 1229 * @see #FOCUSED_STATE_SET 1230 */ 1231 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1232 /** 1233 * Indicates the view is enabled and selected. 1234 * 1235 * @see #ENABLED_STATE_SET 1236 * @see #SELECTED_STATE_SET 1237 */ 1238 protected static final int[] ENABLED_SELECTED_STATE_SET; 1239 /** 1240 * Indicates the view is enabled and that its window has focus. 1241 * 1242 * @see #ENABLED_STATE_SET 1243 * @see #WINDOW_FOCUSED_STATE_SET 1244 */ 1245 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1246 /** 1247 * Indicates the view is focused and selected. 1248 * 1249 * @see #FOCUSED_STATE_SET 1250 * @see #SELECTED_STATE_SET 1251 */ 1252 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1253 /** 1254 * Indicates the view has the focus and that its window has the focus. 1255 * 1256 * @see #FOCUSED_STATE_SET 1257 * @see #WINDOW_FOCUSED_STATE_SET 1258 */ 1259 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1260 /** 1261 * Indicates the view is selected and that its window has the focus. 1262 * 1263 * @see #SELECTED_STATE_SET 1264 * @see #WINDOW_FOCUSED_STATE_SET 1265 */ 1266 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1267 // Triples 1268 /** 1269 * Indicates the view is enabled, focused and selected. 1270 * 1271 * @see #ENABLED_STATE_SET 1272 * @see #FOCUSED_STATE_SET 1273 * @see #SELECTED_STATE_SET 1274 */ 1275 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1276 /** 1277 * Indicates the view is enabled, focused and its window has the focus. 1278 * 1279 * @see #ENABLED_STATE_SET 1280 * @see #FOCUSED_STATE_SET 1281 * @see #WINDOW_FOCUSED_STATE_SET 1282 */ 1283 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1284 /** 1285 * Indicates the view is enabled, selected and its window has the focus. 1286 * 1287 * @see #ENABLED_STATE_SET 1288 * @see #SELECTED_STATE_SET 1289 * @see #WINDOW_FOCUSED_STATE_SET 1290 */ 1291 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1292 /** 1293 * Indicates the view is focused, selected and its window has the focus. 1294 * 1295 * @see #FOCUSED_STATE_SET 1296 * @see #SELECTED_STATE_SET 1297 * @see #WINDOW_FOCUSED_STATE_SET 1298 */ 1299 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1300 /** 1301 * Indicates the view is enabled, focused, selected and its window 1302 * has the focus. 1303 * 1304 * @see #ENABLED_STATE_SET 1305 * @see #FOCUSED_STATE_SET 1306 * @see #SELECTED_STATE_SET 1307 * @see #WINDOW_FOCUSED_STATE_SET 1308 */ 1309 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1310 /** 1311 * Indicates the view is pressed and its window has the focus. 1312 * 1313 * @see #PRESSED_STATE_SET 1314 * @see #WINDOW_FOCUSED_STATE_SET 1315 */ 1316 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1317 /** 1318 * Indicates the view is pressed and selected. 1319 * 1320 * @see #PRESSED_STATE_SET 1321 * @see #SELECTED_STATE_SET 1322 */ 1323 protected static final int[] PRESSED_SELECTED_STATE_SET; 1324 /** 1325 * Indicates the view is pressed, selected and its window has the focus. 1326 * 1327 * @see #PRESSED_STATE_SET 1328 * @see #SELECTED_STATE_SET 1329 * @see #WINDOW_FOCUSED_STATE_SET 1330 */ 1331 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1332 /** 1333 * Indicates the view is pressed and focused. 1334 * 1335 * @see #PRESSED_STATE_SET 1336 * @see #FOCUSED_STATE_SET 1337 */ 1338 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1339 /** 1340 * Indicates the view is pressed, focused and its window has the focus. 1341 * 1342 * @see #PRESSED_STATE_SET 1343 * @see #FOCUSED_STATE_SET 1344 * @see #WINDOW_FOCUSED_STATE_SET 1345 */ 1346 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1347 /** 1348 * Indicates the view is pressed, focused and selected. 1349 * 1350 * @see #PRESSED_STATE_SET 1351 * @see #SELECTED_STATE_SET 1352 * @see #FOCUSED_STATE_SET 1353 */ 1354 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1355 /** 1356 * Indicates the view is pressed, focused, selected and its window has the focus. 1357 * 1358 * @see #PRESSED_STATE_SET 1359 * @see #FOCUSED_STATE_SET 1360 * @see #SELECTED_STATE_SET 1361 * @see #WINDOW_FOCUSED_STATE_SET 1362 */ 1363 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1364 /** 1365 * Indicates the view is pressed and enabled. 1366 * 1367 * @see #PRESSED_STATE_SET 1368 * @see #ENABLED_STATE_SET 1369 */ 1370 protected static final int[] PRESSED_ENABLED_STATE_SET; 1371 /** 1372 * Indicates the view is pressed, enabled and its window has the focus. 1373 * 1374 * @see #PRESSED_STATE_SET 1375 * @see #ENABLED_STATE_SET 1376 * @see #WINDOW_FOCUSED_STATE_SET 1377 */ 1378 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1379 /** 1380 * Indicates the view is pressed, enabled and selected. 1381 * 1382 * @see #PRESSED_STATE_SET 1383 * @see #ENABLED_STATE_SET 1384 * @see #SELECTED_STATE_SET 1385 */ 1386 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1387 /** 1388 * Indicates the view is pressed, enabled, selected and its window has the 1389 * focus. 1390 * 1391 * @see #PRESSED_STATE_SET 1392 * @see #ENABLED_STATE_SET 1393 * @see #SELECTED_STATE_SET 1394 * @see #WINDOW_FOCUSED_STATE_SET 1395 */ 1396 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1397 /** 1398 * Indicates the view is pressed, enabled and focused. 1399 * 1400 * @see #PRESSED_STATE_SET 1401 * @see #ENABLED_STATE_SET 1402 * @see #FOCUSED_STATE_SET 1403 */ 1404 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1405 /** 1406 * Indicates the view is pressed, enabled, focused and its window has the 1407 * focus. 1408 * 1409 * @see #PRESSED_STATE_SET 1410 * @see #ENABLED_STATE_SET 1411 * @see #FOCUSED_STATE_SET 1412 * @see #WINDOW_FOCUSED_STATE_SET 1413 */ 1414 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1415 /** 1416 * Indicates the view is pressed, enabled, focused and selected. 1417 * 1418 * @see #PRESSED_STATE_SET 1419 * @see #ENABLED_STATE_SET 1420 * @see #SELECTED_STATE_SET 1421 * @see #FOCUSED_STATE_SET 1422 */ 1423 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1424 /** 1425 * Indicates the view is pressed, enabled, focused, selected and its window 1426 * has the focus. 1427 * 1428 * @see #PRESSED_STATE_SET 1429 * @see #ENABLED_STATE_SET 1430 * @see #SELECTED_STATE_SET 1431 * @see #FOCUSED_STATE_SET 1432 * @see #WINDOW_FOCUSED_STATE_SET 1433 */ 1434 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1435 1436 /** 1437 * The order here is very important to {@link #getDrawableState()} 1438 */ 1439 private static final int[][] VIEW_STATE_SETS; 1440 1441 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1442 static final int VIEW_STATE_SELECTED = 1 << 1; 1443 static final int VIEW_STATE_FOCUSED = 1 << 2; 1444 static final int VIEW_STATE_ENABLED = 1 << 3; 1445 static final int VIEW_STATE_PRESSED = 1 << 4; 1446 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1447 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1448 static final int VIEW_STATE_HOVERED = 1 << 7; 1449 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1450 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1451 1452 static final int[] VIEW_STATE_IDS = new int[] { 1453 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1454 R.attr.state_selected, VIEW_STATE_SELECTED, 1455 R.attr.state_focused, VIEW_STATE_FOCUSED, 1456 R.attr.state_enabled, VIEW_STATE_ENABLED, 1457 R.attr.state_pressed, VIEW_STATE_PRESSED, 1458 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1459 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1460 R.attr.state_hovered, VIEW_STATE_HOVERED, 1461 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1462 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1463 }; 1464 1465 static { 1466 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1467 throw new IllegalStateException( 1468 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1469 } 1470 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1471 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1472 int viewState = R.styleable.ViewDrawableStates[i]; 1473 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1474 if (VIEW_STATE_IDS[j] == viewState) { 1475 orderedIds[i * 2] = viewState; 1476 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1477 } 1478 } 1479 } 1480 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1481 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1482 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1483 int numBits = Integer.bitCount(i); 1484 int[] set = new int[numBits]; 1485 int pos = 0; 1486 for (int j = 0; j < orderedIds.length; j += 2) { 1487 if ((i & orderedIds[j+1]) != 0) { 1488 set[pos++] = orderedIds[j]; 1489 } 1490 } 1491 VIEW_STATE_SETS[i] = set; 1492 } 1493 1494 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1495 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1496 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1497 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1498 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1499 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1500 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1501 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1502 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1503 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1504 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1505 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1506 | VIEW_STATE_FOCUSED]; 1507 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1508 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1509 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1510 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1511 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1512 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1513 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1514 | VIEW_STATE_ENABLED]; 1515 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1516 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1517 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1518 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1519 | VIEW_STATE_ENABLED]; 1520 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1521 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1522 | VIEW_STATE_ENABLED]; 1523 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1524 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1525 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1526 1527 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1528 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1529 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1530 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1531 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1532 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1533 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1534 | VIEW_STATE_PRESSED]; 1535 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1536 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1537 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1538 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1539 | VIEW_STATE_PRESSED]; 1540 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1541 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1542 | VIEW_STATE_PRESSED]; 1543 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1544 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1545 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1546 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1547 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1548 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1549 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1550 | VIEW_STATE_PRESSED]; 1551 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1552 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1553 | VIEW_STATE_PRESSED]; 1554 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1555 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1556 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1557 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1558 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1559 | VIEW_STATE_PRESSED]; 1560 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1561 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1562 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1563 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1564 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1565 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1566 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1567 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1568 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1569 | VIEW_STATE_PRESSED]; 1570 } 1571 1572 /** 1573 * Accessibility event types that are dispatched for text population. 1574 */ 1575 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1576 AccessibilityEvent.TYPE_VIEW_CLICKED 1577 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1578 | AccessibilityEvent.TYPE_VIEW_SELECTED 1579 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1580 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1581 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1582 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1583 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1584 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1585 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1586 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1587 1588 /** 1589 * Temporary Rect currently for use in setBackground(). This will probably 1590 * be extended in the future to hold our own class with more than just 1591 * a Rect. :) 1592 */ 1593 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1594 1595 /** 1596 * Map used to store views' tags. 1597 */ 1598 private SparseArray<Object> mKeyedTags; 1599 1600 /** 1601 * The next available accessibility id. 1602 */ 1603 private static int sNextAccessibilityViewId; 1604 1605 /** 1606 * The animation currently associated with this view. 1607 * @hide 1608 */ 1609 protected Animation mCurrentAnimation = null; 1610 1611 /** 1612 * Width as measured during measure pass. 1613 * {@hide} 1614 */ 1615 @ViewDebug.ExportedProperty(category = "measurement") 1616 int mMeasuredWidth; 1617 1618 /** 1619 * Height as measured during measure pass. 1620 * {@hide} 1621 */ 1622 @ViewDebug.ExportedProperty(category = "measurement") 1623 int mMeasuredHeight; 1624 1625 /** 1626 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1627 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1628 * its display list. This flag, used only when hw accelerated, allows us to clear the 1629 * flag while retaining this information until it's needed (at getDisplayList() time and 1630 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1631 * 1632 * {@hide} 1633 */ 1634 boolean mRecreateDisplayList = false; 1635 1636 /** 1637 * The view's identifier. 1638 * {@hide} 1639 * 1640 * @see #setId(int) 1641 * @see #getId() 1642 */ 1643 @ViewDebug.ExportedProperty(resolveId = true) 1644 int mID = NO_ID; 1645 1646 /** 1647 * The stable ID of this view for accessibility purposes. 1648 */ 1649 int mAccessibilityViewId = NO_ID; 1650 1651 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1652 1653 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1654 1655 /** 1656 * The view's tag. 1657 * {@hide} 1658 * 1659 * @see #setTag(Object) 1660 * @see #getTag() 1661 */ 1662 protected Object mTag = null; 1663 1664 // for mPrivateFlags: 1665 /** {@hide} */ 1666 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1667 /** {@hide} */ 1668 static final int PFLAG_FOCUSED = 0x00000002; 1669 /** {@hide} */ 1670 static final int PFLAG_SELECTED = 0x00000004; 1671 /** {@hide} */ 1672 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1673 /** {@hide} */ 1674 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1675 /** {@hide} */ 1676 static final int PFLAG_DRAWN = 0x00000020; 1677 /** 1678 * When this flag is set, this view is running an animation on behalf of its 1679 * children and should therefore not cancel invalidate requests, even if they 1680 * lie outside of this view's bounds. 1681 * 1682 * {@hide} 1683 */ 1684 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1685 /** {@hide} */ 1686 static final int PFLAG_SKIP_DRAW = 0x00000080; 1687 /** {@hide} */ 1688 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1689 /** {@hide} */ 1690 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1691 /** {@hide} */ 1692 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1693 /** {@hide} */ 1694 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1695 /** {@hide} */ 1696 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1697 /** {@hide} */ 1698 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1699 1700 private static final int PFLAG_PRESSED = 0x00004000; 1701 1702 /** {@hide} */ 1703 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1704 /** 1705 * Flag used to indicate that this view should be drawn once more (and only once 1706 * more) after its animation has completed. 1707 * {@hide} 1708 */ 1709 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1710 1711 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1712 1713 /** 1714 * Indicates that the View returned true when onSetAlpha() was called and that 1715 * the alpha must be restored. 1716 * {@hide} 1717 */ 1718 static final int PFLAG_ALPHA_SET = 0x00040000; 1719 1720 /** 1721 * Set by {@link #setScrollContainer(boolean)}. 1722 */ 1723 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1724 1725 /** 1726 * Set by {@link #setScrollContainer(boolean)}. 1727 */ 1728 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1729 1730 /** 1731 * View flag indicating whether this view was invalidated (fully or partially.) 1732 * 1733 * @hide 1734 */ 1735 static final int PFLAG_DIRTY = 0x00200000; 1736 1737 /** 1738 * View flag indicating whether this view was invalidated by an opaque 1739 * invalidate request. 1740 * 1741 * @hide 1742 */ 1743 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1744 1745 /** 1746 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1747 * 1748 * @hide 1749 */ 1750 static final int PFLAG_DIRTY_MASK = 0x00600000; 1751 1752 /** 1753 * Indicates whether the background is opaque. 1754 * 1755 * @hide 1756 */ 1757 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1758 1759 /** 1760 * Indicates whether the scrollbars are opaque. 1761 * 1762 * @hide 1763 */ 1764 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1765 1766 /** 1767 * Indicates whether the view is opaque. 1768 * 1769 * @hide 1770 */ 1771 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1772 1773 /** 1774 * Indicates a prepressed state; 1775 * the short time between ACTION_DOWN and recognizing 1776 * a 'real' press. Prepressed is used to recognize quick taps 1777 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1778 * 1779 * @hide 1780 */ 1781 private static final int PFLAG_PREPRESSED = 0x02000000; 1782 1783 /** 1784 * Indicates whether the view is temporarily detached. 1785 * 1786 * @hide 1787 */ 1788 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1789 1790 /** 1791 * Indicates that we should awaken scroll bars once attached 1792 * 1793 * @hide 1794 */ 1795 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1796 1797 /** 1798 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1799 * @hide 1800 */ 1801 private static final int PFLAG_HOVERED = 0x10000000; 1802 1803 /** 1804 * no longer needed, should be reused 1805 */ 1806 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1807 1808 /** {@hide} */ 1809 static final int PFLAG_ACTIVATED = 0x40000000; 1810 1811 /** 1812 * Indicates that this view was specifically invalidated, not just dirtied because some 1813 * child view was invalidated. The flag is used to determine when we need to recreate 1814 * a view's display list (as opposed to just returning a reference to its existing 1815 * display list). 1816 * 1817 * @hide 1818 */ 1819 static final int PFLAG_INVALIDATED = 0x80000000; 1820 1821 /** 1822 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1823 * 1824 * |-------|-------|-------|-------| 1825 * 1 PFLAG2_DRAG_CAN_ACCEPT 1826 * 1 PFLAG2_DRAG_HOVERED 1827 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1828 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1829 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1830 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1831 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1832 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1833 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1834 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1835 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1836 * 111 PFLAG2_TEXT_DIRECTION_MASK 1837 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1838 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1839 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1840 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1841 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1842 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1843 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1844 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1845 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1846 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1847 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1848 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1849 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1850 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1851 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1852 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1853 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1854 * 1 PFLAG2_VIEW_QUICK_REJECTED 1855 * 1 PFLAG2_PADDING_RESOLVED 1856 * 1 PFLAG2_DRAWABLE_RESOLVED 1857 * 1 PFLAG2_HAS_TRANSIENT_STATE 1858 * |-------|-------|-------|-------| 1859 */ 1860 1861 /** 1862 * Indicates that this view has reported that it can accept the current drag's content. 1863 * Cleared when the drag operation concludes. 1864 * @hide 1865 */ 1866 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1867 1868 /** 1869 * Indicates that this view is currently directly under the drag location in a 1870 * drag-and-drop operation involving content that it can accept. Cleared when 1871 * the drag exits the view, or when the drag operation concludes. 1872 * @hide 1873 */ 1874 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1875 1876 /** @hide */ 1877 @IntDef({ 1878 LAYOUT_DIRECTION_LTR, 1879 LAYOUT_DIRECTION_RTL, 1880 LAYOUT_DIRECTION_INHERIT, 1881 LAYOUT_DIRECTION_LOCALE 1882 }) 1883 @Retention(RetentionPolicy.SOURCE) 1884 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1885 public @interface LayoutDir {} 1886 1887 /** @hide */ 1888 @IntDef({ 1889 LAYOUT_DIRECTION_LTR, 1890 LAYOUT_DIRECTION_RTL 1891 }) 1892 @Retention(RetentionPolicy.SOURCE) 1893 public @interface ResolvedLayoutDir {} 1894 1895 /** 1896 * Horizontal layout direction of this view is from Left to Right. 1897 * Use with {@link #setLayoutDirection}. 1898 */ 1899 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1900 1901 /** 1902 * Horizontal layout direction of this view is from Right to Left. 1903 * Use with {@link #setLayoutDirection}. 1904 */ 1905 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1906 1907 /** 1908 * Horizontal layout direction of this view is inherited from its parent. 1909 * Use with {@link #setLayoutDirection}. 1910 */ 1911 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1912 1913 /** 1914 * Horizontal layout direction of this view is from deduced from the default language 1915 * script for the locale. Use with {@link #setLayoutDirection}. 1916 */ 1917 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1918 1919 /** 1920 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1921 * @hide 1922 */ 1923 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1924 1925 /** 1926 * Mask for use with private flags indicating bits used for horizontal layout direction. 1927 * @hide 1928 */ 1929 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1930 1931 /** 1932 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1933 * right-to-left direction. 1934 * @hide 1935 */ 1936 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1937 1938 /** 1939 * Indicates whether the view horizontal layout direction has been resolved. 1940 * @hide 1941 */ 1942 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1943 1944 /** 1945 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1946 * @hide 1947 */ 1948 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1949 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1950 1951 /* 1952 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1953 * flag value. 1954 * @hide 1955 */ 1956 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1957 LAYOUT_DIRECTION_LTR, 1958 LAYOUT_DIRECTION_RTL, 1959 LAYOUT_DIRECTION_INHERIT, 1960 LAYOUT_DIRECTION_LOCALE 1961 }; 1962 1963 /** 1964 * Default horizontal layout direction. 1965 */ 1966 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1967 1968 /** 1969 * Default horizontal layout direction. 1970 * @hide 1971 */ 1972 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1973 1974 /** 1975 * Text direction is inherited thru {@link ViewGroup} 1976 */ 1977 public static final int TEXT_DIRECTION_INHERIT = 0; 1978 1979 /** 1980 * Text direction is using "first strong algorithm". The first strong directional character 1981 * determines the paragraph direction. If there is no strong directional character, the 1982 * paragraph direction is the view's resolved layout direction. 1983 */ 1984 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1985 1986 /** 1987 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1988 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1989 * If there are neither, the paragraph direction is the view's resolved layout direction. 1990 */ 1991 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1992 1993 /** 1994 * Text direction is forced to LTR. 1995 */ 1996 public static final int TEXT_DIRECTION_LTR = 3; 1997 1998 /** 1999 * Text direction is forced to RTL. 2000 */ 2001 public static final int TEXT_DIRECTION_RTL = 4; 2002 2003 /** 2004 * Text direction is coming from the system Locale. 2005 */ 2006 public static final int TEXT_DIRECTION_LOCALE = 5; 2007 2008 /** 2009 * Default text direction is inherited 2010 */ 2011 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2012 2013 /** 2014 * Default resolved text direction 2015 * @hide 2016 */ 2017 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2018 2019 /** 2020 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2021 * @hide 2022 */ 2023 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2024 2025 /** 2026 * Mask for use with private flags indicating bits used for text direction. 2027 * @hide 2028 */ 2029 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2030 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2031 2032 /** 2033 * Array of text direction flags for mapping attribute "textDirection" to correct 2034 * flag value. 2035 * @hide 2036 */ 2037 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2038 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2039 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2040 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2041 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2042 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2043 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2044 }; 2045 2046 /** 2047 * Indicates whether the view text direction has been resolved. 2048 * @hide 2049 */ 2050 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2051 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2052 2053 /** 2054 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2055 * @hide 2056 */ 2057 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2058 2059 /** 2060 * Mask for use with private flags indicating bits used for resolved text direction. 2061 * @hide 2062 */ 2063 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2064 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2065 2066 /** 2067 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2068 * @hide 2069 */ 2070 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2071 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2072 2073 /** @hide */ 2074 @IntDef({ 2075 TEXT_ALIGNMENT_INHERIT, 2076 TEXT_ALIGNMENT_GRAVITY, 2077 TEXT_ALIGNMENT_CENTER, 2078 TEXT_ALIGNMENT_TEXT_START, 2079 TEXT_ALIGNMENT_TEXT_END, 2080 TEXT_ALIGNMENT_VIEW_START, 2081 TEXT_ALIGNMENT_VIEW_END 2082 }) 2083 @Retention(RetentionPolicy.SOURCE) 2084 public @interface TextAlignment {} 2085 2086 /** 2087 * Default text alignment. The text alignment of this View is inherited from its parent. 2088 * Use with {@link #setTextAlignment(int)} 2089 */ 2090 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2091 2092 /** 2093 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2094 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2095 * 2096 * Use with {@link #setTextAlignment(int)} 2097 */ 2098 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2099 2100 /** 2101 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2102 * 2103 * Use with {@link #setTextAlignment(int)} 2104 */ 2105 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2106 2107 /** 2108 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2109 * 2110 * Use with {@link #setTextAlignment(int)} 2111 */ 2112 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2113 2114 /** 2115 * Center the paragraph, e.g. ALIGN_CENTER. 2116 * 2117 * Use with {@link #setTextAlignment(int)} 2118 */ 2119 public static final int TEXT_ALIGNMENT_CENTER = 4; 2120 2121 /** 2122 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2123 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2124 * 2125 * Use with {@link #setTextAlignment(int)} 2126 */ 2127 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2128 2129 /** 2130 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2131 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2132 * 2133 * Use with {@link #setTextAlignment(int)} 2134 */ 2135 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2136 2137 /** 2138 * Default text alignment is inherited 2139 */ 2140 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2141 2142 /** 2143 * Default resolved text alignment 2144 * @hide 2145 */ 2146 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2147 2148 /** 2149 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2150 * @hide 2151 */ 2152 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2153 2154 /** 2155 * Mask for use with private flags indicating bits used for text alignment. 2156 * @hide 2157 */ 2158 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2159 2160 /** 2161 * Array of text direction flags for mapping attribute "textAlignment" to correct 2162 * flag value. 2163 * @hide 2164 */ 2165 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2166 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2167 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2168 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2169 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2170 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2171 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2172 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2173 }; 2174 2175 /** 2176 * Indicates whether the view text alignment has been resolved. 2177 * @hide 2178 */ 2179 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2180 2181 /** 2182 * Bit shift to get the resolved text alignment. 2183 * @hide 2184 */ 2185 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2186 2187 /** 2188 * Mask for use with private flags indicating bits used for text alignment. 2189 * @hide 2190 */ 2191 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2192 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2193 2194 /** 2195 * Indicates whether if the view text alignment has been resolved to gravity 2196 */ 2197 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2198 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2199 2200 // Accessiblity constants for mPrivateFlags2 2201 2202 /** 2203 * Shift for the bits in {@link #mPrivateFlags2} related to the 2204 * "importantForAccessibility" attribute. 2205 */ 2206 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2207 2208 /** 2209 * Automatically determine whether a view is important for accessibility. 2210 */ 2211 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2212 2213 /** 2214 * The view is important for accessibility. 2215 */ 2216 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2217 2218 /** 2219 * The view is not important for accessibility. 2220 */ 2221 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2222 2223 /** 2224 * The view is not important for accessibility, nor are any of its 2225 * descendant views. 2226 */ 2227 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2228 2229 /** 2230 * The default whether the view is important for accessibility. 2231 */ 2232 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2233 2234 /** 2235 * Mask for obtainig the bits which specify how to determine 2236 * whether a view is important for accessibility. 2237 */ 2238 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2239 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2240 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2241 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2242 2243 /** 2244 * Shift for the bits in {@link #mPrivateFlags2} related to the 2245 * "accessibilityLiveRegion" attribute. 2246 */ 2247 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2248 2249 /** 2250 * Live region mode specifying that accessibility services should not 2251 * automatically announce changes to this view. This is the default live 2252 * region mode for most views. 2253 * <p> 2254 * Use with {@link #setAccessibilityLiveRegion(int)}. 2255 */ 2256 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2257 2258 /** 2259 * Live region mode specifying that accessibility services should announce 2260 * changes to this view. 2261 * <p> 2262 * Use with {@link #setAccessibilityLiveRegion(int)}. 2263 */ 2264 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2265 2266 /** 2267 * Live region mode specifying that accessibility services should interrupt 2268 * ongoing speech to immediately announce changes to this view. 2269 * <p> 2270 * Use with {@link #setAccessibilityLiveRegion(int)}. 2271 */ 2272 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2273 2274 /** 2275 * The default whether the view is important for accessibility. 2276 */ 2277 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2278 2279 /** 2280 * Mask for obtaining the bits which specify a view's accessibility live 2281 * region mode. 2282 */ 2283 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2284 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2285 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2286 2287 /** 2288 * Flag indicating whether a view has accessibility focus. 2289 */ 2290 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2291 2292 /** 2293 * Flag whether the accessibility state of the subtree rooted at this view changed. 2294 */ 2295 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2296 2297 /** 2298 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2299 * is used to check whether later changes to the view's transform should invalidate the 2300 * view to force the quickReject test to run again. 2301 */ 2302 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2303 2304 /** 2305 * Flag indicating that start/end padding has been resolved into left/right padding 2306 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2307 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2308 * during measurement. In some special cases this is required such as when an adapter-based 2309 * view measures prospective children without attaching them to a window. 2310 */ 2311 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2312 2313 /** 2314 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2315 */ 2316 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2317 2318 /** 2319 * Indicates that the view is tracking some sort of transient state 2320 * that the app should not need to be aware of, but that the framework 2321 * should take special care to preserve. 2322 */ 2323 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2324 2325 /** 2326 * Group of bits indicating that RTL properties resolution is done. 2327 */ 2328 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2329 PFLAG2_TEXT_DIRECTION_RESOLVED | 2330 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2331 PFLAG2_PADDING_RESOLVED | 2332 PFLAG2_DRAWABLE_RESOLVED; 2333 2334 // There are a couple of flags left in mPrivateFlags2 2335 2336 /* End of masks for mPrivateFlags2 */ 2337 2338 /** 2339 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2340 * 2341 * |-------|-------|-------|-------| 2342 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2343 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2344 * 1 PFLAG3_IS_LAID_OUT 2345 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2346 * 1 PFLAG3_CALLED_SUPER 2347 * |-------|-------|-------|-------| 2348 */ 2349 2350 /** 2351 * Flag indicating that view has a transform animation set on it. This is used to track whether 2352 * an animation is cleared between successive frames, in order to tell the associated 2353 * DisplayList to clear its animation matrix. 2354 */ 2355 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2356 2357 /** 2358 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2359 * animation is cleared between successive frames, in order to tell the associated 2360 * DisplayList to restore its alpha value. 2361 */ 2362 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2363 2364 /** 2365 * Flag indicating that the view has been through at least one layout since it 2366 * was last attached to a window. 2367 */ 2368 static final int PFLAG3_IS_LAID_OUT = 0x4; 2369 2370 /** 2371 * Flag indicating that a call to measure() was skipped and should be done 2372 * instead when layout() is invoked. 2373 */ 2374 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2375 2376 /** 2377 * Flag indicating that an overridden method correctly called down to 2378 * the superclass implementation as required by the API spec. 2379 */ 2380 static final int PFLAG3_CALLED_SUPER = 0x10; 2381 2382 /** 2383 * Flag indicating that we're in the process of applying window insets. 2384 */ 2385 static final int PFLAG3_APPLYING_INSETS = 0x20; 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 = 0x40; 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 = 0x80; 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 * Whether Recents is visible or not. 2776 */ 2777 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2778 2779 /** 2780 * @hide 2781 * 2782 * Makes system ui transparent. 2783 */ 2784 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2785 2786 /** 2787 * @hide 2788 */ 2789 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2790 2791 /** 2792 * These are the system UI flags that can be cleared by events outside 2793 * of an application. Currently this is just the ability to tap on the 2794 * screen while hiding the navigation bar to have it return. 2795 * @hide 2796 */ 2797 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2798 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2799 | SYSTEM_UI_FLAG_FULLSCREEN; 2800 2801 /** 2802 * Flags that can impact the layout in relation to system UI. 2803 */ 2804 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2805 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2806 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2807 2808 /** @hide */ 2809 @IntDef(flag = true, 2810 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2811 @Retention(RetentionPolicy.SOURCE) 2812 public @interface FindViewFlags {} 2813 2814 /** 2815 * Find views that render the specified text. 2816 * 2817 * @see #findViewsWithText(ArrayList, CharSequence, int) 2818 */ 2819 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2820 2821 /** 2822 * Find find views that contain the specified content description. 2823 * 2824 * @see #findViewsWithText(ArrayList, CharSequence, int) 2825 */ 2826 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2827 2828 /** 2829 * Find views that contain {@link AccessibilityNodeProvider}. Such 2830 * a View is a root of virtual view hierarchy and may contain the searched 2831 * text. If this flag is set Views with providers are automatically 2832 * added and it is a responsibility of the client to call the APIs of 2833 * the provider to determine whether the virtual tree rooted at this View 2834 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2835 * representing the virtual views with this text. 2836 * 2837 * @see #findViewsWithText(ArrayList, CharSequence, int) 2838 * 2839 * @hide 2840 */ 2841 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2842 2843 /** 2844 * The undefined cursor position. 2845 * 2846 * @hide 2847 */ 2848 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2849 2850 /** 2851 * Indicates that the screen has changed state and is now off. 2852 * 2853 * @see #onScreenStateChanged(int) 2854 */ 2855 public static final int SCREEN_STATE_OFF = 0x0; 2856 2857 /** 2858 * Indicates that the screen has changed state and is now on. 2859 * 2860 * @see #onScreenStateChanged(int) 2861 */ 2862 public static final int SCREEN_STATE_ON = 0x1; 2863 2864 /** 2865 * Indicates no axis of view scrolling. 2866 */ 2867 public static final int SCROLL_AXIS_NONE = 0; 2868 2869 /** 2870 * Indicates scrolling along the horizontal axis. 2871 */ 2872 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2873 2874 /** 2875 * Indicates scrolling along the vertical axis. 2876 */ 2877 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2878 2879 /** 2880 * Controls the over-scroll mode for this view. 2881 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2882 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2883 * and {@link #OVER_SCROLL_NEVER}. 2884 */ 2885 private int mOverScrollMode; 2886 2887 /** 2888 * The parent this view is attached to. 2889 * {@hide} 2890 * 2891 * @see #getParent() 2892 */ 2893 protected ViewParent mParent; 2894 2895 /** 2896 * {@hide} 2897 */ 2898 AttachInfo mAttachInfo; 2899 2900 /** 2901 * {@hide} 2902 */ 2903 @ViewDebug.ExportedProperty(flagMapping = { 2904 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2905 name = "FORCE_LAYOUT"), 2906 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2907 name = "LAYOUT_REQUIRED"), 2908 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2909 name = "DRAWING_CACHE_INVALID", outputIf = false), 2910 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2911 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2912 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2913 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2914 }) 2915 int mPrivateFlags; 2916 int mPrivateFlags2; 2917 int mPrivateFlags3; 2918 2919 /** 2920 * This view's request for the visibility of the status bar. 2921 * @hide 2922 */ 2923 @ViewDebug.ExportedProperty(flagMapping = { 2924 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2925 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2926 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2927 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2928 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2929 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2930 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2931 equals = SYSTEM_UI_FLAG_VISIBLE, 2932 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2933 }) 2934 int mSystemUiVisibility; 2935 2936 /** 2937 * Reference count for transient state. 2938 * @see #setHasTransientState(boolean) 2939 */ 2940 int mTransientStateCount = 0; 2941 2942 /** 2943 * Count of how many windows this view has been attached to. 2944 */ 2945 int mWindowAttachCount; 2946 2947 /** 2948 * The layout parameters associated with this view and used by the parent 2949 * {@link android.view.ViewGroup} to determine how this view should be 2950 * laid out. 2951 * {@hide} 2952 */ 2953 protected ViewGroup.LayoutParams mLayoutParams; 2954 2955 /** 2956 * The view flags hold various views states. 2957 * {@hide} 2958 */ 2959 @ViewDebug.ExportedProperty 2960 int mViewFlags; 2961 2962 static class TransformationInfo { 2963 /** 2964 * The transform matrix for the View. This transform is calculated internally 2965 * based on the translation, rotation, and scale properties. 2966 * 2967 * Do *not* use this variable directly; instead call getMatrix(), which will 2968 * load the value from the View's RenderNode. 2969 */ 2970 private final Matrix mMatrix = new Matrix(); 2971 2972 /** 2973 * The inverse transform matrix for the View. This transform is calculated 2974 * internally based on the translation, rotation, and scale properties. 2975 * 2976 * Do *not* use this variable directly; instead call getInverseMatrix(), 2977 * which will load the value from the View's RenderNode. 2978 */ 2979 private Matrix mInverseMatrix; 2980 2981 /** 2982 * The opacity of the View. This is a value from 0 to 1, where 0 means 2983 * completely transparent and 1 means completely opaque. 2984 */ 2985 @ViewDebug.ExportedProperty 2986 float mAlpha = 1f; 2987 2988 /** 2989 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2990 * property only used by transitions, which is composited with the other alpha 2991 * values to calculate the final visual alpha value. 2992 */ 2993 float mTransitionAlpha = 1f; 2994 } 2995 2996 TransformationInfo mTransformationInfo; 2997 2998 /** 2999 * Current clip bounds. to which all drawing of this view are constrained. 3000 */ 3001 Rect mClipBounds = null; 3002 3003 private boolean mLastIsOpaque; 3004 3005 /** 3006 * The distance in pixels from the left edge of this view's parent 3007 * to the left edge of this view. 3008 * {@hide} 3009 */ 3010 @ViewDebug.ExportedProperty(category = "layout") 3011 protected int mLeft; 3012 /** 3013 * The distance in pixels from the left edge of this view's parent 3014 * to the right edge of this view. 3015 * {@hide} 3016 */ 3017 @ViewDebug.ExportedProperty(category = "layout") 3018 protected int mRight; 3019 /** 3020 * The distance in pixels from the top edge of this view's parent 3021 * to the top edge of this view. 3022 * {@hide} 3023 */ 3024 @ViewDebug.ExportedProperty(category = "layout") 3025 protected int mTop; 3026 /** 3027 * The distance in pixels from the top edge of this view's parent 3028 * to the bottom edge of this view. 3029 * {@hide} 3030 */ 3031 @ViewDebug.ExportedProperty(category = "layout") 3032 protected int mBottom; 3033 3034 /** 3035 * The offset, in pixels, by which the content of this view is scrolled 3036 * horizontally. 3037 * {@hide} 3038 */ 3039 @ViewDebug.ExportedProperty(category = "scrolling") 3040 protected int mScrollX; 3041 /** 3042 * The offset, in pixels, by which the content of this view is scrolled 3043 * vertically. 3044 * {@hide} 3045 */ 3046 @ViewDebug.ExportedProperty(category = "scrolling") 3047 protected int mScrollY; 3048 3049 /** 3050 * The left padding in pixels, that is the distance in pixels between the 3051 * left edge of this view and the left edge of its content. 3052 * {@hide} 3053 */ 3054 @ViewDebug.ExportedProperty(category = "padding") 3055 protected int mPaddingLeft = 0; 3056 /** 3057 * The right padding in pixels, that is the distance in pixels between the 3058 * right edge of this view and the right edge of its content. 3059 * {@hide} 3060 */ 3061 @ViewDebug.ExportedProperty(category = "padding") 3062 protected int mPaddingRight = 0; 3063 /** 3064 * The top padding in pixels, that is the distance in pixels between the 3065 * top edge of this view and the top edge of its content. 3066 * {@hide} 3067 */ 3068 @ViewDebug.ExportedProperty(category = "padding") 3069 protected int mPaddingTop; 3070 /** 3071 * The bottom padding in pixels, that is the distance in pixels between the 3072 * bottom edge of this view and the bottom edge of its content. 3073 * {@hide} 3074 */ 3075 @ViewDebug.ExportedProperty(category = "padding") 3076 protected int mPaddingBottom; 3077 3078 /** 3079 * The layout insets in pixels, that is the distance in pixels between the 3080 * visible edges of this view its bounds. 3081 */ 3082 private Insets mLayoutInsets; 3083 3084 /** 3085 * Briefly describes the view and is primarily used for accessibility support. 3086 */ 3087 private CharSequence mContentDescription; 3088 3089 /** 3090 * Specifies the id of a view for which this view serves as a label for 3091 * accessibility purposes. 3092 */ 3093 private int mLabelForId = View.NO_ID; 3094 3095 /** 3096 * Predicate for matching labeled view id with its label for 3097 * accessibility purposes. 3098 */ 3099 private MatchLabelForPredicate mMatchLabelForPredicate; 3100 3101 /** 3102 * Predicate for matching a view by its id. 3103 */ 3104 private MatchIdPredicate mMatchIdPredicate; 3105 3106 /** 3107 * Cache the paddingRight set by the user to append to the scrollbar's size. 3108 * 3109 * @hide 3110 */ 3111 @ViewDebug.ExportedProperty(category = "padding") 3112 protected int mUserPaddingRight; 3113 3114 /** 3115 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3116 * 3117 * @hide 3118 */ 3119 @ViewDebug.ExportedProperty(category = "padding") 3120 protected int mUserPaddingBottom; 3121 3122 /** 3123 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3124 * 3125 * @hide 3126 */ 3127 @ViewDebug.ExportedProperty(category = "padding") 3128 protected int mUserPaddingLeft; 3129 3130 /** 3131 * Cache the paddingStart set by the user to append to the scrollbar's size. 3132 * 3133 */ 3134 @ViewDebug.ExportedProperty(category = "padding") 3135 int mUserPaddingStart; 3136 3137 /** 3138 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3139 * 3140 */ 3141 @ViewDebug.ExportedProperty(category = "padding") 3142 int mUserPaddingEnd; 3143 3144 /** 3145 * Cache initial left padding. 3146 * 3147 * @hide 3148 */ 3149 int mUserPaddingLeftInitial; 3150 3151 /** 3152 * Cache initial right padding. 3153 * 3154 * @hide 3155 */ 3156 int mUserPaddingRightInitial; 3157 3158 /** 3159 * Default undefined padding 3160 */ 3161 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3162 3163 /** 3164 * Cache if a left padding has been defined 3165 */ 3166 private boolean mLeftPaddingDefined = false; 3167 3168 /** 3169 * Cache if a right padding has been defined 3170 */ 3171 private boolean mRightPaddingDefined = false; 3172 3173 /** 3174 * @hide 3175 */ 3176 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3177 /** 3178 * @hide 3179 */ 3180 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3181 3182 private LongSparseLongArray mMeasureCache; 3183 3184 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3185 private Drawable mBackground; 3186 private ColorStateList mBackgroundTint = null; 3187 private PorterDuff.Mode mBackgroundTintMode = PorterDuff.Mode.SRC_ATOP; 3188 private boolean mHasBackgroundTint = false; 3189 3190 /** 3191 * RenderNode used for backgrounds. 3192 * <p> 3193 * When non-null and valid, this is expected to contain an up-to-date copy 3194 * of the background drawable. It is cleared on temporary detach, and reset 3195 * on cleanup. 3196 */ 3197 private RenderNode mBackgroundRenderNode; 3198 3199 private int mBackgroundResource; 3200 private boolean mBackgroundSizeChanged; 3201 3202 private String mTransitionName; 3203 3204 static class ListenerInfo { 3205 /** 3206 * Listener used to dispatch focus change events. 3207 * This field should be made private, so it is hidden from the SDK. 3208 * {@hide} 3209 */ 3210 protected OnFocusChangeListener mOnFocusChangeListener; 3211 3212 /** 3213 * Listeners for layout change events. 3214 */ 3215 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3216 3217 /** 3218 * Listeners for attach events. 3219 */ 3220 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3221 3222 /** 3223 * Listener used to dispatch click events. 3224 * This field should be made private, so it is hidden from the SDK. 3225 * {@hide} 3226 */ 3227 public OnClickListener mOnClickListener; 3228 3229 /** 3230 * Listener used to dispatch long click events. 3231 * This field should be made private, so it is hidden from the SDK. 3232 * {@hide} 3233 */ 3234 protected OnLongClickListener mOnLongClickListener; 3235 3236 /** 3237 * Listener used to build the context menu. 3238 * This field should be made private, so it is hidden from the SDK. 3239 * {@hide} 3240 */ 3241 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3242 3243 private OnKeyListener mOnKeyListener; 3244 3245 private OnTouchListener mOnTouchListener; 3246 3247 private OnHoverListener mOnHoverListener; 3248 3249 private OnGenericMotionListener mOnGenericMotionListener; 3250 3251 private OnDragListener mOnDragListener; 3252 3253 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3254 3255 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3256 } 3257 3258 ListenerInfo mListenerInfo; 3259 3260 /** 3261 * The application environment this view lives in. 3262 * This field should be made private, so it is hidden from the SDK. 3263 * {@hide} 3264 */ 3265 protected Context mContext; 3266 3267 private final Resources mResources; 3268 3269 private ScrollabilityCache mScrollCache; 3270 3271 private int[] mDrawableState = null; 3272 3273 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3274 3275 /** 3276 * Animator that automatically runs based on state changes. 3277 */ 3278 private StateListAnimator mStateListAnimator; 3279 3280 /** 3281 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3282 * the user may specify which view to go to next. 3283 */ 3284 private int mNextFocusLeftId = View.NO_ID; 3285 3286 /** 3287 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3288 * the user may specify which view to go to next. 3289 */ 3290 private int mNextFocusRightId = View.NO_ID; 3291 3292 /** 3293 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3294 * the user may specify which view to go to next. 3295 */ 3296 private int mNextFocusUpId = View.NO_ID; 3297 3298 /** 3299 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3300 * the user may specify which view to go to next. 3301 */ 3302 private int mNextFocusDownId = View.NO_ID; 3303 3304 /** 3305 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3306 * the user may specify which view to go to next. 3307 */ 3308 int mNextFocusForwardId = View.NO_ID; 3309 3310 private CheckForLongPress mPendingCheckForLongPress; 3311 private CheckForTap mPendingCheckForTap = null; 3312 private PerformClick mPerformClick; 3313 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3314 3315 private UnsetPressedState mUnsetPressedState; 3316 3317 /** 3318 * Whether the long press's action has been invoked. The tap's action is invoked on the 3319 * up event while a long press is invoked as soon as the long press duration is reached, so 3320 * a long press could be performed before the tap is checked, in which case the tap's action 3321 * should not be invoked. 3322 */ 3323 private boolean mHasPerformedLongPress; 3324 3325 /** 3326 * The minimum height of the view. We'll try our best to have the height 3327 * of this view to at least this amount. 3328 */ 3329 @ViewDebug.ExportedProperty(category = "measurement") 3330 private int mMinHeight; 3331 3332 /** 3333 * The minimum width of the view. We'll try our best to have the width 3334 * of this view to at least this amount. 3335 */ 3336 @ViewDebug.ExportedProperty(category = "measurement") 3337 private int mMinWidth; 3338 3339 /** 3340 * The delegate to handle touch events that are physically in this view 3341 * but should be handled by another view. 3342 */ 3343 private TouchDelegate mTouchDelegate = null; 3344 3345 /** 3346 * Solid color to use as a background when creating the drawing cache. Enables 3347 * the cache to use 16 bit bitmaps instead of 32 bit. 3348 */ 3349 private int mDrawingCacheBackgroundColor = 0; 3350 3351 /** 3352 * Special tree observer used when mAttachInfo is null. 3353 */ 3354 private ViewTreeObserver mFloatingTreeObserver; 3355 3356 /** 3357 * Cache the touch slop from the context that created the view. 3358 */ 3359 private int mTouchSlop; 3360 3361 /** 3362 * Object that handles automatic animation of view properties. 3363 */ 3364 private ViewPropertyAnimator mAnimator = null; 3365 3366 /** 3367 * Flag indicating that a drag can cross window boundaries. When 3368 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3369 * with this flag set, all visible applications will be able to participate 3370 * in the drag operation and receive the dragged content. 3371 * 3372 * @hide 3373 */ 3374 public static final int DRAG_FLAG_GLOBAL = 1; 3375 3376 /** 3377 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3378 */ 3379 private float mVerticalScrollFactor; 3380 3381 /** 3382 * Position of the vertical scroll bar. 3383 */ 3384 private int mVerticalScrollbarPosition; 3385 3386 /** 3387 * Position the scroll bar at the default position as determined by the system. 3388 */ 3389 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3390 3391 /** 3392 * Position the scroll bar along the left edge. 3393 */ 3394 public static final int SCROLLBAR_POSITION_LEFT = 1; 3395 3396 /** 3397 * Position the scroll bar along the right edge. 3398 */ 3399 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3400 3401 /** 3402 * Indicates that the view does not have a layer. 3403 * 3404 * @see #getLayerType() 3405 * @see #setLayerType(int, android.graphics.Paint) 3406 * @see #LAYER_TYPE_SOFTWARE 3407 * @see #LAYER_TYPE_HARDWARE 3408 */ 3409 public static final int LAYER_TYPE_NONE = 0; 3410 3411 /** 3412 * <p>Indicates that the view has a software layer. A software layer is backed 3413 * by a bitmap and causes the view to be rendered using Android's software 3414 * rendering pipeline, even if hardware acceleration is enabled.</p> 3415 * 3416 * <p>Software layers have various usages:</p> 3417 * <p>When the application is not using hardware acceleration, a software layer 3418 * is useful to apply a specific color filter and/or blending mode and/or 3419 * translucency to a view and all its children.</p> 3420 * <p>When the application is using hardware acceleration, a software layer 3421 * is useful to render drawing primitives not supported by the hardware 3422 * accelerated pipeline. It can also be used to cache a complex view tree 3423 * into a texture and reduce the complexity of drawing operations. For instance, 3424 * when animating a complex view tree with a translation, a software layer can 3425 * be used to render the view tree only once.</p> 3426 * <p>Software layers should be avoided when the affected view tree updates 3427 * often. Every update will require to re-render the software layer, which can 3428 * potentially be slow (particularly when hardware acceleration is turned on 3429 * since the layer will have to be uploaded into a hardware texture after every 3430 * update.)</p> 3431 * 3432 * @see #getLayerType() 3433 * @see #setLayerType(int, android.graphics.Paint) 3434 * @see #LAYER_TYPE_NONE 3435 * @see #LAYER_TYPE_HARDWARE 3436 */ 3437 public static final int LAYER_TYPE_SOFTWARE = 1; 3438 3439 /** 3440 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3441 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3442 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3443 * rendering pipeline, but only if hardware acceleration is turned on for the 3444 * view hierarchy. When hardware acceleration is turned off, hardware layers 3445 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3446 * 3447 * <p>A hardware layer is useful to apply a specific color filter and/or 3448 * blending mode and/or translucency to a view and all its children.</p> 3449 * <p>A hardware layer can be used to cache a complex view tree into a 3450 * texture and reduce the complexity of drawing operations. For instance, 3451 * when animating a complex view tree with a translation, a hardware layer can 3452 * be used to render the view tree only once.</p> 3453 * <p>A hardware layer can also be used to increase the rendering quality when 3454 * rotation transformations are applied on a view. It can also be used to 3455 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3456 * 3457 * @see #getLayerType() 3458 * @see #setLayerType(int, android.graphics.Paint) 3459 * @see #LAYER_TYPE_NONE 3460 * @see #LAYER_TYPE_SOFTWARE 3461 */ 3462 public static final int LAYER_TYPE_HARDWARE = 2; 3463 3464 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3465 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3466 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3467 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3468 }) 3469 int mLayerType = LAYER_TYPE_NONE; 3470 Paint mLayerPaint; 3471 3472 /** 3473 * Set to true when drawing cache is enabled and cannot be created. 3474 * 3475 * @hide 3476 */ 3477 public boolean mCachingFailed; 3478 private Bitmap mDrawingCache; 3479 private Bitmap mUnscaledDrawingCache; 3480 3481 /** 3482 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3483 * <p> 3484 * When non-null and valid, this is expected to contain an up-to-date copy 3485 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3486 * cleanup. 3487 */ 3488 final RenderNode mRenderNode; 3489 3490 /** 3491 * Set to true when the view is sending hover accessibility events because it 3492 * is the innermost hovered view. 3493 */ 3494 private boolean mSendingHoverAccessibilityEvents; 3495 3496 /** 3497 * Delegate for injecting accessibility functionality. 3498 */ 3499 AccessibilityDelegate mAccessibilityDelegate; 3500 3501 /** 3502 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3503 * and add/remove objects to/from the overlay directly through the Overlay methods. 3504 */ 3505 ViewOverlay mOverlay; 3506 3507 /** 3508 * The currently active parent view for receiving delegated nested scrolling events. 3509 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3510 * by {@link #stopNestedScroll()} at the same point where we clear 3511 * requestDisallowInterceptTouchEvent. 3512 */ 3513 private ViewParent mNestedScrollingParent; 3514 3515 /** 3516 * Consistency verifier for debugging purposes. 3517 * @hide 3518 */ 3519 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3520 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3521 new InputEventConsistencyVerifier(this, 0) : null; 3522 3523 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3524 3525 private int[] mTempNestedScrollConsumed; 3526 3527 /** 3528 * Simple constructor to use when creating a view from code. 3529 * 3530 * @param context The Context the view is running in, through which it can 3531 * access the current theme, resources, etc. 3532 */ 3533 public View(Context context) { 3534 mContext = context; 3535 mResources = context != null ? context.getResources() : null; 3536 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3537 // Set some flags defaults 3538 mPrivateFlags2 = 3539 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3540 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3541 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3542 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3543 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3544 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3545 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3546 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3547 mUserPaddingStart = UNDEFINED_PADDING; 3548 mUserPaddingEnd = UNDEFINED_PADDING; 3549 mRenderNode = RenderNode.create(getClass().getName()); 3550 3551 if (!sCompatibilityDone && context != null) { 3552 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3553 3554 // Older apps may need this compatibility hack for measurement. 3555 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3556 3557 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3558 // of whether a layout was requested on that View. 3559 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3560 3561 // Older apps may need this to ignore the clip bounds 3562 sIgnoreClipBoundsForChildren = targetSdkVersion < L; 3563 3564 sCompatibilityDone = true; 3565 } 3566 } 3567 3568 /** 3569 * Constructor that is called when inflating a view from XML. This is called 3570 * when a view is being constructed from an XML file, supplying attributes 3571 * that were specified in the XML file. This version uses a default style of 3572 * 0, so the only attribute values applied are those in the Context's Theme 3573 * and the given AttributeSet. 3574 * 3575 * <p> 3576 * The method onFinishInflate() will be called after all children have been 3577 * added. 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 * @see #View(Context, AttributeSet, int) 3583 */ 3584 public View(Context context, AttributeSet attrs) { 3585 this(context, attrs, 0); 3586 } 3587 3588 /** 3589 * Perform inflation from XML and apply a class-specific base style from a 3590 * theme attribute. This constructor of View allows subclasses to use their 3591 * own base style when they are inflating. For example, a Button class's 3592 * constructor would call this version of the super class constructor and 3593 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3594 * allows the theme's button style to modify all of the base view attributes 3595 * (in particular its background) as well as the Button class's attributes. 3596 * 3597 * @param context The Context the view is running in, through which it can 3598 * access the current theme, resources, etc. 3599 * @param attrs The attributes of the XML tag that is inflating the view. 3600 * @param defStyleAttr An attribute in the current theme that contains a 3601 * reference to a style resource that supplies default values for 3602 * the view. Can be 0 to not look for defaults. 3603 * @see #View(Context, AttributeSet) 3604 */ 3605 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3606 this(context, attrs, defStyleAttr, 0); 3607 } 3608 3609 /** 3610 * Perform inflation from XML and apply a class-specific base style from a 3611 * theme attribute or style resource. This constructor of View allows 3612 * subclasses to use their own base style when they are inflating. 3613 * <p> 3614 * When determining the final value of a particular attribute, there are 3615 * four inputs that come into play: 3616 * <ol> 3617 * <li>Any attribute values in the given AttributeSet. 3618 * <li>The style resource specified in the AttributeSet (named "style"). 3619 * <li>The default style specified by <var>defStyleAttr</var>. 3620 * <li>The default style specified by <var>defStyleRes</var>. 3621 * <li>The base values in this theme. 3622 * </ol> 3623 * <p> 3624 * Each of these inputs is considered in-order, with the first listed taking 3625 * precedence over the following ones. In other words, if in the 3626 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3627 * , then the button's text will <em>always</em> be black, regardless of 3628 * what is specified in any of the styles. 3629 * 3630 * @param context The Context the view is running in, through which it can 3631 * access the current theme, resources, etc. 3632 * @param attrs The attributes of the XML tag that is inflating the view. 3633 * @param defStyleAttr An attribute in the current theme that contains a 3634 * reference to a style resource that supplies default values for 3635 * the view. Can be 0 to not look for defaults. 3636 * @param defStyleRes A resource identifier of a style resource that 3637 * supplies default values for the view, used only if 3638 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3639 * to not look for defaults. 3640 * @see #View(Context, AttributeSet, int) 3641 */ 3642 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3643 this(context); 3644 3645 final TypedArray a = context.obtainStyledAttributes( 3646 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3647 3648 Drawable background = null; 3649 3650 int leftPadding = -1; 3651 int topPadding = -1; 3652 int rightPadding = -1; 3653 int bottomPadding = -1; 3654 int startPadding = UNDEFINED_PADDING; 3655 int endPadding = UNDEFINED_PADDING; 3656 3657 int padding = -1; 3658 3659 int viewFlagValues = 0; 3660 int viewFlagMasks = 0; 3661 3662 boolean setScrollContainer = false; 3663 3664 int x = 0; 3665 int y = 0; 3666 3667 float tx = 0; 3668 float ty = 0; 3669 float tz = 0; 3670 float elevation = 0; 3671 float rotation = 0; 3672 float rotationX = 0; 3673 float rotationY = 0; 3674 float sx = 1f; 3675 float sy = 1f; 3676 boolean transformSet = false; 3677 3678 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3679 int overScrollMode = mOverScrollMode; 3680 boolean initializeScrollbars = false; 3681 3682 boolean startPaddingDefined = false; 3683 boolean endPaddingDefined = false; 3684 boolean leftPaddingDefined = false; 3685 boolean rightPaddingDefined = false; 3686 3687 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3688 3689 final int N = a.getIndexCount(); 3690 for (int i = 0; i < N; i++) { 3691 int attr = a.getIndex(i); 3692 switch (attr) { 3693 case com.android.internal.R.styleable.View_background: 3694 background = a.getDrawable(attr); 3695 break; 3696 case com.android.internal.R.styleable.View_padding: 3697 padding = a.getDimensionPixelSize(attr, -1); 3698 mUserPaddingLeftInitial = padding; 3699 mUserPaddingRightInitial = padding; 3700 leftPaddingDefined = true; 3701 rightPaddingDefined = true; 3702 break; 3703 case com.android.internal.R.styleable.View_paddingLeft: 3704 leftPadding = a.getDimensionPixelSize(attr, -1); 3705 mUserPaddingLeftInitial = leftPadding; 3706 leftPaddingDefined = true; 3707 break; 3708 case com.android.internal.R.styleable.View_paddingTop: 3709 topPadding = a.getDimensionPixelSize(attr, -1); 3710 break; 3711 case com.android.internal.R.styleable.View_paddingRight: 3712 rightPadding = a.getDimensionPixelSize(attr, -1); 3713 mUserPaddingRightInitial = rightPadding; 3714 rightPaddingDefined = true; 3715 break; 3716 case com.android.internal.R.styleable.View_paddingBottom: 3717 bottomPadding = a.getDimensionPixelSize(attr, -1); 3718 break; 3719 case com.android.internal.R.styleable.View_paddingStart: 3720 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3721 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3722 break; 3723 case com.android.internal.R.styleable.View_paddingEnd: 3724 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3725 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3726 break; 3727 case com.android.internal.R.styleable.View_scrollX: 3728 x = a.getDimensionPixelOffset(attr, 0); 3729 break; 3730 case com.android.internal.R.styleable.View_scrollY: 3731 y = a.getDimensionPixelOffset(attr, 0); 3732 break; 3733 case com.android.internal.R.styleable.View_alpha: 3734 setAlpha(a.getFloat(attr, 1f)); 3735 break; 3736 case com.android.internal.R.styleable.View_transformPivotX: 3737 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3738 break; 3739 case com.android.internal.R.styleable.View_transformPivotY: 3740 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3741 break; 3742 case com.android.internal.R.styleable.View_translationX: 3743 tx = a.getDimensionPixelOffset(attr, 0); 3744 transformSet = true; 3745 break; 3746 case com.android.internal.R.styleable.View_translationY: 3747 ty = a.getDimensionPixelOffset(attr, 0); 3748 transformSet = true; 3749 break; 3750 case com.android.internal.R.styleable.View_translationZ: 3751 tz = a.getDimensionPixelOffset(attr, 0); 3752 transformSet = true; 3753 break; 3754 case com.android.internal.R.styleable.View_elevation: 3755 elevation = a.getDimensionPixelOffset(attr, 0); 3756 transformSet = true; 3757 break; 3758 case com.android.internal.R.styleable.View_rotation: 3759 rotation = a.getFloat(attr, 0); 3760 transformSet = true; 3761 break; 3762 case com.android.internal.R.styleable.View_rotationX: 3763 rotationX = a.getFloat(attr, 0); 3764 transformSet = true; 3765 break; 3766 case com.android.internal.R.styleable.View_rotationY: 3767 rotationY = a.getFloat(attr, 0); 3768 transformSet = true; 3769 break; 3770 case com.android.internal.R.styleable.View_scaleX: 3771 sx = a.getFloat(attr, 1f); 3772 transformSet = true; 3773 break; 3774 case com.android.internal.R.styleable.View_scaleY: 3775 sy = a.getFloat(attr, 1f); 3776 transformSet = true; 3777 break; 3778 case com.android.internal.R.styleable.View_id: 3779 mID = a.getResourceId(attr, NO_ID); 3780 break; 3781 case com.android.internal.R.styleable.View_tag: 3782 mTag = a.getText(attr); 3783 break; 3784 case com.android.internal.R.styleable.View_fitsSystemWindows: 3785 if (a.getBoolean(attr, false)) { 3786 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3787 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3788 } 3789 break; 3790 case com.android.internal.R.styleable.View_focusable: 3791 if (a.getBoolean(attr, false)) { 3792 viewFlagValues |= FOCUSABLE; 3793 viewFlagMasks |= FOCUSABLE_MASK; 3794 } 3795 break; 3796 case com.android.internal.R.styleable.View_focusableInTouchMode: 3797 if (a.getBoolean(attr, false)) { 3798 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3799 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3800 } 3801 break; 3802 case com.android.internal.R.styleable.View_clickable: 3803 if (a.getBoolean(attr, false)) { 3804 viewFlagValues |= CLICKABLE; 3805 viewFlagMasks |= CLICKABLE; 3806 } 3807 break; 3808 case com.android.internal.R.styleable.View_longClickable: 3809 if (a.getBoolean(attr, false)) { 3810 viewFlagValues |= LONG_CLICKABLE; 3811 viewFlagMasks |= LONG_CLICKABLE; 3812 } 3813 break; 3814 case com.android.internal.R.styleable.View_saveEnabled: 3815 if (!a.getBoolean(attr, true)) { 3816 viewFlagValues |= SAVE_DISABLED; 3817 viewFlagMasks |= SAVE_DISABLED_MASK; 3818 } 3819 break; 3820 case com.android.internal.R.styleable.View_duplicateParentState: 3821 if (a.getBoolean(attr, false)) { 3822 viewFlagValues |= DUPLICATE_PARENT_STATE; 3823 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3824 } 3825 break; 3826 case com.android.internal.R.styleable.View_visibility: 3827 final int visibility = a.getInt(attr, 0); 3828 if (visibility != 0) { 3829 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3830 viewFlagMasks |= VISIBILITY_MASK; 3831 } 3832 break; 3833 case com.android.internal.R.styleable.View_layoutDirection: 3834 // Clear any layout direction flags (included resolved bits) already set 3835 mPrivateFlags2 &= 3836 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3837 // Set the layout direction flags depending on the value of the attribute 3838 final int layoutDirection = a.getInt(attr, -1); 3839 final int value = (layoutDirection != -1) ? 3840 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3841 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3842 break; 3843 case com.android.internal.R.styleable.View_drawingCacheQuality: 3844 final int cacheQuality = a.getInt(attr, 0); 3845 if (cacheQuality != 0) { 3846 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3847 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3848 } 3849 break; 3850 case com.android.internal.R.styleable.View_contentDescription: 3851 setContentDescription(a.getString(attr)); 3852 break; 3853 case com.android.internal.R.styleable.View_labelFor: 3854 setLabelFor(a.getResourceId(attr, NO_ID)); 3855 break; 3856 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3857 if (!a.getBoolean(attr, true)) { 3858 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3859 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3860 } 3861 break; 3862 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3863 if (!a.getBoolean(attr, true)) { 3864 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3865 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3866 } 3867 break; 3868 case R.styleable.View_scrollbars: 3869 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3870 if (scrollbars != SCROLLBARS_NONE) { 3871 viewFlagValues |= scrollbars; 3872 viewFlagMasks |= SCROLLBARS_MASK; 3873 initializeScrollbars = true; 3874 } 3875 break; 3876 //noinspection deprecation 3877 case R.styleable.View_fadingEdge: 3878 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3879 // Ignore the attribute starting with ICS 3880 break; 3881 } 3882 // With builds < ICS, fall through and apply fading edges 3883 case R.styleable.View_requiresFadingEdge: 3884 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3885 if (fadingEdge != FADING_EDGE_NONE) { 3886 viewFlagValues |= fadingEdge; 3887 viewFlagMasks |= FADING_EDGE_MASK; 3888 initializeFadingEdgeInternal(a); 3889 } 3890 break; 3891 case R.styleable.View_scrollbarStyle: 3892 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3893 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3894 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3895 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3896 } 3897 break; 3898 case R.styleable.View_isScrollContainer: 3899 setScrollContainer = true; 3900 if (a.getBoolean(attr, false)) { 3901 setScrollContainer(true); 3902 } 3903 break; 3904 case com.android.internal.R.styleable.View_keepScreenOn: 3905 if (a.getBoolean(attr, false)) { 3906 viewFlagValues |= KEEP_SCREEN_ON; 3907 viewFlagMasks |= KEEP_SCREEN_ON; 3908 } 3909 break; 3910 case R.styleable.View_filterTouchesWhenObscured: 3911 if (a.getBoolean(attr, false)) { 3912 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3913 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3914 } 3915 break; 3916 case R.styleable.View_nextFocusLeft: 3917 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3918 break; 3919 case R.styleable.View_nextFocusRight: 3920 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3921 break; 3922 case R.styleable.View_nextFocusUp: 3923 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3924 break; 3925 case R.styleable.View_nextFocusDown: 3926 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3927 break; 3928 case R.styleable.View_nextFocusForward: 3929 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3930 break; 3931 case R.styleable.View_minWidth: 3932 mMinWidth = a.getDimensionPixelSize(attr, 0); 3933 break; 3934 case R.styleable.View_minHeight: 3935 mMinHeight = a.getDimensionPixelSize(attr, 0); 3936 break; 3937 case R.styleable.View_onClick: 3938 if (context.isRestricted()) { 3939 throw new IllegalStateException("The android:onClick attribute cannot " 3940 + "be used within a restricted context"); 3941 } 3942 3943 final String handlerName = a.getString(attr); 3944 if (handlerName != null) { 3945 setOnClickListener(new OnClickListener() { 3946 private Method mHandler; 3947 3948 public void onClick(View v) { 3949 if (mHandler == null) { 3950 try { 3951 mHandler = getContext().getClass().getMethod(handlerName, 3952 View.class); 3953 } catch (NoSuchMethodException e) { 3954 int id = getId(); 3955 String idText = id == NO_ID ? "" : " with id '" 3956 + getContext().getResources().getResourceEntryName( 3957 id) + "'"; 3958 throw new IllegalStateException("Could not find a method " + 3959 handlerName + "(View) in the activity " 3960 + getContext().getClass() + " for onClick handler" 3961 + " on view " + View.this.getClass() + idText, e); 3962 } 3963 } 3964 3965 try { 3966 mHandler.invoke(getContext(), View.this); 3967 } catch (IllegalAccessException e) { 3968 throw new IllegalStateException("Could not execute non " 3969 + "public method of the activity", e); 3970 } catch (InvocationTargetException e) { 3971 throw new IllegalStateException("Could not execute " 3972 + "method of the activity", e); 3973 } 3974 } 3975 }); 3976 } 3977 break; 3978 case R.styleable.View_overScrollMode: 3979 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3980 break; 3981 case R.styleable.View_verticalScrollbarPosition: 3982 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3983 break; 3984 case R.styleable.View_layerType: 3985 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3986 break; 3987 case R.styleable.View_textDirection: 3988 // Clear any text direction flag already set 3989 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3990 // Set the text direction flags depending on the value of the attribute 3991 final int textDirection = a.getInt(attr, -1); 3992 if (textDirection != -1) { 3993 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3994 } 3995 break; 3996 case R.styleable.View_textAlignment: 3997 // Clear any text alignment flag already set 3998 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3999 // Set the text alignment flag depending on the value of the attribute 4000 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4001 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4002 break; 4003 case R.styleable.View_importantForAccessibility: 4004 setImportantForAccessibility(a.getInt(attr, 4005 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4006 break; 4007 case R.styleable.View_accessibilityLiveRegion: 4008 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4009 break; 4010 case R.styleable.View_transitionName: 4011 setTransitionName(a.getString(attr)); 4012 break; 4013 case R.styleable.View_nestedScrollingEnabled: 4014 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4015 break; 4016 case R.styleable.View_stateListAnimator: 4017 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4018 a.getResourceId(attr, 0))); 4019 break; 4020 case R.styleable.View_backgroundTint: 4021 // This will get applied later during setBackground(). 4022 mBackgroundTint = a.getColorStateList(R.styleable.View_backgroundTint); 4023 mHasBackgroundTint = true; 4024 break; 4025 case R.styleable.View_backgroundTintMode: 4026 // This will get applied later during setBackground(). 4027 mBackgroundTintMode = Drawable.parseTintMode(a.getInt( 4028 R.styleable.View_backgroundTintMode, -1), mBackgroundTintMode); 4029 break; 4030 } 4031 } 4032 4033 setOverScrollMode(overScrollMode); 4034 4035 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4036 // the resolved layout direction). Those cached values will be used later during padding 4037 // resolution. 4038 mUserPaddingStart = startPadding; 4039 mUserPaddingEnd = endPadding; 4040 4041 if (background != null) { 4042 setBackground(background); 4043 } 4044 4045 // setBackground above will record that padding is currently provided by the background. 4046 // If we have padding specified via xml, record that here instead and use it. 4047 mLeftPaddingDefined = leftPaddingDefined; 4048 mRightPaddingDefined = rightPaddingDefined; 4049 4050 if (padding >= 0) { 4051 leftPadding = padding; 4052 topPadding = padding; 4053 rightPadding = padding; 4054 bottomPadding = padding; 4055 mUserPaddingLeftInitial = padding; 4056 mUserPaddingRightInitial = padding; 4057 } 4058 4059 if (isRtlCompatibilityMode()) { 4060 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4061 // left / right padding are used if defined (meaning here nothing to do). If they are not 4062 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4063 // start / end and resolve them as left / right (layout direction is not taken into account). 4064 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4065 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4066 // defined. 4067 if (!mLeftPaddingDefined && startPaddingDefined) { 4068 leftPadding = startPadding; 4069 } 4070 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4071 if (!mRightPaddingDefined && endPaddingDefined) { 4072 rightPadding = endPadding; 4073 } 4074 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4075 } else { 4076 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4077 // values defined. Otherwise, left /right values are used. 4078 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4079 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4080 // defined. 4081 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4082 4083 if (mLeftPaddingDefined && !hasRelativePadding) { 4084 mUserPaddingLeftInitial = leftPadding; 4085 } 4086 if (mRightPaddingDefined && !hasRelativePadding) { 4087 mUserPaddingRightInitial = rightPadding; 4088 } 4089 } 4090 4091 internalSetPadding( 4092 mUserPaddingLeftInitial, 4093 topPadding >= 0 ? topPadding : mPaddingTop, 4094 mUserPaddingRightInitial, 4095 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4096 4097 if (viewFlagMasks != 0) { 4098 setFlags(viewFlagValues, viewFlagMasks); 4099 } 4100 4101 if (initializeScrollbars) { 4102 initializeScrollbarsInternal(a); 4103 } 4104 4105 a.recycle(); 4106 4107 // Needs to be called after mViewFlags is set 4108 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4109 recomputePadding(); 4110 } 4111 4112 if (x != 0 || y != 0) { 4113 scrollTo(x, y); 4114 } 4115 4116 if (transformSet) { 4117 setTranslationX(tx); 4118 setTranslationY(ty); 4119 setTranslationZ(tz); 4120 setElevation(elevation); 4121 setRotation(rotation); 4122 setRotationX(rotationX); 4123 setRotationY(rotationY); 4124 setScaleX(sx); 4125 setScaleY(sy); 4126 } 4127 4128 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4129 setScrollContainer(true); 4130 } 4131 4132 computeOpaqueFlags(); 4133 } 4134 4135 /** 4136 * Non-public constructor for use in testing 4137 */ 4138 View() { 4139 mResources = null; 4140 mRenderNode = RenderNode.create(getClass().getName()); 4141 } 4142 4143 public String toString() { 4144 StringBuilder out = new StringBuilder(128); 4145 out.append(getClass().getName()); 4146 out.append('{'); 4147 out.append(Integer.toHexString(System.identityHashCode(this))); 4148 out.append(' '); 4149 switch (mViewFlags&VISIBILITY_MASK) { 4150 case VISIBLE: out.append('V'); break; 4151 case INVISIBLE: out.append('I'); break; 4152 case GONE: out.append('G'); break; 4153 default: out.append('.'); break; 4154 } 4155 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4156 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4157 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4158 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4159 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4160 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4161 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4162 out.append(' '); 4163 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4164 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4165 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4166 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4167 out.append('p'); 4168 } else { 4169 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4170 } 4171 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4172 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4173 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4174 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4175 out.append(' '); 4176 out.append(mLeft); 4177 out.append(','); 4178 out.append(mTop); 4179 out.append('-'); 4180 out.append(mRight); 4181 out.append(','); 4182 out.append(mBottom); 4183 final int id = getId(); 4184 if (id != NO_ID) { 4185 out.append(" #"); 4186 out.append(Integer.toHexString(id)); 4187 final Resources r = mResources; 4188 if (Resources.resourceHasPackage(id) && r != null) { 4189 try { 4190 String pkgname; 4191 switch (id&0xff000000) { 4192 case 0x7f000000: 4193 pkgname="app"; 4194 break; 4195 case 0x01000000: 4196 pkgname="android"; 4197 break; 4198 default: 4199 pkgname = r.getResourcePackageName(id); 4200 break; 4201 } 4202 String typename = r.getResourceTypeName(id); 4203 String entryname = r.getResourceEntryName(id); 4204 out.append(" "); 4205 out.append(pkgname); 4206 out.append(":"); 4207 out.append(typename); 4208 out.append("/"); 4209 out.append(entryname); 4210 } catch (Resources.NotFoundException e) { 4211 } 4212 } 4213 } 4214 out.append("}"); 4215 return out.toString(); 4216 } 4217 4218 /** 4219 * <p> 4220 * Initializes the fading edges from a given set of styled attributes. This 4221 * method should be called by subclasses that need fading edges and when an 4222 * instance of these subclasses is created programmatically rather than 4223 * being inflated from XML. This method is automatically called when the XML 4224 * is inflated. 4225 * </p> 4226 * 4227 * @param a the styled attributes set to initialize the fading edges from 4228 */ 4229 protected void initializeFadingEdge(TypedArray a) { 4230 // This method probably shouldn't have been included in the SDK to begin with. 4231 // It relies on 'a' having been initialized using an attribute filter array that is 4232 // not publicly available to the SDK. The old method has been renamed 4233 // to initializeFadingEdgeInternal and hidden for framework use only; 4234 // this one initializes using defaults to make it safe to call for apps. 4235 4236 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4237 4238 initializeFadingEdgeInternal(arr); 4239 4240 arr.recycle(); 4241 } 4242 4243 /** 4244 * <p> 4245 * Initializes the fading edges from a given set of styled attributes. This 4246 * method should be called by subclasses that need fading edges and when an 4247 * instance of these subclasses is created programmatically rather than 4248 * being inflated from XML. This method is automatically called when the XML 4249 * is inflated. 4250 * </p> 4251 * 4252 * @param a the styled attributes set to initialize the fading edges from 4253 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4254 */ 4255 protected void initializeFadingEdgeInternal(TypedArray a) { 4256 initScrollCache(); 4257 4258 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4259 R.styleable.View_fadingEdgeLength, 4260 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4261 } 4262 4263 /** 4264 * Returns the size of the vertical faded edges used to indicate that more 4265 * content in this view is visible. 4266 * 4267 * @return The size in pixels of the vertical faded edge or 0 if vertical 4268 * faded edges are not enabled for this view. 4269 * @attr ref android.R.styleable#View_fadingEdgeLength 4270 */ 4271 public int getVerticalFadingEdgeLength() { 4272 if (isVerticalFadingEdgeEnabled()) { 4273 ScrollabilityCache cache = mScrollCache; 4274 if (cache != null) { 4275 return cache.fadingEdgeLength; 4276 } 4277 } 4278 return 0; 4279 } 4280 4281 /** 4282 * Set the size of the faded edge used to indicate that more content in this 4283 * view is available. Will not change whether the fading edge is enabled; use 4284 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4285 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4286 * for the vertical or horizontal fading edges. 4287 * 4288 * @param length The size in pixels of the faded edge used to indicate that more 4289 * content in this view is visible. 4290 */ 4291 public void setFadingEdgeLength(int length) { 4292 initScrollCache(); 4293 mScrollCache.fadingEdgeLength = length; 4294 } 4295 4296 /** 4297 * Returns the size of the horizontal faded edges used to indicate that more 4298 * content in this view is visible. 4299 * 4300 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4301 * faded edges are not enabled for this view. 4302 * @attr ref android.R.styleable#View_fadingEdgeLength 4303 */ 4304 public int getHorizontalFadingEdgeLength() { 4305 if (isHorizontalFadingEdgeEnabled()) { 4306 ScrollabilityCache cache = mScrollCache; 4307 if (cache != null) { 4308 return cache.fadingEdgeLength; 4309 } 4310 } 4311 return 0; 4312 } 4313 4314 /** 4315 * Returns the width of the vertical scrollbar. 4316 * 4317 * @return The width in pixels of the vertical scrollbar or 0 if there 4318 * is no vertical scrollbar. 4319 */ 4320 public int getVerticalScrollbarWidth() { 4321 ScrollabilityCache cache = mScrollCache; 4322 if (cache != null) { 4323 ScrollBarDrawable scrollBar = cache.scrollBar; 4324 if (scrollBar != null) { 4325 int size = scrollBar.getSize(true); 4326 if (size <= 0) { 4327 size = cache.scrollBarSize; 4328 } 4329 return size; 4330 } 4331 return 0; 4332 } 4333 return 0; 4334 } 4335 4336 /** 4337 * Returns the height of the horizontal scrollbar. 4338 * 4339 * @return The height in pixels of the horizontal scrollbar or 0 if 4340 * there is no horizontal scrollbar. 4341 */ 4342 protected int getHorizontalScrollbarHeight() { 4343 ScrollabilityCache cache = mScrollCache; 4344 if (cache != null) { 4345 ScrollBarDrawable scrollBar = cache.scrollBar; 4346 if (scrollBar != null) { 4347 int size = scrollBar.getSize(false); 4348 if (size <= 0) { 4349 size = cache.scrollBarSize; 4350 } 4351 return size; 4352 } 4353 return 0; 4354 } 4355 return 0; 4356 } 4357 4358 /** 4359 * <p> 4360 * Initializes the scrollbars from a given set of styled attributes. This 4361 * method should be called by subclasses that need scrollbars and when an 4362 * instance of these subclasses is created programmatically rather than 4363 * being inflated from XML. This method is automatically called when the XML 4364 * is inflated. 4365 * </p> 4366 * 4367 * @param a the styled attributes set to initialize the scrollbars from 4368 */ 4369 protected void initializeScrollbars(TypedArray a) { 4370 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4371 // using the View filter array which is not available to the SDK. As such, internal 4372 // framework usage now uses initializeScrollbarsInternal and we grab a default 4373 // TypedArray with the right filter instead here. 4374 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4375 4376 initializeScrollbarsInternal(arr); 4377 4378 // We ignored the method parameter. Recycle the one we actually did use. 4379 arr.recycle(); 4380 } 4381 4382 /** 4383 * <p> 4384 * Initializes the scrollbars from a given set of styled attributes. This 4385 * method should be called by subclasses that need scrollbars and when an 4386 * instance of these subclasses is created programmatically rather than 4387 * being inflated from XML. This method is automatically called when the XML 4388 * is inflated. 4389 * </p> 4390 * 4391 * @param a the styled attributes set to initialize the scrollbars from 4392 * @hide 4393 */ 4394 protected void initializeScrollbarsInternal(TypedArray a) { 4395 initScrollCache(); 4396 4397 final ScrollabilityCache scrollabilityCache = mScrollCache; 4398 4399 if (scrollabilityCache.scrollBar == null) { 4400 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4401 } 4402 4403 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4404 4405 if (!fadeScrollbars) { 4406 scrollabilityCache.state = ScrollabilityCache.ON; 4407 } 4408 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4409 4410 4411 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4412 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4413 .getScrollBarFadeDuration()); 4414 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4415 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4416 ViewConfiguration.getScrollDefaultDelay()); 4417 4418 4419 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4420 com.android.internal.R.styleable.View_scrollbarSize, 4421 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4422 4423 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4424 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4425 4426 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4427 if (thumb != null) { 4428 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4429 } 4430 4431 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4432 false); 4433 if (alwaysDraw) { 4434 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4435 } 4436 4437 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4438 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4439 4440 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4441 if (thumb != null) { 4442 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4443 } 4444 4445 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4446 false); 4447 if (alwaysDraw) { 4448 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4449 } 4450 4451 // Apply layout direction to the new Drawables if needed 4452 final int layoutDirection = getLayoutDirection(); 4453 if (track != null) { 4454 track.setLayoutDirection(layoutDirection); 4455 } 4456 if (thumb != null) { 4457 thumb.setLayoutDirection(layoutDirection); 4458 } 4459 4460 // Re-apply user/background padding so that scrollbar(s) get added 4461 resolvePadding(); 4462 } 4463 4464 /** 4465 * <p> 4466 * Initalizes the scrollability cache if necessary. 4467 * </p> 4468 */ 4469 private void initScrollCache() { 4470 if (mScrollCache == null) { 4471 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4472 } 4473 } 4474 4475 private ScrollabilityCache getScrollCache() { 4476 initScrollCache(); 4477 return mScrollCache; 4478 } 4479 4480 /** 4481 * Set the position of the vertical scroll bar. Should be one of 4482 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4483 * {@link #SCROLLBAR_POSITION_RIGHT}. 4484 * 4485 * @param position Where the vertical scroll bar should be positioned. 4486 */ 4487 public void setVerticalScrollbarPosition(int position) { 4488 if (mVerticalScrollbarPosition != position) { 4489 mVerticalScrollbarPosition = position; 4490 computeOpaqueFlags(); 4491 resolvePadding(); 4492 } 4493 } 4494 4495 /** 4496 * @return The position where the vertical scroll bar will show, if applicable. 4497 * @see #setVerticalScrollbarPosition(int) 4498 */ 4499 public int getVerticalScrollbarPosition() { 4500 return mVerticalScrollbarPosition; 4501 } 4502 4503 ListenerInfo getListenerInfo() { 4504 if (mListenerInfo != null) { 4505 return mListenerInfo; 4506 } 4507 mListenerInfo = new ListenerInfo(); 4508 return mListenerInfo; 4509 } 4510 4511 /** 4512 * Register a callback to be invoked when focus of this view changed. 4513 * 4514 * @param l The callback that will run. 4515 */ 4516 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4517 getListenerInfo().mOnFocusChangeListener = l; 4518 } 4519 4520 /** 4521 * Add a listener that will be called when the bounds of the view change due to 4522 * layout processing. 4523 * 4524 * @param listener The listener that will be called when layout bounds change. 4525 */ 4526 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4527 ListenerInfo li = getListenerInfo(); 4528 if (li.mOnLayoutChangeListeners == null) { 4529 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4530 } 4531 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4532 li.mOnLayoutChangeListeners.add(listener); 4533 } 4534 } 4535 4536 /** 4537 * Remove a listener for layout changes. 4538 * 4539 * @param listener The listener for layout bounds change. 4540 */ 4541 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4542 ListenerInfo li = mListenerInfo; 4543 if (li == null || li.mOnLayoutChangeListeners == null) { 4544 return; 4545 } 4546 li.mOnLayoutChangeListeners.remove(listener); 4547 } 4548 4549 /** 4550 * Add a listener for attach state changes. 4551 * 4552 * This listener will be called whenever this view is attached or detached 4553 * from a window. Remove the listener using 4554 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4555 * 4556 * @param listener Listener to attach 4557 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4558 */ 4559 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4560 ListenerInfo li = getListenerInfo(); 4561 if (li.mOnAttachStateChangeListeners == null) { 4562 li.mOnAttachStateChangeListeners 4563 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4564 } 4565 li.mOnAttachStateChangeListeners.add(listener); 4566 } 4567 4568 /** 4569 * Remove a listener for attach state changes. The listener will receive no further 4570 * notification of window attach/detach events. 4571 * 4572 * @param listener Listener to remove 4573 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4574 */ 4575 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4576 ListenerInfo li = mListenerInfo; 4577 if (li == null || li.mOnAttachStateChangeListeners == null) { 4578 return; 4579 } 4580 li.mOnAttachStateChangeListeners.remove(listener); 4581 } 4582 4583 /** 4584 * Returns the focus-change callback registered for this view. 4585 * 4586 * @return The callback, or null if one is not registered. 4587 */ 4588 public OnFocusChangeListener getOnFocusChangeListener() { 4589 ListenerInfo li = mListenerInfo; 4590 return li != null ? li.mOnFocusChangeListener : null; 4591 } 4592 4593 /** 4594 * Register a callback to be invoked when this view is clicked. If this view is not 4595 * clickable, it becomes clickable. 4596 * 4597 * @param l The callback that will run 4598 * 4599 * @see #setClickable(boolean) 4600 */ 4601 public void setOnClickListener(OnClickListener l) { 4602 if (!isClickable()) { 4603 setClickable(true); 4604 } 4605 getListenerInfo().mOnClickListener = l; 4606 } 4607 4608 /** 4609 * Return whether this view has an attached OnClickListener. Returns 4610 * true if there is a listener, false if there is none. 4611 */ 4612 public boolean hasOnClickListeners() { 4613 ListenerInfo li = mListenerInfo; 4614 return (li != null && li.mOnClickListener != null); 4615 } 4616 4617 /** 4618 * Register a callback to be invoked when this view is clicked and held. If this view is not 4619 * long clickable, it becomes long clickable. 4620 * 4621 * @param l The callback that will run 4622 * 4623 * @see #setLongClickable(boolean) 4624 */ 4625 public void setOnLongClickListener(OnLongClickListener l) { 4626 if (!isLongClickable()) { 4627 setLongClickable(true); 4628 } 4629 getListenerInfo().mOnLongClickListener = l; 4630 } 4631 4632 /** 4633 * Register a callback to be invoked when the context menu for this view is 4634 * being built. If this view is not long clickable, it becomes long clickable. 4635 * 4636 * @param l The callback that will run 4637 * 4638 */ 4639 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4640 if (!isLongClickable()) { 4641 setLongClickable(true); 4642 } 4643 getListenerInfo().mOnCreateContextMenuListener = l; 4644 } 4645 4646 /** 4647 * Call this view's OnClickListener, if it is defined. Performs all normal 4648 * actions associated with clicking: reporting accessibility event, playing 4649 * a sound, etc. 4650 * 4651 * @return True there was an assigned OnClickListener that was called, false 4652 * otherwise is returned. 4653 */ 4654 public boolean performClick() { 4655 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4656 4657 ListenerInfo li = mListenerInfo; 4658 if (li != null && li.mOnClickListener != null) { 4659 playSoundEffect(SoundEffectConstants.CLICK); 4660 li.mOnClickListener.onClick(this); 4661 return true; 4662 } 4663 4664 return false; 4665 } 4666 4667 /** 4668 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4669 * this only calls the listener, and does not do any associated clicking 4670 * actions like reporting an accessibility event. 4671 * 4672 * @return True there was an assigned OnClickListener that was called, false 4673 * otherwise is returned. 4674 */ 4675 public boolean callOnClick() { 4676 ListenerInfo li = mListenerInfo; 4677 if (li != null && li.mOnClickListener != null) { 4678 li.mOnClickListener.onClick(this); 4679 return true; 4680 } 4681 return false; 4682 } 4683 4684 /** 4685 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4686 * OnLongClickListener did not consume the event. 4687 * 4688 * @return True if one of the above receivers consumed the event, false otherwise. 4689 */ 4690 public boolean performLongClick() { 4691 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4692 4693 boolean handled = false; 4694 ListenerInfo li = mListenerInfo; 4695 if (li != null && li.mOnLongClickListener != null) { 4696 handled = li.mOnLongClickListener.onLongClick(View.this); 4697 } 4698 if (!handled) { 4699 handled = showContextMenu(); 4700 } 4701 if (handled) { 4702 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4703 } 4704 return handled; 4705 } 4706 4707 /** 4708 * Performs button-related actions during a touch down event. 4709 * 4710 * @param event The event. 4711 * @return True if the down was consumed. 4712 * 4713 * @hide 4714 */ 4715 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4716 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4717 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4718 return true; 4719 } 4720 } 4721 return false; 4722 } 4723 4724 /** 4725 * Bring up the context menu for this view. 4726 * 4727 * @return Whether a context menu was displayed. 4728 */ 4729 public boolean showContextMenu() { 4730 return getParent().showContextMenuForChild(this); 4731 } 4732 4733 /** 4734 * Bring up the context menu for this view, referring to the item under the specified point. 4735 * 4736 * @param x The referenced x coordinate. 4737 * @param y The referenced y coordinate. 4738 * @param metaState The keyboard modifiers that were pressed. 4739 * @return Whether a context menu was displayed. 4740 * 4741 * @hide 4742 */ 4743 public boolean showContextMenu(float x, float y, int metaState) { 4744 return showContextMenu(); 4745 } 4746 4747 /** 4748 * Start an action mode. 4749 * 4750 * @param callback Callback that will control the lifecycle of the action mode 4751 * @return The new action mode if it is started, null otherwise 4752 * 4753 * @see ActionMode 4754 */ 4755 public ActionMode startActionMode(ActionMode.Callback callback) { 4756 ViewParent parent = getParent(); 4757 if (parent == null) return null; 4758 return parent.startActionModeForChild(this, callback); 4759 } 4760 4761 /** 4762 * Register a callback to be invoked when a hardware key is pressed in this view. 4763 * Key presses in software input methods will generally not trigger the methods of 4764 * this listener. 4765 * @param l the key listener to attach to this view 4766 */ 4767 public void setOnKeyListener(OnKeyListener l) { 4768 getListenerInfo().mOnKeyListener = l; 4769 } 4770 4771 /** 4772 * Register a callback to be invoked when a touch event is sent to this view. 4773 * @param l the touch listener to attach to this view 4774 */ 4775 public void setOnTouchListener(OnTouchListener l) { 4776 getListenerInfo().mOnTouchListener = l; 4777 } 4778 4779 /** 4780 * Register a callback to be invoked when a generic motion event is sent to this view. 4781 * @param l the generic motion listener to attach to this view 4782 */ 4783 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4784 getListenerInfo().mOnGenericMotionListener = l; 4785 } 4786 4787 /** 4788 * Register a callback to be invoked when a hover event is sent to this view. 4789 * @param l the hover listener to attach to this view 4790 */ 4791 public void setOnHoverListener(OnHoverListener l) { 4792 getListenerInfo().mOnHoverListener = l; 4793 } 4794 4795 /** 4796 * Register a drag event listener callback object for this View. The parameter is 4797 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4798 * View, the system calls the 4799 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4800 * @param l An implementation of {@link android.view.View.OnDragListener}. 4801 */ 4802 public void setOnDragListener(OnDragListener l) { 4803 getListenerInfo().mOnDragListener = l; 4804 } 4805 4806 /** 4807 * Give this view focus. This will cause 4808 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4809 * 4810 * Note: this does not check whether this {@link View} should get focus, it just 4811 * gives it focus no matter what. It should only be called internally by framework 4812 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4813 * 4814 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4815 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4816 * focus moved when requestFocus() is called. It may not always 4817 * apply, in which case use the default View.FOCUS_DOWN. 4818 * @param previouslyFocusedRect The rectangle of the view that had focus 4819 * prior in this View's coordinate system. 4820 */ 4821 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4822 if (DBG) { 4823 System.out.println(this + " requestFocus()"); 4824 } 4825 4826 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4827 mPrivateFlags |= PFLAG_FOCUSED; 4828 4829 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4830 4831 if (mParent != null) { 4832 mParent.requestChildFocus(this, this); 4833 } 4834 4835 if (mAttachInfo != null) { 4836 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4837 } 4838 4839 onFocusChanged(true, direction, previouslyFocusedRect); 4840 manageFocusHotspot(true, oldFocus); 4841 refreshDrawableState(); 4842 } 4843 } 4844 4845 /** 4846 * Forwards focus information to the background drawable, if necessary. When 4847 * the view is gaining focus, <code>v</code> is the previous focus holder. 4848 * When the view is losing focus, <code>v</code> is the next focus holder. 4849 * 4850 * @param focused whether this view is focused 4851 * @param v previous or the next focus holder, or null if none 4852 */ 4853 private void manageFocusHotspot(boolean focused, View v) { 4854 final Rect r = new Rect(); 4855 if (v != null && mAttachInfo != null) { 4856 v.getHotspotBounds(r); 4857 final int[] location = mAttachInfo.mTmpLocation; 4858 getLocationOnScreen(location); 4859 r.offset(-location[0], -location[1]); 4860 } else { 4861 r.set(0, 0, mRight - mLeft, mBottom - mTop); 4862 } 4863 4864 final float x = r.exactCenterX(); 4865 final float y = r.exactCenterY(); 4866 drawableHotspotChanged(x, y); 4867 } 4868 4869 /** 4870 * Populates <code>outRect</code> with the hotspot bounds. By default, 4871 * the hotspot bounds are identical to the screen bounds. 4872 * 4873 * @param outRect rect to populate with hotspot bounds 4874 * @hide Only for internal use by views and widgets. 4875 */ 4876 public void getHotspotBounds(Rect outRect) { 4877 final Drawable background = getBackground(); 4878 if (background != null) { 4879 background.getHotspotBounds(outRect); 4880 } else { 4881 getBoundsOnScreen(outRect); 4882 } 4883 } 4884 4885 /** 4886 * Request that a rectangle of this view be visible on the screen, 4887 * scrolling if necessary just enough. 4888 * 4889 * <p>A View should call this if it maintains some notion of which part 4890 * of its content is interesting. For example, a text editing view 4891 * should call this when its cursor moves. 4892 * 4893 * @param rectangle The rectangle. 4894 * @return Whether any parent scrolled. 4895 */ 4896 public boolean requestRectangleOnScreen(Rect rectangle) { 4897 return requestRectangleOnScreen(rectangle, false); 4898 } 4899 4900 /** 4901 * Request that a rectangle of this view be visible on the screen, 4902 * scrolling if necessary just enough. 4903 * 4904 * <p>A View should call this if it maintains some notion of which part 4905 * of its content is interesting. For example, a text editing view 4906 * should call this when its cursor moves. 4907 * 4908 * <p>When <code>immediate</code> is set to true, scrolling will not be 4909 * animated. 4910 * 4911 * @param rectangle The rectangle. 4912 * @param immediate True to forbid animated scrolling, false otherwise 4913 * @return Whether any parent scrolled. 4914 */ 4915 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4916 if (mParent == null) { 4917 return false; 4918 } 4919 4920 View child = this; 4921 4922 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4923 position.set(rectangle); 4924 4925 ViewParent parent = mParent; 4926 boolean scrolled = false; 4927 while (parent != null) { 4928 rectangle.set((int) position.left, (int) position.top, 4929 (int) position.right, (int) position.bottom); 4930 4931 scrolled |= parent.requestChildRectangleOnScreen(child, 4932 rectangle, immediate); 4933 4934 if (!child.hasIdentityMatrix()) { 4935 child.getMatrix().mapRect(position); 4936 } 4937 4938 position.offset(child.mLeft, child.mTop); 4939 4940 if (!(parent instanceof View)) { 4941 break; 4942 } 4943 4944 View parentView = (View) parent; 4945 4946 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4947 4948 child = parentView; 4949 parent = child.getParent(); 4950 } 4951 4952 return scrolled; 4953 } 4954 4955 /** 4956 * Called when this view wants to give up focus. If focus is cleared 4957 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4958 * <p> 4959 * <strong>Note:</strong> When a View clears focus the framework is trying 4960 * to give focus to the first focusable View from the top. Hence, if this 4961 * View is the first from the top that can take focus, then all callbacks 4962 * related to clearing focus will be invoked after wich the framework will 4963 * give focus to this view. 4964 * </p> 4965 */ 4966 public void clearFocus() { 4967 if (DBG) { 4968 System.out.println(this + " clearFocus()"); 4969 } 4970 4971 clearFocusInternal(null, true, true); 4972 } 4973 4974 /** 4975 * Clears focus from the view, optionally propagating the change up through 4976 * the parent hierarchy and requesting that the root view place new focus. 4977 * 4978 * @param propagate whether to propagate the change up through the parent 4979 * hierarchy 4980 * @param refocus when propagate is true, specifies whether to request the 4981 * root view place new focus 4982 */ 4983 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4984 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4985 mPrivateFlags &= ~PFLAG_FOCUSED; 4986 4987 if (propagate && mParent != null) { 4988 mParent.clearChildFocus(this); 4989 } 4990 4991 onFocusChanged(false, 0, null); 4992 4993 manageFocusHotspot(false, focused); 4994 refreshDrawableState(); 4995 4996 if (propagate && (!refocus || !rootViewRequestFocus())) { 4997 notifyGlobalFocusCleared(this); 4998 } 4999 } 5000 } 5001 5002 void notifyGlobalFocusCleared(View oldFocus) { 5003 if (oldFocus != null && mAttachInfo != null) { 5004 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 5005 } 5006 } 5007 5008 boolean rootViewRequestFocus() { 5009 final View root = getRootView(); 5010 return root != null && root.requestFocus(); 5011 } 5012 5013 /** 5014 * Called internally by the view system when a new view is getting focus. 5015 * This is what clears the old focus. 5016 * <p> 5017 * <b>NOTE:</b> The parent view's focused child must be updated manually 5018 * after calling this method. Otherwise, the view hierarchy may be left in 5019 * an inconstent state. 5020 */ 5021 void unFocus(View focused) { 5022 if (DBG) { 5023 System.out.println(this + " unFocus()"); 5024 } 5025 5026 clearFocusInternal(focused, false, false); 5027 } 5028 5029 /** 5030 * Returns true if this view has focus iteself, or is the ancestor of the 5031 * view that has focus. 5032 * 5033 * @return True if this view has or contains focus, false otherwise. 5034 */ 5035 @ViewDebug.ExportedProperty(category = "focus") 5036 public boolean hasFocus() { 5037 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5038 } 5039 5040 /** 5041 * Returns true if this view is focusable or if it contains a reachable View 5042 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5043 * is a View whose parents do not block descendants focus. 5044 * 5045 * Only {@link #VISIBLE} views are considered focusable. 5046 * 5047 * @return True if the view is focusable or if the view contains a focusable 5048 * View, false otherwise. 5049 * 5050 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5051 */ 5052 public boolean hasFocusable() { 5053 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5054 } 5055 5056 /** 5057 * Called by the view system when the focus state of this view changes. 5058 * When the focus change event is caused by directional navigation, direction 5059 * and previouslyFocusedRect provide insight into where the focus is coming from. 5060 * When overriding, be sure to call up through to the super class so that 5061 * the standard focus handling will occur. 5062 * 5063 * @param gainFocus True if the View has focus; false otherwise. 5064 * @param direction The direction focus has moved when requestFocus() 5065 * is called to give this view focus. Values are 5066 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5067 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5068 * It may not always apply, in which case use the default. 5069 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5070 * system, of the previously focused view. If applicable, this will be 5071 * passed in as finer grained information about where the focus is coming 5072 * from (in addition to direction). Will be <code>null</code> otherwise. 5073 */ 5074 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5075 @Nullable Rect previouslyFocusedRect) { 5076 if (gainFocus) { 5077 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5078 } else { 5079 notifyViewAccessibilityStateChangedIfNeeded( 5080 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5081 } 5082 5083 InputMethodManager imm = InputMethodManager.peekInstance(); 5084 if (!gainFocus) { 5085 if (isPressed()) { 5086 setPressed(false); 5087 } 5088 if (imm != null && mAttachInfo != null 5089 && mAttachInfo.mHasWindowFocus) { 5090 imm.focusOut(this); 5091 } 5092 onFocusLost(); 5093 } else if (imm != null && mAttachInfo != null 5094 && mAttachInfo.mHasWindowFocus) { 5095 imm.focusIn(this); 5096 } 5097 5098 invalidate(true); 5099 ListenerInfo li = mListenerInfo; 5100 if (li != null && li.mOnFocusChangeListener != null) { 5101 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5102 } 5103 5104 if (mAttachInfo != null) { 5105 mAttachInfo.mKeyDispatchState.reset(this); 5106 } 5107 } 5108 5109 /** 5110 * Sends an accessibility event of the given type. If accessibility is 5111 * not enabled this method has no effect. The default implementation calls 5112 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5113 * to populate information about the event source (this View), then calls 5114 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5115 * populate the text content of the event source including its descendants, 5116 * and last calls 5117 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5118 * on its parent to resuest sending of the event to interested parties. 5119 * <p> 5120 * If an {@link AccessibilityDelegate} has been specified via calling 5121 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5122 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5123 * responsible for handling this call. 5124 * </p> 5125 * 5126 * @param eventType The type of the event to send, as defined by several types from 5127 * {@link android.view.accessibility.AccessibilityEvent}, such as 5128 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5129 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5130 * 5131 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5132 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5133 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5134 * @see AccessibilityDelegate 5135 */ 5136 public void sendAccessibilityEvent(int eventType) { 5137 if (mAccessibilityDelegate != null) { 5138 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5139 } else { 5140 sendAccessibilityEventInternal(eventType); 5141 } 5142 } 5143 5144 /** 5145 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5146 * {@link AccessibilityEvent} to make an announcement which is related to some 5147 * sort of a context change for which none of the events representing UI transitions 5148 * is a good fit. For example, announcing a new page in a book. If accessibility 5149 * is not enabled this method does nothing. 5150 * 5151 * @param text The announcement text. 5152 */ 5153 public void announceForAccessibility(CharSequence text) { 5154 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5155 AccessibilityEvent event = AccessibilityEvent.obtain( 5156 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5157 onInitializeAccessibilityEvent(event); 5158 event.getText().add(text); 5159 event.setContentDescription(null); 5160 mParent.requestSendAccessibilityEvent(this, event); 5161 } 5162 } 5163 5164 /** 5165 * @see #sendAccessibilityEvent(int) 5166 * 5167 * Note: Called from the default {@link AccessibilityDelegate}. 5168 */ 5169 void sendAccessibilityEventInternal(int eventType) { 5170 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5171 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5172 } 5173 } 5174 5175 /** 5176 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5177 * takes as an argument an empty {@link AccessibilityEvent} and does not 5178 * perform a check whether accessibility is enabled. 5179 * <p> 5180 * If an {@link AccessibilityDelegate} has been specified via calling 5181 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5182 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5183 * is responsible for handling this call. 5184 * </p> 5185 * 5186 * @param event The event to send. 5187 * 5188 * @see #sendAccessibilityEvent(int) 5189 */ 5190 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5191 if (mAccessibilityDelegate != null) { 5192 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5193 } else { 5194 sendAccessibilityEventUncheckedInternal(event); 5195 } 5196 } 5197 5198 /** 5199 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5200 * 5201 * Note: Called from the default {@link AccessibilityDelegate}. 5202 */ 5203 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5204 if (!isShown()) { 5205 return; 5206 } 5207 onInitializeAccessibilityEvent(event); 5208 // Only a subset of accessibility events populates text content. 5209 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5210 dispatchPopulateAccessibilityEvent(event); 5211 } 5212 // In the beginning we called #isShown(), so we know that getParent() is not null. 5213 getParent().requestSendAccessibilityEvent(this, event); 5214 } 5215 5216 /** 5217 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5218 * to its children for adding their text content to the event. Note that the 5219 * event text is populated in a separate dispatch path since we add to the 5220 * event not only the text of the source but also the text of all its descendants. 5221 * A typical implementation will call 5222 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5223 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5224 * on each child. Override this method if custom population of the event text 5225 * content is required. 5226 * <p> 5227 * If an {@link AccessibilityDelegate} has been specified via calling 5228 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5229 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5230 * is responsible for handling this call. 5231 * </p> 5232 * <p> 5233 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5234 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5235 * </p> 5236 * 5237 * @param event The event. 5238 * 5239 * @return True if the event population was completed. 5240 */ 5241 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5242 if (mAccessibilityDelegate != null) { 5243 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5244 } else { 5245 return dispatchPopulateAccessibilityEventInternal(event); 5246 } 5247 } 5248 5249 /** 5250 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5251 * 5252 * Note: Called from the default {@link AccessibilityDelegate}. 5253 */ 5254 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5255 onPopulateAccessibilityEvent(event); 5256 return false; 5257 } 5258 5259 /** 5260 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5261 * giving a chance to this View to populate the accessibility event with its 5262 * text content. While this method is free to modify event 5263 * attributes other than text content, doing so should normally be performed in 5264 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5265 * <p> 5266 * Example: Adding formatted date string to an accessibility event in addition 5267 * to the text added by the super implementation: 5268 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5269 * super.onPopulateAccessibilityEvent(event); 5270 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5271 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5272 * mCurrentDate.getTimeInMillis(), flags); 5273 * event.getText().add(selectedDateUtterance); 5274 * }</pre> 5275 * <p> 5276 * If an {@link AccessibilityDelegate} has been specified via calling 5277 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5278 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5279 * is responsible for handling this call. 5280 * </p> 5281 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5282 * information to the event, in case the default implementation has basic information to add. 5283 * </p> 5284 * 5285 * @param event The accessibility event which to populate. 5286 * 5287 * @see #sendAccessibilityEvent(int) 5288 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5289 */ 5290 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5291 if (mAccessibilityDelegate != null) { 5292 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5293 } else { 5294 onPopulateAccessibilityEventInternal(event); 5295 } 5296 } 5297 5298 /** 5299 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5300 * 5301 * Note: Called from the default {@link AccessibilityDelegate}. 5302 */ 5303 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5304 } 5305 5306 /** 5307 * Initializes an {@link AccessibilityEvent} with information about 5308 * this View which is the event source. In other words, the source of 5309 * an accessibility event is the view whose state change triggered firing 5310 * the event. 5311 * <p> 5312 * Example: Setting the password property of an event in addition 5313 * to properties set by the super implementation: 5314 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5315 * super.onInitializeAccessibilityEvent(event); 5316 * event.setPassword(true); 5317 * }</pre> 5318 * <p> 5319 * If an {@link AccessibilityDelegate} has been specified via calling 5320 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5321 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5322 * is responsible for handling this call. 5323 * </p> 5324 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5325 * information to the event, in case the default implementation has basic information to add. 5326 * </p> 5327 * @param event The event to initialize. 5328 * 5329 * @see #sendAccessibilityEvent(int) 5330 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5331 */ 5332 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5333 if (mAccessibilityDelegate != null) { 5334 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5335 } else { 5336 onInitializeAccessibilityEventInternal(event); 5337 } 5338 } 5339 5340 /** 5341 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5342 * 5343 * Note: Called from the default {@link AccessibilityDelegate}. 5344 */ 5345 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5346 event.setSource(this); 5347 event.setClassName(View.class.getName()); 5348 event.setPackageName(getContext().getPackageName()); 5349 event.setEnabled(isEnabled()); 5350 event.setContentDescription(mContentDescription); 5351 5352 switch (event.getEventType()) { 5353 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5354 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5355 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5356 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5357 event.setItemCount(focusablesTempList.size()); 5358 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5359 if (mAttachInfo != null) { 5360 focusablesTempList.clear(); 5361 } 5362 } break; 5363 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5364 CharSequence text = getIterableTextForAccessibility(); 5365 if (text != null && text.length() > 0) { 5366 event.setFromIndex(getAccessibilitySelectionStart()); 5367 event.setToIndex(getAccessibilitySelectionEnd()); 5368 event.setItemCount(text.length()); 5369 } 5370 } break; 5371 } 5372 } 5373 5374 /** 5375 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5376 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5377 * This method is responsible for obtaining an accessibility node info from a 5378 * pool of reusable instances and calling 5379 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5380 * initialize the former. 5381 * <p> 5382 * Note: The client is responsible for recycling the obtained instance by calling 5383 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5384 * </p> 5385 * 5386 * @return A populated {@link AccessibilityNodeInfo}. 5387 * 5388 * @see AccessibilityNodeInfo 5389 */ 5390 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5391 if (mAccessibilityDelegate != null) { 5392 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5393 } else { 5394 return createAccessibilityNodeInfoInternal(); 5395 } 5396 } 5397 5398 /** 5399 * @see #createAccessibilityNodeInfo() 5400 */ 5401 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5402 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5403 if (provider != null) { 5404 return provider.createAccessibilityNodeInfo(View.NO_ID); 5405 } else { 5406 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5407 onInitializeAccessibilityNodeInfo(info); 5408 return info; 5409 } 5410 } 5411 5412 /** 5413 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5414 * The base implementation sets: 5415 * <ul> 5416 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5417 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5418 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5419 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5420 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5421 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5422 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5423 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5424 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5425 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5426 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5427 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5428 * </ul> 5429 * <p> 5430 * Subclasses should override this method, call the super implementation, 5431 * and set additional attributes. 5432 * </p> 5433 * <p> 5434 * If an {@link AccessibilityDelegate} has been specified via calling 5435 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5436 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5437 * is responsible for handling this call. 5438 * </p> 5439 * 5440 * @param info The instance to initialize. 5441 */ 5442 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5443 if (mAccessibilityDelegate != null) { 5444 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5445 } else { 5446 onInitializeAccessibilityNodeInfoInternal(info); 5447 } 5448 } 5449 5450 /** 5451 * Gets the location of this view in screen coordintates. 5452 * 5453 * @param outRect The output location 5454 * @hide 5455 */ 5456 public void getBoundsOnScreen(Rect outRect) { 5457 if (mAttachInfo == null) { 5458 return; 5459 } 5460 5461 RectF position = mAttachInfo.mTmpTransformRect; 5462 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5463 5464 if (!hasIdentityMatrix()) { 5465 getMatrix().mapRect(position); 5466 } 5467 5468 position.offset(mLeft, mTop); 5469 5470 ViewParent parent = mParent; 5471 while (parent instanceof View) { 5472 View parentView = (View) parent; 5473 5474 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5475 5476 if (!parentView.hasIdentityMatrix()) { 5477 parentView.getMatrix().mapRect(position); 5478 } 5479 5480 position.offset(parentView.mLeft, parentView.mTop); 5481 5482 parent = parentView.mParent; 5483 } 5484 5485 if (parent instanceof ViewRootImpl) { 5486 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5487 position.offset(0, -viewRootImpl.mCurScrollY); 5488 } 5489 5490 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5491 5492 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5493 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5494 } 5495 5496 /** 5497 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5498 * 5499 * Note: Called from the default {@link AccessibilityDelegate}. 5500 */ 5501 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5502 Rect bounds = mAttachInfo.mTmpInvalRect; 5503 5504 getDrawingRect(bounds); 5505 info.setBoundsInParent(bounds); 5506 5507 getBoundsOnScreen(bounds); 5508 info.setBoundsInScreen(bounds); 5509 5510 ViewParent parent = getParentForAccessibility(); 5511 if (parent instanceof View) { 5512 info.setParent((View) parent); 5513 } 5514 5515 if (mID != View.NO_ID) { 5516 View rootView = getRootView(); 5517 if (rootView == null) { 5518 rootView = this; 5519 } 5520 View label = rootView.findLabelForView(this, mID); 5521 if (label != null) { 5522 info.setLabeledBy(label); 5523 } 5524 5525 if ((mAttachInfo.mAccessibilityFetchFlags 5526 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5527 && Resources.resourceHasPackage(mID)) { 5528 try { 5529 String viewId = getResources().getResourceName(mID); 5530 info.setViewIdResourceName(viewId); 5531 } catch (Resources.NotFoundException nfe) { 5532 /* ignore */ 5533 } 5534 } 5535 } 5536 5537 if (mLabelForId != View.NO_ID) { 5538 View rootView = getRootView(); 5539 if (rootView == null) { 5540 rootView = this; 5541 } 5542 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5543 if (labeled != null) { 5544 info.setLabelFor(labeled); 5545 } 5546 } 5547 5548 info.setVisibleToUser(isVisibleToUser()); 5549 5550 info.setPackageName(mContext.getPackageName()); 5551 info.setClassName(View.class.getName()); 5552 info.setContentDescription(getContentDescription()); 5553 5554 info.setEnabled(isEnabled()); 5555 info.setClickable(isClickable()); 5556 info.setFocusable(isFocusable()); 5557 info.setFocused(isFocused()); 5558 info.setAccessibilityFocused(isAccessibilityFocused()); 5559 info.setSelected(isSelected()); 5560 info.setLongClickable(isLongClickable()); 5561 info.setLiveRegion(getAccessibilityLiveRegion()); 5562 5563 // TODO: These make sense only if we are in an AdapterView but all 5564 // views can be selected. Maybe from accessibility perspective 5565 // we should report as selectable view in an AdapterView. 5566 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5567 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5568 5569 if (isFocusable()) { 5570 if (isFocused()) { 5571 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5572 } else { 5573 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5574 } 5575 } 5576 5577 if (!isAccessibilityFocused()) { 5578 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5579 } else { 5580 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5581 } 5582 5583 if (isClickable() && isEnabled()) { 5584 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5585 } 5586 5587 if (isLongClickable() && isEnabled()) { 5588 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5589 } 5590 5591 CharSequence text = getIterableTextForAccessibility(); 5592 if (text != null && text.length() > 0) { 5593 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5594 5595 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5596 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5597 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5598 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5599 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5600 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5601 } 5602 } 5603 5604 private View findLabelForView(View view, int labeledId) { 5605 if (mMatchLabelForPredicate == null) { 5606 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5607 } 5608 mMatchLabelForPredicate.mLabeledId = labeledId; 5609 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5610 } 5611 5612 /** 5613 * Computes whether this view is visible to the user. Such a view is 5614 * attached, visible, all its predecessors are visible, it is not clipped 5615 * entirely by its predecessors, and has an alpha greater than zero. 5616 * 5617 * @return Whether the view is visible on the screen. 5618 * 5619 * @hide 5620 */ 5621 protected boolean isVisibleToUser() { 5622 return isVisibleToUser(null); 5623 } 5624 5625 /** 5626 * Computes whether the given portion of this view is visible to the user. 5627 * Such a view is attached, visible, all its predecessors are visible, 5628 * has an alpha greater than zero, and the specified portion is not 5629 * clipped entirely by its predecessors. 5630 * 5631 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5632 * <code>null</code>, and the entire view will be tested in this case. 5633 * When <code>true</code> is returned by the function, the actual visible 5634 * region will be stored in this parameter; that is, if boundInView is fully 5635 * contained within the view, no modification will be made, otherwise regions 5636 * outside of the visible area of the view will be clipped. 5637 * 5638 * @return Whether the specified portion of the view is visible on the screen. 5639 * 5640 * @hide 5641 */ 5642 protected boolean isVisibleToUser(Rect boundInView) { 5643 if (mAttachInfo != null) { 5644 // Attached to invisible window means this view is not visible. 5645 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5646 return false; 5647 } 5648 // An invisible predecessor or one with alpha zero means 5649 // that this view is not visible to the user. 5650 Object current = this; 5651 while (current instanceof View) { 5652 View view = (View) current; 5653 // We have attach info so this view is attached and there is no 5654 // need to check whether we reach to ViewRootImpl on the way up. 5655 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5656 view.getVisibility() != VISIBLE) { 5657 return false; 5658 } 5659 current = view.mParent; 5660 } 5661 // Check if the view is entirely covered by its predecessors. 5662 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5663 Point offset = mAttachInfo.mPoint; 5664 if (!getGlobalVisibleRect(visibleRect, offset)) { 5665 return false; 5666 } 5667 // Check if the visible portion intersects the rectangle of interest. 5668 if (boundInView != null) { 5669 visibleRect.offset(-offset.x, -offset.y); 5670 return boundInView.intersect(visibleRect); 5671 } 5672 return true; 5673 } 5674 return false; 5675 } 5676 5677 /** 5678 * Returns the delegate for implementing accessibility support via 5679 * composition. For more details see {@link AccessibilityDelegate}. 5680 * 5681 * @return The delegate, or null if none set. 5682 * 5683 * @hide 5684 */ 5685 public AccessibilityDelegate getAccessibilityDelegate() { 5686 return mAccessibilityDelegate; 5687 } 5688 5689 /** 5690 * Sets a delegate for implementing accessibility support via composition as 5691 * opposed to inheritance. The delegate's primary use is for implementing 5692 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5693 * 5694 * @param delegate The delegate instance. 5695 * 5696 * @see AccessibilityDelegate 5697 */ 5698 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5699 mAccessibilityDelegate = delegate; 5700 } 5701 5702 /** 5703 * Gets the provider for managing a virtual view hierarchy rooted at this View 5704 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5705 * that explore the window content. 5706 * <p> 5707 * If this method returns an instance, this instance is responsible for managing 5708 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5709 * View including the one representing the View itself. Similarly the returned 5710 * instance is responsible for performing accessibility actions on any virtual 5711 * view or the root view itself. 5712 * </p> 5713 * <p> 5714 * If an {@link AccessibilityDelegate} has been specified via calling 5715 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5716 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5717 * is responsible for handling this call. 5718 * </p> 5719 * 5720 * @return The provider. 5721 * 5722 * @see AccessibilityNodeProvider 5723 */ 5724 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5725 if (mAccessibilityDelegate != null) { 5726 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5727 } else { 5728 return null; 5729 } 5730 } 5731 5732 /** 5733 * Gets the unique identifier of this view on the screen for accessibility purposes. 5734 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5735 * 5736 * @return The view accessibility id. 5737 * 5738 * @hide 5739 */ 5740 public int getAccessibilityViewId() { 5741 if (mAccessibilityViewId == NO_ID) { 5742 mAccessibilityViewId = sNextAccessibilityViewId++; 5743 } 5744 return mAccessibilityViewId; 5745 } 5746 5747 /** 5748 * Gets the unique identifier of the window in which this View reseides. 5749 * 5750 * @return The window accessibility id. 5751 * 5752 * @hide 5753 */ 5754 public int getAccessibilityWindowId() { 5755 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5756 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5757 } 5758 5759 /** 5760 * Gets the {@link View} description. It briefly describes the view and is 5761 * primarily used for accessibility support. Set this property to enable 5762 * better accessibility support for your application. This is especially 5763 * true for views that do not have textual representation (For example, 5764 * ImageButton). 5765 * 5766 * @return The content description. 5767 * 5768 * @attr ref android.R.styleable#View_contentDescription 5769 */ 5770 @ViewDebug.ExportedProperty(category = "accessibility") 5771 public CharSequence getContentDescription() { 5772 return mContentDescription; 5773 } 5774 5775 /** 5776 * Sets the {@link View} description. It briefly describes the view and is 5777 * primarily used for accessibility support. Set this property to enable 5778 * better accessibility support for your application. This is especially 5779 * true for views that do not have textual representation (For example, 5780 * ImageButton). 5781 * 5782 * @param contentDescription The content description. 5783 * 5784 * @attr ref android.R.styleable#View_contentDescription 5785 */ 5786 @RemotableViewMethod 5787 public void setContentDescription(CharSequence contentDescription) { 5788 if (mContentDescription == null) { 5789 if (contentDescription == null) { 5790 return; 5791 } 5792 } else if (mContentDescription.equals(contentDescription)) { 5793 return; 5794 } 5795 mContentDescription = contentDescription; 5796 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5797 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5798 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5799 notifySubtreeAccessibilityStateChangedIfNeeded(); 5800 } else { 5801 notifyViewAccessibilityStateChangedIfNeeded( 5802 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5803 } 5804 } 5805 5806 /** 5807 * Gets the id of a view for which this view serves as a label for 5808 * accessibility purposes. 5809 * 5810 * @return The labeled view id. 5811 */ 5812 @ViewDebug.ExportedProperty(category = "accessibility") 5813 public int getLabelFor() { 5814 return mLabelForId; 5815 } 5816 5817 /** 5818 * Sets the id of a view for which this view serves as a label for 5819 * accessibility purposes. 5820 * 5821 * @param id The labeled view id. 5822 */ 5823 @RemotableViewMethod 5824 public void setLabelFor(int id) { 5825 mLabelForId = id; 5826 if (mLabelForId != View.NO_ID 5827 && mID == View.NO_ID) { 5828 mID = generateViewId(); 5829 } 5830 } 5831 5832 /** 5833 * Invoked whenever this view loses focus, either by losing window focus or by losing 5834 * focus within its window. This method can be used to clear any state tied to the 5835 * focus. For instance, if a button is held pressed with the trackball and the window 5836 * loses focus, this method can be used to cancel the press. 5837 * 5838 * Subclasses of View overriding this method should always call super.onFocusLost(). 5839 * 5840 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5841 * @see #onWindowFocusChanged(boolean) 5842 * 5843 * @hide pending API council approval 5844 */ 5845 protected void onFocusLost() { 5846 resetPressedState(); 5847 } 5848 5849 private void resetPressedState() { 5850 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5851 return; 5852 } 5853 5854 if (isPressed()) { 5855 setPressed(false); 5856 5857 if (!mHasPerformedLongPress) { 5858 removeLongPressCallback(); 5859 } 5860 } 5861 } 5862 5863 /** 5864 * Returns true if this view has focus 5865 * 5866 * @return True if this view has focus, false otherwise. 5867 */ 5868 @ViewDebug.ExportedProperty(category = "focus") 5869 public boolean isFocused() { 5870 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5871 } 5872 5873 /** 5874 * Find the view in the hierarchy rooted at this view that currently has 5875 * focus. 5876 * 5877 * @return The view that currently has focus, or null if no focused view can 5878 * be found. 5879 */ 5880 public View findFocus() { 5881 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5882 } 5883 5884 /** 5885 * Indicates whether this view is one of the set of scrollable containers in 5886 * its window. 5887 * 5888 * @return whether this view is one of the set of scrollable containers in 5889 * its window 5890 * 5891 * @attr ref android.R.styleable#View_isScrollContainer 5892 */ 5893 public boolean isScrollContainer() { 5894 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5895 } 5896 5897 /** 5898 * Change whether this view is one of the set of scrollable containers in 5899 * its window. This will be used to determine whether the window can 5900 * resize or must pan when a soft input area is open -- scrollable 5901 * containers allow the window to use resize mode since the container 5902 * will appropriately shrink. 5903 * 5904 * @attr ref android.R.styleable#View_isScrollContainer 5905 */ 5906 public void setScrollContainer(boolean isScrollContainer) { 5907 if (isScrollContainer) { 5908 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5909 mAttachInfo.mScrollContainers.add(this); 5910 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5911 } 5912 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5913 } else { 5914 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5915 mAttachInfo.mScrollContainers.remove(this); 5916 } 5917 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5918 } 5919 } 5920 5921 /** 5922 * Returns the quality of the drawing cache. 5923 * 5924 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5925 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5926 * 5927 * @see #setDrawingCacheQuality(int) 5928 * @see #setDrawingCacheEnabled(boolean) 5929 * @see #isDrawingCacheEnabled() 5930 * 5931 * @attr ref android.R.styleable#View_drawingCacheQuality 5932 */ 5933 @DrawingCacheQuality 5934 public int getDrawingCacheQuality() { 5935 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5936 } 5937 5938 /** 5939 * Set the drawing cache quality of this view. This value is used only when the 5940 * drawing cache is enabled 5941 * 5942 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5943 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5944 * 5945 * @see #getDrawingCacheQuality() 5946 * @see #setDrawingCacheEnabled(boolean) 5947 * @see #isDrawingCacheEnabled() 5948 * 5949 * @attr ref android.R.styleable#View_drawingCacheQuality 5950 */ 5951 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5952 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5953 } 5954 5955 /** 5956 * Returns whether the screen should remain on, corresponding to the current 5957 * value of {@link #KEEP_SCREEN_ON}. 5958 * 5959 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5960 * 5961 * @see #setKeepScreenOn(boolean) 5962 * 5963 * @attr ref android.R.styleable#View_keepScreenOn 5964 */ 5965 public boolean getKeepScreenOn() { 5966 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5967 } 5968 5969 /** 5970 * Controls whether the screen should remain on, modifying the 5971 * value of {@link #KEEP_SCREEN_ON}. 5972 * 5973 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5974 * 5975 * @see #getKeepScreenOn() 5976 * 5977 * @attr ref android.R.styleable#View_keepScreenOn 5978 */ 5979 public void setKeepScreenOn(boolean keepScreenOn) { 5980 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5981 } 5982 5983 /** 5984 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5985 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5986 * 5987 * @attr ref android.R.styleable#View_nextFocusLeft 5988 */ 5989 public int getNextFocusLeftId() { 5990 return mNextFocusLeftId; 5991 } 5992 5993 /** 5994 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5995 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5996 * decide automatically. 5997 * 5998 * @attr ref android.R.styleable#View_nextFocusLeft 5999 */ 6000 public void setNextFocusLeftId(int nextFocusLeftId) { 6001 mNextFocusLeftId = nextFocusLeftId; 6002 } 6003 6004 /** 6005 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6006 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6007 * 6008 * @attr ref android.R.styleable#View_nextFocusRight 6009 */ 6010 public int getNextFocusRightId() { 6011 return mNextFocusRightId; 6012 } 6013 6014 /** 6015 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6016 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 6017 * decide automatically. 6018 * 6019 * @attr ref android.R.styleable#View_nextFocusRight 6020 */ 6021 public void setNextFocusRightId(int nextFocusRightId) { 6022 mNextFocusRightId = nextFocusRightId; 6023 } 6024 6025 /** 6026 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6027 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6028 * 6029 * @attr ref android.R.styleable#View_nextFocusUp 6030 */ 6031 public int getNextFocusUpId() { 6032 return mNextFocusUpId; 6033 } 6034 6035 /** 6036 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6037 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6038 * decide automatically. 6039 * 6040 * @attr ref android.R.styleable#View_nextFocusUp 6041 */ 6042 public void setNextFocusUpId(int nextFocusUpId) { 6043 mNextFocusUpId = nextFocusUpId; 6044 } 6045 6046 /** 6047 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6048 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6049 * 6050 * @attr ref android.R.styleable#View_nextFocusDown 6051 */ 6052 public int getNextFocusDownId() { 6053 return mNextFocusDownId; 6054 } 6055 6056 /** 6057 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6058 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6059 * decide automatically. 6060 * 6061 * @attr ref android.R.styleable#View_nextFocusDown 6062 */ 6063 public void setNextFocusDownId(int nextFocusDownId) { 6064 mNextFocusDownId = nextFocusDownId; 6065 } 6066 6067 /** 6068 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6069 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6070 * 6071 * @attr ref android.R.styleable#View_nextFocusForward 6072 */ 6073 public int getNextFocusForwardId() { 6074 return mNextFocusForwardId; 6075 } 6076 6077 /** 6078 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6079 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6080 * decide automatically. 6081 * 6082 * @attr ref android.R.styleable#View_nextFocusForward 6083 */ 6084 public void setNextFocusForwardId(int nextFocusForwardId) { 6085 mNextFocusForwardId = nextFocusForwardId; 6086 } 6087 6088 /** 6089 * Returns the visibility of this view and all of its ancestors 6090 * 6091 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6092 */ 6093 public boolean isShown() { 6094 View current = this; 6095 //noinspection ConstantConditions 6096 do { 6097 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6098 return false; 6099 } 6100 ViewParent parent = current.mParent; 6101 if (parent == null) { 6102 return false; // We are not attached to the view root 6103 } 6104 if (!(parent instanceof View)) { 6105 return true; 6106 } 6107 current = (View) parent; 6108 } while (current != null); 6109 6110 return false; 6111 } 6112 6113 /** 6114 * Called by the view hierarchy when the content insets for a window have 6115 * changed, to allow it to adjust its content to fit within those windows. 6116 * The content insets tell you the space that the status bar, input method, 6117 * and other system windows infringe on the application's window. 6118 * 6119 * <p>You do not normally need to deal with this function, since the default 6120 * window decoration given to applications takes care of applying it to the 6121 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6122 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6123 * and your content can be placed under those system elements. You can then 6124 * use this method within your view hierarchy if you have parts of your UI 6125 * which you would like to ensure are not being covered. 6126 * 6127 * <p>The default implementation of this method simply applies the content 6128 * insets to the view's padding, consuming that content (modifying the 6129 * insets to be 0), and returning true. This behavior is off by default, but can 6130 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6131 * 6132 * <p>This function's traversal down the hierarchy is depth-first. The same content 6133 * insets object is propagated down the hierarchy, so any changes made to it will 6134 * be seen by all following views (including potentially ones above in 6135 * the hierarchy since this is a depth-first traversal). The first view 6136 * that returns true will abort the entire traversal. 6137 * 6138 * <p>The default implementation works well for a situation where it is 6139 * used with a container that covers the entire window, allowing it to 6140 * apply the appropriate insets to its content on all edges. If you need 6141 * a more complicated layout (such as two different views fitting system 6142 * windows, one on the top of the window, and one on the bottom), 6143 * you can override the method and handle the insets however you would like. 6144 * Note that the insets provided by the framework are always relative to the 6145 * far edges of the window, not accounting for the location of the called view 6146 * within that window. (In fact when this method is called you do not yet know 6147 * where the layout will place the view, as it is done before layout happens.) 6148 * 6149 * <p>Note: unlike many View methods, there is no dispatch phase to this 6150 * call. If you are overriding it in a ViewGroup and want to allow the 6151 * call to continue to your children, you must be sure to call the super 6152 * implementation. 6153 * 6154 * <p>Here is a sample layout that makes use of fitting system windows 6155 * to have controls for a video view placed inside of the window decorations 6156 * that it hides and shows. This can be used with code like the second 6157 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6158 * 6159 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6160 * 6161 * @param insets Current content insets of the window. Prior to 6162 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6163 * the insets or else you and Android will be unhappy. 6164 * 6165 * @return {@code true} if this view applied the insets and it should not 6166 * continue propagating further down the hierarchy, {@code false} otherwise. 6167 * @see #getFitsSystemWindows() 6168 * @see #setFitsSystemWindows(boolean) 6169 * @see #setSystemUiVisibility(int) 6170 * 6171 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6172 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6173 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6174 * to implement handling their own insets. 6175 */ 6176 protected boolean fitSystemWindows(Rect insets) { 6177 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6178 if (insets == null) { 6179 // Null insets by definition have already been consumed. 6180 // This call cannot apply insets since there are none to apply, 6181 // so return false. 6182 return false; 6183 } 6184 // If we're not in the process of dispatching the newer apply insets call, 6185 // that means we're not in the compatibility path. Dispatch into the newer 6186 // apply insets path and take things from there. 6187 try { 6188 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6189 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 6190 } finally { 6191 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6192 } 6193 } else { 6194 // We're being called from the newer apply insets path. 6195 // Perform the standard fallback behavior. 6196 return fitSystemWindowsInt(insets); 6197 } 6198 } 6199 6200 private boolean fitSystemWindowsInt(Rect insets) { 6201 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6202 mUserPaddingStart = UNDEFINED_PADDING; 6203 mUserPaddingEnd = UNDEFINED_PADDING; 6204 Rect localInsets = sThreadLocal.get(); 6205 if (localInsets == null) { 6206 localInsets = new Rect(); 6207 sThreadLocal.set(localInsets); 6208 } 6209 boolean res = computeFitSystemWindows(insets, localInsets); 6210 mUserPaddingLeftInitial = localInsets.left; 6211 mUserPaddingRightInitial = localInsets.right; 6212 internalSetPadding(localInsets.left, localInsets.top, 6213 localInsets.right, localInsets.bottom); 6214 return res; 6215 } 6216 return false; 6217 } 6218 6219 /** 6220 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6221 * 6222 * <p>This method should be overridden by views that wish to apply a policy different from or 6223 * in addition to the default behavior. Clients that wish to force a view subtree 6224 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6225 * 6226 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6227 * it will be called during dispatch instead of this method. The listener may optionally 6228 * call this method from its own implementation if it wishes to apply the view's default 6229 * insets policy in addition to its own.</p> 6230 * 6231 * <p>Implementations of this method should either return the insets parameter unchanged 6232 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6233 * that this view applied itself. This allows new inset types added in future platform 6234 * versions to pass through existing implementations unchanged without being erroneously 6235 * consumed.</p> 6236 * 6237 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6238 * property is set then the view will consume the system window insets and apply them 6239 * as padding for the view.</p> 6240 * 6241 * @param insets Insets to apply 6242 * @return The supplied insets with any applied insets consumed 6243 */ 6244 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6245 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6246 // We weren't called from within a direct call to fitSystemWindows, 6247 // call into it as a fallback in case we're in a class that overrides it 6248 // and has logic to perform. 6249 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6250 return insets.consumeSystemWindowInsets(); 6251 } 6252 } else { 6253 // We were called from within a direct call to fitSystemWindows. 6254 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6255 return insets.consumeSystemWindowInsets(); 6256 } 6257 } 6258 return insets; 6259 } 6260 6261 /** 6262 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6263 * window insets to this view. The listener's 6264 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6265 * method will be called instead of the view's 6266 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6267 * 6268 * @param listener Listener to set 6269 * 6270 * @see #onApplyWindowInsets(WindowInsets) 6271 */ 6272 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6273 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6274 } 6275 6276 /** 6277 * Request to apply the given window insets to this view or another view in its subtree. 6278 * 6279 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6280 * obscured by window decorations or overlays. This can include the status and navigation bars, 6281 * action bars, input methods and more. New inset categories may be added in the future. 6282 * The method returns the insets provided minus any that were applied by this view or its 6283 * children.</p> 6284 * 6285 * <p>Clients wishing to provide custom behavior should override the 6286 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6287 * {@link OnApplyWindowInsetsListener} via the 6288 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6289 * method.</p> 6290 * 6291 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6292 * </p> 6293 * 6294 * @param insets Insets to apply 6295 * @return The provided insets minus the insets that were consumed 6296 */ 6297 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6298 try { 6299 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6300 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6301 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6302 } else { 6303 return onApplyWindowInsets(insets); 6304 } 6305 } finally { 6306 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6307 } 6308 } 6309 6310 /** 6311 * @hide Compute the insets that should be consumed by this view and the ones 6312 * that should propagate to those under it. 6313 */ 6314 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6315 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6316 || mAttachInfo == null 6317 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6318 && !mAttachInfo.mOverscanRequested)) { 6319 outLocalInsets.set(inoutInsets); 6320 inoutInsets.set(0, 0, 0, 0); 6321 return true; 6322 } else { 6323 // The application wants to take care of fitting system window for 6324 // the content... however we still need to take care of any overscan here. 6325 final Rect overscan = mAttachInfo.mOverscanInsets; 6326 outLocalInsets.set(overscan); 6327 inoutInsets.left -= overscan.left; 6328 inoutInsets.top -= overscan.top; 6329 inoutInsets.right -= overscan.right; 6330 inoutInsets.bottom -= overscan.bottom; 6331 return false; 6332 } 6333 } 6334 6335 /** 6336 * Sets whether or not this view should account for system screen decorations 6337 * such as the status bar and inset its content; that is, controlling whether 6338 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6339 * executed. See that method for more details. 6340 * 6341 * <p>Note that if you are providing your own implementation of 6342 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6343 * flag to true -- your implementation will be overriding the default 6344 * implementation that checks this flag. 6345 * 6346 * @param fitSystemWindows If true, then the default implementation of 6347 * {@link #fitSystemWindows(Rect)} will be executed. 6348 * 6349 * @attr ref android.R.styleable#View_fitsSystemWindows 6350 * @see #getFitsSystemWindows() 6351 * @see #fitSystemWindows(Rect) 6352 * @see #setSystemUiVisibility(int) 6353 */ 6354 public void setFitsSystemWindows(boolean fitSystemWindows) { 6355 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6356 } 6357 6358 /** 6359 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6360 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6361 * will be executed. 6362 * 6363 * @return {@code true} if the default implementation of 6364 * {@link #fitSystemWindows(Rect)} will be executed. 6365 * 6366 * @attr ref android.R.styleable#View_fitsSystemWindows 6367 * @see #setFitsSystemWindows(boolean) 6368 * @see #fitSystemWindows(Rect) 6369 * @see #setSystemUiVisibility(int) 6370 */ 6371 public boolean getFitsSystemWindows() { 6372 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6373 } 6374 6375 /** @hide */ 6376 public boolean fitsSystemWindows() { 6377 return getFitsSystemWindows(); 6378 } 6379 6380 /** 6381 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6382 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6383 */ 6384 public void requestFitSystemWindows() { 6385 if (mParent != null) { 6386 mParent.requestFitSystemWindows(); 6387 } 6388 } 6389 6390 /** 6391 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6392 */ 6393 public void requestApplyInsets() { 6394 requestFitSystemWindows(); 6395 } 6396 6397 /** 6398 * For use by PhoneWindow to make its own system window fitting optional. 6399 * @hide 6400 */ 6401 public void makeOptionalFitsSystemWindows() { 6402 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6403 } 6404 6405 /** 6406 * Returns the visibility status for this view. 6407 * 6408 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6409 * @attr ref android.R.styleable#View_visibility 6410 */ 6411 @ViewDebug.ExportedProperty(mapping = { 6412 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6413 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6414 @ViewDebug.IntToString(from = GONE, to = "GONE") 6415 }) 6416 @Visibility 6417 public int getVisibility() { 6418 return mViewFlags & VISIBILITY_MASK; 6419 } 6420 6421 /** 6422 * Set the enabled state of this view. 6423 * 6424 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6425 * @attr ref android.R.styleable#View_visibility 6426 */ 6427 @RemotableViewMethod 6428 public void setVisibility(@Visibility int visibility) { 6429 setFlags(visibility, VISIBILITY_MASK); 6430 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6431 } 6432 6433 /** 6434 * Returns the enabled status for this view. The interpretation of the 6435 * enabled state varies by subclass. 6436 * 6437 * @return True if this view is enabled, false otherwise. 6438 */ 6439 @ViewDebug.ExportedProperty 6440 public boolean isEnabled() { 6441 return (mViewFlags & ENABLED_MASK) == ENABLED; 6442 } 6443 6444 /** 6445 * Set the enabled state of this view. The interpretation of the enabled 6446 * state varies by subclass. 6447 * 6448 * @param enabled True if this view is enabled, false otherwise. 6449 */ 6450 @RemotableViewMethod 6451 public void setEnabled(boolean enabled) { 6452 if (enabled == isEnabled()) return; 6453 6454 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6455 6456 /* 6457 * The View most likely has to change its appearance, so refresh 6458 * the drawable state. 6459 */ 6460 refreshDrawableState(); 6461 6462 // Invalidate too, since the default behavior for views is to be 6463 // be drawn at 50% alpha rather than to change the drawable. 6464 invalidate(true); 6465 6466 if (!enabled) { 6467 cancelPendingInputEvents(); 6468 } 6469 } 6470 6471 /** 6472 * Set whether this view can receive the focus. 6473 * 6474 * Setting this to false will also ensure that this view is not focusable 6475 * in touch mode. 6476 * 6477 * @param focusable If true, this view can receive the focus. 6478 * 6479 * @see #setFocusableInTouchMode(boolean) 6480 * @attr ref android.R.styleable#View_focusable 6481 */ 6482 public void setFocusable(boolean focusable) { 6483 if (!focusable) { 6484 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6485 } 6486 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6487 } 6488 6489 /** 6490 * Set whether this view can receive focus while in touch mode. 6491 * 6492 * Setting this to true will also ensure that this view is focusable. 6493 * 6494 * @param focusableInTouchMode If true, this view can receive the focus while 6495 * in touch mode. 6496 * 6497 * @see #setFocusable(boolean) 6498 * @attr ref android.R.styleable#View_focusableInTouchMode 6499 */ 6500 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6501 // Focusable in touch mode should always be set before the focusable flag 6502 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6503 // which, in touch mode, will not successfully request focus on this view 6504 // because the focusable in touch mode flag is not set 6505 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6506 if (focusableInTouchMode) { 6507 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6508 } 6509 } 6510 6511 /** 6512 * Set whether this view should have sound effects enabled for events such as 6513 * clicking and touching. 6514 * 6515 * <p>You may wish to disable sound effects for a view if you already play sounds, 6516 * for instance, a dial key that plays dtmf tones. 6517 * 6518 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6519 * @see #isSoundEffectsEnabled() 6520 * @see #playSoundEffect(int) 6521 * @attr ref android.R.styleable#View_soundEffectsEnabled 6522 */ 6523 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6524 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6525 } 6526 6527 /** 6528 * @return whether this view should have sound effects enabled for events such as 6529 * clicking and touching. 6530 * 6531 * @see #setSoundEffectsEnabled(boolean) 6532 * @see #playSoundEffect(int) 6533 * @attr ref android.R.styleable#View_soundEffectsEnabled 6534 */ 6535 @ViewDebug.ExportedProperty 6536 public boolean isSoundEffectsEnabled() { 6537 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6538 } 6539 6540 /** 6541 * Set whether this view should have haptic feedback for events such as 6542 * long presses. 6543 * 6544 * <p>You may wish to disable haptic feedback if your view already controls 6545 * its own haptic feedback. 6546 * 6547 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6548 * @see #isHapticFeedbackEnabled() 6549 * @see #performHapticFeedback(int) 6550 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6551 */ 6552 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6553 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6554 } 6555 6556 /** 6557 * @return whether this view should have haptic feedback enabled for events 6558 * long presses. 6559 * 6560 * @see #setHapticFeedbackEnabled(boolean) 6561 * @see #performHapticFeedback(int) 6562 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6563 */ 6564 @ViewDebug.ExportedProperty 6565 public boolean isHapticFeedbackEnabled() { 6566 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6567 } 6568 6569 /** 6570 * Returns the layout direction for this view. 6571 * 6572 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6573 * {@link #LAYOUT_DIRECTION_RTL}, 6574 * {@link #LAYOUT_DIRECTION_INHERIT} or 6575 * {@link #LAYOUT_DIRECTION_LOCALE}. 6576 * 6577 * @attr ref android.R.styleable#View_layoutDirection 6578 * 6579 * @hide 6580 */ 6581 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6582 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6583 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6584 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6585 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6586 }) 6587 @LayoutDir 6588 public int getRawLayoutDirection() { 6589 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6590 } 6591 6592 /** 6593 * Set the layout direction for this view. This will propagate a reset of layout direction 6594 * resolution to the view's children and resolve layout direction for this view. 6595 * 6596 * @param layoutDirection the layout direction to set. Should be one of: 6597 * 6598 * {@link #LAYOUT_DIRECTION_LTR}, 6599 * {@link #LAYOUT_DIRECTION_RTL}, 6600 * {@link #LAYOUT_DIRECTION_INHERIT}, 6601 * {@link #LAYOUT_DIRECTION_LOCALE}. 6602 * 6603 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6604 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6605 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6606 * 6607 * @attr ref android.R.styleable#View_layoutDirection 6608 */ 6609 @RemotableViewMethod 6610 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6611 if (getRawLayoutDirection() != layoutDirection) { 6612 // Reset the current layout direction and the resolved one 6613 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6614 resetRtlProperties(); 6615 // Set the new layout direction (filtered) 6616 mPrivateFlags2 |= 6617 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6618 // We need to resolve all RTL properties as they all depend on layout direction 6619 resolveRtlPropertiesIfNeeded(); 6620 requestLayout(); 6621 invalidate(true); 6622 } 6623 } 6624 6625 /** 6626 * Returns the resolved layout direction for this view. 6627 * 6628 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6629 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6630 * 6631 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6632 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6633 * 6634 * @attr ref android.R.styleable#View_layoutDirection 6635 */ 6636 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6637 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6638 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6639 }) 6640 @ResolvedLayoutDir 6641 public int getLayoutDirection() { 6642 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6643 if (targetSdkVersion < JELLY_BEAN_MR1) { 6644 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6645 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6646 } 6647 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6648 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6649 } 6650 6651 /** 6652 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6653 * layout attribute and/or the inherited value from the parent 6654 * 6655 * @return true if the layout is right-to-left. 6656 * 6657 * @hide 6658 */ 6659 @ViewDebug.ExportedProperty(category = "layout") 6660 public boolean isLayoutRtl() { 6661 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6662 } 6663 6664 /** 6665 * Indicates whether the view is currently tracking transient state that the 6666 * app should not need to concern itself with saving and restoring, but that 6667 * the framework should take special note to preserve when possible. 6668 * 6669 * <p>A view with transient state cannot be trivially rebound from an external 6670 * data source, such as an adapter binding item views in a list. This may be 6671 * because the view is performing an animation, tracking user selection 6672 * of content, or similar.</p> 6673 * 6674 * @return true if the view has transient state 6675 */ 6676 @ViewDebug.ExportedProperty(category = "layout") 6677 public boolean hasTransientState() { 6678 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6679 } 6680 6681 /** 6682 * Set whether this view is currently tracking transient state that the 6683 * framework should attempt to preserve when possible. This flag is reference counted, 6684 * so every call to setHasTransientState(true) should be paired with a later call 6685 * to setHasTransientState(false). 6686 * 6687 * <p>A view with transient state cannot be trivially rebound from an external 6688 * data source, such as an adapter binding item views in a list. This may be 6689 * because the view is performing an animation, tracking user selection 6690 * of content, or similar.</p> 6691 * 6692 * @param hasTransientState true if this view has transient state 6693 */ 6694 public void setHasTransientState(boolean hasTransientState) { 6695 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6696 mTransientStateCount - 1; 6697 if (mTransientStateCount < 0) { 6698 mTransientStateCount = 0; 6699 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6700 "unmatched pair of setHasTransientState calls"); 6701 } else if ((hasTransientState && mTransientStateCount == 1) || 6702 (!hasTransientState && mTransientStateCount == 0)) { 6703 // update flag if we've just incremented up from 0 or decremented down to 0 6704 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6705 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6706 if (mParent != null) { 6707 try { 6708 mParent.childHasTransientStateChanged(this, hasTransientState); 6709 } catch (AbstractMethodError e) { 6710 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6711 " does not fully implement ViewParent", e); 6712 } 6713 } 6714 } 6715 } 6716 6717 /** 6718 * Returns true if this view is currently attached to a window. 6719 */ 6720 public boolean isAttachedToWindow() { 6721 return mAttachInfo != null; 6722 } 6723 6724 /** 6725 * Returns true if this view has been through at least one layout since it 6726 * was last attached to or detached from a window. 6727 */ 6728 public boolean isLaidOut() { 6729 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6730 } 6731 6732 /** 6733 * If this view doesn't do any drawing on its own, set this flag to 6734 * allow further optimizations. By default, this flag is not set on 6735 * View, but could be set on some View subclasses such as ViewGroup. 6736 * 6737 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6738 * you should clear this flag. 6739 * 6740 * @param willNotDraw whether or not this View draw on its own 6741 */ 6742 public void setWillNotDraw(boolean willNotDraw) { 6743 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6744 } 6745 6746 /** 6747 * Returns whether or not this View draws on its own. 6748 * 6749 * @return true if this view has nothing to draw, false otherwise 6750 */ 6751 @ViewDebug.ExportedProperty(category = "drawing") 6752 public boolean willNotDraw() { 6753 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6754 } 6755 6756 /** 6757 * When a View's drawing cache is enabled, drawing is redirected to an 6758 * offscreen bitmap. Some views, like an ImageView, must be able to 6759 * bypass this mechanism if they already draw a single bitmap, to avoid 6760 * unnecessary usage of the memory. 6761 * 6762 * @param willNotCacheDrawing true if this view does not cache its 6763 * drawing, false otherwise 6764 */ 6765 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6766 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6767 } 6768 6769 /** 6770 * Returns whether or not this View can cache its drawing or not. 6771 * 6772 * @return true if this view does not cache its drawing, false otherwise 6773 */ 6774 @ViewDebug.ExportedProperty(category = "drawing") 6775 public boolean willNotCacheDrawing() { 6776 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6777 } 6778 6779 /** 6780 * Indicates whether this view reacts to click events or not. 6781 * 6782 * @return true if the view is clickable, false otherwise 6783 * 6784 * @see #setClickable(boolean) 6785 * @attr ref android.R.styleable#View_clickable 6786 */ 6787 @ViewDebug.ExportedProperty 6788 public boolean isClickable() { 6789 return (mViewFlags & CLICKABLE) == CLICKABLE; 6790 } 6791 6792 /** 6793 * Enables or disables click events for this view. When a view 6794 * is clickable it will change its state to "pressed" on every click. 6795 * Subclasses should set the view clickable to visually react to 6796 * user's clicks. 6797 * 6798 * @param clickable true to make the view clickable, false otherwise 6799 * 6800 * @see #isClickable() 6801 * @attr ref android.R.styleable#View_clickable 6802 */ 6803 public void setClickable(boolean clickable) { 6804 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6805 } 6806 6807 /** 6808 * Indicates whether this view reacts to long click events or not. 6809 * 6810 * @return true if the view is long clickable, false otherwise 6811 * 6812 * @see #setLongClickable(boolean) 6813 * @attr ref android.R.styleable#View_longClickable 6814 */ 6815 public boolean isLongClickable() { 6816 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6817 } 6818 6819 /** 6820 * Enables or disables long click events for this view. When a view is long 6821 * clickable it reacts to the user holding down the button for a longer 6822 * duration than a tap. This event can either launch the listener or a 6823 * context menu. 6824 * 6825 * @param longClickable true to make the view long clickable, false otherwise 6826 * @see #isLongClickable() 6827 * @attr ref android.R.styleable#View_longClickable 6828 */ 6829 public void setLongClickable(boolean longClickable) { 6830 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6831 } 6832 6833 /** 6834 * Sets the pressed state for this view and provides a touch coordinate for 6835 * animation hinting. 6836 * 6837 * @param pressed Pass true to set the View's internal state to "pressed", 6838 * or false to reverts the View's internal state from a 6839 * previously set "pressed" state. 6840 * @param x The x coordinate of the touch that caused the press 6841 * @param y The y coordinate of the touch that caused the press 6842 */ 6843 private void setPressed(boolean pressed, float x, float y) { 6844 if (pressed) { 6845 drawableHotspotChanged(x, y); 6846 } 6847 6848 setPressed(pressed); 6849 } 6850 6851 /** 6852 * Sets the pressed state for this view. 6853 * 6854 * @see #isClickable() 6855 * @see #setClickable(boolean) 6856 * 6857 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6858 * the View's internal state from a previously set "pressed" state. 6859 */ 6860 public void setPressed(boolean pressed) { 6861 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6862 6863 if (pressed) { 6864 mPrivateFlags |= PFLAG_PRESSED; 6865 } else { 6866 mPrivateFlags &= ~PFLAG_PRESSED; 6867 } 6868 6869 if (needsRefresh) { 6870 refreshDrawableState(); 6871 } 6872 dispatchSetPressed(pressed); 6873 } 6874 6875 /** 6876 * Dispatch setPressed to all of this View's children. 6877 * 6878 * @see #setPressed(boolean) 6879 * 6880 * @param pressed The new pressed state 6881 */ 6882 protected void dispatchSetPressed(boolean pressed) { 6883 } 6884 6885 /** 6886 * Indicates whether the view is currently in pressed state. Unless 6887 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6888 * the pressed state. 6889 * 6890 * @see #setPressed(boolean) 6891 * @see #isClickable() 6892 * @see #setClickable(boolean) 6893 * 6894 * @return true if the view is currently pressed, false otherwise 6895 */ 6896 public boolean isPressed() { 6897 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6898 } 6899 6900 /** 6901 * Indicates whether this view will save its state (that is, 6902 * whether its {@link #onSaveInstanceState} method will be called). 6903 * 6904 * @return Returns true if the view state saving is enabled, else false. 6905 * 6906 * @see #setSaveEnabled(boolean) 6907 * @attr ref android.R.styleable#View_saveEnabled 6908 */ 6909 public boolean isSaveEnabled() { 6910 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6911 } 6912 6913 /** 6914 * Controls whether the saving of this view's state is 6915 * enabled (that is, whether its {@link #onSaveInstanceState} method 6916 * will be called). Note that even if freezing is enabled, the 6917 * view still must have an id assigned to it (via {@link #setId(int)}) 6918 * for its state to be saved. This flag can only disable the 6919 * saving of this view; any child views may still have their state saved. 6920 * 6921 * @param enabled Set to false to <em>disable</em> state saving, or true 6922 * (the default) to allow it. 6923 * 6924 * @see #isSaveEnabled() 6925 * @see #setId(int) 6926 * @see #onSaveInstanceState() 6927 * @attr ref android.R.styleable#View_saveEnabled 6928 */ 6929 public void setSaveEnabled(boolean enabled) { 6930 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6931 } 6932 6933 /** 6934 * Gets whether the framework should discard touches when the view's 6935 * window is obscured by another visible window. 6936 * Refer to the {@link View} security documentation for more details. 6937 * 6938 * @return True if touch filtering is enabled. 6939 * 6940 * @see #setFilterTouchesWhenObscured(boolean) 6941 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6942 */ 6943 @ViewDebug.ExportedProperty 6944 public boolean getFilterTouchesWhenObscured() { 6945 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6946 } 6947 6948 /** 6949 * Sets whether the framework should discard touches when the view's 6950 * window is obscured by another visible window. 6951 * Refer to the {@link View} security documentation for more details. 6952 * 6953 * @param enabled True if touch filtering should be enabled. 6954 * 6955 * @see #getFilterTouchesWhenObscured 6956 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6957 */ 6958 public void setFilterTouchesWhenObscured(boolean enabled) { 6959 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 6960 FILTER_TOUCHES_WHEN_OBSCURED); 6961 } 6962 6963 /** 6964 * Indicates whether the entire hierarchy under this view will save its 6965 * state when a state saving traversal occurs from its parent. The default 6966 * is true; if false, these views will not be saved unless 6967 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6968 * 6969 * @return Returns true if the view state saving from parent is enabled, else false. 6970 * 6971 * @see #setSaveFromParentEnabled(boolean) 6972 */ 6973 public boolean isSaveFromParentEnabled() { 6974 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6975 } 6976 6977 /** 6978 * Controls whether the entire hierarchy under this view will save its 6979 * state when a state saving traversal occurs from its parent. The default 6980 * is true; if false, these views will not be saved unless 6981 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6982 * 6983 * @param enabled Set to false to <em>disable</em> state saving, or true 6984 * (the default) to allow it. 6985 * 6986 * @see #isSaveFromParentEnabled() 6987 * @see #setId(int) 6988 * @see #onSaveInstanceState() 6989 */ 6990 public void setSaveFromParentEnabled(boolean enabled) { 6991 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6992 } 6993 6994 6995 /** 6996 * Returns whether this View is able to take focus. 6997 * 6998 * @return True if this view can take focus, or false otherwise. 6999 * @attr ref android.R.styleable#View_focusable 7000 */ 7001 @ViewDebug.ExportedProperty(category = "focus") 7002 public final boolean isFocusable() { 7003 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 7004 } 7005 7006 /** 7007 * When a view is focusable, it may not want to take focus when in touch mode. 7008 * For example, a button would like focus when the user is navigating via a D-pad 7009 * so that the user can click on it, but once the user starts touching the screen, 7010 * the button shouldn't take focus 7011 * @return Whether the view is focusable in touch mode. 7012 * @attr ref android.R.styleable#View_focusableInTouchMode 7013 */ 7014 @ViewDebug.ExportedProperty 7015 public final boolean isFocusableInTouchMode() { 7016 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 7017 } 7018 7019 /** 7020 * Find the nearest view in the specified direction that can take focus. 7021 * This does not actually give focus to that view. 7022 * 7023 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7024 * 7025 * @return The nearest focusable in the specified direction, or null if none 7026 * can be found. 7027 */ 7028 public View focusSearch(@FocusRealDirection int direction) { 7029 if (mParent != null) { 7030 return mParent.focusSearch(this, direction); 7031 } else { 7032 return null; 7033 } 7034 } 7035 7036 /** 7037 * This method is the last chance for the focused view and its ancestors to 7038 * respond to an arrow key. This is called when the focused view did not 7039 * consume the key internally, nor could the view system find a new view in 7040 * the requested direction to give focus to. 7041 * 7042 * @param focused The currently focused view. 7043 * @param direction The direction focus wants to move. One of FOCUS_UP, 7044 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 7045 * @return True if the this view consumed this unhandled move. 7046 */ 7047 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 7048 return false; 7049 } 7050 7051 /** 7052 * If a user manually specified the next view id for a particular direction, 7053 * use the root to look up the view. 7054 * @param root The root view of the hierarchy containing this view. 7055 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 7056 * or FOCUS_BACKWARD. 7057 * @return The user specified next view, or null if there is none. 7058 */ 7059 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7060 switch (direction) { 7061 case FOCUS_LEFT: 7062 if (mNextFocusLeftId == View.NO_ID) return null; 7063 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7064 case FOCUS_RIGHT: 7065 if (mNextFocusRightId == View.NO_ID) return null; 7066 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7067 case FOCUS_UP: 7068 if (mNextFocusUpId == View.NO_ID) return null; 7069 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7070 case FOCUS_DOWN: 7071 if (mNextFocusDownId == View.NO_ID) return null; 7072 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7073 case FOCUS_FORWARD: 7074 if (mNextFocusForwardId == View.NO_ID) return null; 7075 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7076 case FOCUS_BACKWARD: { 7077 if (mID == View.NO_ID) return null; 7078 final int id = mID; 7079 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7080 @Override 7081 public boolean apply(View t) { 7082 return t.mNextFocusForwardId == id; 7083 } 7084 }); 7085 } 7086 } 7087 return null; 7088 } 7089 7090 private View findViewInsideOutShouldExist(View root, int id) { 7091 if (mMatchIdPredicate == null) { 7092 mMatchIdPredicate = new MatchIdPredicate(); 7093 } 7094 mMatchIdPredicate.mId = id; 7095 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7096 if (result == null) { 7097 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7098 } 7099 return result; 7100 } 7101 7102 /** 7103 * Find and return all focusable views that are descendants of this view, 7104 * possibly including this view if it is focusable itself. 7105 * 7106 * @param direction The direction of the focus 7107 * @return A list of focusable views 7108 */ 7109 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7110 ArrayList<View> result = new ArrayList<View>(24); 7111 addFocusables(result, direction); 7112 return result; 7113 } 7114 7115 /** 7116 * Add any focusable views that are descendants of this view (possibly 7117 * including this view if it is focusable itself) to views. If we are in touch mode, 7118 * only add views that are also focusable in touch mode. 7119 * 7120 * @param views Focusable views found so far 7121 * @param direction The direction of the focus 7122 */ 7123 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7124 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7125 } 7126 7127 /** 7128 * Adds any focusable views that are descendants of this view (possibly 7129 * including this view if it is focusable itself) to views. This method 7130 * adds all focusable views regardless if we are in touch mode or 7131 * only views focusable in touch mode if we are in touch mode or 7132 * only views that can take accessibility focus if accessibility is enabeld 7133 * depending on the focusable mode paramater. 7134 * 7135 * @param views Focusable views found so far or null if all we are interested is 7136 * the number of focusables. 7137 * @param direction The direction of the focus. 7138 * @param focusableMode The type of focusables to be added. 7139 * 7140 * @see #FOCUSABLES_ALL 7141 * @see #FOCUSABLES_TOUCH_MODE 7142 */ 7143 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7144 @FocusableMode int focusableMode) { 7145 if (views == null) { 7146 return; 7147 } 7148 if (!isFocusable()) { 7149 return; 7150 } 7151 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7152 && isInTouchMode() && !isFocusableInTouchMode()) { 7153 return; 7154 } 7155 views.add(this); 7156 } 7157 7158 /** 7159 * Finds the Views that contain given text. The containment is case insensitive. 7160 * The search is performed by either the text that the View renders or the content 7161 * description that describes the view for accessibility purposes and the view does 7162 * not render or both. Clients can specify how the search is to be performed via 7163 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7164 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7165 * 7166 * @param outViews The output list of matching Views. 7167 * @param searched The text to match against. 7168 * 7169 * @see #FIND_VIEWS_WITH_TEXT 7170 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7171 * @see #setContentDescription(CharSequence) 7172 */ 7173 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7174 @FindViewFlags int flags) { 7175 if (getAccessibilityNodeProvider() != null) { 7176 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7177 outViews.add(this); 7178 } 7179 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7180 && (searched != null && searched.length() > 0) 7181 && (mContentDescription != null && mContentDescription.length() > 0)) { 7182 String searchedLowerCase = searched.toString().toLowerCase(); 7183 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7184 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7185 outViews.add(this); 7186 } 7187 } 7188 } 7189 7190 /** 7191 * Find and return all touchable views that are descendants of this view, 7192 * possibly including this view if it is touchable itself. 7193 * 7194 * @return A list of touchable views 7195 */ 7196 public ArrayList<View> getTouchables() { 7197 ArrayList<View> result = new ArrayList<View>(); 7198 addTouchables(result); 7199 return result; 7200 } 7201 7202 /** 7203 * Add any touchable views that are descendants of this view (possibly 7204 * including this view if it is touchable itself) to views. 7205 * 7206 * @param views Touchable views found so far 7207 */ 7208 public void addTouchables(ArrayList<View> views) { 7209 final int viewFlags = mViewFlags; 7210 7211 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7212 && (viewFlags & ENABLED_MASK) == ENABLED) { 7213 views.add(this); 7214 } 7215 } 7216 7217 /** 7218 * Returns whether this View is accessibility focused. 7219 * 7220 * @return True if this View is accessibility focused. 7221 */ 7222 public boolean isAccessibilityFocused() { 7223 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7224 } 7225 7226 /** 7227 * Call this to try to give accessibility focus to this view. 7228 * 7229 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7230 * returns false or the view is no visible or the view already has accessibility 7231 * focus. 7232 * 7233 * See also {@link #focusSearch(int)}, which is what you call to say that you 7234 * have focus, and you want your parent to look for the next one. 7235 * 7236 * @return Whether this view actually took accessibility focus. 7237 * 7238 * @hide 7239 */ 7240 public boolean requestAccessibilityFocus() { 7241 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7242 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7243 return false; 7244 } 7245 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7246 return false; 7247 } 7248 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7249 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7250 ViewRootImpl viewRootImpl = getViewRootImpl(); 7251 if (viewRootImpl != null) { 7252 viewRootImpl.setAccessibilityFocus(this, null); 7253 } 7254 invalidate(); 7255 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7256 return true; 7257 } 7258 return false; 7259 } 7260 7261 /** 7262 * Call this to try to clear accessibility focus of this view. 7263 * 7264 * See also {@link #focusSearch(int)}, which is what you call to say that you 7265 * have focus, and you want your parent to look for the next one. 7266 * 7267 * @hide 7268 */ 7269 public void clearAccessibilityFocus() { 7270 clearAccessibilityFocusNoCallbacks(); 7271 // Clear the global reference of accessibility focus if this 7272 // view or any of its descendants had accessibility focus. 7273 ViewRootImpl viewRootImpl = getViewRootImpl(); 7274 if (viewRootImpl != null) { 7275 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7276 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7277 viewRootImpl.setAccessibilityFocus(null, null); 7278 } 7279 } 7280 } 7281 7282 private void sendAccessibilityHoverEvent(int eventType) { 7283 // Since we are not delivering to a client accessibility events from not 7284 // important views (unless the clinet request that) we need to fire the 7285 // event from the deepest view exposed to the client. As a consequence if 7286 // the user crosses a not exposed view the client will see enter and exit 7287 // of the exposed predecessor followed by and enter and exit of that same 7288 // predecessor when entering and exiting the not exposed descendant. This 7289 // is fine since the client has a clear idea which view is hovered at the 7290 // price of a couple more events being sent. This is a simple and 7291 // working solution. 7292 View source = this; 7293 while (true) { 7294 if (source.includeForAccessibility()) { 7295 source.sendAccessibilityEvent(eventType); 7296 return; 7297 } 7298 ViewParent parent = source.getParent(); 7299 if (parent instanceof View) { 7300 source = (View) parent; 7301 } else { 7302 return; 7303 } 7304 } 7305 } 7306 7307 /** 7308 * Clears accessibility focus without calling any callback methods 7309 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7310 * is used for clearing accessibility focus when giving this focus to 7311 * another view. 7312 */ 7313 void clearAccessibilityFocusNoCallbacks() { 7314 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7315 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7316 invalidate(); 7317 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7318 } 7319 } 7320 7321 /** 7322 * Call this to try to give focus to a specific view or to one of its 7323 * descendants. 7324 * 7325 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7326 * false), or if it is focusable and it is not focusable in touch mode 7327 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7328 * 7329 * See also {@link #focusSearch(int)}, which is what you call to say that you 7330 * have focus, and you want your parent to look for the next one. 7331 * 7332 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7333 * {@link #FOCUS_DOWN} and <code>null</code>. 7334 * 7335 * @return Whether this view or one of its descendants actually took focus. 7336 */ 7337 public final boolean requestFocus() { 7338 return requestFocus(View.FOCUS_DOWN); 7339 } 7340 7341 /** 7342 * Call this to try to give focus to a specific view or to one of its 7343 * descendants and give it a hint about what direction focus is heading. 7344 * 7345 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7346 * false), or if it is focusable and it is not focusable in touch mode 7347 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7348 * 7349 * See also {@link #focusSearch(int)}, which is what you call to say that you 7350 * have focus, and you want your parent to look for the next one. 7351 * 7352 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7353 * <code>null</code> set for the previously focused rectangle. 7354 * 7355 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7356 * @return Whether this view or one of its descendants actually took focus. 7357 */ 7358 public final boolean requestFocus(int direction) { 7359 return requestFocus(direction, null); 7360 } 7361 7362 /** 7363 * Call this to try to give focus to a specific view or to one of its descendants 7364 * and give it hints about the direction and a specific rectangle that the focus 7365 * is coming from. The rectangle can help give larger views a finer grained hint 7366 * about where focus is coming from, and therefore, where to show selection, or 7367 * forward focus change internally. 7368 * 7369 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7370 * false), or if it is focusable and it is not focusable in touch mode 7371 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7372 * 7373 * A View will not take focus if it is not visible. 7374 * 7375 * A View will not take focus if one of its parents has 7376 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7377 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7378 * 7379 * See also {@link #focusSearch(int)}, which is what you call to say that you 7380 * have focus, and you want your parent to look for the next one. 7381 * 7382 * You may wish to override this method if your custom {@link View} has an internal 7383 * {@link View} that it wishes to forward the request to. 7384 * 7385 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7386 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7387 * to give a finer grained hint about where focus is coming from. May be null 7388 * if there is no hint. 7389 * @return Whether this view or one of its descendants actually took focus. 7390 */ 7391 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7392 return requestFocusNoSearch(direction, previouslyFocusedRect); 7393 } 7394 7395 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7396 // need to be focusable 7397 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7398 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7399 return false; 7400 } 7401 7402 // need to be focusable in touch mode if in touch mode 7403 if (isInTouchMode() && 7404 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7405 return false; 7406 } 7407 7408 // need to not have any parents blocking us 7409 if (hasAncestorThatBlocksDescendantFocus()) { 7410 return false; 7411 } 7412 7413 handleFocusGainInternal(direction, previouslyFocusedRect); 7414 return true; 7415 } 7416 7417 /** 7418 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7419 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7420 * touch mode to request focus when they are touched. 7421 * 7422 * @return Whether this view or one of its descendants actually took focus. 7423 * 7424 * @see #isInTouchMode() 7425 * 7426 */ 7427 public final boolean requestFocusFromTouch() { 7428 // Leave touch mode if we need to 7429 if (isInTouchMode()) { 7430 ViewRootImpl viewRoot = getViewRootImpl(); 7431 if (viewRoot != null) { 7432 viewRoot.ensureTouchMode(false); 7433 } 7434 } 7435 return requestFocus(View.FOCUS_DOWN); 7436 } 7437 7438 /** 7439 * @return Whether any ancestor of this view blocks descendant focus. 7440 */ 7441 private boolean hasAncestorThatBlocksDescendantFocus() { 7442 ViewParent ancestor = mParent; 7443 while (ancestor instanceof ViewGroup) { 7444 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7445 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 7446 || vgAncestor.shouldBlockFocusForTouchscreen()) { 7447 return true; 7448 } else { 7449 ancestor = vgAncestor.getParent(); 7450 } 7451 } 7452 return false; 7453 } 7454 7455 /** 7456 * Gets the mode for determining whether this View is important for accessibility 7457 * which is if it fires accessibility events and if it is reported to 7458 * accessibility services that query the screen. 7459 * 7460 * @return The mode for determining whether a View is important for accessibility. 7461 * 7462 * @attr ref android.R.styleable#View_importantForAccessibility 7463 * 7464 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7465 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7466 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7467 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7468 */ 7469 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7470 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7471 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7472 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7473 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7474 to = "noHideDescendants") 7475 }) 7476 public int getImportantForAccessibility() { 7477 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7478 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7479 } 7480 7481 /** 7482 * Sets the live region mode for this view. This indicates to accessibility 7483 * services whether they should automatically notify the user about changes 7484 * to the view's content description or text, or to the content descriptions 7485 * or text of the view's children (where applicable). 7486 * <p> 7487 * For example, in a login screen with a TextView that displays an "incorrect 7488 * password" notification, that view should be marked as a live region with 7489 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7490 * <p> 7491 * To disable change notifications for this view, use 7492 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7493 * mode for most views. 7494 * <p> 7495 * To indicate that the user should be notified of changes, use 7496 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7497 * <p> 7498 * If the view's changes should interrupt ongoing speech and notify the user 7499 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7500 * 7501 * @param mode The live region mode for this view, one of: 7502 * <ul> 7503 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7504 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7505 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7506 * </ul> 7507 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7508 */ 7509 public void setAccessibilityLiveRegion(int mode) { 7510 if (mode != getAccessibilityLiveRegion()) { 7511 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7512 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7513 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7514 notifyViewAccessibilityStateChangedIfNeeded( 7515 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7516 } 7517 } 7518 7519 /** 7520 * Gets the live region mode for this View. 7521 * 7522 * @return The live region mode for the view. 7523 * 7524 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7525 * 7526 * @see #setAccessibilityLiveRegion(int) 7527 */ 7528 public int getAccessibilityLiveRegion() { 7529 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7530 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7531 } 7532 7533 /** 7534 * Sets how to determine whether this view is important for accessibility 7535 * which is if it fires accessibility events and if it is reported to 7536 * accessibility services that query the screen. 7537 * 7538 * @param mode How to determine whether this view is important for accessibility. 7539 * 7540 * @attr ref android.R.styleable#View_importantForAccessibility 7541 * 7542 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7543 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7544 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7545 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7546 */ 7547 public void setImportantForAccessibility(int mode) { 7548 final int oldMode = getImportantForAccessibility(); 7549 if (mode != oldMode) { 7550 // If we're moving between AUTO and another state, we might not need 7551 // to send a subtree changed notification. We'll store the computed 7552 // importance, since we'll need to check it later to make sure. 7553 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7554 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7555 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7556 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7557 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7558 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7559 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7560 notifySubtreeAccessibilityStateChangedIfNeeded(); 7561 } else { 7562 notifyViewAccessibilityStateChangedIfNeeded( 7563 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7564 } 7565 } 7566 } 7567 7568 /** 7569 * Computes whether this view should be exposed for accessibility. In 7570 * general, views that are interactive or provide information are exposed 7571 * while views that serve only as containers are hidden. 7572 * <p> 7573 * If an ancestor of this view has importance 7574 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7575 * returns <code>false</code>. 7576 * <p> 7577 * Otherwise, the value is computed according to the view's 7578 * {@link #getImportantForAccessibility()} value: 7579 * <ol> 7580 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7581 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7582 * </code> 7583 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7584 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7585 * view satisfies any of the following: 7586 * <ul> 7587 * <li>Is actionable, e.g. {@link #isClickable()}, 7588 * {@link #isLongClickable()}, or {@link #isFocusable()} 7589 * <li>Has an {@link AccessibilityDelegate} 7590 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7591 * {@link OnKeyListener}, etc. 7592 * <li>Is an accessibility live region, e.g. 7593 * {@link #getAccessibilityLiveRegion()} is not 7594 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7595 * </ul> 7596 * </ol> 7597 * 7598 * @return Whether the view is exposed for accessibility. 7599 * @see #setImportantForAccessibility(int) 7600 * @see #getImportantForAccessibility() 7601 */ 7602 public boolean isImportantForAccessibility() { 7603 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7604 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7605 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7606 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7607 return false; 7608 } 7609 7610 // Check parent mode to ensure we're not hidden. 7611 ViewParent parent = mParent; 7612 while (parent instanceof View) { 7613 if (((View) parent).getImportantForAccessibility() 7614 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7615 return false; 7616 } 7617 parent = parent.getParent(); 7618 } 7619 7620 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7621 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7622 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7623 } 7624 7625 /** 7626 * Gets the parent for accessibility purposes. Note that the parent for 7627 * accessibility is not necessary the immediate parent. It is the first 7628 * predecessor that is important for accessibility. 7629 * 7630 * @return The parent for accessibility purposes. 7631 */ 7632 public ViewParent getParentForAccessibility() { 7633 if (mParent instanceof View) { 7634 View parentView = (View) mParent; 7635 if (parentView.includeForAccessibility()) { 7636 return mParent; 7637 } else { 7638 return mParent.getParentForAccessibility(); 7639 } 7640 } 7641 return null; 7642 } 7643 7644 /** 7645 * Adds the children of a given View for accessibility. Since some Views are 7646 * not important for accessibility the children for accessibility are not 7647 * necessarily direct children of the view, rather they are the first level of 7648 * descendants important for accessibility. 7649 * 7650 * @param children The list of children for accessibility. 7651 */ 7652 public void addChildrenForAccessibility(ArrayList<View> children) { 7653 7654 } 7655 7656 /** 7657 * Whether to regard this view for accessibility. A view is regarded for 7658 * accessibility if it is important for accessibility or the querying 7659 * accessibility service has explicitly requested that view not 7660 * important for accessibility are regarded. 7661 * 7662 * @return Whether to regard the view for accessibility. 7663 * 7664 * @hide 7665 */ 7666 public boolean includeForAccessibility() { 7667 if (mAttachInfo != null) { 7668 return (mAttachInfo.mAccessibilityFetchFlags 7669 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7670 || isImportantForAccessibility(); 7671 } 7672 return false; 7673 } 7674 7675 /** 7676 * Returns whether the View is considered actionable from 7677 * accessibility perspective. Such view are important for 7678 * accessibility. 7679 * 7680 * @return True if the view is actionable for accessibility. 7681 * 7682 * @hide 7683 */ 7684 public boolean isActionableForAccessibility() { 7685 return (isClickable() || isLongClickable() || isFocusable()); 7686 } 7687 7688 /** 7689 * Returns whether the View has registered callbacks which makes it 7690 * important for accessibility. 7691 * 7692 * @return True if the view is actionable for accessibility. 7693 */ 7694 private boolean hasListenersForAccessibility() { 7695 ListenerInfo info = getListenerInfo(); 7696 return mTouchDelegate != null || info.mOnKeyListener != null 7697 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7698 || info.mOnHoverListener != null || info.mOnDragListener != null; 7699 } 7700 7701 /** 7702 * Notifies that the accessibility state of this view changed. The change 7703 * is local to this view and does not represent structural changes such 7704 * as children and parent. For example, the view became focusable. The 7705 * notification is at at most once every 7706 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7707 * to avoid unnecessary load to the system. Also once a view has a pending 7708 * notification this method is a NOP until the notification has been sent. 7709 * 7710 * @hide 7711 */ 7712 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7713 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7714 return; 7715 } 7716 if (mSendViewStateChangedAccessibilityEvent == null) { 7717 mSendViewStateChangedAccessibilityEvent = 7718 new SendViewStateChangedAccessibilityEvent(); 7719 } 7720 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7721 } 7722 7723 /** 7724 * Notifies that the accessibility state of this view changed. The change 7725 * is *not* local to this view and does represent structural changes such 7726 * as children and parent. For example, the view size changed. The 7727 * notification is at at most once every 7728 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7729 * to avoid unnecessary load to the system. Also once a view has a pending 7730 * notification this method is a NOP until the notification has been sent. 7731 * 7732 * @hide 7733 */ 7734 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7735 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7736 return; 7737 } 7738 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7739 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7740 if (mParent != null) { 7741 try { 7742 mParent.notifySubtreeAccessibilityStateChanged( 7743 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7744 } catch (AbstractMethodError e) { 7745 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7746 " does not fully implement ViewParent", e); 7747 } 7748 } 7749 } 7750 } 7751 7752 /** 7753 * Reset the flag indicating the accessibility state of the subtree rooted 7754 * at this view changed. 7755 */ 7756 void resetSubtreeAccessibilityStateChanged() { 7757 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7758 } 7759 7760 /** 7761 * Performs the specified accessibility action on the view. For 7762 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7763 * <p> 7764 * If an {@link AccessibilityDelegate} has been specified via calling 7765 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7766 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7767 * is responsible for handling this call. 7768 * </p> 7769 * 7770 * @param action The action to perform. 7771 * @param arguments Optional action arguments. 7772 * @return Whether the action was performed. 7773 */ 7774 public boolean performAccessibilityAction(int action, Bundle arguments) { 7775 if (mAccessibilityDelegate != null) { 7776 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7777 } else { 7778 return performAccessibilityActionInternal(action, arguments); 7779 } 7780 } 7781 7782 /** 7783 * @see #performAccessibilityAction(int, Bundle) 7784 * 7785 * Note: Called from the default {@link AccessibilityDelegate}. 7786 */ 7787 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7788 switch (action) { 7789 case AccessibilityNodeInfo.ACTION_CLICK: { 7790 if (isClickable()) { 7791 performClick(); 7792 return true; 7793 } 7794 } break; 7795 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7796 if (isLongClickable()) { 7797 performLongClick(); 7798 return true; 7799 } 7800 } break; 7801 case AccessibilityNodeInfo.ACTION_FOCUS: { 7802 if (!hasFocus()) { 7803 // Get out of touch mode since accessibility 7804 // wants to move focus around. 7805 getViewRootImpl().ensureTouchMode(false); 7806 return requestFocus(); 7807 } 7808 } break; 7809 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7810 if (hasFocus()) { 7811 clearFocus(); 7812 return !isFocused(); 7813 } 7814 } break; 7815 case AccessibilityNodeInfo.ACTION_SELECT: { 7816 if (!isSelected()) { 7817 setSelected(true); 7818 return isSelected(); 7819 } 7820 } break; 7821 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7822 if (isSelected()) { 7823 setSelected(false); 7824 return !isSelected(); 7825 } 7826 } break; 7827 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7828 if (!isAccessibilityFocused()) { 7829 return requestAccessibilityFocus(); 7830 } 7831 } break; 7832 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7833 if (isAccessibilityFocused()) { 7834 clearAccessibilityFocus(); 7835 return true; 7836 } 7837 } break; 7838 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7839 if (arguments != null) { 7840 final int granularity = arguments.getInt( 7841 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7842 final boolean extendSelection = arguments.getBoolean( 7843 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7844 return traverseAtGranularity(granularity, true, extendSelection); 7845 } 7846 } break; 7847 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7848 if (arguments != null) { 7849 final int granularity = arguments.getInt( 7850 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7851 final boolean extendSelection = arguments.getBoolean( 7852 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7853 return traverseAtGranularity(granularity, false, extendSelection); 7854 } 7855 } break; 7856 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7857 CharSequence text = getIterableTextForAccessibility(); 7858 if (text == null) { 7859 return false; 7860 } 7861 final int start = (arguments != null) ? arguments.getInt( 7862 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7863 final int end = (arguments != null) ? arguments.getInt( 7864 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7865 // Only cursor position can be specified (selection length == 0) 7866 if ((getAccessibilitySelectionStart() != start 7867 || getAccessibilitySelectionEnd() != end) 7868 && (start == end)) { 7869 setAccessibilitySelection(start, end); 7870 notifyViewAccessibilityStateChangedIfNeeded( 7871 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7872 return true; 7873 } 7874 } break; 7875 } 7876 return false; 7877 } 7878 7879 private boolean traverseAtGranularity(int granularity, boolean forward, 7880 boolean extendSelection) { 7881 CharSequence text = getIterableTextForAccessibility(); 7882 if (text == null || text.length() == 0) { 7883 return false; 7884 } 7885 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7886 if (iterator == null) { 7887 return false; 7888 } 7889 int current = getAccessibilitySelectionEnd(); 7890 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7891 current = forward ? 0 : text.length(); 7892 } 7893 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7894 if (range == null) { 7895 return false; 7896 } 7897 final int segmentStart = range[0]; 7898 final int segmentEnd = range[1]; 7899 int selectionStart; 7900 int selectionEnd; 7901 if (extendSelection && isAccessibilitySelectionExtendable()) { 7902 selectionStart = getAccessibilitySelectionStart(); 7903 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7904 selectionStart = forward ? segmentStart : segmentEnd; 7905 } 7906 selectionEnd = forward ? segmentEnd : segmentStart; 7907 } else { 7908 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7909 } 7910 setAccessibilitySelection(selectionStart, selectionEnd); 7911 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7912 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7913 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7914 return true; 7915 } 7916 7917 /** 7918 * Gets the text reported for accessibility purposes. 7919 * 7920 * @return The accessibility text. 7921 * 7922 * @hide 7923 */ 7924 public CharSequence getIterableTextForAccessibility() { 7925 return getContentDescription(); 7926 } 7927 7928 /** 7929 * Gets whether accessibility selection can be extended. 7930 * 7931 * @return If selection is extensible. 7932 * 7933 * @hide 7934 */ 7935 public boolean isAccessibilitySelectionExtendable() { 7936 return false; 7937 } 7938 7939 /** 7940 * @hide 7941 */ 7942 public int getAccessibilitySelectionStart() { 7943 return mAccessibilityCursorPosition; 7944 } 7945 7946 /** 7947 * @hide 7948 */ 7949 public int getAccessibilitySelectionEnd() { 7950 return getAccessibilitySelectionStart(); 7951 } 7952 7953 /** 7954 * @hide 7955 */ 7956 public void setAccessibilitySelection(int start, int end) { 7957 if (start == end && end == mAccessibilityCursorPosition) { 7958 return; 7959 } 7960 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7961 mAccessibilityCursorPosition = start; 7962 } else { 7963 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7964 } 7965 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7966 } 7967 7968 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7969 int fromIndex, int toIndex) { 7970 if (mParent == null) { 7971 return; 7972 } 7973 AccessibilityEvent event = AccessibilityEvent.obtain( 7974 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7975 onInitializeAccessibilityEvent(event); 7976 onPopulateAccessibilityEvent(event); 7977 event.setFromIndex(fromIndex); 7978 event.setToIndex(toIndex); 7979 event.setAction(action); 7980 event.setMovementGranularity(granularity); 7981 mParent.requestSendAccessibilityEvent(this, event); 7982 } 7983 7984 /** 7985 * @hide 7986 */ 7987 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7988 switch (granularity) { 7989 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7990 CharSequence text = getIterableTextForAccessibility(); 7991 if (text != null && text.length() > 0) { 7992 CharacterTextSegmentIterator iterator = 7993 CharacterTextSegmentIterator.getInstance( 7994 mContext.getResources().getConfiguration().locale); 7995 iterator.initialize(text.toString()); 7996 return iterator; 7997 } 7998 } break; 7999 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 8000 CharSequence text = getIterableTextForAccessibility(); 8001 if (text != null && text.length() > 0) { 8002 WordTextSegmentIterator iterator = 8003 WordTextSegmentIterator.getInstance( 8004 mContext.getResources().getConfiguration().locale); 8005 iterator.initialize(text.toString()); 8006 return iterator; 8007 } 8008 } break; 8009 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 8010 CharSequence text = getIterableTextForAccessibility(); 8011 if (text != null && text.length() > 0) { 8012 ParagraphTextSegmentIterator iterator = 8013 ParagraphTextSegmentIterator.getInstance(); 8014 iterator.initialize(text.toString()); 8015 return iterator; 8016 } 8017 } break; 8018 } 8019 return null; 8020 } 8021 8022 /** 8023 * @hide 8024 */ 8025 public void dispatchStartTemporaryDetach() { 8026 onStartTemporaryDetach(); 8027 } 8028 8029 /** 8030 * This is called when a container is going to temporarily detach a child, with 8031 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 8032 * It will either be followed by {@link #onFinishTemporaryDetach()} or 8033 * {@link #onDetachedFromWindow()} when the container is done. 8034 */ 8035 public void onStartTemporaryDetach() { 8036 removeUnsetPressCallback(); 8037 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 8038 } 8039 8040 /** 8041 * @hide 8042 */ 8043 public void dispatchFinishTemporaryDetach() { 8044 onFinishTemporaryDetach(); 8045 } 8046 8047 /** 8048 * Called after {@link #onStartTemporaryDetach} when the container is done 8049 * changing the view. 8050 */ 8051 public void onFinishTemporaryDetach() { 8052 } 8053 8054 /** 8055 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8056 * for this view's window. Returns null if the view is not currently attached 8057 * to the window. Normally you will not need to use this directly, but 8058 * just use the standard high-level event callbacks like 8059 * {@link #onKeyDown(int, KeyEvent)}. 8060 */ 8061 public KeyEvent.DispatcherState getKeyDispatcherState() { 8062 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8063 } 8064 8065 /** 8066 * Dispatch a key event before it is processed by any input method 8067 * associated with the view hierarchy. This can be used to intercept 8068 * key events in special situations before the IME consumes them; a 8069 * typical example would be handling the BACK key to update the application's 8070 * UI instead of allowing the IME to see it and close itself. 8071 * 8072 * @param event The key event to be dispatched. 8073 * @return True if the event was handled, false otherwise. 8074 */ 8075 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8076 return onKeyPreIme(event.getKeyCode(), event); 8077 } 8078 8079 /** 8080 * Dispatch a key event to the next view on the focus path. This path runs 8081 * from the top of the view tree down to the currently focused view. If this 8082 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8083 * the next node down the focus path. This method also fires any key 8084 * listeners. 8085 * 8086 * @param event The key event to be dispatched. 8087 * @return True if the event was handled, false otherwise. 8088 */ 8089 public boolean dispatchKeyEvent(KeyEvent event) { 8090 if (mInputEventConsistencyVerifier != null) { 8091 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8092 } 8093 8094 // Give any attached key listener a first crack at the event. 8095 //noinspection SimplifiableIfStatement 8096 ListenerInfo li = mListenerInfo; 8097 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8098 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8099 return true; 8100 } 8101 8102 if (event.dispatch(this, mAttachInfo != null 8103 ? mAttachInfo.mKeyDispatchState : null, this)) { 8104 return true; 8105 } 8106 8107 if (mInputEventConsistencyVerifier != null) { 8108 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8109 } 8110 return false; 8111 } 8112 8113 /** 8114 * Dispatches a key shortcut event. 8115 * 8116 * @param event The key event to be dispatched. 8117 * @return True if the event was handled by the view, false otherwise. 8118 */ 8119 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8120 return onKeyShortcut(event.getKeyCode(), event); 8121 } 8122 8123 /** 8124 * Pass the touch screen motion event down to the target view, or this 8125 * view if it is the target. 8126 * 8127 * @param event The motion event to be dispatched. 8128 * @return True if the event was handled by the view, false otherwise. 8129 */ 8130 public boolean dispatchTouchEvent(MotionEvent event) { 8131 boolean result = false; 8132 8133 if (mInputEventConsistencyVerifier != null) { 8134 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8135 } 8136 8137 final int actionMasked = event.getActionMasked(); 8138 if (actionMasked == MotionEvent.ACTION_DOWN) { 8139 // Defensive cleanup for new gesture 8140 stopNestedScroll(); 8141 } 8142 8143 if (onFilterTouchEventForSecurity(event)) { 8144 //noinspection SimplifiableIfStatement 8145 ListenerInfo li = mListenerInfo; 8146 if (li != null && li.mOnTouchListener != null 8147 && (mViewFlags & ENABLED_MASK) == ENABLED 8148 && li.mOnTouchListener.onTouch(this, event)) { 8149 result = true; 8150 } 8151 8152 if (!result && onTouchEvent(event)) { 8153 result = true; 8154 } 8155 } 8156 8157 if (!result && mInputEventConsistencyVerifier != null) { 8158 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8159 } 8160 8161 // Clean up after nested scrolls if this is the end of a gesture; 8162 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8163 // of the gesture. 8164 if (actionMasked == MotionEvent.ACTION_UP || 8165 actionMasked == MotionEvent.ACTION_CANCEL || 8166 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8167 stopNestedScroll(); 8168 } 8169 8170 return result; 8171 } 8172 8173 /** 8174 * Filter the touch event to apply security policies. 8175 * 8176 * @param event The motion event to be filtered. 8177 * @return True if the event should be dispatched, false if the event should be dropped. 8178 * 8179 * @see #getFilterTouchesWhenObscured 8180 */ 8181 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8182 //noinspection RedundantIfStatement 8183 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8184 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8185 // Window is obscured, drop this touch. 8186 return false; 8187 } 8188 return true; 8189 } 8190 8191 /** 8192 * Pass a trackball motion event down to the focused view. 8193 * 8194 * @param event The motion event to be dispatched. 8195 * @return True if the event was handled by the view, false otherwise. 8196 */ 8197 public boolean dispatchTrackballEvent(MotionEvent event) { 8198 if (mInputEventConsistencyVerifier != null) { 8199 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8200 } 8201 8202 return onTrackballEvent(event); 8203 } 8204 8205 /** 8206 * Dispatch a generic motion event. 8207 * <p> 8208 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8209 * are delivered to the view under the pointer. All other generic motion events are 8210 * delivered to the focused view. Hover events are handled specially and are delivered 8211 * to {@link #onHoverEvent(MotionEvent)}. 8212 * </p> 8213 * 8214 * @param event The motion event to be dispatched. 8215 * @return True if the event was handled by the view, false otherwise. 8216 */ 8217 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8218 if (mInputEventConsistencyVerifier != null) { 8219 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8220 } 8221 8222 final int source = event.getSource(); 8223 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8224 final int action = event.getAction(); 8225 if (action == MotionEvent.ACTION_HOVER_ENTER 8226 || action == MotionEvent.ACTION_HOVER_MOVE 8227 || action == MotionEvent.ACTION_HOVER_EXIT) { 8228 if (dispatchHoverEvent(event)) { 8229 return true; 8230 } 8231 } else if (dispatchGenericPointerEvent(event)) { 8232 return true; 8233 } 8234 } else if (dispatchGenericFocusedEvent(event)) { 8235 return true; 8236 } 8237 8238 if (dispatchGenericMotionEventInternal(event)) { 8239 return true; 8240 } 8241 8242 if (mInputEventConsistencyVerifier != null) { 8243 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8244 } 8245 return false; 8246 } 8247 8248 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8249 //noinspection SimplifiableIfStatement 8250 ListenerInfo li = mListenerInfo; 8251 if (li != null && li.mOnGenericMotionListener != null 8252 && (mViewFlags & ENABLED_MASK) == ENABLED 8253 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8254 return true; 8255 } 8256 8257 if (onGenericMotionEvent(event)) { 8258 return true; 8259 } 8260 8261 if (mInputEventConsistencyVerifier != null) { 8262 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8263 } 8264 return false; 8265 } 8266 8267 /** 8268 * Dispatch a hover event. 8269 * <p> 8270 * Do not call this method directly. 8271 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8272 * </p> 8273 * 8274 * @param event The motion event to be dispatched. 8275 * @return True if the event was handled by the view, false otherwise. 8276 */ 8277 protected boolean dispatchHoverEvent(MotionEvent event) { 8278 ListenerInfo li = mListenerInfo; 8279 //noinspection SimplifiableIfStatement 8280 if (li != null && li.mOnHoverListener != null 8281 && (mViewFlags & ENABLED_MASK) == ENABLED 8282 && li.mOnHoverListener.onHover(this, event)) { 8283 return true; 8284 } 8285 8286 return onHoverEvent(event); 8287 } 8288 8289 /** 8290 * Returns true if the view has a child to which it has recently sent 8291 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8292 * it does not have a hovered child, then it must be the innermost hovered view. 8293 * @hide 8294 */ 8295 protected boolean hasHoveredChild() { 8296 return false; 8297 } 8298 8299 /** 8300 * Dispatch a generic motion event to the view under the first pointer. 8301 * <p> 8302 * Do not call this method directly. 8303 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8304 * </p> 8305 * 8306 * @param event The motion event to be dispatched. 8307 * @return True if the event was handled by the view, false otherwise. 8308 */ 8309 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8310 return false; 8311 } 8312 8313 /** 8314 * Dispatch a generic motion event to the currently focused view. 8315 * <p> 8316 * Do not call this method directly. 8317 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8318 * </p> 8319 * 8320 * @param event The motion event to be dispatched. 8321 * @return True if the event was handled by the view, false otherwise. 8322 */ 8323 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8324 return false; 8325 } 8326 8327 /** 8328 * Dispatch a pointer event. 8329 * <p> 8330 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8331 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8332 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8333 * and should not be expected to handle other pointing device features. 8334 * </p> 8335 * 8336 * @param event The motion event to be dispatched. 8337 * @return True if the event was handled by the view, false otherwise. 8338 * @hide 8339 */ 8340 public final boolean dispatchPointerEvent(MotionEvent event) { 8341 if (event.isTouchEvent()) { 8342 return dispatchTouchEvent(event); 8343 } else { 8344 return dispatchGenericMotionEvent(event); 8345 } 8346 } 8347 8348 /** 8349 * Called when the window containing this view gains or loses window focus. 8350 * ViewGroups should override to route to their children. 8351 * 8352 * @param hasFocus True if the window containing this view now has focus, 8353 * false otherwise. 8354 */ 8355 public void dispatchWindowFocusChanged(boolean hasFocus) { 8356 onWindowFocusChanged(hasFocus); 8357 } 8358 8359 /** 8360 * Called when the window containing this view gains or loses focus. Note 8361 * that this is separate from view focus: to receive key events, both 8362 * your view and its window must have focus. If a window is displayed 8363 * on top of yours that takes input focus, then your own window will lose 8364 * focus but the view focus will remain unchanged. 8365 * 8366 * @param hasWindowFocus True if the window containing this view now has 8367 * focus, false otherwise. 8368 */ 8369 public void onWindowFocusChanged(boolean hasWindowFocus) { 8370 InputMethodManager imm = InputMethodManager.peekInstance(); 8371 if (!hasWindowFocus) { 8372 if (isPressed()) { 8373 setPressed(false); 8374 } 8375 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8376 imm.focusOut(this); 8377 } 8378 removeLongPressCallback(); 8379 removeTapCallback(); 8380 onFocusLost(); 8381 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8382 imm.focusIn(this); 8383 } 8384 refreshDrawableState(); 8385 } 8386 8387 /** 8388 * Returns true if this view is in a window that currently has window focus. 8389 * Note that this is not the same as the view itself having focus. 8390 * 8391 * @return True if this view is in a window that currently has window focus. 8392 */ 8393 public boolean hasWindowFocus() { 8394 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8395 } 8396 8397 /** 8398 * Dispatch a view visibility change down the view hierarchy. 8399 * ViewGroups should override to route to their children. 8400 * @param changedView The view whose visibility changed. Could be 'this' or 8401 * an ancestor view. 8402 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8403 * {@link #INVISIBLE} or {@link #GONE}. 8404 */ 8405 protected void dispatchVisibilityChanged(@NonNull View changedView, 8406 @Visibility int visibility) { 8407 onVisibilityChanged(changedView, visibility); 8408 } 8409 8410 /** 8411 * Called when the visibility of the view or an ancestor of the view is changed. 8412 * @param changedView The view whose visibility changed. Could be 'this' or 8413 * an ancestor view. 8414 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8415 * {@link #INVISIBLE} or {@link #GONE}. 8416 */ 8417 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8418 if (visibility == VISIBLE) { 8419 if (mAttachInfo != null) { 8420 initialAwakenScrollBars(); 8421 } else { 8422 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8423 } 8424 } 8425 } 8426 8427 /** 8428 * Dispatch a hint about whether this view is displayed. For instance, when 8429 * a View moves out of the screen, it might receives a display hint indicating 8430 * the view is not displayed. Applications should not <em>rely</em> on this hint 8431 * as there is no guarantee that they will receive one. 8432 * 8433 * @param hint A hint about whether or not this view is displayed: 8434 * {@link #VISIBLE} or {@link #INVISIBLE}. 8435 */ 8436 public void dispatchDisplayHint(@Visibility int hint) { 8437 onDisplayHint(hint); 8438 } 8439 8440 /** 8441 * Gives this view a hint about whether is displayed or not. For instance, when 8442 * a View moves out of the screen, it might receives a display hint indicating 8443 * the view is not displayed. Applications should not <em>rely</em> on this hint 8444 * as there is no guarantee that they will receive one. 8445 * 8446 * @param hint A hint about whether or not this view is displayed: 8447 * {@link #VISIBLE} or {@link #INVISIBLE}. 8448 */ 8449 protected void onDisplayHint(@Visibility int hint) { 8450 } 8451 8452 /** 8453 * Dispatch a window visibility change down the view hierarchy. 8454 * ViewGroups should override to route to their children. 8455 * 8456 * @param visibility The new visibility of the window. 8457 * 8458 * @see #onWindowVisibilityChanged(int) 8459 */ 8460 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8461 onWindowVisibilityChanged(visibility); 8462 } 8463 8464 /** 8465 * Called when the window containing has change its visibility 8466 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8467 * that this tells you whether or not your window is being made visible 8468 * to the window manager; this does <em>not</em> tell you whether or not 8469 * your window is obscured by other windows on the screen, even if it 8470 * is itself visible. 8471 * 8472 * @param visibility The new visibility of the window. 8473 */ 8474 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8475 if (visibility == VISIBLE) { 8476 initialAwakenScrollBars(); 8477 } 8478 } 8479 8480 /** 8481 * Returns the current visibility of the window this view is attached to 8482 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8483 * 8484 * @return Returns the current visibility of the view's window. 8485 */ 8486 @Visibility 8487 public int getWindowVisibility() { 8488 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8489 } 8490 8491 /** 8492 * Retrieve the overall visible display size in which the window this view is 8493 * attached to has been positioned in. This takes into account screen 8494 * decorations above the window, for both cases where the window itself 8495 * is being position inside of them or the window is being placed under 8496 * then and covered insets are used for the window to position its content 8497 * inside. In effect, this tells you the available area where content can 8498 * be placed and remain visible to users. 8499 * 8500 * <p>This function requires an IPC back to the window manager to retrieve 8501 * the requested information, so should not be used in performance critical 8502 * code like drawing. 8503 * 8504 * @param outRect Filled in with the visible display frame. If the view 8505 * is not attached to a window, this is simply the raw display size. 8506 */ 8507 public void getWindowVisibleDisplayFrame(Rect outRect) { 8508 if (mAttachInfo != null) { 8509 try { 8510 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8511 } catch (RemoteException e) { 8512 return; 8513 } 8514 // XXX This is really broken, and probably all needs to be done 8515 // in the window manager, and we need to know more about whether 8516 // we want the area behind or in front of the IME. 8517 final Rect insets = mAttachInfo.mVisibleInsets; 8518 outRect.left += insets.left; 8519 outRect.top += insets.top; 8520 outRect.right -= insets.right; 8521 outRect.bottom -= insets.bottom; 8522 return; 8523 } 8524 // The view is not attached to a display so we don't have a context. 8525 // Make a best guess about the display size. 8526 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8527 d.getRectSize(outRect); 8528 } 8529 8530 /** 8531 * Dispatch a notification about a resource configuration change down 8532 * the view hierarchy. 8533 * ViewGroups should override to route to their children. 8534 * 8535 * @param newConfig The new resource configuration. 8536 * 8537 * @see #onConfigurationChanged(android.content.res.Configuration) 8538 */ 8539 public void dispatchConfigurationChanged(Configuration newConfig) { 8540 onConfigurationChanged(newConfig); 8541 } 8542 8543 /** 8544 * Called when the current configuration of the resources being used 8545 * by the application have changed. You can use this to decide when 8546 * to reload resources that can changed based on orientation and other 8547 * configuration characterstics. You only need to use this if you are 8548 * not relying on the normal {@link android.app.Activity} mechanism of 8549 * recreating the activity instance upon a configuration change. 8550 * 8551 * @param newConfig The new resource configuration. 8552 */ 8553 protected void onConfigurationChanged(Configuration newConfig) { 8554 } 8555 8556 /** 8557 * Private function to aggregate all per-view attributes in to the view 8558 * root. 8559 */ 8560 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8561 performCollectViewAttributes(attachInfo, visibility); 8562 } 8563 8564 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8565 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8566 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8567 attachInfo.mKeepScreenOn = true; 8568 } 8569 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8570 ListenerInfo li = mListenerInfo; 8571 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8572 attachInfo.mHasSystemUiListeners = true; 8573 } 8574 } 8575 } 8576 8577 void needGlobalAttributesUpdate(boolean force) { 8578 final AttachInfo ai = mAttachInfo; 8579 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8580 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8581 || ai.mHasSystemUiListeners) { 8582 ai.mRecomputeGlobalAttributes = true; 8583 } 8584 } 8585 } 8586 8587 /** 8588 * Returns whether the device is currently in touch mode. Touch mode is entered 8589 * once the user begins interacting with the device by touch, and affects various 8590 * things like whether focus is always visible to the user. 8591 * 8592 * @return Whether the device is in touch mode. 8593 */ 8594 @ViewDebug.ExportedProperty 8595 public boolean isInTouchMode() { 8596 if (mAttachInfo != null) { 8597 return mAttachInfo.mInTouchMode; 8598 } else { 8599 return ViewRootImpl.isInTouchMode(); 8600 } 8601 } 8602 8603 /** 8604 * Returns the context the view is running in, through which it can 8605 * access the current theme, resources, etc. 8606 * 8607 * @return The view's Context. 8608 */ 8609 @ViewDebug.CapturedViewProperty 8610 public final Context getContext() { 8611 return mContext; 8612 } 8613 8614 /** 8615 * Handle a key event before it is processed by any input method 8616 * associated with the view hierarchy. This can be used to intercept 8617 * key events in special situations before the IME consumes them; a 8618 * typical example would be handling the BACK key to update the application's 8619 * UI instead of allowing the IME to see it and close itself. 8620 * 8621 * @param keyCode The value in event.getKeyCode(). 8622 * @param event Description of the key event. 8623 * @return If you handled the event, return true. If you want to allow the 8624 * event to be handled by the next receiver, return false. 8625 */ 8626 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8627 return false; 8628 } 8629 8630 /** 8631 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8632 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8633 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8634 * is released, if the view is enabled and clickable. 8635 * 8636 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8637 * although some may elect to do so in some situations. Do not rely on this to 8638 * catch software key presses. 8639 * 8640 * @param keyCode A key code that represents the button pressed, from 8641 * {@link android.view.KeyEvent}. 8642 * @param event The KeyEvent object that defines the button action. 8643 */ 8644 public boolean onKeyDown(int keyCode, KeyEvent event) { 8645 boolean result = false; 8646 8647 if (KeyEvent.isConfirmKey(keyCode)) { 8648 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8649 return true; 8650 } 8651 // Long clickable items don't necessarily have to be clickable 8652 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8653 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8654 (event.getRepeatCount() == 0)) { 8655 setPressed(true); 8656 checkForLongClick(0); 8657 return true; 8658 } 8659 } 8660 return result; 8661 } 8662 8663 /** 8664 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8665 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8666 * the event). 8667 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8668 * although some may elect to do so in some situations. Do not rely on this to 8669 * catch software key presses. 8670 */ 8671 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8672 return false; 8673 } 8674 8675 /** 8676 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8677 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8678 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8679 * {@link KeyEvent#KEYCODE_ENTER} is released. 8680 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8681 * although some may elect to do so in some situations. Do not rely on this to 8682 * catch software key presses. 8683 * 8684 * @param keyCode A key code that represents the button pressed, from 8685 * {@link android.view.KeyEvent}. 8686 * @param event The KeyEvent object that defines the button action. 8687 */ 8688 public boolean onKeyUp(int keyCode, KeyEvent event) { 8689 if (KeyEvent.isConfirmKey(keyCode)) { 8690 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8691 return true; 8692 } 8693 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8694 setPressed(false); 8695 8696 if (!mHasPerformedLongPress) { 8697 // This is a tap, so remove the longpress check 8698 removeLongPressCallback(); 8699 return performClick(); 8700 } 8701 } 8702 } 8703 return false; 8704 } 8705 8706 /** 8707 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8708 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8709 * the event). 8710 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8711 * although some may elect to do so in some situations. Do not rely on this to 8712 * catch software key presses. 8713 * 8714 * @param keyCode A key code that represents the button pressed, from 8715 * {@link android.view.KeyEvent}. 8716 * @param repeatCount The number of times the action was made. 8717 * @param event The KeyEvent object that defines the button action. 8718 */ 8719 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8720 return false; 8721 } 8722 8723 /** 8724 * Called on the focused view when a key shortcut event is not handled. 8725 * Override this method to implement local key shortcuts for the View. 8726 * Key shortcuts can also be implemented by setting the 8727 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8728 * 8729 * @param keyCode The value in event.getKeyCode(). 8730 * @param event Description of the key event. 8731 * @return If you handled the event, return true. If you want to allow the 8732 * event to be handled by the next receiver, return false. 8733 */ 8734 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8735 return false; 8736 } 8737 8738 /** 8739 * Check whether the called view is a text editor, in which case it 8740 * would make sense to automatically display a soft input window for 8741 * it. Subclasses should override this if they implement 8742 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8743 * a call on that method would return a non-null InputConnection, and 8744 * they are really a first-class editor that the user would normally 8745 * start typing on when the go into a window containing your view. 8746 * 8747 * <p>The default implementation always returns false. This does 8748 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8749 * will not be called or the user can not otherwise perform edits on your 8750 * view; it is just a hint to the system that this is not the primary 8751 * purpose of this view. 8752 * 8753 * @return Returns true if this view is a text editor, else false. 8754 */ 8755 public boolean onCheckIsTextEditor() { 8756 return false; 8757 } 8758 8759 /** 8760 * Create a new InputConnection for an InputMethod to interact 8761 * with the view. The default implementation returns null, since it doesn't 8762 * support input methods. You can override this to implement such support. 8763 * This is only needed for views that take focus and text input. 8764 * 8765 * <p>When implementing this, you probably also want to implement 8766 * {@link #onCheckIsTextEditor()} to indicate you will return a 8767 * non-null InputConnection.</p> 8768 * 8769 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8770 * object correctly and in its entirety, so that the connected IME can rely 8771 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8772 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8773 * must be filled in with the correct cursor position for IMEs to work correctly 8774 * with your application.</p> 8775 * 8776 * @param outAttrs Fill in with attribute information about the connection. 8777 */ 8778 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8779 return null; 8780 } 8781 8782 /** 8783 * Called by the {@link android.view.inputmethod.InputMethodManager} 8784 * when a view who is not the current 8785 * input connection target is trying to make a call on the manager. The 8786 * default implementation returns false; you can override this to return 8787 * true for certain views if you are performing InputConnection proxying 8788 * to them. 8789 * @param view The View that is making the InputMethodManager call. 8790 * @return Return true to allow the call, false to reject. 8791 */ 8792 public boolean checkInputConnectionProxy(View view) { 8793 return false; 8794 } 8795 8796 /** 8797 * Show the context menu for this view. It is not safe to hold on to the 8798 * menu after returning from this method. 8799 * 8800 * You should normally not overload this method. Overload 8801 * {@link #onCreateContextMenu(ContextMenu)} or define an 8802 * {@link OnCreateContextMenuListener} to add items to the context menu. 8803 * 8804 * @param menu The context menu to populate 8805 */ 8806 public void createContextMenu(ContextMenu menu) { 8807 ContextMenuInfo menuInfo = getContextMenuInfo(); 8808 8809 // Sets the current menu info so all items added to menu will have 8810 // my extra info set. 8811 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8812 8813 onCreateContextMenu(menu); 8814 ListenerInfo li = mListenerInfo; 8815 if (li != null && li.mOnCreateContextMenuListener != null) { 8816 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8817 } 8818 8819 // Clear the extra information so subsequent items that aren't mine don't 8820 // have my extra info. 8821 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8822 8823 if (mParent != null) { 8824 mParent.createContextMenu(menu); 8825 } 8826 } 8827 8828 /** 8829 * Views should implement this if they have extra information to associate 8830 * with the context menu. The return result is supplied as a parameter to 8831 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8832 * callback. 8833 * 8834 * @return Extra information about the item for which the context menu 8835 * should be shown. This information will vary across different 8836 * subclasses of View. 8837 */ 8838 protected ContextMenuInfo getContextMenuInfo() { 8839 return null; 8840 } 8841 8842 /** 8843 * Views should implement this if the view itself is going to add items to 8844 * the context menu. 8845 * 8846 * @param menu the context menu to populate 8847 */ 8848 protected void onCreateContextMenu(ContextMenu menu) { 8849 } 8850 8851 /** 8852 * Implement this method to handle trackball motion events. The 8853 * <em>relative</em> movement of the trackball since the last event 8854 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8855 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8856 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8857 * they will often be fractional values, representing the more fine-grained 8858 * movement information available from a trackball). 8859 * 8860 * @param event The motion event. 8861 * @return True if the event was handled, false otherwise. 8862 */ 8863 public boolean onTrackballEvent(MotionEvent event) { 8864 return false; 8865 } 8866 8867 /** 8868 * Implement this method to handle generic motion events. 8869 * <p> 8870 * Generic motion events describe joystick movements, mouse hovers, track pad 8871 * touches, scroll wheel movements and other input events. The 8872 * {@link MotionEvent#getSource() source} of the motion event specifies 8873 * the class of input that was received. Implementations of this method 8874 * must examine the bits in the source before processing the event. 8875 * The following code example shows how this is done. 8876 * </p><p> 8877 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8878 * are delivered to the view under the pointer. All other generic motion events are 8879 * delivered to the focused view. 8880 * </p> 8881 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8882 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8883 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8884 * // process the joystick movement... 8885 * return true; 8886 * } 8887 * } 8888 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8889 * switch (event.getAction()) { 8890 * case MotionEvent.ACTION_HOVER_MOVE: 8891 * // process the mouse hover movement... 8892 * return true; 8893 * case MotionEvent.ACTION_SCROLL: 8894 * // process the scroll wheel movement... 8895 * return true; 8896 * } 8897 * } 8898 * return super.onGenericMotionEvent(event); 8899 * }</pre> 8900 * 8901 * @param event The generic motion event being processed. 8902 * @return True if the event was handled, false otherwise. 8903 */ 8904 public boolean onGenericMotionEvent(MotionEvent event) { 8905 return false; 8906 } 8907 8908 /** 8909 * Implement this method to handle hover events. 8910 * <p> 8911 * This method is called whenever a pointer is hovering into, over, or out of the 8912 * bounds of a view and the view is not currently being touched. 8913 * Hover events are represented as pointer events with action 8914 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8915 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8916 * </p> 8917 * <ul> 8918 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8919 * when the pointer enters the bounds of the view.</li> 8920 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8921 * when the pointer has already entered the bounds of the view and has moved.</li> 8922 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8923 * when the pointer has exited the bounds of the view or when the pointer is 8924 * about to go down due to a button click, tap, or similar user action that 8925 * causes the view to be touched.</li> 8926 * </ul> 8927 * <p> 8928 * The view should implement this method to return true to indicate that it is 8929 * handling the hover event, such as by changing its drawable state. 8930 * </p><p> 8931 * The default implementation calls {@link #setHovered} to update the hovered state 8932 * of the view when a hover enter or hover exit event is received, if the view 8933 * is enabled and is clickable. The default implementation also sends hover 8934 * accessibility events. 8935 * </p> 8936 * 8937 * @param event The motion event that describes the hover. 8938 * @return True if the view handled the hover event. 8939 * 8940 * @see #isHovered 8941 * @see #setHovered 8942 * @see #onHoverChanged 8943 */ 8944 public boolean onHoverEvent(MotionEvent event) { 8945 // The root view may receive hover (or touch) events that are outside the bounds of 8946 // the window. This code ensures that we only send accessibility events for 8947 // hovers that are actually within the bounds of the root view. 8948 final int action = event.getActionMasked(); 8949 if (!mSendingHoverAccessibilityEvents) { 8950 if ((action == MotionEvent.ACTION_HOVER_ENTER 8951 || action == MotionEvent.ACTION_HOVER_MOVE) 8952 && !hasHoveredChild() 8953 && pointInView(event.getX(), event.getY())) { 8954 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8955 mSendingHoverAccessibilityEvents = true; 8956 } 8957 } else { 8958 if (action == MotionEvent.ACTION_HOVER_EXIT 8959 || (action == MotionEvent.ACTION_MOVE 8960 && !pointInView(event.getX(), event.getY()))) { 8961 mSendingHoverAccessibilityEvents = false; 8962 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8963 } 8964 } 8965 8966 if (isHoverable()) { 8967 switch (action) { 8968 case MotionEvent.ACTION_HOVER_ENTER: 8969 setHovered(true); 8970 break; 8971 case MotionEvent.ACTION_HOVER_EXIT: 8972 setHovered(false); 8973 break; 8974 } 8975 8976 // Dispatch the event to onGenericMotionEvent before returning true. 8977 // This is to provide compatibility with existing applications that 8978 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8979 // break because of the new default handling for hoverable views 8980 // in onHoverEvent. 8981 // Note that onGenericMotionEvent will be called by default when 8982 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8983 dispatchGenericMotionEventInternal(event); 8984 // The event was already handled by calling setHovered(), so always 8985 // return true. 8986 return true; 8987 } 8988 8989 return false; 8990 } 8991 8992 /** 8993 * Returns true if the view should handle {@link #onHoverEvent} 8994 * by calling {@link #setHovered} to change its hovered state. 8995 * 8996 * @return True if the view is hoverable. 8997 */ 8998 private boolean isHoverable() { 8999 final int viewFlags = mViewFlags; 9000 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9001 return false; 9002 } 9003 9004 return (viewFlags & CLICKABLE) == CLICKABLE 9005 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 9006 } 9007 9008 /** 9009 * Returns true if the view is currently hovered. 9010 * 9011 * @return True if the view is currently hovered. 9012 * 9013 * @see #setHovered 9014 * @see #onHoverChanged 9015 */ 9016 @ViewDebug.ExportedProperty 9017 public boolean isHovered() { 9018 return (mPrivateFlags & PFLAG_HOVERED) != 0; 9019 } 9020 9021 /** 9022 * Sets whether the view is currently hovered. 9023 * <p> 9024 * Calling this method also changes the drawable state of the view. This 9025 * enables the view to react to hover by using different drawable resources 9026 * to change its appearance. 9027 * </p><p> 9028 * The {@link #onHoverChanged} method is called when the hovered state changes. 9029 * </p> 9030 * 9031 * @param hovered True if the view is hovered. 9032 * 9033 * @see #isHovered 9034 * @see #onHoverChanged 9035 */ 9036 public void setHovered(boolean hovered) { 9037 if (hovered) { 9038 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 9039 mPrivateFlags |= PFLAG_HOVERED; 9040 refreshDrawableState(); 9041 onHoverChanged(true); 9042 } 9043 } else { 9044 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 9045 mPrivateFlags &= ~PFLAG_HOVERED; 9046 refreshDrawableState(); 9047 onHoverChanged(false); 9048 } 9049 } 9050 } 9051 9052 /** 9053 * Implement this method to handle hover state changes. 9054 * <p> 9055 * This method is called whenever the hover state changes as a result of a 9056 * call to {@link #setHovered}. 9057 * </p> 9058 * 9059 * @param hovered The current hover state, as returned by {@link #isHovered}. 9060 * 9061 * @see #isHovered 9062 * @see #setHovered 9063 */ 9064 public void onHoverChanged(boolean hovered) { 9065 } 9066 9067 /** 9068 * Implement this method to handle touch screen motion events. 9069 * <p> 9070 * If this method is used to detect click actions, it is recommended that 9071 * the actions be performed by implementing and calling 9072 * {@link #performClick()}. This will ensure consistent system behavior, 9073 * including: 9074 * <ul> 9075 * <li>obeying click sound preferences 9076 * <li>dispatching OnClickListener calls 9077 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9078 * accessibility features are enabled 9079 * </ul> 9080 * 9081 * @param event The motion event. 9082 * @return True if the event was handled, false otherwise. 9083 */ 9084 public boolean onTouchEvent(MotionEvent event) { 9085 final float x = event.getX(); 9086 final float y = event.getY(); 9087 final int viewFlags = mViewFlags; 9088 9089 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9090 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9091 setPressed(false); 9092 } 9093 // A disabled view that is clickable still consumes the touch 9094 // events, it just doesn't respond to them. 9095 return (((viewFlags & CLICKABLE) == CLICKABLE || 9096 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9097 } 9098 9099 if (mTouchDelegate != null) { 9100 if (mTouchDelegate.onTouchEvent(event)) { 9101 return true; 9102 } 9103 } 9104 9105 if (((viewFlags & CLICKABLE) == CLICKABLE || 9106 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9107 switch (event.getAction()) { 9108 case MotionEvent.ACTION_UP: 9109 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9110 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9111 // take focus if we don't have it already and we should in 9112 // touch mode. 9113 boolean focusTaken = false; 9114 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9115 focusTaken = requestFocus(); 9116 } 9117 9118 if (prepressed) { 9119 // The button is being released before we actually 9120 // showed it as pressed. Make it show the pressed 9121 // state now (before scheduling the click) to ensure 9122 // the user sees it. 9123 setPressed(true, x, y); 9124 } 9125 9126 if (!mHasPerformedLongPress) { 9127 // This is a tap, so remove the longpress check 9128 removeLongPressCallback(); 9129 9130 // Only perform take click actions if we were in the pressed state 9131 if (!focusTaken) { 9132 // Use a Runnable and post this rather than calling 9133 // performClick directly. This lets other visual state 9134 // of the view update before click actions start. 9135 if (mPerformClick == null) { 9136 mPerformClick = new PerformClick(); 9137 } 9138 if (!post(mPerformClick)) { 9139 performClick(); 9140 } 9141 } 9142 } 9143 9144 if (mUnsetPressedState == null) { 9145 mUnsetPressedState = new UnsetPressedState(); 9146 } 9147 9148 if (prepressed) { 9149 postDelayed(mUnsetPressedState, 9150 ViewConfiguration.getPressedStateDuration()); 9151 } else if (!post(mUnsetPressedState)) { 9152 // If the post failed, unpress right now 9153 mUnsetPressedState.run(); 9154 } 9155 9156 removeTapCallback(); 9157 } 9158 break; 9159 9160 case MotionEvent.ACTION_DOWN: 9161 mHasPerformedLongPress = false; 9162 9163 if (performButtonActionOnTouchDown(event)) { 9164 break; 9165 } 9166 9167 // Walk up the hierarchy to determine if we're inside a scrolling container. 9168 boolean isInScrollingContainer = isInScrollingContainer(); 9169 9170 // For views inside a scrolling container, delay the pressed feedback for 9171 // a short period in case this is a scroll. 9172 if (isInScrollingContainer) { 9173 mPrivateFlags |= PFLAG_PREPRESSED; 9174 if (mPendingCheckForTap == null) { 9175 mPendingCheckForTap = new CheckForTap(); 9176 } 9177 mPendingCheckForTap.x = event.getX(); 9178 mPendingCheckForTap.y = event.getY(); 9179 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9180 } else { 9181 // Not inside a scrolling container, so show the feedback right away 9182 setPressed(true, x, y); 9183 checkForLongClick(0); 9184 } 9185 break; 9186 9187 case MotionEvent.ACTION_CANCEL: 9188 setPressed(false); 9189 removeTapCallback(); 9190 removeLongPressCallback(); 9191 break; 9192 9193 case MotionEvent.ACTION_MOVE: 9194 drawableHotspotChanged(x, y); 9195 9196 // Be lenient about moving outside of buttons 9197 if (!pointInView(x, y, mTouchSlop)) { 9198 // Outside button 9199 removeTapCallback(); 9200 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9201 // Remove any future long press/tap checks 9202 removeLongPressCallback(); 9203 9204 setPressed(false); 9205 } 9206 } 9207 break; 9208 } 9209 9210 return true; 9211 } 9212 9213 return false; 9214 } 9215 9216 /** 9217 * @hide 9218 */ 9219 public boolean isInScrollingContainer() { 9220 ViewParent p = getParent(); 9221 while (p != null && p instanceof ViewGroup) { 9222 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9223 return true; 9224 } 9225 p = p.getParent(); 9226 } 9227 return false; 9228 } 9229 9230 /** 9231 * Remove the longpress detection timer. 9232 */ 9233 private void removeLongPressCallback() { 9234 if (mPendingCheckForLongPress != null) { 9235 removeCallbacks(mPendingCheckForLongPress); 9236 } 9237 } 9238 9239 /** 9240 * Remove the pending click action 9241 */ 9242 private void removePerformClickCallback() { 9243 if (mPerformClick != null) { 9244 removeCallbacks(mPerformClick); 9245 } 9246 } 9247 9248 /** 9249 * Remove the prepress detection timer. 9250 */ 9251 private void removeUnsetPressCallback() { 9252 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9253 setPressed(false); 9254 removeCallbacks(mUnsetPressedState); 9255 } 9256 } 9257 9258 /** 9259 * Remove the tap detection timer. 9260 */ 9261 private void removeTapCallback() { 9262 if (mPendingCheckForTap != null) { 9263 mPrivateFlags &= ~PFLAG_PREPRESSED; 9264 removeCallbacks(mPendingCheckForTap); 9265 } 9266 } 9267 9268 /** 9269 * Cancels a pending long press. Your subclass can use this if you 9270 * want the context menu to come up if the user presses and holds 9271 * at the same place, but you don't want it to come up if they press 9272 * and then move around enough to cause scrolling. 9273 */ 9274 public void cancelLongPress() { 9275 removeLongPressCallback(); 9276 9277 /* 9278 * The prepressed state handled by the tap callback is a display 9279 * construct, but the tap callback will post a long press callback 9280 * less its own timeout. Remove it here. 9281 */ 9282 removeTapCallback(); 9283 } 9284 9285 /** 9286 * Remove the pending callback for sending a 9287 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9288 */ 9289 private void removeSendViewScrolledAccessibilityEventCallback() { 9290 if (mSendViewScrolledAccessibilityEvent != null) { 9291 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9292 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9293 } 9294 } 9295 9296 /** 9297 * Sets the TouchDelegate for this View. 9298 */ 9299 public void setTouchDelegate(TouchDelegate delegate) { 9300 mTouchDelegate = delegate; 9301 } 9302 9303 /** 9304 * Gets the TouchDelegate for this View. 9305 */ 9306 public TouchDelegate getTouchDelegate() { 9307 return mTouchDelegate; 9308 } 9309 9310 /** 9311 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9312 * 9313 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9314 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9315 * available. This method should only be called for touch events. 9316 * 9317 * <p class="note">This api is not intended for most applications. Buffered dispatch 9318 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9319 * streams will not improve your input latency. Side effects include: increased latency, 9320 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9321 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9322 * you.</p> 9323 */ 9324 public final void requestUnbufferedDispatch(MotionEvent event) { 9325 final int action = event.getAction(); 9326 if (mAttachInfo == null 9327 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9328 || !event.isTouchEvent()) { 9329 return; 9330 } 9331 mAttachInfo.mUnbufferedDispatchRequested = true; 9332 } 9333 9334 /** 9335 * Set flags controlling behavior of this view. 9336 * 9337 * @param flags Constant indicating the value which should be set 9338 * @param mask Constant indicating the bit range that should be changed 9339 */ 9340 void setFlags(int flags, int mask) { 9341 final boolean accessibilityEnabled = 9342 AccessibilityManager.getInstance(mContext).isEnabled(); 9343 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9344 9345 int old = mViewFlags; 9346 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9347 9348 int changed = mViewFlags ^ old; 9349 if (changed == 0) { 9350 return; 9351 } 9352 int privateFlags = mPrivateFlags; 9353 9354 /* Check if the FOCUSABLE bit has changed */ 9355 if (((changed & FOCUSABLE_MASK) != 0) && 9356 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9357 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9358 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9359 /* Give up focus if we are no longer focusable */ 9360 clearFocus(); 9361 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9362 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9363 /* 9364 * Tell the view system that we are now available to take focus 9365 * if no one else already has it. 9366 */ 9367 if (mParent != null) mParent.focusableViewAvailable(this); 9368 } 9369 } 9370 9371 final int newVisibility = flags & VISIBILITY_MASK; 9372 if (newVisibility == VISIBLE) { 9373 if ((changed & VISIBILITY_MASK) != 0) { 9374 /* 9375 * If this view is becoming visible, invalidate it in case it changed while 9376 * it was not visible. Marking it drawn ensures that the invalidation will 9377 * go through. 9378 */ 9379 mPrivateFlags |= PFLAG_DRAWN; 9380 invalidate(true); 9381 9382 needGlobalAttributesUpdate(true); 9383 9384 // a view becoming visible is worth notifying the parent 9385 // about in case nothing has focus. even if this specific view 9386 // isn't focusable, it may contain something that is, so let 9387 // the root view try to give this focus if nothing else does. 9388 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9389 mParent.focusableViewAvailable(this); 9390 } 9391 } 9392 } 9393 9394 /* Check if the GONE bit has changed */ 9395 if ((changed & GONE) != 0) { 9396 needGlobalAttributesUpdate(false); 9397 requestLayout(); 9398 9399 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9400 if (hasFocus()) clearFocus(); 9401 clearAccessibilityFocus(); 9402 destroyDrawingCache(); 9403 if (mParent instanceof View) { 9404 // GONE views noop invalidation, so invalidate the parent 9405 ((View) mParent).invalidate(true); 9406 } 9407 // Mark the view drawn to ensure that it gets invalidated properly the next 9408 // time it is visible and gets invalidated 9409 mPrivateFlags |= PFLAG_DRAWN; 9410 } 9411 if (mAttachInfo != null) { 9412 mAttachInfo.mViewVisibilityChanged = true; 9413 } 9414 } 9415 9416 /* Check if the VISIBLE bit has changed */ 9417 if ((changed & INVISIBLE) != 0) { 9418 needGlobalAttributesUpdate(false); 9419 /* 9420 * If this view is becoming invisible, set the DRAWN flag so that 9421 * the next invalidate() will not be skipped. 9422 */ 9423 mPrivateFlags |= PFLAG_DRAWN; 9424 9425 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9426 // root view becoming invisible shouldn't clear focus and accessibility focus 9427 if (getRootView() != this) { 9428 if (hasFocus()) clearFocus(); 9429 clearAccessibilityFocus(); 9430 } 9431 } 9432 if (mAttachInfo != null) { 9433 mAttachInfo.mViewVisibilityChanged = true; 9434 } 9435 } 9436 9437 if ((changed & VISIBILITY_MASK) != 0) { 9438 // If the view is invisible, cleanup its display list to free up resources 9439 if (newVisibility != VISIBLE && mAttachInfo != null) { 9440 cleanupDraw(); 9441 } 9442 9443 if (mParent instanceof ViewGroup) { 9444 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9445 (changed & VISIBILITY_MASK), newVisibility); 9446 ((View) mParent).invalidate(true); 9447 } else if (mParent != null) { 9448 mParent.invalidateChild(this, null); 9449 } 9450 dispatchVisibilityChanged(this, newVisibility); 9451 9452 notifySubtreeAccessibilityStateChangedIfNeeded(); 9453 } 9454 9455 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9456 destroyDrawingCache(); 9457 } 9458 9459 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9460 destroyDrawingCache(); 9461 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9462 invalidateParentCaches(); 9463 } 9464 9465 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9466 destroyDrawingCache(); 9467 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9468 } 9469 9470 if ((changed & DRAW_MASK) != 0) { 9471 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9472 if (mBackground != null) { 9473 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9474 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9475 } else { 9476 mPrivateFlags |= PFLAG_SKIP_DRAW; 9477 } 9478 } else { 9479 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9480 } 9481 requestLayout(); 9482 invalidate(true); 9483 } 9484 9485 if ((changed & KEEP_SCREEN_ON) != 0) { 9486 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9487 mParent.recomputeViewAttributes(this); 9488 } 9489 } 9490 9491 if (accessibilityEnabled) { 9492 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9493 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9494 if (oldIncludeForAccessibility != includeForAccessibility()) { 9495 notifySubtreeAccessibilityStateChangedIfNeeded(); 9496 } else { 9497 notifyViewAccessibilityStateChangedIfNeeded( 9498 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9499 } 9500 } else if ((changed & ENABLED_MASK) != 0) { 9501 notifyViewAccessibilityStateChangedIfNeeded( 9502 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9503 } 9504 } 9505 } 9506 9507 /** 9508 * Change the view's z order in the tree, so it's on top of other sibling 9509 * views. This ordering change may affect layout, if the parent container 9510 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9511 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9512 * method should be followed by calls to {@link #requestLayout()} and 9513 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9514 * with the new child ordering. 9515 * 9516 * @see ViewGroup#bringChildToFront(View) 9517 */ 9518 public void bringToFront() { 9519 if (mParent != null) { 9520 mParent.bringChildToFront(this); 9521 } 9522 } 9523 9524 /** 9525 * This is called in response to an internal scroll in this view (i.e., the 9526 * view scrolled its own contents). This is typically as a result of 9527 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9528 * called. 9529 * 9530 * @param l Current horizontal scroll origin. 9531 * @param t Current vertical scroll origin. 9532 * @param oldl Previous horizontal scroll origin. 9533 * @param oldt Previous vertical scroll origin. 9534 */ 9535 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9536 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9537 postSendViewScrolledAccessibilityEventCallback(); 9538 } 9539 9540 mBackgroundSizeChanged = true; 9541 9542 final AttachInfo ai = mAttachInfo; 9543 if (ai != null) { 9544 ai.mViewScrollChanged = true; 9545 } 9546 } 9547 9548 /** 9549 * Interface definition for a callback to be invoked when the layout bounds of a view 9550 * changes due to layout processing. 9551 */ 9552 public interface OnLayoutChangeListener { 9553 /** 9554 * Called when the layout bounds of a view changes due to layout processing. 9555 * 9556 * @param v The view whose bounds have changed. 9557 * @param left The new value of the view's left property. 9558 * @param top The new value of the view's top property. 9559 * @param right The new value of the view's right property. 9560 * @param bottom The new value of the view's bottom property. 9561 * @param oldLeft The previous value of the view's left property. 9562 * @param oldTop The previous value of the view's top property. 9563 * @param oldRight The previous value of the view's right property. 9564 * @param oldBottom The previous value of the view's bottom property. 9565 */ 9566 void onLayoutChange(View v, int left, int top, int right, int bottom, 9567 int oldLeft, int oldTop, int oldRight, int oldBottom); 9568 } 9569 9570 /** 9571 * This is called during layout when the size of this view has changed. If 9572 * you were just added to the view hierarchy, you're called with the old 9573 * values of 0. 9574 * 9575 * @param w Current width of this view. 9576 * @param h Current height of this view. 9577 * @param oldw Old width of this view. 9578 * @param oldh Old height of this view. 9579 */ 9580 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9581 } 9582 9583 /** 9584 * Called by draw to draw the child views. This may be overridden 9585 * by derived classes to gain control just before its children are drawn 9586 * (but after its own view has been drawn). 9587 * @param canvas the canvas on which to draw the view 9588 */ 9589 protected void dispatchDraw(Canvas canvas) { 9590 9591 } 9592 9593 /** 9594 * Gets the parent of this view. Note that the parent is a 9595 * ViewParent and not necessarily a View. 9596 * 9597 * @return Parent of this view. 9598 */ 9599 public final ViewParent getParent() { 9600 return mParent; 9601 } 9602 9603 /** 9604 * Set the horizontal scrolled position of your view. This will cause a call to 9605 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9606 * invalidated. 9607 * @param value the x position to scroll to 9608 */ 9609 public void setScrollX(int value) { 9610 scrollTo(value, mScrollY); 9611 } 9612 9613 /** 9614 * Set the vertical scrolled position of your view. This will cause a call to 9615 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9616 * invalidated. 9617 * @param value the y position to scroll to 9618 */ 9619 public void setScrollY(int value) { 9620 scrollTo(mScrollX, value); 9621 } 9622 9623 /** 9624 * Return the scrolled left position of this view. This is the left edge of 9625 * the displayed part of your view. You do not need to draw any pixels 9626 * farther left, since those are outside of the frame of your view on 9627 * screen. 9628 * 9629 * @return The left edge of the displayed part of your view, in pixels. 9630 */ 9631 public final int getScrollX() { 9632 return mScrollX; 9633 } 9634 9635 /** 9636 * Return the scrolled top position of this view. This is the top edge of 9637 * the displayed part of your view. You do not need to draw any pixels above 9638 * it, since those are outside of the frame of your view on screen. 9639 * 9640 * @return The top edge of the displayed part of your view, in pixels. 9641 */ 9642 public final int getScrollY() { 9643 return mScrollY; 9644 } 9645 9646 /** 9647 * Return the width of the your view. 9648 * 9649 * @return The width of your view, in pixels. 9650 */ 9651 @ViewDebug.ExportedProperty(category = "layout") 9652 public final int getWidth() { 9653 return mRight - mLeft; 9654 } 9655 9656 /** 9657 * Return the height of your view. 9658 * 9659 * @return The height of your view, in pixels. 9660 */ 9661 @ViewDebug.ExportedProperty(category = "layout") 9662 public final int getHeight() { 9663 return mBottom - mTop; 9664 } 9665 9666 /** 9667 * Return the visible drawing bounds of your view. Fills in the output 9668 * rectangle with the values from getScrollX(), getScrollY(), 9669 * getWidth(), and getHeight(). These bounds do not account for any 9670 * transformation properties currently set on the view, such as 9671 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9672 * 9673 * @param outRect The (scrolled) drawing bounds of the view. 9674 */ 9675 public void getDrawingRect(Rect outRect) { 9676 outRect.left = mScrollX; 9677 outRect.top = mScrollY; 9678 outRect.right = mScrollX + (mRight - mLeft); 9679 outRect.bottom = mScrollY + (mBottom - mTop); 9680 } 9681 9682 /** 9683 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9684 * raw width component (that is the result is masked by 9685 * {@link #MEASURED_SIZE_MASK}). 9686 * 9687 * @return The raw measured width of this view. 9688 */ 9689 public final int getMeasuredWidth() { 9690 return mMeasuredWidth & MEASURED_SIZE_MASK; 9691 } 9692 9693 /** 9694 * Return the full width measurement information for this view as computed 9695 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9696 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9697 * This should be used during measurement and layout calculations only. Use 9698 * {@link #getWidth()} to see how wide a view is after layout. 9699 * 9700 * @return The measured width of this view as a bit mask. 9701 */ 9702 public final int getMeasuredWidthAndState() { 9703 return mMeasuredWidth; 9704 } 9705 9706 /** 9707 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9708 * raw width component (that is the result is masked by 9709 * {@link #MEASURED_SIZE_MASK}). 9710 * 9711 * @return The raw measured height of this view. 9712 */ 9713 public final int getMeasuredHeight() { 9714 return mMeasuredHeight & MEASURED_SIZE_MASK; 9715 } 9716 9717 /** 9718 * Return the full height measurement information for this view as computed 9719 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9720 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9721 * This should be used during measurement and layout calculations only. Use 9722 * {@link #getHeight()} to see how wide a view is after layout. 9723 * 9724 * @return The measured width of this view as a bit mask. 9725 */ 9726 public final int getMeasuredHeightAndState() { 9727 return mMeasuredHeight; 9728 } 9729 9730 /** 9731 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9732 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9733 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9734 * and the height component is at the shifted bits 9735 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9736 */ 9737 public final int getMeasuredState() { 9738 return (mMeasuredWidth&MEASURED_STATE_MASK) 9739 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9740 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9741 } 9742 9743 /** 9744 * The transform matrix of this view, which is calculated based on the current 9745 * rotation, scale, and pivot properties. 9746 * 9747 * @see #getRotation() 9748 * @see #getScaleX() 9749 * @see #getScaleY() 9750 * @see #getPivotX() 9751 * @see #getPivotY() 9752 * @return The current transform matrix for the view 9753 */ 9754 public Matrix getMatrix() { 9755 ensureTransformationInfo(); 9756 final Matrix matrix = mTransformationInfo.mMatrix; 9757 mRenderNode.getMatrix(matrix); 9758 return matrix; 9759 } 9760 9761 /** 9762 * Returns true if the transform matrix is the identity matrix. 9763 * Recomputes the matrix if necessary. 9764 * 9765 * @return True if the transform matrix is the identity matrix, false otherwise. 9766 */ 9767 final boolean hasIdentityMatrix() { 9768 return mRenderNode.hasIdentityMatrix(); 9769 } 9770 9771 void ensureTransformationInfo() { 9772 if (mTransformationInfo == null) { 9773 mTransformationInfo = new TransformationInfo(); 9774 } 9775 } 9776 9777 /** 9778 * Utility method to retrieve the inverse of the current mMatrix property. 9779 * We cache the matrix to avoid recalculating it when transform properties 9780 * have not changed. 9781 * 9782 * @return The inverse of the current matrix of this view. 9783 */ 9784 final Matrix getInverseMatrix() { 9785 ensureTransformationInfo(); 9786 if (mTransformationInfo.mInverseMatrix == null) { 9787 mTransformationInfo.mInverseMatrix = new Matrix(); 9788 } 9789 final Matrix matrix = mTransformationInfo.mInverseMatrix; 9790 mRenderNode.getInverseMatrix(matrix); 9791 return matrix; 9792 } 9793 9794 /** 9795 * Gets the distance along the Z axis from the camera to this view. 9796 * 9797 * @see #setCameraDistance(float) 9798 * 9799 * @return The distance along the Z axis. 9800 */ 9801 public float getCameraDistance() { 9802 final float dpi = mResources.getDisplayMetrics().densityDpi; 9803 return -(mRenderNode.getCameraDistance() * dpi); 9804 } 9805 9806 /** 9807 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9808 * views are drawn) from the camera to this view. The camera's distance 9809 * affects 3D transformations, for instance rotations around the X and Y 9810 * axis. If the rotationX or rotationY properties are changed and this view is 9811 * large (more than half the size of the screen), it is recommended to always 9812 * use a camera distance that's greater than the height (X axis rotation) or 9813 * the width (Y axis rotation) of this view.</p> 9814 * 9815 * <p>The distance of the camera from the view plane can have an affect on the 9816 * perspective distortion of the view when it is rotated around the x or y axis. 9817 * For example, a large distance will result in a large viewing angle, and there 9818 * will not be much perspective distortion of the view as it rotates. A short 9819 * distance may cause much more perspective distortion upon rotation, and can 9820 * also result in some drawing artifacts if the rotated view ends up partially 9821 * behind the camera (which is why the recommendation is to use a distance at 9822 * least as far as the size of the view, if the view is to be rotated.)</p> 9823 * 9824 * <p>The distance is expressed in "depth pixels." The default distance depends 9825 * on the screen density. For instance, on a medium density display, the 9826 * default distance is 1280. On a high density display, the default distance 9827 * is 1920.</p> 9828 * 9829 * <p>If you want to specify a distance that leads to visually consistent 9830 * results across various densities, use the following formula:</p> 9831 * <pre> 9832 * float scale = context.getResources().getDisplayMetrics().density; 9833 * view.setCameraDistance(distance * scale); 9834 * </pre> 9835 * 9836 * <p>The density scale factor of a high density display is 1.5, 9837 * and 1920 = 1280 * 1.5.</p> 9838 * 9839 * @param distance The distance in "depth pixels", if negative the opposite 9840 * value is used 9841 * 9842 * @see #setRotationX(float) 9843 * @see #setRotationY(float) 9844 */ 9845 public void setCameraDistance(float distance) { 9846 final float dpi = mResources.getDisplayMetrics().densityDpi; 9847 9848 invalidateViewProperty(true, false); 9849 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 9850 invalidateViewProperty(false, false); 9851 9852 invalidateParentIfNeededAndWasQuickRejected(); 9853 } 9854 9855 /** 9856 * The degrees that the view is rotated around the pivot point. 9857 * 9858 * @see #setRotation(float) 9859 * @see #getPivotX() 9860 * @see #getPivotY() 9861 * 9862 * @return The degrees of rotation. 9863 */ 9864 @ViewDebug.ExportedProperty(category = "drawing") 9865 public float getRotation() { 9866 return mRenderNode.getRotation(); 9867 } 9868 9869 /** 9870 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9871 * result in clockwise rotation. 9872 * 9873 * @param rotation The degrees of rotation. 9874 * 9875 * @see #getRotation() 9876 * @see #getPivotX() 9877 * @see #getPivotY() 9878 * @see #setRotationX(float) 9879 * @see #setRotationY(float) 9880 * 9881 * @attr ref android.R.styleable#View_rotation 9882 */ 9883 public void setRotation(float rotation) { 9884 if (rotation != getRotation()) { 9885 // Double-invalidation is necessary to capture view's old and new areas 9886 invalidateViewProperty(true, false); 9887 mRenderNode.setRotation(rotation); 9888 invalidateViewProperty(false, true); 9889 9890 invalidateParentIfNeededAndWasQuickRejected(); 9891 notifySubtreeAccessibilityStateChangedIfNeeded(); 9892 } 9893 } 9894 9895 /** 9896 * The degrees that the view is rotated around the vertical axis through the pivot point. 9897 * 9898 * @see #getPivotX() 9899 * @see #getPivotY() 9900 * @see #setRotationY(float) 9901 * 9902 * @return The degrees of Y rotation. 9903 */ 9904 @ViewDebug.ExportedProperty(category = "drawing") 9905 public float getRotationY() { 9906 return mRenderNode.getRotationY(); 9907 } 9908 9909 /** 9910 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9911 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9912 * down the y axis. 9913 * 9914 * When rotating large views, it is recommended to adjust the camera distance 9915 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9916 * 9917 * @param rotationY The degrees of Y rotation. 9918 * 9919 * @see #getRotationY() 9920 * @see #getPivotX() 9921 * @see #getPivotY() 9922 * @see #setRotation(float) 9923 * @see #setRotationX(float) 9924 * @see #setCameraDistance(float) 9925 * 9926 * @attr ref android.R.styleable#View_rotationY 9927 */ 9928 public void setRotationY(float rotationY) { 9929 if (rotationY != getRotationY()) { 9930 invalidateViewProperty(true, false); 9931 mRenderNode.setRotationY(rotationY); 9932 invalidateViewProperty(false, true); 9933 9934 invalidateParentIfNeededAndWasQuickRejected(); 9935 notifySubtreeAccessibilityStateChangedIfNeeded(); 9936 } 9937 } 9938 9939 /** 9940 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9941 * 9942 * @see #getPivotX() 9943 * @see #getPivotY() 9944 * @see #setRotationX(float) 9945 * 9946 * @return The degrees of X rotation. 9947 */ 9948 @ViewDebug.ExportedProperty(category = "drawing") 9949 public float getRotationX() { 9950 return mRenderNode.getRotationX(); 9951 } 9952 9953 /** 9954 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9955 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9956 * x axis. 9957 * 9958 * When rotating large views, it is recommended to adjust the camera distance 9959 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9960 * 9961 * @param rotationX The degrees of X rotation. 9962 * 9963 * @see #getRotationX() 9964 * @see #getPivotX() 9965 * @see #getPivotY() 9966 * @see #setRotation(float) 9967 * @see #setRotationY(float) 9968 * @see #setCameraDistance(float) 9969 * 9970 * @attr ref android.R.styleable#View_rotationX 9971 */ 9972 public void setRotationX(float rotationX) { 9973 if (rotationX != getRotationX()) { 9974 invalidateViewProperty(true, false); 9975 mRenderNode.setRotationX(rotationX); 9976 invalidateViewProperty(false, true); 9977 9978 invalidateParentIfNeededAndWasQuickRejected(); 9979 notifySubtreeAccessibilityStateChangedIfNeeded(); 9980 } 9981 } 9982 9983 /** 9984 * The amount that the view is scaled in x around the pivot point, as a proportion of 9985 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9986 * 9987 * <p>By default, this is 1.0f. 9988 * 9989 * @see #getPivotX() 9990 * @see #getPivotY() 9991 * @return The scaling factor. 9992 */ 9993 @ViewDebug.ExportedProperty(category = "drawing") 9994 public float getScaleX() { 9995 return mRenderNode.getScaleX(); 9996 } 9997 9998 /** 9999 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 10000 * the view's unscaled width. A value of 1 means that no scaling is applied. 10001 * 10002 * @param scaleX The scaling factor. 10003 * @see #getPivotX() 10004 * @see #getPivotY() 10005 * 10006 * @attr ref android.R.styleable#View_scaleX 10007 */ 10008 public void setScaleX(float scaleX) { 10009 if (scaleX != getScaleX()) { 10010 invalidateViewProperty(true, false); 10011 mRenderNode.setScaleX(scaleX); 10012 invalidateViewProperty(false, true); 10013 10014 invalidateParentIfNeededAndWasQuickRejected(); 10015 notifySubtreeAccessibilityStateChangedIfNeeded(); 10016 } 10017 } 10018 10019 /** 10020 * The amount that the view is scaled in y around the pivot point, as a proportion of 10021 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 10022 * 10023 * <p>By default, this is 1.0f. 10024 * 10025 * @see #getPivotX() 10026 * @see #getPivotY() 10027 * @return The scaling factor. 10028 */ 10029 @ViewDebug.ExportedProperty(category = "drawing") 10030 public float getScaleY() { 10031 return mRenderNode.getScaleY(); 10032 } 10033 10034 /** 10035 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 10036 * the view's unscaled width. A value of 1 means that no scaling is applied. 10037 * 10038 * @param scaleY The scaling factor. 10039 * @see #getPivotX() 10040 * @see #getPivotY() 10041 * 10042 * @attr ref android.R.styleable#View_scaleY 10043 */ 10044 public void setScaleY(float scaleY) { 10045 if (scaleY != getScaleY()) { 10046 invalidateViewProperty(true, false); 10047 mRenderNode.setScaleY(scaleY); 10048 invalidateViewProperty(false, true); 10049 10050 invalidateParentIfNeededAndWasQuickRejected(); 10051 notifySubtreeAccessibilityStateChangedIfNeeded(); 10052 } 10053 } 10054 10055 /** 10056 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10057 * and {@link #setScaleX(float) scaled}. 10058 * 10059 * @see #getRotation() 10060 * @see #getScaleX() 10061 * @see #getScaleY() 10062 * @see #getPivotY() 10063 * @return The x location of the pivot point. 10064 * 10065 * @attr ref android.R.styleable#View_transformPivotX 10066 */ 10067 @ViewDebug.ExportedProperty(category = "drawing") 10068 public float getPivotX() { 10069 return mRenderNode.getPivotX(); 10070 } 10071 10072 /** 10073 * Sets the x location of the point around which the view is 10074 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10075 * By default, the pivot point is centered on the object. 10076 * Setting this property disables this behavior and causes the view to use only the 10077 * explicitly set pivotX and pivotY values. 10078 * 10079 * @param pivotX The x location of the pivot point. 10080 * @see #getRotation() 10081 * @see #getScaleX() 10082 * @see #getScaleY() 10083 * @see #getPivotY() 10084 * 10085 * @attr ref android.R.styleable#View_transformPivotX 10086 */ 10087 public void setPivotX(float pivotX) { 10088 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10089 invalidateViewProperty(true, false); 10090 mRenderNode.setPivotX(pivotX); 10091 invalidateViewProperty(false, true); 10092 10093 invalidateParentIfNeededAndWasQuickRejected(); 10094 } 10095 } 10096 10097 /** 10098 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10099 * and {@link #setScaleY(float) scaled}. 10100 * 10101 * @see #getRotation() 10102 * @see #getScaleX() 10103 * @see #getScaleY() 10104 * @see #getPivotY() 10105 * @return The y location of the pivot point. 10106 * 10107 * @attr ref android.R.styleable#View_transformPivotY 10108 */ 10109 @ViewDebug.ExportedProperty(category = "drawing") 10110 public float getPivotY() { 10111 return mRenderNode.getPivotY(); 10112 } 10113 10114 /** 10115 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10116 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10117 * Setting this property disables this behavior and causes the view to use only the 10118 * explicitly set pivotX and pivotY values. 10119 * 10120 * @param pivotY The y location of the pivot point. 10121 * @see #getRotation() 10122 * @see #getScaleX() 10123 * @see #getScaleY() 10124 * @see #getPivotY() 10125 * 10126 * @attr ref android.R.styleable#View_transformPivotY 10127 */ 10128 public void setPivotY(float pivotY) { 10129 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10130 invalidateViewProperty(true, false); 10131 mRenderNode.setPivotY(pivotY); 10132 invalidateViewProperty(false, true); 10133 10134 invalidateParentIfNeededAndWasQuickRejected(); 10135 } 10136 } 10137 10138 /** 10139 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10140 * completely transparent and 1 means the view is completely opaque. 10141 * 10142 * <p>By default this is 1.0f. 10143 * @return The opacity of the view. 10144 */ 10145 @ViewDebug.ExportedProperty(category = "drawing") 10146 public float getAlpha() { 10147 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10148 } 10149 10150 /** 10151 * Returns whether this View has content which overlaps. 10152 * 10153 * <p>This function, intended to be overridden by specific View types, is an optimization when 10154 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10155 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10156 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10157 * directly. An example of overlapping rendering is a TextView with a background image, such as 10158 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10159 * ImageView with only the foreground image. The default implementation returns true; subclasses 10160 * should override if they have cases which can be optimized.</p> 10161 * 10162 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10163 * necessitates that a View return true if it uses the methods internally without passing the 10164 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10165 * 10166 * @return true if the content in this view might overlap, false otherwise. 10167 */ 10168 public boolean hasOverlappingRendering() { 10169 return true; 10170 } 10171 10172 /** 10173 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10174 * completely transparent and 1 means the view is completely opaque.</p> 10175 * 10176 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10177 * performance implications, especially for large views. It is best to use the alpha property 10178 * sparingly and transiently, as in the case of fading animations.</p> 10179 * 10180 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10181 * strongly recommended for performance reasons to either override 10182 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10183 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10184 * 10185 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10186 * responsible for applying the opacity itself.</p> 10187 * 10188 * <p>Note that if the view is backed by a 10189 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10190 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10191 * 1.0 will supercede the alpha of the layer paint.</p> 10192 * 10193 * @param alpha The opacity of the view. 10194 * 10195 * @see #hasOverlappingRendering() 10196 * @see #setLayerType(int, android.graphics.Paint) 10197 * 10198 * @attr ref android.R.styleable#View_alpha 10199 */ 10200 public void setAlpha(float alpha) { 10201 ensureTransformationInfo(); 10202 if (mTransformationInfo.mAlpha != alpha) { 10203 mTransformationInfo.mAlpha = alpha; 10204 if (onSetAlpha((int) (alpha * 255))) { 10205 mPrivateFlags |= PFLAG_ALPHA_SET; 10206 // subclass is handling alpha - don't optimize rendering cache invalidation 10207 invalidateParentCaches(); 10208 invalidate(true); 10209 } else { 10210 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10211 invalidateViewProperty(true, false); 10212 mRenderNode.setAlpha(getFinalAlpha()); 10213 notifyViewAccessibilityStateChangedIfNeeded( 10214 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10215 } 10216 } 10217 } 10218 10219 /** 10220 * Faster version of setAlpha() which performs the same steps except there are 10221 * no calls to invalidate(). The caller of this function should perform proper invalidation 10222 * on the parent and this object. The return value indicates whether the subclass handles 10223 * alpha (the return value for onSetAlpha()). 10224 * 10225 * @param alpha The new value for the alpha property 10226 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10227 * the new value for the alpha property is different from the old value 10228 */ 10229 boolean setAlphaNoInvalidation(float alpha) { 10230 ensureTransformationInfo(); 10231 if (mTransformationInfo.mAlpha != alpha) { 10232 mTransformationInfo.mAlpha = alpha; 10233 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10234 if (subclassHandlesAlpha) { 10235 mPrivateFlags |= PFLAG_ALPHA_SET; 10236 return true; 10237 } else { 10238 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10239 mRenderNode.setAlpha(getFinalAlpha()); 10240 } 10241 } 10242 return false; 10243 } 10244 10245 /** 10246 * This property is hidden and intended only for use by the Fade transition, which 10247 * animates it to produce a visual translucency that does not side-effect (or get 10248 * affected by) the real alpha property. This value is composited with the other 10249 * alpha value (and the AlphaAnimation value, when that is present) to produce 10250 * a final visual translucency result, which is what is passed into the DisplayList. 10251 * 10252 * @hide 10253 */ 10254 public void setTransitionAlpha(float alpha) { 10255 ensureTransformationInfo(); 10256 if (mTransformationInfo.mTransitionAlpha != alpha) { 10257 mTransformationInfo.mTransitionAlpha = alpha; 10258 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10259 invalidateViewProperty(true, false); 10260 mRenderNode.setAlpha(getFinalAlpha()); 10261 } 10262 } 10263 10264 /** 10265 * Calculates the visual alpha of this view, which is a combination of the actual 10266 * alpha value and the transitionAlpha value (if set). 10267 */ 10268 private float getFinalAlpha() { 10269 if (mTransformationInfo != null) { 10270 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10271 } 10272 return 1; 10273 } 10274 10275 /** 10276 * This property is hidden and intended only for use by the Fade transition, which 10277 * animates it to produce a visual translucency that does not side-effect (or get 10278 * affected by) the real alpha property. This value is composited with the other 10279 * alpha value (and the AlphaAnimation value, when that is present) to produce 10280 * a final visual translucency result, which is what is passed into the DisplayList. 10281 * 10282 * @hide 10283 */ 10284 public float getTransitionAlpha() { 10285 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10286 } 10287 10288 /** 10289 * Top position of this view relative to its parent. 10290 * 10291 * @return The top of this view, in pixels. 10292 */ 10293 @ViewDebug.CapturedViewProperty 10294 public final int getTop() { 10295 return mTop; 10296 } 10297 10298 /** 10299 * Sets the top position of this view relative to its parent. This method is meant to be called 10300 * by the layout system and should not generally be called otherwise, because the property 10301 * may be changed at any time by the layout. 10302 * 10303 * @param top The top of this view, in pixels. 10304 */ 10305 public final void setTop(int top) { 10306 if (top != mTop) { 10307 final boolean matrixIsIdentity = hasIdentityMatrix(); 10308 if (matrixIsIdentity) { 10309 if (mAttachInfo != null) { 10310 int minTop; 10311 int yLoc; 10312 if (top < mTop) { 10313 minTop = top; 10314 yLoc = top - mTop; 10315 } else { 10316 minTop = mTop; 10317 yLoc = 0; 10318 } 10319 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10320 } 10321 } else { 10322 // Double-invalidation is necessary to capture view's old and new areas 10323 invalidate(true); 10324 } 10325 10326 int width = mRight - mLeft; 10327 int oldHeight = mBottom - mTop; 10328 10329 mTop = top; 10330 mRenderNode.setTop(mTop); 10331 10332 sizeChange(width, mBottom - mTop, width, oldHeight); 10333 10334 if (!matrixIsIdentity) { 10335 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10336 invalidate(true); 10337 } 10338 mBackgroundSizeChanged = true; 10339 invalidateParentIfNeeded(); 10340 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10341 // View was rejected last time it was drawn by its parent; this may have changed 10342 invalidateParentIfNeeded(); 10343 } 10344 } 10345 } 10346 10347 /** 10348 * Bottom position of this view relative to its parent. 10349 * 10350 * @return The bottom of this view, in pixels. 10351 */ 10352 @ViewDebug.CapturedViewProperty 10353 public final int getBottom() { 10354 return mBottom; 10355 } 10356 10357 /** 10358 * True if this view has changed since the last time being drawn. 10359 * 10360 * @return The dirty state of this view. 10361 */ 10362 public boolean isDirty() { 10363 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10364 } 10365 10366 /** 10367 * Sets the bottom position of this view relative to its parent. This method is meant to be 10368 * called by the layout system and should not generally be called otherwise, because the 10369 * property may be changed at any time by the layout. 10370 * 10371 * @param bottom The bottom of this view, in pixels. 10372 */ 10373 public final void setBottom(int bottom) { 10374 if (bottom != mBottom) { 10375 final boolean matrixIsIdentity = hasIdentityMatrix(); 10376 if (matrixIsIdentity) { 10377 if (mAttachInfo != null) { 10378 int maxBottom; 10379 if (bottom < mBottom) { 10380 maxBottom = mBottom; 10381 } else { 10382 maxBottom = bottom; 10383 } 10384 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10385 } 10386 } else { 10387 // Double-invalidation is necessary to capture view's old and new areas 10388 invalidate(true); 10389 } 10390 10391 int width = mRight - mLeft; 10392 int oldHeight = mBottom - mTop; 10393 10394 mBottom = bottom; 10395 mRenderNode.setBottom(mBottom); 10396 10397 sizeChange(width, mBottom - mTop, width, oldHeight); 10398 10399 if (!matrixIsIdentity) { 10400 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10401 invalidate(true); 10402 } 10403 mBackgroundSizeChanged = true; 10404 invalidateParentIfNeeded(); 10405 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10406 // View was rejected last time it was drawn by its parent; this may have changed 10407 invalidateParentIfNeeded(); 10408 } 10409 } 10410 } 10411 10412 /** 10413 * Left position of this view relative to its parent. 10414 * 10415 * @return The left edge of this view, in pixels. 10416 */ 10417 @ViewDebug.CapturedViewProperty 10418 public final int getLeft() { 10419 return mLeft; 10420 } 10421 10422 /** 10423 * Sets the left position of this view relative to its parent. This method is meant to be called 10424 * by the layout system and should not generally be called otherwise, because the property 10425 * may be changed at any time by the layout. 10426 * 10427 * @param left The left of this view, in pixels. 10428 */ 10429 public final void setLeft(int left) { 10430 if (left != mLeft) { 10431 final boolean matrixIsIdentity = hasIdentityMatrix(); 10432 if (matrixIsIdentity) { 10433 if (mAttachInfo != null) { 10434 int minLeft; 10435 int xLoc; 10436 if (left < mLeft) { 10437 minLeft = left; 10438 xLoc = left - mLeft; 10439 } else { 10440 minLeft = mLeft; 10441 xLoc = 0; 10442 } 10443 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10444 } 10445 } else { 10446 // Double-invalidation is necessary to capture view's old and new areas 10447 invalidate(true); 10448 } 10449 10450 int oldWidth = mRight - mLeft; 10451 int height = mBottom - mTop; 10452 10453 mLeft = left; 10454 mRenderNode.setLeft(left); 10455 10456 sizeChange(mRight - mLeft, height, oldWidth, height); 10457 10458 if (!matrixIsIdentity) { 10459 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10460 invalidate(true); 10461 } 10462 mBackgroundSizeChanged = true; 10463 invalidateParentIfNeeded(); 10464 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10465 // View was rejected last time it was drawn by its parent; this may have changed 10466 invalidateParentIfNeeded(); 10467 } 10468 } 10469 } 10470 10471 /** 10472 * Right position of this view relative to its parent. 10473 * 10474 * @return The right edge of this view, in pixels. 10475 */ 10476 @ViewDebug.CapturedViewProperty 10477 public final int getRight() { 10478 return mRight; 10479 } 10480 10481 /** 10482 * Sets the right position of this view relative to its parent. This method is meant to be called 10483 * by the layout system and should not generally be called otherwise, because the property 10484 * may be changed at any time by the layout. 10485 * 10486 * @param right The right of this view, in pixels. 10487 */ 10488 public final void setRight(int right) { 10489 if (right != mRight) { 10490 final boolean matrixIsIdentity = hasIdentityMatrix(); 10491 if (matrixIsIdentity) { 10492 if (mAttachInfo != null) { 10493 int maxRight; 10494 if (right < mRight) { 10495 maxRight = mRight; 10496 } else { 10497 maxRight = right; 10498 } 10499 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10500 } 10501 } else { 10502 // Double-invalidation is necessary to capture view's old and new areas 10503 invalidate(true); 10504 } 10505 10506 int oldWidth = mRight - mLeft; 10507 int height = mBottom - mTop; 10508 10509 mRight = right; 10510 mRenderNode.setRight(mRight); 10511 10512 sizeChange(mRight - mLeft, height, oldWidth, height); 10513 10514 if (!matrixIsIdentity) { 10515 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10516 invalidate(true); 10517 } 10518 mBackgroundSizeChanged = true; 10519 invalidateParentIfNeeded(); 10520 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10521 // View was rejected last time it was drawn by its parent; this may have changed 10522 invalidateParentIfNeeded(); 10523 } 10524 } 10525 } 10526 10527 /** 10528 * The visual x position of this view, in pixels. This is equivalent to the 10529 * {@link #setTranslationX(float) translationX} property plus the current 10530 * {@link #getLeft() left} property. 10531 * 10532 * @return The visual x position of this view, in pixels. 10533 */ 10534 @ViewDebug.ExportedProperty(category = "drawing") 10535 public float getX() { 10536 return mLeft + getTranslationX(); 10537 } 10538 10539 /** 10540 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10541 * {@link #setTranslationX(float) translationX} property to be the difference between 10542 * the x value passed in and the current {@link #getLeft() left} property. 10543 * 10544 * @param x The visual x position of this view, in pixels. 10545 */ 10546 public void setX(float x) { 10547 setTranslationX(x - mLeft); 10548 } 10549 10550 /** 10551 * The visual y position of this view, in pixels. This is equivalent to the 10552 * {@link #setTranslationY(float) translationY} property plus the current 10553 * {@link #getTop() top} property. 10554 * 10555 * @return The visual y position of this view, in pixels. 10556 */ 10557 @ViewDebug.ExportedProperty(category = "drawing") 10558 public float getY() { 10559 return mTop + getTranslationY(); 10560 } 10561 10562 /** 10563 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10564 * {@link #setTranslationY(float) translationY} property to be the difference between 10565 * the y value passed in and the current {@link #getTop() top} property. 10566 * 10567 * @param y The visual y position of this view, in pixels. 10568 */ 10569 public void setY(float y) { 10570 setTranslationY(y - mTop); 10571 } 10572 10573 /** 10574 * The visual z position of this view, in pixels. This is equivalent to the 10575 * {@link #setTranslationZ(float) translationZ} property plus the current 10576 * {@link #getElevation() elevation} property. 10577 * 10578 * @return The visual z position of this view, in pixels. 10579 */ 10580 @ViewDebug.ExportedProperty(category = "drawing") 10581 public float getZ() { 10582 return getElevation() + getTranslationZ(); 10583 } 10584 10585 /** 10586 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10587 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10588 * the x value passed in and the current {@link #getElevation() elevation} property. 10589 * 10590 * @param z The visual z position of this view, in pixels. 10591 */ 10592 public void setZ(float z) { 10593 setTranslationZ(z - getElevation()); 10594 } 10595 10596 /** 10597 * The base elevation of this view relative to its parent, in pixels. 10598 * 10599 * @return The base depth position of the view, in pixels. 10600 */ 10601 @ViewDebug.ExportedProperty(category = "drawing") 10602 public float getElevation() { 10603 return mRenderNode.getElevation(); 10604 } 10605 10606 /** 10607 * Sets the base elevation of this view, in pixels. 10608 * 10609 * @attr ref android.R.styleable#View_elevation 10610 */ 10611 public void setElevation(float elevation) { 10612 if (elevation != getElevation()) { 10613 invalidateViewProperty(true, false); 10614 mRenderNode.setElevation(elevation); 10615 invalidateViewProperty(false, true); 10616 10617 invalidateParentIfNeededAndWasQuickRejected(); 10618 } 10619 } 10620 10621 /** 10622 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10623 * This position is post-layout, in addition to wherever the object's 10624 * layout placed it. 10625 * 10626 * @return The horizontal position of this view relative to its left position, in pixels. 10627 */ 10628 @ViewDebug.ExportedProperty(category = "drawing") 10629 public float getTranslationX() { 10630 return mRenderNode.getTranslationX(); 10631 } 10632 10633 /** 10634 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10635 * This effectively positions the object post-layout, in addition to wherever the object's 10636 * layout placed it. 10637 * 10638 * @param translationX The horizontal position of this view relative to its left position, 10639 * in pixels. 10640 * 10641 * @attr ref android.R.styleable#View_translationX 10642 */ 10643 public void setTranslationX(float translationX) { 10644 if (translationX != getTranslationX()) { 10645 invalidateViewProperty(true, false); 10646 mRenderNode.setTranslationX(translationX); 10647 invalidateViewProperty(false, true); 10648 10649 invalidateParentIfNeededAndWasQuickRejected(); 10650 notifySubtreeAccessibilityStateChangedIfNeeded(); 10651 } 10652 } 10653 10654 /** 10655 * The vertical location of this view relative to its {@link #getTop() top} position. 10656 * This position is post-layout, in addition to wherever the object's 10657 * layout placed it. 10658 * 10659 * @return The vertical position of this view relative to its top position, 10660 * in pixels. 10661 */ 10662 @ViewDebug.ExportedProperty(category = "drawing") 10663 public float getTranslationY() { 10664 return mRenderNode.getTranslationY(); 10665 } 10666 10667 /** 10668 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10669 * This effectively positions the object post-layout, in addition to wherever the object's 10670 * layout placed it. 10671 * 10672 * @param translationY The vertical position of this view relative to its top position, 10673 * in pixels. 10674 * 10675 * @attr ref android.R.styleable#View_translationY 10676 */ 10677 public void setTranslationY(float translationY) { 10678 if (translationY != getTranslationY()) { 10679 invalidateViewProperty(true, false); 10680 mRenderNode.setTranslationY(translationY); 10681 invalidateViewProperty(false, true); 10682 10683 invalidateParentIfNeededAndWasQuickRejected(); 10684 } 10685 } 10686 10687 /** 10688 * The depth location of this view relative to its {@link #getElevation() elevation}. 10689 * 10690 * @return The depth of this view relative to its elevation. 10691 */ 10692 @ViewDebug.ExportedProperty(category = "drawing") 10693 public float getTranslationZ() { 10694 return mRenderNode.getTranslationZ(); 10695 } 10696 10697 /** 10698 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 10699 * 10700 * @attr ref android.R.styleable#View_translationZ 10701 */ 10702 public void setTranslationZ(float translationZ) { 10703 if (translationZ != getTranslationZ()) { 10704 invalidateViewProperty(true, false); 10705 mRenderNode.setTranslationZ(translationZ); 10706 invalidateViewProperty(false, true); 10707 10708 invalidateParentIfNeededAndWasQuickRejected(); 10709 } 10710 } 10711 10712 /** 10713 * Returns a ValueAnimator which can animate a clearing circle. 10714 * <p> 10715 * The View is prevented from drawing within the circle, so the content 10716 * behind the View shows through. 10717 * 10718 * @param centerX The x coordinate of the center of the animating circle. 10719 * @param centerY The y coordinate of the center of the animating circle. 10720 * @param startRadius The starting radius of the animating circle. 10721 * @param endRadius The ending radius of the animating circle. 10722 * 10723 * @hide 10724 */ 10725 public final ValueAnimator createClearCircleAnimator(int centerX, int centerY, 10726 float startRadius, float endRadius) { 10727 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10728 startRadius, endRadius, true); 10729 } 10730 10731 /** 10732 * Returns the current StateListAnimator if exists. 10733 * 10734 * @return StateListAnimator or null if it does not exists 10735 * @see #setStateListAnimator(android.animation.StateListAnimator) 10736 */ 10737 public StateListAnimator getStateListAnimator() { 10738 return mStateListAnimator; 10739 } 10740 10741 /** 10742 * Attaches the provided StateListAnimator to this View. 10743 * <p> 10744 * Any previously attached StateListAnimator will be detached. 10745 * 10746 * @param stateListAnimator The StateListAnimator to update the view 10747 * @see {@link android.animation.StateListAnimator} 10748 */ 10749 public void setStateListAnimator(StateListAnimator stateListAnimator) { 10750 if (mStateListAnimator == stateListAnimator) { 10751 return; 10752 } 10753 if (mStateListAnimator != null) { 10754 mStateListAnimator.setTarget(null); 10755 } 10756 mStateListAnimator = stateListAnimator; 10757 if (stateListAnimator != null) { 10758 stateListAnimator.setTarget(this); 10759 if (isAttachedToWindow()) { 10760 stateListAnimator.setState(getDrawableState()); 10761 } 10762 } 10763 } 10764 10765 /** Deprecated, pending removal */ 10766 @Deprecated 10767 public void setOutline(@Nullable Outline outline) {} 10768 10769 /** 10770 * Returns whether the Outline should be used to clip the contents of the View. 10771 * <p> 10772 * Note that this flag will only be respected if the View's Outline returns true from 10773 * {@link Outline#canClip()}. 10774 * 10775 * @see #setOutlineProvider(ViewOutlineProvider) 10776 * @see #setClipToOutline(boolean) 10777 */ 10778 public final boolean getClipToOutline() { 10779 return mRenderNode.getClipToOutline(); 10780 } 10781 10782 /** 10783 * Sets whether the View's Outline should be used to clip the contents of the View. 10784 * <p> 10785 * Note that this flag will only be respected if the View's Outline returns true from 10786 * {@link Outline#canClip()}. 10787 * 10788 * @see #setOutlineProvider(ViewOutlineProvider) 10789 * @see #getClipToOutline() 10790 */ 10791 public void setClipToOutline(boolean clipToOutline) { 10792 damageInParent(); 10793 if (getClipToOutline() != clipToOutline) { 10794 mRenderNode.setClipToOutline(clipToOutline); 10795 } 10796 } 10797 10798 /** 10799 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 10800 * the shape of the shadow it casts, and enables outline clipping. 10801 * <p> 10802 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 10803 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 10804 * outline provider with this method allows this behavior to be overridden. 10805 * <p> 10806 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 10807 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 10808 * <p> 10809 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 10810 * 10811 * @see #setClipToOutline(boolean) 10812 * @see #getClipToOutline() 10813 * @see #getOutlineProvider() 10814 */ 10815 public void setOutlineProvider(ViewOutlineProvider provider) { 10816 mOutlineProvider = provider; 10817 invalidateOutline(); 10818 } 10819 10820 /** 10821 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 10822 * that defines the shape of the shadow it casts, and enables outline clipping. 10823 * 10824 * @see #setOutlineProvider(ViewOutlineProvider) 10825 */ 10826 public ViewOutlineProvider getOutlineProvider() { 10827 return mOutlineProvider; 10828 } 10829 10830 /** 10831 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 10832 * 10833 * @see #setOutlineProvider(ViewOutlineProvider) 10834 */ 10835 public void invalidateOutline() { 10836 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 10837 if (mAttachInfo == null) return; 10838 10839 final Outline outline = mAttachInfo.mTmpOutline; 10840 outline.setEmpty(); 10841 10842 if (mOutlineProvider == null) { 10843 // no provider, remove outline 10844 mRenderNode.setOutline(null); 10845 } else { 10846 if (mOutlineProvider.getOutline(this, outline)) { 10847 if (outline.isEmpty()) { 10848 throw new IllegalStateException("Outline provider failed to build outline"); 10849 } 10850 // provider has provided 10851 mRenderNode.setOutline(outline); 10852 } else { 10853 // provider failed to provide 10854 mRenderNode.setOutline(null); 10855 } 10856 } 10857 10858 notifySubtreeAccessibilityStateChangedIfNeeded(); 10859 invalidateViewProperty(false, false); 10860 } 10861 10862 /** 10863 * Private API to be used for reveal animation 10864 * 10865 * @hide 10866 */ 10867 public void setRevealClip(boolean shouldClip, boolean inverseClip, 10868 float x, float y, float radius) { 10869 mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius); 10870 // TODO: Handle this invalidate in a better way, or purely in native. 10871 invalidate(); 10872 } 10873 10874 /** 10875 * Hit rectangle in parent's coordinates 10876 * 10877 * @param outRect The hit rectangle of the view. 10878 */ 10879 public void getHitRect(Rect outRect) { 10880 if (hasIdentityMatrix() || mAttachInfo == null) { 10881 outRect.set(mLeft, mTop, mRight, mBottom); 10882 } else { 10883 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10884 tmpRect.set(0, 0, getWidth(), getHeight()); 10885 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 10886 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10887 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10888 } 10889 } 10890 10891 /** 10892 * Determines whether the given point, in local coordinates is inside the view. 10893 */ 10894 /*package*/ final boolean pointInView(float localX, float localY) { 10895 return localX >= 0 && localX < (mRight - mLeft) 10896 && localY >= 0 && localY < (mBottom - mTop); 10897 } 10898 10899 /** 10900 * Utility method to determine whether the given point, in local coordinates, 10901 * is inside the view, where the area of the view is expanded by the slop factor. 10902 * This method is called while processing touch-move events to determine if the event 10903 * is still within the view. 10904 * 10905 * @hide 10906 */ 10907 public boolean pointInView(float localX, float localY, float slop) { 10908 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10909 localY < ((mBottom - mTop) + slop); 10910 } 10911 10912 /** 10913 * When a view has focus and the user navigates away from it, the next view is searched for 10914 * starting from the rectangle filled in by this method. 10915 * 10916 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10917 * of the view. However, if your view maintains some idea of internal selection, 10918 * such as a cursor, or a selected row or column, you should override this method and 10919 * fill in a more specific rectangle. 10920 * 10921 * @param r The rectangle to fill in, in this view's coordinates. 10922 */ 10923 public void getFocusedRect(Rect r) { 10924 getDrawingRect(r); 10925 } 10926 10927 /** 10928 * If some part of this view is not clipped by any of its parents, then 10929 * return that area in r in global (root) coordinates. To convert r to local 10930 * coordinates (without taking possible View rotations into account), offset 10931 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10932 * If the view is completely clipped or translated out, return false. 10933 * 10934 * @param r If true is returned, r holds the global coordinates of the 10935 * visible portion of this view. 10936 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10937 * between this view and its root. globalOffet may be null. 10938 * @return true if r is non-empty (i.e. part of the view is visible at the 10939 * root level. 10940 */ 10941 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10942 int width = mRight - mLeft; 10943 int height = mBottom - mTop; 10944 if (width > 0 && height > 0) { 10945 r.set(0, 0, width, height); 10946 if (globalOffset != null) { 10947 globalOffset.set(-mScrollX, -mScrollY); 10948 } 10949 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10950 } 10951 return false; 10952 } 10953 10954 public final boolean getGlobalVisibleRect(Rect r) { 10955 return getGlobalVisibleRect(r, null); 10956 } 10957 10958 public final boolean getLocalVisibleRect(Rect r) { 10959 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10960 if (getGlobalVisibleRect(r, offset)) { 10961 r.offset(-offset.x, -offset.y); // make r local 10962 return true; 10963 } 10964 return false; 10965 } 10966 10967 /** 10968 * Offset this view's vertical location by the specified number of pixels. 10969 * 10970 * @param offset the number of pixels to offset the view by 10971 */ 10972 public void offsetTopAndBottom(int offset) { 10973 if (offset != 0) { 10974 final boolean matrixIsIdentity = hasIdentityMatrix(); 10975 if (matrixIsIdentity) { 10976 if (isHardwareAccelerated()) { 10977 invalidateViewProperty(false, false); 10978 } else { 10979 final ViewParent p = mParent; 10980 if (p != null && mAttachInfo != null) { 10981 final Rect r = mAttachInfo.mTmpInvalRect; 10982 int minTop; 10983 int maxBottom; 10984 int yLoc; 10985 if (offset < 0) { 10986 minTop = mTop + offset; 10987 maxBottom = mBottom; 10988 yLoc = offset; 10989 } else { 10990 minTop = mTop; 10991 maxBottom = mBottom + offset; 10992 yLoc = 0; 10993 } 10994 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10995 p.invalidateChild(this, r); 10996 } 10997 } 10998 } else { 10999 invalidateViewProperty(false, false); 11000 } 11001 11002 mTop += offset; 11003 mBottom += offset; 11004 mRenderNode.offsetTopAndBottom(offset); 11005 if (isHardwareAccelerated()) { 11006 invalidateViewProperty(false, false); 11007 } else { 11008 if (!matrixIsIdentity) { 11009 invalidateViewProperty(false, true); 11010 } 11011 invalidateParentIfNeeded(); 11012 } 11013 notifySubtreeAccessibilityStateChangedIfNeeded(); 11014 } 11015 } 11016 11017 /** 11018 * Offset this view's horizontal location by the specified amount of pixels. 11019 * 11020 * @param offset the number of pixels to offset the view by 11021 */ 11022 public void offsetLeftAndRight(int offset) { 11023 if (offset != 0) { 11024 final boolean matrixIsIdentity = hasIdentityMatrix(); 11025 if (matrixIsIdentity) { 11026 if (isHardwareAccelerated()) { 11027 invalidateViewProperty(false, false); 11028 } else { 11029 final ViewParent p = mParent; 11030 if (p != null && mAttachInfo != null) { 11031 final Rect r = mAttachInfo.mTmpInvalRect; 11032 int minLeft; 11033 int maxRight; 11034 if (offset < 0) { 11035 minLeft = mLeft + offset; 11036 maxRight = mRight; 11037 } else { 11038 minLeft = mLeft; 11039 maxRight = mRight + offset; 11040 } 11041 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 11042 p.invalidateChild(this, r); 11043 } 11044 } 11045 } else { 11046 invalidateViewProperty(false, false); 11047 } 11048 11049 mLeft += offset; 11050 mRight += offset; 11051 mRenderNode.offsetLeftAndRight(offset); 11052 if (isHardwareAccelerated()) { 11053 invalidateViewProperty(false, false); 11054 } else { 11055 if (!matrixIsIdentity) { 11056 invalidateViewProperty(false, true); 11057 } 11058 invalidateParentIfNeeded(); 11059 } 11060 notifySubtreeAccessibilityStateChangedIfNeeded(); 11061 } 11062 } 11063 11064 /** 11065 * Get the LayoutParams associated with this view. All views should have 11066 * layout parameters. These supply parameters to the <i>parent</i> of this 11067 * view specifying how it should be arranged. There are many subclasses of 11068 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11069 * of ViewGroup that are responsible for arranging their children. 11070 * 11071 * This method may return null if this View is not attached to a parent 11072 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11073 * was not invoked successfully. When a View is attached to a parent 11074 * ViewGroup, this method must not return null. 11075 * 11076 * @return The LayoutParams associated with this view, or null if no 11077 * parameters have been set yet 11078 */ 11079 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11080 public ViewGroup.LayoutParams getLayoutParams() { 11081 return mLayoutParams; 11082 } 11083 11084 /** 11085 * Set the layout parameters associated with this view. These supply 11086 * parameters to the <i>parent</i> of this view specifying how it should be 11087 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11088 * correspond to the different subclasses of ViewGroup that are responsible 11089 * for arranging their children. 11090 * 11091 * @param params The layout parameters for this view, cannot be null 11092 */ 11093 public void setLayoutParams(ViewGroup.LayoutParams params) { 11094 if (params == null) { 11095 throw new NullPointerException("Layout parameters cannot be null"); 11096 } 11097 mLayoutParams = params; 11098 resolveLayoutParams(); 11099 if (mParent instanceof ViewGroup) { 11100 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11101 } 11102 requestLayout(); 11103 } 11104 11105 /** 11106 * Resolve the layout parameters depending on the resolved layout direction 11107 * 11108 * @hide 11109 */ 11110 public void resolveLayoutParams() { 11111 if (mLayoutParams != null) { 11112 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11113 } 11114 } 11115 11116 /** 11117 * Set the scrolled position of your view. This will cause a call to 11118 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11119 * invalidated. 11120 * @param x the x position to scroll to 11121 * @param y the y position to scroll to 11122 */ 11123 public void scrollTo(int x, int y) { 11124 if (mScrollX != x || mScrollY != y) { 11125 int oldX = mScrollX; 11126 int oldY = mScrollY; 11127 mScrollX = x; 11128 mScrollY = y; 11129 invalidateParentCaches(); 11130 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11131 if (!awakenScrollBars()) { 11132 postInvalidateOnAnimation(); 11133 } 11134 } 11135 } 11136 11137 /** 11138 * Move the scrolled position of your view. This will cause a call to 11139 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11140 * invalidated. 11141 * @param x the amount of pixels to scroll by horizontally 11142 * @param y the amount of pixels to scroll by vertically 11143 */ 11144 public void scrollBy(int x, int y) { 11145 scrollTo(mScrollX + x, mScrollY + y); 11146 } 11147 11148 /** 11149 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11150 * animation to fade the scrollbars out after a default delay. If a subclass 11151 * provides animated scrolling, the start delay should equal the duration 11152 * of the scrolling animation.</p> 11153 * 11154 * <p>The animation starts only if at least one of the scrollbars is 11155 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11156 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11157 * this method returns true, and false otherwise. If the animation is 11158 * started, this method calls {@link #invalidate()}; in that case the 11159 * caller should not call {@link #invalidate()}.</p> 11160 * 11161 * <p>This method should be invoked every time a subclass directly updates 11162 * the scroll parameters.</p> 11163 * 11164 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11165 * and {@link #scrollTo(int, int)}.</p> 11166 * 11167 * @return true if the animation is played, false otherwise 11168 * 11169 * @see #awakenScrollBars(int) 11170 * @see #scrollBy(int, int) 11171 * @see #scrollTo(int, int) 11172 * @see #isHorizontalScrollBarEnabled() 11173 * @see #isVerticalScrollBarEnabled() 11174 * @see #setHorizontalScrollBarEnabled(boolean) 11175 * @see #setVerticalScrollBarEnabled(boolean) 11176 */ 11177 protected boolean awakenScrollBars() { 11178 return mScrollCache != null && 11179 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11180 } 11181 11182 /** 11183 * Trigger the scrollbars to draw. 11184 * This method differs from awakenScrollBars() only in its default duration. 11185 * initialAwakenScrollBars() will show the scroll bars for longer than 11186 * usual to give the user more of a chance to notice them. 11187 * 11188 * @return true if the animation is played, false otherwise. 11189 */ 11190 private boolean initialAwakenScrollBars() { 11191 return mScrollCache != null && 11192 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11193 } 11194 11195 /** 11196 * <p> 11197 * Trigger the scrollbars to draw. When invoked this method starts an 11198 * animation to fade the scrollbars out after a fixed delay. If a subclass 11199 * provides animated scrolling, the start delay should equal the duration of 11200 * the scrolling animation. 11201 * </p> 11202 * 11203 * <p> 11204 * The animation starts only if at least one of the scrollbars is enabled, 11205 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11206 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11207 * this method returns true, and false otherwise. If the animation is 11208 * started, this method calls {@link #invalidate()}; in that case the caller 11209 * should not call {@link #invalidate()}. 11210 * </p> 11211 * 11212 * <p> 11213 * This method should be invoked everytime a subclass directly updates the 11214 * scroll parameters. 11215 * </p> 11216 * 11217 * @param startDelay the delay, in milliseconds, after which the animation 11218 * should start; when the delay is 0, the animation starts 11219 * immediately 11220 * @return true if the animation is played, false otherwise 11221 * 11222 * @see #scrollBy(int, int) 11223 * @see #scrollTo(int, int) 11224 * @see #isHorizontalScrollBarEnabled() 11225 * @see #isVerticalScrollBarEnabled() 11226 * @see #setHorizontalScrollBarEnabled(boolean) 11227 * @see #setVerticalScrollBarEnabled(boolean) 11228 */ 11229 protected boolean awakenScrollBars(int startDelay) { 11230 return awakenScrollBars(startDelay, true); 11231 } 11232 11233 /** 11234 * <p> 11235 * Trigger the scrollbars to draw. When invoked this method starts an 11236 * animation to fade the scrollbars out after a fixed delay. If a subclass 11237 * provides animated scrolling, the start delay should equal the duration of 11238 * the scrolling animation. 11239 * </p> 11240 * 11241 * <p> 11242 * The animation starts only if at least one of the scrollbars is enabled, 11243 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11244 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11245 * this method returns true, and false otherwise. If the animation is 11246 * started, this method calls {@link #invalidate()} if the invalidate parameter 11247 * is set to true; in that case the caller 11248 * should not call {@link #invalidate()}. 11249 * </p> 11250 * 11251 * <p> 11252 * This method should be invoked everytime a subclass directly updates the 11253 * scroll parameters. 11254 * </p> 11255 * 11256 * @param startDelay the delay, in milliseconds, after which the animation 11257 * should start; when the delay is 0, the animation starts 11258 * immediately 11259 * 11260 * @param invalidate Wheter this method should call invalidate 11261 * 11262 * @return true if the animation is played, false otherwise 11263 * 11264 * @see #scrollBy(int, int) 11265 * @see #scrollTo(int, int) 11266 * @see #isHorizontalScrollBarEnabled() 11267 * @see #isVerticalScrollBarEnabled() 11268 * @see #setHorizontalScrollBarEnabled(boolean) 11269 * @see #setVerticalScrollBarEnabled(boolean) 11270 */ 11271 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11272 final ScrollabilityCache scrollCache = mScrollCache; 11273 11274 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11275 return false; 11276 } 11277 11278 if (scrollCache.scrollBar == null) { 11279 scrollCache.scrollBar = new ScrollBarDrawable(); 11280 } 11281 11282 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11283 11284 if (invalidate) { 11285 // Invalidate to show the scrollbars 11286 postInvalidateOnAnimation(); 11287 } 11288 11289 if (scrollCache.state == ScrollabilityCache.OFF) { 11290 // FIXME: this is copied from WindowManagerService. 11291 // We should get this value from the system when it 11292 // is possible to do so. 11293 final int KEY_REPEAT_FIRST_DELAY = 750; 11294 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11295 } 11296 11297 // Tell mScrollCache when we should start fading. This may 11298 // extend the fade start time if one was already scheduled 11299 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11300 scrollCache.fadeStartTime = fadeStartTime; 11301 scrollCache.state = ScrollabilityCache.ON; 11302 11303 // Schedule our fader to run, unscheduling any old ones first 11304 if (mAttachInfo != null) { 11305 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11306 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11307 } 11308 11309 return true; 11310 } 11311 11312 return false; 11313 } 11314 11315 /** 11316 * Do not invalidate views which are not visible and which are not running an animation. They 11317 * will not get drawn and they should not set dirty flags as if they will be drawn 11318 */ 11319 private boolean skipInvalidate() { 11320 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11321 (!(mParent instanceof ViewGroup) || 11322 !((ViewGroup) mParent).isViewTransitioning(this)); 11323 } 11324 11325 /** 11326 * Mark the area defined by dirty as needing to be drawn. If the view is 11327 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11328 * point in the future. 11329 * <p> 11330 * This must be called from a UI thread. To call from a non-UI thread, call 11331 * {@link #postInvalidate()}. 11332 * <p> 11333 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11334 * {@code dirty}. 11335 * 11336 * @param dirty the rectangle representing the bounds of the dirty region 11337 */ 11338 public void invalidate(Rect dirty) { 11339 final int scrollX = mScrollX; 11340 final int scrollY = mScrollY; 11341 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11342 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11343 } 11344 11345 /** 11346 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11347 * coordinates of the dirty rect are relative to the view. If the view is 11348 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11349 * point in the future. 11350 * <p> 11351 * This must be called from a UI thread. To call from a non-UI thread, call 11352 * {@link #postInvalidate()}. 11353 * 11354 * @param l the left position of the dirty region 11355 * @param t the top position of the dirty region 11356 * @param r the right position of the dirty region 11357 * @param b the bottom position of the dirty region 11358 */ 11359 public void invalidate(int l, int t, int r, int b) { 11360 final int scrollX = mScrollX; 11361 final int scrollY = mScrollY; 11362 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11363 } 11364 11365 /** 11366 * Invalidate the whole view. If the view is visible, 11367 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11368 * the future. 11369 * <p> 11370 * This must be called from a UI thread. To call from a non-UI thread, call 11371 * {@link #postInvalidate()}. 11372 */ 11373 public void invalidate() { 11374 invalidate(true); 11375 } 11376 11377 /** 11378 * This is where the invalidate() work actually happens. A full invalidate() 11379 * causes the drawing cache to be invalidated, but this function can be 11380 * called with invalidateCache set to false to skip that invalidation step 11381 * for cases that do not need it (for example, a component that remains at 11382 * the same dimensions with the same content). 11383 * 11384 * @param invalidateCache Whether the drawing cache for this view should be 11385 * invalidated as well. This is usually true for a full 11386 * invalidate, but may be set to false if the View's contents or 11387 * dimensions have not changed. 11388 */ 11389 void invalidate(boolean invalidateCache) { 11390 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11391 } 11392 11393 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11394 boolean fullInvalidate) { 11395 if (skipInvalidate()) { 11396 return; 11397 } 11398 11399 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11400 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11401 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11402 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11403 if (fullInvalidate) { 11404 mLastIsOpaque = isOpaque(); 11405 mPrivateFlags &= ~PFLAG_DRAWN; 11406 } 11407 11408 mPrivateFlags |= PFLAG_DIRTY; 11409 11410 if (invalidateCache) { 11411 mPrivateFlags |= PFLAG_INVALIDATED; 11412 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11413 } 11414 11415 // Propagate the damage rectangle to the parent view. 11416 final AttachInfo ai = mAttachInfo; 11417 final ViewParent p = mParent; 11418 if (p != null && ai != null && l < r && t < b) { 11419 final Rect damage = ai.mTmpInvalRect; 11420 damage.set(l, t, r, b); 11421 p.invalidateChild(this, damage); 11422 } 11423 11424 // Damage the entire projection receiver, if necessary. 11425 if (mBackground != null && mBackground.isProjected()) { 11426 final View receiver = getProjectionReceiver(); 11427 if (receiver != null) { 11428 receiver.damageInParent(); 11429 } 11430 } 11431 11432 // Damage the entire IsolatedZVolume recieving this view's shadow. 11433 if (isHardwareAccelerated() && getZ() != 0) { 11434 damageShadowReceiver(); 11435 } 11436 } 11437 } 11438 11439 /** 11440 * @return this view's projection receiver, or {@code null} if none exists 11441 */ 11442 private View getProjectionReceiver() { 11443 ViewParent p = getParent(); 11444 while (p != null && p instanceof View) { 11445 final View v = (View) p; 11446 if (v.isProjectionReceiver()) { 11447 return v; 11448 } 11449 p = p.getParent(); 11450 } 11451 11452 return null; 11453 } 11454 11455 /** 11456 * @return whether the view is a projection receiver 11457 */ 11458 private boolean isProjectionReceiver() { 11459 return mBackground != null; 11460 } 11461 11462 /** 11463 * Damage area of the screen that can be covered by this View's shadow. 11464 * 11465 * This method will guarantee that any changes to shadows cast by a View 11466 * are damaged on the screen for future redraw. 11467 */ 11468 private void damageShadowReceiver() { 11469 final AttachInfo ai = mAttachInfo; 11470 if (ai != null) { 11471 ViewParent p = getParent(); 11472 if (p != null && p instanceof ViewGroup) { 11473 final ViewGroup vg = (ViewGroup) p; 11474 vg.damageInParent(); 11475 } 11476 } 11477 } 11478 11479 /** 11480 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11481 * set any flags or handle all of the cases handled by the default invalidation methods. 11482 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11483 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11484 * walk up the hierarchy, transforming the dirty rect as necessary. 11485 * 11486 * The method also handles normal invalidation logic if display list properties are not 11487 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11488 * backup approach, to handle these cases used in the various property-setting methods. 11489 * 11490 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11491 * are not being used in this view 11492 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11493 * list properties are not being used in this view 11494 */ 11495 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11496 if (!isHardwareAccelerated() 11497 || !mRenderNode.isValid() 11498 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11499 if (invalidateParent) { 11500 invalidateParentCaches(); 11501 } 11502 if (forceRedraw) { 11503 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11504 } 11505 invalidate(false); 11506 } else { 11507 damageInParent(); 11508 } 11509 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11510 damageShadowReceiver(); 11511 } 11512 } 11513 11514 /** 11515 * Tells the parent view to damage this view's bounds. 11516 * 11517 * @hide 11518 */ 11519 protected void damageInParent() { 11520 final AttachInfo ai = mAttachInfo; 11521 final ViewParent p = mParent; 11522 if (p != null && ai != null) { 11523 final Rect r = ai.mTmpInvalRect; 11524 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11525 if (mParent instanceof ViewGroup) { 11526 ((ViewGroup) mParent).damageChild(this, r); 11527 } else { 11528 mParent.invalidateChild(this, r); 11529 } 11530 } 11531 } 11532 11533 /** 11534 * Utility method to transform a given Rect by the current matrix of this view. 11535 */ 11536 void transformRect(final Rect rect) { 11537 if (!getMatrix().isIdentity()) { 11538 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11539 boundingRect.set(rect); 11540 getMatrix().mapRect(boundingRect); 11541 rect.set((int) Math.floor(boundingRect.left), 11542 (int) Math.floor(boundingRect.top), 11543 (int) Math.ceil(boundingRect.right), 11544 (int) Math.ceil(boundingRect.bottom)); 11545 } 11546 } 11547 11548 /** 11549 * Used to indicate that the parent of this view should clear its caches. This functionality 11550 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11551 * which is necessary when various parent-managed properties of the view change, such as 11552 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11553 * clears the parent caches and does not causes an invalidate event. 11554 * 11555 * @hide 11556 */ 11557 protected void invalidateParentCaches() { 11558 if (mParent instanceof View) { 11559 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11560 } 11561 } 11562 11563 /** 11564 * Used to indicate that the parent of this view should be invalidated. This functionality 11565 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11566 * which is necessary when various parent-managed properties of the view change, such as 11567 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11568 * an invalidation event to the parent. 11569 * 11570 * @hide 11571 */ 11572 protected void invalidateParentIfNeeded() { 11573 if (isHardwareAccelerated() && mParent instanceof View) { 11574 ((View) mParent).invalidate(true); 11575 } 11576 } 11577 11578 /** 11579 * @hide 11580 */ 11581 protected void invalidateParentIfNeededAndWasQuickRejected() { 11582 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11583 // View was rejected last time it was drawn by its parent; this may have changed 11584 invalidateParentIfNeeded(); 11585 } 11586 } 11587 11588 /** 11589 * Indicates whether this View is opaque. An opaque View guarantees that it will 11590 * draw all the pixels overlapping its bounds using a fully opaque color. 11591 * 11592 * Subclasses of View should override this method whenever possible to indicate 11593 * whether an instance is opaque. Opaque Views are treated in a special way by 11594 * the View hierarchy, possibly allowing it to perform optimizations during 11595 * invalidate/draw passes. 11596 * 11597 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11598 */ 11599 @ViewDebug.ExportedProperty(category = "drawing") 11600 public boolean isOpaque() { 11601 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11602 getFinalAlpha() >= 1.0f; 11603 } 11604 11605 /** 11606 * @hide 11607 */ 11608 protected void computeOpaqueFlags() { 11609 // Opaque if: 11610 // - Has a background 11611 // - Background is opaque 11612 // - Doesn't have scrollbars or scrollbars overlay 11613 11614 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11615 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11616 } else { 11617 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11618 } 11619 11620 final int flags = mViewFlags; 11621 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11622 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11623 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11624 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11625 } else { 11626 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11627 } 11628 } 11629 11630 /** 11631 * @hide 11632 */ 11633 protected boolean hasOpaqueScrollbars() { 11634 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11635 } 11636 11637 /** 11638 * @return A handler associated with the thread running the View. This 11639 * handler can be used to pump events in the UI events queue. 11640 */ 11641 public Handler getHandler() { 11642 final AttachInfo attachInfo = mAttachInfo; 11643 if (attachInfo != null) { 11644 return attachInfo.mHandler; 11645 } 11646 return null; 11647 } 11648 11649 /** 11650 * Gets the view root associated with the View. 11651 * @return The view root, or null if none. 11652 * @hide 11653 */ 11654 public ViewRootImpl getViewRootImpl() { 11655 if (mAttachInfo != null) { 11656 return mAttachInfo.mViewRootImpl; 11657 } 11658 return null; 11659 } 11660 11661 /** 11662 * @hide 11663 */ 11664 public HardwareRenderer getHardwareRenderer() { 11665 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11666 } 11667 11668 /** 11669 * <p>Causes the Runnable to be added to the message queue. 11670 * The runnable will be run on the user interface thread.</p> 11671 * 11672 * @param action The Runnable that will be executed. 11673 * 11674 * @return Returns true if the Runnable was successfully placed in to the 11675 * message queue. Returns false on failure, usually because the 11676 * looper processing the message queue is exiting. 11677 * 11678 * @see #postDelayed 11679 * @see #removeCallbacks 11680 */ 11681 public boolean post(Runnable action) { 11682 final AttachInfo attachInfo = mAttachInfo; 11683 if (attachInfo != null) { 11684 return attachInfo.mHandler.post(action); 11685 } 11686 // Assume that post will succeed later 11687 ViewRootImpl.getRunQueue().post(action); 11688 return true; 11689 } 11690 11691 /** 11692 * <p>Causes the Runnable to be added to the message queue, to be run 11693 * after the specified amount of time elapses. 11694 * The runnable will be run on the user interface thread.</p> 11695 * 11696 * @param action The Runnable that will be executed. 11697 * @param delayMillis The delay (in milliseconds) until the Runnable 11698 * will be executed. 11699 * 11700 * @return true if the Runnable was successfully placed in to the 11701 * message queue. Returns false on failure, usually because the 11702 * looper processing the message queue is exiting. Note that a 11703 * result of true does not mean the Runnable will be processed -- 11704 * if the looper is quit before the delivery time of the message 11705 * occurs then the message will be dropped. 11706 * 11707 * @see #post 11708 * @see #removeCallbacks 11709 */ 11710 public boolean postDelayed(Runnable action, long delayMillis) { 11711 final AttachInfo attachInfo = mAttachInfo; 11712 if (attachInfo != null) { 11713 return attachInfo.mHandler.postDelayed(action, delayMillis); 11714 } 11715 // Assume that post will succeed later 11716 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11717 return true; 11718 } 11719 11720 /** 11721 * <p>Causes the Runnable to execute on the next animation time step. 11722 * The runnable will be run on the user interface thread.</p> 11723 * 11724 * @param action The Runnable that will be executed. 11725 * 11726 * @see #postOnAnimationDelayed 11727 * @see #removeCallbacks 11728 */ 11729 public void postOnAnimation(Runnable action) { 11730 final AttachInfo attachInfo = mAttachInfo; 11731 if (attachInfo != null) { 11732 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11733 Choreographer.CALLBACK_ANIMATION, action, null); 11734 } else { 11735 // Assume that post will succeed later 11736 ViewRootImpl.getRunQueue().post(action); 11737 } 11738 } 11739 11740 /** 11741 * <p>Causes the Runnable to execute on the next animation time step, 11742 * after the specified amount of time elapses. 11743 * The runnable will be run on the user interface thread.</p> 11744 * 11745 * @param action The Runnable that will be executed. 11746 * @param delayMillis The delay (in milliseconds) until the Runnable 11747 * will be executed. 11748 * 11749 * @see #postOnAnimation 11750 * @see #removeCallbacks 11751 */ 11752 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11753 final AttachInfo attachInfo = mAttachInfo; 11754 if (attachInfo != null) { 11755 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11756 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11757 } else { 11758 // Assume that post will succeed later 11759 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11760 } 11761 } 11762 11763 /** 11764 * <p>Removes the specified Runnable from the message queue.</p> 11765 * 11766 * @param action The Runnable to remove from the message handling queue 11767 * 11768 * @return true if this view could ask the Handler to remove the Runnable, 11769 * false otherwise. When the returned value is true, the Runnable 11770 * may or may not have been actually removed from the message queue 11771 * (for instance, if the Runnable was not in the queue already.) 11772 * 11773 * @see #post 11774 * @see #postDelayed 11775 * @see #postOnAnimation 11776 * @see #postOnAnimationDelayed 11777 */ 11778 public boolean removeCallbacks(Runnable action) { 11779 if (action != null) { 11780 final AttachInfo attachInfo = mAttachInfo; 11781 if (attachInfo != null) { 11782 attachInfo.mHandler.removeCallbacks(action); 11783 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11784 Choreographer.CALLBACK_ANIMATION, action, null); 11785 } 11786 // Assume that post will succeed later 11787 ViewRootImpl.getRunQueue().removeCallbacks(action); 11788 } 11789 return true; 11790 } 11791 11792 /** 11793 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11794 * Use this to invalidate the View from a non-UI thread.</p> 11795 * 11796 * <p>This method can be invoked from outside of the UI thread 11797 * only when this View is attached to a window.</p> 11798 * 11799 * @see #invalidate() 11800 * @see #postInvalidateDelayed(long) 11801 */ 11802 public void postInvalidate() { 11803 postInvalidateDelayed(0); 11804 } 11805 11806 /** 11807 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11808 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11809 * 11810 * <p>This method can be invoked from outside of the UI thread 11811 * only when this View is attached to a window.</p> 11812 * 11813 * @param left The left coordinate of the rectangle to invalidate. 11814 * @param top The top coordinate of the rectangle to invalidate. 11815 * @param right The right coordinate of the rectangle to invalidate. 11816 * @param bottom The bottom coordinate of the rectangle to invalidate. 11817 * 11818 * @see #invalidate(int, int, int, int) 11819 * @see #invalidate(Rect) 11820 * @see #postInvalidateDelayed(long, int, int, int, int) 11821 */ 11822 public void postInvalidate(int left, int top, int right, int bottom) { 11823 postInvalidateDelayed(0, left, top, right, bottom); 11824 } 11825 11826 /** 11827 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11828 * loop. Waits for the specified amount of time.</p> 11829 * 11830 * <p>This method can be invoked from outside of the UI thread 11831 * only when this View is attached to a window.</p> 11832 * 11833 * @param delayMilliseconds the duration in milliseconds to delay the 11834 * invalidation by 11835 * 11836 * @see #invalidate() 11837 * @see #postInvalidate() 11838 */ 11839 public void postInvalidateDelayed(long delayMilliseconds) { 11840 // We try only with the AttachInfo because there's no point in invalidating 11841 // if we are not attached to our window 11842 final AttachInfo attachInfo = mAttachInfo; 11843 if (attachInfo != null) { 11844 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11845 } 11846 } 11847 11848 /** 11849 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11850 * through the event loop. Waits for the specified amount of time.</p> 11851 * 11852 * <p>This method can be invoked from outside of the UI thread 11853 * only when this View is attached to a window.</p> 11854 * 11855 * @param delayMilliseconds the duration in milliseconds to delay the 11856 * invalidation by 11857 * @param left The left coordinate of the rectangle to invalidate. 11858 * @param top The top coordinate of the rectangle to invalidate. 11859 * @param right The right coordinate of the rectangle to invalidate. 11860 * @param bottom The bottom coordinate of the rectangle to invalidate. 11861 * 11862 * @see #invalidate(int, int, int, int) 11863 * @see #invalidate(Rect) 11864 * @see #postInvalidate(int, int, int, int) 11865 */ 11866 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11867 int right, int bottom) { 11868 11869 // We try only with the AttachInfo because there's no point in invalidating 11870 // if we are not attached to our window 11871 final AttachInfo attachInfo = mAttachInfo; 11872 if (attachInfo != null) { 11873 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11874 info.target = this; 11875 info.left = left; 11876 info.top = top; 11877 info.right = right; 11878 info.bottom = bottom; 11879 11880 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11881 } 11882 } 11883 11884 /** 11885 * <p>Cause an invalidate to happen on the next animation time step, typically the 11886 * next display frame.</p> 11887 * 11888 * <p>This method can be invoked from outside of the UI thread 11889 * only when this View is attached to a window.</p> 11890 * 11891 * @see #invalidate() 11892 */ 11893 public void postInvalidateOnAnimation() { 11894 // We try only with the AttachInfo because there's no point in invalidating 11895 // if we are not attached to our window 11896 final AttachInfo attachInfo = mAttachInfo; 11897 if (attachInfo != null) { 11898 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11899 } 11900 } 11901 11902 /** 11903 * <p>Cause an invalidate of the specified area to happen on the next animation 11904 * time step, typically the next display frame.</p> 11905 * 11906 * <p>This method can be invoked from outside of the UI thread 11907 * only when this View is attached to a window.</p> 11908 * 11909 * @param left The left coordinate of the rectangle to invalidate. 11910 * @param top The top coordinate of the rectangle to invalidate. 11911 * @param right The right coordinate of the rectangle to invalidate. 11912 * @param bottom The bottom coordinate of the rectangle to invalidate. 11913 * 11914 * @see #invalidate(int, int, int, int) 11915 * @see #invalidate(Rect) 11916 */ 11917 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11918 // We try only with the AttachInfo because there's no point in invalidating 11919 // if we are not attached to our window 11920 final AttachInfo attachInfo = mAttachInfo; 11921 if (attachInfo != null) { 11922 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11923 info.target = this; 11924 info.left = left; 11925 info.top = top; 11926 info.right = right; 11927 info.bottom = bottom; 11928 11929 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11930 } 11931 } 11932 11933 /** 11934 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11935 * This event is sent at most once every 11936 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11937 */ 11938 private void postSendViewScrolledAccessibilityEventCallback() { 11939 if (mSendViewScrolledAccessibilityEvent == null) { 11940 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11941 } 11942 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11943 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11944 postDelayed(mSendViewScrolledAccessibilityEvent, 11945 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11946 } 11947 } 11948 11949 /** 11950 * Called by a parent to request that a child update its values for mScrollX 11951 * and mScrollY if necessary. This will typically be done if the child is 11952 * animating a scroll using a {@link android.widget.Scroller Scroller} 11953 * object. 11954 */ 11955 public void computeScroll() { 11956 } 11957 11958 /** 11959 * <p>Indicate whether the horizontal edges are faded when the view is 11960 * scrolled horizontally.</p> 11961 * 11962 * @return true if the horizontal edges should are faded on scroll, false 11963 * otherwise 11964 * 11965 * @see #setHorizontalFadingEdgeEnabled(boolean) 11966 * 11967 * @attr ref android.R.styleable#View_requiresFadingEdge 11968 */ 11969 public boolean isHorizontalFadingEdgeEnabled() { 11970 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11971 } 11972 11973 /** 11974 * <p>Define whether the horizontal edges should be faded when this view 11975 * is scrolled horizontally.</p> 11976 * 11977 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11978 * be faded when the view is scrolled 11979 * horizontally 11980 * 11981 * @see #isHorizontalFadingEdgeEnabled() 11982 * 11983 * @attr ref android.R.styleable#View_requiresFadingEdge 11984 */ 11985 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11986 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11987 if (horizontalFadingEdgeEnabled) { 11988 initScrollCache(); 11989 } 11990 11991 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11992 } 11993 } 11994 11995 /** 11996 * <p>Indicate whether the vertical edges are faded when the view is 11997 * scrolled horizontally.</p> 11998 * 11999 * @return true if the vertical edges should are faded on scroll, false 12000 * otherwise 12001 * 12002 * @see #setVerticalFadingEdgeEnabled(boolean) 12003 * 12004 * @attr ref android.R.styleable#View_requiresFadingEdge 12005 */ 12006 public boolean isVerticalFadingEdgeEnabled() { 12007 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 12008 } 12009 12010 /** 12011 * <p>Define whether the vertical edges should be faded when this view 12012 * is scrolled vertically.</p> 12013 * 12014 * @param verticalFadingEdgeEnabled true if the vertical edges should 12015 * be faded when the view is scrolled 12016 * vertically 12017 * 12018 * @see #isVerticalFadingEdgeEnabled() 12019 * 12020 * @attr ref android.R.styleable#View_requiresFadingEdge 12021 */ 12022 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 12023 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 12024 if (verticalFadingEdgeEnabled) { 12025 initScrollCache(); 12026 } 12027 12028 mViewFlags ^= FADING_EDGE_VERTICAL; 12029 } 12030 } 12031 12032 /** 12033 * Returns the strength, or intensity, of the top faded edge. The strength is 12034 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12035 * returns 0.0 or 1.0 but no value in between. 12036 * 12037 * Subclasses should override this method to provide a smoother fade transition 12038 * when scrolling occurs. 12039 * 12040 * @return the intensity of the top fade as a float between 0.0f and 1.0f 12041 */ 12042 protected float getTopFadingEdgeStrength() { 12043 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 12044 } 12045 12046 /** 12047 * Returns the strength, or intensity, of the bottom faded edge. The strength is 12048 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12049 * returns 0.0 or 1.0 but no value in between. 12050 * 12051 * Subclasses should override this method to provide a smoother fade transition 12052 * when scrolling occurs. 12053 * 12054 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 12055 */ 12056 protected float getBottomFadingEdgeStrength() { 12057 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 12058 computeVerticalScrollRange() ? 1.0f : 0.0f; 12059 } 12060 12061 /** 12062 * Returns the strength, or intensity, of the left faded edge. The strength is 12063 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12064 * returns 0.0 or 1.0 but no value in between. 12065 * 12066 * Subclasses should override this method to provide a smoother fade transition 12067 * when scrolling occurs. 12068 * 12069 * @return the intensity of the left fade as a float between 0.0f and 1.0f 12070 */ 12071 protected float getLeftFadingEdgeStrength() { 12072 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12073 } 12074 12075 /** 12076 * Returns the strength, or intensity, of the right faded edge. The strength is 12077 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12078 * returns 0.0 or 1.0 but no value in between. 12079 * 12080 * Subclasses should override this method to provide a smoother fade transition 12081 * when scrolling occurs. 12082 * 12083 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12084 */ 12085 protected float getRightFadingEdgeStrength() { 12086 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12087 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12088 } 12089 12090 /** 12091 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12092 * scrollbar is not drawn by default.</p> 12093 * 12094 * @return true if the horizontal scrollbar should be painted, false 12095 * otherwise 12096 * 12097 * @see #setHorizontalScrollBarEnabled(boolean) 12098 */ 12099 public boolean isHorizontalScrollBarEnabled() { 12100 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12101 } 12102 12103 /** 12104 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12105 * scrollbar is not drawn by default.</p> 12106 * 12107 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12108 * be painted 12109 * 12110 * @see #isHorizontalScrollBarEnabled() 12111 */ 12112 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12113 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12114 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12115 computeOpaqueFlags(); 12116 resolvePadding(); 12117 } 12118 } 12119 12120 /** 12121 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12122 * scrollbar is not drawn by default.</p> 12123 * 12124 * @return true if the vertical scrollbar should be painted, false 12125 * otherwise 12126 * 12127 * @see #setVerticalScrollBarEnabled(boolean) 12128 */ 12129 public boolean isVerticalScrollBarEnabled() { 12130 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12131 } 12132 12133 /** 12134 * <p>Define whether the vertical scrollbar should be drawn or not. The 12135 * scrollbar is not drawn by default.</p> 12136 * 12137 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12138 * be painted 12139 * 12140 * @see #isVerticalScrollBarEnabled() 12141 */ 12142 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12143 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12144 mViewFlags ^= SCROLLBARS_VERTICAL; 12145 computeOpaqueFlags(); 12146 resolvePadding(); 12147 } 12148 } 12149 12150 /** 12151 * @hide 12152 */ 12153 protected void recomputePadding() { 12154 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12155 } 12156 12157 /** 12158 * Define whether scrollbars will fade when the view is not scrolling. 12159 * 12160 * @param fadeScrollbars wheter to enable fading 12161 * 12162 * @attr ref android.R.styleable#View_fadeScrollbars 12163 */ 12164 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12165 initScrollCache(); 12166 final ScrollabilityCache scrollabilityCache = mScrollCache; 12167 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12168 if (fadeScrollbars) { 12169 scrollabilityCache.state = ScrollabilityCache.OFF; 12170 } else { 12171 scrollabilityCache.state = ScrollabilityCache.ON; 12172 } 12173 } 12174 12175 /** 12176 * 12177 * Returns true if scrollbars will fade when this view is not scrolling 12178 * 12179 * @return true if scrollbar fading is enabled 12180 * 12181 * @attr ref android.R.styleable#View_fadeScrollbars 12182 */ 12183 public boolean isScrollbarFadingEnabled() { 12184 return mScrollCache != null && mScrollCache.fadeScrollBars; 12185 } 12186 12187 /** 12188 * 12189 * Returns the delay before scrollbars fade. 12190 * 12191 * @return the delay before scrollbars fade 12192 * 12193 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12194 */ 12195 public int getScrollBarDefaultDelayBeforeFade() { 12196 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12197 mScrollCache.scrollBarDefaultDelayBeforeFade; 12198 } 12199 12200 /** 12201 * Define the delay before scrollbars fade. 12202 * 12203 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12204 * 12205 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12206 */ 12207 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12208 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12209 } 12210 12211 /** 12212 * 12213 * Returns the scrollbar fade duration. 12214 * 12215 * @return the scrollbar fade duration 12216 * 12217 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12218 */ 12219 public int getScrollBarFadeDuration() { 12220 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12221 mScrollCache.scrollBarFadeDuration; 12222 } 12223 12224 /** 12225 * Define the scrollbar fade duration. 12226 * 12227 * @param scrollBarFadeDuration - the scrollbar fade duration 12228 * 12229 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12230 */ 12231 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12232 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12233 } 12234 12235 /** 12236 * 12237 * Returns the scrollbar size. 12238 * 12239 * @return the scrollbar size 12240 * 12241 * @attr ref android.R.styleable#View_scrollbarSize 12242 */ 12243 public int getScrollBarSize() { 12244 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12245 mScrollCache.scrollBarSize; 12246 } 12247 12248 /** 12249 * Define the scrollbar size. 12250 * 12251 * @param scrollBarSize - the scrollbar size 12252 * 12253 * @attr ref android.R.styleable#View_scrollbarSize 12254 */ 12255 public void setScrollBarSize(int scrollBarSize) { 12256 getScrollCache().scrollBarSize = scrollBarSize; 12257 } 12258 12259 /** 12260 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12261 * inset. When inset, they add to the padding of the view. And the scrollbars 12262 * can be drawn inside the padding area or on the edge of the view. For example, 12263 * if a view has a background drawable and you want to draw the scrollbars 12264 * inside the padding specified by the drawable, you can use 12265 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12266 * appear at the edge of the view, ignoring the padding, then you can use 12267 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12268 * @param style the style of the scrollbars. Should be one of 12269 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12270 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12271 * @see #SCROLLBARS_INSIDE_OVERLAY 12272 * @see #SCROLLBARS_INSIDE_INSET 12273 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12274 * @see #SCROLLBARS_OUTSIDE_INSET 12275 * 12276 * @attr ref android.R.styleable#View_scrollbarStyle 12277 */ 12278 public void setScrollBarStyle(@ScrollBarStyle int style) { 12279 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12280 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12281 computeOpaqueFlags(); 12282 resolvePadding(); 12283 } 12284 } 12285 12286 /** 12287 * <p>Returns the current scrollbar style.</p> 12288 * @return the current scrollbar style 12289 * @see #SCROLLBARS_INSIDE_OVERLAY 12290 * @see #SCROLLBARS_INSIDE_INSET 12291 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12292 * @see #SCROLLBARS_OUTSIDE_INSET 12293 * 12294 * @attr ref android.R.styleable#View_scrollbarStyle 12295 */ 12296 @ViewDebug.ExportedProperty(mapping = { 12297 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12298 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12299 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12300 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12301 }) 12302 @ScrollBarStyle 12303 public int getScrollBarStyle() { 12304 return mViewFlags & SCROLLBARS_STYLE_MASK; 12305 } 12306 12307 /** 12308 * <p>Compute the horizontal range that the horizontal scrollbar 12309 * represents.</p> 12310 * 12311 * <p>The range is expressed in arbitrary units that must be the same as the 12312 * units used by {@link #computeHorizontalScrollExtent()} and 12313 * {@link #computeHorizontalScrollOffset()}.</p> 12314 * 12315 * <p>The default range is the drawing width of this view.</p> 12316 * 12317 * @return the total horizontal range represented by the horizontal 12318 * scrollbar 12319 * 12320 * @see #computeHorizontalScrollExtent() 12321 * @see #computeHorizontalScrollOffset() 12322 * @see android.widget.ScrollBarDrawable 12323 */ 12324 protected int computeHorizontalScrollRange() { 12325 return getWidth(); 12326 } 12327 12328 /** 12329 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12330 * within the horizontal range. This value is used to compute the position 12331 * of the thumb within the scrollbar's track.</p> 12332 * 12333 * <p>The range is expressed in arbitrary units that must be the same as the 12334 * units used by {@link #computeHorizontalScrollRange()} and 12335 * {@link #computeHorizontalScrollExtent()}.</p> 12336 * 12337 * <p>The default offset is the scroll offset of this view.</p> 12338 * 12339 * @return the horizontal offset of the scrollbar's thumb 12340 * 12341 * @see #computeHorizontalScrollRange() 12342 * @see #computeHorizontalScrollExtent() 12343 * @see android.widget.ScrollBarDrawable 12344 */ 12345 protected int computeHorizontalScrollOffset() { 12346 return mScrollX; 12347 } 12348 12349 /** 12350 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12351 * within the horizontal range. This value is used to compute the length 12352 * of the thumb within the scrollbar's track.</p> 12353 * 12354 * <p>The range is expressed in arbitrary units that must be the same as the 12355 * units used by {@link #computeHorizontalScrollRange()} and 12356 * {@link #computeHorizontalScrollOffset()}.</p> 12357 * 12358 * <p>The default extent is the drawing width of this view.</p> 12359 * 12360 * @return the horizontal extent of the scrollbar's thumb 12361 * 12362 * @see #computeHorizontalScrollRange() 12363 * @see #computeHorizontalScrollOffset() 12364 * @see android.widget.ScrollBarDrawable 12365 */ 12366 protected int computeHorizontalScrollExtent() { 12367 return getWidth(); 12368 } 12369 12370 /** 12371 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12372 * 12373 * <p>The range is expressed in arbitrary units that must be the same as the 12374 * units used by {@link #computeVerticalScrollExtent()} and 12375 * {@link #computeVerticalScrollOffset()}.</p> 12376 * 12377 * @return the total vertical range represented by the vertical scrollbar 12378 * 12379 * <p>The default range is the drawing height of this view.</p> 12380 * 12381 * @see #computeVerticalScrollExtent() 12382 * @see #computeVerticalScrollOffset() 12383 * @see android.widget.ScrollBarDrawable 12384 */ 12385 protected int computeVerticalScrollRange() { 12386 return getHeight(); 12387 } 12388 12389 /** 12390 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12391 * within the horizontal range. This value is used to compute the position 12392 * of the thumb within the scrollbar's track.</p> 12393 * 12394 * <p>The range is expressed in arbitrary units that must be the same as the 12395 * units used by {@link #computeVerticalScrollRange()} and 12396 * {@link #computeVerticalScrollExtent()}.</p> 12397 * 12398 * <p>The default offset is the scroll offset of this view.</p> 12399 * 12400 * @return the vertical offset of the scrollbar's thumb 12401 * 12402 * @see #computeVerticalScrollRange() 12403 * @see #computeVerticalScrollExtent() 12404 * @see android.widget.ScrollBarDrawable 12405 */ 12406 protected int computeVerticalScrollOffset() { 12407 return mScrollY; 12408 } 12409 12410 /** 12411 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12412 * within the vertical range. This value is used to compute the length 12413 * of the thumb within the scrollbar's track.</p> 12414 * 12415 * <p>The range is expressed in arbitrary units that must be the same as the 12416 * units used by {@link #computeVerticalScrollRange()} and 12417 * {@link #computeVerticalScrollOffset()}.</p> 12418 * 12419 * <p>The default extent is the drawing height of this view.</p> 12420 * 12421 * @return the vertical extent of the scrollbar's thumb 12422 * 12423 * @see #computeVerticalScrollRange() 12424 * @see #computeVerticalScrollOffset() 12425 * @see android.widget.ScrollBarDrawable 12426 */ 12427 protected int computeVerticalScrollExtent() { 12428 return getHeight(); 12429 } 12430 12431 /** 12432 * Check if this view can be scrolled horizontally in a certain direction. 12433 * 12434 * @param direction Negative to check scrolling left, positive to check scrolling right. 12435 * @return true if this view can be scrolled in the specified direction, false otherwise. 12436 */ 12437 public boolean canScrollHorizontally(int direction) { 12438 final int offset = computeHorizontalScrollOffset(); 12439 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12440 if (range == 0) return false; 12441 if (direction < 0) { 12442 return offset > 0; 12443 } else { 12444 return offset < range - 1; 12445 } 12446 } 12447 12448 /** 12449 * Check if this view can be scrolled vertically in a certain direction. 12450 * 12451 * @param direction Negative to check scrolling up, positive to check scrolling down. 12452 * @return true if this view can be scrolled in the specified direction, false otherwise. 12453 */ 12454 public boolean canScrollVertically(int direction) { 12455 final int offset = computeVerticalScrollOffset(); 12456 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12457 if (range == 0) return false; 12458 if (direction < 0) { 12459 return offset > 0; 12460 } else { 12461 return offset < range - 1; 12462 } 12463 } 12464 12465 /** 12466 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12467 * scrollbars are painted only if they have been awakened first.</p> 12468 * 12469 * @param canvas the canvas on which to draw the scrollbars 12470 * 12471 * @see #awakenScrollBars(int) 12472 */ 12473 protected final void onDrawScrollBars(Canvas canvas) { 12474 // scrollbars are drawn only when the animation is running 12475 final ScrollabilityCache cache = mScrollCache; 12476 if (cache != null) { 12477 12478 int state = cache.state; 12479 12480 if (state == ScrollabilityCache.OFF) { 12481 return; 12482 } 12483 12484 boolean invalidate = false; 12485 12486 if (state == ScrollabilityCache.FADING) { 12487 // We're fading -- get our fade interpolation 12488 if (cache.interpolatorValues == null) { 12489 cache.interpolatorValues = new float[1]; 12490 } 12491 12492 float[] values = cache.interpolatorValues; 12493 12494 // Stops the animation if we're done 12495 if (cache.scrollBarInterpolator.timeToValues(values) == 12496 Interpolator.Result.FREEZE_END) { 12497 cache.state = ScrollabilityCache.OFF; 12498 } else { 12499 cache.scrollBar.setAlpha(Math.round(values[0])); 12500 } 12501 12502 // This will make the scroll bars inval themselves after 12503 // drawing. We only want this when we're fading so that 12504 // we prevent excessive redraws 12505 invalidate = true; 12506 } else { 12507 // We're just on -- but we may have been fading before so 12508 // reset alpha 12509 cache.scrollBar.setAlpha(255); 12510 } 12511 12512 12513 final int viewFlags = mViewFlags; 12514 12515 final boolean drawHorizontalScrollBar = 12516 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12517 final boolean drawVerticalScrollBar = 12518 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12519 && !isVerticalScrollBarHidden(); 12520 12521 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12522 final int width = mRight - mLeft; 12523 final int height = mBottom - mTop; 12524 12525 final ScrollBarDrawable scrollBar = cache.scrollBar; 12526 12527 final int scrollX = mScrollX; 12528 final int scrollY = mScrollY; 12529 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12530 12531 int left; 12532 int top; 12533 int right; 12534 int bottom; 12535 12536 if (drawHorizontalScrollBar) { 12537 int size = scrollBar.getSize(false); 12538 if (size <= 0) { 12539 size = cache.scrollBarSize; 12540 } 12541 12542 scrollBar.setParameters(computeHorizontalScrollRange(), 12543 computeHorizontalScrollOffset(), 12544 computeHorizontalScrollExtent(), false); 12545 final int verticalScrollBarGap = drawVerticalScrollBar ? 12546 getVerticalScrollbarWidth() : 0; 12547 top = scrollY + height - size - (mUserPaddingBottom & inside); 12548 left = scrollX + (mPaddingLeft & inside); 12549 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12550 bottom = top + size; 12551 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12552 if (invalidate) { 12553 invalidate(left, top, right, bottom); 12554 } 12555 } 12556 12557 if (drawVerticalScrollBar) { 12558 int size = scrollBar.getSize(true); 12559 if (size <= 0) { 12560 size = cache.scrollBarSize; 12561 } 12562 12563 scrollBar.setParameters(computeVerticalScrollRange(), 12564 computeVerticalScrollOffset(), 12565 computeVerticalScrollExtent(), true); 12566 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12567 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12568 verticalScrollbarPosition = isLayoutRtl() ? 12569 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12570 } 12571 switch (verticalScrollbarPosition) { 12572 default: 12573 case SCROLLBAR_POSITION_RIGHT: 12574 left = scrollX + width - size - (mUserPaddingRight & inside); 12575 break; 12576 case SCROLLBAR_POSITION_LEFT: 12577 left = scrollX + (mUserPaddingLeft & inside); 12578 break; 12579 } 12580 top = scrollY + (mPaddingTop & inside); 12581 right = left + size; 12582 bottom = scrollY + height - (mUserPaddingBottom & inside); 12583 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12584 if (invalidate) { 12585 invalidate(left, top, right, bottom); 12586 } 12587 } 12588 } 12589 } 12590 } 12591 12592 /** 12593 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12594 * FastScroller is visible. 12595 * @return whether to temporarily hide the vertical scrollbar 12596 * @hide 12597 */ 12598 protected boolean isVerticalScrollBarHidden() { 12599 return false; 12600 } 12601 12602 /** 12603 * <p>Draw the horizontal scrollbar if 12604 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12605 * 12606 * @param canvas the canvas on which to draw the scrollbar 12607 * @param scrollBar the scrollbar's drawable 12608 * 12609 * @see #isHorizontalScrollBarEnabled() 12610 * @see #computeHorizontalScrollRange() 12611 * @see #computeHorizontalScrollExtent() 12612 * @see #computeHorizontalScrollOffset() 12613 * @see android.widget.ScrollBarDrawable 12614 * @hide 12615 */ 12616 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12617 int l, int t, int r, int b) { 12618 scrollBar.setBounds(l, t, r, b); 12619 scrollBar.draw(canvas); 12620 } 12621 12622 /** 12623 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12624 * returns true.</p> 12625 * 12626 * @param canvas the canvas on which to draw the scrollbar 12627 * @param scrollBar the scrollbar's drawable 12628 * 12629 * @see #isVerticalScrollBarEnabled() 12630 * @see #computeVerticalScrollRange() 12631 * @see #computeVerticalScrollExtent() 12632 * @see #computeVerticalScrollOffset() 12633 * @see android.widget.ScrollBarDrawable 12634 * @hide 12635 */ 12636 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12637 int l, int t, int r, int b) { 12638 scrollBar.setBounds(l, t, r, b); 12639 scrollBar.draw(canvas); 12640 } 12641 12642 /** 12643 * Implement this to do your drawing. 12644 * 12645 * @param canvas the canvas on which the background will be drawn 12646 */ 12647 protected void onDraw(Canvas canvas) { 12648 } 12649 12650 /* 12651 * Caller is responsible for calling requestLayout if necessary. 12652 * (This allows addViewInLayout to not request a new layout.) 12653 */ 12654 void assignParent(ViewParent parent) { 12655 if (mParent == null) { 12656 mParent = parent; 12657 } else if (parent == null) { 12658 mParent = null; 12659 } else { 12660 throw new RuntimeException("view " + this + " being added, but" 12661 + " it already has a parent"); 12662 } 12663 } 12664 12665 /** 12666 * This is called when the view is attached to a window. At this point it 12667 * has a Surface and will start drawing. Note that this function is 12668 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12669 * however it may be called any time before the first onDraw -- including 12670 * before or after {@link #onMeasure(int, int)}. 12671 * 12672 * @see #onDetachedFromWindow() 12673 */ 12674 protected void onAttachedToWindow() { 12675 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12676 mParent.requestTransparentRegion(this); 12677 } 12678 12679 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12680 initialAwakenScrollBars(); 12681 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12682 } 12683 12684 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12685 12686 jumpDrawablesToCurrentState(); 12687 12688 resetSubtreeAccessibilityStateChanged(); 12689 12690 invalidateOutline(); 12691 12692 if (isFocused()) { 12693 InputMethodManager imm = InputMethodManager.peekInstance(); 12694 imm.focusIn(this); 12695 } 12696 } 12697 12698 /** 12699 * Resolve all RTL related properties. 12700 * 12701 * @return true if resolution of RTL properties has been done 12702 * 12703 * @hide 12704 */ 12705 public boolean resolveRtlPropertiesIfNeeded() { 12706 if (!needRtlPropertiesResolution()) return false; 12707 12708 // Order is important here: LayoutDirection MUST be resolved first 12709 if (!isLayoutDirectionResolved()) { 12710 resolveLayoutDirection(); 12711 resolveLayoutParams(); 12712 } 12713 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12714 if (!isTextDirectionResolved()) { 12715 resolveTextDirection(); 12716 } 12717 if (!isTextAlignmentResolved()) { 12718 resolveTextAlignment(); 12719 } 12720 // Should resolve Drawables before Padding because we need the layout direction of the 12721 // Drawable to correctly resolve Padding. 12722 if (!isDrawablesResolved()) { 12723 resolveDrawables(); 12724 } 12725 if (!isPaddingResolved()) { 12726 resolvePadding(); 12727 } 12728 onRtlPropertiesChanged(getLayoutDirection()); 12729 return true; 12730 } 12731 12732 /** 12733 * Reset resolution of all RTL related properties. 12734 * 12735 * @hide 12736 */ 12737 public void resetRtlProperties() { 12738 resetResolvedLayoutDirection(); 12739 resetResolvedTextDirection(); 12740 resetResolvedTextAlignment(); 12741 resetResolvedPadding(); 12742 resetResolvedDrawables(); 12743 } 12744 12745 /** 12746 * @see #onScreenStateChanged(int) 12747 */ 12748 void dispatchScreenStateChanged(int screenState) { 12749 onScreenStateChanged(screenState); 12750 } 12751 12752 /** 12753 * This method is called whenever the state of the screen this view is 12754 * attached to changes. A state change will usually occurs when the screen 12755 * turns on or off (whether it happens automatically or the user does it 12756 * manually.) 12757 * 12758 * @param screenState The new state of the screen. Can be either 12759 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12760 */ 12761 public void onScreenStateChanged(int screenState) { 12762 } 12763 12764 /** 12765 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12766 */ 12767 private boolean hasRtlSupport() { 12768 return mContext.getApplicationInfo().hasRtlSupport(); 12769 } 12770 12771 /** 12772 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12773 * RTL not supported) 12774 */ 12775 private boolean isRtlCompatibilityMode() { 12776 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12777 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12778 } 12779 12780 /** 12781 * @return true if RTL properties need resolution. 12782 * 12783 */ 12784 private boolean needRtlPropertiesResolution() { 12785 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12786 } 12787 12788 /** 12789 * Called when any RTL property (layout direction or text direction or text alignment) has 12790 * been changed. 12791 * 12792 * Subclasses need to override this method to take care of cached information that depends on the 12793 * resolved layout direction, or to inform child views that inherit their layout direction. 12794 * 12795 * The default implementation does nothing. 12796 * 12797 * @param layoutDirection the direction of the layout 12798 * 12799 * @see #LAYOUT_DIRECTION_LTR 12800 * @see #LAYOUT_DIRECTION_RTL 12801 */ 12802 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12803 } 12804 12805 /** 12806 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12807 * that the parent directionality can and will be resolved before its children. 12808 * 12809 * @return true if resolution has been done, false otherwise. 12810 * 12811 * @hide 12812 */ 12813 public boolean resolveLayoutDirection() { 12814 // Clear any previous layout direction resolution 12815 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12816 12817 if (hasRtlSupport()) { 12818 // Set resolved depending on layout direction 12819 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12820 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12821 case LAYOUT_DIRECTION_INHERIT: 12822 // We cannot resolve yet. LTR is by default and let the resolution happen again 12823 // later to get the correct resolved value 12824 if (!canResolveLayoutDirection()) return false; 12825 12826 // Parent has not yet resolved, LTR is still the default 12827 try { 12828 if (!mParent.isLayoutDirectionResolved()) return false; 12829 12830 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12831 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12832 } 12833 } catch (AbstractMethodError e) { 12834 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12835 " does not fully implement ViewParent", e); 12836 } 12837 break; 12838 case LAYOUT_DIRECTION_RTL: 12839 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12840 break; 12841 case LAYOUT_DIRECTION_LOCALE: 12842 if((LAYOUT_DIRECTION_RTL == 12843 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12844 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12845 } 12846 break; 12847 default: 12848 // Nothing to do, LTR by default 12849 } 12850 } 12851 12852 // Set to resolved 12853 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12854 return true; 12855 } 12856 12857 /** 12858 * Check if layout direction resolution can be done. 12859 * 12860 * @return true if layout direction resolution can be done otherwise return false. 12861 */ 12862 public boolean canResolveLayoutDirection() { 12863 switch (getRawLayoutDirection()) { 12864 case LAYOUT_DIRECTION_INHERIT: 12865 if (mParent != null) { 12866 try { 12867 return mParent.canResolveLayoutDirection(); 12868 } catch (AbstractMethodError e) { 12869 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12870 " does not fully implement ViewParent", e); 12871 } 12872 } 12873 return false; 12874 12875 default: 12876 return true; 12877 } 12878 } 12879 12880 /** 12881 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12882 * {@link #onMeasure(int, int)}. 12883 * 12884 * @hide 12885 */ 12886 public void resetResolvedLayoutDirection() { 12887 // Reset the current resolved bits 12888 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12889 } 12890 12891 /** 12892 * @return true if the layout direction is inherited. 12893 * 12894 * @hide 12895 */ 12896 public boolean isLayoutDirectionInherited() { 12897 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12898 } 12899 12900 /** 12901 * @return true if layout direction has been resolved. 12902 */ 12903 public boolean isLayoutDirectionResolved() { 12904 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12905 } 12906 12907 /** 12908 * Return if padding has been resolved 12909 * 12910 * @hide 12911 */ 12912 boolean isPaddingResolved() { 12913 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12914 } 12915 12916 /** 12917 * Resolves padding depending on layout direction, if applicable, and 12918 * recomputes internal padding values to adjust for scroll bars. 12919 * 12920 * @hide 12921 */ 12922 public void resolvePadding() { 12923 final int resolvedLayoutDirection = getLayoutDirection(); 12924 12925 if (!isRtlCompatibilityMode()) { 12926 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12927 // If start / end padding are defined, they will be resolved (hence overriding) to 12928 // left / right or right / left depending on the resolved layout direction. 12929 // If start / end padding are not defined, use the left / right ones. 12930 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12931 Rect padding = sThreadLocal.get(); 12932 if (padding == null) { 12933 padding = new Rect(); 12934 sThreadLocal.set(padding); 12935 } 12936 mBackground.getPadding(padding); 12937 if (!mLeftPaddingDefined) { 12938 mUserPaddingLeftInitial = padding.left; 12939 } 12940 if (!mRightPaddingDefined) { 12941 mUserPaddingRightInitial = padding.right; 12942 } 12943 } 12944 switch (resolvedLayoutDirection) { 12945 case LAYOUT_DIRECTION_RTL: 12946 if (mUserPaddingStart != UNDEFINED_PADDING) { 12947 mUserPaddingRight = mUserPaddingStart; 12948 } else { 12949 mUserPaddingRight = mUserPaddingRightInitial; 12950 } 12951 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12952 mUserPaddingLeft = mUserPaddingEnd; 12953 } else { 12954 mUserPaddingLeft = mUserPaddingLeftInitial; 12955 } 12956 break; 12957 case LAYOUT_DIRECTION_LTR: 12958 default: 12959 if (mUserPaddingStart != UNDEFINED_PADDING) { 12960 mUserPaddingLeft = mUserPaddingStart; 12961 } else { 12962 mUserPaddingLeft = mUserPaddingLeftInitial; 12963 } 12964 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12965 mUserPaddingRight = mUserPaddingEnd; 12966 } else { 12967 mUserPaddingRight = mUserPaddingRightInitial; 12968 } 12969 } 12970 12971 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12972 } 12973 12974 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12975 onRtlPropertiesChanged(resolvedLayoutDirection); 12976 12977 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12978 } 12979 12980 /** 12981 * Reset the resolved layout direction. 12982 * 12983 * @hide 12984 */ 12985 public void resetResolvedPadding() { 12986 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12987 } 12988 12989 /** 12990 * This is called when the view is detached from a window. At this point it 12991 * no longer has a surface for drawing. 12992 * 12993 * @see #onAttachedToWindow() 12994 */ 12995 protected void onDetachedFromWindow() { 12996 } 12997 12998 /** 12999 * This is a framework-internal mirror of onDetachedFromWindow() that's called 13000 * after onDetachedFromWindow(). 13001 * 13002 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 13003 * The super method should be called at the end of the overriden method to ensure 13004 * subclasses are destroyed first 13005 * 13006 * @hide 13007 */ 13008 protected void onDetachedFromWindowInternal() { 13009 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 13010 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13011 13012 removeUnsetPressCallback(); 13013 removeLongPressCallback(); 13014 removePerformClickCallback(); 13015 removeSendViewScrolledAccessibilityEventCallback(); 13016 stopNestedScroll(); 13017 13018 destroyDrawingCache(); 13019 13020 cleanupDraw(); 13021 mCurrentAnimation = null; 13022 } 13023 13024 private void cleanupDraw() { 13025 resetDisplayList(); 13026 if (mAttachInfo != null) { 13027 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 13028 } 13029 } 13030 13031 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 13032 } 13033 13034 /** 13035 * @return The number of times this view has been attached to a window 13036 */ 13037 protected int getWindowAttachCount() { 13038 return mWindowAttachCount; 13039 } 13040 13041 /** 13042 * Retrieve a unique token identifying the window this view is attached to. 13043 * @return Return the window's token for use in 13044 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13045 */ 13046 public IBinder getWindowToken() { 13047 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13048 } 13049 13050 /** 13051 * Retrieve the {@link WindowId} for the window this view is 13052 * currently attached to. 13053 */ 13054 public WindowId getWindowId() { 13055 if (mAttachInfo == null) { 13056 return null; 13057 } 13058 if (mAttachInfo.mWindowId == null) { 13059 try { 13060 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13061 mAttachInfo.mWindowToken); 13062 mAttachInfo.mWindowId = new WindowId( 13063 mAttachInfo.mIWindowId); 13064 } catch (RemoteException e) { 13065 } 13066 } 13067 return mAttachInfo.mWindowId; 13068 } 13069 13070 /** 13071 * Retrieve a unique token identifying the top-level "real" window of 13072 * the window that this view is attached to. That is, this is like 13073 * {@link #getWindowToken}, except if the window this view in is a panel 13074 * window (attached to another containing window), then the token of 13075 * the containing window is returned instead. 13076 * 13077 * @return Returns the associated window token, either 13078 * {@link #getWindowToken()} or the containing window's token. 13079 */ 13080 public IBinder getApplicationWindowToken() { 13081 AttachInfo ai = mAttachInfo; 13082 if (ai != null) { 13083 IBinder appWindowToken = ai.mPanelParentWindowToken; 13084 if (appWindowToken == null) { 13085 appWindowToken = ai.mWindowToken; 13086 } 13087 return appWindowToken; 13088 } 13089 return null; 13090 } 13091 13092 /** 13093 * Gets the logical display to which the view's window has been attached. 13094 * 13095 * @return The logical display, or null if the view is not currently attached to a window. 13096 */ 13097 public Display getDisplay() { 13098 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13099 } 13100 13101 /** 13102 * Retrieve private session object this view hierarchy is using to 13103 * communicate with the window manager. 13104 * @return the session object to communicate with the window manager 13105 */ 13106 /*package*/ IWindowSession getWindowSession() { 13107 return mAttachInfo != null ? mAttachInfo.mSession : null; 13108 } 13109 13110 /** 13111 * @param info the {@link android.view.View.AttachInfo} to associated with 13112 * this view 13113 */ 13114 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13115 //System.out.println("Attached! " + this); 13116 mAttachInfo = info; 13117 if (mOverlay != null) { 13118 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13119 } 13120 mWindowAttachCount++; 13121 // We will need to evaluate the drawable state at least once. 13122 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13123 if (mFloatingTreeObserver != null) { 13124 info.mTreeObserver.merge(mFloatingTreeObserver); 13125 mFloatingTreeObserver = null; 13126 } 13127 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13128 mAttachInfo.mScrollContainers.add(this); 13129 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13130 } 13131 performCollectViewAttributes(mAttachInfo, visibility); 13132 onAttachedToWindow(); 13133 13134 ListenerInfo li = mListenerInfo; 13135 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13136 li != null ? li.mOnAttachStateChangeListeners : null; 13137 if (listeners != null && listeners.size() > 0) { 13138 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13139 // perform the dispatching. The iterator is a safe guard against listeners that 13140 // could mutate the list by calling the various add/remove methods. This prevents 13141 // the array from being modified while we iterate it. 13142 for (OnAttachStateChangeListener listener : listeners) { 13143 listener.onViewAttachedToWindow(this); 13144 } 13145 } 13146 13147 int vis = info.mWindowVisibility; 13148 if (vis != GONE) { 13149 onWindowVisibilityChanged(vis); 13150 } 13151 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13152 // If nobody has evaluated the drawable state yet, then do it now. 13153 refreshDrawableState(); 13154 } 13155 needGlobalAttributesUpdate(false); 13156 } 13157 13158 void dispatchDetachedFromWindow() { 13159 AttachInfo info = mAttachInfo; 13160 if (info != null) { 13161 int vis = info.mWindowVisibility; 13162 if (vis != GONE) { 13163 onWindowVisibilityChanged(GONE); 13164 } 13165 } 13166 13167 onDetachedFromWindow(); 13168 onDetachedFromWindowInternal(); 13169 13170 ListenerInfo li = mListenerInfo; 13171 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13172 li != null ? li.mOnAttachStateChangeListeners : null; 13173 if (listeners != null && listeners.size() > 0) { 13174 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13175 // perform the dispatching. The iterator is a safe guard against listeners that 13176 // could mutate the list by calling the various add/remove methods. This prevents 13177 // the array from being modified while we iterate it. 13178 for (OnAttachStateChangeListener listener : listeners) { 13179 listener.onViewDetachedFromWindow(this); 13180 } 13181 } 13182 13183 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13184 mAttachInfo.mScrollContainers.remove(this); 13185 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13186 } 13187 13188 mAttachInfo = null; 13189 if (mOverlay != null) { 13190 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13191 } 13192 } 13193 13194 /** 13195 * Cancel any deferred high-level input events that were previously posted to the event queue. 13196 * 13197 * <p>Many views post high-level events such as click handlers to the event queue 13198 * to run deferred in order to preserve a desired user experience - clearing visible 13199 * pressed states before executing, etc. This method will abort any events of this nature 13200 * that are currently in flight.</p> 13201 * 13202 * <p>Custom views that generate their own high-level deferred input events should override 13203 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13204 * 13205 * <p>This will also cancel pending input events for any child views.</p> 13206 * 13207 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13208 * This will not impact newer events posted after this call that may occur as a result of 13209 * lower-level input events still waiting in the queue. If you are trying to prevent 13210 * double-submitted events for the duration of some sort of asynchronous transaction 13211 * you should also take other steps to protect against unexpected double inputs e.g. calling 13212 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13213 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13214 */ 13215 public final void cancelPendingInputEvents() { 13216 dispatchCancelPendingInputEvents(); 13217 } 13218 13219 /** 13220 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13221 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13222 */ 13223 void dispatchCancelPendingInputEvents() { 13224 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13225 onCancelPendingInputEvents(); 13226 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13227 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13228 " did not call through to super.onCancelPendingInputEvents()"); 13229 } 13230 } 13231 13232 /** 13233 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13234 * a parent view. 13235 * 13236 * <p>This method is responsible for removing any pending high-level input events that were 13237 * posted to the event queue to run later. Custom view classes that post their own deferred 13238 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13239 * {@link android.os.Handler} should override this method, call 13240 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13241 * </p> 13242 */ 13243 public void onCancelPendingInputEvents() { 13244 removePerformClickCallback(); 13245 cancelLongPress(); 13246 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13247 } 13248 13249 /** 13250 * Store this view hierarchy's frozen state into the given container. 13251 * 13252 * @param container The SparseArray in which to save the view's state. 13253 * 13254 * @see #restoreHierarchyState(android.util.SparseArray) 13255 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13256 * @see #onSaveInstanceState() 13257 */ 13258 public void saveHierarchyState(SparseArray<Parcelable> container) { 13259 dispatchSaveInstanceState(container); 13260 } 13261 13262 /** 13263 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13264 * this view and its children. May be overridden to modify how freezing happens to a 13265 * view's children; for example, some views may want to not store state for their children. 13266 * 13267 * @param container The SparseArray in which to save the view's state. 13268 * 13269 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13270 * @see #saveHierarchyState(android.util.SparseArray) 13271 * @see #onSaveInstanceState() 13272 */ 13273 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13274 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13275 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13276 Parcelable state = onSaveInstanceState(); 13277 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13278 throw new IllegalStateException( 13279 "Derived class did not call super.onSaveInstanceState()"); 13280 } 13281 if (state != null) { 13282 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13283 // + ": " + state); 13284 container.put(mID, state); 13285 } 13286 } 13287 } 13288 13289 /** 13290 * Hook allowing a view to generate a representation of its internal state 13291 * that can later be used to create a new instance with that same state. 13292 * This state should only contain information that is not persistent or can 13293 * not be reconstructed later. For example, you will never store your 13294 * current position on screen because that will be computed again when a 13295 * new instance of the view is placed in its view hierarchy. 13296 * <p> 13297 * Some examples of things you may store here: the current cursor position 13298 * in a text view (but usually not the text itself since that is stored in a 13299 * content provider or other persistent storage), the currently selected 13300 * item in a list view. 13301 * 13302 * @return Returns a Parcelable object containing the view's current dynamic 13303 * state, or null if there is nothing interesting to save. The 13304 * default implementation returns null. 13305 * @see #onRestoreInstanceState(android.os.Parcelable) 13306 * @see #saveHierarchyState(android.util.SparseArray) 13307 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13308 * @see #setSaveEnabled(boolean) 13309 */ 13310 protected Parcelable onSaveInstanceState() { 13311 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13312 return BaseSavedState.EMPTY_STATE; 13313 } 13314 13315 /** 13316 * Restore this view hierarchy's frozen state from the given container. 13317 * 13318 * @param container The SparseArray which holds previously frozen states. 13319 * 13320 * @see #saveHierarchyState(android.util.SparseArray) 13321 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13322 * @see #onRestoreInstanceState(android.os.Parcelable) 13323 */ 13324 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13325 dispatchRestoreInstanceState(container); 13326 } 13327 13328 /** 13329 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13330 * state for this view and its children. May be overridden to modify how restoring 13331 * happens to a view's children; for example, some views may want to not store state 13332 * for their children. 13333 * 13334 * @param container The SparseArray which holds previously saved state. 13335 * 13336 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13337 * @see #restoreHierarchyState(android.util.SparseArray) 13338 * @see #onRestoreInstanceState(android.os.Parcelable) 13339 */ 13340 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13341 if (mID != NO_ID) { 13342 Parcelable state = container.get(mID); 13343 if (state != null) { 13344 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13345 // + ": " + state); 13346 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13347 onRestoreInstanceState(state); 13348 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13349 throw new IllegalStateException( 13350 "Derived class did not call super.onRestoreInstanceState()"); 13351 } 13352 } 13353 } 13354 } 13355 13356 /** 13357 * Hook allowing a view to re-apply a representation of its internal state that had previously 13358 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13359 * null state. 13360 * 13361 * @param state The frozen state that had previously been returned by 13362 * {@link #onSaveInstanceState}. 13363 * 13364 * @see #onSaveInstanceState() 13365 * @see #restoreHierarchyState(android.util.SparseArray) 13366 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13367 */ 13368 protected void onRestoreInstanceState(Parcelable state) { 13369 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13370 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13371 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13372 + "received " + state.getClass().toString() + " instead. This usually happens " 13373 + "when two views of different type have the same id in the same hierarchy. " 13374 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13375 + "other views do not use the same id."); 13376 } 13377 } 13378 13379 /** 13380 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13381 * 13382 * @return the drawing start time in milliseconds 13383 */ 13384 public long getDrawingTime() { 13385 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13386 } 13387 13388 /** 13389 * <p>Enables or disables the duplication of the parent's state into this view. When 13390 * duplication is enabled, this view gets its drawable state from its parent rather 13391 * than from its own internal properties.</p> 13392 * 13393 * <p>Note: in the current implementation, setting this property to true after the 13394 * view was added to a ViewGroup might have no effect at all. This property should 13395 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13396 * 13397 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13398 * property is enabled, an exception will be thrown.</p> 13399 * 13400 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13401 * parent, these states should not be affected by this method.</p> 13402 * 13403 * @param enabled True to enable duplication of the parent's drawable state, false 13404 * to disable it. 13405 * 13406 * @see #getDrawableState() 13407 * @see #isDuplicateParentStateEnabled() 13408 */ 13409 public void setDuplicateParentStateEnabled(boolean enabled) { 13410 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13411 } 13412 13413 /** 13414 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13415 * 13416 * @return True if this view's drawable state is duplicated from the parent, 13417 * false otherwise 13418 * 13419 * @see #getDrawableState() 13420 * @see #setDuplicateParentStateEnabled(boolean) 13421 */ 13422 public boolean isDuplicateParentStateEnabled() { 13423 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13424 } 13425 13426 /** 13427 * <p>Specifies the type of layer backing this view. The layer can be 13428 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13429 * {@link #LAYER_TYPE_HARDWARE}.</p> 13430 * 13431 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13432 * instance that controls how the layer is composed on screen. The following 13433 * properties of the paint are taken into account when composing the layer:</p> 13434 * <ul> 13435 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13436 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13437 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13438 * </ul> 13439 * 13440 * <p>If this view has an alpha value set to < 1.0 by calling 13441 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13442 * by this view's alpha value.</p> 13443 * 13444 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13445 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13446 * for more information on when and how to use layers.</p> 13447 * 13448 * @param layerType The type of layer to use with this view, must be one of 13449 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13450 * {@link #LAYER_TYPE_HARDWARE} 13451 * @param paint The paint used to compose the layer. This argument is optional 13452 * and can be null. It is ignored when the layer type is 13453 * {@link #LAYER_TYPE_NONE} 13454 * 13455 * @see #getLayerType() 13456 * @see #LAYER_TYPE_NONE 13457 * @see #LAYER_TYPE_SOFTWARE 13458 * @see #LAYER_TYPE_HARDWARE 13459 * @see #setAlpha(float) 13460 * 13461 * @attr ref android.R.styleable#View_layerType 13462 */ 13463 public void setLayerType(int layerType, Paint paint) { 13464 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13465 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13466 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13467 } 13468 13469 boolean typeChanged = mRenderNode.setLayerType(layerType); 13470 13471 if (!typeChanged) { 13472 setLayerPaint(paint); 13473 return; 13474 } 13475 13476 // Destroy any previous software drawing cache if needed 13477 if (mLayerType == LAYER_TYPE_SOFTWARE) { 13478 destroyDrawingCache(); 13479 } 13480 13481 mLayerType = layerType; 13482 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 13483 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13484 mRenderNode.setLayerPaint(mLayerPaint); 13485 13486 // draw() behaves differently if we are on a layer, so we need to 13487 // invalidate() here 13488 invalidateParentCaches(); 13489 invalidate(true); 13490 } 13491 13492 /** 13493 * Updates the {@link Paint} object used with the current layer (used only if the current 13494 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13495 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13496 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13497 * ensure that the view gets redrawn immediately. 13498 * 13499 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13500 * instance that controls how the layer is composed on screen. The following 13501 * properties of the paint are taken into account when composing the layer:</p> 13502 * <ul> 13503 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13504 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13505 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13506 * </ul> 13507 * 13508 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13509 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13510 * 13511 * @param paint The paint used to compose the layer. This argument is optional 13512 * and can be null. It is ignored when the layer type is 13513 * {@link #LAYER_TYPE_NONE} 13514 * 13515 * @see #setLayerType(int, android.graphics.Paint) 13516 */ 13517 public void setLayerPaint(Paint paint) { 13518 int layerType = getLayerType(); 13519 if (layerType != LAYER_TYPE_NONE) { 13520 mLayerPaint = paint == null ? new Paint() : paint; 13521 if (layerType == LAYER_TYPE_HARDWARE) { 13522 if (mRenderNode.setLayerPaint(mLayerPaint)) { 13523 invalidateViewProperty(false, false); 13524 } 13525 } else { 13526 invalidate(); 13527 } 13528 } 13529 } 13530 13531 /** 13532 * Indicates whether this view has a static layer. A view with layer type 13533 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13534 * dynamic. 13535 */ 13536 boolean hasStaticLayer() { 13537 return true; 13538 } 13539 13540 /** 13541 * Indicates what type of layer is currently associated with this view. By default 13542 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13543 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13544 * for more information on the different types of layers. 13545 * 13546 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13547 * {@link #LAYER_TYPE_HARDWARE} 13548 * 13549 * @see #setLayerType(int, android.graphics.Paint) 13550 * @see #buildLayer() 13551 * @see #LAYER_TYPE_NONE 13552 * @see #LAYER_TYPE_SOFTWARE 13553 * @see #LAYER_TYPE_HARDWARE 13554 */ 13555 public int getLayerType() { 13556 return mLayerType; 13557 } 13558 13559 /** 13560 * Forces this view's layer to be created and this view to be rendered 13561 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13562 * invoking this method will have no effect. 13563 * 13564 * This method can for instance be used to render a view into its layer before 13565 * starting an animation. If this view is complex, rendering into the layer 13566 * before starting the animation will avoid skipping frames. 13567 * 13568 * @throws IllegalStateException If this view is not attached to a window 13569 * 13570 * @see #setLayerType(int, android.graphics.Paint) 13571 */ 13572 public void buildLayer() { 13573 if (mLayerType == LAYER_TYPE_NONE) return; 13574 13575 final AttachInfo attachInfo = mAttachInfo; 13576 if (attachInfo == null) { 13577 throw new IllegalStateException("This view must be attached to a window first"); 13578 } 13579 13580 if (getWidth() == 0 || getHeight() == 0) { 13581 return; 13582 } 13583 13584 switch (mLayerType) { 13585 case LAYER_TYPE_HARDWARE: 13586 // The only part of a hardware layer we can build in response to 13587 // this call is to ensure the display list is up to date. 13588 // The actual rendering of the display list into the layer must 13589 // be done at playback time 13590 updateDisplayListIfDirty(); 13591 break; 13592 case LAYER_TYPE_SOFTWARE: 13593 buildDrawingCache(true); 13594 break; 13595 } 13596 } 13597 13598 /** 13599 * If this View draws with a HardwareLayer, returns it. 13600 * Otherwise returns null 13601 * 13602 * TODO: Only TextureView uses this, can we eliminate it? 13603 */ 13604 HardwareLayer getHardwareLayer() { 13605 return null; 13606 } 13607 13608 /** 13609 * Destroys all hardware rendering resources. This method is invoked 13610 * when the system needs to reclaim resources. Upon execution of this 13611 * method, you should free any OpenGL resources created by the view. 13612 * 13613 * Note: you <strong>must</strong> call 13614 * <code>super.destroyHardwareResources()</code> when overriding 13615 * this method. 13616 * 13617 * @hide 13618 */ 13619 protected void destroyHardwareResources() { 13620 // Although the Layer will be destroyed by RenderNode, we want to release 13621 // the staging display list, which is also a signal to RenderNode that it's 13622 // safe to free its copy of the display list as it knows that we will 13623 // push an updated DisplayList if we try to draw again 13624 resetDisplayList(); 13625 } 13626 13627 /** 13628 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13629 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13630 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13631 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13632 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13633 * null.</p> 13634 * 13635 * <p>Enabling the drawing cache is similar to 13636 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13637 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13638 * drawing cache has no effect on rendering because the system uses a different mechanism 13639 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13640 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13641 * for information on how to enable software and hardware layers.</p> 13642 * 13643 * <p>This API can be used to manually generate 13644 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13645 * {@link #getDrawingCache()}.</p> 13646 * 13647 * @param enabled true to enable the drawing cache, false otherwise 13648 * 13649 * @see #isDrawingCacheEnabled() 13650 * @see #getDrawingCache() 13651 * @see #buildDrawingCache() 13652 * @see #setLayerType(int, android.graphics.Paint) 13653 */ 13654 public void setDrawingCacheEnabled(boolean enabled) { 13655 mCachingFailed = false; 13656 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13657 } 13658 13659 /** 13660 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13661 * 13662 * @return true if the drawing cache is enabled 13663 * 13664 * @see #setDrawingCacheEnabled(boolean) 13665 * @see #getDrawingCache() 13666 */ 13667 @ViewDebug.ExportedProperty(category = "drawing") 13668 public boolean isDrawingCacheEnabled() { 13669 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13670 } 13671 13672 /** 13673 * Debugging utility which recursively outputs the dirty state of a view and its 13674 * descendants. 13675 * 13676 * @hide 13677 */ 13678 @SuppressWarnings({"UnusedDeclaration"}) 13679 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13680 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13681 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13682 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13683 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13684 if (clear) { 13685 mPrivateFlags &= clearMask; 13686 } 13687 if (this instanceof ViewGroup) { 13688 ViewGroup parent = (ViewGroup) this; 13689 final int count = parent.getChildCount(); 13690 for (int i = 0; i < count; i++) { 13691 final View child = parent.getChildAt(i); 13692 child.outputDirtyFlags(indent + " ", clear, clearMask); 13693 } 13694 } 13695 } 13696 13697 /** 13698 * This method is used by ViewGroup to cause its children to restore or recreate their 13699 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13700 * to recreate its own display list, which would happen if it went through the normal 13701 * draw/dispatchDraw mechanisms. 13702 * 13703 * @hide 13704 */ 13705 protected void dispatchGetDisplayList() {} 13706 13707 /** 13708 * A view that is not attached or hardware accelerated cannot create a display list. 13709 * This method checks these conditions and returns the appropriate result. 13710 * 13711 * @return true if view has the ability to create a display list, false otherwise. 13712 * 13713 * @hide 13714 */ 13715 public boolean canHaveDisplayList() { 13716 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13717 } 13718 13719 private void updateDisplayListIfDirty() { 13720 final RenderNode renderNode = mRenderNode; 13721 if (!canHaveDisplayList()) { 13722 // can't populate RenderNode, don't try 13723 return; 13724 } 13725 13726 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13727 || !renderNode.isValid() 13728 || (mRecreateDisplayList)) { 13729 // Don't need to recreate the display list, just need to tell our 13730 // children to restore/recreate theirs 13731 if (renderNode.isValid() 13732 && !mRecreateDisplayList) { 13733 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13734 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13735 dispatchGetDisplayList(); 13736 13737 return; // no work needed 13738 } 13739 13740 // If we got here, we're recreating it. Mark it as such to ensure that 13741 // we copy in child display lists into ours in drawChild() 13742 mRecreateDisplayList = true; 13743 13744 int width = mRight - mLeft; 13745 int height = mBottom - mTop; 13746 int layerType = getLayerType(); 13747 13748 final HardwareCanvas canvas = renderNode.start(width, height); 13749 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 13750 13751 try { 13752 final HardwareLayer layer = getHardwareLayer(); 13753 if (layer != null && layer.isValid()) { 13754 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13755 } else if (layerType == LAYER_TYPE_SOFTWARE) { 13756 buildDrawingCache(true); 13757 Bitmap cache = getDrawingCache(true); 13758 if (cache != null) { 13759 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13760 } 13761 } else { 13762 computeScroll(); 13763 13764 canvas.translate(-mScrollX, -mScrollY); 13765 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13766 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13767 13768 // Fast path for layouts with no backgrounds 13769 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13770 dispatchDraw(canvas); 13771 if (mOverlay != null && !mOverlay.isEmpty()) { 13772 mOverlay.getOverlayView().draw(canvas); 13773 } 13774 } else { 13775 draw(canvas); 13776 } 13777 } 13778 } finally { 13779 renderNode.end(canvas); 13780 setDisplayListProperties(renderNode); 13781 } 13782 } else { 13783 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13784 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13785 } 13786 } 13787 13788 /** 13789 * Returns a RenderNode with View draw content recorded, which can be 13790 * used to draw this view again without executing its draw method. 13791 * 13792 * @return A RenderNode ready to replay, or null if caching is not enabled. 13793 * 13794 * @hide 13795 */ 13796 public RenderNode getDisplayList() { 13797 updateDisplayListIfDirty(); 13798 return mRenderNode; 13799 } 13800 13801 private void resetDisplayList() { 13802 if (mRenderNode.isValid()) { 13803 mRenderNode.destroyDisplayListData(); 13804 } 13805 13806 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 13807 mBackgroundRenderNode.destroyDisplayListData(); 13808 } 13809 } 13810 13811 /** 13812 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13813 * 13814 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13815 * 13816 * @see #getDrawingCache(boolean) 13817 */ 13818 public Bitmap getDrawingCache() { 13819 return getDrawingCache(false); 13820 } 13821 13822 /** 13823 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13824 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13825 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13826 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13827 * request the drawing cache by calling this method and draw it on screen if the 13828 * returned bitmap is not null.</p> 13829 * 13830 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13831 * this method will create a bitmap of the same size as this view. Because this bitmap 13832 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13833 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13834 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13835 * size than the view. This implies that your application must be able to handle this 13836 * size.</p> 13837 * 13838 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13839 * the current density of the screen when the application is in compatibility 13840 * mode. 13841 * 13842 * @return A bitmap representing this view or null if cache is disabled. 13843 * 13844 * @see #setDrawingCacheEnabled(boolean) 13845 * @see #isDrawingCacheEnabled() 13846 * @see #buildDrawingCache(boolean) 13847 * @see #destroyDrawingCache() 13848 */ 13849 public Bitmap getDrawingCache(boolean autoScale) { 13850 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13851 return null; 13852 } 13853 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13854 buildDrawingCache(autoScale); 13855 } 13856 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13857 } 13858 13859 /** 13860 * <p>Frees the resources used by the drawing cache. If you call 13861 * {@link #buildDrawingCache()} manually without calling 13862 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13863 * should cleanup the cache with this method afterwards.</p> 13864 * 13865 * @see #setDrawingCacheEnabled(boolean) 13866 * @see #buildDrawingCache() 13867 * @see #getDrawingCache() 13868 */ 13869 public void destroyDrawingCache() { 13870 if (mDrawingCache != null) { 13871 mDrawingCache.recycle(); 13872 mDrawingCache = null; 13873 } 13874 if (mUnscaledDrawingCache != null) { 13875 mUnscaledDrawingCache.recycle(); 13876 mUnscaledDrawingCache = null; 13877 } 13878 } 13879 13880 /** 13881 * Setting a solid background color for the drawing cache's bitmaps will improve 13882 * performance and memory usage. Note, though that this should only be used if this 13883 * view will always be drawn on top of a solid color. 13884 * 13885 * @param color The background color to use for the drawing cache's bitmap 13886 * 13887 * @see #setDrawingCacheEnabled(boolean) 13888 * @see #buildDrawingCache() 13889 * @see #getDrawingCache() 13890 */ 13891 public void setDrawingCacheBackgroundColor(int color) { 13892 if (color != mDrawingCacheBackgroundColor) { 13893 mDrawingCacheBackgroundColor = color; 13894 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13895 } 13896 } 13897 13898 /** 13899 * @see #setDrawingCacheBackgroundColor(int) 13900 * 13901 * @return The background color to used for the drawing cache's bitmap 13902 */ 13903 public int getDrawingCacheBackgroundColor() { 13904 return mDrawingCacheBackgroundColor; 13905 } 13906 13907 /** 13908 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13909 * 13910 * @see #buildDrawingCache(boolean) 13911 */ 13912 public void buildDrawingCache() { 13913 buildDrawingCache(false); 13914 } 13915 13916 /** 13917 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13918 * 13919 * <p>If you call {@link #buildDrawingCache()} manually without calling 13920 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13921 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13922 * 13923 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13924 * this method will create a bitmap of the same size as this view. Because this bitmap 13925 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13926 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13927 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13928 * size than the view. This implies that your application must be able to handle this 13929 * size.</p> 13930 * 13931 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13932 * you do not need the drawing cache bitmap, calling this method will increase memory 13933 * usage and cause the view to be rendered in software once, thus negatively impacting 13934 * performance.</p> 13935 * 13936 * @see #getDrawingCache() 13937 * @see #destroyDrawingCache() 13938 */ 13939 public void buildDrawingCache(boolean autoScale) { 13940 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13941 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13942 mCachingFailed = false; 13943 13944 int width = mRight - mLeft; 13945 int height = mBottom - mTop; 13946 13947 final AttachInfo attachInfo = mAttachInfo; 13948 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13949 13950 if (autoScale && scalingRequired) { 13951 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13952 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13953 } 13954 13955 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13956 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13957 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13958 13959 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13960 final long drawingCacheSize = 13961 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13962 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13963 if (width > 0 && height > 0) { 13964 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13965 + projectedBitmapSize + " bytes, only " 13966 + drawingCacheSize + " available"); 13967 } 13968 destroyDrawingCache(); 13969 mCachingFailed = true; 13970 return; 13971 } 13972 13973 boolean clear = true; 13974 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13975 13976 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13977 Bitmap.Config quality; 13978 if (!opaque) { 13979 // Never pick ARGB_4444 because it looks awful 13980 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13981 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13982 case DRAWING_CACHE_QUALITY_AUTO: 13983 case DRAWING_CACHE_QUALITY_LOW: 13984 case DRAWING_CACHE_QUALITY_HIGH: 13985 default: 13986 quality = Bitmap.Config.ARGB_8888; 13987 break; 13988 } 13989 } else { 13990 // Optimization for translucent windows 13991 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13992 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13993 } 13994 13995 // Try to cleanup memory 13996 if (bitmap != null) bitmap.recycle(); 13997 13998 try { 13999 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14000 width, height, quality); 14001 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14002 if (autoScale) { 14003 mDrawingCache = bitmap; 14004 } else { 14005 mUnscaledDrawingCache = bitmap; 14006 } 14007 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14008 } catch (OutOfMemoryError e) { 14009 // If there is not enough memory to create the bitmap cache, just 14010 // ignore the issue as bitmap caches are not required to draw the 14011 // view hierarchy 14012 if (autoScale) { 14013 mDrawingCache = null; 14014 } else { 14015 mUnscaledDrawingCache = null; 14016 } 14017 mCachingFailed = true; 14018 return; 14019 } 14020 14021 clear = drawingCacheBackgroundColor != 0; 14022 } 14023 14024 Canvas canvas; 14025 if (attachInfo != null) { 14026 canvas = attachInfo.mCanvas; 14027 if (canvas == null) { 14028 canvas = new Canvas(); 14029 } 14030 canvas.setBitmap(bitmap); 14031 // Temporarily clobber the cached Canvas in case one of our children 14032 // is also using a drawing cache. Without this, the children would 14033 // steal the canvas by attaching their own bitmap to it and bad, bad 14034 // thing would happen (invisible views, corrupted drawings, etc.) 14035 attachInfo.mCanvas = null; 14036 } else { 14037 // This case should hopefully never or seldom happen 14038 canvas = new Canvas(bitmap); 14039 } 14040 14041 if (clear) { 14042 bitmap.eraseColor(drawingCacheBackgroundColor); 14043 } 14044 14045 computeScroll(); 14046 final int restoreCount = canvas.save(); 14047 14048 if (autoScale && scalingRequired) { 14049 final float scale = attachInfo.mApplicationScale; 14050 canvas.scale(scale, scale); 14051 } 14052 14053 canvas.translate(-mScrollX, -mScrollY); 14054 14055 mPrivateFlags |= PFLAG_DRAWN; 14056 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14057 mLayerType != LAYER_TYPE_NONE) { 14058 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14059 } 14060 14061 // Fast path for layouts with no backgrounds 14062 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14063 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14064 dispatchDraw(canvas); 14065 if (mOverlay != null && !mOverlay.isEmpty()) { 14066 mOverlay.getOverlayView().draw(canvas); 14067 } 14068 } else { 14069 draw(canvas); 14070 } 14071 14072 canvas.restoreToCount(restoreCount); 14073 canvas.setBitmap(null); 14074 14075 if (attachInfo != null) { 14076 // Restore the cached Canvas for our siblings 14077 attachInfo.mCanvas = canvas; 14078 } 14079 } 14080 } 14081 14082 /** 14083 * Create a snapshot of the view into a bitmap. We should probably make 14084 * some form of this public, but should think about the API. 14085 */ 14086 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14087 int width = mRight - mLeft; 14088 int height = mBottom - mTop; 14089 14090 final AttachInfo attachInfo = mAttachInfo; 14091 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14092 width = (int) ((width * scale) + 0.5f); 14093 height = (int) ((height * scale) + 0.5f); 14094 14095 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14096 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14097 if (bitmap == null) { 14098 throw new OutOfMemoryError(); 14099 } 14100 14101 Resources resources = getResources(); 14102 if (resources != null) { 14103 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14104 } 14105 14106 Canvas canvas; 14107 if (attachInfo != null) { 14108 canvas = attachInfo.mCanvas; 14109 if (canvas == null) { 14110 canvas = new Canvas(); 14111 } 14112 canvas.setBitmap(bitmap); 14113 // Temporarily clobber the cached Canvas in case one of our children 14114 // is also using a drawing cache. Without this, the children would 14115 // steal the canvas by attaching their own bitmap to it and bad, bad 14116 // things would happen (invisible views, corrupted drawings, etc.) 14117 attachInfo.mCanvas = null; 14118 } else { 14119 // This case should hopefully never or seldom happen 14120 canvas = new Canvas(bitmap); 14121 } 14122 14123 if ((backgroundColor & 0xff000000) != 0) { 14124 bitmap.eraseColor(backgroundColor); 14125 } 14126 14127 computeScroll(); 14128 final int restoreCount = canvas.save(); 14129 canvas.scale(scale, scale); 14130 canvas.translate(-mScrollX, -mScrollY); 14131 14132 // Temporarily remove the dirty mask 14133 int flags = mPrivateFlags; 14134 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14135 14136 // Fast path for layouts with no backgrounds 14137 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14138 dispatchDraw(canvas); 14139 if (mOverlay != null && !mOverlay.isEmpty()) { 14140 mOverlay.getOverlayView().draw(canvas); 14141 } 14142 } else { 14143 draw(canvas); 14144 } 14145 14146 mPrivateFlags = flags; 14147 14148 canvas.restoreToCount(restoreCount); 14149 canvas.setBitmap(null); 14150 14151 if (attachInfo != null) { 14152 // Restore the cached Canvas for our siblings 14153 attachInfo.mCanvas = canvas; 14154 } 14155 14156 return bitmap; 14157 } 14158 14159 /** 14160 * Indicates whether this View is currently in edit mode. A View is usually 14161 * in edit mode when displayed within a developer tool. For instance, if 14162 * this View is being drawn by a visual user interface builder, this method 14163 * should return true. 14164 * 14165 * Subclasses should check the return value of this method to provide 14166 * different behaviors if their normal behavior might interfere with the 14167 * host environment. For instance: the class spawns a thread in its 14168 * constructor, the drawing code relies on device-specific features, etc. 14169 * 14170 * This method is usually checked in the drawing code of custom widgets. 14171 * 14172 * @return True if this View is in edit mode, false otherwise. 14173 */ 14174 public boolean isInEditMode() { 14175 return false; 14176 } 14177 14178 /** 14179 * If the View draws content inside its padding and enables fading edges, 14180 * it needs to support padding offsets. Padding offsets are added to the 14181 * fading edges to extend the length of the fade so that it covers pixels 14182 * drawn inside the padding. 14183 * 14184 * Subclasses of this class should override this method if they need 14185 * to draw content inside the padding. 14186 * 14187 * @return True if padding offset must be applied, false otherwise. 14188 * 14189 * @see #getLeftPaddingOffset() 14190 * @see #getRightPaddingOffset() 14191 * @see #getTopPaddingOffset() 14192 * @see #getBottomPaddingOffset() 14193 * 14194 * @since CURRENT 14195 */ 14196 protected boolean isPaddingOffsetRequired() { 14197 return false; 14198 } 14199 14200 /** 14201 * Amount by which to extend the left fading region. Called only when 14202 * {@link #isPaddingOffsetRequired()} returns true. 14203 * 14204 * @return The left padding offset in pixels. 14205 * 14206 * @see #isPaddingOffsetRequired() 14207 * 14208 * @since CURRENT 14209 */ 14210 protected int getLeftPaddingOffset() { 14211 return 0; 14212 } 14213 14214 /** 14215 * Amount by which to extend the right fading region. Called only when 14216 * {@link #isPaddingOffsetRequired()} returns true. 14217 * 14218 * @return The right padding offset in pixels. 14219 * 14220 * @see #isPaddingOffsetRequired() 14221 * 14222 * @since CURRENT 14223 */ 14224 protected int getRightPaddingOffset() { 14225 return 0; 14226 } 14227 14228 /** 14229 * Amount by which to extend the top fading region. Called only when 14230 * {@link #isPaddingOffsetRequired()} returns true. 14231 * 14232 * @return The top padding offset in pixels. 14233 * 14234 * @see #isPaddingOffsetRequired() 14235 * 14236 * @since CURRENT 14237 */ 14238 protected int getTopPaddingOffset() { 14239 return 0; 14240 } 14241 14242 /** 14243 * Amount by which to extend the bottom fading region. Called only when 14244 * {@link #isPaddingOffsetRequired()} returns true. 14245 * 14246 * @return The bottom padding offset in pixels. 14247 * 14248 * @see #isPaddingOffsetRequired() 14249 * 14250 * @since CURRENT 14251 */ 14252 protected int getBottomPaddingOffset() { 14253 return 0; 14254 } 14255 14256 /** 14257 * @hide 14258 * @param offsetRequired 14259 */ 14260 protected int getFadeTop(boolean offsetRequired) { 14261 int top = mPaddingTop; 14262 if (offsetRequired) top += getTopPaddingOffset(); 14263 return top; 14264 } 14265 14266 /** 14267 * @hide 14268 * @param offsetRequired 14269 */ 14270 protected int getFadeHeight(boolean offsetRequired) { 14271 int padding = mPaddingTop; 14272 if (offsetRequired) padding += getTopPaddingOffset(); 14273 return mBottom - mTop - mPaddingBottom - padding; 14274 } 14275 14276 /** 14277 * <p>Indicates whether this view is attached to a hardware accelerated 14278 * window or not.</p> 14279 * 14280 * <p>Even if this method returns true, it does not mean that every call 14281 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14282 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14283 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14284 * window is hardware accelerated, 14285 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14286 * return false, and this method will return true.</p> 14287 * 14288 * @return True if the view is attached to a window and the window is 14289 * hardware accelerated; false in any other case. 14290 */ 14291 @ViewDebug.ExportedProperty(category = "drawing") 14292 public boolean isHardwareAccelerated() { 14293 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14294 } 14295 14296 /** 14297 * Sets a rectangular area on this view to which the view will be clipped 14298 * when it is drawn. Setting the value to null will remove the clip bounds 14299 * and the view will draw normally, using its full bounds. 14300 * 14301 * @param clipBounds The rectangular area, in the local coordinates of 14302 * this view, to which future drawing operations will be clipped. 14303 */ 14304 public void setClipBounds(Rect clipBounds) { 14305 if (clipBounds != null) { 14306 if (clipBounds.equals(mClipBounds)) { 14307 return; 14308 } 14309 if (mClipBounds == null) { 14310 invalidate(); 14311 mClipBounds = new Rect(clipBounds); 14312 } else { 14313 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14314 Math.min(mClipBounds.top, clipBounds.top), 14315 Math.max(mClipBounds.right, clipBounds.right), 14316 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14317 mClipBounds.set(clipBounds); 14318 } 14319 } else { 14320 if (mClipBounds != null) { 14321 invalidate(); 14322 mClipBounds = null; 14323 } 14324 } 14325 } 14326 14327 /** 14328 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14329 * 14330 * @return A copy of the current clip bounds if clip bounds are set, 14331 * otherwise null. 14332 */ 14333 public Rect getClipBounds() { 14334 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14335 } 14336 14337 /** 14338 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14339 * case of an active Animation being run on the view. 14340 */ 14341 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14342 Animation a, boolean scalingRequired) { 14343 Transformation invalidationTransform; 14344 final int flags = parent.mGroupFlags; 14345 final boolean initialized = a.isInitialized(); 14346 if (!initialized) { 14347 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14348 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14349 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14350 onAnimationStart(); 14351 } 14352 14353 final Transformation t = parent.getChildTransformation(); 14354 boolean more = a.getTransformation(drawingTime, t, 1f); 14355 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14356 if (parent.mInvalidationTransformation == null) { 14357 parent.mInvalidationTransformation = new Transformation(); 14358 } 14359 invalidationTransform = parent.mInvalidationTransformation; 14360 a.getTransformation(drawingTime, invalidationTransform, 1f); 14361 } else { 14362 invalidationTransform = t; 14363 } 14364 14365 if (more) { 14366 if (!a.willChangeBounds()) { 14367 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14368 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14369 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14370 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14371 // The child need to draw an animation, potentially offscreen, so 14372 // make sure we do not cancel invalidate requests 14373 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14374 parent.invalidate(mLeft, mTop, mRight, mBottom); 14375 } 14376 } else { 14377 if (parent.mInvalidateRegion == null) { 14378 parent.mInvalidateRegion = new RectF(); 14379 } 14380 final RectF region = parent.mInvalidateRegion; 14381 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14382 invalidationTransform); 14383 14384 // The child need to draw an animation, potentially offscreen, so 14385 // make sure we do not cancel invalidate requests 14386 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14387 14388 final int left = mLeft + (int) region.left; 14389 final int top = mTop + (int) region.top; 14390 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14391 top + (int) (region.height() + .5f)); 14392 } 14393 } 14394 return more; 14395 } 14396 14397 /** 14398 * This method is called by getDisplayList() when a display list is recorded for a View. 14399 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14400 */ 14401 void setDisplayListProperties(RenderNode renderNode) { 14402 if (renderNode != null) { 14403 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14404 if (mParent instanceof ViewGroup) { 14405 renderNode.setClipToBounds( 14406 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14407 } 14408 float alpha = 1; 14409 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14410 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14411 ViewGroup parentVG = (ViewGroup) mParent; 14412 final Transformation t = parentVG.getChildTransformation(); 14413 if (parentVG.getChildStaticTransformation(this, t)) { 14414 final int transformType = t.getTransformationType(); 14415 if (transformType != Transformation.TYPE_IDENTITY) { 14416 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14417 alpha = t.getAlpha(); 14418 } 14419 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14420 renderNode.setStaticMatrix(t.getMatrix()); 14421 } 14422 } 14423 } 14424 } 14425 if (mTransformationInfo != null) { 14426 alpha *= getFinalAlpha(); 14427 if (alpha < 1) { 14428 final int multipliedAlpha = (int) (255 * alpha); 14429 if (onSetAlpha(multipliedAlpha)) { 14430 alpha = 1; 14431 } 14432 } 14433 renderNode.setAlpha(alpha); 14434 } else if (alpha < 1) { 14435 renderNode.setAlpha(alpha); 14436 } 14437 } 14438 } 14439 14440 /** 14441 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14442 * This draw() method is an implementation detail and is not intended to be overridden or 14443 * to be called from anywhere else other than ViewGroup.drawChild(). 14444 */ 14445 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14446 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14447 boolean more = false; 14448 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14449 final int flags = parent.mGroupFlags; 14450 14451 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14452 parent.getChildTransformation().clear(); 14453 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14454 } 14455 14456 Transformation transformToApply = null; 14457 boolean concatMatrix = false; 14458 14459 boolean scalingRequired = false; 14460 boolean caching; 14461 int layerType = getLayerType(); 14462 14463 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14464 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14465 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14466 caching = true; 14467 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14468 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14469 } else { 14470 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14471 } 14472 14473 final Animation a = getAnimation(); 14474 if (a != null) { 14475 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14476 concatMatrix = a.willChangeTransformationMatrix(); 14477 if (concatMatrix) { 14478 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14479 } 14480 transformToApply = parent.getChildTransformation(); 14481 } else { 14482 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14483 // No longer animating: clear out old animation matrix 14484 mRenderNode.setAnimationMatrix(null); 14485 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14486 } 14487 if (!useDisplayListProperties && 14488 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14489 final Transformation t = parent.getChildTransformation(); 14490 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14491 if (hasTransform) { 14492 final int transformType = t.getTransformationType(); 14493 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14494 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14495 } 14496 } 14497 } 14498 14499 concatMatrix |= !childHasIdentityMatrix; 14500 14501 // Sets the flag as early as possible to allow draw() implementations 14502 // to call invalidate() successfully when doing animations 14503 mPrivateFlags |= PFLAG_DRAWN; 14504 14505 if (!concatMatrix && 14506 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14507 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14508 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14509 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14510 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14511 return more; 14512 } 14513 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14514 14515 if (hardwareAccelerated) { 14516 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14517 // retain the flag's value temporarily in the mRecreateDisplayList flag 14518 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14519 mPrivateFlags &= ~PFLAG_INVALIDATED; 14520 } 14521 14522 RenderNode renderNode = null; 14523 Bitmap cache = null; 14524 boolean hasDisplayList = false; 14525 if (caching) { 14526 if (!hardwareAccelerated) { 14527 if (layerType != LAYER_TYPE_NONE) { 14528 layerType = LAYER_TYPE_SOFTWARE; 14529 buildDrawingCache(true); 14530 } 14531 cache = getDrawingCache(true); 14532 } else { 14533 switch (layerType) { 14534 case LAYER_TYPE_SOFTWARE: 14535 if (useDisplayListProperties) { 14536 hasDisplayList = canHaveDisplayList(); 14537 } else { 14538 buildDrawingCache(true); 14539 cache = getDrawingCache(true); 14540 } 14541 break; 14542 case LAYER_TYPE_HARDWARE: 14543 if (useDisplayListProperties) { 14544 hasDisplayList = canHaveDisplayList(); 14545 } 14546 break; 14547 case LAYER_TYPE_NONE: 14548 // Delay getting the display list until animation-driven alpha values are 14549 // set up and possibly passed on to the view 14550 hasDisplayList = canHaveDisplayList(); 14551 break; 14552 } 14553 } 14554 } 14555 useDisplayListProperties &= hasDisplayList; 14556 if (useDisplayListProperties) { 14557 renderNode = getDisplayList(); 14558 if (!renderNode.isValid()) { 14559 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14560 // to getDisplayList(), the display list will be marked invalid and we should not 14561 // try to use it again. 14562 renderNode = null; 14563 hasDisplayList = false; 14564 useDisplayListProperties = false; 14565 } 14566 } 14567 14568 int sx = 0; 14569 int sy = 0; 14570 if (!hasDisplayList) { 14571 computeScroll(); 14572 sx = mScrollX; 14573 sy = mScrollY; 14574 } 14575 14576 final boolean hasNoCache = cache == null || hasDisplayList; 14577 final boolean offsetForScroll = cache == null && !hasDisplayList && 14578 layerType != LAYER_TYPE_HARDWARE; 14579 14580 int restoreTo = -1; 14581 if (!useDisplayListProperties || transformToApply != null) { 14582 restoreTo = canvas.save(); 14583 } 14584 if (offsetForScroll) { 14585 canvas.translate(mLeft - sx, mTop - sy); 14586 } else { 14587 if (!useDisplayListProperties) { 14588 canvas.translate(mLeft, mTop); 14589 } 14590 if (scalingRequired) { 14591 if (useDisplayListProperties) { 14592 // TODO: Might not need this if we put everything inside the DL 14593 restoreTo = canvas.save(); 14594 } 14595 // mAttachInfo cannot be null, otherwise scalingRequired == false 14596 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14597 canvas.scale(scale, scale); 14598 } 14599 } 14600 14601 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14602 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14603 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14604 if (transformToApply != null || !childHasIdentityMatrix) { 14605 int transX = 0; 14606 int transY = 0; 14607 14608 if (offsetForScroll) { 14609 transX = -sx; 14610 transY = -sy; 14611 } 14612 14613 if (transformToApply != null) { 14614 if (concatMatrix) { 14615 if (useDisplayListProperties) { 14616 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 14617 } else { 14618 // Undo the scroll translation, apply the transformation matrix, 14619 // then redo the scroll translate to get the correct result. 14620 canvas.translate(-transX, -transY); 14621 canvas.concat(transformToApply.getMatrix()); 14622 canvas.translate(transX, transY); 14623 } 14624 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14625 } 14626 14627 float transformAlpha = transformToApply.getAlpha(); 14628 if (transformAlpha < 1) { 14629 alpha *= transformAlpha; 14630 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14631 } 14632 } 14633 14634 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14635 canvas.translate(-transX, -transY); 14636 canvas.concat(getMatrix()); 14637 canvas.translate(transX, transY); 14638 } 14639 } 14640 14641 // Deal with alpha if it is or used to be <1 14642 if (alpha < 1 || 14643 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14644 if (alpha < 1) { 14645 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14646 } else { 14647 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14648 } 14649 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14650 if (hasNoCache) { 14651 final int multipliedAlpha = (int) (255 * alpha); 14652 if (!onSetAlpha(multipliedAlpha)) { 14653 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14654 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14655 layerType != LAYER_TYPE_NONE) { 14656 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14657 } 14658 if (useDisplayListProperties) { 14659 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14660 } else if (layerType == LAYER_TYPE_NONE) { 14661 final int scrollX = hasDisplayList ? 0 : sx; 14662 final int scrollY = hasDisplayList ? 0 : sy; 14663 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14664 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14665 } 14666 } else { 14667 // Alpha is handled by the child directly, clobber the layer's alpha 14668 mPrivateFlags |= PFLAG_ALPHA_SET; 14669 } 14670 } 14671 } 14672 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14673 onSetAlpha(255); 14674 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14675 } 14676 14677 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14678 !useDisplayListProperties && cache == null) { 14679 if (offsetForScroll) { 14680 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14681 } else { 14682 if (!scalingRequired || cache == null) { 14683 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14684 } else { 14685 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14686 } 14687 } 14688 } 14689 14690 if (!useDisplayListProperties && hasDisplayList) { 14691 renderNode = getDisplayList(); 14692 if (!renderNode.isValid()) { 14693 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14694 // to getDisplayList(), the display list will be marked invalid and we should not 14695 // try to use it again. 14696 renderNode = null; 14697 hasDisplayList = false; 14698 } 14699 } 14700 14701 if (hasNoCache) { 14702 boolean layerRendered = false; 14703 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14704 final HardwareLayer layer = getHardwareLayer(); 14705 if (layer != null && layer.isValid()) { 14706 mLayerPaint.setAlpha((int) (alpha * 255)); 14707 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14708 layerRendered = true; 14709 } else { 14710 final int scrollX = hasDisplayList ? 0 : sx; 14711 final int scrollY = hasDisplayList ? 0 : sy; 14712 canvas.saveLayer(scrollX, scrollY, 14713 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14714 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14715 } 14716 } 14717 14718 if (!layerRendered) { 14719 if (!hasDisplayList) { 14720 // Fast path for layouts with no backgrounds 14721 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14722 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14723 dispatchDraw(canvas); 14724 } else { 14725 draw(canvas); 14726 } 14727 } else { 14728 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14729 ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags); 14730 } 14731 } 14732 } else if (cache != null) { 14733 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14734 Paint cachePaint; 14735 14736 if (layerType == LAYER_TYPE_NONE) { 14737 cachePaint = parent.mCachePaint; 14738 if (cachePaint == null) { 14739 cachePaint = new Paint(); 14740 cachePaint.setDither(false); 14741 parent.mCachePaint = cachePaint; 14742 } 14743 if (alpha < 1) { 14744 cachePaint.setAlpha((int) (alpha * 255)); 14745 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14746 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14747 cachePaint.setAlpha(255); 14748 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14749 } 14750 } else { 14751 cachePaint = mLayerPaint; 14752 cachePaint.setAlpha((int) (alpha * 255)); 14753 } 14754 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14755 } 14756 14757 if (restoreTo >= 0) { 14758 canvas.restoreToCount(restoreTo); 14759 } 14760 14761 if (a != null && !more) { 14762 if (!hardwareAccelerated && !a.getFillAfter()) { 14763 onSetAlpha(255); 14764 } 14765 parent.finishAnimatingView(this, a); 14766 } 14767 14768 if (more && hardwareAccelerated) { 14769 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14770 // alpha animations should cause the child to recreate its display list 14771 invalidate(true); 14772 } 14773 } 14774 14775 mRecreateDisplayList = false; 14776 14777 return more; 14778 } 14779 14780 /** 14781 * Manually render this view (and all of its children) to the given Canvas. 14782 * The view must have already done a full layout before this function is 14783 * called. When implementing a view, implement 14784 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14785 * If you do need to override this method, call the superclass version. 14786 * 14787 * @param canvas The Canvas to which the View is rendered. 14788 */ 14789 public void draw(Canvas canvas) { 14790 if (mClipBounds != null) { 14791 canvas.clipRect(mClipBounds); 14792 } 14793 final int privateFlags = mPrivateFlags; 14794 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14795 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14796 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14797 14798 /* 14799 * Draw traversal performs several drawing steps which must be executed 14800 * in the appropriate order: 14801 * 14802 * 1. Draw the background 14803 * 2. If necessary, save the canvas' layers to prepare for fading 14804 * 3. Draw view's content 14805 * 4. Draw children 14806 * 5. If necessary, draw the fading edges and restore layers 14807 * 6. Draw decorations (scrollbars for instance) 14808 */ 14809 14810 // Step 1, draw the background, if needed 14811 int saveCount; 14812 14813 if (!dirtyOpaque) { 14814 drawBackground(canvas); 14815 } 14816 14817 // skip step 2 & 5 if possible (common case) 14818 final int viewFlags = mViewFlags; 14819 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14820 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14821 if (!verticalEdges && !horizontalEdges) { 14822 // Step 3, draw the content 14823 if (!dirtyOpaque) onDraw(canvas); 14824 14825 // Step 4, draw the children 14826 dispatchDraw(canvas); 14827 14828 // Step 6, draw decorations (scrollbars) 14829 onDrawScrollBars(canvas); 14830 14831 if (mOverlay != null && !mOverlay.isEmpty()) { 14832 mOverlay.getOverlayView().dispatchDraw(canvas); 14833 } 14834 14835 // we're done... 14836 return; 14837 } 14838 14839 /* 14840 * Here we do the full fledged routine... 14841 * (this is an uncommon case where speed matters less, 14842 * this is why we repeat some of the tests that have been 14843 * done above) 14844 */ 14845 14846 boolean drawTop = false; 14847 boolean drawBottom = false; 14848 boolean drawLeft = false; 14849 boolean drawRight = false; 14850 14851 float topFadeStrength = 0.0f; 14852 float bottomFadeStrength = 0.0f; 14853 float leftFadeStrength = 0.0f; 14854 float rightFadeStrength = 0.0f; 14855 14856 // Step 2, save the canvas' layers 14857 int paddingLeft = mPaddingLeft; 14858 14859 final boolean offsetRequired = isPaddingOffsetRequired(); 14860 if (offsetRequired) { 14861 paddingLeft += getLeftPaddingOffset(); 14862 } 14863 14864 int left = mScrollX + paddingLeft; 14865 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14866 int top = mScrollY + getFadeTop(offsetRequired); 14867 int bottom = top + getFadeHeight(offsetRequired); 14868 14869 if (offsetRequired) { 14870 right += getRightPaddingOffset(); 14871 bottom += getBottomPaddingOffset(); 14872 } 14873 14874 final ScrollabilityCache scrollabilityCache = mScrollCache; 14875 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14876 int length = (int) fadeHeight; 14877 14878 // clip the fade length if top and bottom fades overlap 14879 // overlapping fades produce odd-looking artifacts 14880 if (verticalEdges && (top + length > bottom - length)) { 14881 length = (bottom - top) / 2; 14882 } 14883 14884 // also clip horizontal fades if necessary 14885 if (horizontalEdges && (left + length > right - length)) { 14886 length = (right - left) / 2; 14887 } 14888 14889 if (verticalEdges) { 14890 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14891 drawTop = topFadeStrength * fadeHeight > 1.0f; 14892 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14893 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14894 } 14895 14896 if (horizontalEdges) { 14897 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14898 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14899 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14900 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14901 } 14902 14903 saveCount = canvas.getSaveCount(); 14904 14905 int solidColor = getSolidColor(); 14906 if (solidColor == 0) { 14907 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14908 14909 if (drawTop) { 14910 canvas.saveLayer(left, top, right, top + length, null, flags); 14911 } 14912 14913 if (drawBottom) { 14914 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14915 } 14916 14917 if (drawLeft) { 14918 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14919 } 14920 14921 if (drawRight) { 14922 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14923 } 14924 } else { 14925 scrollabilityCache.setFadeColor(solidColor); 14926 } 14927 14928 // Step 3, draw the content 14929 if (!dirtyOpaque) onDraw(canvas); 14930 14931 // Step 4, draw the children 14932 dispatchDraw(canvas); 14933 14934 // Step 5, draw the fade effect and restore layers 14935 final Paint p = scrollabilityCache.paint; 14936 final Matrix matrix = scrollabilityCache.matrix; 14937 final Shader fade = scrollabilityCache.shader; 14938 14939 if (drawTop) { 14940 matrix.setScale(1, fadeHeight * topFadeStrength); 14941 matrix.postTranslate(left, top); 14942 fade.setLocalMatrix(matrix); 14943 p.setShader(fade); 14944 canvas.drawRect(left, top, right, top + length, p); 14945 } 14946 14947 if (drawBottom) { 14948 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14949 matrix.postRotate(180); 14950 matrix.postTranslate(left, bottom); 14951 fade.setLocalMatrix(matrix); 14952 p.setShader(fade); 14953 canvas.drawRect(left, bottom - length, right, bottom, p); 14954 } 14955 14956 if (drawLeft) { 14957 matrix.setScale(1, fadeHeight * leftFadeStrength); 14958 matrix.postRotate(-90); 14959 matrix.postTranslate(left, top); 14960 fade.setLocalMatrix(matrix); 14961 p.setShader(fade); 14962 canvas.drawRect(left, top, left + length, bottom, p); 14963 } 14964 14965 if (drawRight) { 14966 matrix.setScale(1, fadeHeight * rightFadeStrength); 14967 matrix.postRotate(90); 14968 matrix.postTranslate(right, top); 14969 fade.setLocalMatrix(matrix); 14970 p.setShader(fade); 14971 canvas.drawRect(right - length, top, right, bottom, p); 14972 } 14973 14974 canvas.restoreToCount(saveCount); 14975 14976 // Step 6, draw decorations (scrollbars) 14977 onDrawScrollBars(canvas); 14978 14979 if (mOverlay != null && !mOverlay.isEmpty()) { 14980 mOverlay.getOverlayView().dispatchDraw(canvas); 14981 } 14982 } 14983 14984 /** 14985 * Draws the background onto the specified canvas. 14986 * 14987 * @param canvas Canvas on which to draw the background 14988 */ 14989 private void drawBackground(Canvas canvas) { 14990 final Drawable background = mBackground; 14991 if (background == null) { 14992 return; 14993 } 14994 14995 if (mBackgroundSizeChanged) { 14996 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14997 mBackgroundSizeChanged = false; 14998 invalidateOutline(); 14999 } 15000 15001 // Attempt to use a display list if requested. 15002 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15003 && mAttachInfo.mHardwareRenderer != null) { 15004 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 15005 15006 final RenderNode displayList = mBackgroundRenderNode; 15007 if (displayList != null && displayList.isValid()) { 15008 setBackgroundDisplayListProperties(displayList); 15009 ((HardwareCanvas) canvas).drawRenderNode(displayList); 15010 return; 15011 } 15012 } 15013 15014 final int scrollX = mScrollX; 15015 final int scrollY = mScrollY; 15016 if ((scrollX | scrollY) == 0) { 15017 background.draw(canvas); 15018 } else { 15019 canvas.translate(scrollX, scrollY); 15020 background.draw(canvas); 15021 canvas.translate(-scrollX, -scrollY); 15022 } 15023 } 15024 15025 /** 15026 * Set up background drawable display list properties. 15027 * 15028 * @param displayList Valid display list for the background drawable 15029 */ 15030 private void setBackgroundDisplayListProperties(RenderNode displayList) { 15031 displayList.setTranslationX(mScrollX); 15032 displayList.setTranslationY(mScrollY); 15033 } 15034 15035 /** 15036 * Creates a new display list or updates the existing display list for the 15037 * specified Drawable. 15038 * 15039 * @param drawable Drawable for which to create a display list 15040 * @param renderNode Existing RenderNode, or {@code null} 15041 * @return A valid display list for the specified drawable 15042 */ 15043 private static RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 15044 if (renderNode == null) { 15045 renderNode = RenderNode.create(drawable.getClass().getName()); 15046 } 15047 15048 final Rect bounds = drawable.getBounds(); 15049 final int width = bounds.width(); 15050 final int height = bounds.height(); 15051 final HardwareCanvas canvas = renderNode.start(width, height); 15052 try { 15053 drawable.draw(canvas); 15054 } finally { 15055 renderNode.end(canvas); 15056 } 15057 15058 // Set up drawable properties that are view-independent. 15059 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15060 renderNode.setProjectBackwards(drawable.isProjected()); 15061 renderNode.setProjectionReceiver(true); 15062 renderNode.setClipToBounds(false); 15063 return renderNode; 15064 } 15065 15066 /** 15067 * Returns the overlay for this view, creating it if it does not yet exist. 15068 * Adding drawables to the overlay will cause them to be displayed whenever 15069 * the view itself is redrawn. Objects in the overlay should be actively 15070 * managed: remove them when they should not be displayed anymore. The 15071 * overlay will always have the same size as its host view. 15072 * 15073 * <p>Note: Overlays do not currently work correctly with {@link 15074 * SurfaceView} or {@link TextureView}; contents in overlays for these 15075 * types of views may not display correctly.</p> 15076 * 15077 * @return The ViewOverlay object for this view. 15078 * @see ViewOverlay 15079 */ 15080 public ViewOverlay getOverlay() { 15081 if (mOverlay == null) { 15082 mOverlay = new ViewOverlay(mContext, this); 15083 } 15084 return mOverlay; 15085 } 15086 15087 /** 15088 * Override this if your view is known to always be drawn on top of a solid color background, 15089 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15090 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15091 * should be set to 0xFF. 15092 * 15093 * @see #setVerticalFadingEdgeEnabled(boolean) 15094 * @see #setHorizontalFadingEdgeEnabled(boolean) 15095 * 15096 * @return The known solid color background for this view, or 0 if the color may vary 15097 */ 15098 @ViewDebug.ExportedProperty(category = "drawing") 15099 public int getSolidColor() { 15100 return 0; 15101 } 15102 15103 /** 15104 * Build a human readable string representation of the specified view flags. 15105 * 15106 * @param flags the view flags to convert to a string 15107 * @return a String representing the supplied flags 15108 */ 15109 private static String printFlags(int flags) { 15110 String output = ""; 15111 int numFlags = 0; 15112 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15113 output += "TAKES_FOCUS"; 15114 numFlags++; 15115 } 15116 15117 switch (flags & VISIBILITY_MASK) { 15118 case INVISIBLE: 15119 if (numFlags > 0) { 15120 output += " "; 15121 } 15122 output += "INVISIBLE"; 15123 // USELESS HERE numFlags++; 15124 break; 15125 case GONE: 15126 if (numFlags > 0) { 15127 output += " "; 15128 } 15129 output += "GONE"; 15130 // USELESS HERE numFlags++; 15131 break; 15132 default: 15133 break; 15134 } 15135 return output; 15136 } 15137 15138 /** 15139 * Build a human readable string representation of the specified private 15140 * view flags. 15141 * 15142 * @param privateFlags the private view flags to convert to a string 15143 * @return a String representing the supplied flags 15144 */ 15145 private static String printPrivateFlags(int privateFlags) { 15146 String output = ""; 15147 int numFlags = 0; 15148 15149 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15150 output += "WANTS_FOCUS"; 15151 numFlags++; 15152 } 15153 15154 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15155 if (numFlags > 0) { 15156 output += " "; 15157 } 15158 output += "FOCUSED"; 15159 numFlags++; 15160 } 15161 15162 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15163 if (numFlags > 0) { 15164 output += " "; 15165 } 15166 output += "SELECTED"; 15167 numFlags++; 15168 } 15169 15170 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15171 if (numFlags > 0) { 15172 output += " "; 15173 } 15174 output += "IS_ROOT_NAMESPACE"; 15175 numFlags++; 15176 } 15177 15178 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15179 if (numFlags > 0) { 15180 output += " "; 15181 } 15182 output += "HAS_BOUNDS"; 15183 numFlags++; 15184 } 15185 15186 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15187 if (numFlags > 0) { 15188 output += " "; 15189 } 15190 output += "DRAWN"; 15191 // USELESS HERE numFlags++; 15192 } 15193 return output; 15194 } 15195 15196 /** 15197 * <p>Indicates whether or not this view's layout will be requested during 15198 * the next hierarchy layout pass.</p> 15199 * 15200 * @return true if the layout will be forced during next layout pass 15201 */ 15202 public boolean isLayoutRequested() { 15203 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15204 } 15205 15206 /** 15207 * Return true if o is a ViewGroup that is laying out using optical bounds. 15208 * @hide 15209 */ 15210 public static boolean isLayoutModeOptical(Object o) { 15211 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15212 } 15213 15214 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15215 Insets parentInsets = mParent instanceof View ? 15216 ((View) mParent).getOpticalInsets() : Insets.NONE; 15217 Insets childInsets = getOpticalInsets(); 15218 return setFrame( 15219 left + parentInsets.left - childInsets.left, 15220 top + parentInsets.top - childInsets.top, 15221 right + parentInsets.left + childInsets.right, 15222 bottom + parentInsets.top + childInsets.bottom); 15223 } 15224 15225 /** 15226 * Assign a size and position to a view and all of its 15227 * descendants 15228 * 15229 * <p>This is the second phase of the layout mechanism. 15230 * (The first is measuring). In this phase, each parent calls 15231 * layout on all of its children to position them. 15232 * This is typically done using the child measurements 15233 * that were stored in the measure pass().</p> 15234 * 15235 * <p>Derived classes should not override this method. 15236 * Derived classes with children should override 15237 * onLayout. In that method, they should 15238 * call layout on each of their children.</p> 15239 * 15240 * @param l Left position, relative to parent 15241 * @param t Top position, relative to parent 15242 * @param r Right position, relative to parent 15243 * @param b Bottom position, relative to parent 15244 */ 15245 @SuppressWarnings({"unchecked"}) 15246 public void layout(int l, int t, int r, int b) { 15247 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15248 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15249 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15250 } 15251 15252 int oldL = mLeft; 15253 int oldT = mTop; 15254 int oldB = mBottom; 15255 int oldR = mRight; 15256 15257 boolean changed = isLayoutModeOptical(mParent) ? 15258 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15259 15260 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15261 onLayout(changed, l, t, r, b); 15262 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15263 15264 ListenerInfo li = mListenerInfo; 15265 if (li != null && li.mOnLayoutChangeListeners != null) { 15266 ArrayList<OnLayoutChangeListener> listenersCopy = 15267 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15268 int numListeners = listenersCopy.size(); 15269 for (int i = 0; i < numListeners; ++i) { 15270 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15271 } 15272 } 15273 } 15274 15275 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15276 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15277 } 15278 15279 /** 15280 * Called from layout when this view should 15281 * assign a size and position to each of its children. 15282 * 15283 * Derived classes with children should override 15284 * this method and call layout on each of 15285 * their children. 15286 * @param changed This is a new size or position for this view 15287 * @param left Left position, relative to parent 15288 * @param top Top position, relative to parent 15289 * @param right Right position, relative to parent 15290 * @param bottom Bottom position, relative to parent 15291 */ 15292 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15293 } 15294 15295 /** 15296 * Assign a size and position to this view. 15297 * 15298 * This is called from layout. 15299 * 15300 * @param left Left position, relative to parent 15301 * @param top Top position, relative to parent 15302 * @param right Right position, relative to parent 15303 * @param bottom Bottom position, relative to parent 15304 * @return true if the new size and position are different than the 15305 * previous ones 15306 * {@hide} 15307 */ 15308 protected boolean setFrame(int left, int top, int right, int bottom) { 15309 boolean changed = false; 15310 15311 if (DBG) { 15312 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15313 + right + "," + bottom + ")"); 15314 } 15315 15316 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15317 changed = true; 15318 15319 // Remember our drawn bit 15320 int drawn = mPrivateFlags & PFLAG_DRAWN; 15321 15322 int oldWidth = mRight - mLeft; 15323 int oldHeight = mBottom - mTop; 15324 int newWidth = right - left; 15325 int newHeight = bottom - top; 15326 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15327 15328 // Invalidate our old position 15329 invalidate(sizeChanged); 15330 15331 mLeft = left; 15332 mTop = top; 15333 mRight = right; 15334 mBottom = bottom; 15335 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15336 15337 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15338 15339 15340 if (sizeChanged) { 15341 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15342 } 15343 15344 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15345 // If we are visible, force the DRAWN bit to on so that 15346 // this invalidate will go through (at least to our parent). 15347 // This is because someone may have invalidated this view 15348 // before this call to setFrame came in, thereby clearing 15349 // the DRAWN bit. 15350 mPrivateFlags |= PFLAG_DRAWN; 15351 invalidate(sizeChanged); 15352 // parent display list may need to be recreated based on a change in the bounds 15353 // of any child 15354 invalidateParentCaches(); 15355 } 15356 15357 // Reset drawn bit to original value (invalidate turns it off) 15358 mPrivateFlags |= drawn; 15359 15360 mBackgroundSizeChanged = true; 15361 15362 notifySubtreeAccessibilityStateChangedIfNeeded(); 15363 } 15364 return changed; 15365 } 15366 15367 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15368 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15369 if (mOverlay != null) { 15370 mOverlay.getOverlayView().setRight(newWidth); 15371 mOverlay.getOverlayView().setBottom(newHeight); 15372 } 15373 invalidateOutline(); 15374 } 15375 15376 /** 15377 * Finalize inflating a view from XML. This is called as the last phase 15378 * of inflation, after all child views have been added. 15379 * 15380 * <p>Even if the subclass overrides onFinishInflate, they should always be 15381 * sure to call the super method, so that we get called. 15382 */ 15383 protected void onFinishInflate() { 15384 } 15385 15386 /** 15387 * Returns the resources associated with this view. 15388 * 15389 * @return Resources object. 15390 */ 15391 public Resources getResources() { 15392 return mResources; 15393 } 15394 15395 /** 15396 * Invalidates the specified Drawable. 15397 * 15398 * @param drawable the drawable to invalidate 15399 */ 15400 @Override 15401 public void invalidateDrawable(@NonNull Drawable drawable) { 15402 if (verifyDrawable(drawable)) { 15403 final Rect dirty = drawable.getDirtyBounds(); 15404 final int scrollX = mScrollX; 15405 final int scrollY = mScrollY; 15406 15407 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15408 dirty.right + scrollX, dirty.bottom + scrollY); 15409 15410 invalidateOutline(); 15411 } 15412 } 15413 15414 /** 15415 * Schedules an action on a drawable to occur at a specified time. 15416 * 15417 * @param who the recipient of the action 15418 * @param what the action to run on the drawable 15419 * @param when the time at which the action must occur. Uses the 15420 * {@link SystemClock#uptimeMillis} timebase. 15421 */ 15422 @Override 15423 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15424 if (verifyDrawable(who) && what != null) { 15425 final long delay = when - SystemClock.uptimeMillis(); 15426 if (mAttachInfo != null) { 15427 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15428 Choreographer.CALLBACK_ANIMATION, what, who, 15429 Choreographer.subtractFrameDelay(delay)); 15430 } else { 15431 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15432 } 15433 } 15434 } 15435 15436 /** 15437 * Cancels a scheduled action on a drawable. 15438 * 15439 * @param who the recipient of the action 15440 * @param what the action to cancel 15441 */ 15442 @Override 15443 public void unscheduleDrawable(Drawable who, Runnable what) { 15444 if (verifyDrawable(who) && what != null) { 15445 if (mAttachInfo != null) { 15446 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15447 Choreographer.CALLBACK_ANIMATION, what, who); 15448 } 15449 ViewRootImpl.getRunQueue().removeCallbacks(what); 15450 } 15451 } 15452 15453 /** 15454 * Unschedule any events associated with the given Drawable. This can be 15455 * used when selecting a new Drawable into a view, so that the previous 15456 * one is completely unscheduled. 15457 * 15458 * @param who The Drawable to unschedule. 15459 * 15460 * @see #drawableStateChanged 15461 */ 15462 public void unscheduleDrawable(Drawable who) { 15463 if (mAttachInfo != null && who != null) { 15464 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15465 Choreographer.CALLBACK_ANIMATION, null, who); 15466 } 15467 } 15468 15469 /** 15470 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15471 * that the View directionality can and will be resolved before its Drawables. 15472 * 15473 * Will call {@link View#onResolveDrawables} when resolution is done. 15474 * 15475 * @hide 15476 */ 15477 protected void resolveDrawables() { 15478 // Drawables resolution may need to happen before resolving the layout direction (which is 15479 // done only during the measure() call). 15480 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15481 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15482 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15483 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15484 // direction to be resolved as its resolved value will be the same as its raw value. 15485 if (!isLayoutDirectionResolved() && 15486 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15487 return; 15488 } 15489 15490 final int layoutDirection = isLayoutDirectionResolved() ? 15491 getLayoutDirection() : getRawLayoutDirection(); 15492 15493 if (mBackground != null) { 15494 mBackground.setLayoutDirection(layoutDirection); 15495 } 15496 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15497 onResolveDrawables(layoutDirection); 15498 } 15499 15500 /** 15501 * Called when layout direction has been resolved. 15502 * 15503 * The default implementation does nothing. 15504 * 15505 * @param layoutDirection The resolved layout direction. 15506 * 15507 * @see #LAYOUT_DIRECTION_LTR 15508 * @see #LAYOUT_DIRECTION_RTL 15509 * 15510 * @hide 15511 */ 15512 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15513 } 15514 15515 /** 15516 * @hide 15517 */ 15518 protected void resetResolvedDrawables() { 15519 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15520 } 15521 15522 private boolean isDrawablesResolved() { 15523 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15524 } 15525 15526 /** 15527 * If your view subclass is displaying its own Drawable objects, it should 15528 * override this function and return true for any Drawable it is 15529 * displaying. This allows animations for those drawables to be 15530 * scheduled. 15531 * 15532 * <p>Be sure to call through to the super class when overriding this 15533 * function. 15534 * 15535 * @param who The Drawable to verify. Return true if it is one you are 15536 * displaying, else return the result of calling through to the 15537 * super class. 15538 * 15539 * @return boolean If true than the Drawable is being displayed in the 15540 * view; else false and it is not allowed to animate. 15541 * 15542 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15543 * @see #drawableStateChanged() 15544 */ 15545 protected boolean verifyDrawable(Drawable who) { 15546 return who == mBackground; 15547 } 15548 15549 /** 15550 * This function is called whenever the state of the view changes in such 15551 * a way that it impacts the state of drawables being shown. 15552 * <p> 15553 * If the View has a StateListAnimator, it will also be called to run necessary state 15554 * change animations. 15555 * <p> 15556 * Be sure to call through to the superclass when overriding this function. 15557 * 15558 * @see Drawable#setState(int[]) 15559 */ 15560 protected void drawableStateChanged() { 15561 final Drawable d = mBackground; 15562 if (d != null && d.isStateful()) { 15563 d.setState(getDrawableState()); 15564 } 15565 15566 if (mStateListAnimator != null) { 15567 mStateListAnimator.setState(getDrawableState()); 15568 } 15569 } 15570 15571 /** 15572 * This function is called whenever the drawable hotspot changes. 15573 * <p> 15574 * Be sure to call through to the superclass when overriding this function. 15575 * 15576 * @param x hotspot x coordinate 15577 * @param y hotspot y coordinate 15578 */ 15579 public void drawableHotspotChanged(float x, float y) { 15580 if (mBackground != null) { 15581 mBackground.setHotspot(x, y); 15582 } 15583 } 15584 15585 /** 15586 * Call this to force a view to update its drawable state. This will cause 15587 * drawableStateChanged to be called on this view. Views that are interested 15588 * in the new state should call getDrawableState. 15589 * 15590 * @see #drawableStateChanged 15591 * @see #getDrawableState 15592 */ 15593 public void refreshDrawableState() { 15594 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15595 drawableStateChanged(); 15596 15597 ViewParent parent = mParent; 15598 if (parent != null) { 15599 parent.childDrawableStateChanged(this); 15600 } 15601 } 15602 15603 /** 15604 * Return an array of resource IDs of the drawable states representing the 15605 * current state of the view. 15606 * 15607 * @return The current drawable state 15608 * 15609 * @see Drawable#setState(int[]) 15610 * @see #drawableStateChanged() 15611 * @see #onCreateDrawableState(int) 15612 */ 15613 public final int[] getDrawableState() { 15614 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15615 return mDrawableState; 15616 } else { 15617 mDrawableState = onCreateDrawableState(0); 15618 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15619 return mDrawableState; 15620 } 15621 } 15622 15623 /** 15624 * Generate the new {@link android.graphics.drawable.Drawable} state for 15625 * this view. This is called by the view 15626 * system when the cached Drawable state is determined to be invalid. To 15627 * retrieve the current state, you should use {@link #getDrawableState}. 15628 * 15629 * @param extraSpace if non-zero, this is the number of extra entries you 15630 * would like in the returned array in which you can place your own 15631 * states. 15632 * 15633 * @return Returns an array holding the current {@link Drawable} state of 15634 * the view. 15635 * 15636 * @see #mergeDrawableStates(int[], int[]) 15637 */ 15638 protected int[] onCreateDrawableState(int extraSpace) { 15639 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15640 mParent instanceof View) { 15641 return ((View) mParent).onCreateDrawableState(extraSpace); 15642 } 15643 15644 int[] drawableState; 15645 15646 int privateFlags = mPrivateFlags; 15647 15648 int viewStateIndex = 0; 15649 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15650 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15651 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15652 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15653 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15654 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15655 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15656 HardwareRenderer.isAvailable()) { 15657 // This is set if HW acceleration is requested, even if the current 15658 // process doesn't allow it. This is just to allow app preview 15659 // windows to better match their app. 15660 viewStateIndex |= VIEW_STATE_ACCELERATED; 15661 } 15662 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15663 15664 final int privateFlags2 = mPrivateFlags2; 15665 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15666 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15667 15668 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15669 15670 //noinspection ConstantIfStatement 15671 if (false) { 15672 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15673 Log.i("View", toString() 15674 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15675 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15676 + " fo=" + hasFocus() 15677 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15678 + " wf=" + hasWindowFocus() 15679 + ": " + Arrays.toString(drawableState)); 15680 } 15681 15682 if (extraSpace == 0) { 15683 return drawableState; 15684 } 15685 15686 final int[] fullState; 15687 if (drawableState != null) { 15688 fullState = new int[drawableState.length + extraSpace]; 15689 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15690 } else { 15691 fullState = new int[extraSpace]; 15692 } 15693 15694 return fullState; 15695 } 15696 15697 /** 15698 * Merge your own state values in <var>additionalState</var> into the base 15699 * state values <var>baseState</var> that were returned by 15700 * {@link #onCreateDrawableState(int)}. 15701 * 15702 * @param baseState The base state values returned by 15703 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15704 * own additional state values. 15705 * 15706 * @param additionalState The additional state values you would like 15707 * added to <var>baseState</var>; this array is not modified. 15708 * 15709 * @return As a convenience, the <var>baseState</var> array you originally 15710 * passed into the function is returned. 15711 * 15712 * @see #onCreateDrawableState(int) 15713 */ 15714 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15715 final int N = baseState.length; 15716 int i = N - 1; 15717 while (i >= 0 && baseState[i] == 0) { 15718 i--; 15719 } 15720 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15721 return baseState; 15722 } 15723 15724 /** 15725 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15726 * on all Drawable objects associated with this view. 15727 * <p> 15728 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 15729 * attached to this view. 15730 */ 15731 public void jumpDrawablesToCurrentState() { 15732 if (mBackground != null) { 15733 mBackground.jumpToCurrentState(); 15734 } 15735 if (mStateListAnimator != null) { 15736 mStateListAnimator.jumpToCurrentState(); 15737 } 15738 } 15739 15740 /** 15741 * Sets the background color for this view. 15742 * @param color the color of the background 15743 */ 15744 @RemotableViewMethod 15745 public void setBackgroundColor(int color) { 15746 if (mBackground instanceof ColorDrawable) { 15747 ((ColorDrawable) mBackground.mutate()).setColor(color); 15748 computeOpaqueFlags(); 15749 mBackgroundResource = 0; 15750 } else { 15751 setBackground(new ColorDrawable(color)); 15752 } 15753 } 15754 15755 /** 15756 * Set the background to a given resource. The resource should refer to 15757 * a Drawable object or 0 to remove the background. 15758 * @param resid The identifier of the resource. 15759 * 15760 * @attr ref android.R.styleable#View_background 15761 */ 15762 @RemotableViewMethod 15763 public void setBackgroundResource(int resid) { 15764 if (resid != 0 && resid == mBackgroundResource) { 15765 return; 15766 } 15767 15768 Drawable d = null; 15769 if (resid != 0) { 15770 d = mContext.getDrawable(resid); 15771 } 15772 setBackground(d); 15773 15774 mBackgroundResource = resid; 15775 } 15776 15777 /** 15778 * Set the background to a given Drawable, or remove the background. If the 15779 * background has padding, this View's padding is set to the background's 15780 * padding. However, when a background is removed, this View's padding isn't 15781 * touched. If setting the padding is desired, please use 15782 * {@link #setPadding(int, int, int, int)}. 15783 * 15784 * @param background The Drawable to use as the background, or null to remove the 15785 * background 15786 */ 15787 public void setBackground(Drawable background) { 15788 //noinspection deprecation 15789 setBackgroundDrawable(background); 15790 } 15791 15792 /** 15793 * @deprecated use {@link #setBackground(Drawable)} instead 15794 */ 15795 @Deprecated 15796 public void setBackgroundDrawable(Drawable background) { 15797 computeOpaqueFlags(); 15798 15799 if (background == mBackground) { 15800 return; 15801 } 15802 15803 boolean requestLayout = false; 15804 15805 mBackgroundResource = 0; 15806 15807 /* 15808 * Regardless of whether we're setting a new background or not, we want 15809 * to clear the previous drawable. 15810 */ 15811 if (mBackground != null) { 15812 mBackground.setCallback(null); 15813 unscheduleDrawable(mBackground); 15814 } 15815 15816 if (background != null) { 15817 Rect padding = sThreadLocal.get(); 15818 if (padding == null) { 15819 padding = new Rect(); 15820 sThreadLocal.set(padding); 15821 } 15822 resetResolvedDrawables(); 15823 background.setLayoutDirection(getLayoutDirection()); 15824 if (background.getPadding(padding)) { 15825 resetResolvedPadding(); 15826 switch (background.getLayoutDirection()) { 15827 case LAYOUT_DIRECTION_RTL: 15828 mUserPaddingLeftInitial = padding.right; 15829 mUserPaddingRightInitial = padding.left; 15830 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15831 break; 15832 case LAYOUT_DIRECTION_LTR: 15833 default: 15834 mUserPaddingLeftInitial = padding.left; 15835 mUserPaddingRightInitial = padding.right; 15836 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15837 } 15838 mLeftPaddingDefined = false; 15839 mRightPaddingDefined = false; 15840 } 15841 15842 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15843 // if it has a different minimum size, we should layout again 15844 if (mBackground == null 15845 || mBackground.getMinimumHeight() != background.getMinimumHeight() 15846 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15847 requestLayout = true; 15848 } 15849 15850 background.setCallback(this); 15851 if (background.isStateful()) { 15852 background.setState(getDrawableState()); 15853 } 15854 background.setVisible(getVisibility() == VISIBLE, false); 15855 mBackground = background; 15856 15857 applyBackgroundTint(); 15858 15859 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15860 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15861 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15862 requestLayout = true; 15863 } 15864 } else { 15865 /* Remove the background */ 15866 mBackground = null; 15867 15868 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15869 /* 15870 * This view ONLY drew the background before and we're removing 15871 * the background, so now it won't draw anything 15872 * (hence we SKIP_DRAW) 15873 */ 15874 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15875 mPrivateFlags |= PFLAG_SKIP_DRAW; 15876 } 15877 15878 /* 15879 * When the background is set, we try to apply its padding to this 15880 * View. When the background is removed, we don't touch this View's 15881 * padding. This is noted in the Javadocs. Hence, we don't need to 15882 * requestLayout(), the invalidate() below is sufficient. 15883 */ 15884 15885 // The old background's minimum size could have affected this 15886 // View's layout, so let's requestLayout 15887 requestLayout = true; 15888 } 15889 15890 computeOpaqueFlags(); 15891 15892 if (requestLayout) { 15893 requestLayout(); 15894 } 15895 15896 mBackgroundSizeChanged = true; 15897 invalidate(true); 15898 } 15899 15900 /** 15901 * Gets the background drawable 15902 * 15903 * @return The drawable used as the background for this view, if any. 15904 * 15905 * @see #setBackground(Drawable) 15906 * 15907 * @attr ref android.R.styleable#View_background 15908 */ 15909 public Drawable getBackground() { 15910 return mBackground; 15911 } 15912 15913 /** 15914 * Applies a tint to the background drawable. 15915 * <p> 15916 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 15917 * mutate the drawable and apply the specified tint and tint mode using 15918 * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}. 15919 * 15920 * @param tint the tint to apply, may be {@code null} to clear tint 15921 * @param tintMode the blending mode used to apply the tint, may be 15922 * {@code null} to clear tint 15923 * 15924 * @attr ref android.R.styleable#View_backgroundTint 15925 * @attr ref android.R.styleable#View_backgroundTintMode 15926 * @see Drawable#setTint(ColorStateList, PorterDuff.Mode) 15927 */ 15928 private void setBackgroundTint(@Nullable ColorStateList tint, 15929 @Nullable PorterDuff.Mode tintMode) { 15930 mBackgroundTint = tint; 15931 mBackgroundTintMode = tintMode; 15932 mHasBackgroundTint = true; 15933 15934 applyBackgroundTint(); 15935 } 15936 15937 /** 15938 * Applies a tint to the background drawable. Does not modify the current tint 15939 * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default. 15940 * <p> 15941 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 15942 * mutate the drawable and apply the specified tint and tint mode using 15943 * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}. 15944 * 15945 * @param tint the tint to apply, may be {@code null} to clear tint 15946 * 15947 * @attr ref android.R.styleable#View_backgroundTint 15948 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15949 */ 15950 public void setBackgroundTint(@Nullable ColorStateList tint) { 15951 setBackgroundTint(tint, mBackgroundTintMode); 15952 } 15953 15954 /** 15955 * @return the tint applied to the background drawable 15956 * @attr ref android.R.styleable#View_backgroundTint 15957 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15958 */ 15959 @Nullable 15960 public ColorStateList getBackgroundTint() { 15961 return mBackgroundTint; 15962 } 15963 15964 /** 15965 * Specifies the blending mode used to apply the tint specified by 15966 * {@link #setBackgroundTint(ColorStateList)}} to the background drawable. 15967 * The default mode is {@link PorterDuff.Mode#SRC_ATOP}. 15968 * 15969 * @param tintMode the blending mode used to apply the tint, may be 15970 * {@code null} to clear tint 15971 * @attr ref android.R.styleable#View_backgroundTintMode 15972 * @see #setBackgroundTint(ColorStateList) 15973 */ 15974 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 15975 setBackgroundTint(mBackgroundTint, tintMode); 15976 } 15977 15978 /** 15979 * @return the blending mode used to apply the tint to the background drawable 15980 * @attr ref android.R.styleable#View_backgroundTintMode 15981 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15982 */ 15983 @Nullable 15984 public PorterDuff.Mode getBackgroundTintMode() { 15985 return mBackgroundTintMode; 15986 } 15987 15988 private void applyBackgroundTint() { 15989 if (mBackground != null && mHasBackgroundTint) { 15990 mBackground = mBackground.mutate(); 15991 mBackground.setTint(mBackgroundTint, mBackgroundTintMode); 15992 } 15993 } 15994 15995 /** 15996 * Sets the padding. The view may add on the space required to display 15997 * the scrollbars, depending on the style and visibility of the scrollbars. 15998 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15999 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 16000 * from the values set in this call. 16001 * 16002 * @attr ref android.R.styleable#View_padding 16003 * @attr ref android.R.styleable#View_paddingBottom 16004 * @attr ref android.R.styleable#View_paddingLeft 16005 * @attr ref android.R.styleable#View_paddingRight 16006 * @attr ref android.R.styleable#View_paddingTop 16007 * @param left the left padding in pixels 16008 * @param top the top padding in pixels 16009 * @param right the right padding in pixels 16010 * @param bottom the bottom padding in pixels 16011 */ 16012 public void setPadding(int left, int top, int right, int bottom) { 16013 resetResolvedPadding(); 16014 16015 mUserPaddingStart = UNDEFINED_PADDING; 16016 mUserPaddingEnd = UNDEFINED_PADDING; 16017 16018 mUserPaddingLeftInitial = left; 16019 mUserPaddingRightInitial = right; 16020 16021 mLeftPaddingDefined = true; 16022 mRightPaddingDefined = true; 16023 16024 internalSetPadding(left, top, right, bottom); 16025 } 16026 16027 /** 16028 * @hide 16029 */ 16030 protected void internalSetPadding(int left, int top, int right, int bottom) { 16031 mUserPaddingLeft = left; 16032 mUserPaddingRight = right; 16033 mUserPaddingBottom = bottom; 16034 16035 final int viewFlags = mViewFlags; 16036 boolean changed = false; 16037 16038 // Common case is there are no scroll bars. 16039 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 16040 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 16041 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 16042 ? 0 : getVerticalScrollbarWidth(); 16043 switch (mVerticalScrollbarPosition) { 16044 case SCROLLBAR_POSITION_DEFAULT: 16045 if (isLayoutRtl()) { 16046 left += offset; 16047 } else { 16048 right += offset; 16049 } 16050 break; 16051 case SCROLLBAR_POSITION_RIGHT: 16052 right += offset; 16053 break; 16054 case SCROLLBAR_POSITION_LEFT: 16055 left += offset; 16056 break; 16057 } 16058 } 16059 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16060 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16061 ? 0 : getHorizontalScrollbarHeight(); 16062 } 16063 } 16064 16065 if (mPaddingLeft != left) { 16066 changed = true; 16067 mPaddingLeft = left; 16068 } 16069 if (mPaddingTop != top) { 16070 changed = true; 16071 mPaddingTop = top; 16072 } 16073 if (mPaddingRight != right) { 16074 changed = true; 16075 mPaddingRight = right; 16076 } 16077 if (mPaddingBottom != bottom) { 16078 changed = true; 16079 mPaddingBottom = bottom; 16080 } 16081 16082 if (changed) { 16083 requestLayout(); 16084 } 16085 } 16086 16087 /** 16088 * Sets the relative padding. The view may add on the space required to display 16089 * the scrollbars, depending on the style and visibility of the scrollbars. 16090 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16091 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16092 * from the values set in this call. 16093 * 16094 * @attr ref android.R.styleable#View_padding 16095 * @attr ref android.R.styleable#View_paddingBottom 16096 * @attr ref android.R.styleable#View_paddingStart 16097 * @attr ref android.R.styleable#View_paddingEnd 16098 * @attr ref android.R.styleable#View_paddingTop 16099 * @param start the start padding in pixels 16100 * @param top the top padding in pixels 16101 * @param end the end padding in pixels 16102 * @param bottom the bottom padding in pixels 16103 */ 16104 public void setPaddingRelative(int start, int top, int end, int bottom) { 16105 resetResolvedPadding(); 16106 16107 mUserPaddingStart = start; 16108 mUserPaddingEnd = end; 16109 mLeftPaddingDefined = true; 16110 mRightPaddingDefined = true; 16111 16112 switch(getLayoutDirection()) { 16113 case LAYOUT_DIRECTION_RTL: 16114 mUserPaddingLeftInitial = end; 16115 mUserPaddingRightInitial = start; 16116 internalSetPadding(end, top, start, bottom); 16117 break; 16118 case LAYOUT_DIRECTION_LTR: 16119 default: 16120 mUserPaddingLeftInitial = start; 16121 mUserPaddingRightInitial = end; 16122 internalSetPadding(start, top, end, bottom); 16123 } 16124 } 16125 16126 /** 16127 * Returns the top padding of this view. 16128 * 16129 * @return the top padding in pixels 16130 */ 16131 public int getPaddingTop() { 16132 return mPaddingTop; 16133 } 16134 16135 /** 16136 * Returns the bottom padding of this view. If there are inset and enabled 16137 * scrollbars, this value may include the space required to display the 16138 * scrollbars as well. 16139 * 16140 * @return the bottom padding in pixels 16141 */ 16142 public int getPaddingBottom() { 16143 return mPaddingBottom; 16144 } 16145 16146 /** 16147 * Returns the left padding of this view. If there are inset and enabled 16148 * scrollbars, this value may include the space required to display the 16149 * scrollbars as well. 16150 * 16151 * @return the left padding in pixels 16152 */ 16153 public int getPaddingLeft() { 16154 if (!isPaddingResolved()) { 16155 resolvePadding(); 16156 } 16157 return mPaddingLeft; 16158 } 16159 16160 /** 16161 * Returns the start padding of this view depending on its resolved layout direction. 16162 * If there are inset and enabled scrollbars, this value may include the space 16163 * required to display the scrollbars as well. 16164 * 16165 * @return the start padding in pixels 16166 */ 16167 public int getPaddingStart() { 16168 if (!isPaddingResolved()) { 16169 resolvePadding(); 16170 } 16171 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16172 mPaddingRight : mPaddingLeft; 16173 } 16174 16175 /** 16176 * Returns the right padding of this view. If there are inset and enabled 16177 * scrollbars, this value may include the space required to display the 16178 * scrollbars as well. 16179 * 16180 * @return the right padding in pixels 16181 */ 16182 public int getPaddingRight() { 16183 if (!isPaddingResolved()) { 16184 resolvePadding(); 16185 } 16186 return mPaddingRight; 16187 } 16188 16189 /** 16190 * Returns the end padding of this view depending on its resolved layout direction. 16191 * If there are inset and enabled scrollbars, this value may include the space 16192 * required to display the scrollbars as well. 16193 * 16194 * @return the end padding in pixels 16195 */ 16196 public int getPaddingEnd() { 16197 if (!isPaddingResolved()) { 16198 resolvePadding(); 16199 } 16200 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16201 mPaddingLeft : mPaddingRight; 16202 } 16203 16204 /** 16205 * Return if the padding as been set thru relative values 16206 * {@link #setPaddingRelative(int, int, int, int)} or thru 16207 * @attr ref android.R.styleable#View_paddingStart or 16208 * @attr ref android.R.styleable#View_paddingEnd 16209 * 16210 * @return true if the padding is relative or false if it is not. 16211 */ 16212 public boolean isPaddingRelative() { 16213 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16214 } 16215 16216 Insets computeOpticalInsets() { 16217 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16218 } 16219 16220 /** 16221 * @hide 16222 */ 16223 public void resetPaddingToInitialValues() { 16224 if (isRtlCompatibilityMode()) { 16225 mPaddingLeft = mUserPaddingLeftInitial; 16226 mPaddingRight = mUserPaddingRightInitial; 16227 return; 16228 } 16229 if (isLayoutRtl()) { 16230 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16231 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16232 } else { 16233 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16234 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16235 } 16236 } 16237 16238 /** 16239 * @hide 16240 */ 16241 public Insets getOpticalInsets() { 16242 if (mLayoutInsets == null) { 16243 mLayoutInsets = computeOpticalInsets(); 16244 } 16245 return mLayoutInsets; 16246 } 16247 16248 /** 16249 * Set this view's optical insets. 16250 * 16251 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16252 * property. Views that compute their own optical insets should call it as part of measurement. 16253 * This method does not request layout. If you are setting optical insets outside of 16254 * measure/layout itself you will want to call requestLayout() yourself. 16255 * </p> 16256 * @hide 16257 */ 16258 public void setOpticalInsets(Insets insets) { 16259 mLayoutInsets = insets; 16260 } 16261 16262 /** 16263 * Changes the selection state of this view. A view can be selected or not. 16264 * Note that selection is not the same as focus. Views are typically 16265 * selected in the context of an AdapterView like ListView or GridView; 16266 * the selected view is the view that is highlighted. 16267 * 16268 * @param selected true if the view must be selected, false otherwise 16269 */ 16270 public void setSelected(boolean selected) { 16271 //noinspection DoubleNegation 16272 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16273 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16274 if (!selected) resetPressedState(); 16275 invalidate(true); 16276 refreshDrawableState(); 16277 dispatchSetSelected(selected); 16278 notifyViewAccessibilityStateChangedIfNeeded( 16279 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16280 } 16281 } 16282 16283 /** 16284 * Dispatch setSelected to all of this View's children. 16285 * 16286 * @see #setSelected(boolean) 16287 * 16288 * @param selected The new selected state 16289 */ 16290 protected void dispatchSetSelected(boolean selected) { 16291 } 16292 16293 /** 16294 * Indicates the selection state of this view. 16295 * 16296 * @return true if the view is selected, false otherwise 16297 */ 16298 @ViewDebug.ExportedProperty 16299 public boolean isSelected() { 16300 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16301 } 16302 16303 /** 16304 * Changes the activated state of this view. A view can be activated or not. 16305 * Note that activation is not the same as selection. Selection is 16306 * a transient property, representing the view (hierarchy) the user is 16307 * currently interacting with. Activation is a longer-term state that the 16308 * user can move views in and out of. For example, in a list view with 16309 * single or multiple selection enabled, the views in the current selection 16310 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16311 * here.) The activated state is propagated down to children of the view it 16312 * is set on. 16313 * 16314 * @param activated true if the view must be activated, false otherwise 16315 */ 16316 public void setActivated(boolean activated) { 16317 //noinspection DoubleNegation 16318 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16319 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16320 invalidate(true); 16321 refreshDrawableState(); 16322 dispatchSetActivated(activated); 16323 } 16324 } 16325 16326 /** 16327 * Dispatch setActivated to all of this View's children. 16328 * 16329 * @see #setActivated(boolean) 16330 * 16331 * @param activated The new activated state 16332 */ 16333 protected void dispatchSetActivated(boolean activated) { 16334 } 16335 16336 /** 16337 * Indicates the activation state of this view. 16338 * 16339 * @return true if the view is activated, false otherwise 16340 */ 16341 @ViewDebug.ExportedProperty 16342 public boolean isActivated() { 16343 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16344 } 16345 16346 /** 16347 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16348 * observer can be used to get notifications when global events, like 16349 * layout, happen. 16350 * 16351 * The returned ViewTreeObserver observer is not guaranteed to remain 16352 * valid for the lifetime of this View. If the caller of this method keeps 16353 * a long-lived reference to ViewTreeObserver, it should always check for 16354 * the return value of {@link ViewTreeObserver#isAlive()}. 16355 * 16356 * @return The ViewTreeObserver for this view's hierarchy. 16357 */ 16358 public ViewTreeObserver getViewTreeObserver() { 16359 if (mAttachInfo != null) { 16360 return mAttachInfo.mTreeObserver; 16361 } 16362 if (mFloatingTreeObserver == null) { 16363 mFloatingTreeObserver = new ViewTreeObserver(); 16364 } 16365 return mFloatingTreeObserver; 16366 } 16367 16368 /** 16369 * <p>Finds the topmost view in the current view hierarchy.</p> 16370 * 16371 * @return the topmost view containing this view 16372 */ 16373 public View getRootView() { 16374 if (mAttachInfo != null) { 16375 final View v = mAttachInfo.mRootView; 16376 if (v != null) { 16377 return v; 16378 } 16379 } 16380 16381 View parent = this; 16382 16383 while (parent.mParent != null && parent.mParent instanceof View) { 16384 parent = (View) parent.mParent; 16385 } 16386 16387 return parent; 16388 } 16389 16390 /** 16391 * Transforms a motion event from view-local coordinates to on-screen 16392 * coordinates. 16393 * 16394 * @param ev the view-local motion event 16395 * @return false if the transformation could not be applied 16396 * @hide 16397 */ 16398 public boolean toGlobalMotionEvent(MotionEvent ev) { 16399 final AttachInfo info = mAttachInfo; 16400 if (info == null) { 16401 return false; 16402 } 16403 16404 final Matrix m = info.mTmpMatrix; 16405 m.set(Matrix.IDENTITY_MATRIX); 16406 transformMatrixToGlobal(m); 16407 ev.transform(m); 16408 return true; 16409 } 16410 16411 /** 16412 * Transforms a motion event from on-screen coordinates to view-local 16413 * coordinates. 16414 * 16415 * @param ev the on-screen motion event 16416 * @return false if the transformation could not be applied 16417 * @hide 16418 */ 16419 public boolean toLocalMotionEvent(MotionEvent ev) { 16420 final AttachInfo info = mAttachInfo; 16421 if (info == null) { 16422 return false; 16423 } 16424 16425 final Matrix m = info.mTmpMatrix; 16426 m.set(Matrix.IDENTITY_MATRIX); 16427 transformMatrixToLocal(m); 16428 ev.transform(m); 16429 return true; 16430 } 16431 16432 /** 16433 * Modifies the input matrix such that it maps view-local coordinates to 16434 * on-screen coordinates. 16435 * 16436 * @param m input matrix to modify 16437 */ 16438 void transformMatrixToGlobal(Matrix m) { 16439 final ViewParent parent = mParent; 16440 if (parent instanceof View) { 16441 final View vp = (View) parent; 16442 vp.transformMatrixToGlobal(m); 16443 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16444 } else if (parent instanceof ViewRootImpl) { 16445 final ViewRootImpl vr = (ViewRootImpl) parent; 16446 vr.transformMatrixToGlobal(m); 16447 m.postTranslate(0, -vr.mCurScrollY); 16448 } 16449 16450 m.postTranslate(mLeft, mTop); 16451 16452 if (!hasIdentityMatrix()) { 16453 m.postConcat(getMatrix()); 16454 } 16455 } 16456 16457 /** 16458 * Modifies the input matrix such that it maps on-screen coordinates to 16459 * view-local coordinates. 16460 * 16461 * @param m input matrix to modify 16462 */ 16463 void transformMatrixToLocal(Matrix m) { 16464 final ViewParent parent = mParent; 16465 if (parent instanceof View) { 16466 final View vp = (View) parent; 16467 vp.transformMatrixToLocal(m); 16468 m.preTranslate(vp.mScrollX, vp.mScrollY); 16469 } else if (parent instanceof ViewRootImpl) { 16470 final ViewRootImpl vr = (ViewRootImpl) parent; 16471 vr.transformMatrixToLocal(m); 16472 m.preTranslate(0, vr.mCurScrollY); 16473 } 16474 16475 m.preTranslate(-mLeft, -mTop); 16476 16477 if (!hasIdentityMatrix()) { 16478 m.preConcat(getInverseMatrix()); 16479 } 16480 } 16481 16482 /** 16483 * <p>Computes the coordinates of this view on the screen. The argument 16484 * must be an array of two integers. After the method returns, the array 16485 * contains the x and y location in that order.</p> 16486 * 16487 * @param location an array of two integers in which to hold the coordinates 16488 */ 16489 public void getLocationOnScreen(int[] location) { 16490 getLocationInWindow(location); 16491 16492 final AttachInfo info = mAttachInfo; 16493 if (info != null) { 16494 location[0] += info.mWindowLeft; 16495 location[1] += info.mWindowTop; 16496 } 16497 } 16498 16499 /** 16500 * <p>Computes the coordinates of this view in its window. The argument 16501 * must be an array of two integers. After the method returns, the array 16502 * contains the x and y location in that order.</p> 16503 * 16504 * @param location an array of two integers in which to hold the coordinates 16505 */ 16506 public void getLocationInWindow(int[] location) { 16507 if (location == null || location.length < 2) { 16508 throw new IllegalArgumentException("location must be an array of two integers"); 16509 } 16510 16511 if (mAttachInfo == null) { 16512 // When the view is not attached to a window, this method does not make sense 16513 location[0] = location[1] = 0; 16514 return; 16515 } 16516 16517 float[] position = mAttachInfo.mTmpTransformLocation; 16518 position[0] = position[1] = 0.0f; 16519 16520 if (!hasIdentityMatrix()) { 16521 getMatrix().mapPoints(position); 16522 } 16523 16524 position[0] += mLeft; 16525 position[1] += mTop; 16526 16527 ViewParent viewParent = mParent; 16528 while (viewParent instanceof View) { 16529 final View view = (View) viewParent; 16530 16531 position[0] -= view.mScrollX; 16532 position[1] -= view.mScrollY; 16533 16534 if (!view.hasIdentityMatrix()) { 16535 view.getMatrix().mapPoints(position); 16536 } 16537 16538 position[0] += view.mLeft; 16539 position[1] += view.mTop; 16540 16541 viewParent = view.mParent; 16542 } 16543 16544 if (viewParent instanceof ViewRootImpl) { 16545 // *cough* 16546 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16547 position[1] -= vr.mCurScrollY; 16548 } 16549 16550 location[0] = (int) (position[0] + 0.5f); 16551 location[1] = (int) (position[1] + 0.5f); 16552 } 16553 16554 /** 16555 * {@hide} 16556 * @param id the id of the view to be found 16557 * @return the view of the specified id, null if cannot be found 16558 */ 16559 protected View findViewTraversal(int id) { 16560 if (id == mID) { 16561 return this; 16562 } 16563 return null; 16564 } 16565 16566 /** 16567 * {@hide} 16568 * @param tag the tag of the view to be found 16569 * @return the view of specified tag, null if cannot be found 16570 */ 16571 protected View findViewWithTagTraversal(Object tag) { 16572 if (tag != null && tag.equals(mTag)) { 16573 return this; 16574 } 16575 return null; 16576 } 16577 16578 /** 16579 * {@hide} 16580 * @param predicate The predicate to evaluate. 16581 * @param childToSkip If not null, ignores this child during the recursive traversal. 16582 * @return The first view that matches the predicate or null. 16583 */ 16584 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16585 if (predicate.apply(this)) { 16586 return this; 16587 } 16588 return null; 16589 } 16590 16591 /** 16592 * Look for a child view with the given id. If this view has the given 16593 * id, return this view. 16594 * 16595 * @param id The id to search for. 16596 * @return The view that has the given id in the hierarchy or null 16597 */ 16598 public final View findViewById(int id) { 16599 if (id < 0) { 16600 return null; 16601 } 16602 return findViewTraversal(id); 16603 } 16604 16605 /** 16606 * Finds a view by its unuque and stable accessibility id. 16607 * 16608 * @param accessibilityId The searched accessibility id. 16609 * @return The found view. 16610 */ 16611 final View findViewByAccessibilityId(int accessibilityId) { 16612 if (accessibilityId < 0) { 16613 return null; 16614 } 16615 return findViewByAccessibilityIdTraversal(accessibilityId); 16616 } 16617 16618 /** 16619 * Performs the traversal to find a view by its unuque and stable accessibility id. 16620 * 16621 * <strong>Note:</strong>This method does not stop at the root namespace 16622 * boundary since the user can touch the screen at an arbitrary location 16623 * potentially crossing the root namespace bounday which will send an 16624 * accessibility event to accessibility services and they should be able 16625 * to obtain the event source. Also accessibility ids are guaranteed to be 16626 * unique in the window. 16627 * 16628 * @param accessibilityId The accessibility id. 16629 * @return The found view. 16630 * 16631 * @hide 16632 */ 16633 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16634 if (getAccessibilityViewId() == accessibilityId) { 16635 return this; 16636 } 16637 return null; 16638 } 16639 16640 /** 16641 * Look for a child view with the given tag. If this view has the given 16642 * tag, return this view. 16643 * 16644 * @param tag The tag to search for, using "tag.equals(getTag())". 16645 * @return The View that has the given tag in the hierarchy or null 16646 */ 16647 public final View findViewWithTag(Object tag) { 16648 if (tag == null) { 16649 return null; 16650 } 16651 return findViewWithTagTraversal(tag); 16652 } 16653 16654 /** 16655 * {@hide} 16656 * Look for a child view that matches the specified predicate. 16657 * If this view matches the predicate, return this view. 16658 * 16659 * @param predicate The predicate to evaluate. 16660 * @return The first view that matches the predicate or null. 16661 */ 16662 public final View findViewByPredicate(Predicate<View> predicate) { 16663 return findViewByPredicateTraversal(predicate, null); 16664 } 16665 16666 /** 16667 * {@hide} 16668 * Look for a child view that matches the specified predicate, 16669 * starting with the specified view and its descendents and then 16670 * recusively searching the ancestors and siblings of that view 16671 * until this view is reached. 16672 * 16673 * This method is useful in cases where the predicate does not match 16674 * a single unique view (perhaps multiple views use the same id) 16675 * and we are trying to find the view that is "closest" in scope to the 16676 * starting view. 16677 * 16678 * @param start The view to start from. 16679 * @param predicate The predicate to evaluate. 16680 * @return The first view that matches the predicate or null. 16681 */ 16682 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16683 View childToSkip = null; 16684 for (;;) { 16685 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16686 if (view != null || start == this) { 16687 return view; 16688 } 16689 16690 ViewParent parent = start.getParent(); 16691 if (parent == null || !(parent instanceof View)) { 16692 return null; 16693 } 16694 16695 childToSkip = start; 16696 start = (View) parent; 16697 } 16698 } 16699 16700 /** 16701 * Sets the identifier for this view. The identifier does not have to be 16702 * unique in this view's hierarchy. The identifier should be a positive 16703 * number. 16704 * 16705 * @see #NO_ID 16706 * @see #getId() 16707 * @see #findViewById(int) 16708 * 16709 * @param id a number used to identify the view 16710 * 16711 * @attr ref android.R.styleable#View_id 16712 */ 16713 public void setId(int id) { 16714 mID = id; 16715 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16716 mID = generateViewId(); 16717 } 16718 } 16719 16720 /** 16721 * {@hide} 16722 * 16723 * @param isRoot true if the view belongs to the root namespace, false 16724 * otherwise 16725 */ 16726 public void setIsRootNamespace(boolean isRoot) { 16727 if (isRoot) { 16728 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16729 } else { 16730 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16731 } 16732 } 16733 16734 /** 16735 * {@hide} 16736 * 16737 * @return true if the view belongs to the root namespace, false otherwise 16738 */ 16739 public boolean isRootNamespace() { 16740 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16741 } 16742 16743 /** 16744 * Returns this view's identifier. 16745 * 16746 * @return a positive integer used to identify the view or {@link #NO_ID} 16747 * if the view has no ID 16748 * 16749 * @see #setId(int) 16750 * @see #findViewById(int) 16751 * @attr ref android.R.styleable#View_id 16752 */ 16753 @ViewDebug.CapturedViewProperty 16754 public int getId() { 16755 return mID; 16756 } 16757 16758 /** 16759 * Returns this view's tag. 16760 * 16761 * @return the Object stored in this view as a tag, or {@code null} if not 16762 * set 16763 * 16764 * @see #setTag(Object) 16765 * @see #getTag(int) 16766 */ 16767 @ViewDebug.ExportedProperty 16768 public Object getTag() { 16769 return mTag; 16770 } 16771 16772 /** 16773 * Sets the tag associated with this view. A tag can be used to mark 16774 * a view in its hierarchy and does not have to be unique within the 16775 * hierarchy. Tags can also be used to store data within a view without 16776 * resorting to another data structure. 16777 * 16778 * @param tag an Object to tag the view with 16779 * 16780 * @see #getTag() 16781 * @see #setTag(int, Object) 16782 */ 16783 public void setTag(final Object tag) { 16784 mTag = tag; 16785 } 16786 16787 /** 16788 * Returns the tag associated with this view and the specified key. 16789 * 16790 * @param key The key identifying the tag 16791 * 16792 * @return the Object stored in this view as a tag, or {@code null} if not 16793 * set 16794 * 16795 * @see #setTag(int, Object) 16796 * @see #getTag() 16797 */ 16798 public Object getTag(int key) { 16799 if (mKeyedTags != null) return mKeyedTags.get(key); 16800 return null; 16801 } 16802 16803 /** 16804 * Sets a tag associated with this view and a key. A tag can be used 16805 * to mark a view in its hierarchy and does not have to be unique within 16806 * the hierarchy. Tags can also be used to store data within a view 16807 * without resorting to another data structure. 16808 * 16809 * The specified key should be an id declared in the resources of the 16810 * application to ensure it is unique (see the <a 16811 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16812 * Keys identified as belonging to 16813 * the Android framework or not associated with any package will cause 16814 * an {@link IllegalArgumentException} to be thrown. 16815 * 16816 * @param key The key identifying the tag 16817 * @param tag An Object to tag the view with 16818 * 16819 * @throws IllegalArgumentException If they specified key is not valid 16820 * 16821 * @see #setTag(Object) 16822 * @see #getTag(int) 16823 */ 16824 public void setTag(int key, final Object tag) { 16825 // If the package id is 0x00 or 0x01, it's either an undefined package 16826 // or a framework id 16827 if ((key >>> 24) < 2) { 16828 throw new IllegalArgumentException("The key must be an application-specific " 16829 + "resource id."); 16830 } 16831 16832 setKeyedTag(key, tag); 16833 } 16834 16835 /** 16836 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16837 * framework id. 16838 * 16839 * @hide 16840 */ 16841 public void setTagInternal(int key, Object tag) { 16842 if ((key >>> 24) != 0x1) { 16843 throw new IllegalArgumentException("The key must be a framework-specific " 16844 + "resource id."); 16845 } 16846 16847 setKeyedTag(key, tag); 16848 } 16849 16850 private void setKeyedTag(int key, Object tag) { 16851 if (mKeyedTags == null) { 16852 mKeyedTags = new SparseArray<Object>(2); 16853 } 16854 16855 mKeyedTags.put(key, tag); 16856 } 16857 16858 /** 16859 * Prints information about this view in the log output, with the tag 16860 * {@link #VIEW_LOG_TAG}. 16861 * 16862 * @hide 16863 */ 16864 public void debug() { 16865 debug(0); 16866 } 16867 16868 /** 16869 * Prints information about this view in the log output, with the tag 16870 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16871 * indentation defined by the <code>depth</code>. 16872 * 16873 * @param depth the indentation level 16874 * 16875 * @hide 16876 */ 16877 protected void debug(int depth) { 16878 String output = debugIndent(depth - 1); 16879 16880 output += "+ " + this; 16881 int id = getId(); 16882 if (id != -1) { 16883 output += " (id=" + id + ")"; 16884 } 16885 Object tag = getTag(); 16886 if (tag != null) { 16887 output += " (tag=" + tag + ")"; 16888 } 16889 Log.d(VIEW_LOG_TAG, output); 16890 16891 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16892 output = debugIndent(depth) + " FOCUSED"; 16893 Log.d(VIEW_LOG_TAG, output); 16894 } 16895 16896 output = debugIndent(depth); 16897 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16898 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16899 + "} "; 16900 Log.d(VIEW_LOG_TAG, output); 16901 16902 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16903 || mPaddingBottom != 0) { 16904 output = debugIndent(depth); 16905 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16906 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16907 Log.d(VIEW_LOG_TAG, output); 16908 } 16909 16910 output = debugIndent(depth); 16911 output += "mMeasureWidth=" + mMeasuredWidth + 16912 " mMeasureHeight=" + mMeasuredHeight; 16913 Log.d(VIEW_LOG_TAG, output); 16914 16915 output = debugIndent(depth); 16916 if (mLayoutParams == null) { 16917 output += "BAD! no layout params"; 16918 } else { 16919 output = mLayoutParams.debug(output); 16920 } 16921 Log.d(VIEW_LOG_TAG, output); 16922 16923 output = debugIndent(depth); 16924 output += "flags={"; 16925 output += View.printFlags(mViewFlags); 16926 output += "}"; 16927 Log.d(VIEW_LOG_TAG, output); 16928 16929 output = debugIndent(depth); 16930 output += "privateFlags={"; 16931 output += View.printPrivateFlags(mPrivateFlags); 16932 output += "}"; 16933 Log.d(VIEW_LOG_TAG, output); 16934 } 16935 16936 /** 16937 * Creates a string of whitespaces used for indentation. 16938 * 16939 * @param depth the indentation level 16940 * @return a String containing (depth * 2 + 3) * 2 white spaces 16941 * 16942 * @hide 16943 */ 16944 protected static String debugIndent(int depth) { 16945 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16946 for (int i = 0; i < (depth * 2) + 3; i++) { 16947 spaces.append(' ').append(' '); 16948 } 16949 return spaces.toString(); 16950 } 16951 16952 /** 16953 * <p>Return the offset of the widget's text baseline from the widget's top 16954 * boundary. If this widget does not support baseline alignment, this 16955 * method returns -1. </p> 16956 * 16957 * @return the offset of the baseline within the widget's bounds or -1 16958 * if baseline alignment is not supported 16959 */ 16960 @ViewDebug.ExportedProperty(category = "layout") 16961 public int getBaseline() { 16962 return -1; 16963 } 16964 16965 /** 16966 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16967 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16968 * a layout pass. 16969 * 16970 * @return whether the view hierarchy is currently undergoing a layout pass 16971 */ 16972 public boolean isInLayout() { 16973 ViewRootImpl viewRoot = getViewRootImpl(); 16974 return (viewRoot != null && viewRoot.isInLayout()); 16975 } 16976 16977 /** 16978 * Call this when something has changed which has invalidated the 16979 * layout of this view. This will schedule a layout pass of the view 16980 * tree. This should not be called while the view hierarchy is currently in a layout 16981 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16982 * end of the current layout pass (and then layout will run again) or after the current 16983 * frame is drawn and the next layout occurs. 16984 * 16985 * <p>Subclasses which override this method should call the superclass method to 16986 * handle possible request-during-layout errors correctly.</p> 16987 */ 16988 public void requestLayout() { 16989 if (mMeasureCache != null) mMeasureCache.clear(); 16990 16991 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16992 // Only trigger request-during-layout logic if this is the view requesting it, 16993 // not the views in its parent hierarchy 16994 ViewRootImpl viewRoot = getViewRootImpl(); 16995 if (viewRoot != null && viewRoot.isInLayout()) { 16996 if (!viewRoot.requestLayoutDuringLayout(this)) { 16997 return; 16998 } 16999 } 17000 mAttachInfo.mViewRequestingLayout = this; 17001 } 17002 17003 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17004 mPrivateFlags |= PFLAG_INVALIDATED; 17005 17006 if (mParent != null && !mParent.isLayoutRequested()) { 17007 mParent.requestLayout(); 17008 } 17009 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 17010 mAttachInfo.mViewRequestingLayout = null; 17011 } 17012 } 17013 17014 /** 17015 * Forces this view to be laid out during the next layout pass. 17016 * This method does not call requestLayout() or forceLayout() 17017 * on the parent. 17018 */ 17019 public void forceLayout() { 17020 if (mMeasureCache != null) mMeasureCache.clear(); 17021 17022 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17023 mPrivateFlags |= PFLAG_INVALIDATED; 17024 } 17025 17026 /** 17027 * <p> 17028 * This is called to find out how big a view should be. The parent 17029 * supplies constraint information in the width and height parameters. 17030 * </p> 17031 * 17032 * <p> 17033 * The actual measurement work of a view is performed in 17034 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 17035 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 17036 * </p> 17037 * 17038 * 17039 * @param widthMeasureSpec Horizontal space requirements as imposed by the 17040 * parent 17041 * @param heightMeasureSpec Vertical space requirements as imposed by the 17042 * parent 17043 * 17044 * @see #onMeasure(int, int) 17045 */ 17046 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 17047 boolean optical = isLayoutModeOptical(this); 17048 if (optical != isLayoutModeOptical(mParent)) { 17049 Insets insets = getOpticalInsets(); 17050 int oWidth = insets.left + insets.right; 17051 int oHeight = insets.top + insets.bottom; 17052 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 17053 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 17054 } 17055 17056 // Suppress sign extension for the low bytes 17057 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 17058 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 17059 17060 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 17061 widthMeasureSpec != mOldWidthMeasureSpec || 17062 heightMeasureSpec != mOldHeightMeasureSpec) { 17063 17064 // first clears the measured dimension flag 17065 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 17066 17067 resolveRtlPropertiesIfNeeded(); 17068 17069 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 17070 mMeasureCache.indexOfKey(key); 17071 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17072 // measure ourselves, this should set the measured dimension flag back 17073 onMeasure(widthMeasureSpec, heightMeasureSpec); 17074 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17075 } else { 17076 long value = mMeasureCache.valueAt(cacheIndex); 17077 // Casting a long to int drops the high 32 bits, no mask needed 17078 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17079 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17080 } 17081 17082 // flag not set, setMeasuredDimension() was not invoked, we raise 17083 // an exception to warn the developer 17084 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17085 throw new IllegalStateException("onMeasure() did not set the" 17086 + " measured dimension by calling" 17087 + " setMeasuredDimension()"); 17088 } 17089 17090 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17091 } 17092 17093 mOldWidthMeasureSpec = widthMeasureSpec; 17094 mOldHeightMeasureSpec = heightMeasureSpec; 17095 17096 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17097 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17098 } 17099 17100 /** 17101 * <p> 17102 * Measure the view and its content to determine the measured width and the 17103 * measured height. This method is invoked by {@link #measure(int, int)} and 17104 * should be overriden by subclasses to provide accurate and efficient 17105 * measurement of their contents. 17106 * </p> 17107 * 17108 * <p> 17109 * <strong>CONTRACT:</strong> When overriding this method, you 17110 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17111 * measured width and height of this view. Failure to do so will trigger an 17112 * <code>IllegalStateException</code>, thrown by 17113 * {@link #measure(int, int)}. Calling the superclass' 17114 * {@link #onMeasure(int, int)} is a valid use. 17115 * </p> 17116 * 17117 * <p> 17118 * The base class implementation of measure defaults to the background size, 17119 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17120 * override {@link #onMeasure(int, int)} to provide better measurements of 17121 * their content. 17122 * </p> 17123 * 17124 * <p> 17125 * If this method is overridden, it is the subclass's responsibility to make 17126 * sure the measured height and width are at least the view's minimum height 17127 * and width ({@link #getSuggestedMinimumHeight()} and 17128 * {@link #getSuggestedMinimumWidth()}). 17129 * </p> 17130 * 17131 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17132 * The requirements are encoded with 17133 * {@link android.view.View.MeasureSpec}. 17134 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17135 * The requirements are encoded with 17136 * {@link android.view.View.MeasureSpec}. 17137 * 17138 * @see #getMeasuredWidth() 17139 * @see #getMeasuredHeight() 17140 * @see #setMeasuredDimension(int, int) 17141 * @see #getSuggestedMinimumHeight() 17142 * @see #getSuggestedMinimumWidth() 17143 * @see android.view.View.MeasureSpec#getMode(int) 17144 * @see android.view.View.MeasureSpec#getSize(int) 17145 */ 17146 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17147 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17148 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17149 } 17150 17151 /** 17152 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17153 * measured width and measured height. Failing to do so will trigger an 17154 * exception at measurement time.</p> 17155 * 17156 * @param measuredWidth The measured width of this view. May be a complex 17157 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17158 * {@link #MEASURED_STATE_TOO_SMALL}. 17159 * @param measuredHeight The measured height of this view. May be a complex 17160 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17161 * {@link #MEASURED_STATE_TOO_SMALL}. 17162 */ 17163 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17164 boolean optical = isLayoutModeOptical(this); 17165 if (optical != isLayoutModeOptical(mParent)) { 17166 Insets insets = getOpticalInsets(); 17167 int opticalWidth = insets.left + insets.right; 17168 int opticalHeight = insets.top + insets.bottom; 17169 17170 measuredWidth += optical ? opticalWidth : -opticalWidth; 17171 measuredHeight += optical ? opticalHeight : -opticalHeight; 17172 } 17173 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17174 } 17175 17176 /** 17177 * Sets the measured dimension without extra processing for things like optical bounds. 17178 * Useful for reapplying consistent values that have already been cooked with adjustments 17179 * for optical bounds, etc. such as those from the measurement cache. 17180 * 17181 * @param measuredWidth The measured width of this view. May be a complex 17182 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17183 * {@link #MEASURED_STATE_TOO_SMALL}. 17184 * @param measuredHeight The measured height of this view. May be a complex 17185 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17186 * {@link #MEASURED_STATE_TOO_SMALL}. 17187 */ 17188 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17189 mMeasuredWidth = measuredWidth; 17190 mMeasuredHeight = measuredHeight; 17191 17192 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17193 } 17194 17195 /** 17196 * Merge two states as returned by {@link #getMeasuredState()}. 17197 * @param curState The current state as returned from a view or the result 17198 * of combining multiple views. 17199 * @param newState The new view state to combine. 17200 * @return Returns a new integer reflecting the combination of the two 17201 * states. 17202 */ 17203 public static int combineMeasuredStates(int curState, int newState) { 17204 return curState | newState; 17205 } 17206 17207 /** 17208 * Version of {@link #resolveSizeAndState(int, int, int)} 17209 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17210 */ 17211 public static int resolveSize(int size, int measureSpec) { 17212 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17213 } 17214 17215 /** 17216 * Utility to reconcile a desired size and state, with constraints imposed 17217 * by a MeasureSpec. Will take the desired size, unless a different size 17218 * is imposed by the constraints. The returned value is a compound integer, 17219 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17220 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17221 * size is smaller than the size the view wants to be. 17222 * 17223 * @param size How big the view wants to be 17224 * @param measureSpec Constraints imposed by the parent 17225 * @return Size information bit mask as defined by 17226 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17227 */ 17228 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17229 int result = size; 17230 int specMode = MeasureSpec.getMode(measureSpec); 17231 int specSize = MeasureSpec.getSize(measureSpec); 17232 switch (specMode) { 17233 case MeasureSpec.UNSPECIFIED: 17234 result = size; 17235 break; 17236 case MeasureSpec.AT_MOST: 17237 if (specSize < size) { 17238 result = specSize | MEASURED_STATE_TOO_SMALL; 17239 } else { 17240 result = size; 17241 } 17242 break; 17243 case MeasureSpec.EXACTLY: 17244 result = specSize; 17245 break; 17246 } 17247 return result | (childMeasuredState&MEASURED_STATE_MASK); 17248 } 17249 17250 /** 17251 * Utility to return a default size. Uses the supplied size if the 17252 * MeasureSpec imposed no constraints. Will get larger if allowed 17253 * by the MeasureSpec. 17254 * 17255 * @param size Default size for this view 17256 * @param measureSpec Constraints imposed by the parent 17257 * @return The size this view should be. 17258 */ 17259 public static int getDefaultSize(int size, int measureSpec) { 17260 int result = size; 17261 int specMode = MeasureSpec.getMode(measureSpec); 17262 int specSize = MeasureSpec.getSize(measureSpec); 17263 17264 switch (specMode) { 17265 case MeasureSpec.UNSPECIFIED: 17266 result = size; 17267 break; 17268 case MeasureSpec.AT_MOST: 17269 case MeasureSpec.EXACTLY: 17270 result = specSize; 17271 break; 17272 } 17273 return result; 17274 } 17275 17276 /** 17277 * Returns the suggested minimum height that the view should use. This 17278 * returns the maximum of the view's minimum height 17279 * and the background's minimum height 17280 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17281 * <p> 17282 * When being used in {@link #onMeasure(int, int)}, the caller should still 17283 * ensure the returned height is within the requirements of the parent. 17284 * 17285 * @return The suggested minimum height of the view. 17286 */ 17287 protected int getSuggestedMinimumHeight() { 17288 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17289 17290 } 17291 17292 /** 17293 * Returns the suggested minimum width that the view should use. This 17294 * returns the maximum of the view's minimum width) 17295 * and the background's minimum width 17296 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17297 * <p> 17298 * When being used in {@link #onMeasure(int, int)}, the caller should still 17299 * ensure the returned width is within the requirements of the parent. 17300 * 17301 * @return The suggested minimum width of the view. 17302 */ 17303 protected int getSuggestedMinimumWidth() { 17304 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17305 } 17306 17307 /** 17308 * Returns the minimum height of the view. 17309 * 17310 * @return the minimum height the view will try to be. 17311 * 17312 * @see #setMinimumHeight(int) 17313 * 17314 * @attr ref android.R.styleable#View_minHeight 17315 */ 17316 public int getMinimumHeight() { 17317 return mMinHeight; 17318 } 17319 17320 /** 17321 * Sets the minimum height of the view. It is not guaranteed the view will 17322 * be able to achieve this minimum height (for example, if its parent layout 17323 * constrains it with less available height). 17324 * 17325 * @param minHeight The minimum height the view will try to be. 17326 * 17327 * @see #getMinimumHeight() 17328 * 17329 * @attr ref android.R.styleable#View_minHeight 17330 */ 17331 public void setMinimumHeight(int minHeight) { 17332 mMinHeight = minHeight; 17333 requestLayout(); 17334 } 17335 17336 /** 17337 * Returns the minimum width of the view. 17338 * 17339 * @return the minimum width the view will try to be. 17340 * 17341 * @see #setMinimumWidth(int) 17342 * 17343 * @attr ref android.R.styleable#View_minWidth 17344 */ 17345 public int getMinimumWidth() { 17346 return mMinWidth; 17347 } 17348 17349 /** 17350 * Sets the minimum width of the view. It is not guaranteed the view will 17351 * be able to achieve this minimum width (for example, if its parent layout 17352 * constrains it with less available width). 17353 * 17354 * @param minWidth The minimum width the view will try to be. 17355 * 17356 * @see #getMinimumWidth() 17357 * 17358 * @attr ref android.R.styleable#View_minWidth 17359 */ 17360 public void setMinimumWidth(int minWidth) { 17361 mMinWidth = minWidth; 17362 requestLayout(); 17363 17364 } 17365 17366 /** 17367 * Get the animation currently associated with this view. 17368 * 17369 * @return The animation that is currently playing or 17370 * scheduled to play for this view. 17371 */ 17372 public Animation getAnimation() { 17373 return mCurrentAnimation; 17374 } 17375 17376 /** 17377 * Start the specified animation now. 17378 * 17379 * @param animation the animation to start now 17380 */ 17381 public void startAnimation(Animation animation) { 17382 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17383 setAnimation(animation); 17384 invalidateParentCaches(); 17385 invalidate(true); 17386 } 17387 17388 /** 17389 * Cancels any animations for this view. 17390 */ 17391 public void clearAnimation() { 17392 if (mCurrentAnimation != null) { 17393 mCurrentAnimation.detach(); 17394 } 17395 mCurrentAnimation = null; 17396 invalidateParentIfNeeded(); 17397 } 17398 17399 /** 17400 * Sets the next animation to play for this view. 17401 * If you want the animation to play immediately, use 17402 * {@link #startAnimation(android.view.animation.Animation)} instead. 17403 * This method provides allows fine-grained 17404 * control over the start time and invalidation, but you 17405 * must make sure that 1) the animation has a start time set, and 17406 * 2) the view's parent (which controls animations on its children) 17407 * will be invalidated when the animation is supposed to 17408 * start. 17409 * 17410 * @param animation The next animation, or null. 17411 */ 17412 public void setAnimation(Animation animation) { 17413 mCurrentAnimation = animation; 17414 17415 if (animation != null) { 17416 // If the screen is off assume the animation start time is now instead of 17417 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17418 // would cause the animation to start when the screen turns back on 17419 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17420 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17421 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17422 } 17423 animation.reset(); 17424 } 17425 } 17426 17427 /** 17428 * Invoked by a parent ViewGroup to notify the start of the animation 17429 * currently associated with this view. If you override this method, 17430 * always call super.onAnimationStart(); 17431 * 17432 * @see #setAnimation(android.view.animation.Animation) 17433 * @see #getAnimation() 17434 */ 17435 protected void onAnimationStart() { 17436 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17437 } 17438 17439 /** 17440 * Invoked by a parent ViewGroup to notify the end of the animation 17441 * currently associated with this view. If you override this method, 17442 * always call super.onAnimationEnd(); 17443 * 17444 * @see #setAnimation(android.view.animation.Animation) 17445 * @see #getAnimation() 17446 */ 17447 protected void onAnimationEnd() { 17448 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17449 } 17450 17451 /** 17452 * Invoked if there is a Transform that involves alpha. Subclass that can 17453 * draw themselves with the specified alpha should return true, and then 17454 * respect that alpha when their onDraw() is called. If this returns false 17455 * then the view may be redirected to draw into an offscreen buffer to 17456 * fulfill the request, which will look fine, but may be slower than if the 17457 * subclass handles it internally. The default implementation returns false. 17458 * 17459 * @param alpha The alpha (0..255) to apply to the view's drawing 17460 * @return true if the view can draw with the specified alpha. 17461 */ 17462 protected boolean onSetAlpha(int alpha) { 17463 return false; 17464 } 17465 17466 /** 17467 * This is used by the RootView to perform an optimization when 17468 * the view hierarchy contains one or several SurfaceView. 17469 * SurfaceView is always considered transparent, but its children are not, 17470 * therefore all View objects remove themselves from the global transparent 17471 * region (passed as a parameter to this function). 17472 * 17473 * @param region The transparent region for this ViewAncestor (window). 17474 * 17475 * @return Returns true if the effective visibility of the view at this 17476 * point is opaque, regardless of the transparent region; returns false 17477 * if it is possible for underlying windows to be seen behind the view. 17478 * 17479 * {@hide} 17480 */ 17481 public boolean gatherTransparentRegion(Region region) { 17482 final AttachInfo attachInfo = mAttachInfo; 17483 if (region != null && attachInfo != null) { 17484 final int pflags = mPrivateFlags; 17485 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17486 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17487 // remove it from the transparent region. 17488 final int[] location = attachInfo.mTransparentLocation; 17489 getLocationInWindow(location); 17490 region.op(location[0], location[1], location[0] + mRight - mLeft, 17491 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17492 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null && 17493 mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 17494 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17495 // exists, so we remove the background drawable's non-transparent 17496 // parts from this transparent region. 17497 applyDrawableToTransparentRegion(mBackground, region); 17498 } 17499 } 17500 return true; 17501 } 17502 17503 /** 17504 * Play a sound effect for this view. 17505 * 17506 * <p>The framework will play sound effects for some built in actions, such as 17507 * clicking, but you may wish to play these effects in your widget, 17508 * for instance, for internal navigation. 17509 * 17510 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17511 * {@link #isSoundEffectsEnabled()} is true. 17512 * 17513 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17514 */ 17515 public void playSoundEffect(int soundConstant) { 17516 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17517 return; 17518 } 17519 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17520 } 17521 17522 /** 17523 * BZZZTT!!1! 17524 * 17525 * <p>Provide haptic feedback to the user for this view. 17526 * 17527 * <p>The framework will provide haptic feedback for some built in actions, 17528 * such as long presses, but you may wish to provide feedback for your 17529 * own widget. 17530 * 17531 * <p>The feedback will only be performed if 17532 * {@link #isHapticFeedbackEnabled()} is true. 17533 * 17534 * @param feedbackConstant One of the constants defined in 17535 * {@link HapticFeedbackConstants} 17536 */ 17537 public boolean performHapticFeedback(int feedbackConstant) { 17538 return performHapticFeedback(feedbackConstant, 0); 17539 } 17540 17541 /** 17542 * BZZZTT!!1! 17543 * 17544 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17545 * 17546 * @param feedbackConstant One of the constants defined in 17547 * {@link HapticFeedbackConstants} 17548 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17549 */ 17550 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17551 if (mAttachInfo == null) { 17552 return false; 17553 } 17554 //noinspection SimplifiableIfStatement 17555 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17556 && !isHapticFeedbackEnabled()) { 17557 return false; 17558 } 17559 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17560 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17561 } 17562 17563 /** 17564 * Request that the visibility of the status bar or other screen/window 17565 * decorations be changed. 17566 * 17567 * <p>This method is used to put the over device UI into temporary modes 17568 * where the user's attention is focused more on the application content, 17569 * by dimming or hiding surrounding system affordances. This is typically 17570 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17571 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17572 * to be placed behind the action bar (and with these flags other system 17573 * affordances) so that smooth transitions between hiding and showing them 17574 * can be done. 17575 * 17576 * <p>Two representative examples of the use of system UI visibility is 17577 * implementing a content browsing application (like a magazine reader) 17578 * and a video playing application. 17579 * 17580 * <p>The first code shows a typical implementation of a View in a content 17581 * browsing application. In this implementation, the application goes 17582 * into a content-oriented mode by hiding the status bar and action bar, 17583 * and putting the navigation elements into lights out mode. The user can 17584 * then interact with content while in this mode. Such an application should 17585 * provide an easy way for the user to toggle out of the mode (such as to 17586 * check information in the status bar or access notifications). In the 17587 * implementation here, this is done simply by tapping on the content. 17588 * 17589 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17590 * content} 17591 * 17592 * <p>This second code sample shows a typical implementation of a View 17593 * in a video playing application. In this situation, while the video is 17594 * playing the application would like to go into a complete full-screen mode, 17595 * to use as much of the display as possible for the video. When in this state 17596 * the user can not interact with the application; the system intercepts 17597 * touching on the screen to pop the UI out of full screen mode. See 17598 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17599 * 17600 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17601 * content} 17602 * 17603 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17604 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17605 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17606 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17607 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17608 */ 17609 public void setSystemUiVisibility(int visibility) { 17610 if (visibility != mSystemUiVisibility) { 17611 mSystemUiVisibility = visibility; 17612 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17613 mParent.recomputeViewAttributes(this); 17614 } 17615 } 17616 } 17617 17618 /** 17619 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17620 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17621 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17622 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17623 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17624 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17625 */ 17626 public int getSystemUiVisibility() { 17627 return mSystemUiVisibility; 17628 } 17629 17630 /** 17631 * Returns the current system UI visibility that is currently set for 17632 * the entire window. This is the combination of the 17633 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17634 * views in the window. 17635 */ 17636 public int getWindowSystemUiVisibility() { 17637 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17638 } 17639 17640 /** 17641 * Override to find out when the window's requested system UI visibility 17642 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17643 * This is different from the callbacks received through 17644 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17645 * in that this is only telling you about the local request of the window, 17646 * not the actual values applied by the system. 17647 */ 17648 public void onWindowSystemUiVisibilityChanged(int visible) { 17649 } 17650 17651 /** 17652 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17653 * the view hierarchy. 17654 */ 17655 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17656 onWindowSystemUiVisibilityChanged(visible); 17657 } 17658 17659 /** 17660 * Set a listener to receive callbacks when the visibility of the system bar changes. 17661 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17662 */ 17663 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17664 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17665 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17666 mParent.recomputeViewAttributes(this); 17667 } 17668 } 17669 17670 /** 17671 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17672 * the view hierarchy. 17673 */ 17674 public void dispatchSystemUiVisibilityChanged(int visibility) { 17675 ListenerInfo li = mListenerInfo; 17676 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17677 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17678 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17679 } 17680 } 17681 17682 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17683 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17684 if (val != mSystemUiVisibility) { 17685 setSystemUiVisibility(val); 17686 return true; 17687 } 17688 return false; 17689 } 17690 17691 /** @hide */ 17692 public void setDisabledSystemUiVisibility(int flags) { 17693 if (mAttachInfo != null) { 17694 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17695 mAttachInfo.mDisabledSystemUiVisibility = flags; 17696 if (mParent != null) { 17697 mParent.recomputeViewAttributes(this); 17698 } 17699 } 17700 } 17701 } 17702 17703 /** 17704 * Creates an image that the system displays during the drag and drop 17705 * operation. This is called a "drag shadow". The default implementation 17706 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17707 * appearance as the given View. The default also positions the center of the drag shadow 17708 * directly under the touch point. If no View is provided (the constructor with no parameters 17709 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17710 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17711 * default is an invisible drag shadow. 17712 * <p> 17713 * You are not required to use the View you provide to the constructor as the basis of the 17714 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17715 * anything you want as the drag shadow. 17716 * </p> 17717 * <p> 17718 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17719 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17720 * size and position of the drag shadow. It uses this data to construct a 17721 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17722 * so that your application can draw the shadow image in the Canvas. 17723 * </p> 17724 * 17725 * <div class="special reference"> 17726 * <h3>Developer Guides</h3> 17727 * <p>For a guide to implementing drag and drop features, read the 17728 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17729 * </div> 17730 */ 17731 public static class DragShadowBuilder { 17732 private final WeakReference<View> mView; 17733 17734 /** 17735 * Constructs a shadow image builder based on a View. By default, the resulting drag 17736 * shadow will have the same appearance and dimensions as the View, with the touch point 17737 * over the center of the View. 17738 * @param view A View. Any View in scope can be used. 17739 */ 17740 public DragShadowBuilder(View view) { 17741 mView = new WeakReference<View>(view); 17742 } 17743 17744 /** 17745 * Construct a shadow builder object with no associated View. This 17746 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17747 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17748 * to supply the drag shadow's dimensions and appearance without 17749 * reference to any View object. If they are not overridden, then the result is an 17750 * invisible drag shadow. 17751 */ 17752 public DragShadowBuilder() { 17753 mView = new WeakReference<View>(null); 17754 } 17755 17756 /** 17757 * Returns the View object that had been passed to the 17758 * {@link #View.DragShadowBuilder(View)} 17759 * constructor. If that View parameter was {@code null} or if the 17760 * {@link #View.DragShadowBuilder()} 17761 * constructor was used to instantiate the builder object, this method will return 17762 * null. 17763 * 17764 * @return The View object associate with this builder object. 17765 */ 17766 @SuppressWarnings({"JavadocReference"}) 17767 final public View getView() { 17768 return mView.get(); 17769 } 17770 17771 /** 17772 * Provides the metrics for the shadow image. These include the dimensions of 17773 * the shadow image, and the point within that shadow that should 17774 * be centered under the touch location while dragging. 17775 * <p> 17776 * The default implementation sets the dimensions of the shadow to be the 17777 * same as the dimensions of the View itself and centers the shadow under 17778 * the touch point. 17779 * </p> 17780 * 17781 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17782 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17783 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17784 * image. 17785 * 17786 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17787 * shadow image that should be underneath the touch point during the drag and drop 17788 * operation. Your application must set {@link android.graphics.Point#x} to the 17789 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17790 */ 17791 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17792 final View view = mView.get(); 17793 if (view != null) { 17794 shadowSize.set(view.getWidth(), view.getHeight()); 17795 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17796 } else { 17797 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17798 } 17799 } 17800 17801 /** 17802 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17803 * based on the dimensions it received from the 17804 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17805 * 17806 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17807 */ 17808 public void onDrawShadow(Canvas canvas) { 17809 final View view = mView.get(); 17810 if (view != null) { 17811 view.draw(canvas); 17812 } else { 17813 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17814 } 17815 } 17816 } 17817 17818 /** 17819 * Starts a drag and drop operation. When your application calls this method, it passes a 17820 * {@link android.view.View.DragShadowBuilder} object to the system. The 17821 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17822 * to get metrics for the drag shadow, and then calls the object's 17823 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17824 * <p> 17825 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17826 * drag events to all the View objects in your application that are currently visible. It does 17827 * this either by calling the View object's drag listener (an implementation of 17828 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17829 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17830 * Both are passed a {@link android.view.DragEvent} object that has a 17831 * {@link android.view.DragEvent#getAction()} value of 17832 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17833 * </p> 17834 * <p> 17835 * Your application can invoke startDrag() on any attached View object. The View object does not 17836 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17837 * be related to the View the user selected for dragging. 17838 * </p> 17839 * @param data A {@link android.content.ClipData} object pointing to the data to be 17840 * transferred by the drag and drop operation. 17841 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17842 * drag shadow. 17843 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17844 * drop operation. This Object is put into every DragEvent object sent by the system during the 17845 * current drag. 17846 * <p> 17847 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17848 * to the target Views. For example, it can contain flags that differentiate between a 17849 * a copy operation and a move operation. 17850 * </p> 17851 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17852 * so the parameter should be set to 0. 17853 * @return {@code true} if the method completes successfully, or 17854 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17855 * do a drag, and so no drag operation is in progress. 17856 */ 17857 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17858 Object myLocalState, int flags) { 17859 if (ViewDebug.DEBUG_DRAG) { 17860 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17861 } 17862 boolean okay = false; 17863 17864 Point shadowSize = new Point(); 17865 Point shadowTouchPoint = new Point(); 17866 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17867 17868 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17869 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17870 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17871 } 17872 17873 if (ViewDebug.DEBUG_DRAG) { 17874 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17875 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17876 } 17877 Surface surface = new Surface(); 17878 try { 17879 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17880 flags, shadowSize.x, shadowSize.y, surface); 17881 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17882 + " surface=" + surface); 17883 if (token != null) { 17884 Canvas canvas = surface.lockCanvas(null); 17885 try { 17886 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17887 shadowBuilder.onDrawShadow(canvas); 17888 } finally { 17889 surface.unlockCanvasAndPost(canvas); 17890 } 17891 17892 final ViewRootImpl root = getViewRootImpl(); 17893 17894 // Cache the local state object for delivery with DragEvents 17895 root.setLocalDragState(myLocalState); 17896 17897 // repurpose 'shadowSize' for the last touch point 17898 root.getLastTouchPoint(shadowSize); 17899 17900 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17901 shadowSize.x, shadowSize.y, 17902 shadowTouchPoint.x, shadowTouchPoint.y, data); 17903 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17904 17905 // Off and running! Release our local surface instance; the drag 17906 // shadow surface is now managed by the system process. 17907 surface.release(); 17908 } 17909 } catch (Exception e) { 17910 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17911 surface.destroy(); 17912 } 17913 17914 return okay; 17915 } 17916 17917 /** 17918 * Handles drag events sent by the system following a call to 17919 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17920 *<p> 17921 * When the system calls this method, it passes a 17922 * {@link android.view.DragEvent} object. A call to 17923 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17924 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17925 * operation. 17926 * @param event The {@link android.view.DragEvent} sent by the system. 17927 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17928 * in DragEvent, indicating the type of drag event represented by this object. 17929 * @return {@code true} if the method was successful, otherwise {@code false}. 17930 * <p> 17931 * The method should return {@code true} in response to an action type of 17932 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17933 * operation. 17934 * </p> 17935 * <p> 17936 * The method should also return {@code true} in response to an action type of 17937 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17938 * {@code false} if it didn't. 17939 * </p> 17940 */ 17941 public boolean onDragEvent(DragEvent event) { 17942 return false; 17943 } 17944 17945 /** 17946 * Detects if this View is enabled and has a drag event listener. 17947 * If both are true, then it calls the drag event listener with the 17948 * {@link android.view.DragEvent} it received. If the drag event listener returns 17949 * {@code true}, then dispatchDragEvent() returns {@code true}. 17950 * <p> 17951 * For all other cases, the method calls the 17952 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17953 * method and returns its result. 17954 * </p> 17955 * <p> 17956 * This ensures that a drag event is always consumed, even if the View does not have a drag 17957 * event listener. However, if the View has a listener and the listener returns true, then 17958 * onDragEvent() is not called. 17959 * </p> 17960 */ 17961 public boolean dispatchDragEvent(DragEvent event) { 17962 ListenerInfo li = mListenerInfo; 17963 //noinspection SimplifiableIfStatement 17964 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17965 && li.mOnDragListener.onDrag(this, event)) { 17966 return true; 17967 } 17968 return onDragEvent(event); 17969 } 17970 17971 boolean canAcceptDrag() { 17972 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17973 } 17974 17975 /** 17976 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17977 * it is ever exposed at all. 17978 * @hide 17979 */ 17980 public void onCloseSystemDialogs(String reason) { 17981 } 17982 17983 /** 17984 * Given a Drawable whose bounds have been set to draw into this view, 17985 * update a Region being computed for 17986 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17987 * that any non-transparent parts of the Drawable are removed from the 17988 * given transparent region. 17989 * 17990 * @param dr The Drawable whose transparency is to be applied to the region. 17991 * @param region A Region holding the current transparency information, 17992 * where any parts of the region that are set are considered to be 17993 * transparent. On return, this region will be modified to have the 17994 * transparency information reduced by the corresponding parts of the 17995 * Drawable that are not transparent. 17996 * {@hide} 17997 */ 17998 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17999 if (DBG) { 18000 Log.i("View", "Getting transparent region for: " + this); 18001 } 18002 final Region r = dr.getTransparentRegion(); 18003 final Rect db = dr.getBounds(); 18004 final AttachInfo attachInfo = mAttachInfo; 18005 if (r != null && attachInfo != null) { 18006 final int w = getRight()-getLeft(); 18007 final int h = getBottom()-getTop(); 18008 if (db.left > 0) { 18009 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 18010 r.op(0, 0, db.left, h, Region.Op.UNION); 18011 } 18012 if (db.right < w) { 18013 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 18014 r.op(db.right, 0, w, h, Region.Op.UNION); 18015 } 18016 if (db.top > 0) { 18017 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 18018 r.op(0, 0, w, db.top, Region.Op.UNION); 18019 } 18020 if (db.bottom < h) { 18021 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 18022 r.op(0, db.bottom, w, h, Region.Op.UNION); 18023 } 18024 final int[] location = attachInfo.mTransparentLocation; 18025 getLocationInWindow(location); 18026 r.translate(location[0], location[1]); 18027 region.op(r, Region.Op.INTERSECT); 18028 } else { 18029 region.op(db, Region.Op.DIFFERENCE); 18030 } 18031 } 18032 18033 private void checkForLongClick(int delayOffset) { 18034 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 18035 mHasPerformedLongPress = false; 18036 18037 if (mPendingCheckForLongPress == null) { 18038 mPendingCheckForLongPress = new CheckForLongPress(); 18039 } 18040 mPendingCheckForLongPress.rememberWindowAttachCount(); 18041 postDelayed(mPendingCheckForLongPress, 18042 ViewConfiguration.getLongPressTimeout() - delayOffset); 18043 } 18044 } 18045 18046 /** 18047 * Inflate a view from an XML resource. This convenience method wraps the {@link 18048 * LayoutInflater} class, which provides a full range of options for view inflation. 18049 * 18050 * @param context The Context object for your activity or application. 18051 * @param resource The resource ID to inflate 18052 * @param root A view group that will be the parent. Used to properly inflate the 18053 * layout_* parameters. 18054 * @see LayoutInflater 18055 */ 18056 public static View inflate(Context context, int resource, ViewGroup root) { 18057 LayoutInflater factory = LayoutInflater.from(context); 18058 return factory.inflate(resource, root); 18059 } 18060 18061 /** 18062 * Scroll the view with standard behavior for scrolling beyond the normal 18063 * content boundaries. Views that call this method should override 18064 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 18065 * results of an over-scroll operation. 18066 * 18067 * Views can use this method to handle any touch or fling-based scrolling. 18068 * 18069 * @param deltaX Change in X in pixels 18070 * @param deltaY Change in Y in pixels 18071 * @param scrollX Current X scroll value in pixels before applying deltaX 18072 * @param scrollY Current Y scroll value in pixels before applying deltaY 18073 * @param scrollRangeX Maximum content scroll range along the X axis 18074 * @param scrollRangeY Maximum content scroll range along the Y axis 18075 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18076 * along the X axis. 18077 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18078 * along the Y axis. 18079 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18080 * @return true if scrolling was clamped to an over-scroll boundary along either 18081 * axis, false otherwise. 18082 */ 18083 @SuppressWarnings({"UnusedParameters"}) 18084 protected boolean overScrollBy(int deltaX, int deltaY, 18085 int scrollX, int scrollY, 18086 int scrollRangeX, int scrollRangeY, 18087 int maxOverScrollX, int maxOverScrollY, 18088 boolean isTouchEvent) { 18089 final int overScrollMode = mOverScrollMode; 18090 final boolean canScrollHorizontal = 18091 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18092 final boolean canScrollVertical = 18093 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18094 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18095 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18096 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18097 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18098 18099 int newScrollX = scrollX + deltaX; 18100 if (!overScrollHorizontal) { 18101 maxOverScrollX = 0; 18102 } 18103 18104 int newScrollY = scrollY + deltaY; 18105 if (!overScrollVertical) { 18106 maxOverScrollY = 0; 18107 } 18108 18109 // Clamp values if at the limits and record 18110 final int left = -maxOverScrollX; 18111 final int right = maxOverScrollX + scrollRangeX; 18112 final int top = -maxOverScrollY; 18113 final int bottom = maxOverScrollY + scrollRangeY; 18114 18115 boolean clampedX = false; 18116 if (newScrollX > right) { 18117 newScrollX = right; 18118 clampedX = true; 18119 } else if (newScrollX < left) { 18120 newScrollX = left; 18121 clampedX = true; 18122 } 18123 18124 boolean clampedY = false; 18125 if (newScrollY > bottom) { 18126 newScrollY = bottom; 18127 clampedY = true; 18128 } else if (newScrollY < top) { 18129 newScrollY = top; 18130 clampedY = true; 18131 } 18132 18133 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18134 18135 return clampedX || clampedY; 18136 } 18137 18138 /** 18139 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18140 * respond to the results of an over-scroll operation. 18141 * 18142 * @param scrollX New X scroll value in pixels 18143 * @param scrollY New Y scroll value in pixels 18144 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18145 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18146 */ 18147 protected void onOverScrolled(int scrollX, int scrollY, 18148 boolean clampedX, boolean clampedY) { 18149 // Intentionally empty. 18150 } 18151 18152 /** 18153 * Returns the over-scroll mode for this view. The result will be 18154 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18155 * (allow over-scrolling only if the view content is larger than the container), 18156 * or {@link #OVER_SCROLL_NEVER}. 18157 * 18158 * @return This view's over-scroll mode. 18159 */ 18160 public int getOverScrollMode() { 18161 return mOverScrollMode; 18162 } 18163 18164 /** 18165 * Set the over-scroll mode for this view. Valid over-scroll modes are 18166 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18167 * (allow over-scrolling only if the view content is larger than the container), 18168 * or {@link #OVER_SCROLL_NEVER}. 18169 * 18170 * Setting the over-scroll mode of a view will have an effect only if the 18171 * view is capable of scrolling. 18172 * 18173 * @param overScrollMode The new over-scroll mode for this view. 18174 */ 18175 public void setOverScrollMode(int overScrollMode) { 18176 if (overScrollMode != OVER_SCROLL_ALWAYS && 18177 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18178 overScrollMode != OVER_SCROLL_NEVER) { 18179 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18180 } 18181 mOverScrollMode = overScrollMode; 18182 } 18183 18184 /** 18185 * Enable or disable nested scrolling for this view. 18186 * 18187 * <p>If this property is set to true the view will be permitted to initiate nested 18188 * scrolling operations with a compatible parent view in the current hierarchy. If this 18189 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18190 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18191 * the nested scroll.</p> 18192 * 18193 * @param enabled true to enable nested scrolling, false to disable 18194 * 18195 * @see #isNestedScrollingEnabled() 18196 */ 18197 public void setNestedScrollingEnabled(boolean enabled) { 18198 if (enabled) { 18199 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18200 } else { 18201 stopNestedScroll(); 18202 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18203 } 18204 } 18205 18206 /** 18207 * Returns true if nested scrolling is enabled for this view. 18208 * 18209 * <p>If nested scrolling is enabled and this View class implementation supports it, 18210 * this view will act as a nested scrolling child view when applicable, forwarding data 18211 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18212 * parent.</p> 18213 * 18214 * @return true if nested scrolling is enabled 18215 * 18216 * @see #setNestedScrollingEnabled(boolean) 18217 */ 18218 public boolean isNestedScrollingEnabled() { 18219 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18220 PFLAG3_NESTED_SCROLLING_ENABLED; 18221 } 18222 18223 /** 18224 * Begin a nestable scroll operation along the given axes. 18225 * 18226 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18227 * 18228 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18229 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18230 * In the case of touch scrolling the nested scroll will be terminated automatically in 18231 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18232 * In the event of programmatic scrolling the caller must explicitly call 18233 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18234 * 18235 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18236 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18237 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18238 * 18239 * <p>At each incremental step of the scroll the caller should invoke 18240 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18241 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18242 * parent at least partially consumed the scroll and the caller should adjust the amount it 18243 * scrolls by.</p> 18244 * 18245 * <p>After applying the remainder of the scroll delta the caller should invoke 18246 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18247 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18248 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18249 * </p> 18250 * 18251 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18252 * {@link #SCROLL_AXIS_VERTICAL}. 18253 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18254 * the current gesture. 18255 * 18256 * @see #stopNestedScroll() 18257 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18258 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18259 */ 18260 public boolean startNestedScroll(int axes) { 18261 if (hasNestedScrollingParent()) { 18262 // Already in progress 18263 return true; 18264 } 18265 if (isNestedScrollingEnabled()) { 18266 ViewParent p = getParent(); 18267 View child = this; 18268 while (p != null) { 18269 try { 18270 if (p.onStartNestedScroll(child, this, axes)) { 18271 mNestedScrollingParent = p; 18272 p.onNestedScrollAccepted(child, this, axes); 18273 return true; 18274 } 18275 } catch (AbstractMethodError e) { 18276 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18277 "method onStartNestedScroll", e); 18278 // Allow the search upward to continue 18279 } 18280 if (p instanceof View) { 18281 child = (View) p; 18282 } 18283 p = p.getParent(); 18284 } 18285 } 18286 return false; 18287 } 18288 18289 /** 18290 * Stop a nested scroll in progress. 18291 * 18292 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18293 * 18294 * @see #startNestedScroll(int) 18295 */ 18296 public void stopNestedScroll() { 18297 if (mNestedScrollingParent != null) { 18298 mNestedScrollingParent.onStopNestedScroll(this); 18299 mNestedScrollingParent = null; 18300 } 18301 } 18302 18303 /** 18304 * Returns true if this view has a nested scrolling parent. 18305 * 18306 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18307 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18308 * 18309 * @return whether this view has a nested scrolling parent 18310 */ 18311 public boolean hasNestedScrollingParent() { 18312 return mNestedScrollingParent != null; 18313 } 18314 18315 /** 18316 * Dispatch one step of a nested scroll in progress. 18317 * 18318 * <p>Implementations of views that support nested scrolling should call this to report 18319 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18320 * is not currently in progress or nested scrolling is not 18321 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18322 * 18323 * <p>Compatible View implementations should also call 18324 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18325 * consuming a component of the scroll event themselves.</p> 18326 * 18327 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18328 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18329 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18330 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18331 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18332 * in local view coordinates of this view from before this operation 18333 * to after it completes. View implementations may use this to adjust 18334 * expected input coordinate tracking. 18335 * @return true if the event was dispatched, false if it could not be dispatched. 18336 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18337 */ 18338 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18339 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18340 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18341 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18342 int startX = 0; 18343 int startY = 0; 18344 if (offsetInWindow != null) { 18345 getLocationInWindow(offsetInWindow); 18346 startX = offsetInWindow[0]; 18347 startY = offsetInWindow[1]; 18348 } 18349 18350 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18351 dxUnconsumed, dyUnconsumed); 18352 18353 if (offsetInWindow != null) { 18354 getLocationInWindow(offsetInWindow); 18355 offsetInWindow[0] -= startX; 18356 offsetInWindow[1] -= startY; 18357 } 18358 return true; 18359 } else if (offsetInWindow != null) { 18360 // No motion, no dispatch. Keep offsetInWindow up to date. 18361 offsetInWindow[0] = 0; 18362 offsetInWindow[1] = 0; 18363 } 18364 } 18365 return false; 18366 } 18367 18368 /** 18369 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18370 * 18371 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18372 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18373 * scrolling operation to consume some or all of the scroll operation before the child view 18374 * consumes it.</p> 18375 * 18376 * @param dx Horizontal scroll distance in pixels 18377 * @param dy Vertical scroll distance in pixels 18378 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18379 * and consumed[1] the consumed dy. 18380 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18381 * in local view coordinates of this view from before this operation 18382 * to after it completes. View implementations may use this to adjust 18383 * expected input coordinate tracking. 18384 * @return true if the parent consumed some or all of the scroll delta 18385 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18386 */ 18387 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18388 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18389 if (dx != 0 || dy != 0) { 18390 int startX = 0; 18391 int startY = 0; 18392 if (offsetInWindow != null) { 18393 getLocationInWindow(offsetInWindow); 18394 startX = offsetInWindow[0]; 18395 startY = offsetInWindow[1]; 18396 } 18397 18398 if (consumed == null) { 18399 if (mTempNestedScrollConsumed == null) { 18400 mTempNestedScrollConsumed = new int[2]; 18401 } 18402 consumed = mTempNestedScrollConsumed; 18403 } 18404 consumed[0] = 0; 18405 consumed[1] = 0; 18406 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18407 18408 if (offsetInWindow != null) { 18409 getLocationInWindow(offsetInWindow); 18410 offsetInWindow[0] -= startX; 18411 offsetInWindow[1] -= startY; 18412 } 18413 return consumed[0] != 0 || consumed[1] != 0; 18414 } else if (offsetInWindow != null) { 18415 offsetInWindow[0] = 0; 18416 offsetInWindow[1] = 0; 18417 } 18418 } 18419 return false; 18420 } 18421 18422 /** 18423 * Dispatch a fling to a nested scrolling parent. 18424 * 18425 * <p>This method should be used to indicate that a nested scrolling child has detected 18426 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18427 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18428 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18429 * along a scrollable axis.</p> 18430 * 18431 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18432 * its own content, it can use this method to delegate the fling to its nested scrolling 18433 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18434 * 18435 * @param velocityX Horizontal fling velocity in pixels per second 18436 * @param velocityY Vertical fling velocity in pixels per second 18437 * @param consumed true if the child consumed the fling, false otherwise 18438 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18439 */ 18440 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18441 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18442 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18443 } 18444 return false; 18445 } 18446 18447 /** 18448 * Gets a scale factor that determines the distance the view should scroll 18449 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18450 * @return The vertical scroll scale factor. 18451 * @hide 18452 */ 18453 protected float getVerticalScrollFactor() { 18454 if (mVerticalScrollFactor == 0) { 18455 TypedValue outValue = new TypedValue(); 18456 if (!mContext.getTheme().resolveAttribute( 18457 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18458 throw new IllegalStateException( 18459 "Expected theme to define listPreferredItemHeight."); 18460 } 18461 mVerticalScrollFactor = outValue.getDimension( 18462 mContext.getResources().getDisplayMetrics()); 18463 } 18464 return mVerticalScrollFactor; 18465 } 18466 18467 /** 18468 * Gets a scale factor that determines the distance the view should scroll 18469 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18470 * @return The horizontal scroll scale factor. 18471 * @hide 18472 */ 18473 protected float getHorizontalScrollFactor() { 18474 // TODO: Should use something else. 18475 return getVerticalScrollFactor(); 18476 } 18477 18478 /** 18479 * Return the value specifying the text direction or policy that was set with 18480 * {@link #setTextDirection(int)}. 18481 * 18482 * @return the defined text direction. It can be one of: 18483 * 18484 * {@link #TEXT_DIRECTION_INHERIT}, 18485 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18486 * {@link #TEXT_DIRECTION_ANY_RTL}, 18487 * {@link #TEXT_DIRECTION_LTR}, 18488 * {@link #TEXT_DIRECTION_RTL}, 18489 * {@link #TEXT_DIRECTION_LOCALE} 18490 * 18491 * @attr ref android.R.styleable#View_textDirection 18492 * 18493 * @hide 18494 */ 18495 @ViewDebug.ExportedProperty(category = "text", mapping = { 18496 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18497 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18498 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18499 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18500 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18501 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18502 }) 18503 public int getRawTextDirection() { 18504 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18505 } 18506 18507 /** 18508 * Set the text direction. 18509 * 18510 * @param textDirection the direction to set. Should be one of: 18511 * 18512 * {@link #TEXT_DIRECTION_INHERIT}, 18513 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18514 * {@link #TEXT_DIRECTION_ANY_RTL}, 18515 * {@link #TEXT_DIRECTION_LTR}, 18516 * {@link #TEXT_DIRECTION_RTL}, 18517 * {@link #TEXT_DIRECTION_LOCALE} 18518 * 18519 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18520 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18521 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18522 * 18523 * @attr ref android.R.styleable#View_textDirection 18524 */ 18525 public void setTextDirection(int textDirection) { 18526 if (getRawTextDirection() != textDirection) { 18527 // Reset the current text direction and the resolved one 18528 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18529 resetResolvedTextDirection(); 18530 // Set the new text direction 18531 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18532 // Do resolution 18533 resolveTextDirection(); 18534 // Notify change 18535 onRtlPropertiesChanged(getLayoutDirection()); 18536 // Refresh 18537 requestLayout(); 18538 invalidate(true); 18539 } 18540 } 18541 18542 /** 18543 * Return the resolved text direction. 18544 * 18545 * @return the resolved text direction. Returns one of: 18546 * 18547 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18548 * {@link #TEXT_DIRECTION_ANY_RTL}, 18549 * {@link #TEXT_DIRECTION_LTR}, 18550 * {@link #TEXT_DIRECTION_RTL}, 18551 * {@link #TEXT_DIRECTION_LOCALE} 18552 * 18553 * @attr ref android.R.styleable#View_textDirection 18554 */ 18555 @ViewDebug.ExportedProperty(category = "text", mapping = { 18556 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18557 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18558 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18559 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18560 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18561 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18562 }) 18563 public int getTextDirection() { 18564 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18565 } 18566 18567 /** 18568 * Resolve the text direction. 18569 * 18570 * @return true if resolution has been done, false otherwise. 18571 * 18572 * @hide 18573 */ 18574 public boolean resolveTextDirection() { 18575 // Reset any previous text direction resolution 18576 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18577 18578 if (hasRtlSupport()) { 18579 // Set resolved text direction flag depending on text direction flag 18580 final int textDirection = getRawTextDirection(); 18581 switch(textDirection) { 18582 case TEXT_DIRECTION_INHERIT: 18583 if (!canResolveTextDirection()) { 18584 // We cannot do the resolution if there is no parent, so use the default one 18585 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18586 // Resolution will need to happen again later 18587 return false; 18588 } 18589 18590 // Parent has not yet resolved, so we still return the default 18591 try { 18592 if (!mParent.isTextDirectionResolved()) { 18593 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18594 // Resolution will need to happen again later 18595 return false; 18596 } 18597 } catch (AbstractMethodError e) { 18598 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18599 " does not fully implement ViewParent", e); 18600 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18601 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18602 return true; 18603 } 18604 18605 // Set current resolved direction to the same value as the parent's one 18606 int parentResolvedDirection; 18607 try { 18608 parentResolvedDirection = mParent.getTextDirection(); 18609 } catch (AbstractMethodError e) { 18610 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18611 " does not fully implement ViewParent", e); 18612 parentResolvedDirection = TEXT_DIRECTION_LTR; 18613 } 18614 switch (parentResolvedDirection) { 18615 case TEXT_DIRECTION_FIRST_STRONG: 18616 case TEXT_DIRECTION_ANY_RTL: 18617 case TEXT_DIRECTION_LTR: 18618 case TEXT_DIRECTION_RTL: 18619 case TEXT_DIRECTION_LOCALE: 18620 mPrivateFlags2 |= 18621 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18622 break; 18623 default: 18624 // Default resolved direction is "first strong" heuristic 18625 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18626 } 18627 break; 18628 case TEXT_DIRECTION_FIRST_STRONG: 18629 case TEXT_DIRECTION_ANY_RTL: 18630 case TEXT_DIRECTION_LTR: 18631 case TEXT_DIRECTION_RTL: 18632 case TEXT_DIRECTION_LOCALE: 18633 // Resolved direction is the same as text direction 18634 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18635 break; 18636 default: 18637 // Default resolved direction is "first strong" heuristic 18638 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18639 } 18640 } else { 18641 // Default resolved direction is "first strong" heuristic 18642 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18643 } 18644 18645 // Set to resolved 18646 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18647 return true; 18648 } 18649 18650 /** 18651 * Check if text direction resolution can be done. 18652 * 18653 * @return true if text direction resolution can be done otherwise return false. 18654 */ 18655 public boolean canResolveTextDirection() { 18656 switch (getRawTextDirection()) { 18657 case TEXT_DIRECTION_INHERIT: 18658 if (mParent != null) { 18659 try { 18660 return mParent.canResolveTextDirection(); 18661 } catch (AbstractMethodError e) { 18662 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18663 " does not fully implement ViewParent", e); 18664 } 18665 } 18666 return false; 18667 18668 default: 18669 return true; 18670 } 18671 } 18672 18673 /** 18674 * Reset resolved text direction. Text direction will be resolved during a call to 18675 * {@link #onMeasure(int, int)}. 18676 * 18677 * @hide 18678 */ 18679 public void resetResolvedTextDirection() { 18680 // Reset any previous text direction resolution 18681 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18682 // Set to default value 18683 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18684 } 18685 18686 /** 18687 * @return true if text direction is inherited. 18688 * 18689 * @hide 18690 */ 18691 public boolean isTextDirectionInherited() { 18692 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18693 } 18694 18695 /** 18696 * @return true if text direction is resolved. 18697 */ 18698 public boolean isTextDirectionResolved() { 18699 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18700 } 18701 18702 /** 18703 * Return the value specifying the text alignment or policy that was set with 18704 * {@link #setTextAlignment(int)}. 18705 * 18706 * @return the defined text alignment. It can be one of: 18707 * 18708 * {@link #TEXT_ALIGNMENT_INHERIT}, 18709 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18710 * {@link #TEXT_ALIGNMENT_CENTER}, 18711 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18712 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18713 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18714 * {@link #TEXT_ALIGNMENT_VIEW_END} 18715 * 18716 * @attr ref android.R.styleable#View_textAlignment 18717 * 18718 * @hide 18719 */ 18720 @ViewDebug.ExportedProperty(category = "text", mapping = { 18721 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18722 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18723 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18724 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18725 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18726 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18727 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18728 }) 18729 @TextAlignment 18730 public int getRawTextAlignment() { 18731 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18732 } 18733 18734 /** 18735 * Set the text alignment. 18736 * 18737 * @param textAlignment The text alignment to set. Should be one of 18738 * 18739 * {@link #TEXT_ALIGNMENT_INHERIT}, 18740 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18741 * {@link #TEXT_ALIGNMENT_CENTER}, 18742 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18743 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18744 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18745 * {@link #TEXT_ALIGNMENT_VIEW_END} 18746 * 18747 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18748 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18749 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18750 * 18751 * @attr ref android.R.styleable#View_textAlignment 18752 */ 18753 public void setTextAlignment(@TextAlignment int textAlignment) { 18754 if (textAlignment != getRawTextAlignment()) { 18755 // Reset the current and resolved text alignment 18756 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18757 resetResolvedTextAlignment(); 18758 // Set the new text alignment 18759 mPrivateFlags2 |= 18760 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18761 // Do resolution 18762 resolveTextAlignment(); 18763 // Notify change 18764 onRtlPropertiesChanged(getLayoutDirection()); 18765 // Refresh 18766 requestLayout(); 18767 invalidate(true); 18768 } 18769 } 18770 18771 /** 18772 * Return the resolved text alignment. 18773 * 18774 * @return the resolved text alignment. Returns one of: 18775 * 18776 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18777 * {@link #TEXT_ALIGNMENT_CENTER}, 18778 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18779 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18780 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18781 * {@link #TEXT_ALIGNMENT_VIEW_END} 18782 * 18783 * @attr ref android.R.styleable#View_textAlignment 18784 */ 18785 @ViewDebug.ExportedProperty(category = "text", mapping = { 18786 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18787 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18788 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18789 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18790 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18791 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18792 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18793 }) 18794 @TextAlignment 18795 public int getTextAlignment() { 18796 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18797 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18798 } 18799 18800 /** 18801 * Resolve the text alignment. 18802 * 18803 * @return true if resolution has been done, false otherwise. 18804 * 18805 * @hide 18806 */ 18807 public boolean resolveTextAlignment() { 18808 // Reset any previous text alignment resolution 18809 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18810 18811 if (hasRtlSupport()) { 18812 // Set resolved text alignment flag depending on text alignment flag 18813 final int textAlignment = getRawTextAlignment(); 18814 switch (textAlignment) { 18815 case TEXT_ALIGNMENT_INHERIT: 18816 // Check if we can resolve the text alignment 18817 if (!canResolveTextAlignment()) { 18818 // We cannot do the resolution if there is no parent so use the default 18819 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18820 // Resolution will need to happen again later 18821 return false; 18822 } 18823 18824 // Parent has not yet resolved, so we still return the default 18825 try { 18826 if (!mParent.isTextAlignmentResolved()) { 18827 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18828 // Resolution will need to happen again later 18829 return false; 18830 } 18831 } catch (AbstractMethodError e) { 18832 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18833 " does not fully implement ViewParent", e); 18834 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18835 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18836 return true; 18837 } 18838 18839 int parentResolvedTextAlignment; 18840 try { 18841 parentResolvedTextAlignment = mParent.getTextAlignment(); 18842 } catch (AbstractMethodError e) { 18843 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18844 " does not fully implement ViewParent", e); 18845 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18846 } 18847 switch (parentResolvedTextAlignment) { 18848 case TEXT_ALIGNMENT_GRAVITY: 18849 case TEXT_ALIGNMENT_TEXT_START: 18850 case TEXT_ALIGNMENT_TEXT_END: 18851 case TEXT_ALIGNMENT_CENTER: 18852 case TEXT_ALIGNMENT_VIEW_START: 18853 case TEXT_ALIGNMENT_VIEW_END: 18854 // Resolved text alignment is the same as the parent resolved 18855 // text alignment 18856 mPrivateFlags2 |= 18857 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18858 break; 18859 default: 18860 // Use default resolved text alignment 18861 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18862 } 18863 break; 18864 case TEXT_ALIGNMENT_GRAVITY: 18865 case TEXT_ALIGNMENT_TEXT_START: 18866 case TEXT_ALIGNMENT_TEXT_END: 18867 case TEXT_ALIGNMENT_CENTER: 18868 case TEXT_ALIGNMENT_VIEW_START: 18869 case TEXT_ALIGNMENT_VIEW_END: 18870 // Resolved text alignment is the same as text alignment 18871 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18872 break; 18873 default: 18874 // Use default resolved text alignment 18875 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18876 } 18877 } else { 18878 // Use default resolved text alignment 18879 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18880 } 18881 18882 // Set the resolved 18883 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18884 return true; 18885 } 18886 18887 /** 18888 * Check if text alignment resolution can be done. 18889 * 18890 * @return true if text alignment resolution can be done otherwise return false. 18891 */ 18892 public boolean canResolveTextAlignment() { 18893 switch (getRawTextAlignment()) { 18894 case TEXT_DIRECTION_INHERIT: 18895 if (mParent != null) { 18896 try { 18897 return mParent.canResolveTextAlignment(); 18898 } catch (AbstractMethodError e) { 18899 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18900 " does not fully implement ViewParent", e); 18901 } 18902 } 18903 return false; 18904 18905 default: 18906 return true; 18907 } 18908 } 18909 18910 /** 18911 * Reset resolved text alignment. Text alignment will be resolved during a call to 18912 * {@link #onMeasure(int, int)}. 18913 * 18914 * @hide 18915 */ 18916 public void resetResolvedTextAlignment() { 18917 // Reset any previous text alignment resolution 18918 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18919 // Set to default 18920 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18921 } 18922 18923 /** 18924 * @return true if text alignment is inherited. 18925 * 18926 * @hide 18927 */ 18928 public boolean isTextAlignmentInherited() { 18929 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18930 } 18931 18932 /** 18933 * @return true if text alignment is resolved. 18934 */ 18935 public boolean isTextAlignmentResolved() { 18936 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18937 } 18938 18939 /** 18940 * Generate a value suitable for use in {@link #setId(int)}. 18941 * This value will not collide with ID values generated at build time by aapt for R.id. 18942 * 18943 * @return a generated ID value 18944 */ 18945 public static int generateViewId() { 18946 for (;;) { 18947 final int result = sNextGeneratedId.get(); 18948 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18949 int newValue = result + 1; 18950 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18951 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18952 return result; 18953 } 18954 } 18955 } 18956 18957 /** 18958 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 18959 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 18960 * a normal View or a ViewGroup with 18961 * {@link android.view.ViewGroup#isTransitionGroup()} true. 18962 * @hide 18963 */ 18964 public void captureTransitioningViews(List<View> transitioningViews) { 18965 if (getVisibility() == View.VISIBLE) { 18966 transitioningViews.add(this); 18967 } 18968 } 18969 18970 /** 18971 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 18972 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 18973 * @hide 18974 */ 18975 public void findNamedViews(Map<String, View> namedElements) { 18976 if (getVisibility() == VISIBLE) { 18977 String transitionName = getTransitionName(); 18978 if (transitionName != null) { 18979 namedElements.put(transitionName, this); 18980 } 18981 } 18982 } 18983 18984 // 18985 // Properties 18986 // 18987 /** 18988 * A Property wrapper around the <code>alpha</code> functionality handled by the 18989 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18990 */ 18991 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18992 @Override 18993 public void setValue(View object, float value) { 18994 object.setAlpha(value); 18995 } 18996 18997 @Override 18998 public Float get(View object) { 18999 return object.getAlpha(); 19000 } 19001 }; 19002 19003 /** 19004 * A Property wrapper around the <code>translationX</code> functionality handled by the 19005 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 19006 */ 19007 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 19008 @Override 19009 public void setValue(View object, float value) { 19010 object.setTranslationX(value); 19011 } 19012 19013 @Override 19014 public Float get(View object) { 19015 return object.getTranslationX(); 19016 } 19017 }; 19018 19019 /** 19020 * A Property wrapper around the <code>translationY</code> functionality handled by the 19021 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 19022 */ 19023 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 19024 @Override 19025 public void setValue(View object, float value) { 19026 object.setTranslationY(value); 19027 } 19028 19029 @Override 19030 public Float get(View object) { 19031 return object.getTranslationY(); 19032 } 19033 }; 19034 19035 /** 19036 * A Property wrapper around the <code>translationZ</code> functionality handled by the 19037 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 19038 */ 19039 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 19040 @Override 19041 public void setValue(View object, float value) { 19042 object.setTranslationZ(value); 19043 } 19044 19045 @Override 19046 public Float get(View object) { 19047 return object.getTranslationZ(); 19048 } 19049 }; 19050 19051 /** 19052 * A Property wrapper around the <code>x</code> functionality handled by the 19053 * {@link View#setX(float)} and {@link View#getX()} methods. 19054 */ 19055 public static final Property<View, Float> X = new FloatProperty<View>("x") { 19056 @Override 19057 public void setValue(View object, float value) { 19058 object.setX(value); 19059 } 19060 19061 @Override 19062 public Float get(View object) { 19063 return object.getX(); 19064 } 19065 }; 19066 19067 /** 19068 * A Property wrapper around the <code>y</code> functionality handled by the 19069 * {@link View#setY(float)} and {@link View#getY()} methods. 19070 */ 19071 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 19072 @Override 19073 public void setValue(View object, float value) { 19074 object.setY(value); 19075 } 19076 19077 @Override 19078 public Float get(View object) { 19079 return object.getY(); 19080 } 19081 }; 19082 19083 /** 19084 * A Property wrapper around the <code>z</code> functionality handled by the 19085 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19086 */ 19087 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19088 @Override 19089 public void setValue(View object, float value) { 19090 object.setZ(value); 19091 } 19092 19093 @Override 19094 public Float get(View object) { 19095 return object.getZ(); 19096 } 19097 }; 19098 19099 /** 19100 * A Property wrapper around the <code>rotation</code> functionality handled by the 19101 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19102 */ 19103 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19104 @Override 19105 public void setValue(View object, float value) { 19106 object.setRotation(value); 19107 } 19108 19109 @Override 19110 public Float get(View object) { 19111 return object.getRotation(); 19112 } 19113 }; 19114 19115 /** 19116 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19117 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19118 */ 19119 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19120 @Override 19121 public void setValue(View object, float value) { 19122 object.setRotationX(value); 19123 } 19124 19125 @Override 19126 public Float get(View object) { 19127 return object.getRotationX(); 19128 } 19129 }; 19130 19131 /** 19132 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19133 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19134 */ 19135 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19136 @Override 19137 public void setValue(View object, float value) { 19138 object.setRotationY(value); 19139 } 19140 19141 @Override 19142 public Float get(View object) { 19143 return object.getRotationY(); 19144 } 19145 }; 19146 19147 /** 19148 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19149 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19150 */ 19151 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19152 @Override 19153 public void setValue(View object, float value) { 19154 object.setScaleX(value); 19155 } 19156 19157 @Override 19158 public Float get(View object) { 19159 return object.getScaleX(); 19160 } 19161 }; 19162 19163 /** 19164 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19165 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19166 */ 19167 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19168 @Override 19169 public void setValue(View object, float value) { 19170 object.setScaleY(value); 19171 } 19172 19173 @Override 19174 public Float get(View object) { 19175 return object.getScaleY(); 19176 } 19177 }; 19178 19179 /** 19180 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19181 * Each MeasureSpec represents a requirement for either the width or the height. 19182 * A MeasureSpec is comprised of a size and a mode. There are three possible 19183 * modes: 19184 * <dl> 19185 * <dt>UNSPECIFIED</dt> 19186 * <dd> 19187 * The parent has not imposed any constraint on the child. It can be whatever size 19188 * it wants. 19189 * </dd> 19190 * 19191 * <dt>EXACTLY</dt> 19192 * <dd> 19193 * The parent has determined an exact size for the child. The child is going to be 19194 * given those bounds regardless of how big it wants to be. 19195 * </dd> 19196 * 19197 * <dt>AT_MOST</dt> 19198 * <dd> 19199 * The child can be as large as it wants up to the specified size. 19200 * </dd> 19201 * </dl> 19202 * 19203 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19204 * is provided to pack and unpack the <size, mode> tuple into the int. 19205 */ 19206 public static class MeasureSpec { 19207 private static final int MODE_SHIFT = 30; 19208 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19209 19210 /** 19211 * Measure specification mode: The parent has not imposed any constraint 19212 * on the child. It can be whatever size it wants. 19213 */ 19214 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19215 19216 /** 19217 * Measure specification mode: The parent has determined an exact size 19218 * for the child. The child is going to be given those bounds regardless 19219 * of how big it wants to be. 19220 */ 19221 public static final int EXACTLY = 1 << MODE_SHIFT; 19222 19223 /** 19224 * Measure specification mode: The child can be as large as it wants up 19225 * to the specified size. 19226 */ 19227 public static final int AT_MOST = 2 << MODE_SHIFT; 19228 19229 /** 19230 * Creates a measure specification based on the supplied size and mode. 19231 * 19232 * The mode must always be one of the following: 19233 * <ul> 19234 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19235 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19236 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19237 * </ul> 19238 * 19239 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19240 * implementation was such that the order of arguments did not matter 19241 * and overflow in either value could impact the resulting MeasureSpec. 19242 * {@link android.widget.RelativeLayout} was affected by this bug. 19243 * Apps targeting API levels greater than 17 will get the fixed, more strict 19244 * behavior.</p> 19245 * 19246 * @param size the size of the measure specification 19247 * @param mode the mode of the measure specification 19248 * @return the measure specification based on size and mode 19249 */ 19250 public static int makeMeasureSpec(int size, int mode) { 19251 if (sUseBrokenMakeMeasureSpec) { 19252 return size + mode; 19253 } else { 19254 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19255 } 19256 } 19257 19258 /** 19259 * Extracts the mode from the supplied measure specification. 19260 * 19261 * @param measureSpec the measure specification to extract the mode from 19262 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19263 * {@link android.view.View.MeasureSpec#AT_MOST} or 19264 * {@link android.view.View.MeasureSpec#EXACTLY} 19265 */ 19266 public static int getMode(int measureSpec) { 19267 return (measureSpec & MODE_MASK); 19268 } 19269 19270 /** 19271 * Extracts the size from the supplied measure specification. 19272 * 19273 * @param measureSpec the measure specification to extract the size from 19274 * @return the size in pixels defined in the supplied measure specification 19275 */ 19276 public static int getSize(int measureSpec) { 19277 return (measureSpec & ~MODE_MASK); 19278 } 19279 19280 static int adjust(int measureSpec, int delta) { 19281 final int mode = getMode(measureSpec); 19282 if (mode == UNSPECIFIED) { 19283 // No need to adjust size for UNSPECIFIED mode. 19284 return makeMeasureSpec(0, UNSPECIFIED); 19285 } 19286 int size = getSize(measureSpec) + delta; 19287 if (size < 0) { 19288 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19289 ") spec: " + toString(measureSpec) + " delta: " + delta); 19290 size = 0; 19291 } 19292 return makeMeasureSpec(size, mode); 19293 } 19294 19295 /** 19296 * Returns a String representation of the specified measure 19297 * specification. 19298 * 19299 * @param measureSpec the measure specification to convert to a String 19300 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19301 */ 19302 public static String toString(int measureSpec) { 19303 int mode = getMode(measureSpec); 19304 int size = getSize(measureSpec); 19305 19306 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19307 19308 if (mode == UNSPECIFIED) 19309 sb.append("UNSPECIFIED "); 19310 else if (mode == EXACTLY) 19311 sb.append("EXACTLY "); 19312 else if (mode == AT_MOST) 19313 sb.append("AT_MOST "); 19314 else 19315 sb.append(mode).append(" "); 19316 19317 sb.append(size); 19318 return sb.toString(); 19319 } 19320 } 19321 19322 private final class CheckForLongPress implements Runnable { 19323 private int mOriginalWindowAttachCount; 19324 19325 @Override 19326 public void run() { 19327 if (isPressed() && (mParent != null) 19328 && mOriginalWindowAttachCount == mWindowAttachCount) { 19329 if (performLongClick()) { 19330 mHasPerformedLongPress = true; 19331 } 19332 } 19333 } 19334 19335 public void rememberWindowAttachCount() { 19336 mOriginalWindowAttachCount = mWindowAttachCount; 19337 } 19338 } 19339 19340 private final class CheckForTap implements Runnable { 19341 public float x; 19342 public float y; 19343 19344 @Override 19345 public void run() { 19346 mPrivateFlags &= ~PFLAG_PREPRESSED; 19347 setPressed(true, x, y); 19348 checkForLongClick(ViewConfiguration.getTapTimeout()); 19349 } 19350 } 19351 19352 private final class PerformClick implements Runnable { 19353 @Override 19354 public void run() { 19355 performClick(); 19356 } 19357 } 19358 19359 /** @hide */ 19360 public void hackTurnOffWindowResizeAnim(boolean off) { 19361 mAttachInfo.mTurnOffWindowResizeAnim = off; 19362 } 19363 19364 /** 19365 * This method returns a ViewPropertyAnimator object, which can be used to animate 19366 * specific properties on this View. 19367 * 19368 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19369 */ 19370 public ViewPropertyAnimator animate() { 19371 if (mAnimator == null) { 19372 mAnimator = new ViewPropertyAnimator(this); 19373 } 19374 return mAnimator; 19375 } 19376 19377 /** 19378 * Sets the name of the View to be used to identify Views in Transitions. 19379 * Names should be unique in the View hierarchy. 19380 * 19381 * @param transitionName The name of the View to uniquely identify it for Transitions. 19382 */ 19383 public final void setTransitionName(String transitionName) { 19384 mTransitionName = transitionName; 19385 } 19386 19387 /** 19388 * Returns the name of the View to be used to identify Views in Transitions. 19389 * Names should be unique in the View hierarchy. 19390 * 19391 * <p>This returns null if the View has not been given a name.</p> 19392 * 19393 * @return The name used of the View to be used to identify Views in Transitions or null 19394 * if no name has been given. 19395 */ 19396 public String getTransitionName() { 19397 return mTransitionName; 19398 } 19399 19400 /** 19401 * Interface definition for a callback to be invoked when a hardware key event is 19402 * dispatched to this view. The callback will be invoked before the key event is 19403 * given to the view. This is only useful for hardware keyboards; a software input 19404 * method has no obligation to trigger this listener. 19405 */ 19406 public interface OnKeyListener { 19407 /** 19408 * Called when a hardware key is dispatched to a view. This allows listeners to 19409 * get a chance to respond before the target view. 19410 * <p>Key presses in software keyboards will generally NOT trigger this method, 19411 * although some may elect to do so in some situations. Do not assume a 19412 * software input method has to be key-based; even if it is, it may use key presses 19413 * in a different way than you expect, so there is no way to reliably catch soft 19414 * input key presses. 19415 * 19416 * @param v The view the key has been dispatched to. 19417 * @param keyCode The code for the physical key that was pressed 19418 * @param event The KeyEvent object containing full information about 19419 * the event. 19420 * @return True if the listener has consumed the event, false otherwise. 19421 */ 19422 boolean onKey(View v, int keyCode, KeyEvent event); 19423 } 19424 19425 /** 19426 * Interface definition for a callback to be invoked when a touch event is 19427 * dispatched to this view. The callback will be invoked before the touch 19428 * event is given to the view. 19429 */ 19430 public interface OnTouchListener { 19431 /** 19432 * Called when a touch event is dispatched to a view. This allows listeners to 19433 * get a chance to respond before the target view. 19434 * 19435 * @param v The view the touch event has been dispatched to. 19436 * @param event The MotionEvent object containing full information about 19437 * the event. 19438 * @return True if the listener has consumed the event, false otherwise. 19439 */ 19440 boolean onTouch(View v, MotionEvent event); 19441 } 19442 19443 /** 19444 * Interface definition for a callback to be invoked when a hover event is 19445 * dispatched to this view. The callback will be invoked before the hover 19446 * event is given to the view. 19447 */ 19448 public interface OnHoverListener { 19449 /** 19450 * Called when a hover event is dispatched to a view. This allows listeners to 19451 * get a chance to respond before the target view. 19452 * 19453 * @param v The view the hover event has been dispatched to. 19454 * @param event The MotionEvent object containing full information about 19455 * the event. 19456 * @return True if the listener has consumed the event, false otherwise. 19457 */ 19458 boolean onHover(View v, MotionEvent event); 19459 } 19460 19461 /** 19462 * Interface definition for a callback to be invoked when a generic motion event is 19463 * dispatched to this view. The callback will be invoked before the generic motion 19464 * event is given to the view. 19465 */ 19466 public interface OnGenericMotionListener { 19467 /** 19468 * Called when a generic motion event is dispatched to a view. This allows listeners to 19469 * get a chance to respond before the target view. 19470 * 19471 * @param v The view the generic motion event has been dispatched to. 19472 * @param event The MotionEvent object containing full information about 19473 * the event. 19474 * @return True if the listener has consumed the event, false otherwise. 19475 */ 19476 boolean onGenericMotion(View v, MotionEvent event); 19477 } 19478 19479 /** 19480 * Interface definition for a callback to be invoked when a view has been clicked and held. 19481 */ 19482 public interface OnLongClickListener { 19483 /** 19484 * Called when a view has been clicked and held. 19485 * 19486 * @param v The view that was clicked and held. 19487 * 19488 * @return true if the callback consumed the long click, false otherwise. 19489 */ 19490 boolean onLongClick(View v); 19491 } 19492 19493 /** 19494 * Interface definition for a callback to be invoked when a drag is being dispatched 19495 * to this view. The callback will be invoked before the hosting view's own 19496 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19497 * onDrag(event) behavior, it should return 'false' from this callback. 19498 * 19499 * <div class="special reference"> 19500 * <h3>Developer Guides</h3> 19501 * <p>For a guide to implementing drag and drop features, read the 19502 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19503 * </div> 19504 */ 19505 public interface OnDragListener { 19506 /** 19507 * Called when a drag event is dispatched to a view. This allows listeners 19508 * to get a chance to override base View behavior. 19509 * 19510 * @param v The View that received the drag event. 19511 * @param event The {@link android.view.DragEvent} object for the drag event. 19512 * @return {@code true} if the drag event was handled successfully, or {@code false} 19513 * if the drag event was not handled. Note that {@code false} will trigger the View 19514 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19515 */ 19516 boolean onDrag(View v, DragEvent event); 19517 } 19518 19519 /** 19520 * Interface definition for a callback to be invoked when the focus state of 19521 * a view changed. 19522 */ 19523 public interface OnFocusChangeListener { 19524 /** 19525 * Called when the focus state of a view has changed. 19526 * 19527 * @param v The view whose state has changed. 19528 * @param hasFocus The new focus state of v. 19529 */ 19530 void onFocusChange(View v, boolean hasFocus); 19531 } 19532 19533 /** 19534 * Interface definition for a callback to be invoked when a view is clicked. 19535 */ 19536 public interface OnClickListener { 19537 /** 19538 * Called when a view has been clicked. 19539 * 19540 * @param v The view that was clicked. 19541 */ 19542 void onClick(View v); 19543 } 19544 19545 /** 19546 * Interface definition for a callback to be invoked when the context menu 19547 * for this view is being built. 19548 */ 19549 public interface OnCreateContextMenuListener { 19550 /** 19551 * Called when the context menu for this view is being built. It is not 19552 * safe to hold onto the menu after this method returns. 19553 * 19554 * @param menu The context menu that is being built 19555 * @param v The view for which the context menu is being built 19556 * @param menuInfo Extra information about the item for which the 19557 * context menu should be shown. This information will vary 19558 * depending on the class of v. 19559 */ 19560 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19561 } 19562 19563 /** 19564 * Interface definition for a callback to be invoked when the status bar changes 19565 * visibility. This reports <strong>global</strong> changes to the system UI 19566 * state, not what the application is requesting. 19567 * 19568 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19569 */ 19570 public interface OnSystemUiVisibilityChangeListener { 19571 /** 19572 * Called when the status bar changes visibility because of a call to 19573 * {@link View#setSystemUiVisibility(int)}. 19574 * 19575 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19576 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19577 * This tells you the <strong>global</strong> state of these UI visibility 19578 * flags, not what your app is currently applying. 19579 */ 19580 public void onSystemUiVisibilityChange(int visibility); 19581 } 19582 19583 /** 19584 * Interface definition for a callback to be invoked when this view is attached 19585 * or detached from its window. 19586 */ 19587 public interface OnAttachStateChangeListener { 19588 /** 19589 * Called when the view is attached to a window. 19590 * @param v The view that was attached 19591 */ 19592 public void onViewAttachedToWindow(View v); 19593 /** 19594 * Called when the view is detached from a window. 19595 * @param v The view that was detached 19596 */ 19597 public void onViewDetachedFromWindow(View v); 19598 } 19599 19600 /** 19601 * Listener for applying window insets on a view in a custom way. 19602 * 19603 * <p>Apps may choose to implement this interface if they want to apply custom policy 19604 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19605 * is set, its 19606 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19607 * method will be called instead of the View's own 19608 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19609 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19610 * the View's normal behavior as part of its own.</p> 19611 */ 19612 public interface OnApplyWindowInsetsListener { 19613 /** 19614 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19615 * on a View, this listener method will be called instead of the view's own 19616 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19617 * 19618 * @param v The view applying window insets 19619 * @param insets The insets to apply 19620 * @return The insets supplied, minus any insets that were consumed 19621 */ 19622 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19623 } 19624 19625 private final class UnsetPressedState implements Runnable { 19626 @Override 19627 public void run() { 19628 setPressed(false); 19629 } 19630 } 19631 19632 /** 19633 * Base class for derived classes that want to save and restore their own 19634 * state in {@link android.view.View#onSaveInstanceState()}. 19635 */ 19636 public static class BaseSavedState extends AbsSavedState { 19637 /** 19638 * Constructor used when reading from a parcel. Reads the state of the superclass. 19639 * 19640 * @param source 19641 */ 19642 public BaseSavedState(Parcel source) { 19643 super(source); 19644 } 19645 19646 /** 19647 * Constructor called by derived classes when creating their SavedState objects 19648 * 19649 * @param superState The state of the superclass of this view 19650 */ 19651 public BaseSavedState(Parcelable superState) { 19652 super(superState); 19653 } 19654 19655 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19656 new Parcelable.Creator<BaseSavedState>() { 19657 public BaseSavedState createFromParcel(Parcel in) { 19658 return new BaseSavedState(in); 19659 } 19660 19661 public BaseSavedState[] newArray(int size) { 19662 return new BaseSavedState[size]; 19663 } 19664 }; 19665 } 19666 19667 /** 19668 * A set of information given to a view when it is attached to its parent 19669 * window. 19670 */ 19671 final static class AttachInfo { 19672 interface Callbacks { 19673 void playSoundEffect(int effectId); 19674 boolean performHapticFeedback(int effectId, boolean always); 19675 } 19676 19677 /** 19678 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19679 * to a Handler. This class contains the target (View) to invalidate and 19680 * the coordinates of the dirty rectangle. 19681 * 19682 * For performance purposes, this class also implements a pool of up to 19683 * POOL_LIMIT objects that get reused. This reduces memory allocations 19684 * whenever possible. 19685 */ 19686 static class InvalidateInfo { 19687 private static final int POOL_LIMIT = 10; 19688 19689 private static final SynchronizedPool<InvalidateInfo> sPool = 19690 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19691 19692 View target; 19693 19694 int left; 19695 int top; 19696 int right; 19697 int bottom; 19698 19699 public static InvalidateInfo obtain() { 19700 InvalidateInfo instance = sPool.acquire(); 19701 return (instance != null) ? instance : new InvalidateInfo(); 19702 } 19703 19704 public void recycle() { 19705 target = null; 19706 sPool.release(this); 19707 } 19708 } 19709 19710 final IWindowSession mSession; 19711 19712 final IWindow mWindow; 19713 19714 final IBinder mWindowToken; 19715 19716 final Display mDisplay; 19717 19718 final Callbacks mRootCallbacks; 19719 19720 IWindowId mIWindowId; 19721 WindowId mWindowId; 19722 19723 /** 19724 * The top view of the hierarchy. 19725 */ 19726 View mRootView; 19727 19728 IBinder mPanelParentWindowToken; 19729 19730 boolean mHardwareAccelerated; 19731 boolean mHardwareAccelerationRequested; 19732 HardwareRenderer mHardwareRenderer; 19733 19734 /** 19735 * The state of the display to which the window is attached, as reported 19736 * by {@link Display#getState()}. Note that the display state constants 19737 * declared by {@link Display} do not exactly line up with the screen state 19738 * constants declared by {@link View} (there are more display states than 19739 * screen states). 19740 */ 19741 int mDisplayState = Display.STATE_UNKNOWN; 19742 19743 /** 19744 * Scale factor used by the compatibility mode 19745 */ 19746 float mApplicationScale; 19747 19748 /** 19749 * Indicates whether the application is in compatibility mode 19750 */ 19751 boolean mScalingRequired; 19752 19753 /** 19754 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19755 */ 19756 boolean mTurnOffWindowResizeAnim; 19757 19758 /** 19759 * Left position of this view's window 19760 */ 19761 int mWindowLeft; 19762 19763 /** 19764 * Top position of this view's window 19765 */ 19766 int mWindowTop; 19767 19768 /** 19769 * Indicates whether views need to use 32-bit drawing caches 19770 */ 19771 boolean mUse32BitDrawingCache; 19772 19773 /** 19774 * For windows that are full-screen but using insets to layout inside 19775 * of the screen areas, these are the current insets to appear inside 19776 * the overscan area of the display. 19777 */ 19778 final Rect mOverscanInsets = new Rect(); 19779 19780 /** 19781 * For windows that are full-screen but using insets to layout inside 19782 * of the screen decorations, these are the current insets for the 19783 * content of the window. 19784 */ 19785 final Rect mContentInsets = new Rect(); 19786 19787 /** 19788 * For windows that are full-screen but using insets to layout inside 19789 * of the screen decorations, these are the current insets for the 19790 * actual visible parts of the window. 19791 */ 19792 final Rect mVisibleInsets = new Rect(); 19793 19794 /** 19795 * For windows that are full-screen but using insets to layout inside 19796 * of the screen decorations, these are the current insets for the 19797 * stable system windows. 19798 */ 19799 final Rect mStableInsets = new Rect(); 19800 19801 /** 19802 * The internal insets given by this window. This value is 19803 * supplied by the client (through 19804 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19805 * be given to the window manager when changed to be used in laying 19806 * out windows behind it. 19807 */ 19808 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19809 = new ViewTreeObserver.InternalInsetsInfo(); 19810 19811 /** 19812 * Set to true when mGivenInternalInsets is non-empty. 19813 */ 19814 boolean mHasNonEmptyGivenInternalInsets; 19815 19816 /** 19817 * All views in the window's hierarchy that serve as scroll containers, 19818 * used to determine if the window can be resized or must be panned 19819 * to adjust for a soft input area. 19820 */ 19821 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19822 19823 final KeyEvent.DispatcherState mKeyDispatchState 19824 = new KeyEvent.DispatcherState(); 19825 19826 /** 19827 * Indicates whether the view's window currently has the focus. 19828 */ 19829 boolean mHasWindowFocus; 19830 19831 /** 19832 * The current visibility of the window. 19833 */ 19834 int mWindowVisibility; 19835 19836 /** 19837 * Indicates the time at which drawing started to occur. 19838 */ 19839 long mDrawingTime; 19840 19841 /** 19842 * Indicates whether or not ignoring the DIRTY_MASK flags. 19843 */ 19844 boolean mIgnoreDirtyState; 19845 19846 /** 19847 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19848 * to avoid clearing that flag prematurely. 19849 */ 19850 boolean mSetIgnoreDirtyState = false; 19851 19852 /** 19853 * Indicates whether the view's window is currently in touch mode. 19854 */ 19855 boolean mInTouchMode; 19856 19857 /** 19858 * Indicates whether the view has requested unbuffered input dispatching for the current 19859 * event stream. 19860 */ 19861 boolean mUnbufferedDispatchRequested; 19862 19863 /** 19864 * Indicates that ViewAncestor should trigger a global layout change 19865 * the next time it performs a traversal 19866 */ 19867 boolean mRecomputeGlobalAttributes; 19868 19869 /** 19870 * Always report new attributes at next traversal. 19871 */ 19872 boolean mForceReportNewAttributes; 19873 19874 /** 19875 * Set during a traveral if any views want to keep the screen on. 19876 */ 19877 boolean mKeepScreenOn; 19878 19879 /** 19880 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19881 */ 19882 int mSystemUiVisibility; 19883 19884 /** 19885 * Hack to force certain system UI visibility flags to be cleared. 19886 */ 19887 int mDisabledSystemUiVisibility; 19888 19889 /** 19890 * Last global system UI visibility reported by the window manager. 19891 */ 19892 int mGlobalSystemUiVisibility; 19893 19894 /** 19895 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19896 * attached. 19897 */ 19898 boolean mHasSystemUiListeners; 19899 19900 /** 19901 * Set if the window has requested to extend into the overscan region 19902 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19903 */ 19904 boolean mOverscanRequested; 19905 19906 /** 19907 * Set if the visibility of any views has changed. 19908 */ 19909 boolean mViewVisibilityChanged; 19910 19911 /** 19912 * Set to true if a view has been scrolled. 19913 */ 19914 boolean mViewScrollChanged; 19915 19916 /** 19917 * Set to true if high contrast mode enabled 19918 */ 19919 boolean mHighContrastText; 19920 19921 /** 19922 * Global to the view hierarchy used as a temporary for dealing with 19923 * x/y points in the transparent region computations. 19924 */ 19925 final int[] mTransparentLocation = new int[2]; 19926 19927 /** 19928 * Global to the view hierarchy used as a temporary for dealing with 19929 * x/y points in the ViewGroup.invalidateChild implementation. 19930 */ 19931 final int[] mInvalidateChildLocation = new int[2]; 19932 19933 /** 19934 * Global to the view hierarchy used as a temporary for dealng with 19935 * computing absolute on-screen location. 19936 */ 19937 final int[] mTmpLocation = new int[2]; 19938 19939 /** 19940 * Global to the view hierarchy used as a temporary for dealing with 19941 * x/y location when view is transformed. 19942 */ 19943 final float[] mTmpTransformLocation = new float[2]; 19944 19945 /** 19946 * The view tree observer used to dispatch global events like 19947 * layout, pre-draw, touch mode change, etc. 19948 */ 19949 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19950 19951 /** 19952 * A Canvas used by the view hierarchy to perform bitmap caching. 19953 */ 19954 Canvas mCanvas; 19955 19956 /** 19957 * The view root impl. 19958 */ 19959 final ViewRootImpl mViewRootImpl; 19960 19961 /** 19962 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19963 * handler can be used to pump events in the UI events queue. 19964 */ 19965 final Handler mHandler; 19966 19967 /** 19968 * Temporary for use in computing invalidate rectangles while 19969 * calling up the hierarchy. 19970 */ 19971 final Rect mTmpInvalRect = new Rect(); 19972 19973 /** 19974 * Temporary for use in computing hit areas with transformed views 19975 */ 19976 final RectF mTmpTransformRect = new RectF(); 19977 19978 /** 19979 * Temporary for use in transforming invalidation rect 19980 */ 19981 final Matrix mTmpMatrix = new Matrix(); 19982 19983 /** 19984 * Temporary for use in transforming invalidation rect 19985 */ 19986 final Transformation mTmpTransformation = new Transformation(); 19987 19988 /** 19989 * Temporary for use in querying outlines from OutlineProviders 19990 */ 19991 final Outline mTmpOutline = new Outline(); 19992 19993 /** 19994 * Temporary list for use in collecting focusable descendents of a view. 19995 */ 19996 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19997 19998 /** 19999 * The id of the window for accessibility purposes. 20000 */ 20001 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 20002 20003 /** 20004 * Flags related to accessibility processing. 20005 * 20006 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 20007 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 20008 */ 20009 int mAccessibilityFetchFlags; 20010 20011 /** 20012 * The drawable for highlighting accessibility focus. 20013 */ 20014 Drawable mAccessibilityFocusDrawable; 20015 20016 /** 20017 * Show where the margins, bounds and layout bounds are for each view. 20018 */ 20019 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 20020 20021 /** 20022 * Point used to compute visible regions. 20023 */ 20024 final Point mPoint = new Point(); 20025 20026 /** 20027 * Used to track which View originated a requestLayout() call, used when 20028 * requestLayout() is called during layout. 20029 */ 20030 View mViewRequestingLayout; 20031 20032 /** 20033 * Creates a new set of attachment information with the specified 20034 * events handler and thread. 20035 * 20036 * @param handler the events handler the view must use 20037 */ 20038 AttachInfo(IWindowSession session, IWindow window, Display display, 20039 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 20040 mSession = session; 20041 mWindow = window; 20042 mWindowToken = window.asBinder(); 20043 mDisplay = display; 20044 mViewRootImpl = viewRootImpl; 20045 mHandler = handler; 20046 mRootCallbacks = effectPlayer; 20047 } 20048 } 20049 20050 /** 20051 * <p>ScrollabilityCache holds various fields used by a View when scrolling 20052 * is supported. This avoids keeping too many unused fields in most 20053 * instances of View.</p> 20054 */ 20055 private static class ScrollabilityCache implements Runnable { 20056 20057 /** 20058 * Scrollbars are not visible 20059 */ 20060 public static final int OFF = 0; 20061 20062 /** 20063 * Scrollbars are visible 20064 */ 20065 public static final int ON = 1; 20066 20067 /** 20068 * Scrollbars are fading away 20069 */ 20070 public static final int FADING = 2; 20071 20072 public boolean fadeScrollBars; 20073 20074 public int fadingEdgeLength; 20075 public int scrollBarDefaultDelayBeforeFade; 20076 public int scrollBarFadeDuration; 20077 20078 public int scrollBarSize; 20079 public ScrollBarDrawable scrollBar; 20080 public float[] interpolatorValues; 20081 public View host; 20082 20083 public final Paint paint; 20084 public final Matrix matrix; 20085 public Shader shader; 20086 20087 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 20088 20089 private static final float[] OPAQUE = { 255 }; 20090 private static final float[] TRANSPARENT = { 0.0f }; 20091 20092 /** 20093 * When fading should start. This time moves into the future every time 20094 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20095 */ 20096 public long fadeStartTime; 20097 20098 20099 /** 20100 * The current state of the scrollbars: ON, OFF, or FADING 20101 */ 20102 public int state = OFF; 20103 20104 private int mLastColor; 20105 20106 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20107 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20108 scrollBarSize = configuration.getScaledScrollBarSize(); 20109 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20110 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20111 20112 paint = new Paint(); 20113 matrix = new Matrix(); 20114 // use use a height of 1, and then wack the matrix each time we 20115 // actually use it. 20116 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20117 paint.setShader(shader); 20118 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20119 20120 this.host = host; 20121 } 20122 20123 public void setFadeColor(int color) { 20124 if (color != mLastColor) { 20125 mLastColor = color; 20126 20127 if (color != 0) { 20128 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20129 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20130 paint.setShader(shader); 20131 // Restore the default transfer mode (src_over) 20132 paint.setXfermode(null); 20133 } else { 20134 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20135 paint.setShader(shader); 20136 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20137 } 20138 } 20139 } 20140 20141 public void run() { 20142 long now = AnimationUtils.currentAnimationTimeMillis(); 20143 if (now >= fadeStartTime) { 20144 20145 // the animation fades the scrollbars out by changing 20146 // the opacity (alpha) from fully opaque to fully 20147 // transparent 20148 int nextFrame = (int) now; 20149 int framesCount = 0; 20150 20151 Interpolator interpolator = scrollBarInterpolator; 20152 20153 // Start opaque 20154 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20155 20156 // End transparent 20157 nextFrame += scrollBarFadeDuration; 20158 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20159 20160 state = FADING; 20161 20162 // Kick off the fade animation 20163 host.invalidate(true); 20164 } 20165 } 20166 } 20167 20168 /** 20169 * Resuable callback for sending 20170 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20171 */ 20172 private class SendViewScrolledAccessibilityEvent implements Runnable { 20173 public volatile boolean mIsPending; 20174 20175 public void run() { 20176 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20177 mIsPending = false; 20178 } 20179 } 20180 20181 /** 20182 * <p> 20183 * This class represents a delegate that can be registered in a {@link View} 20184 * to enhance accessibility support via composition rather via inheritance. 20185 * It is specifically targeted to widget developers that extend basic View 20186 * classes i.e. classes in package android.view, that would like their 20187 * applications to be backwards compatible. 20188 * </p> 20189 * <div class="special reference"> 20190 * <h3>Developer Guides</h3> 20191 * <p>For more information about making applications accessible, read the 20192 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20193 * developer guide.</p> 20194 * </div> 20195 * <p> 20196 * A scenario in which a developer would like to use an accessibility delegate 20197 * is overriding a method introduced in a later API version then the minimal API 20198 * version supported by the application. For example, the method 20199 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20200 * in API version 4 when the accessibility APIs were first introduced. If a 20201 * developer would like his application to run on API version 4 devices (assuming 20202 * all other APIs used by the application are version 4 or lower) and take advantage 20203 * of this method, instead of overriding the method which would break the application's 20204 * backwards compatibility, he can override the corresponding method in this 20205 * delegate and register the delegate in the target View if the API version of 20206 * the system is high enough i.e. the API version is same or higher to the API 20207 * version that introduced 20208 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20209 * </p> 20210 * <p> 20211 * Here is an example implementation: 20212 * </p> 20213 * <code><pre><p> 20214 * if (Build.VERSION.SDK_INT >= 14) { 20215 * // If the API version is equal of higher than the version in 20216 * // which onInitializeAccessibilityNodeInfo was introduced we 20217 * // register a delegate with a customized implementation. 20218 * View view = findViewById(R.id.view_id); 20219 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20220 * public void onInitializeAccessibilityNodeInfo(View host, 20221 * AccessibilityNodeInfo info) { 20222 * // Let the default implementation populate the info. 20223 * super.onInitializeAccessibilityNodeInfo(host, info); 20224 * // Set some other information. 20225 * info.setEnabled(host.isEnabled()); 20226 * } 20227 * }); 20228 * } 20229 * </code></pre></p> 20230 * <p> 20231 * This delegate contains methods that correspond to the accessibility methods 20232 * in View. If a delegate has been specified the implementation in View hands 20233 * off handling to the corresponding method in this delegate. The default 20234 * implementation the delegate methods behaves exactly as the corresponding 20235 * method in View for the case of no accessibility delegate been set. Hence, 20236 * to customize the behavior of a View method, clients can override only the 20237 * corresponding delegate method without altering the behavior of the rest 20238 * accessibility related methods of the host view. 20239 * </p> 20240 */ 20241 public static class AccessibilityDelegate { 20242 20243 /** 20244 * Sends an accessibility event of the given type. If accessibility is not 20245 * enabled this method has no effect. 20246 * <p> 20247 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20248 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20249 * been set. 20250 * </p> 20251 * 20252 * @param host The View hosting the delegate. 20253 * @param eventType The type of the event to send. 20254 * 20255 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20256 */ 20257 public void sendAccessibilityEvent(View host, int eventType) { 20258 host.sendAccessibilityEventInternal(eventType); 20259 } 20260 20261 /** 20262 * Performs the specified accessibility action on the view. For 20263 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20264 * <p> 20265 * The default implementation behaves as 20266 * {@link View#performAccessibilityAction(int, Bundle) 20267 * View#performAccessibilityAction(int, Bundle)} for the case of 20268 * no accessibility delegate been set. 20269 * </p> 20270 * 20271 * @param action The action to perform. 20272 * @return Whether the action was performed. 20273 * 20274 * @see View#performAccessibilityAction(int, Bundle) 20275 * View#performAccessibilityAction(int, Bundle) 20276 */ 20277 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20278 return host.performAccessibilityActionInternal(action, args); 20279 } 20280 20281 /** 20282 * Sends an accessibility event. This method behaves exactly as 20283 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20284 * empty {@link AccessibilityEvent} and does not perform a check whether 20285 * accessibility is enabled. 20286 * <p> 20287 * The default implementation behaves as 20288 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20289 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20290 * the case of no accessibility delegate been set. 20291 * </p> 20292 * 20293 * @param host The View hosting the delegate. 20294 * @param event The event to send. 20295 * 20296 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20297 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20298 */ 20299 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20300 host.sendAccessibilityEventUncheckedInternal(event); 20301 } 20302 20303 /** 20304 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20305 * to its children for adding their text content to the event. 20306 * <p> 20307 * The default implementation behaves as 20308 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20309 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20310 * the case of no accessibility delegate been set. 20311 * </p> 20312 * 20313 * @param host The View hosting the delegate. 20314 * @param event The event. 20315 * @return True if the event population was completed. 20316 * 20317 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20318 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20319 */ 20320 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20321 return host.dispatchPopulateAccessibilityEventInternal(event); 20322 } 20323 20324 /** 20325 * Gives a chance to the host View to populate the accessibility event with its 20326 * text content. 20327 * <p> 20328 * The default implementation behaves as 20329 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20330 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20331 * the case of no accessibility delegate been set. 20332 * </p> 20333 * 20334 * @param host The View hosting the delegate. 20335 * @param event The accessibility event which to populate. 20336 * 20337 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20338 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20339 */ 20340 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20341 host.onPopulateAccessibilityEventInternal(event); 20342 } 20343 20344 /** 20345 * Initializes an {@link AccessibilityEvent} with information about the 20346 * the host View which is the event source. 20347 * <p> 20348 * The default implementation behaves as 20349 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20350 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20351 * the case of no accessibility delegate been set. 20352 * </p> 20353 * 20354 * @param host The View hosting the delegate. 20355 * @param event The event to initialize. 20356 * 20357 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20358 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20359 */ 20360 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20361 host.onInitializeAccessibilityEventInternal(event); 20362 } 20363 20364 /** 20365 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20366 * <p> 20367 * The default implementation behaves as 20368 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20369 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20370 * the case of no accessibility delegate been set. 20371 * </p> 20372 * 20373 * @param host The View hosting the delegate. 20374 * @param info The instance to initialize. 20375 * 20376 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20377 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20378 */ 20379 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20380 host.onInitializeAccessibilityNodeInfoInternal(info); 20381 } 20382 20383 /** 20384 * Called when a child of the host View has requested sending an 20385 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20386 * to augment the event. 20387 * <p> 20388 * The default implementation behaves as 20389 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20390 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20391 * the case of no accessibility delegate been set. 20392 * </p> 20393 * 20394 * @param host The View hosting the delegate. 20395 * @param child The child which requests sending the event. 20396 * @param event The event to be sent. 20397 * @return True if the event should be sent 20398 * 20399 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20400 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20401 */ 20402 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20403 AccessibilityEvent event) { 20404 return host.onRequestSendAccessibilityEventInternal(child, event); 20405 } 20406 20407 /** 20408 * Gets the provider for managing a virtual view hierarchy rooted at this View 20409 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20410 * that explore the window content. 20411 * <p> 20412 * The default implementation behaves as 20413 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20414 * the case of no accessibility delegate been set. 20415 * </p> 20416 * 20417 * @return The provider. 20418 * 20419 * @see AccessibilityNodeProvider 20420 */ 20421 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20422 return null; 20423 } 20424 20425 /** 20426 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20427 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20428 * This method is responsible for obtaining an accessibility node info from a 20429 * pool of reusable instances and calling 20430 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20431 * view to initialize the former. 20432 * <p> 20433 * <strong>Note:</strong> The client is responsible for recycling the obtained 20434 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20435 * creation. 20436 * </p> 20437 * <p> 20438 * The default implementation behaves as 20439 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20440 * the case of no accessibility delegate been set. 20441 * </p> 20442 * @return A populated {@link AccessibilityNodeInfo}. 20443 * 20444 * @see AccessibilityNodeInfo 20445 * 20446 * @hide 20447 */ 20448 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20449 return host.createAccessibilityNodeInfoInternal(); 20450 } 20451 } 20452 20453 private class MatchIdPredicate implements Predicate<View> { 20454 public int mId; 20455 20456 @Override 20457 public boolean apply(View view) { 20458 return (view.mID == mId); 20459 } 20460 } 20461 20462 private class MatchLabelForPredicate implements Predicate<View> { 20463 private int mLabeledId; 20464 20465 @Override 20466 public boolean apply(View view) { 20467 return (view.mLabelForId == mLabeledId); 20468 } 20469 } 20470 20471 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20472 private int mChangeTypes = 0; 20473 private boolean mPosted; 20474 private boolean mPostedWithDelay; 20475 private long mLastEventTimeMillis; 20476 20477 @Override 20478 public void run() { 20479 mPosted = false; 20480 mPostedWithDelay = false; 20481 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20482 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20483 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20484 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20485 event.setContentChangeTypes(mChangeTypes); 20486 sendAccessibilityEventUnchecked(event); 20487 } 20488 mChangeTypes = 0; 20489 } 20490 20491 public void runOrPost(int changeType) { 20492 mChangeTypes |= changeType; 20493 20494 // If this is a live region or the child of a live region, collect 20495 // all events from this frame and send them on the next frame. 20496 if (inLiveRegion()) { 20497 // If we're already posted with a delay, remove that. 20498 if (mPostedWithDelay) { 20499 removeCallbacks(this); 20500 mPostedWithDelay = false; 20501 } 20502 // Only post if we're not already posted. 20503 if (!mPosted) { 20504 post(this); 20505 mPosted = true; 20506 } 20507 return; 20508 } 20509 20510 if (mPosted) { 20511 return; 20512 } 20513 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20514 final long minEventIntevalMillis = 20515 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20516 if (timeSinceLastMillis >= minEventIntevalMillis) { 20517 removeCallbacks(this); 20518 run(); 20519 } else { 20520 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20521 mPosted = true; 20522 mPostedWithDelay = true; 20523 } 20524 } 20525 } 20526 20527 private boolean inLiveRegion() { 20528 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20529 return true; 20530 } 20531 20532 ViewParent parent = getParent(); 20533 while (parent instanceof View) { 20534 if (((View) parent).getAccessibilityLiveRegion() 20535 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20536 return true; 20537 } 20538 parent = parent.getParent(); 20539 } 20540 20541 return false; 20542 } 20543 20544 /** 20545 * Dump all private flags in readable format, useful for documentation and 20546 * sanity checking. 20547 */ 20548 private static void dumpFlags() { 20549 final HashMap<String, String> found = Maps.newHashMap(); 20550 try { 20551 for (Field field : View.class.getDeclaredFields()) { 20552 final int modifiers = field.getModifiers(); 20553 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20554 if (field.getType().equals(int.class)) { 20555 final int value = field.getInt(null); 20556 dumpFlag(found, field.getName(), value); 20557 } else if (field.getType().equals(int[].class)) { 20558 final int[] values = (int[]) field.get(null); 20559 for (int i = 0; i < values.length; i++) { 20560 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20561 } 20562 } 20563 } 20564 } 20565 } catch (IllegalAccessException e) { 20566 throw new RuntimeException(e); 20567 } 20568 20569 final ArrayList<String> keys = Lists.newArrayList(); 20570 keys.addAll(found.keySet()); 20571 Collections.sort(keys); 20572 for (String key : keys) { 20573 Log.d(VIEW_LOG_TAG, found.get(key)); 20574 } 20575 } 20576 20577 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20578 // Sort flags by prefix, then by bits, always keeping unique keys 20579 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20580 final int prefix = name.indexOf('_'); 20581 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20582 final String output = bits + " " + name; 20583 found.put(key, output); 20584 } 20585} 20586