View.java revision ec0c92548071801c81e02ca72b9864739e1c080c
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 @Deprecated 2383 static final int PFLAG3_OUTLINE_DEFINED = 0x20; 2384 2385 /** 2386 * Flag indicating that we're in the process of applying window insets. 2387 */ 2388 static final int PFLAG3_APPLYING_INSETS = 0x40; 2389 2390 /** 2391 * Flag indicating that we're in the process of fitting system windows using the old method. 2392 */ 2393 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80; 2394 2395 /** 2396 * Flag indicating that nested scrolling is enabled for this view. 2397 * The view will optionally cooperate with views up its parent chain to allow for 2398 * integrated nested scrolling along the same axis. 2399 */ 2400 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x200; 2401 2402 /* End of masks for mPrivateFlags3 */ 2403 2404 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2405 2406 /** 2407 * Always allow a user to over-scroll this view, provided it is a 2408 * view that can scroll. 2409 * 2410 * @see #getOverScrollMode() 2411 * @see #setOverScrollMode(int) 2412 */ 2413 public static final int OVER_SCROLL_ALWAYS = 0; 2414 2415 /** 2416 * Allow a user to over-scroll this view only if the content is large 2417 * enough to meaningfully scroll, provided it is a view that can scroll. 2418 * 2419 * @see #getOverScrollMode() 2420 * @see #setOverScrollMode(int) 2421 */ 2422 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2423 2424 /** 2425 * Never allow a user to over-scroll this view. 2426 * 2427 * @see #getOverScrollMode() 2428 * @see #setOverScrollMode(int) 2429 */ 2430 public static final int OVER_SCROLL_NEVER = 2; 2431 2432 /** 2433 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2434 * requested the system UI (status bar) to be visible (the default). 2435 * 2436 * @see #setSystemUiVisibility(int) 2437 */ 2438 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2439 2440 /** 2441 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2442 * system UI to enter an unobtrusive "low profile" mode. 2443 * 2444 * <p>This is for use in games, book readers, video players, or any other 2445 * "immersive" application where the usual system chrome is deemed too distracting. 2446 * 2447 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2448 * 2449 * @see #setSystemUiVisibility(int) 2450 */ 2451 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2452 2453 /** 2454 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2455 * system navigation be temporarily hidden. 2456 * 2457 * <p>This is an even less obtrusive state than that called for by 2458 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2459 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2460 * those to disappear. This is useful (in conjunction with the 2461 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2462 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2463 * window flags) for displaying content using every last pixel on the display. 2464 * 2465 * <p>There is a limitation: because navigation controls are so important, the least user 2466 * interaction will cause them to reappear immediately. When this happens, both 2467 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2468 * so that both elements reappear at the same time. 2469 * 2470 * @see #setSystemUiVisibility(int) 2471 */ 2472 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2473 2474 /** 2475 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2476 * into the normal fullscreen mode so that its content can take over the screen 2477 * while still allowing the user to interact with the application. 2478 * 2479 * <p>This has the same visual effect as 2480 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2481 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2482 * meaning that non-critical screen decorations (such as the status bar) will be 2483 * hidden while the user is in the View's window, focusing the experience on 2484 * that content. Unlike the window flag, if you are using ActionBar in 2485 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2486 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2487 * hide the action bar. 2488 * 2489 * <p>This approach to going fullscreen is best used over the window flag when 2490 * it is a transient state -- that is, the application does this at certain 2491 * points in its user interaction where it wants to allow the user to focus 2492 * on content, but not as a continuous state. For situations where the application 2493 * would like to simply stay full screen the entire time (such as a game that 2494 * wants to take over the screen), the 2495 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2496 * is usually a better approach. The state set here will be removed by the system 2497 * in various situations (such as the user moving to another application) like 2498 * the other system UI states. 2499 * 2500 * <p>When using this flag, the application should provide some easy facility 2501 * for the user to go out of it. A common example would be in an e-book 2502 * reader, where tapping on the screen brings back whatever screen and UI 2503 * decorations that had been hidden while the user was immersed in reading 2504 * the book. 2505 * 2506 * @see #setSystemUiVisibility(int) 2507 */ 2508 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2509 2510 /** 2511 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2512 * flags, we would like a stable view of the content insets given to 2513 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2514 * will always represent the worst case that the application can expect 2515 * as a continuous state. In the stock Android UI this is the space for 2516 * the system bar, nav bar, and status bar, but not more transient elements 2517 * such as an input method. 2518 * 2519 * The stable layout your UI sees is based on the system UI modes you can 2520 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2521 * then you will get a stable layout for changes of the 2522 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2523 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2524 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2525 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2526 * with a stable layout. (Note that you should avoid using 2527 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2528 * 2529 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2530 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2531 * then a hidden status bar will be considered a "stable" state for purposes 2532 * here. This allows your UI to continually hide the status bar, while still 2533 * using the system UI flags to hide the action bar while still retaining 2534 * a stable layout. Note that changing the window fullscreen flag will never 2535 * provide a stable layout for a clean transition. 2536 * 2537 * <p>If you are using ActionBar in 2538 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2539 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2540 * insets it adds to those given to the application. 2541 */ 2542 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2543 2544 /** 2545 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2546 * to be layed out as if it has requested 2547 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2548 * allows it to avoid artifacts when switching in and out of that mode, at 2549 * the expense that some of its user interface may be covered by screen 2550 * decorations when they are shown. You can perform layout of your inner 2551 * UI elements to account for the navigation system UI through the 2552 * {@link #fitSystemWindows(Rect)} method. 2553 */ 2554 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2555 2556 /** 2557 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2558 * to be layed out as if it has requested 2559 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2560 * allows it to avoid artifacts when switching in and out of that mode, at 2561 * the expense that some of its user interface may be covered by screen 2562 * decorations when they are shown. You can perform layout of your inner 2563 * UI elements to account for non-fullscreen system UI through the 2564 * {@link #fitSystemWindows(Rect)} method. 2565 */ 2566 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2567 2568 /** 2569 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2570 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2571 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2572 * user interaction. 2573 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2574 * has an effect when used in combination with that flag.</p> 2575 */ 2576 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2577 2578 /** 2579 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2580 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2581 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2582 * experience while also hiding the system bars. If this flag is not set, 2583 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2584 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2585 * if the user swipes from the top of the screen. 2586 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2587 * system gestures, such as swiping from the top of the screen. These transient system bars 2588 * will overlay app’s content, may have some degree of transparency, and will automatically 2589 * hide after a short timeout. 2590 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2591 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2592 * with one or both of those flags.</p> 2593 */ 2594 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2595 2596 /** 2597 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2598 */ 2599 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2600 2601 /** 2602 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2603 */ 2604 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2605 2606 /** 2607 * @hide 2608 * 2609 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2610 * out of the public fields to keep the undefined bits out of the developer's way. 2611 * 2612 * Flag to make the status bar not expandable. Unless you also 2613 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2614 */ 2615 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2616 2617 /** 2618 * @hide 2619 * 2620 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2621 * out of the public fields to keep the undefined bits out of the developer's way. 2622 * 2623 * Flag to hide notification icons and scrolling ticker text. 2624 */ 2625 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2626 2627 /** 2628 * @hide 2629 * 2630 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2631 * out of the public fields to keep the undefined bits out of the developer's way. 2632 * 2633 * Flag to disable incoming notification alerts. This will not block 2634 * icons, but it will block sound, vibrating and other visual or aural notifications. 2635 */ 2636 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2637 2638 /** 2639 * @hide 2640 * 2641 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2642 * out of the public fields to keep the undefined bits out of the developer's way. 2643 * 2644 * Flag to hide only the scrolling ticker. Note that 2645 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2646 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2647 */ 2648 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2649 2650 /** 2651 * @hide 2652 * 2653 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2654 * out of the public fields to keep the undefined bits out of the developer's way. 2655 * 2656 * Flag to hide the center system info area. 2657 */ 2658 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2659 2660 /** 2661 * @hide 2662 * 2663 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2664 * out of the public fields to keep the undefined bits out of the developer's way. 2665 * 2666 * Flag to hide only the home button. Don't use this 2667 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2668 */ 2669 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2670 2671 /** 2672 * @hide 2673 * 2674 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2675 * out of the public fields to keep the undefined bits out of the developer's way. 2676 * 2677 * Flag to hide only the back button. Don't use this 2678 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2679 */ 2680 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2681 2682 /** 2683 * @hide 2684 * 2685 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2686 * out of the public fields to keep the undefined bits out of the developer's way. 2687 * 2688 * Flag to hide only the clock. You might use this if your activity has 2689 * its own clock making the status bar's clock redundant. 2690 */ 2691 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2692 2693 /** 2694 * @hide 2695 * 2696 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2697 * out of the public fields to keep the undefined bits out of the developer's way. 2698 * 2699 * Flag to hide only the recent apps button. Don't use this 2700 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2701 */ 2702 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2703 2704 /** 2705 * @hide 2706 * 2707 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2708 * out of the public fields to keep the undefined bits out of the developer's way. 2709 * 2710 * Flag to disable the global search gesture. Don't use this 2711 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2712 */ 2713 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2714 2715 /** 2716 * @hide 2717 * 2718 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2719 * out of the public fields to keep the undefined bits out of the developer's way. 2720 * 2721 * Flag to specify that the status bar is displayed in transient mode. 2722 */ 2723 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2724 2725 /** 2726 * @hide 2727 * 2728 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2729 * out of the public fields to keep the undefined bits out of the developer's way. 2730 * 2731 * Flag to specify that the navigation bar is displayed in transient mode. 2732 */ 2733 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2734 2735 /** 2736 * @hide 2737 * 2738 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2739 * out of the public fields to keep the undefined bits out of the developer's way. 2740 * 2741 * Flag to specify that the hidden status bar would like to be shown. 2742 */ 2743 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2744 2745 /** 2746 * @hide 2747 * 2748 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2749 * out of the public fields to keep the undefined bits out of the developer's way. 2750 * 2751 * Flag to specify that the hidden navigation bar would like to be shown. 2752 */ 2753 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2754 2755 /** 2756 * @hide 2757 * 2758 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2759 * out of the public fields to keep the undefined bits out of the developer's way. 2760 * 2761 * Flag to specify that the status bar is displayed in translucent mode. 2762 */ 2763 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2764 2765 /** 2766 * @hide 2767 * 2768 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2769 * out of the public fields to keep the undefined bits out of the developer's way. 2770 * 2771 * Flag to specify that the navigation bar is displayed in translucent mode. 2772 */ 2773 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2774 2775 /** 2776 * @hide 2777 * 2778 * Whether Recents is visible or not. 2779 */ 2780 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2781 2782 /** 2783 * @hide 2784 * 2785 * Makes system ui transparent. 2786 */ 2787 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2788 2789 /** 2790 * @hide 2791 */ 2792 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2793 2794 /** 2795 * These are the system UI flags that can be cleared by events outside 2796 * of an application. Currently this is just the ability to tap on the 2797 * screen while hiding the navigation bar to have it return. 2798 * @hide 2799 */ 2800 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2801 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2802 | SYSTEM_UI_FLAG_FULLSCREEN; 2803 2804 /** 2805 * Flags that can impact the layout in relation to system UI. 2806 */ 2807 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2808 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2809 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2810 2811 /** @hide */ 2812 @IntDef(flag = true, 2813 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2814 @Retention(RetentionPolicy.SOURCE) 2815 public @interface FindViewFlags {} 2816 2817 /** 2818 * Find views that render the specified text. 2819 * 2820 * @see #findViewsWithText(ArrayList, CharSequence, int) 2821 */ 2822 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2823 2824 /** 2825 * Find find views that contain the specified content description. 2826 * 2827 * @see #findViewsWithText(ArrayList, CharSequence, int) 2828 */ 2829 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2830 2831 /** 2832 * Find views that contain {@link AccessibilityNodeProvider}. Such 2833 * a View is a root of virtual view hierarchy and may contain the searched 2834 * text. If this flag is set Views with providers are automatically 2835 * added and it is a responsibility of the client to call the APIs of 2836 * the provider to determine whether the virtual tree rooted at this View 2837 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2838 * representing the virtual views with this text. 2839 * 2840 * @see #findViewsWithText(ArrayList, CharSequence, int) 2841 * 2842 * @hide 2843 */ 2844 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2845 2846 /** 2847 * The undefined cursor position. 2848 * 2849 * @hide 2850 */ 2851 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2852 2853 /** 2854 * Indicates that the screen has changed state and is now off. 2855 * 2856 * @see #onScreenStateChanged(int) 2857 */ 2858 public static final int SCREEN_STATE_OFF = 0x0; 2859 2860 /** 2861 * Indicates that the screen has changed state and is now on. 2862 * 2863 * @see #onScreenStateChanged(int) 2864 */ 2865 public static final int SCREEN_STATE_ON = 0x1; 2866 2867 /** 2868 * Indicates no axis of view scrolling. 2869 */ 2870 public static final int SCROLL_AXIS_NONE = 0; 2871 2872 /** 2873 * Indicates scrolling along the horizontal axis. 2874 */ 2875 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2876 2877 /** 2878 * Indicates scrolling along the vertical axis. 2879 */ 2880 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2881 2882 /** 2883 * Controls the over-scroll mode for this view. 2884 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2885 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2886 * and {@link #OVER_SCROLL_NEVER}. 2887 */ 2888 private int mOverScrollMode; 2889 2890 /** 2891 * The parent this view is attached to. 2892 * {@hide} 2893 * 2894 * @see #getParent() 2895 */ 2896 protected ViewParent mParent; 2897 2898 /** 2899 * {@hide} 2900 */ 2901 AttachInfo mAttachInfo; 2902 2903 /** 2904 * {@hide} 2905 */ 2906 @ViewDebug.ExportedProperty(flagMapping = { 2907 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2908 name = "FORCE_LAYOUT"), 2909 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2910 name = "LAYOUT_REQUIRED"), 2911 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2912 name = "DRAWING_CACHE_INVALID", outputIf = false), 2913 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2914 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2915 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2916 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2917 }) 2918 int mPrivateFlags; 2919 int mPrivateFlags2; 2920 int mPrivateFlags3; 2921 2922 /** 2923 * This view's request for the visibility of the status bar. 2924 * @hide 2925 */ 2926 @ViewDebug.ExportedProperty(flagMapping = { 2927 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2928 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2929 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2930 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2931 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2932 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2933 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2934 equals = SYSTEM_UI_FLAG_VISIBLE, 2935 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2936 }) 2937 int mSystemUiVisibility; 2938 2939 /** 2940 * Reference count for transient state. 2941 * @see #setHasTransientState(boolean) 2942 */ 2943 int mTransientStateCount = 0; 2944 2945 /** 2946 * Count of how many windows this view has been attached to. 2947 */ 2948 int mWindowAttachCount; 2949 2950 /** 2951 * The layout parameters associated with this view and used by the parent 2952 * {@link android.view.ViewGroup} to determine how this view should be 2953 * laid out. 2954 * {@hide} 2955 */ 2956 protected ViewGroup.LayoutParams mLayoutParams; 2957 2958 /** 2959 * The view flags hold various views states. 2960 * {@hide} 2961 */ 2962 @ViewDebug.ExportedProperty 2963 int mViewFlags; 2964 2965 static class TransformationInfo { 2966 /** 2967 * The transform matrix for the View. This transform is calculated internally 2968 * based on the translation, rotation, and scale properties. 2969 * 2970 * Do *not* use this variable directly; instead call getMatrix(), which will 2971 * load the value from the View's RenderNode. 2972 */ 2973 private final Matrix mMatrix = new Matrix(); 2974 2975 /** 2976 * The inverse transform matrix for the View. This transform is calculated 2977 * internally based on the translation, rotation, and scale properties. 2978 * 2979 * Do *not* use this variable directly; instead call getInverseMatrix(), 2980 * which will load the value from the View's RenderNode. 2981 */ 2982 private Matrix mInverseMatrix; 2983 2984 /** 2985 * The opacity of the View. This is a value from 0 to 1, where 0 means 2986 * completely transparent and 1 means completely opaque. 2987 */ 2988 @ViewDebug.ExportedProperty 2989 float mAlpha = 1f; 2990 2991 /** 2992 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2993 * property only used by transitions, which is composited with the other alpha 2994 * values to calculate the final visual alpha value. 2995 */ 2996 float mTransitionAlpha = 1f; 2997 } 2998 2999 TransformationInfo mTransformationInfo; 3000 3001 /** 3002 * Current clip bounds. to which all drawing of this view are constrained. 3003 */ 3004 Rect mClipBounds = null; 3005 3006 private boolean mLastIsOpaque; 3007 3008 /** 3009 * The distance in pixels from the left edge of this view's parent 3010 * to the left edge of this view. 3011 * {@hide} 3012 */ 3013 @ViewDebug.ExportedProperty(category = "layout") 3014 protected int mLeft; 3015 /** 3016 * The distance in pixels from the left edge of this view's parent 3017 * to the right edge of this view. 3018 * {@hide} 3019 */ 3020 @ViewDebug.ExportedProperty(category = "layout") 3021 protected int mRight; 3022 /** 3023 * The distance in pixels from the top edge of this view's parent 3024 * to the top edge of this view. 3025 * {@hide} 3026 */ 3027 @ViewDebug.ExportedProperty(category = "layout") 3028 protected int mTop; 3029 /** 3030 * The distance in pixels from the top edge of this view's parent 3031 * to the bottom edge of this view. 3032 * {@hide} 3033 */ 3034 @ViewDebug.ExportedProperty(category = "layout") 3035 protected int mBottom; 3036 3037 /** 3038 * The offset, in pixels, by which the content of this view is scrolled 3039 * horizontally. 3040 * {@hide} 3041 */ 3042 @ViewDebug.ExportedProperty(category = "scrolling") 3043 protected int mScrollX; 3044 /** 3045 * The offset, in pixels, by which the content of this view is scrolled 3046 * vertically. 3047 * {@hide} 3048 */ 3049 @ViewDebug.ExportedProperty(category = "scrolling") 3050 protected int mScrollY; 3051 3052 /** 3053 * The left padding in pixels, that is the distance in pixels between the 3054 * left edge of this view and the left edge of its content. 3055 * {@hide} 3056 */ 3057 @ViewDebug.ExportedProperty(category = "padding") 3058 protected int mPaddingLeft = 0; 3059 /** 3060 * The right padding in pixels, that is the distance in pixels between the 3061 * right edge of this view and the right edge of its content. 3062 * {@hide} 3063 */ 3064 @ViewDebug.ExportedProperty(category = "padding") 3065 protected int mPaddingRight = 0; 3066 /** 3067 * The top padding in pixels, that is the distance in pixels between the 3068 * top edge of this view and the top edge of its content. 3069 * {@hide} 3070 */ 3071 @ViewDebug.ExportedProperty(category = "padding") 3072 protected int mPaddingTop; 3073 /** 3074 * The bottom padding in pixels, that is the distance in pixels between the 3075 * bottom edge of this view and the bottom edge of its content. 3076 * {@hide} 3077 */ 3078 @ViewDebug.ExportedProperty(category = "padding") 3079 protected int mPaddingBottom; 3080 3081 /** 3082 * The layout insets in pixels, that is the distance in pixels between the 3083 * visible edges of this view its bounds. 3084 */ 3085 private Insets mLayoutInsets; 3086 3087 /** 3088 * Briefly describes the view and is primarily used for accessibility support. 3089 */ 3090 private CharSequence mContentDescription; 3091 3092 /** 3093 * Specifies the id of a view for which this view serves as a label for 3094 * accessibility purposes. 3095 */ 3096 private int mLabelForId = View.NO_ID; 3097 3098 /** 3099 * Predicate for matching labeled view id with its label for 3100 * accessibility purposes. 3101 */ 3102 private MatchLabelForPredicate mMatchLabelForPredicate; 3103 3104 /** 3105 * Predicate for matching a view by its id. 3106 */ 3107 private MatchIdPredicate mMatchIdPredicate; 3108 3109 /** 3110 * Cache the paddingRight set by the user to append to the scrollbar's size. 3111 * 3112 * @hide 3113 */ 3114 @ViewDebug.ExportedProperty(category = "padding") 3115 protected int mUserPaddingRight; 3116 3117 /** 3118 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3119 * 3120 * @hide 3121 */ 3122 @ViewDebug.ExportedProperty(category = "padding") 3123 protected int mUserPaddingBottom; 3124 3125 /** 3126 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3127 * 3128 * @hide 3129 */ 3130 @ViewDebug.ExportedProperty(category = "padding") 3131 protected int mUserPaddingLeft; 3132 3133 /** 3134 * Cache the paddingStart set by the user to append to the scrollbar's size. 3135 * 3136 */ 3137 @ViewDebug.ExportedProperty(category = "padding") 3138 int mUserPaddingStart; 3139 3140 /** 3141 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3142 * 3143 */ 3144 @ViewDebug.ExportedProperty(category = "padding") 3145 int mUserPaddingEnd; 3146 3147 /** 3148 * Cache initial left padding. 3149 * 3150 * @hide 3151 */ 3152 int mUserPaddingLeftInitial; 3153 3154 /** 3155 * Cache initial right padding. 3156 * 3157 * @hide 3158 */ 3159 int mUserPaddingRightInitial; 3160 3161 /** 3162 * Default undefined padding 3163 */ 3164 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3165 3166 /** 3167 * Cache if a left padding has been defined 3168 */ 3169 private boolean mLeftPaddingDefined = false; 3170 3171 /** 3172 * Cache if a right padding has been defined 3173 */ 3174 private boolean mRightPaddingDefined = false; 3175 3176 /** 3177 * @hide 3178 */ 3179 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3180 /** 3181 * @hide 3182 */ 3183 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3184 3185 private LongSparseLongArray mMeasureCache; 3186 3187 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3188 private Drawable mBackground; 3189 private ColorStateList mBackgroundTint = null; 3190 private PorterDuff.Mode mBackgroundTintMode = PorterDuff.Mode.SRC_ATOP; 3191 private boolean mHasBackgroundTint = false; 3192 3193 /** 3194 * RenderNode used for backgrounds. 3195 * <p> 3196 * When non-null and valid, this is expected to contain an up-to-date copy 3197 * of the background drawable. It is cleared on temporary detach, and reset 3198 * on cleanup. 3199 */ 3200 private RenderNode mBackgroundRenderNode; 3201 3202 private int mBackgroundResource; 3203 private boolean mBackgroundSizeChanged; 3204 3205 private String mTransitionName; 3206 3207 static class ListenerInfo { 3208 /** 3209 * Listener used to dispatch focus change events. 3210 * This field should be made private, so it is hidden from the SDK. 3211 * {@hide} 3212 */ 3213 protected OnFocusChangeListener mOnFocusChangeListener; 3214 3215 /** 3216 * Listeners for layout change events. 3217 */ 3218 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3219 3220 /** 3221 * Listeners for attach events. 3222 */ 3223 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3224 3225 /** 3226 * Listener used to dispatch click events. 3227 * This field should be made private, so it is hidden from the SDK. 3228 * {@hide} 3229 */ 3230 public OnClickListener mOnClickListener; 3231 3232 /** 3233 * Listener used to dispatch long click events. 3234 * This field should be made private, so it is hidden from the SDK. 3235 * {@hide} 3236 */ 3237 protected OnLongClickListener mOnLongClickListener; 3238 3239 /** 3240 * Listener used to build the context menu. 3241 * This field should be made private, so it is hidden from the SDK. 3242 * {@hide} 3243 */ 3244 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3245 3246 private OnKeyListener mOnKeyListener; 3247 3248 private OnTouchListener mOnTouchListener; 3249 3250 private OnHoverListener mOnHoverListener; 3251 3252 private OnGenericMotionListener mOnGenericMotionListener; 3253 3254 private OnDragListener mOnDragListener; 3255 3256 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3257 3258 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3259 } 3260 3261 ListenerInfo mListenerInfo; 3262 3263 /** 3264 * The application environment this view lives in. 3265 * This field should be made private, so it is hidden from the SDK. 3266 * {@hide} 3267 */ 3268 protected Context mContext; 3269 3270 private final Resources mResources; 3271 3272 private ScrollabilityCache mScrollCache; 3273 3274 private int[] mDrawableState = null; 3275 3276 @Deprecated 3277 private Outline mOutline; 3278 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3279 3280 /** 3281 * Animator that automatically runs based on state changes. 3282 */ 3283 private StateListAnimator mStateListAnimator; 3284 3285 /** 3286 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3287 * the user may specify which view to go to next. 3288 */ 3289 private int mNextFocusLeftId = View.NO_ID; 3290 3291 /** 3292 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3293 * the user may specify which view to go to next. 3294 */ 3295 private int mNextFocusRightId = View.NO_ID; 3296 3297 /** 3298 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3299 * the user may specify which view to go to next. 3300 */ 3301 private int mNextFocusUpId = View.NO_ID; 3302 3303 /** 3304 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3305 * the user may specify which view to go to next. 3306 */ 3307 private int mNextFocusDownId = View.NO_ID; 3308 3309 /** 3310 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3311 * the user may specify which view to go to next. 3312 */ 3313 int mNextFocusForwardId = View.NO_ID; 3314 3315 private CheckForLongPress mPendingCheckForLongPress; 3316 private CheckForTap mPendingCheckForTap = null; 3317 private PerformClick mPerformClick; 3318 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3319 3320 private UnsetPressedState mUnsetPressedState; 3321 3322 /** 3323 * Whether the long press's action has been invoked. The tap's action is invoked on the 3324 * up event while a long press is invoked as soon as the long press duration is reached, so 3325 * a long press could be performed before the tap is checked, in which case the tap's action 3326 * should not be invoked. 3327 */ 3328 private boolean mHasPerformedLongPress; 3329 3330 /** 3331 * The minimum height of the view. We'll try our best to have the height 3332 * of this view to at least this amount. 3333 */ 3334 @ViewDebug.ExportedProperty(category = "measurement") 3335 private int mMinHeight; 3336 3337 /** 3338 * The minimum width of the view. We'll try our best to have the width 3339 * of this view to at least this amount. 3340 */ 3341 @ViewDebug.ExportedProperty(category = "measurement") 3342 private int mMinWidth; 3343 3344 /** 3345 * The delegate to handle touch events that are physically in this view 3346 * but should be handled by another view. 3347 */ 3348 private TouchDelegate mTouchDelegate = null; 3349 3350 /** 3351 * Solid color to use as a background when creating the drawing cache. Enables 3352 * the cache to use 16 bit bitmaps instead of 32 bit. 3353 */ 3354 private int mDrawingCacheBackgroundColor = 0; 3355 3356 /** 3357 * Special tree observer used when mAttachInfo is null. 3358 */ 3359 private ViewTreeObserver mFloatingTreeObserver; 3360 3361 /** 3362 * Cache the touch slop from the context that created the view. 3363 */ 3364 private int mTouchSlop; 3365 3366 /** 3367 * Object that handles automatic animation of view properties. 3368 */ 3369 private ViewPropertyAnimator mAnimator = null; 3370 3371 /** 3372 * Flag indicating that a drag can cross window boundaries. When 3373 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3374 * with this flag set, all visible applications will be able to participate 3375 * in the drag operation and receive the dragged content. 3376 * 3377 * @hide 3378 */ 3379 public static final int DRAG_FLAG_GLOBAL = 1; 3380 3381 /** 3382 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3383 */ 3384 private float mVerticalScrollFactor; 3385 3386 /** 3387 * Position of the vertical scroll bar. 3388 */ 3389 private int mVerticalScrollbarPosition; 3390 3391 /** 3392 * Position the scroll bar at the default position as determined by the system. 3393 */ 3394 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3395 3396 /** 3397 * Position the scroll bar along the left edge. 3398 */ 3399 public static final int SCROLLBAR_POSITION_LEFT = 1; 3400 3401 /** 3402 * Position the scroll bar along the right edge. 3403 */ 3404 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3405 3406 /** 3407 * Indicates that the view does not have a layer. 3408 * 3409 * @see #getLayerType() 3410 * @see #setLayerType(int, android.graphics.Paint) 3411 * @see #LAYER_TYPE_SOFTWARE 3412 * @see #LAYER_TYPE_HARDWARE 3413 */ 3414 public static final int LAYER_TYPE_NONE = 0; 3415 3416 /** 3417 * <p>Indicates that the view has a software layer. A software layer is backed 3418 * by a bitmap and causes the view to be rendered using Android's software 3419 * rendering pipeline, even if hardware acceleration is enabled.</p> 3420 * 3421 * <p>Software layers have various usages:</p> 3422 * <p>When the application is not using hardware acceleration, a software layer 3423 * is useful to apply a specific color filter and/or blending mode and/or 3424 * translucency to a view and all its children.</p> 3425 * <p>When the application is using hardware acceleration, a software layer 3426 * is useful to render drawing primitives not supported by the hardware 3427 * accelerated pipeline. It can also be used to cache a complex view tree 3428 * into a texture and reduce the complexity of drawing operations. For instance, 3429 * when animating a complex view tree with a translation, a software layer can 3430 * be used to render the view tree only once.</p> 3431 * <p>Software layers should be avoided when the affected view tree updates 3432 * often. Every update will require to re-render the software layer, which can 3433 * potentially be slow (particularly when hardware acceleration is turned on 3434 * since the layer will have to be uploaded into a hardware texture after every 3435 * update.)</p> 3436 * 3437 * @see #getLayerType() 3438 * @see #setLayerType(int, android.graphics.Paint) 3439 * @see #LAYER_TYPE_NONE 3440 * @see #LAYER_TYPE_HARDWARE 3441 */ 3442 public static final int LAYER_TYPE_SOFTWARE = 1; 3443 3444 /** 3445 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3446 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3447 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3448 * rendering pipeline, but only if hardware acceleration is turned on for the 3449 * view hierarchy. When hardware acceleration is turned off, hardware layers 3450 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3451 * 3452 * <p>A hardware layer is useful to apply a specific color filter and/or 3453 * blending mode and/or translucency to a view and all its children.</p> 3454 * <p>A hardware layer can be used to cache a complex view tree into a 3455 * texture and reduce the complexity of drawing operations. For instance, 3456 * when animating a complex view tree with a translation, a hardware layer can 3457 * be used to render the view tree only once.</p> 3458 * <p>A hardware layer can also be used to increase the rendering quality when 3459 * rotation transformations are applied on a view. It can also be used to 3460 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3461 * 3462 * @see #getLayerType() 3463 * @see #setLayerType(int, android.graphics.Paint) 3464 * @see #LAYER_TYPE_NONE 3465 * @see #LAYER_TYPE_SOFTWARE 3466 */ 3467 public static final int LAYER_TYPE_HARDWARE = 2; 3468 3469 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3470 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3471 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3472 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3473 }) 3474 int mLayerType = LAYER_TYPE_NONE; 3475 Paint mLayerPaint; 3476 3477 /** 3478 * Set to true when drawing cache is enabled and cannot be created. 3479 * 3480 * @hide 3481 */ 3482 public boolean mCachingFailed; 3483 private Bitmap mDrawingCache; 3484 private Bitmap mUnscaledDrawingCache; 3485 3486 /** 3487 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3488 * <p> 3489 * When non-null and valid, this is expected to contain an up-to-date copy 3490 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3491 * cleanup. 3492 */ 3493 final RenderNode mRenderNode; 3494 3495 /** 3496 * Set to true when the view is sending hover accessibility events because it 3497 * is the innermost hovered view. 3498 */ 3499 private boolean mSendingHoverAccessibilityEvents; 3500 3501 /** 3502 * Delegate for injecting accessibility functionality. 3503 */ 3504 AccessibilityDelegate mAccessibilityDelegate; 3505 3506 /** 3507 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3508 * and add/remove objects to/from the overlay directly through the Overlay methods. 3509 */ 3510 ViewOverlay mOverlay; 3511 3512 /** 3513 * The currently active parent view for receiving delegated nested scrolling events. 3514 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3515 * by {@link #stopNestedScroll()} at the same point where we clear 3516 * requestDisallowInterceptTouchEvent. 3517 */ 3518 private ViewParent mNestedScrollingParent; 3519 3520 /** 3521 * Consistency verifier for debugging purposes. 3522 * @hide 3523 */ 3524 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3525 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3526 new InputEventConsistencyVerifier(this, 0) : null; 3527 3528 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3529 3530 private int[] mTempNestedScrollConsumed; 3531 3532 /** 3533 * Simple constructor to use when creating a view from code. 3534 * 3535 * @param context The Context the view is running in, through which it can 3536 * access the current theme, resources, etc. 3537 */ 3538 public View(Context context) { 3539 mContext = context; 3540 mResources = context != null ? context.getResources() : null; 3541 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3542 // Set some flags defaults 3543 mPrivateFlags2 = 3544 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3545 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3546 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3547 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3548 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3549 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3550 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3551 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3552 mUserPaddingStart = UNDEFINED_PADDING; 3553 mUserPaddingEnd = UNDEFINED_PADDING; 3554 mRenderNode = RenderNode.create(getClass().getName()); 3555 3556 if (!sCompatibilityDone && context != null) { 3557 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3558 3559 // Older apps may need this compatibility hack for measurement. 3560 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3561 3562 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3563 // of whether a layout was requested on that View. 3564 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3565 3566 // Older apps may need this to ignore the clip bounds 3567 sIgnoreClipBoundsForChildren = targetSdkVersion < L; 3568 3569 sCompatibilityDone = true; 3570 } 3571 } 3572 3573 /** 3574 * Constructor that is called when inflating a view from XML. This is called 3575 * when a view is being constructed from an XML file, supplying attributes 3576 * that were specified in the XML file. This version uses a default style of 3577 * 0, so the only attribute values applied are those in the Context's Theme 3578 * and the given AttributeSet. 3579 * 3580 * <p> 3581 * The method onFinishInflate() will be called after all children have been 3582 * added. 3583 * 3584 * @param context The Context the view is running in, through which it can 3585 * access the current theme, resources, etc. 3586 * @param attrs The attributes of the XML tag that is inflating the view. 3587 * @see #View(Context, AttributeSet, int) 3588 */ 3589 public View(Context context, AttributeSet attrs) { 3590 this(context, attrs, 0); 3591 } 3592 3593 /** 3594 * Perform inflation from XML and apply a class-specific base style from a 3595 * theme attribute. This constructor of View allows subclasses to use their 3596 * own base style when they are inflating. For example, a Button class's 3597 * constructor would call this version of the super class constructor and 3598 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3599 * allows the theme's button style to modify all of the base view attributes 3600 * (in particular its background) as well as the Button class's attributes. 3601 * 3602 * @param context The Context the view is running in, through which it can 3603 * access the current theme, resources, etc. 3604 * @param attrs The attributes of the XML tag that is inflating the view. 3605 * @param defStyleAttr An attribute in the current theme that contains a 3606 * reference to a style resource that supplies default values for 3607 * the view. Can be 0 to not look for defaults. 3608 * @see #View(Context, AttributeSet) 3609 */ 3610 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3611 this(context, attrs, defStyleAttr, 0); 3612 } 3613 3614 /** 3615 * Perform inflation from XML and apply a class-specific base style from a 3616 * theme attribute or style resource. This constructor of View allows 3617 * subclasses to use their own base style when they are inflating. 3618 * <p> 3619 * When determining the final value of a particular attribute, there are 3620 * four inputs that come into play: 3621 * <ol> 3622 * <li>Any attribute values in the given AttributeSet. 3623 * <li>The style resource specified in the AttributeSet (named "style"). 3624 * <li>The default style specified by <var>defStyleAttr</var>. 3625 * <li>The default style specified by <var>defStyleRes</var>. 3626 * <li>The base values in this theme. 3627 * </ol> 3628 * <p> 3629 * Each of these inputs is considered in-order, with the first listed taking 3630 * precedence over the following ones. In other words, if in the 3631 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3632 * , then the button's text will <em>always</em> be black, regardless of 3633 * what is specified in any of the styles. 3634 * 3635 * @param context The Context the view is running in, through which it can 3636 * access the current theme, resources, etc. 3637 * @param attrs The attributes of the XML tag that is inflating the view. 3638 * @param defStyleAttr An attribute in the current theme that contains a 3639 * reference to a style resource that supplies default values for 3640 * the view. Can be 0 to not look for defaults. 3641 * @param defStyleRes A resource identifier of a style resource that 3642 * supplies default values for the view, used only if 3643 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3644 * to not look for defaults. 3645 * @see #View(Context, AttributeSet, int) 3646 */ 3647 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3648 this(context); 3649 3650 final TypedArray a = context.obtainStyledAttributes( 3651 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3652 3653 Drawable background = null; 3654 3655 int leftPadding = -1; 3656 int topPadding = -1; 3657 int rightPadding = -1; 3658 int bottomPadding = -1; 3659 int startPadding = UNDEFINED_PADDING; 3660 int endPadding = UNDEFINED_PADDING; 3661 3662 int padding = -1; 3663 3664 int viewFlagValues = 0; 3665 int viewFlagMasks = 0; 3666 3667 boolean setScrollContainer = false; 3668 3669 int x = 0; 3670 int y = 0; 3671 3672 float tx = 0; 3673 float ty = 0; 3674 float tz = 0; 3675 float elevation = 0; 3676 float rotation = 0; 3677 float rotationX = 0; 3678 float rotationY = 0; 3679 float sx = 1f; 3680 float sy = 1f; 3681 boolean transformSet = false; 3682 3683 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3684 int overScrollMode = mOverScrollMode; 3685 boolean initializeScrollbars = false; 3686 3687 boolean startPaddingDefined = false; 3688 boolean endPaddingDefined = false; 3689 boolean leftPaddingDefined = false; 3690 boolean rightPaddingDefined = false; 3691 3692 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3693 3694 final int N = a.getIndexCount(); 3695 for (int i = 0; i < N; i++) { 3696 int attr = a.getIndex(i); 3697 switch (attr) { 3698 case com.android.internal.R.styleable.View_background: 3699 background = a.getDrawable(attr); 3700 break; 3701 case com.android.internal.R.styleable.View_padding: 3702 padding = a.getDimensionPixelSize(attr, -1); 3703 mUserPaddingLeftInitial = padding; 3704 mUserPaddingRightInitial = padding; 3705 leftPaddingDefined = true; 3706 rightPaddingDefined = true; 3707 break; 3708 case com.android.internal.R.styleable.View_paddingLeft: 3709 leftPadding = a.getDimensionPixelSize(attr, -1); 3710 mUserPaddingLeftInitial = leftPadding; 3711 leftPaddingDefined = true; 3712 break; 3713 case com.android.internal.R.styleable.View_paddingTop: 3714 topPadding = a.getDimensionPixelSize(attr, -1); 3715 break; 3716 case com.android.internal.R.styleable.View_paddingRight: 3717 rightPadding = a.getDimensionPixelSize(attr, -1); 3718 mUserPaddingRightInitial = rightPadding; 3719 rightPaddingDefined = true; 3720 break; 3721 case com.android.internal.R.styleable.View_paddingBottom: 3722 bottomPadding = a.getDimensionPixelSize(attr, -1); 3723 break; 3724 case com.android.internal.R.styleable.View_paddingStart: 3725 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3726 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3727 break; 3728 case com.android.internal.R.styleable.View_paddingEnd: 3729 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3730 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3731 break; 3732 case com.android.internal.R.styleable.View_scrollX: 3733 x = a.getDimensionPixelOffset(attr, 0); 3734 break; 3735 case com.android.internal.R.styleable.View_scrollY: 3736 y = a.getDimensionPixelOffset(attr, 0); 3737 break; 3738 case com.android.internal.R.styleable.View_alpha: 3739 setAlpha(a.getFloat(attr, 1f)); 3740 break; 3741 case com.android.internal.R.styleable.View_transformPivotX: 3742 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3743 break; 3744 case com.android.internal.R.styleable.View_transformPivotY: 3745 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3746 break; 3747 case com.android.internal.R.styleable.View_translationX: 3748 tx = a.getDimensionPixelOffset(attr, 0); 3749 transformSet = true; 3750 break; 3751 case com.android.internal.R.styleable.View_translationY: 3752 ty = a.getDimensionPixelOffset(attr, 0); 3753 transformSet = true; 3754 break; 3755 case com.android.internal.R.styleable.View_translationZ: 3756 tz = a.getDimensionPixelOffset(attr, 0); 3757 transformSet = true; 3758 break; 3759 case com.android.internal.R.styleable.View_elevation: 3760 elevation = a.getDimensionPixelOffset(attr, 0); 3761 transformSet = true; 3762 break; 3763 case com.android.internal.R.styleable.View_rotation: 3764 rotation = a.getFloat(attr, 0); 3765 transformSet = true; 3766 break; 3767 case com.android.internal.R.styleable.View_rotationX: 3768 rotationX = a.getFloat(attr, 0); 3769 transformSet = true; 3770 break; 3771 case com.android.internal.R.styleable.View_rotationY: 3772 rotationY = a.getFloat(attr, 0); 3773 transformSet = true; 3774 break; 3775 case com.android.internal.R.styleable.View_scaleX: 3776 sx = a.getFloat(attr, 1f); 3777 transformSet = true; 3778 break; 3779 case com.android.internal.R.styleable.View_scaleY: 3780 sy = a.getFloat(attr, 1f); 3781 transformSet = true; 3782 break; 3783 case com.android.internal.R.styleable.View_id: 3784 mID = a.getResourceId(attr, NO_ID); 3785 break; 3786 case com.android.internal.R.styleable.View_tag: 3787 mTag = a.getText(attr); 3788 break; 3789 case com.android.internal.R.styleable.View_fitsSystemWindows: 3790 if (a.getBoolean(attr, false)) { 3791 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3792 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3793 } 3794 break; 3795 case com.android.internal.R.styleable.View_focusable: 3796 if (a.getBoolean(attr, false)) { 3797 viewFlagValues |= FOCUSABLE; 3798 viewFlagMasks |= FOCUSABLE_MASK; 3799 } 3800 break; 3801 case com.android.internal.R.styleable.View_focusableInTouchMode: 3802 if (a.getBoolean(attr, false)) { 3803 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3804 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3805 } 3806 break; 3807 case com.android.internal.R.styleable.View_clickable: 3808 if (a.getBoolean(attr, false)) { 3809 viewFlagValues |= CLICKABLE; 3810 viewFlagMasks |= CLICKABLE; 3811 } 3812 break; 3813 case com.android.internal.R.styleable.View_longClickable: 3814 if (a.getBoolean(attr, false)) { 3815 viewFlagValues |= LONG_CLICKABLE; 3816 viewFlagMasks |= LONG_CLICKABLE; 3817 } 3818 break; 3819 case com.android.internal.R.styleable.View_saveEnabled: 3820 if (!a.getBoolean(attr, true)) { 3821 viewFlagValues |= SAVE_DISABLED; 3822 viewFlagMasks |= SAVE_DISABLED_MASK; 3823 } 3824 break; 3825 case com.android.internal.R.styleable.View_duplicateParentState: 3826 if (a.getBoolean(attr, false)) { 3827 viewFlagValues |= DUPLICATE_PARENT_STATE; 3828 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3829 } 3830 break; 3831 case com.android.internal.R.styleable.View_visibility: 3832 final int visibility = a.getInt(attr, 0); 3833 if (visibility != 0) { 3834 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3835 viewFlagMasks |= VISIBILITY_MASK; 3836 } 3837 break; 3838 case com.android.internal.R.styleable.View_layoutDirection: 3839 // Clear any layout direction flags (included resolved bits) already set 3840 mPrivateFlags2 &= 3841 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3842 // Set the layout direction flags depending on the value of the attribute 3843 final int layoutDirection = a.getInt(attr, -1); 3844 final int value = (layoutDirection != -1) ? 3845 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3846 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3847 break; 3848 case com.android.internal.R.styleable.View_drawingCacheQuality: 3849 final int cacheQuality = a.getInt(attr, 0); 3850 if (cacheQuality != 0) { 3851 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3852 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3853 } 3854 break; 3855 case com.android.internal.R.styleable.View_contentDescription: 3856 setContentDescription(a.getString(attr)); 3857 break; 3858 case com.android.internal.R.styleable.View_labelFor: 3859 setLabelFor(a.getResourceId(attr, NO_ID)); 3860 break; 3861 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3862 if (!a.getBoolean(attr, true)) { 3863 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3864 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3865 } 3866 break; 3867 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3868 if (!a.getBoolean(attr, true)) { 3869 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3870 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3871 } 3872 break; 3873 case R.styleable.View_scrollbars: 3874 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3875 if (scrollbars != SCROLLBARS_NONE) { 3876 viewFlagValues |= scrollbars; 3877 viewFlagMasks |= SCROLLBARS_MASK; 3878 initializeScrollbars = true; 3879 } 3880 break; 3881 //noinspection deprecation 3882 case R.styleable.View_fadingEdge: 3883 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3884 // Ignore the attribute starting with ICS 3885 break; 3886 } 3887 // With builds < ICS, fall through and apply fading edges 3888 case R.styleable.View_requiresFadingEdge: 3889 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3890 if (fadingEdge != FADING_EDGE_NONE) { 3891 viewFlagValues |= fadingEdge; 3892 viewFlagMasks |= FADING_EDGE_MASK; 3893 initializeFadingEdgeInternal(a); 3894 } 3895 break; 3896 case R.styleable.View_scrollbarStyle: 3897 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3898 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3899 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3900 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3901 } 3902 break; 3903 case R.styleable.View_isScrollContainer: 3904 setScrollContainer = true; 3905 if (a.getBoolean(attr, false)) { 3906 setScrollContainer(true); 3907 } 3908 break; 3909 case com.android.internal.R.styleable.View_keepScreenOn: 3910 if (a.getBoolean(attr, false)) { 3911 viewFlagValues |= KEEP_SCREEN_ON; 3912 viewFlagMasks |= KEEP_SCREEN_ON; 3913 } 3914 break; 3915 case R.styleable.View_filterTouchesWhenObscured: 3916 if (a.getBoolean(attr, false)) { 3917 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3918 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3919 } 3920 break; 3921 case R.styleable.View_nextFocusLeft: 3922 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3923 break; 3924 case R.styleable.View_nextFocusRight: 3925 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3926 break; 3927 case R.styleable.View_nextFocusUp: 3928 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3929 break; 3930 case R.styleable.View_nextFocusDown: 3931 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3932 break; 3933 case R.styleable.View_nextFocusForward: 3934 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3935 break; 3936 case R.styleable.View_minWidth: 3937 mMinWidth = a.getDimensionPixelSize(attr, 0); 3938 break; 3939 case R.styleable.View_minHeight: 3940 mMinHeight = a.getDimensionPixelSize(attr, 0); 3941 break; 3942 case R.styleable.View_onClick: 3943 if (context.isRestricted()) { 3944 throw new IllegalStateException("The android:onClick attribute cannot " 3945 + "be used within a restricted context"); 3946 } 3947 3948 final String handlerName = a.getString(attr); 3949 if (handlerName != null) { 3950 setOnClickListener(new OnClickListener() { 3951 private Method mHandler; 3952 3953 public void onClick(View v) { 3954 if (mHandler == null) { 3955 try { 3956 mHandler = getContext().getClass().getMethod(handlerName, 3957 View.class); 3958 } catch (NoSuchMethodException e) { 3959 int id = getId(); 3960 String idText = id == NO_ID ? "" : " with id '" 3961 + getContext().getResources().getResourceEntryName( 3962 id) + "'"; 3963 throw new IllegalStateException("Could not find a method " + 3964 handlerName + "(View) in the activity " 3965 + getContext().getClass() + " for onClick handler" 3966 + " on view " + View.this.getClass() + idText, e); 3967 } 3968 } 3969 3970 try { 3971 mHandler.invoke(getContext(), View.this); 3972 } catch (IllegalAccessException e) { 3973 throw new IllegalStateException("Could not execute non " 3974 + "public method of the activity", e); 3975 } catch (InvocationTargetException e) { 3976 throw new IllegalStateException("Could not execute " 3977 + "method of the activity", e); 3978 } 3979 } 3980 }); 3981 } 3982 break; 3983 case R.styleable.View_overScrollMode: 3984 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3985 break; 3986 case R.styleable.View_verticalScrollbarPosition: 3987 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3988 break; 3989 case R.styleable.View_layerType: 3990 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3991 break; 3992 case R.styleable.View_textDirection: 3993 // Clear any text direction flag already set 3994 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3995 // Set the text direction flags depending on the value of the attribute 3996 final int textDirection = a.getInt(attr, -1); 3997 if (textDirection != -1) { 3998 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3999 } 4000 break; 4001 case R.styleable.View_textAlignment: 4002 // Clear any text alignment flag already set 4003 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4004 // Set the text alignment flag depending on the value of the attribute 4005 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4006 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4007 break; 4008 case R.styleable.View_importantForAccessibility: 4009 setImportantForAccessibility(a.getInt(attr, 4010 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4011 break; 4012 case R.styleable.View_accessibilityLiveRegion: 4013 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4014 break; 4015 case R.styleable.View_transitionName: 4016 setTransitionName(a.getString(attr)); 4017 break; 4018 case R.styleable.View_nestedScrollingEnabled: 4019 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4020 break; 4021 case R.styleable.View_stateListAnimator: 4022 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4023 a.getResourceId(attr, 0))); 4024 break; 4025 case R.styleable.View_backgroundTint: 4026 // This will get applied later during setBackground(). 4027 mBackgroundTint = a.getColorStateList(R.styleable.View_backgroundTint); 4028 mHasBackgroundTint = true; 4029 break; 4030 case R.styleable.View_backgroundTintMode: 4031 // This will get applied later during setBackground(). 4032 mBackgroundTintMode = Drawable.parseTintMode(a.getInt( 4033 R.styleable.View_backgroundTintMode, -1), mBackgroundTintMode); 4034 break; 4035 } 4036 } 4037 4038 setOverScrollMode(overScrollMode); 4039 4040 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4041 // the resolved layout direction). Those cached values will be used later during padding 4042 // resolution. 4043 mUserPaddingStart = startPadding; 4044 mUserPaddingEnd = endPadding; 4045 4046 if (background != null) { 4047 setBackground(background); 4048 } 4049 4050 // setBackground above will record that padding is currently provided by the background. 4051 // If we have padding specified via xml, record that here instead and use it. 4052 mLeftPaddingDefined = leftPaddingDefined; 4053 mRightPaddingDefined = rightPaddingDefined; 4054 4055 if (padding >= 0) { 4056 leftPadding = padding; 4057 topPadding = padding; 4058 rightPadding = padding; 4059 bottomPadding = padding; 4060 mUserPaddingLeftInitial = padding; 4061 mUserPaddingRightInitial = padding; 4062 } 4063 4064 if (isRtlCompatibilityMode()) { 4065 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4066 // left / right padding are used if defined (meaning here nothing to do). If they are not 4067 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4068 // start / end and resolve them as left / right (layout direction is not taken into account). 4069 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4070 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4071 // defined. 4072 if (!mLeftPaddingDefined && startPaddingDefined) { 4073 leftPadding = startPadding; 4074 } 4075 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4076 if (!mRightPaddingDefined && endPaddingDefined) { 4077 rightPadding = endPadding; 4078 } 4079 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4080 } else { 4081 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4082 // values defined. Otherwise, left /right values are used. 4083 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4084 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4085 // defined. 4086 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4087 4088 if (mLeftPaddingDefined && !hasRelativePadding) { 4089 mUserPaddingLeftInitial = leftPadding; 4090 } 4091 if (mRightPaddingDefined && !hasRelativePadding) { 4092 mUserPaddingRightInitial = rightPadding; 4093 } 4094 } 4095 4096 internalSetPadding( 4097 mUserPaddingLeftInitial, 4098 topPadding >= 0 ? topPadding : mPaddingTop, 4099 mUserPaddingRightInitial, 4100 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4101 4102 if (viewFlagMasks != 0) { 4103 setFlags(viewFlagValues, viewFlagMasks); 4104 } 4105 4106 if (initializeScrollbars) { 4107 initializeScrollbarsInternal(a); 4108 } 4109 4110 a.recycle(); 4111 4112 // Needs to be called after mViewFlags is set 4113 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4114 recomputePadding(); 4115 } 4116 4117 if (x != 0 || y != 0) { 4118 scrollTo(x, y); 4119 } 4120 4121 if (transformSet) { 4122 setTranslationX(tx); 4123 setTranslationY(ty); 4124 setTranslationZ(tz); 4125 setElevation(elevation); 4126 setRotation(rotation); 4127 setRotationX(rotationX); 4128 setRotationY(rotationY); 4129 setScaleX(sx); 4130 setScaleY(sy); 4131 } 4132 4133 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4134 setScrollContainer(true); 4135 } 4136 4137 computeOpaqueFlags(); 4138 } 4139 4140 /** 4141 * Non-public constructor for use in testing 4142 */ 4143 View() { 4144 mResources = null; 4145 mRenderNode = RenderNode.create(getClass().getName()); 4146 } 4147 4148 public String toString() { 4149 StringBuilder out = new StringBuilder(128); 4150 out.append(getClass().getName()); 4151 out.append('{'); 4152 out.append(Integer.toHexString(System.identityHashCode(this))); 4153 out.append(' '); 4154 switch (mViewFlags&VISIBILITY_MASK) { 4155 case VISIBLE: out.append('V'); break; 4156 case INVISIBLE: out.append('I'); break; 4157 case GONE: out.append('G'); break; 4158 default: out.append('.'); break; 4159 } 4160 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4161 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4162 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4163 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4164 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4165 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4166 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4167 out.append(' '); 4168 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4169 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4170 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4171 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4172 out.append('p'); 4173 } else { 4174 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4175 } 4176 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4177 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4178 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4179 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4180 out.append(' '); 4181 out.append(mLeft); 4182 out.append(','); 4183 out.append(mTop); 4184 out.append('-'); 4185 out.append(mRight); 4186 out.append(','); 4187 out.append(mBottom); 4188 final int id = getId(); 4189 if (id != NO_ID) { 4190 out.append(" #"); 4191 out.append(Integer.toHexString(id)); 4192 final Resources r = mResources; 4193 if (Resources.resourceHasPackage(id) && r != null) { 4194 try { 4195 String pkgname; 4196 switch (id&0xff000000) { 4197 case 0x7f000000: 4198 pkgname="app"; 4199 break; 4200 case 0x01000000: 4201 pkgname="android"; 4202 break; 4203 default: 4204 pkgname = r.getResourcePackageName(id); 4205 break; 4206 } 4207 String typename = r.getResourceTypeName(id); 4208 String entryname = r.getResourceEntryName(id); 4209 out.append(" "); 4210 out.append(pkgname); 4211 out.append(":"); 4212 out.append(typename); 4213 out.append("/"); 4214 out.append(entryname); 4215 } catch (Resources.NotFoundException e) { 4216 } 4217 } 4218 } 4219 out.append("}"); 4220 return out.toString(); 4221 } 4222 4223 /** 4224 * <p> 4225 * Initializes the fading edges from a given set of styled attributes. This 4226 * method should be called by subclasses that need fading edges and when an 4227 * instance of these subclasses is created programmatically rather than 4228 * being inflated from XML. This method is automatically called when the XML 4229 * is inflated. 4230 * </p> 4231 * 4232 * @param a the styled attributes set to initialize the fading edges from 4233 */ 4234 protected void initializeFadingEdge(TypedArray a) { 4235 // This method probably shouldn't have been included in the SDK to begin with. 4236 // It relies on 'a' having been initialized using an attribute filter array that is 4237 // not publicly available to the SDK. The old method has been renamed 4238 // to initializeFadingEdgeInternal and hidden for framework use only; 4239 // this one initializes using defaults to make it safe to call for apps. 4240 4241 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4242 4243 initializeFadingEdgeInternal(arr); 4244 4245 arr.recycle(); 4246 } 4247 4248 /** 4249 * <p> 4250 * Initializes the fading edges from a given set of styled attributes. This 4251 * method should be called by subclasses that need fading edges and when an 4252 * instance of these subclasses is created programmatically rather than 4253 * being inflated from XML. This method is automatically called when the XML 4254 * is inflated. 4255 * </p> 4256 * 4257 * @param a the styled attributes set to initialize the fading edges from 4258 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4259 */ 4260 protected void initializeFadingEdgeInternal(TypedArray a) { 4261 initScrollCache(); 4262 4263 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4264 R.styleable.View_fadingEdgeLength, 4265 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4266 } 4267 4268 /** 4269 * Returns the size of the vertical faded edges used to indicate that more 4270 * content in this view is visible. 4271 * 4272 * @return The size in pixels of the vertical faded edge or 0 if vertical 4273 * faded edges are not enabled for this view. 4274 * @attr ref android.R.styleable#View_fadingEdgeLength 4275 */ 4276 public int getVerticalFadingEdgeLength() { 4277 if (isVerticalFadingEdgeEnabled()) { 4278 ScrollabilityCache cache = mScrollCache; 4279 if (cache != null) { 4280 return cache.fadingEdgeLength; 4281 } 4282 } 4283 return 0; 4284 } 4285 4286 /** 4287 * Set the size of the faded edge used to indicate that more content in this 4288 * view is available. Will not change whether the fading edge is enabled; use 4289 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4290 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4291 * for the vertical or horizontal fading edges. 4292 * 4293 * @param length The size in pixels of the faded edge used to indicate that more 4294 * content in this view is visible. 4295 */ 4296 public void setFadingEdgeLength(int length) { 4297 initScrollCache(); 4298 mScrollCache.fadingEdgeLength = length; 4299 } 4300 4301 /** 4302 * Returns the size of the horizontal faded edges used to indicate that more 4303 * content in this view is visible. 4304 * 4305 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4306 * faded edges are not enabled for this view. 4307 * @attr ref android.R.styleable#View_fadingEdgeLength 4308 */ 4309 public int getHorizontalFadingEdgeLength() { 4310 if (isHorizontalFadingEdgeEnabled()) { 4311 ScrollabilityCache cache = mScrollCache; 4312 if (cache != null) { 4313 return cache.fadingEdgeLength; 4314 } 4315 } 4316 return 0; 4317 } 4318 4319 /** 4320 * Returns the width of the vertical scrollbar. 4321 * 4322 * @return The width in pixels of the vertical scrollbar or 0 if there 4323 * is no vertical scrollbar. 4324 */ 4325 public int getVerticalScrollbarWidth() { 4326 ScrollabilityCache cache = mScrollCache; 4327 if (cache != null) { 4328 ScrollBarDrawable scrollBar = cache.scrollBar; 4329 if (scrollBar != null) { 4330 int size = scrollBar.getSize(true); 4331 if (size <= 0) { 4332 size = cache.scrollBarSize; 4333 } 4334 return size; 4335 } 4336 return 0; 4337 } 4338 return 0; 4339 } 4340 4341 /** 4342 * Returns the height of the horizontal scrollbar. 4343 * 4344 * @return The height in pixels of the horizontal scrollbar or 0 if 4345 * there is no horizontal scrollbar. 4346 */ 4347 protected int getHorizontalScrollbarHeight() { 4348 ScrollabilityCache cache = mScrollCache; 4349 if (cache != null) { 4350 ScrollBarDrawable scrollBar = cache.scrollBar; 4351 if (scrollBar != null) { 4352 int size = scrollBar.getSize(false); 4353 if (size <= 0) { 4354 size = cache.scrollBarSize; 4355 } 4356 return size; 4357 } 4358 return 0; 4359 } 4360 return 0; 4361 } 4362 4363 /** 4364 * <p> 4365 * Initializes the scrollbars from a given set of styled attributes. This 4366 * method should be called by subclasses that need scrollbars and when an 4367 * instance of these subclasses is created programmatically rather than 4368 * being inflated from XML. This method is automatically called when the XML 4369 * is inflated. 4370 * </p> 4371 * 4372 * @param a the styled attributes set to initialize the scrollbars from 4373 */ 4374 protected void initializeScrollbars(TypedArray a) { 4375 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4376 // using the View filter array which is not available to the SDK. As such, internal 4377 // framework usage now uses initializeScrollbarsInternal and we grab a default 4378 // TypedArray with the right filter instead here. 4379 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4380 4381 initializeScrollbarsInternal(arr); 4382 4383 // We ignored the method parameter. Recycle the one we actually did use. 4384 arr.recycle(); 4385 } 4386 4387 /** 4388 * <p> 4389 * Initializes the scrollbars from a given set of styled attributes. This 4390 * method should be called by subclasses that need scrollbars and when an 4391 * instance of these subclasses is created programmatically rather than 4392 * being inflated from XML. This method is automatically called when the XML 4393 * is inflated. 4394 * </p> 4395 * 4396 * @param a the styled attributes set to initialize the scrollbars from 4397 * @hide 4398 */ 4399 protected void initializeScrollbarsInternal(TypedArray a) { 4400 initScrollCache(); 4401 4402 final ScrollabilityCache scrollabilityCache = mScrollCache; 4403 4404 if (scrollabilityCache.scrollBar == null) { 4405 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4406 } 4407 4408 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4409 4410 if (!fadeScrollbars) { 4411 scrollabilityCache.state = ScrollabilityCache.ON; 4412 } 4413 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4414 4415 4416 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4417 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4418 .getScrollBarFadeDuration()); 4419 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4420 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4421 ViewConfiguration.getScrollDefaultDelay()); 4422 4423 4424 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4425 com.android.internal.R.styleable.View_scrollbarSize, 4426 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4427 4428 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4429 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4430 4431 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4432 if (thumb != null) { 4433 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4434 } 4435 4436 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4437 false); 4438 if (alwaysDraw) { 4439 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4440 } 4441 4442 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4443 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4444 4445 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4446 if (thumb != null) { 4447 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4448 } 4449 4450 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4451 false); 4452 if (alwaysDraw) { 4453 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4454 } 4455 4456 // Apply layout direction to the new Drawables if needed 4457 final int layoutDirection = getLayoutDirection(); 4458 if (track != null) { 4459 track.setLayoutDirection(layoutDirection); 4460 } 4461 if (thumb != null) { 4462 thumb.setLayoutDirection(layoutDirection); 4463 } 4464 4465 // Re-apply user/background padding so that scrollbar(s) get added 4466 resolvePadding(); 4467 } 4468 4469 /** 4470 * <p> 4471 * Initalizes the scrollability cache if necessary. 4472 * </p> 4473 */ 4474 private void initScrollCache() { 4475 if (mScrollCache == null) { 4476 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4477 } 4478 } 4479 4480 private ScrollabilityCache getScrollCache() { 4481 initScrollCache(); 4482 return mScrollCache; 4483 } 4484 4485 /** 4486 * Set the position of the vertical scroll bar. Should be one of 4487 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4488 * {@link #SCROLLBAR_POSITION_RIGHT}. 4489 * 4490 * @param position Where the vertical scroll bar should be positioned. 4491 */ 4492 public void setVerticalScrollbarPosition(int position) { 4493 if (mVerticalScrollbarPosition != position) { 4494 mVerticalScrollbarPosition = position; 4495 computeOpaqueFlags(); 4496 resolvePadding(); 4497 } 4498 } 4499 4500 /** 4501 * @return The position where the vertical scroll bar will show, if applicable. 4502 * @see #setVerticalScrollbarPosition(int) 4503 */ 4504 public int getVerticalScrollbarPosition() { 4505 return mVerticalScrollbarPosition; 4506 } 4507 4508 ListenerInfo getListenerInfo() { 4509 if (mListenerInfo != null) { 4510 return mListenerInfo; 4511 } 4512 mListenerInfo = new ListenerInfo(); 4513 return mListenerInfo; 4514 } 4515 4516 /** 4517 * Register a callback to be invoked when focus of this view changed. 4518 * 4519 * @param l The callback that will run. 4520 */ 4521 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4522 getListenerInfo().mOnFocusChangeListener = l; 4523 } 4524 4525 /** 4526 * Add a listener that will be called when the bounds of the view change due to 4527 * layout processing. 4528 * 4529 * @param listener The listener that will be called when layout bounds change. 4530 */ 4531 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4532 ListenerInfo li = getListenerInfo(); 4533 if (li.mOnLayoutChangeListeners == null) { 4534 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4535 } 4536 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4537 li.mOnLayoutChangeListeners.add(listener); 4538 } 4539 } 4540 4541 /** 4542 * Remove a listener for layout changes. 4543 * 4544 * @param listener The listener for layout bounds change. 4545 */ 4546 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4547 ListenerInfo li = mListenerInfo; 4548 if (li == null || li.mOnLayoutChangeListeners == null) { 4549 return; 4550 } 4551 li.mOnLayoutChangeListeners.remove(listener); 4552 } 4553 4554 /** 4555 * Add a listener for attach state changes. 4556 * 4557 * This listener will be called whenever this view is attached or detached 4558 * from a window. Remove the listener using 4559 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4560 * 4561 * @param listener Listener to attach 4562 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4563 */ 4564 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4565 ListenerInfo li = getListenerInfo(); 4566 if (li.mOnAttachStateChangeListeners == null) { 4567 li.mOnAttachStateChangeListeners 4568 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4569 } 4570 li.mOnAttachStateChangeListeners.add(listener); 4571 } 4572 4573 /** 4574 * Remove a listener for attach state changes. The listener will receive no further 4575 * notification of window attach/detach events. 4576 * 4577 * @param listener Listener to remove 4578 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4579 */ 4580 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4581 ListenerInfo li = mListenerInfo; 4582 if (li == null || li.mOnAttachStateChangeListeners == null) { 4583 return; 4584 } 4585 li.mOnAttachStateChangeListeners.remove(listener); 4586 } 4587 4588 /** 4589 * Returns the focus-change callback registered for this view. 4590 * 4591 * @return The callback, or null if one is not registered. 4592 */ 4593 public OnFocusChangeListener getOnFocusChangeListener() { 4594 ListenerInfo li = mListenerInfo; 4595 return li != null ? li.mOnFocusChangeListener : null; 4596 } 4597 4598 /** 4599 * Register a callback to be invoked when this view is clicked. If this view is not 4600 * clickable, it becomes clickable. 4601 * 4602 * @param l The callback that will run 4603 * 4604 * @see #setClickable(boolean) 4605 */ 4606 public void setOnClickListener(OnClickListener l) { 4607 if (!isClickable()) { 4608 setClickable(true); 4609 } 4610 getListenerInfo().mOnClickListener = l; 4611 } 4612 4613 /** 4614 * Return whether this view has an attached OnClickListener. Returns 4615 * true if there is a listener, false if there is none. 4616 */ 4617 public boolean hasOnClickListeners() { 4618 ListenerInfo li = mListenerInfo; 4619 return (li != null && li.mOnClickListener != null); 4620 } 4621 4622 /** 4623 * Register a callback to be invoked when this view is clicked and held. If this view is not 4624 * long clickable, it becomes long clickable. 4625 * 4626 * @param l The callback that will run 4627 * 4628 * @see #setLongClickable(boolean) 4629 */ 4630 public void setOnLongClickListener(OnLongClickListener l) { 4631 if (!isLongClickable()) { 4632 setLongClickable(true); 4633 } 4634 getListenerInfo().mOnLongClickListener = l; 4635 } 4636 4637 /** 4638 * Register a callback to be invoked when the context menu for this view is 4639 * being built. If this view is not long clickable, it becomes long clickable. 4640 * 4641 * @param l The callback that will run 4642 * 4643 */ 4644 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4645 if (!isLongClickable()) { 4646 setLongClickable(true); 4647 } 4648 getListenerInfo().mOnCreateContextMenuListener = l; 4649 } 4650 4651 /** 4652 * Call this view's OnClickListener, if it is defined. Performs all normal 4653 * actions associated with clicking: reporting accessibility event, playing 4654 * a sound, etc. 4655 * 4656 * @return True there was an assigned OnClickListener that was called, false 4657 * otherwise is returned. 4658 */ 4659 public boolean performClick() { 4660 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4661 4662 ListenerInfo li = mListenerInfo; 4663 if (li != null && li.mOnClickListener != null) { 4664 playSoundEffect(SoundEffectConstants.CLICK); 4665 li.mOnClickListener.onClick(this); 4666 return true; 4667 } 4668 4669 return false; 4670 } 4671 4672 /** 4673 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4674 * this only calls the listener, and does not do any associated clicking 4675 * actions like reporting an accessibility event. 4676 * 4677 * @return True there was an assigned OnClickListener that was called, false 4678 * otherwise is returned. 4679 */ 4680 public boolean callOnClick() { 4681 ListenerInfo li = mListenerInfo; 4682 if (li != null && li.mOnClickListener != null) { 4683 li.mOnClickListener.onClick(this); 4684 return true; 4685 } 4686 return false; 4687 } 4688 4689 /** 4690 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4691 * OnLongClickListener did not consume the event. 4692 * 4693 * @return True if one of the above receivers consumed the event, false otherwise. 4694 */ 4695 public boolean performLongClick() { 4696 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4697 4698 boolean handled = false; 4699 ListenerInfo li = mListenerInfo; 4700 if (li != null && li.mOnLongClickListener != null) { 4701 handled = li.mOnLongClickListener.onLongClick(View.this); 4702 } 4703 if (!handled) { 4704 handled = showContextMenu(); 4705 } 4706 if (handled) { 4707 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4708 } 4709 return handled; 4710 } 4711 4712 /** 4713 * Performs button-related actions during a touch down event. 4714 * 4715 * @param event The event. 4716 * @return True if the down was consumed. 4717 * 4718 * @hide 4719 */ 4720 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4721 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4722 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4723 return true; 4724 } 4725 } 4726 return false; 4727 } 4728 4729 /** 4730 * Bring up the context menu for this view. 4731 * 4732 * @return Whether a context menu was displayed. 4733 */ 4734 public boolean showContextMenu() { 4735 return getParent().showContextMenuForChild(this); 4736 } 4737 4738 /** 4739 * Bring up the context menu for this view, referring to the item under the specified point. 4740 * 4741 * @param x The referenced x coordinate. 4742 * @param y The referenced y coordinate. 4743 * @param metaState The keyboard modifiers that were pressed. 4744 * @return Whether a context menu was displayed. 4745 * 4746 * @hide 4747 */ 4748 public boolean showContextMenu(float x, float y, int metaState) { 4749 return showContextMenu(); 4750 } 4751 4752 /** 4753 * Start an action mode. 4754 * 4755 * @param callback Callback that will control the lifecycle of the action mode 4756 * @return The new action mode if it is started, null otherwise 4757 * 4758 * @see ActionMode 4759 */ 4760 public ActionMode startActionMode(ActionMode.Callback callback) { 4761 ViewParent parent = getParent(); 4762 if (parent == null) return null; 4763 return parent.startActionModeForChild(this, callback); 4764 } 4765 4766 /** 4767 * Register a callback to be invoked when a hardware key is pressed in this view. 4768 * Key presses in software input methods will generally not trigger the methods of 4769 * this listener. 4770 * @param l the key listener to attach to this view 4771 */ 4772 public void setOnKeyListener(OnKeyListener l) { 4773 getListenerInfo().mOnKeyListener = l; 4774 } 4775 4776 /** 4777 * Register a callback to be invoked when a touch event is sent to this view. 4778 * @param l the touch listener to attach to this view 4779 */ 4780 public void setOnTouchListener(OnTouchListener l) { 4781 getListenerInfo().mOnTouchListener = l; 4782 } 4783 4784 /** 4785 * Register a callback to be invoked when a generic motion event is sent to this view. 4786 * @param l the generic motion listener to attach to this view 4787 */ 4788 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4789 getListenerInfo().mOnGenericMotionListener = l; 4790 } 4791 4792 /** 4793 * Register a callback to be invoked when a hover event is sent to this view. 4794 * @param l the hover listener to attach to this view 4795 */ 4796 public void setOnHoverListener(OnHoverListener l) { 4797 getListenerInfo().mOnHoverListener = l; 4798 } 4799 4800 /** 4801 * Register a drag event listener callback object for this View. The parameter is 4802 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4803 * View, the system calls the 4804 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4805 * @param l An implementation of {@link android.view.View.OnDragListener}. 4806 */ 4807 public void setOnDragListener(OnDragListener l) { 4808 getListenerInfo().mOnDragListener = l; 4809 } 4810 4811 /** 4812 * Give this view focus. This will cause 4813 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4814 * 4815 * Note: this does not check whether this {@link View} should get focus, it just 4816 * gives it focus no matter what. It should only be called internally by framework 4817 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4818 * 4819 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4820 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4821 * focus moved when requestFocus() is called. It may not always 4822 * apply, in which case use the default View.FOCUS_DOWN. 4823 * @param previouslyFocusedRect The rectangle of the view that had focus 4824 * prior in this View's coordinate system. 4825 */ 4826 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4827 if (DBG) { 4828 System.out.println(this + " requestFocus()"); 4829 } 4830 4831 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4832 mPrivateFlags |= PFLAG_FOCUSED; 4833 4834 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4835 4836 if (mParent != null) { 4837 mParent.requestChildFocus(this, this); 4838 } 4839 4840 if (mAttachInfo != null) { 4841 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4842 } 4843 4844 onFocusChanged(true, direction, previouslyFocusedRect); 4845 manageFocusHotspot(true, oldFocus); 4846 refreshDrawableState(); 4847 } 4848 } 4849 4850 /** 4851 * Forwards focus information to the background drawable, if necessary. When 4852 * the view is gaining focus, <code>v</code> is the previous focus holder. 4853 * When the view is losing focus, <code>v</code> is the next focus holder. 4854 * 4855 * @param focused whether this view is focused 4856 * @param v previous or the next focus holder, or null if none 4857 */ 4858 private void manageFocusHotspot(boolean focused, View v) { 4859 final Rect r = new Rect(); 4860 if (!focused && v != null && mAttachInfo != null) { 4861 v.getBoundsOnScreen(r); 4862 final int[] location = mAttachInfo.mTmpLocation; 4863 getLocationOnScreen(location); 4864 r.offset(-location[0], -location[1]); 4865 } else { 4866 r.set(0, 0, mRight - mLeft, mBottom - mTop); 4867 } 4868 4869 final float x = r.exactCenterX(); 4870 final float y = r.exactCenterY(); 4871 drawableHotspotChanged(x, y); 4872 } 4873 4874 /** 4875 * Request that a rectangle of this view be visible on the screen, 4876 * scrolling if necessary just enough. 4877 * 4878 * <p>A View should call this if it maintains some notion of which part 4879 * of its content is interesting. For example, a text editing view 4880 * should call this when its cursor moves. 4881 * 4882 * @param rectangle The rectangle. 4883 * @return Whether any parent scrolled. 4884 */ 4885 public boolean requestRectangleOnScreen(Rect rectangle) { 4886 return requestRectangleOnScreen(rectangle, false); 4887 } 4888 4889 /** 4890 * Request that a rectangle of this view be visible on the screen, 4891 * scrolling if necessary just enough. 4892 * 4893 * <p>A View should call this if it maintains some notion of which part 4894 * of its content is interesting. For example, a text editing view 4895 * should call this when its cursor moves. 4896 * 4897 * <p>When <code>immediate</code> is set to true, scrolling will not be 4898 * animated. 4899 * 4900 * @param rectangle The rectangle. 4901 * @param immediate True to forbid animated scrolling, false otherwise 4902 * @return Whether any parent scrolled. 4903 */ 4904 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4905 if (mParent == null) { 4906 return false; 4907 } 4908 4909 View child = this; 4910 4911 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4912 position.set(rectangle); 4913 4914 ViewParent parent = mParent; 4915 boolean scrolled = false; 4916 while (parent != null) { 4917 rectangle.set((int) position.left, (int) position.top, 4918 (int) position.right, (int) position.bottom); 4919 4920 scrolled |= parent.requestChildRectangleOnScreen(child, 4921 rectangle, immediate); 4922 4923 if (!child.hasIdentityMatrix()) { 4924 child.getMatrix().mapRect(position); 4925 } 4926 4927 position.offset(child.mLeft, child.mTop); 4928 4929 if (!(parent instanceof View)) { 4930 break; 4931 } 4932 4933 View parentView = (View) parent; 4934 4935 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4936 4937 child = parentView; 4938 parent = child.getParent(); 4939 } 4940 4941 return scrolled; 4942 } 4943 4944 /** 4945 * Called when this view wants to give up focus. If focus is cleared 4946 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4947 * <p> 4948 * <strong>Note:</strong> When a View clears focus the framework is trying 4949 * to give focus to the first focusable View from the top. Hence, if this 4950 * View is the first from the top that can take focus, then all callbacks 4951 * related to clearing focus will be invoked after wich the framework will 4952 * give focus to this view. 4953 * </p> 4954 */ 4955 public void clearFocus() { 4956 if (DBG) { 4957 System.out.println(this + " clearFocus()"); 4958 } 4959 4960 clearFocusInternal(null, true, true); 4961 } 4962 4963 /** 4964 * Clears focus from the view, optionally propagating the change up through 4965 * the parent hierarchy and requesting that the root view place new focus. 4966 * 4967 * @param propagate whether to propagate the change up through the parent 4968 * hierarchy 4969 * @param refocus when propagate is true, specifies whether to request the 4970 * root view place new focus 4971 */ 4972 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4973 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4974 mPrivateFlags &= ~PFLAG_FOCUSED; 4975 4976 if (propagate && mParent != null) { 4977 mParent.clearChildFocus(this); 4978 } 4979 4980 onFocusChanged(false, 0, null); 4981 4982 manageFocusHotspot(false, focused); 4983 refreshDrawableState(); 4984 4985 if (propagate && (!refocus || !rootViewRequestFocus())) { 4986 notifyGlobalFocusCleared(this); 4987 } 4988 } 4989 } 4990 4991 void notifyGlobalFocusCleared(View oldFocus) { 4992 if (oldFocus != null && mAttachInfo != null) { 4993 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4994 } 4995 } 4996 4997 boolean rootViewRequestFocus() { 4998 final View root = getRootView(); 4999 return root != null && root.requestFocus(); 5000 } 5001 5002 /** 5003 * Called internally by the view system when a new view is getting focus. 5004 * This is what clears the old focus. 5005 * <p> 5006 * <b>NOTE:</b> The parent view's focused child must be updated manually 5007 * after calling this method. Otherwise, the view hierarchy may be left in 5008 * an inconstent state. 5009 */ 5010 void unFocus(View focused) { 5011 if (DBG) { 5012 System.out.println(this + " unFocus()"); 5013 } 5014 5015 clearFocusInternal(focused, false, false); 5016 } 5017 5018 /** 5019 * Returns true if this view has focus iteself, or is the ancestor of the 5020 * view that has focus. 5021 * 5022 * @return True if this view has or contains focus, false otherwise. 5023 */ 5024 @ViewDebug.ExportedProperty(category = "focus") 5025 public boolean hasFocus() { 5026 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5027 } 5028 5029 /** 5030 * Returns true if this view is focusable or if it contains a reachable View 5031 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5032 * is a View whose parents do not block descendants focus. 5033 * 5034 * Only {@link #VISIBLE} views are considered focusable. 5035 * 5036 * @return True if the view is focusable or if the view contains a focusable 5037 * View, false otherwise. 5038 * 5039 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5040 */ 5041 public boolean hasFocusable() { 5042 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5043 } 5044 5045 /** 5046 * Called by the view system when the focus state of this view changes. 5047 * When the focus change event is caused by directional navigation, direction 5048 * and previouslyFocusedRect provide insight into where the focus is coming from. 5049 * When overriding, be sure to call up through to the super class so that 5050 * the standard focus handling will occur. 5051 * 5052 * @param gainFocus True if the View has focus; false otherwise. 5053 * @param direction The direction focus has moved when requestFocus() 5054 * is called to give this view focus. Values are 5055 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5056 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5057 * It may not always apply, in which case use the default. 5058 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5059 * system, of the previously focused view. If applicable, this will be 5060 * passed in as finer grained information about where the focus is coming 5061 * from (in addition to direction). Will be <code>null</code> otherwise. 5062 */ 5063 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5064 @Nullable Rect previouslyFocusedRect) { 5065 if (gainFocus) { 5066 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5067 } else { 5068 notifyViewAccessibilityStateChangedIfNeeded( 5069 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5070 } 5071 5072 InputMethodManager imm = InputMethodManager.peekInstance(); 5073 if (!gainFocus) { 5074 if (isPressed()) { 5075 setPressed(false); 5076 } 5077 if (imm != null && mAttachInfo != null 5078 && mAttachInfo.mHasWindowFocus) { 5079 imm.focusOut(this); 5080 } 5081 onFocusLost(); 5082 } else if (imm != null && mAttachInfo != null 5083 && mAttachInfo.mHasWindowFocus) { 5084 imm.focusIn(this); 5085 } 5086 5087 invalidate(true); 5088 ListenerInfo li = mListenerInfo; 5089 if (li != null && li.mOnFocusChangeListener != null) { 5090 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5091 } 5092 5093 if (mAttachInfo != null) { 5094 mAttachInfo.mKeyDispatchState.reset(this); 5095 } 5096 } 5097 5098 /** 5099 * Sends an accessibility event of the given type. If accessibility is 5100 * not enabled this method has no effect. The default implementation calls 5101 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5102 * to populate information about the event source (this View), then calls 5103 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5104 * populate the text content of the event source including its descendants, 5105 * and last calls 5106 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5107 * on its parent to resuest sending of the event to interested parties. 5108 * <p> 5109 * If an {@link AccessibilityDelegate} has been specified via calling 5110 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5111 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5112 * responsible for handling this call. 5113 * </p> 5114 * 5115 * @param eventType The type of the event to send, as defined by several types from 5116 * {@link android.view.accessibility.AccessibilityEvent}, such as 5117 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5118 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5119 * 5120 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5121 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5122 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5123 * @see AccessibilityDelegate 5124 */ 5125 public void sendAccessibilityEvent(int eventType) { 5126 if (mAccessibilityDelegate != null) { 5127 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5128 } else { 5129 sendAccessibilityEventInternal(eventType); 5130 } 5131 } 5132 5133 /** 5134 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5135 * {@link AccessibilityEvent} to make an announcement which is related to some 5136 * sort of a context change for which none of the events representing UI transitions 5137 * is a good fit. For example, announcing a new page in a book. If accessibility 5138 * is not enabled this method does nothing. 5139 * 5140 * @param text The announcement text. 5141 */ 5142 public void announceForAccessibility(CharSequence text) { 5143 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5144 AccessibilityEvent event = AccessibilityEvent.obtain( 5145 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5146 onInitializeAccessibilityEvent(event); 5147 event.getText().add(text); 5148 event.setContentDescription(null); 5149 mParent.requestSendAccessibilityEvent(this, event); 5150 } 5151 } 5152 5153 /** 5154 * @see #sendAccessibilityEvent(int) 5155 * 5156 * Note: Called from the default {@link AccessibilityDelegate}. 5157 */ 5158 void sendAccessibilityEventInternal(int eventType) { 5159 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5160 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5161 } 5162 } 5163 5164 /** 5165 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5166 * takes as an argument an empty {@link AccessibilityEvent} and does not 5167 * perform a check whether accessibility is enabled. 5168 * <p> 5169 * If an {@link AccessibilityDelegate} has been specified via calling 5170 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5171 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5172 * is responsible for handling this call. 5173 * </p> 5174 * 5175 * @param event The event to send. 5176 * 5177 * @see #sendAccessibilityEvent(int) 5178 */ 5179 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5180 if (mAccessibilityDelegate != null) { 5181 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5182 } else { 5183 sendAccessibilityEventUncheckedInternal(event); 5184 } 5185 } 5186 5187 /** 5188 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5189 * 5190 * Note: Called from the default {@link AccessibilityDelegate}. 5191 */ 5192 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5193 if (!isShown()) { 5194 return; 5195 } 5196 onInitializeAccessibilityEvent(event); 5197 // Only a subset of accessibility events populates text content. 5198 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5199 dispatchPopulateAccessibilityEvent(event); 5200 } 5201 // In the beginning we called #isShown(), so we know that getParent() is not null. 5202 getParent().requestSendAccessibilityEvent(this, event); 5203 } 5204 5205 /** 5206 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5207 * to its children for adding their text content to the event. Note that the 5208 * event text is populated in a separate dispatch path since we add to the 5209 * event not only the text of the source but also the text of all its descendants. 5210 * A typical implementation will call 5211 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5212 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5213 * on each child. Override this method if custom population of the event text 5214 * content is required. 5215 * <p> 5216 * If an {@link AccessibilityDelegate} has been specified via calling 5217 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5218 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5219 * is responsible for handling this call. 5220 * </p> 5221 * <p> 5222 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5223 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5224 * </p> 5225 * 5226 * @param event The event. 5227 * 5228 * @return True if the event population was completed. 5229 */ 5230 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5231 if (mAccessibilityDelegate != null) { 5232 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5233 } else { 5234 return dispatchPopulateAccessibilityEventInternal(event); 5235 } 5236 } 5237 5238 /** 5239 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5240 * 5241 * Note: Called from the default {@link AccessibilityDelegate}. 5242 */ 5243 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5244 onPopulateAccessibilityEvent(event); 5245 return false; 5246 } 5247 5248 /** 5249 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5250 * giving a chance to this View to populate the accessibility event with its 5251 * text content. While this method is free to modify event 5252 * attributes other than text content, doing so should normally be performed in 5253 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5254 * <p> 5255 * Example: Adding formatted date string to an accessibility event in addition 5256 * to the text added by the super implementation: 5257 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5258 * super.onPopulateAccessibilityEvent(event); 5259 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5260 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5261 * mCurrentDate.getTimeInMillis(), flags); 5262 * event.getText().add(selectedDateUtterance); 5263 * }</pre> 5264 * <p> 5265 * If an {@link AccessibilityDelegate} has been specified via calling 5266 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5267 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5268 * is responsible for handling this call. 5269 * </p> 5270 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5271 * information to the event, in case the default implementation has basic information to add. 5272 * </p> 5273 * 5274 * @param event The accessibility event which to populate. 5275 * 5276 * @see #sendAccessibilityEvent(int) 5277 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5278 */ 5279 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5280 if (mAccessibilityDelegate != null) { 5281 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5282 } else { 5283 onPopulateAccessibilityEventInternal(event); 5284 } 5285 } 5286 5287 /** 5288 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5289 * 5290 * Note: Called from the default {@link AccessibilityDelegate}. 5291 */ 5292 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5293 } 5294 5295 /** 5296 * Initializes an {@link AccessibilityEvent} with information about 5297 * this View which is the event source. In other words, the source of 5298 * an accessibility event is the view whose state change triggered firing 5299 * the event. 5300 * <p> 5301 * Example: Setting the password property of an event in addition 5302 * to properties set by the super implementation: 5303 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5304 * super.onInitializeAccessibilityEvent(event); 5305 * event.setPassword(true); 5306 * }</pre> 5307 * <p> 5308 * If an {@link AccessibilityDelegate} has been specified via calling 5309 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5310 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5311 * is responsible for handling this call. 5312 * </p> 5313 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5314 * information to the event, in case the default implementation has basic information to add. 5315 * </p> 5316 * @param event The event to initialize. 5317 * 5318 * @see #sendAccessibilityEvent(int) 5319 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5320 */ 5321 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5322 if (mAccessibilityDelegate != null) { 5323 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5324 } else { 5325 onInitializeAccessibilityEventInternal(event); 5326 } 5327 } 5328 5329 /** 5330 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5331 * 5332 * Note: Called from the default {@link AccessibilityDelegate}. 5333 */ 5334 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5335 event.setSource(this); 5336 event.setClassName(View.class.getName()); 5337 event.setPackageName(getContext().getPackageName()); 5338 event.setEnabled(isEnabled()); 5339 event.setContentDescription(mContentDescription); 5340 5341 switch (event.getEventType()) { 5342 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5343 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5344 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5345 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5346 event.setItemCount(focusablesTempList.size()); 5347 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5348 if (mAttachInfo != null) { 5349 focusablesTempList.clear(); 5350 } 5351 } break; 5352 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5353 CharSequence text = getIterableTextForAccessibility(); 5354 if (text != null && text.length() > 0) { 5355 event.setFromIndex(getAccessibilitySelectionStart()); 5356 event.setToIndex(getAccessibilitySelectionEnd()); 5357 event.setItemCount(text.length()); 5358 } 5359 } break; 5360 } 5361 } 5362 5363 /** 5364 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5365 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5366 * This method is responsible for obtaining an accessibility node info from a 5367 * pool of reusable instances and calling 5368 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5369 * initialize the former. 5370 * <p> 5371 * Note: The client is responsible for recycling the obtained instance by calling 5372 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5373 * </p> 5374 * 5375 * @return A populated {@link AccessibilityNodeInfo}. 5376 * 5377 * @see AccessibilityNodeInfo 5378 */ 5379 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5380 if (mAccessibilityDelegate != null) { 5381 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5382 } else { 5383 return createAccessibilityNodeInfoInternal(); 5384 } 5385 } 5386 5387 /** 5388 * @see #createAccessibilityNodeInfo() 5389 */ 5390 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5391 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5392 if (provider != null) { 5393 return provider.createAccessibilityNodeInfo(View.NO_ID); 5394 } else { 5395 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5396 onInitializeAccessibilityNodeInfo(info); 5397 return info; 5398 } 5399 } 5400 5401 /** 5402 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5403 * The base implementation sets: 5404 * <ul> 5405 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5406 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5407 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5408 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5409 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5410 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5411 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5412 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5413 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5414 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5415 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5416 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5417 * </ul> 5418 * <p> 5419 * Subclasses should override this method, call the super implementation, 5420 * and set additional attributes. 5421 * </p> 5422 * <p> 5423 * If an {@link AccessibilityDelegate} has been specified via calling 5424 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5425 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5426 * is responsible for handling this call. 5427 * </p> 5428 * 5429 * @param info The instance to initialize. 5430 */ 5431 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5432 if (mAccessibilityDelegate != null) { 5433 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5434 } else { 5435 onInitializeAccessibilityNodeInfoInternal(info); 5436 } 5437 } 5438 5439 /** 5440 * Gets the location of this view in screen coordintates. 5441 * 5442 * @param outRect The output location 5443 * @hide 5444 */ 5445 public void getBoundsOnScreen(Rect outRect) { 5446 if (mAttachInfo == null) { 5447 return; 5448 } 5449 5450 RectF position = mAttachInfo.mTmpTransformRect; 5451 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5452 5453 if (!hasIdentityMatrix()) { 5454 getMatrix().mapRect(position); 5455 } 5456 5457 position.offset(mLeft, mTop); 5458 5459 ViewParent parent = mParent; 5460 while (parent instanceof View) { 5461 View parentView = (View) parent; 5462 5463 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5464 5465 if (!parentView.hasIdentityMatrix()) { 5466 parentView.getMatrix().mapRect(position); 5467 } 5468 5469 position.offset(parentView.mLeft, parentView.mTop); 5470 5471 parent = parentView.mParent; 5472 } 5473 5474 if (parent instanceof ViewRootImpl) { 5475 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5476 position.offset(0, -viewRootImpl.mCurScrollY); 5477 } 5478 5479 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5480 5481 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5482 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5483 } 5484 5485 /** 5486 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5487 * 5488 * Note: Called from the default {@link AccessibilityDelegate}. 5489 */ 5490 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5491 Rect bounds = mAttachInfo.mTmpInvalRect; 5492 5493 getDrawingRect(bounds); 5494 info.setBoundsInParent(bounds); 5495 5496 getBoundsOnScreen(bounds); 5497 info.setBoundsInScreen(bounds); 5498 5499 ViewParent parent = getParentForAccessibility(); 5500 if (parent instanceof View) { 5501 info.setParent((View) parent); 5502 } 5503 5504 if (mID != View.NO_ID) { 5505 View rootView = getRootView(); 5506 if (rootView == null) { 5507 rootView = this; 5508 } 5509 View label = rootView.findLabelForView(this, mID); 5510 if (label != null) { 5511 info.setLabeledBy(label); 5512 } 5513 5514 if ((mAttachInfo.mAccessibilityFetchFlags 5515 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5516 && Resources.resourceHasPackage(mID)) { 5517 try { 5518 String viewId = getResources().getResourceName(mID); 5519 info.setViewIdResourceName(viewId); 5520 } catch (Resources.NotFoundException nfe) { 5521 /* ignore */ 5522 } 5523 } 5524 } 5525 5526 if (mLabelForId != View.NO_ID) { 5527 View rootView = getRootView(); 5528 if (rootView == null) { 5529 rootView = this; 5530 } 5531 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5532 if (labeled != null) { 5533 info.setLabelFor(labeled); 5534 } 5535 } 5536 5537 info.setVisibleToUser(isVisibleToUser()); 5538 5539 info.setPackageName(mContext.getPackageName()); 5540 info.setClassName(View.class.getName()); 5541 info.setContentDescription(getContentDescription()); 5542 5543 info.setEnabled(isEnabled()); 5544 info.setClickable(isClickable()); 5545 info.setFocusable(isFocusable()); 5546 info.setFocused(isFocused()); 5547 info.setAccessibilityFocused(isAccessibilityFocused()); 5548 info.setSelected(isSelected()); 5549 info.setLongClickable(isLongClickable()); 5550 info.setLiveRegion(getAccessibilityLiveRegion()); 5551 5552 // TODO: These make sense only if we are in an AdapterView but all 5553 // views can be selected. Maybe from accessibility perspective 5554 // we should report as selectable view in an AdapterView. 5555 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5556 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5557 5558 if (isFocusable()) { 5559 if (isFocused()) { 5560 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5561 } else { 5562 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5563 } 5564 } 5565 5566 if (!isAccessibilityFocused()) { 5567 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5568 } else { 5569 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5570 } 5571 5572 if (isClickable() && isEnabled()) { 5573 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5574 } 5575 5576 if (isLongClickable() && isEnabled()) { 5577 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5578 } 5579 5580 CharSequence text = getIterableTextForAccessibility(); 5581 if (text != null && text.length() > 0) { 5582 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5583 5584 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5585 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5586 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5587 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5588 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5589 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5590 } 5591 } 5592 5593 private View findLabelForView(View view, int labeledId) { 5594 if (mMatchLabelForPredicate == null) { 5595 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5596 } 5597 mMatchLabelForPredicate.mLabeledId = labeledId; 5598 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5599 } 5600 5601 /** 5602 * Computes whether this view is visible to the user. Such a view is 5603 * attached, visible, all its predecessors are visible, it is not clipped 5604 * entirely by its predecessors, and has an alpha greater than zero. 5605 * 5606 * @return Whether the view is visible on the screen. 5607 * 5608 * @hide 5609 */ 5610 protected boolean isVisibleToUser() { 5611 return isVisibleToUser(null); 5612 } 5613 5614 /** 5615 * Computes whether the given portion of this view is visible to the user. 5616 * Such a view is attached, visible, all its predecessors are visible, 5617 * has an alpha greater than zero, and the specified portion is not 5618 * clipped entirely by its predecessors. 5619 * 5620 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5621 * <code>null</code>, and the entire view will be tested in this case. 5622 * When <code>true</code> is returned by the function, the actual visible 5623 * region will be stored in this parameter; that is, if boundInView is fully 5624 * contained within the view, no modification will be made, otherwise regions 5625 * outside of the visible area of the view will be clipped. 5626 * 5627 * @return Whether the specified portion of the view is visible on the screen. 5628 * 5629 * @hide 5630 */ 5631 protected boolean isVisibleToUser(Rect boundInView) { 5632 if (mAttachInfo != null) { 5633 // Attached to invisible window means this view is not visible. 5634 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5635 return false; 5636 } 5637 // An invisible predecessor or one with alpha zero means 5638 // that this view is not visible to the user. 5639 Object current = this; 5640 while (current instanceof View) { 5641 View view = (View) current; 5642 // We have attach info so this view is attached and there is no 5643 // need to check whether we reach to ViewRootImpl on the way up. 5644 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5645 view.getVisibility() != VISIBLE) { 5646 return false; 5647 } 5648 current = view.mParent; 5649 } 5650 // Check if the view is entirely covered by its predecessors. 5651 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5652 Point offset = mAttachInfo.mPoint; 5653 if (!getGlobalVisibleRect(visibleRect, offset)) { 5654 return false; 5655 } 5656 // Check if the visible portion intersects the rectangle of interest. 5657 if (boundInView != null) { 5658 visibleRect.offset(-offset.x, -offset.y); 5659 return boundInView.intersect(visibleRect); 5660 } 5661 return true; 5662 } 5663 return false; 5664 } 5665 5666 /** 5667 * Returns the delegate for implementing accessibility support via 5668 * composition. For more details see {@link AccessibilityDelegate}. 5669 * 5670 * @return The delegate, or null if none set. 5671 * 5672 * @hide 5673 */ 5674 public AccessibilityDelegate getAccessibilityDelegate() { 5675 return mAccessibilityDelegate; 5676 } 5677 5678 /** 5679 * Sets a delegate for implementing accessibility support via composition as 5680 * opposed to inheritance. The delegate's primary use is for implementing 5681 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5682 * 5683 * @param delegate The delegate instance. 5684 * 5685 * @see AccessibilityDelegate 5686 */ 5687 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5688 mAccessibilityDelegate = delegate; 5689 } 5690 5691 /** 5692 * Gets the provider for managing a virtual view hierarchy rooted at this View 5693 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5694 * that explore the window content. 5695 * <p> 5696 * If this method returns an instance, this instance is responsible for managing 5697 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5698 * View including the one representing the View itself. Similarly the returned 5699 * instance is responsible for performing accessibility actions on any virtual 5700 * view or the root view itself. 5701 * </p> 5702 * <p> 5703 * If an {@link AccessibilityDelegate} has been specified via calling 5704 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5705 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5706 * is responsible for handling this call. 5707 * </p> 5708 * 5709 * @return The provider. 5710 * 5711 * @see AccessibilityNodeProvider 5712 */ 5713 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5714 if (mAccessibilityDelegate != null) { 5715 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5716 } else { 5717 return null; 5718 } 5719 } 5720 5721 /** 5722 * Gets the unique identifier of this view on the screen for accessibility purposes. 5723 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5724 * 5725 * @return The view accessibility id. 5726 * 5727 * @hide 5728 */ 5729 public int getAccessibilityViewId() { 5730 if (mAccessibilityViewId == NO_ID) { 5731 mAccessibilityViewId = sNextAccessibilityViewId++; 5732 } 5733 return mAccessibilityViewId; 5734 } 5735 5736 /** 5737 * Gets the unique identifier of the window in which this View reseides. 5738 * 5739 * @return The window accessibility id. 5740 * 5741 * @hide 5742 */ 5743 public int getAccessibilityWindowId() { 5744 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5745 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5746 } 5747 5748 /** 5749 * Gets the {@link View} description. It briefly describes the view and is 5750 * primarily used for accessibility support. Set this property to enable 5751 * better accessibility support for your application. This is especially 5752 * true for views that do not have textual representation (For example, 5753 * ImageButton). 5754 * 5755 * @return The content description. 5756 * 5757 * @attr ref android.R.styleable#View_contentDescription 5758 */ 5759 @ViewDebug.ExportedProperty(category = "accessibility") 5760 public CharSequence getContentDescription() { 5761 return mContentDescription; 5762 } 5763 5764 /** 5765 * Sets the {@link View} description. It briefly describes the view and is 5766 * primarily used for accessibility support. Set this property to enable 5767 * better accessibility support for your application. This is especially 5768 * true for views that do not have textual representation (For example, 5769 * ImageButton). 5770 * 5771 * @param contentDescription The content description. 5772 * 5773 * @attr ref android.R.styleable#View_contentDescription 5774 */ 5775 @RemotableViewMethod 5776 public void setContentDescription(CharSequence contentDescription) { 5777 if (mContentDescription == null) { 5778 if (contentDescription == null) { 5779 return; 5780 } 5781 } else if (mContentDescription.equals(contentDescription)) { 5782 return; 5783 } 5784 mContentDescription = contentDescription; 5785 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5786 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5787 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5788 notifySubtreeAccessibilityStateChangedIfNeeded(); 5789 } else { 5790 notifyViewAccessibilityStateChangedIfNeeded( 5791 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5792 } 5793 } 5794 5795 /** 5796 * Gets the id of a view for which this view serves as a label for 5797 * accessibility purposes. 5798 * 5799 * @return The labeled view id. 5800 */ 5801 @ViewDebug.ExportedProperty(category = "accessibility") 5802 public int getLabelFor() { 5803 return mLabelForId; 5804 } 5805 5806 /** 5807 * Sets the id of a view for which this view serves as a label for 5808 * accessibility purposes. 5809 * 5810 * @param id The labeled view id. 5811 */ 5812 @RemotableViewMethod 5813 public void setLabelFor(int id) { 5814 mLabelForId = id; 5815 if (mLabelForId != View.NO_ID 5816 && mID == View.NO_ID) { 5817 mID = generateViewId(); 5818 } 5819 } 5820 5821 /** 5822 * Invoked whenever this view loses focus, either by losing window focus or by losing 5823 * focus within its window. This method can be used to clear any state tied to the 5824 * focus. For instance, if a button is held pressed with the trackball and the window 5825 * loses focus, this method can be used to cancel the press. 5826 * 5827 * Subclasses of View overriding this method should always call super.onFocusLost(). 5828 * 5829 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5830 * @see #onWindowFocusChanged(boolean) 5831 * 5832 * @hide pending API council approval 5833 */ 5834 protected void onFocusLost() { 5835 resetPressedState(); 5836 } 5837 5838 private void resetPressedState() { 5839 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5840 return; 5841 } 5842 5843 if (isPressed()) { 5844 setPressed(false); 5845 5846 if (!mHasPerformedLongPress) { 5847 removeLongPressCallback(); 5848 } 5849 } 5850 } 5851 5852 /** 5853 * Returns true if this view has focus 5854 * 5855 * @return True if this view has focus, false otherwise. 5856 */ 5857 @ViewDebug.ExportedProperty(category = "focus") 5858 public boolean isFocused() { 5859 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5860 } 5861 5862 /** 5863 * Find the view in the hierarchy rooted at this view that currently has 5864 * focus. 5865 * 5866 * @return The view that currently has focus, or null if no focused view can 5867 * be found. 5868 */ 5869 public View findFocus() { 5870 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5871 } 5872 5873 /** 5874 * Indicates whether this view is one of the set of scrollable containers in 5875 * its window. 5876 * 5877 * @return whether this view is one of the set of scrollable containers in 5878 * its window 5879 * 5880 * @attr ref android.R.styleable#View_isScrollContainer 5881 */ 5882 public boolean isScrollContainer() { 5883 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5884 } 5885 5886 /** 5887 * Change whether this view is one of the set of scrollable containers in 5888 * its window. This will be used to determine whether the window can 5889 * resize or must pan when a soft input area is open -- scrollable 5890 * containers allow the window to use resize mode since the container 5891 * will appropriately shrink. 5892 * 5893 * @attr ref android.R.styleable#View_isScrollContainer 5894 */ 5895 public void setScrollContainer(boolean isScrollContainer) { 5896 if (isScrollContainer) { 5897 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5898 mAttachInfo.mScrollContainers.add(this); 5899 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5900 } 5901 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5902 } else { 5903 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5904 mAttachInfo.mScrollContainers.remove(this); 5905 } 5906 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5907 } 5908 } 5909 5910 /** 5911 * Returns the quality of the drawing cache. 5912 * 5913 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5914 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5915 * 5916 * @see #setDrawingCacheQuality(int) 5917 * @see #setDrawingCacheEnabled(boolean) 5918 * @see #isDrawingCacheEnabled() 5919 * 5920 * @attr ref android.R.styleable#View_drawingCacheQuality 5921 */ 5922 @DrawingCacheQuality 5923 public int getDrawingCacheQuality() { 5924 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5925 } 5926 5927 /** 5928 * Set the drawing cache quality of this view. This value is used only when the 5929 * drawing cache is enabled 5930 * 5931 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5932 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5933 * 5934 * @see #getDrawingCacheQuality() 5935 * @see #setDrawingCacheEnabled(boolean) 5936 * @see #isDrawingCacheEnabled() 5937 * 5938 * @attr ref android.R.styleable#View_drawingCacheQuality 5939 */ 5940 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5941 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5942 } 5943 5944 /** 5945 * Returns whether the screen should remain on, corresponding to the current 5946 * value of {@link #KEEP_SCREEN_ON}. 5947 * 5948 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5949 * 5950 * @see #setKeepScreenOn(boolean) 5951 * 5952 * @attr ref android.R.styleable#View_keepScreenOn 5953 */ 5954 public boolean getKeepScreenOn() { 5955 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5956 } 5957 5958 /** 5959 * Controls whether the screen should remain on, modifying the 5960 * value of {@link #KEEP_SCREEN_ON}. 5961 * 5962 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5963 * 5964 * @see #getKeepScreenOn() 5965 * 5966 * @attr ref android.R.styleable#View_keepScreenOn 5967 */ 5968 public void setKeepScreenOn(boolean keepScreenOn) { 5969 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5970 } 5971 5972 /** 5973 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5974 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5975 * 5976 * @attr ref android.R.styleable#View_nextFocusLeft 5977 */ 5978 public int getNextFocusLeftId() { 5979 return mNextFocusLeftId; 5980 } 5981 5982 /** 5983 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5984 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5985 * decide automatically. 5986 * 5987 * @attr ref android.R.styleable#View_nextFocusLeft 5988 */ 5989 public void setNextFocusLeftId(int nextFocusLeftId) { 5990 mNextFocusLeftId = nextFocusLeftId; 5991 } 5992 5993 /** 5994 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5995 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5996 * 5997 * @attr ref android.R.styleable#View_nextFocusRight 5998 */ 5999 public int getNextFocusRightId() { 6000 return mNextFocusRightId; 6001 } 6002 6003 /** 6004 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6005 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 6006 * decide automatically. 6007 * 6008 * @attr ref android.R.styleable#View_nextFocusRight 6009 */ 6010 public void setNextFocusRightId(int nextFocusRightId) { 6011 mNextFocusRightId = nextFocusRightId; 6012 } 6013 6014 /** 6015 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6016 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6017 * 6018 * @attr ref android.R.styleable#View_nextFocusUp 6019 */ 6020 public int getNextFocusUpId() { 6021 return mNextFocusUpId; 6022 } 6023 6024 /** 6025 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6026 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6027 * decide automatically. 6028 * 6029 * @attr ref android.R.styleable#View_nextFocusUp 6030 */ 6031 public void setNextFocusUpId(int nextFocusUpId) { 6032 mNextFocusUpId = nextFocusUpId; 6033 } 6034 6035 /** 6036 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6037 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6038 * 6039 * @attr ref android.R.styleable#View_nextFocusDown 6040 */ 6041 public int getNextFocusDownId() { 6042 return mNextFocusDownId; 6043 } 6044 6045 /** 6046 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6047 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6048 * decide automatically. 6049 * 6050 * @attr ref android.R.styleable#View_nextFocusDown 6051 */ 6052 public void setNextFocusDownId(int nextFocusDownId) { 6053 mNextFocusDownId = nextFocusDownId; 6054 } 6055 6056 /** 6057 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6058 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6059 * 6060 * @attr ref android.R.styleable#View_nextFocusForward 6061 */ 6062 public int getNextFocusForwardId() { 6063 return mNextFocusForwardId; 6064 } 6065 6066 /** 6067 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6068 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6069 * decide automatically. 6070 * 6071 * @attr ref android.R.styleable#View_nextFocusForward 6072 */ 6073 public void setNextFocusForwardId(int nextFocusForwardId) { 6074 mNextFocusForwardId = nextFocusForwardId; 6075 } 6076 6077 /** 6078 * Returns the visibility of this view and all of its ancestors 6079 * 6080 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6081 */ 6082 public boolean isShown() { 6083 View current = this; 6084 //noinspection ConstantConditions 6085 do { 6086 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6087 return false; 6088 } 6089 ViewParent parent = current.mParent; 6090 if (parent == null) { 6091 return false; // We are not attached to the view root 6092 } 6093 if (!(parent instanceof View)) { 6094 return true; 6095 } 6096 current = (View) parent; 6097 } while (current != null); 6098 6099 return false; 6100 } 6101 6102 /** 6103 * Called by the view hierarchy when the content insets for a window have 6104 * changed, to allow it to adjust its content to fit within those windows. 6105 * The content insets tell you the space that the status bar, input method, 6106 * and other system windows infringe on the application's window. 6107 * 6108 * <p>You do not normally need to deal with this function, since the default 6109 * window decoration given to applications takes care of applying it to the 6110 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6111 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6112 * and your content can be placed under those system elements. You can then 6113 * use this method within your view hierarchy if you have parts of your UI 6114 * which you would like to ensure are not being covered. 6115 * 6116 * <p>The default implementation of this method simply applies the content 6117 * insets to the view's padding, consuming that content (modifying the 6118 * insets to be 0), and returning true. This behavior is off by default, but can 6119 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6120 * 6121 * <p>This function's traversal down the hierarchy is depth-first. The same content 6122 * insets object is propagated down the hierarchy, so any changes made to it will 6123 * be seen by all following views (including potentially ones above in 6124 * the hierarchy since this is a depth-first traversal). The first view 6125 * that returns true will abort the entire traversal. 6126 * 6127 * <p>The default implementation works well for a situation where it is 6128 * used with a container that covers the entire window, allowing it to 6129 * apply the appropriate insets to its content on all edges. If you need 6130 * a more complicated layout (such as two different views fitting system 6131 * windows, one on the top of the window, and one on the bottom), 6132 * you can override the method and handle the insets however you would like. 6133 * Note that the insets provided by the framework are always relative to the 6134 * far edges of the window, not accounting for the location of the called view 6135 * within that window. (In fact when this method is called you do not yet know 6136 * where the layout will place the view, as it is done before layout happens.) 6137 * 6138 * <p>Note: unlike many View methods, there is no dispatch phase to this 6139 * call. If you are overriding it in a ViewGroup and want to allow the 6140 * call to continue to your children, you must be sure to call the super 6141 * implementation. 6142 * 6143 * <p>Here is a sample layout that makes use of fitting system windows 6144 * to have controls for a video view placed inside of the window decorations 6145 * that it hides and shows. This can be used with code like the second 6146 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6147 * 6148 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6149 * 6150 * @param insets Current content insets of the window. Prior to 6151 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6152 * the insets or else you and Android will be unhappy. 6153 * 6154 * @return {@code true} if this view applied the insets and it should not 6155 * continue propagating further down the hierarchy, {@code false} otherwise. 6156 * @see #getFitsSystemWindows() 6157 * @see #setFitsSystemWindows(boolean) 6158 * @see #setSystemUiVisibility(int) 6159 * 6160 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6161 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6162 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6163 * to implement handling their own insets. 6164 */ 6165 protected boolean fitSystemWindows(Rect insets) { 6166 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6167 if (insets == null) { 6168 // Null insets by definition have already been consumed. 6169 // This call cannot apply insets since there are none to apply, 6170 // so return false. 6171 return false; 6172 } 6173 // If we're not in the process of dispatching the newer apply insets call, 6174 // that means we're not in the compatibility path. Dispatch into the newer 6175 // apply insets path and take things from there. 6176 try { 6177 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6178 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 6179 } finally { 6180 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6181 } 6182 } else { 6183 // We're being called from the newer apply insets path. 6184 // Perform the standard fallback behavior. 6185 return fitSystemWindowsInt(insets); 6186 } 6187 } 6188 6189 private boolean fitSystemWindowsInt(Rect insets) { 6190 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6191 mUserPaddingStart = UNDEFINED_PADDING; 6192 mUserPaddingEnd = UNDEFINED_PADDING; 6193 Rect localInsets = sThreadLocal.get(); 6194 if (localInsets == null) { 6195 localInsets = new Rect(); 6196 sThreadLocal.set(localInsets); 6197 } 6198 boolean res = computeFitSystemWindows(insets, localInsets); 6199 mUserPaddingLeftInitial = localInsets.left; 6200 mUserPaddingRightInitial = localInsets.right; 6201 internalSetPadding(localInsets.left, localInsets.top, 6202 localInsets.right, localInsets.bottom); 6203 return res; 6204 } 6205 return false; 6206 } 6207 6208 /** 6209 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6210 * 6211 * <p>This method should be overridden by views that wish to apply a policy different from or 6212 * in addition to the default behavior. Clients that wish to force a view subtree 6213 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6214 * 6215 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6216 * it will be called during dispatch instead of this method. The listener may optionally 6217 * call this method from its own implementation if it wishes to apply the view's default 6218 * insets policy in addition to its own.</p> 6219 * 6220 * <p>Implementations of this method should either return the insets parameter unchanged 6221 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6222 * that this view applied itself. This allows new inset types added in future platform 6223 * versions to pass through existing implementations unchanged without being erroneously 6224 * consumed.</p> 6225 * 6226 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6227 * property is set then the view will consume the system window insets and apply them 6228 * as padding for the view.</p> 6229 * 6230 * @param insets Insets to apply 6231 * @return The supplied insets with any applied insets consumed 6232 */ 6233 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6234 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6235 // We weren't called from within a direct call to fitSystemWindows, 6236 // call into it as a fallback in case we're in a class that overrides it 6237 // and has logic to perform. 6238 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6239 return insets.consumeSystemWindowInsets(); 6240 } 6241 } else { 6242 // We were called from within a direct call to fitSystemWindows. 6243 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6244 return insets.consumeSystemWindowInsets(); 6245 } 6246 } 6247 return insets; 6248 } 6249 6250 /** 6251 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6252 * window insets to this view. The listener's 6253 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6254 * method will be called instead of the view's 6255 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6256 * 6257 * @param listener Listener to set 6258 * 6259 * @see #onApplyWindowInsets(WindowInsets) 6260 */ 6261 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6262 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6263 } 6264 6265 /** 6266 * Request to apply the given window insets to this view or another view in its subtree. 6267 * 6268 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6269 * obscured by window decorations or overlays. This can include the status and navigation bars, 6270 * action bars, input methods and more. New inset categories may be added in the future. 6271 * The method returns the insets provided minus any that were applied by this view or its 6272 * children.</p> 6273 * 6274 * <p>Clients wishing to provide custom behavior should override the 6275 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6276 * {@link OnApplyWindowInsetsListener} via the 6277 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6278 * method.</p> 6279 * 6280 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6281 * </p> 6282 * 6283 * @param insets Insets to apply 6284 * @return The provided insets minus the insets that were consumed 6285 */ 6286 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6287 try { 6288 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6289 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6290 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6291 } else { 6292 return onApplyWindowInsets(insets); 6293 } 6294 } finally { 6295 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6296 } 6297 } 6298 6299 /** 6300 * @hide Compute the insets that should be consumed by this view and the ones 6301 * that should propagate to those under it. 6302 */ 6303 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6304 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6305 || mAttachInfo == null 6306 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6307 && !mAttachInfo.mOverscanRequested)) { 6308 outLocalInsets.set(inoutInsets); 6309 inoutInsets.set(0, 0, 0, 0); 6310 return true; 6311 } else { 6312 // The application wants to take care of fitting system window for 6313 // the content... however we still need to take care of any overscan here. 6314 final Rect overscan = mAttachInfo.mOverscanInsets; 6315 outLocalInsets.set(overscan); 6316 inoutInsets.left -= overscan.left; 6317 inoutInsets.top -= overscan.top; 6318 inoutInsets.right -= overscan.right; 6319 inoutInsets.bottom -= overscan.bottom; 6320 return false; 6321 } 6322 } 6323 6324 /** 6325 * Sets whether or not this view should account for system screen decorations 6326 * such as the status bar and inset its content; that is, controlling whether 6327 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6328 * executed. See that method for more details. 6329 * 6330 * <p>Note that if you are providing your own implementation of 6331 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6332 * flag to true -- your implementation will be overriding the default 6333 * implementation that checks this flag. 6334 * 6335 * @param fitSystemWindows If true, then the default implementation of 6336 * {@link #fitSystemWindows(Rect)} will be executed. 6337 * 6338 * @attr ref android.R.styleable#View_fitsSystemWindows 6339 * @see #getFitsSystemWindows() 6340 * @see #fitSystemWindows(Rect) 6341 * @see #setSystemUiVisibility(int) 6342 */ 6343 public void setFitsSystemWindows(boolean fitSystemWindows) { 6344 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6345 } 6346 6347 /** 6348 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6349 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6350 * will be executed. 6351 * 6352 * @return {@code true} if the default implementation of 6353 * {@link #fitSystemWindows(Rect)} will be executed. 6354 * 6355 * @attr ref android.R.styleable#View_fitsSystemWindows 6356 * @see #setFitsSystemWindows(boolean) 6357 * @see #fitSystemWindows(Rect) 6358 * @see #setSystemUiVisibility(int) 6359 */ 6360 public boolean getFitsSystemWindows() { 6361 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6362 } 6363 6364 /** @hide */ 6365 public boolean fitsSystemWindows() { 6366 return getFitsSystemWindows(); 6367 } 6368 6369 /** 6370 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6371 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6372 */ 6373 public void requestFitSystemWindows() { 6374 if (mParent != null) { 6375 mParent.requestFitSystemWindows(); 6376 } 6377 } 6378 6379 /** 6380 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6381 */ 6382 public void requestApplyInsets() { 6383 requestFitSystemWindows(); 6384 } 6385 6386 /** 6387 * For use by PhoneWindow to make its own system window fitting optional. 6388 * @hide 6389 */ 6390 public void makeOptionalFitsSystemWindows() { 6391 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6392 } 6393 6394 /** 6395 * Returns the visibility status for this view. 6396 * 6397 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6398 * @attr ref android.R.styleable#View_visibility 6399 */ 6400 @ViewDebug.ExportedProperty(mapping = { 6401 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6402 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6403 @ViewDebug.IntToString(from = GONE, to = "GONE") 6404 }) 6405 @Visibility 6406 public int getVisibility() { 6407 return mViewFlags & VISIBILITY_MASK; 6408 } 6409 6410 /** 6411 * Set the enabled state of this view. 6412 * 6413 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6414 * @attr ref android.R.styleable#View_visibility 6415 */ 6416 @RemotableViewMethod 6417 public void setVisibility(@Visibility int visibility) { 6418 setFlags(visibility, VISIBILITY_MASK); 6419 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6420 } 6421 6422 /** 6423 * Returns the enabled status for this view. The interpretation of the 6424 * enabled state varies by subclass. 6425 * 6426 * @return True if this view is enabled, false otherwise. 6427 */ 6428 @ViewDebug.ExportedProperty 6429 public boolean isEnabled() { 6430 return (mViewFlags & ENABLED_MASK) == ENABLED; 6431 } 6432 6433 /** 6434 * Set the enabled state of this view. The interpretation of the enabled 6435 * state varies by subclass. 6436 * 6437 * @param enabled True if this view is enabled, false otherwise. 6438 */ 6439 @RemotableViewMethod 6440 public void setEnabled(boolean enabled) { 6441 if (enabled == isEnabled()) return; 6442 6443 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6444 6445 /* 6446 * The View most likely has to change its appearance, so refresh 6447 * the drawable state. 6448 */ 6449 refreshDrawableState(); 6450 6451 // Invalidate too, since the default behavior for views is to be 6452 // be drawn at 50% alpha rather than to change the drawable. 6453 invalidate(true); 6454 6455 if (!enabled) { 6456 cancelPendingInputEvents(); 6457 } 6458 } 6459 6460 /** 6461 * Set whether this view can receive the focus. 6462 * 6463 * Setting this to false will also ensure that this view is not focusable 6464 * in touch mode. 6465 * 6466 * @param focusable If true, this view can receive the focus. 6467 * 6468 * @see #setFocusableInTouchMode(boolean) 6469 * @attr ref android.R.styleable#View_focusable 6470 */ 6471 public void setFocusable(boolean focusable) { 6472 if (!focusable) { 6473 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6474 } 6475 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6476 } 6477 6478 /** 6479 * Set whether this view can receive focus while in touch mode. 6480 * 6481 * Setting this to true will also ensure that this view is focusable. 6482 * 6483 * @param focusableInTouchMode If true, this view can receive the focus while 6484 * in touch mode. 6485 * 6486 * @see #setFocusable(boolean) 6487 * @attr ref android.R.styleable#View_focusableInTouchMode 6488 */ 6489 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6490 // Focusable in touch mode should always be set before the focusable flag 6491 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6492 // which, in touch mode, will not successfully request focus on this view 6493 // because the focusable in touch mode flag is not set 6494 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6495 if (focusableInTouchMode) { 6496 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6497 } 6498 } 6499 6500 /** 6501 * Set whether this view should have sound effects enabled for events such as 6502 * clicking and touching. 6503 * 6504 * <p>You may wish to disable sound effects for a view if you already play sounds, 6505 * for instance, a dial key that plays dtmf tones. 6506 * 6507 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6508 * @see #isSoundEffectsEnabled() 6509 * @see #playSoundEffect(int) 6510 * @attr ref android.R.styleable#View_soundEffectsEnabled 6511 */ 6512 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6513 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6514 } 6515 6516 /** 6517 * @return whether this view should have sound effects enabled for events such as 6518 * clicking and touching. 6519 * 6520 * @see #setSoundEffectsEnabled(boolean) 6521 * @see #playSoundEffect(int) 6522 * @attr ref android.R.styleable#View_soundEffectsEnabled 6523 */ 6524 @ViewDebug.ExportedProperty 6525 public boolean isSoundEffectsEnabled() { 6526 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6527 } 6528 6529 /** 6530 * Set whether this view should have haptic feedback for events such as 6531 * long presses. 6532 * 6533 * <p>You may wish to disable haptic feedback if your view already controls 6534 * its own haptic feedback. 6535 * 6536 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6537 * @see #isHapticFeedbackEnabled() 6538 * @see #performHapticFeedback(int) 6539 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6540 */ 6541 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6542 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6543 } 6544 6545 /** 6546 * @return whether this view should have haptic feedback enabled for events 6547 * long presses. 6548 * 6549 * @see #setHapticFeedbackEnabled(boolean) 6550 * @see #performHapticFeedback(int) 6551 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6552 */ 6553 @ViewDebug.ExportedProperty 6554 public boolean isHapticFeedbackEnabled() { 6555 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6556 } 6557 6558 /** 6559 * Returns the layout direction for this view. 6560 * 6561 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6562 * {@link #LAYOUT_DIRECTION_RTL}, 6563 * {@link #LAYOUT_DIRECTION_INHERIT} or 6564 * {@link #LAYOUT_DIRECTION_LOCALE}. 6565 * 6566 * @attr ref android.R.styleable#View_layoutDirection 6567 * 6568 * @hide 6569 */ 6570 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6571 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6572 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6573 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6574 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6575 }) 6576 @LayoutDir 6577 public int getRawLayoutDirection() { 6578 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6579 } 6580 6581 /** 6582 * Set the layout direction for this view. This will propagate a reset of layout direction 6583 * resolution to the view's children and resolve layout direction for this view. 6584 * 6585 * @param layoutDirection the layout direction to set. Should be one of: 6586 * 6587 * {@link #LAYOUT_DIRECTION_LTR}, 6588 * {@link #LAYOUT_DIRECTION_RTL}, 6589 * {@link #LAYOUT_DIRECTION_INHERIT}, 6590 * {@link #LAYOUT_DIRECTION_LOCALE}. 6591 * 6592 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6593 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6594 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6595 * 6596 * @attr ref android.R.styleable#View_layoutDirection 6597 */ 6598 @RemotableViewMethod 6599 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6600 if (getRawLayoutDirection() != layoutDirection) { 6601 // Reset the current layout direction and the resolved one 6602 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6603 resetRtlProperties(); 6604 // Set the new layout direction (filtered) 6605 mPrivateFlags2 |= 6606 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6607 // We need to resolve all RTL properties as they all depend on layout direction 6608 resolveRtlPropertiesIfNeeded(); 6609 requestLayout(); 6610 invalidate(true); 6611 } 6612 } 6613 6614 /** 6615 * Returns the resolved layout direction for this view. 6616 * 6617 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6618 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6619 * 6620 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6621 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6622 * 6623 * @attr ref android.R.styleable#View_layoutDirection 6624 */ 6625 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6626 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6627 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6628 }) 6629 @ResolvedLayoutDir 6630 public int getLayoutDirection() { 6631 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6632 if (targetSdkVersion < JELLY_BEAN_MR1) { 6633 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6634 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6635 } 6636 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6637 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6638 } 6639 6640 /** 6641 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6642 * layout attribute and/or the inherited value from the parent 6643 * 6644 * @return true if the layout is right-to-left. 6645 * 6646 * @hide 6647 */ 6648 @ViewDebug.ExportedProperty(category = "layout") 6649 public boolean isLayoutRtl() { 6650 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6651 } 6652 6653 /** 6654 * Indicates whether the view is currently tracking transient state that the 6655 * app should not need to concern itself with saving and restoring, but that 6656 * the framework should take special note to preserve when possible. 6657 * 6658 * <p>A view with transient state cannot be trivially rebound from an external 6659 * data source, such as an adapter binding item views in a list. This may be 6660 * because the view is performing an animation, tracking user selection 6661 * of content, or similar.</p> 6662 * 6663 * @return true if the view has transient state 6664 */ 6665 @ViewDebug.ExportedProperty(category = "layout") 6666 public boolean hasTransientState() { 6667 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6668 } 6669 6670 /** 6671 * Set whether this view is currently tracking transient state that the 6672 * framework should attempt to preserve when possible. This flag is reference counted, 6673 * so every call to setHasTransientState(true) should be paired with a later call 6674 * to setHasTransientState(false). 6675 * 6676 * <p>A view with transient state cannot be trivially rebound from an external 6677 * data source, such as an adapter binding item views in a list. This may be 6678 * because the view is performing an animation, tracking user selection 6679 * of content, or similar.</p> 6680 * 6681 * @param hasTransientState true if this view has transient state 6682 */ 6683 public void setHasTransientState(boolean hasTransientState) { 6684 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6685 mTransientStateCount - 1; 6686 if (mTransientStateCount < 0) { 6687 mTransientStateCount = 0; 6688 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6689 "unmatched pair of setHasTransientState calls"); 6690 } else if ((hasTransientState && mTransientStateCount == 1) || 6691 (!hasTransientState && mTransientStateCount == 0)) { 6692 // update flag if we've just incremented up from 0 or decremented down to 0 6693 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6694 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6695 if (mParent != null) { 6696 try { 6697 mParent.childHasTransientStateChanged(this, hasTransientState); 6698 } catch (AbstractMethodError e) { 6699 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6700 " does not fully implement ViewParent", e); 6701 } 6702 } 6703 } 6704 } 6705 6706 /** 6707 * Returns true if this view is currently attached to a window. 6708 */ 6709 public boolean isAttachedToWindow() { 6710 return mAttachInfo != null; 6711 } 6712 6713 /** 6714 * Returns true if this view has been through at least one layout since it 6715 * was last attached to or detached from a window. 6716 */ 6717 public boolean isLaidOut() { 6718 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6719 } 6720 6721 /** 6722 * If this view doesn't do any drawing on its own, set this flag to 6723 * allow further optimizations. By default, this flag is not set on 6724 * View, but could be set on some View subclasses such as ViewGroup. 6725 * 6726 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6727 * you should clear this flag. 6728 * 6729 * @param willNotDraw whether or not this View draw on its own 6730 */ 6731 public void setWillNotDraw(boolean willNotDraw) { 6732 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6733 } 6734 6735 /** 6736 * Returns whether or not this View draws on its own. 6737 * 6738 * @return true if this view has nothing to draw, false otherwise 6739 */ 6740 @ViewDebug.ExportedProperty(category = "drawing") 6741 public boolean willNotDraw() { 6742 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6743 } 6744 6745 /** 6746 * When a View's drawing cache is enabled, drawing is redirected to an 6747 * offscreen bitmap. Some views, like an ImageView, must be able to 6748 * bypass this mechanism if they already draw a single bitmap, to avoid 6749 * unnecessary usage of the memory. 6750 * 6751 * @param willNotCacheDrawing true if this view does not cache its 6752 * drawing, false otherwise 6753 */ 6754 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6755 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6756 } 6757 6758 /** 6759 * Returns whether or not this View can cache its drawing or not. 6760 * 6761 * @return true if this view does not cache its drawing, false otherwise 6762 */ 6763 @ViewDebug.ExportedProperty(category = "drawing") 6764 public boolean willNotCacheDrawing() { 6765 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6766 } 6767 6768 /** 6769 * Indicates whether this view reacts to click events or not. 6770 * 6771 * @return true if the view is clickable, false otherwise 6772 * 6773 * @see #setClickable(boolean) 6774 * @attr ref android.R.styleable#View_clickable 6775 */ 6776 @ViewDebug.ExportedProperty 6777 public boolean isClickable() { 6778 return (mViewFlags & CLICKABLE) == CLICKABLE; 6779 } 6780 6781 /** 6782 * Enables or disables click events for this view. When a view 6783 * is clickable it will change its state to "pressed" on every click. 6784 * Subclasses should set the view clickable to visually react to 6785 * user's clicks. 6786 * 6787 * @param clickable true to make the view clickable, false otherwise 6788 * 6789 * @see #isClickable() 6790 * @attr ref android.R.styleable#View_clickable 6791 */ 6792 public void setClickable(boolean clickable) { 6793 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6794 } 6795 6796 /** 6797 * Indicates whether this view reacts to long click events or not. 6798 * 6799 * @return true if the view is long clickable, false otherwise 6800 * 6801 * @see #setLongClickable(boolean) 6802 * @attr ref android.R.styleable#View_longClickable 6803 */ 6804 public boolean isLongClickable() { 6805 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6806 } 6807 6808 /** 6809 * Enables or disables long click events for this view. When a view is long 6810 * clickable it reacts to the user holding down the button for a longer 6811 * duration than a tap. This event can either launch the listener or a 6812 * context menu. 6813 * 6814 * @param longClickable true to make the view long clickable, false otherwise 6815 * @see #isLongClickable() 6816 * @attr ref android.R.styleable#View_longClickable 6817 */ 6818 public void setLongClickable(boolean longClickable) { 6819 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6820 } 6821 6822 /** 6823 * Sets the pressed state for this view and provides a touch coordinate for 6824 * animation hinting. 6825 * 6826 * @param pressed Pass true to set the View's internal state to "pressed", 6827 * or false to reverts the View's internal state from a 6828 * previously set "pressed" state. 6829 * @param x The x coordinate of the touch that caused the press 6830 * @param y The y coordinate of the touch that caused the press 6831 */ 6832 private void setPressed(boolean pressed, float x, float y) { 6833 if (pressed) { 6834 drawableHotspotChanged(x, y); 6835 } 6836 6837 setPressed(pressed); 6838 } 6839 6840 /** 6841 * Sets the pressed state for this view. 6842 * 6843 * @see #isClickable() 6844 * @see #setClickable(boolean) 6845 * 6846 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6847 * the View's internal state from a previously set "pressed" state. 6848 */ 6849 public void setPressed(boolean pressed) { 6850 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6851 6852 if (pressed) { 6853 mPrivateFlags |= PFLAG_PRESSED; 6854 } else { 6855 mPrivateFlags &= ~PFLAG_PRESSED; 6856 } 6857 6858 if (needsRefresh) { 6859 refreshDrawableState(); 6860 } 6861 dispatchSetPressed(pressed); 6862 } 6863 6864 /** 6865 * Dispatch setPressed to all of this View's children. 6866 * 6867 * @see #setPressed(boolean) 6868 * 6869 * @param pressed The new pressed state 6870 */ 6871 protected void dispatchSetPressed(boolean pressed) { 6872 } 6873 6874 /** 6875 * Indicates whether the view is currently in pressed state. Unless 6876 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6877 * the pressed state. 6878 * 6879 * @see #setPressed(boolean) 6880 * @see #isClickable() 6881 * @see #setClickable(boolean) 6882 * 6883 * @return true if the view is currently pressed, false otherwise 6884 */ 6885 public boolean isPressed() { 6886 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6887 } 6888 6889 /** 6890 * Indicates whether this view will save its state (that is, 6891 * whether its {@link #onSaveInstanceState} method will be called). 6892 * 6893 * @return Returns true if the view state saving is enabled, else false. 6894 * 6895 * @see #setSaveEnabled(boolean) 6896 * @attr ref android.R.styleable#View_saveEnabled 6897 */ 6898 public boolean isSaveEnabled() { 6899 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6900 } 6901 6902 /** 6903 * Controls whether the saving of this view's state is 6904 * enabled (that is, whether its {@link #onSaveInstanceState} method 6905 * will be called). Note that even if freezing is enabled, the 6906 * view still must have an id assigned to it (via {@link #setId(int)}) 6907 * for its state to be saved. This flag can only disable the 6908 * saving of this view; any child views may still have their state saved. 6909 * 6910 * @param enabled Set to false to <em>disable</em> state saving, or true 6911 * (the default) to allow it. 6912 * 6913 * @see #isSaveEnabled() 6914 * @see #setId(int) 6915 * @see #onSaveInstanceState() 6916 * @attr ref android.R.styleable#View_saveEnabled 6917 */ 6918 public void setSaveEnabled(boolean enabled) { 6919 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6920 } 6921 6922 /** 6923 * Gets whether the framework should discard touches when the view's 6924 * window is obscured by another visible window. 6925 * Refer to the {@link View} security documentation for more details. 6926 * 6927 * @return True if touch filtering is enabled. 6928 * 6929 * @see #setFilterTouchesWhenObscured(boolean) 6930 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6931 */ 6932 @ViewDebug.ExportedProperty 6933 public boolean getFilterTouchesWhenObscured() { 6934 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6935 } 6936 6937 /** 6938 * Sets whether the framework should discard touches when the view's 6939 * window is obscured by another visible window. 6940 * Refer to the {@link View} security documentation for more details. 6941 * 6942 * @param enabled True if touch filtering should be enabled. 6943 * 6944 * @see #getFilterTouchesWhenObscured 6945 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6946 */ 6947 public void setFilterTouchesWhenObscured(boolean enabled) { 6948 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 6949 FILTER_TOUCHES_WHEN_OBSCURED); 6950 } 6951 6952 /** 6953 * Indicates whether the entire hierarchy under this view will save its 6954 * state when a state saving traversal occurs from its parent. The default 6955 * is true; if false, these views will not be saved unless 6956 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6957 * 6958 * @return Returns true if the view state saving from parent is enabled, else false. 6959 * 6960 * @see #setSaveFromParentEnabled(boolean) 6961 */ 6962 public boolean isSaveFromParentEnabled() { 6963 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6964 } 6965 6966 /** 6967 * Controls whether the entire hierarchy under this view will save its 6968 * state when a state saving traversal occurs from its parent. The default 6969 * is true; if false, these views will not be saved unless 6970 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6971 * 6972 * @param enabled Set to false to <em>disable</em> state saving, or true 6973 * (the default) to allow it. 6974 * 6975 * @see #isSaveFromParentEnabled() 6976 * @see #setId(int) 6977 * @see #onSaveInstanceState() 6978 */ 6979 public void setSaveFromParentEnabled(boolean enabled) { 6980 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6981 } 6982 6983 6984 /** 6985 * Returns whether this View is able to take focus. 6986 * 6987 * @return True if this view can take focus, or false otherwise. 6988 * @attr ref android.R.styleable#View_focusable 6989 */ 6990 @ViewDebug.ExportedProperty(category = "focus") 6991 public final boolean isFocusable() { 6992 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6993 } 6994 6995 /** 6996 * When a view is focusable, it may not want to take focus when in touch mode. 6997 * For example, a button would like focus when the user is navigating via a D-pad 6998 * so that the user can click on it, but once the user starts touching the screen, 6999 * the button shouldn't take focus 7000 * @return Whether the view is focusable in touch mode. 7001 * @attr ref android.R.styleable#View_focusableInTouchMode 7002 */ 7003 @ViewDebug.ExportedProperty 7004 public final boolean isFocusableInTouchMode() { 7005 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 7006 } 7007 7008 /** 7009 * Find the nearest view in the specified direction that can take focus. 7010 * This does not actually give focus to that view. 7011 * 7012 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7013 * 7014 * @return The nearest focusable in the specified direction, or null if none 7015 * can be found. 7016 */ 7017 public View focusSearch(@FocusRealDirection int direction) { 7018 if (mParent != null) { 7019 return mParent.focusSearch(this, direction); 7020 } else { 7021 return null; 7022 } 7023 } 7024 7025 /** 7026 * This method is the last chance for the focused view and its ancestors to 7027 * respond to an arrow key. This is called when the focused view did not 7028 * consume the key internally, nor could the view system find a new view in 7029 * the requested direction to give focus to. 7030 * 7031 * @param focused The currently focused view. 7032 * @param direction The direction focus wants to move. One of FOCUS_UP, 7033 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 7034 * @return True if the this view consumed this unhandled move. 7035 */ 7036 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 7037 return false; 7038 } 7039 7040 /** 7041 * If a user manually specified the next view id for a particular direction, 7042 * use the root to look up the view. 7043 * @param root The root view of the hierarchy containing this view. 7044 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 7045 * or FOCUS_BACKWARD. 7046 * @return The user specified next view, or null if there is none. 7047 */ 7048 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7049 switch (direction) { 7050 case FOCUS_LEFT: 7051 if (mNextFocusLeftId == View.NO_ID) return null; 7052 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7053 case FOCUS_RIGHT: 7054 if (mNextFocusRightId == View.NO_ID) return null; 7055 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7056 case FOCUS_UP: 7057 if (mNextFocusUpId == View.NO_ID) return null; 7058 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7059 case FOCUS_DOWN: 7060 if (mNextFocusDownId == View.NO_ID) return null; 7061 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7062 case FOCUS_FORWARD: 7063 if (mNextFocusForwardId == View.NO_ID) return null; 7064 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7065 case FOCUS_BACKWARD: { 7066 if (mID == View.NO_ID) return null; 7067 final int id = mID; 7068 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7069 @Override 7070 public boolean apply(View t) { 7071 return t.mNextFocusForwardId == id; 7072 } 7073 }); 7074 } 7075 } 7076 return null; 7077 } 7078 7079 private View findViewInsideOutShouldExist(View root, int id) { 7080 if (mMatchIdPredicate == null) { 7081 mMatchIdPredicate = new MatchIdPredicate(); 7082 } 7083 mMatchIdPredicate.mId = id; 7084 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7085 if (result == null) { 7086 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7087 } 7088 return result; 7089 } 7090 7091 /** 7092 * Find and return all focusable views that are descendants of this view, 7093 * possibly including this view if it is focusable itself. 7094 * 7095 * @param direction The direction of the focus 7096 * @return A list of focusable views 7097 */ 7098 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7099 ArrayList<View> result = new ArrayList<View>(24); 7100 addFocusables(result, direction); 7101 return result; 7102 } 7103 7104 /** 7105 * Add any focusable views that are descendants of this view (possibly 7106 * including this view if it is focusable itself) to views. If we are in touch mode, 7107 * only add views that are also focusable in touch mode. 7108 * 7109 * @param views Focusable views found so far 7110 * @param direction The direction of the focus 7111 */ 7112 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7113 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7114 } 7115 7116 /** 7117 * Adds any focusable views that are descendants of this view (possibly 7118 * including this view if it is focusable itself) to views. This method 7119 * adds all focusable views regardless if we are in touch mode or 7120 * only views focusable in touch mode if we are in touch mode or 7121 * only views that can take accessibility focus if accessibility is enabeld 7122 * depending on the focusable mode paramater. 7123 * 7124 * @param views Focusable views found so far or null if all we are interested is 7125 * the number of focusables. 7126 * @param direction The direction of the focus. 7127 * @param focusableMode The type of focusables to be added. 7128 * 7129 * @see #FOCUSABLES_ALL 7130 * @see #FOCUSABLES_TOUCH_MODE 7131 */ 7132 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7133 @FocusableMode int focusableMode) { 7134 if (views == null) { 7135 return; 7136 } 7137 if (!isFocusable()) { 7138 return; 7139 } 7140 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7141 && isInTouchMode() && !isFocusableInTouchMode()) { 7142 return; 7143 } 7144 views.add(this); 7145 } 7146 7147 /** 7148 * Finds the Views that contain given text. The containment is case insensitive. 7149 * The search is performed by either the text that the View renders or the content 7150 * description that describes the view for accessibility purposes and the view does 7151 * not render or both. Clients can specify how the search is to be performed via 7152 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7153 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7154 * 7155 * @param outViews The output list of matching Views. 7156 * @param searched The text to match against. 7157 * 7158 * @see #FIND_VIEWS_WITH_TEXT 7159 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7160 * @see #setContentDescription(CharSequence) 7161 */ 7162 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7163 @FindViewFlags int flags) { 7164 if (getAccessibilityNodeProvider() != null) { 7165 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7166 outViews.add(this); 7167 } 7168 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7169 && (searched != null && searched.length() > 0) 7170 && (mContentDescription != null && mContentDescription.length() > 0)) { 7171 String searchedLowerCase = searched.toString().toLowerCase(); 7172 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7173 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7174 outViews.add(this); 7175 } 7176 } 7177 } 7178 7179 /** 7180 * Find and return all touchable views that are descendants of this view, 7181 * possibly including this view if it is touchable itself. 7182 * 7183 * @return A list of touchable views 7184 */ 7185 public ArrayList<View> getTouchables() { 7186 ArrayList<View> result = new ArrayList<View>(); 7187 addTouchables(result); 7188 return result; 7189 } 7190 7191 /** 7192 * Add any touchable views that are descendants of this view (possibly 7193 * including this view if it is touchable itself) to views. 7194 * 7195 * @param views Touchable views found so far 7196 */ 7197 public void addTouchables(ArrayList<View> views) { 7198 final int viewFlags = mViewFlags; 7199 7200 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7201 && (viewFlags & ENABLED_MASK) == ENABLED) { 7202 views.add(this); 7203 } 7204 } 7205 7206 /** 7207 * Returns whether this View is accessibility focused. 7208 * 7209 * @return True if this View is accessibility focused. 7210 */ 7211 public boolean isAccessibilityFocused() { 7212 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7213 } 7214 7215 /** 7216 * Call this to try to give accessibility focus to this view. 7217 * 7218 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7219 * returns false or the view is no visible or the view already has accessibility 7220 * focus. 7221 * 7222 * See also {@link #focusSearch(int)}, which is what you call to say that you 7223 * have focus, and you want your parent to look for the next one. 7224 * 7225 * @return Whether this view actually took accessibility focus. 7226 * 7227 * @hide 7228 */ 7229 public boolean requestAccessibilityFocus() { 7230 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7231 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7232 return false; 7233 } 7234 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7235 return false; 7236 } 7237 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7238 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7239 ViewRootImpl viewRootImpl = getViewRootImpl(); 7240 if (viewRootImpl != null) { 7241 viewRootImpl.setAccessibilityFocus(this, null); 7242 } 7243 invalidate(); 7244 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7245 return true; 7246 } 7247 return false; 7248 } 7249 7250 /** 7251 * Call this to try to clear accessibility focus of this view. 7252 * 7253 * See also {@link #focusSearch(int)}, which is what you call to say that you 7254 * have focus, and you want your parent to look for the next one. 7255 * 7256 * @hide 7257 */ 7258 public void clearAccessibilityFocus() { 7259 clearAccessibilityFocusNoCallbacks(); 7260 // Clear the global reference of accessibility focus if this 7261 // view or any of its descendants had accessibility focus. 7262 ViewRootImpl viewRootImpl = getViewRootImpl(); 7263 if (viewRootImpl != null) { 7264 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7265 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7266 viewRootImpl.setAccessibilityFocus(null, null); 7267 } 7268 } 7269 } 7270 7271 private void sendAccessibilityHoverEvent(int eventType) { 7272 // Since we are not delivering to a client accessibility events from not 7273 // important views (unless the clinet request that) we need to fire the 7274 // event from the deepest view exposed to the client. As a consequence if 7275 // the user crosses a not exposed view the client will see enter and exit 7276 // of the exposed predecessor followed by and enter and exit of that same 7277 // predecessor when entering and exiting the not exposed descendant. This 7278 // is fine since the client has a clear idea which view is hovered at the 7279 // price of a couple more events being sent. This is a simple and 7280 // working solution. 7281 View source = this; 7282 while (true) { 7283 if (source.includeForAccessibility()) { 7284 source.sendAccessibilityEvent(eventType); 7285 return; 7286 } 7287 ViewParent parent = source.getParent(); 7288 if (parent instanceof View) { 7289 source = (View) parent; 7290 } else { 7291 return; 7292 } 7293 } 7294 } 7295 7296 /** 7297 * Clears accessibility focus without calling any callback methods 7298 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7299 * is used for clearing accessibility focus when giving this focus to 7300 * another view. 7301 */ 7302 void clearAccessibilityFocusNoCallbacks() { 7303 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7304 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7305 invalidate(); 7306 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7307 } 7308 } 7309 7310 /** 7311 * Call this to try to give focus to a specific view or to one of its 7312 * descendants. 7313 * 7314 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7315 * false), or if it is focusable and it is not focusable in touch mode 7316 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7317 * 7318 * See also {@link #focusSearch(int)}, which is what you call to say that you 7319 * have focus, and you want your parent to look for the next one. 7320 * 7321 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7322 * {@link #FOCUS_DOWN} and <code>null</code>. 7323 * 7324 * @return Whether this view or one of its descendants actually took focus. 7325 */ 7326 public final boolean requestFocus() { 7327 return requestFocus(View.FOCUS_DOWN); 7328 } 7329 7330 /** 7331 * Call this to try to give focus to a specific view or to one of its 7332 * descendants and give it a hint about what direction focus is heading. 7333 * 7334 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7335 * false), or if it is focusable and it is not focusable in touch mode 7336 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7337 * 7338 * See also {@link #focusSearch(int)}, which is what you call to say that you 7339 * have focus, and you want your parent to look for the next one. 7340 * 7341 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7342 * <code>null</code> set for the previously focused rectangle. 7343 * 7344 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7345 * @return Whether this view or one of its descendants actually took focus. 7346 */ 7347 public final boolean requestFocus(int direction) { 7348 return requestFocus(direction, null); 7349 } 7350 7351 /** 7352 * Call this to try to give focus to a specific view or to one of its descendants 7353 * and give it hints about the direction and a specific rectangle that the focus 7354 * is coming from. The rectangle can help give larger views a finer grained hint 7355 * about where focus is coming from, and therefore, where to show selection, or 7356 * forward focus change internally. 7357 * 7358 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7359 * false), or if it is focusable and it is not focusable in touch mode 7360 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7361 * 7362 * A View will not take focus if it is not visible. 7363 * 7364 * A View will not take focus if one of its parents has 7365 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7366 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7367 * 7368 * See also {@link #focusSearch(int)}, which is what you call to say that you 7369 * have focus, and you want your parent to look for the next one. 7370 * 7371 * You may wish to override this method if your custom {@link View} has an internal 7372 * {@link View} that it wishes to forward the request to. 7373 * 7374 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7375 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7376 * to give a finer grained hint about where focus is coming from. May be null 7377 * if there is no hint. 7378 * @return Whether this view or one of its descendants actually took focus. 7379 */ 7380 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7381 return requestFocusNoSearch(direction, previouslyFocusedRect); 7382 } 7383 7384 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7385 // need to be focusable 7386 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7387 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7388 return false; 7389 } 7390 7391 // need to be focusable in touch mode if in touch mode 7392 if (isInTouchMode() && 7393 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7394 return false; 7395 } 7396 7397 // need to not have any parents blocking us 7398 if (hasAncestorThatBlocksDescendantFocus()) { 7399 return false; 7400 } 7401 7402 handleFocusGainInternal(direction, previouslyFocusedRect); 7403 return true; 7404 } 7405 7406 /** 7407 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7408 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7409 * touch mode to request focus when they are touched. 7410 * 7411 * @return Whether this view or one of its descendants actually took focus. 7412 * 7413 * @see #isInTouchMode() 7414 * 7415 */ 7416 public final boolean requestFocusFromTouch() { 7417 // Leave touch mode if we need to 7418 if (isInTouchMode()) { 7419 ViewRootImpl viewRoot = getViewRootImpl(); 7420 if (viewRoot != null) { 7421 viewRoot.ensureTouchMode(false); 7422 } 7423 } 7424 return requestFocus(View.FOCUS_DOWN); 7425 } 7426 7427 /** 7428 * @return Whether any ancestor of this view blocks descendant focus. 7429 */ 7430 private boolean hasAncestorThatBlocksDescendantFocus() { 7431 ViewParent ancestor = mParent; 7432 while (ancestor instanceof ViewGroup) { 7433 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7434 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7435 return true; 7436 } else { 7437 ancestor = vgAncestor.getParent(); 7438 } 7439 } 7440 return false; 7441 } 7442 7443 /** 7444 * Gets the mode for determining whether this View is important for accessibility 7445 * which is if it fires accessibility events and if it is reported to 7446 * accessibility services that query the screen. 7447 * 7448 * @return The mode for determining whether a View is important for accessibility. 7449 * 7450 * @attr ref android.R.styleable#View_importantForAccessibility 7451 * 7452 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7453 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7454 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7455 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7456 */ 7457 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7458 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7459 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7460 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7461 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7462 to = "noHideDescendants") 7463 }) 7464 public int getImportantForAccessibility() { 7465 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7466 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7467 } 7468 7469 /** 7470 * Sets the live region mode for this view. This indicates to accessibility 7471 * services whether they should automatically notify the user about changes 7472 * to the view's content description or text, or to the content descriptions 7473 * or text of the view's children (where applicable). 7474 * <p> 7475 * For example, in a login screen with a TextView that displays an "incorrect 7476 * password" notification, that view should be marked as a live region with 7477 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7478 * <p> 7479 * To disable change notifications for this view, use 7480 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7481 * mode for most views. 7482 * <p> 7483 * To indicate that the user should be notified of changes, use 7484 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7485 * <p> 7486 * If the view's changes should interrupt ongoing speech and notify the user 7487 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7488 * 7489 * @param mode The live region mode for this view, one of: 7490 * <ul> 7491 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7492 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7493 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7494 * </ul> 7495 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7496 */ 7497 public void setAccessibilityLiveRegion(int mode) { 7498 if (mode != getAccessibilityLiveRegion()) { 7499 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7500 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7501 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7502 notifyViewAccessibilityStateChangedIfNeeded( 7503 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7504 } 7505 } 7506 7507 /** 7508 * Gets the live region mode for this View. 7509 * 7510 * @return The live region mode for the view. 7511 * 7512 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7513 * 7514 * @see #setAccessibilityLiveRegion(int) 7515 */ 7516 public int getAccessibilityLiveRegion() { 7517 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7518 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7519 } 7520 7521 /** 7522 * Sets how to determine whether this view is important for accessibility 7523 * which is if it fires accessibility events and if it is reported to 7524 * accessibility services that query the screen. 7525 * 7526 * @param mode How to determine whether this view is important for accessibility. 7527 * 7528 * @attr ref android.R.styleable#View_importantForAccessibility 7529 * 7530 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7531 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7532 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7533 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7534 */ 7535 public void setImportantForAccessibility(int mode) { 7536 final int oldMode = getImportantForAccessibility(); 7537 if (mode != oldMode) { 7538 // If we're moving between AUTO and another state, we might not need 7539 // to send a subtree changed notification. We'll store the computed 7540 // importance, since we'll need to check it later to make sure. 7541 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7542 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7543 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7544 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7545 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7546 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7547 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7548 notifySubtreeAccessibilityStateChangedIfNeeded(); 7549 } else { 7550 notifyViewAccessibilityStateChangedIfNeeded( 7551 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7552 } 7553 } 7554 } 7555 7556 /** 7557 * Computes whether this view should be exposed for accessibility. In 7558 * general, views that are interactive or provide information are exposed 7559 * while views that serve only as containers are hidden. 7560 * <p> 7561 * If an ancestor of this view has importance 7562 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7563 * returns <code>false</code>. 7564 * <p> 7565 * Otherwise, the value is computed according to the view's 7566 * {@link #getImportantForAccessibility()} value: 7567 * <ol> 7568 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7569 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7570 * </code> 7571 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7572 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7573 * view satisfies any of the following: 7574 * <ul> 7575 * <li>Is actionable, e.g. {@link #isClickable()}, 7576 * {@link #isLongClickable()}, or {@link #isFocusable()} 7577 * <li>Has an {@link AccessibilityDelegate} 7578 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7579 * {@link OnKeyListener}, etc. 7580 * <li>Is an accessibility live region, e.g. 7581 * {@link #getAccessibilityLiveRegion()} is not 7582 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7583 * </ul> 7584 * </ol> 7585 * 7586 * @return Whether the view is exposed for accessibility. 7587 * @see #setImportantForAccessibility(int) 7588 * @see #getImportantForAccessibility() 7589 */ 7590 public boolean isImportantForAccessibility() { 7591 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7592 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7593 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7594 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7595 return false; 7596 } 7597 7598 // Check parent mode to ensure we're not hidden. 7599 ViewParent parent = mParent; 7600 while (parent instanceof View) { 7601 if (((View) parent).getImportantForAccessibility() 7602 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7603 return false; 7604 } 7605 parent = parent.getParent(); 7606 } 7607 7608 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7609 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7610 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7611 } 7612 7613 /** 7614 * Gets the parent for accessibility purposes. Note that the parent for 7615 * accessibility is not necessary the immediate parent. It is the first 7616 * predecessor that is important for accessibility. 7617 * 7618 * @return The parent for accessibility purposes. 7619 */ 7620 public ViewParent getParentForAccessibility() { 7621 if (mParent instanceof View) { 7622 View parentView = (View) mParent; 7623 if (parentView.includeForAccessibility()) { 7624 return mParent; 7625 } else { 7626 return mParent.getParentForAccessibility(); 7627 } 7628 } 7629 return null; 7630 } 7631 7632 /** 7633 * Adds the children of a given View for accessibility. Since some Views are 7634 * not important for accessibility the children for accessibility are not 7635 * necessarily direct children of the view, rather they are the first level of 7636 * descendants important for accessibility. 7637 * 7638 * @param children The list of children for accessibility. 7639 */ 7640 public void addChildrenForAccessibility(ArrayList<View> children) { 7641 7642 } 7643 7644 /** 7645 * Whether to regard this view for accessibility. A view is regarded for 7646 * accessibility if it is important for accessibility or the querying 7647 * accessibility service has explicitly requested that view not 7648 * important for accessibility are regarded. 7649 * 7650 * @return Whether to regard the view for accessibility. 7651 * 7652 * @hide 7653 */ 7654 public boolean includeForAccessibility() { 7655 if (mAttachInfo != null) { 7656 return (mAttachInfo.mAccessibilityFetchFlags 7657 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7658 || isImportantForAccessibility(); 7659 } 7660 return false; 7661 } 7662 7663 /** 7664 * Returns whether the View is considered actionable from 7665 * accessibility perspective. Such view are important for 7666 * accessibility. 7667 * 7668 * @return True if the view is actionable for accessibility. 7669 * 7670 * @hide 7671 */ 7672 public boolean isActionableForAccessibility() { 7673 return (isClickable() || isLongClickable() || isFocusable()); 7674 } 7675 7676 /** 7677 * Returns whether the View has registered callbacks which makes it 7678 * important for accessibility. 7679 * 7680 * @return True if the view is actionable for accessibility. 7681 */ 7682 private boolean hasListenersForAccessibility() { 7683 ListenerInfo info = getListenerInfo(); 7684 return mTouchDelegate != null || info.mOnKeyListener != null 7685 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7686 || info.mOnHoverListener != null || info.mOnDragListener != null; 7687 } 7688 7689 /** 7690 * Notifies that the accessibility state of this view changed. The change 7691 * is local to this view and does not represent structural changes such 7692 * as children and parent. For example, the view became focusable. The 7693 * notification is at at most once every 7694 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7695 * to avoid unnecessary load to the system. Also once a view has a pending 7696 * notification this method is a NOP until the notification has been sent. 7697 * 7698 * @hide 7699 */ 7700 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7701 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7702 return; 7703 } 7704 if (mSendViewStateChangedAccessibilityEvent == null) { 7705 mSendViewStateChangedAccessibilityEvent = 7706 new SendViewStateChangedAccessibilityEvent(); 7707 } 7708 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7709 } 7710 7711 /** 7712 * Notifies that the accessibility state of this view changed. The change 7713 * is *not* local to this view and does represent structural changes such 7714 * as children and parent. For example, the view size changed. The 7715 * notification is at at most once every 7716 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7717 * to avoid unnecessary load to the system. Also once a view has a pending 7718 * notification this method is a NOP until the notification has been sent. 7719 * 7720 * @hide 7721 */ 7722 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7723 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7724 return; 7725 } 7726 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7727 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7728 if (mParent != null) { 7729 try { 7730 mParent.notifySubtreeAccessibilityStateChanged( 7731 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7732 } catch (AbstractMethodError e) { 7733 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7734 " does not fully implement ViewParent", e); 7735 } 7736 } 7737 } 7738 } 7739 7740 /** 7741 * Reset the flag indicating the accessibility state of the subtree rooted 7742 * at this view changed. 7743 */ 7744 void resetSubtreeAccessibilityStateChanged() { 7745 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7746 } 7747 7748 /** 7749 * Performs the specified accessibility action on the view. For 7750 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7751 * <p> 7752 * If an {@link AccessibilityDelegate} has been specified via calling 7753 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7754 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7755 * is responsible for handling this call. 7756 * </p> 7757 * 7758 * @param action The action to perform. 7759 * @param arguments Optional action arguments. 7760 * @return Whether the action was performed. 7761 */ 7762 public boolean performAccessibilityAction(int action, Bundle arguments) { 7763 if (mAccessibilityDelegate != null) { 7764 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7765 } else { 7766 return performAccessibilityActionInternal(action, arguments); 7767 } 7768 } 7769 7770 /** 7771 * @see #performAccessibilityAction(int, Bundle) 7772 * 7773 * Note: Called from the default {@link AccessibilityDelegate}. 7774 */ 7775 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7776 switch (action) { 7777 case AccessibilityNodeInfo.ACTION_CLICK: { 7778 if (isClickable()) { 7779 performClick(); 7780 return true; 7781 } 7782 } break; 7783 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7784 if (isLongClickable()) { 7785 performLongClick(); 7786 return true; 7787 } 7788 } break; 7789 case AccessibilityNodeInfo.ACTION_FOCUS: { 7790 if (!hasFocus()) { 7791 // Get out of touch mode since accessibility 7792 // wants to move focus around. 7793 getViewRootImpl().ensureTouchMode(false); 7794 return requestFocus(); 7795 } 7796 } break; 7797 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7798 if (hasFocus()) { 7799 clearFocus(); 7800 return !isFocused(); 7801 } 7802 } break; 7803 case AccessibilityNodeInfo.ACTION_SELECT: { 7804 if (!isSelected()) { 7805 setSelected(true); 7806 return isSelected(); 7807 } 7808 } break; 7809 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7810 if (isSelected()) { 7811 setSelected(false); 7812 return !isSelected(); 7813 } 7814 } break; 7815 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7816 if (!isAccessibilityFocused()) { 7817 return requestAccessibilityFocus(); 7818 } 7819 } break; 7820 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7821 if (isAccessibilityFocused()) { 7822 clearAccessibilityFocus(); 7823 return true; 7824 } 7825 } break; 7826 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7827 if (arguments != null) { 7828 final int granularity = arguments.getInt( 7829 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7830 final boolean extendSelection = arguments.getBoolean( 7831 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7832 return traverseAtGranularity(granularity, true, extendSelection); 7833 } 7834 } break; 7835 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7836 if (arguments != null) { 7837 final int granularity = arguments.getInt( 7838 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7839 final boolean extendSelection = arguments.getBoolean( 7840 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7841 return traverseAtGranularity(granularity, false, extendSelection); 7842 } 7843 } break; 7844 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7845 CharSequence text = getIterableTextForAccessibility(); 7846 if (text == null) { 7847 return false; 7848 } 7849 final int start = (arguments != null) ? arguments.getInt( 7850 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7851 final int end = (arguments != null) ? arguments.getInt( 7852 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7853 // Only cursor position can be specified (selection length == 0) 7854 if ((getAccessibilitySelectionStart() != start 7855 || getAccessibilitySelectionEnd() != end) 7856 && (start == end)) { 7857 setAccessibilitySelection(start, end); 7858 notifyViewAccessibilityStateChangedIfNeeded( 7859 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7860 return true; 7861 } 7862 } break; 7863 } 7864 return false; 7865 } 7866 7867 private boolean traverseAtGranularity(int granularity, boolean forward, 7868 boolean extendSelection) { 7869 CharSequence text = getIterableTextForAccessibility(); 7870 if (text == null || text.length() == 0) { 7871 return false; 7872 } 7873 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7874 if (iterator == null) { 7875 return false; 7876 } 7877 int current = getAccessibilitySelectionEnd(); 7878 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7879 current = forward ? 0 : text.length(); 7880 } 7881 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7882 if (range == null) { 7883 return false; 7884 } 7885 final int segmentStart = range[0]; 7886 final int segmentEnd = range[1]; 7887 int selectionStart; 7888 int selectionEnd; 7889 if (extendSelection && isAccessibilitySelectionExtendable()) { 7890 selectionStart = getAccessibilitySelectionStart(); 7891 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7892 selectionStart = forward ? segmentStart : segmentEnd; 7893 } 7894 selectionEnd = forward ? segmentEnd : segmentStart; 7895 } else { 7896 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7897 } 7898 setAccessibilitySelection(selectionStart, selectionEnd); 7899 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7900 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7901 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7902 return true; 7903 } 7904 7905 /** 7906 * Gets the text reported for accessibility purposes. 7907 * 7908 * @return The accessibility text. 7909 * 7910 * @hide 7911 */ 7912 public CharSequence getIterableTextForAccessibility() { 7913 return getContentDescription(); 7914 } 7915 7916 /** 7917 * Gets whether accessibility selection can be extended. 7918 * 7919 * @return If selection is extensible. 7920 * 7921 * @hide 7922 */ 7923 public boolean isAccessibilitySelectionExtendable() { 7924 return false; 7925 } 7926 7927 /** 7928 * @hide 7929 */ 7930 public int getAccessibilitySelectionStart() { 7931 return mAccessibilityCursorPosition; 7932 } 7933 7934 /** 7935 * @hide 7936 */ 7937 public int getAccessibilitySelectionEnd() { 7938 return getAccessibilitySelectionStart(); 7939 } 7940 7941 /** 7942 * @hide 7943 */ 7944 public void setAccessibilitySelection(int start, int end) { 7945 if (start == end && end == mAccessibilityCursorPosition) { 7946 return; 7947 } 7948 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7949 mAccessibilityCursorPosition = start; 7950 } else { 7951 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7952 } 7953 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7954 } 7955 7956 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7957 int fromIndex, int toIndex) { 7958 if (mParent == null) { 7959 return; 7960 } 7961 AccessibilityEvent event = AccessibilityEvent.obtain( 7962 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7963 onInitializeAccessibilityEvent(event); 7964 onPopulateAccessibilityEvent(event); 7965 event.setFromIndex(fromIndex); 7966 event.setToIndex(toIndex); 7967 event.setAction(action); 7968 event.setMovementGranularity(granularity); 7969 mParent.requestSendAccessibilityEvent(this, event); 7970 } 7971 7972 /** 7973 * @hide 7974 */ 7975 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7976 switch (granularity) { 7977 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7978 CharSequence text = getIterableTextForAccessibility(); 7979 if (text != null && text.length() > 0) { 7980 CharacterTextSegmentIterator iterator = 7981 CharacterTextSegmentIterator.getInstance( 7982 mContext.getResources().getConfiguration().locale); 7983 iterator.initialize(text.toString()); 7984 return iterator; 7985 } 7986 } break; 7987 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7988 CharSequence text = getIterableTextForAccessibility(); 7989 if (text != null && text.length() > 0) { 7990 WordTextSegmentIterator iterator = 7991 WordTextSegmentIterator.getInstance( 7992 mContext.getResources().getConfiguration().locale); 7993 iterator.initialize(text.toString()); 7994 return iterator; 7995 } 7996 } break; 7997 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7998 CharSequence text = getIterableTextForAccessibility(); 7999 if (text != null && text.length() > 0) { 8000 ParagraphTextSegmentIterator iterator = 8001 ParagraphTextSegmentIterator.getInstance(); 8002 iterator.initialize(text.toString()); 8003 return iterator; 8004 } 8005 } break; 8006 } 8007 return null; 8008 } 8009 8010 /** 8011 * @hide 8012 */ 8013 public void dispatchStartTemporaryDetach() { 8014 onStartTemporaryDetach(); 8015 } 8016 8017 /** 8018 * This is called when a container is going to temporarily detach a child, with 8019 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 8020 * It will either be followed by {@link #onFinishTemporaryDetach()} or 8021 * {@link #onDetachedFromWindow()} when the container is done. 8022 */ 8023 public void onStartTemporaryDetach() { 8024 removeUnsetPressCallback(); 8025 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 8026 } 8027 8028 /** 8029 * @hide 8030 */ 8031 public void dispatchFinishTemporaryDetach() { 8032 onFinishTemporaryDetach(); 8033 } 8034 8035 /** 8036 * Called after {@link #onStartTemporaryDetach} when the container is done 8037 * changing the view. 8038 */ 8039 public void onFinishTemporaryDetach() { 8040 } 8041 8042 /** 8043 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8044 * for this view's window. Returns null if the view is not currently attached 8045 * to the window. Normally you will not need to use this directly, but 8046 * just use the standard high-level event callbacks like 8047 * {@link #onKeyDown(int, KeyEvent)}. 8048 */ 8049 public KeyEvent.DispatcherState getKeyDispatcherState() { 8050 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8051 } 8052 8053 /** 8054 * Dispatch a key event before it is processed by any input method 8055 * associated with the view hierarchy. This can be used to intercept 8056 * key events in special situations before the IME consumes them; a 8057 * typical example would be handling the BACK key to update the application's 8058 * UI instead of allowing the IME to see it and close itself. 8059 * 8060 * @param event The key event to be dispatched. 8061 * @return True if the event was handled, false otherwise. 8062 */ 8063 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8064 return onKeyPreIme(event.getKeyCode(), event); 8065 } 8066 8067 /** 8068 * Dispatch a key event to the next view on the focus path. This path runs 8069 * from the top of the view tree down to the currently focused view. If this 8070 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8071 * the next node down the focus path. This method also fires any key 8072 * listeners. 8073 * 8074 * @param event The key event to be dispatched. 8075 * @return True if the event was handled, false otherwise. 8076 */ 8077 public boolean dispatchKeyEvent(KeyEvent event) { 8078 if (mInputEventConsistencyVerifier != null) { 8079 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8080 } 8081 8082 // Give any attached key listener a first crack at the event. 8083 //noinspection SimplifiableIfStatement 8084 ListenerInfo li = mListenerInfo; 8085 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8086 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8087 return true; 8088 } 8089 8090 if (event.dispatch(this, mAttachInfo != null 8091 ? mAttachInfo.mKeyDispatchState : null, this)) { 8092 return true; 8093 } 8094 8095 if (mInputEventConsistencyVerifier != null) { 8096 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8097 } 8098 return false; 8099 } 8100 8101 /** 8102 * Dispatches a key shortcut event. 8103 * 8104 * @param event The key event to be dispatched. 8105 * @return True if the event was handled by the view, false otherwise. 8106 */ 8107 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8108 return onKeyShortcut(event.getKeyCode(), event); 8109 } 8110 8111 /** 8112 * Pass the touch screen motion event down to the target view, or this 8113 * view if it is the target. 8114 * 8115 * @param event The motion event to be dispatched. 8116 * @return True if the event was handled by the view, false otherwise. 8117 */ 8118 public boolean dispatchTouchEvent(MotionEvent event) { 8119 boolean result = false; 8120 8121 if (mInputEventConsistencyVerifier != null) { 8122 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8123 } 8124 8125 final int actionMasked = event.getActionMasked(); 8126 if (actionMasked == MotionEvent.ACTION_DOWN) { 8127 // Defensive cleanup for new gesture 8128 stopNestedScroll(); 8129 } 8130 8131 if (onFilterTouchEventForSecurity(event)) { 8132 //noinspection SimplifiableIfStatement 8133 ListenerInfo li = mListenerInfo; 8134 if (li != null && li.mOnTouchListener != null 8135 && (mViewFlags & ENABLED_MASK) == ENABLED 8136 && li.mOnTouchListener.onTouch(this, event)) { 8137 result = true; 8138 } 8139 8140 if (!result && onTouchEvent(event)) { 8141 result = true; 8142 } 8143 } 8144 8145 if (!result && mInputEventConsistencyVerifier != null) { 8146 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8147 } 8148 8149 // Clean up after nested scrolls if this is the end of a gesture; 8150 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8151 // of the gesture. 8152 if (actionMasked == MotionEvent.ACTION_UP || 8153 actionMasked == MotionEvent.ACTION_CANCEL || 8154 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8155 stopNestedScroll(); 8156 } 8157 8158 return result; 8159 } 8160 8161 /** 8162 * Filter the touch event to apply security policies. 8163 * 8164 * @param event The motion event to be filtered. 8165 * @return True if the event should be dispatched, false if the event should be dropped. 8166 * 8167 * @see #getFilterTouchesWhenObscured 8168 */ 8169 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8170 //noinspection RedundantIfStatement 8171 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8172 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8173 // Window is obscured, drop this touch. 8174 return false; 8175 } 8176 return true; 8177 } 8178 8179 /** 8180 * Pass a trackball motion event down to the focused view. 8181 * 8182 * @param event The motion event to be dispatched. 8183 * @return True if the event was handled by the view, false otherwise. 8184 */ 8185 public boolean dispatchTrackballEvent(MotionEvent event) { 8186 if (mInputEventConsistencyVerifier != null) { 8187 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8188 } 8189 8190 return onTrackballEvent(event); 8191 } 8192 8193 /** 8194 * Dispatch a generic motion event. 8195 * <p> 8196 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8197 * are delivered to the view under the pointer. All other generic motion events are 8198 * delivered to the focused view. Hover events are handled specially and are delivered 8199 * to {@link #onHoverEvent(MotionEvent)}. 8200 * </p> 8201 * 8202 * @param event The motion event to be dispatched. 8203 * @return True if the event was handled by the view, false otherwise. 8204 */ 8205 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8206 if (mInputEventConsistencyVerifier != null) { 8207 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8208 } 8209 8210 final int source = event.getSource(); 8211 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8212 final int action = event.getAction(); 8213 if (action == MotionEvent.ACTION_HOVER_ENTER 8214 || action == MotionEvent.ACTION_HOVER_MOVE 8215 || action == MotionEvent.ACTION_HOVER_EXIT) { 8216 if (dispatchHoverEvent(event)) { 8217 return true; 8218 } 8219 } else if (dispatchGenericPointerEvent(event)) { 8220 return true; 8221 } 8222 } else if (dispatchGenericFocusedEvent(event)) { 8223 return true; 8224 } 8225 8226 if (dispatchGenericMotionEventInternal(event)) { 8227 return true; 8228 } 8229 8230 if (mInputEventConsistencyVerifier != null) { 8231 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8232 } 8233 return false; 8234 } 8235 8236 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8237 //noinspection SimplifiableIfStatement 8238 ListenerInfo li = mListenerInfo; 8239 if (li != null && li.mOnGenericMotionListener != null 8240 && (mViewFlags & ENABLED_MASK) == ENABLED 8241 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8242 return true; 8243 } 8244 8245 if (onGenericMotionEvent(event)) { 8246 return true; 8247 } 8248 8249 if (mInputEventConsistencyVerifier != null) { 8250 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8251 } 8252 return false; 8253 } 8254 8255 /** 8256 * Dispatch a hover event. 8257 * <p> 8258 * Do not call this method directly. 8259 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8260 * </p> 8261 * 8262 * @param event The motion event to be dispatched. 8263 * @return True if the event was handled by the view, false otherwise. 8264 */ 8265 protected boolean dispatchHoverEvent(MotionEvent event) { 8266 ListenerInfo li = mListenerInfo; 8267 //noinspection SimplifiableIfStatement 8268 if (li != null && li.mOnHoverListener != null 8269 && (mViewFlags & ENABLED_MASK) == ENABLED 8270 && li.mOnHoverListener.onHover(this, event)) { 8271 return true; 8272 } 8273 8274 return onHoverEvent(event); 8275 } 8276 8277 /** 8278 * Returns true if the view has a child to which it has recently sent 8279 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8280 * it does not have a hovered child, then it must be the innermost hovered view. 8281 * @hide 8282 */ 8283 protected boolean hasHoveredChild() { 8284 return false; 8285 } 8286 8287 /** 8288 * Dispatch a generic motion event to the view under the first pointer. 8289 * <p> 8290 * Do not call this method directly. 8291 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8292 * </p> 8293 * 8294 * @param event The motion event to be dispatched. 8295 * @return True if the event was handled by the view, false otherwise. 8296 */ 8297 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8298 return false; 8299 } 8300 8301 /** 8302 * Dispatch a generic motion event to the currently focused view. 8303 * <p> 8304 * Do not call this method directly. 8305 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8306 * </p> 8307 * 8308 * @param event The motion event to be dispatched. 8309 * @return True if the event was handled by the view, false otherwise. 8310 */ 8311 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8312 return false; 8313 } 8314 8315 /** 8316 * Dispatch a pointer event. 8317 * <p> 8318 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8319 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8320 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8321 * and should not be expected to handle other pointing device features. 8322 * </p> 8323 * 8324 * @param event The motion event to be dispatched. 8325 * @return True if the event was handled by the view, false otherwise. 8326 * @hide 8327 */ 8328 public final boolean dispatchPointerEvent(MotionEvent event) { 8329 if (event.isTouchEvent()) { 8330 return dispatchTouchEvent(event); 8331 } else { 8332 return dispatchGenericMotionEvent(event); 8333 } 8334 } 8335 8336 /** 8337 * Called when the window containing this view gains or loses window focus. 8338 * ViewGroups should override to route to their children. 8339 * 8340 * @param hasFocus True if the window containing this view now has focus, 8341 * false otherwise. 8342 */ 8343 public void dispatchWindowFocusChanged(boolean hasFocus) { 8344 onWindowFocusChanged(hasFocus); 8345 } 8346 8347 /** 8348 * Called when the window containing this view gains or loses focus. Note 8349 * that this is separate from view focus: to receive key events, both 8350 * your view and its window must have focus. If a window is displayed 8351 * on top of yours that takes input focus, then your own window will lose 8352 * focus but the view focus will remain unchanged. 8353 * 8354 * @param hasWindowFocus True if the window containing this view now has 8355 * focus, false otherwise. 8356 */ 8357 public void onWindowFocusChanged(boolean hasWindowFocus) { 8358 InputMethodManager imm = InputMethodManager.peekInstance(); 8359 if (!hasWindowFocus) { 8360 if (isPressed()) { 8361 setPressed(false); 8362 } 8363 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8364 imm.focusOut(this); 8365 } 8366 removeLongPressCallback(); 8367 removeTapCallback(); 8368 onFocusLost(); 8369 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8370 imm.focusIn(this); 8371 } 8372 refreshDrawableState(); 8373 } 8374 8375 /** 8376 * Returns true if this view is in a window that currently has window focus. 8377 * Note that this is not the same as the view itself having focus. 8378 * 8379 * @return True if this view is in a window that currently has window focus. 8380 */ 8381 public boolean hasWindowFocus() { 8382 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8383 } 8384 8385 /** 8386 * Dispatch a view visibility change down the view hierarchy. 8387 * ViewGroups should override to route to their children. 8388 * @param changedView The view whose visibility changed. Could be 'this' or 8389 * an ancestor view. 8390 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8391 * {@link #INVISIBLE} or {@link #GONE}. 8392 */ 8393 protected void dispatchVisibilityChanged(@NonNull View changedView, 8394 @Visibility int visibility) { 8395 onVisibilityChanged(changedView, visibility); 8396 } 8397 8398 /** 8399 * Called when the visibility of the view or an ancestor of the view is changed. 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 onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8406 if (visibility == VISIBLE) { 8407 if (mAttachInfo != null) { 8408 initialAwakenScrollBars(); 8409 } else { 8410 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8411 } 8412 } 8413 } 8414 8415 /** 8416 * Dispatch a hint about whether this view is displayed. For instance, when 8417 * a View moves out of the screen, it might receives a display hint indicating 8418 * the view is not displayed. Applications should not <em>rely</em> on this hint 8419 * as there is no guarantee that they will receive one. 8420 * 8421 * @param hint A hint about whether or not this view is displayed: 8422 * {@link #VISIBLE} or {@link #INVISIBLE}. 8423 */ 8424 public void dispatchDisplayHint(@Visibility int hint) { 8425 onDisplayHint(hint); 8426 } 8427 8428 /** 8429 * Gives this view a hint about whether is displayed or not. For instance, when 8430 * a View moves out of the screen, it might receives a display hint indicating 8431 * the view is not displayed. Applications should not <em>rely</em> on this hint 8432 * as there is no guarantee that they will receive one. 8433 * 8434 * @param hint A hint about whether or not this view is displayed: 8435 * {@link #VISIBLE} or {@link #INVISIBLE}. 8436 */ 8437 protected void onDisplayHint(@Visibility int hint) { 8438 } 8439 8440 /** 8441 * Dispatch a window visibility change down the view hierarchy. 8442 * ViewGroups should override to route to their children. 8443 * 8444 * @param visibility The new visibility of the window. 8445 * 8446 * @see #onWindowVisibilityChanged(int) 8447 */ 8448 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8449 onWindowVisibilityChanged(visibility); 8450 } 8451 8452 /** 8453 * Called when the window containing has change its visibility 8454 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8455 * that this tells you whether or not your window is being made visible 8456 * to the window manager; this does <em>not</em> tell you whether or not 8457 * your window is obscured by other windows on the screen, even if it 8458 * is itself visible. 8459 * 8460 * @param visibility The new visibility of the window. 8461 */ 8462 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8463 if (visibility == VISIBLE) { 8464 initialAwakenScrollBars(); 8465 } 8466 } 8467 8468 /** 8469 * Returns the current visibility of the window this view is attached to 8470 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8471 * 8472 * @return Returns the current visibility of the view's window. 8473 */ 8474 @Visibility 8475 public int getWindowVisibility() { 8476 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8477 } 8478 8479 /** 8480 * Retrieve the overall visible display size in which the window this view is 8481 * attached to has been positioned in. This takes into account screen 8482 * decorations above the window, for both cases where the window itself 8483 * is being position inside of them or the window is being placed under 8484 * then and covered insets are used for the window to position its content 8485 * inside. In effect, this tells you the available area where content can 8486 * be placed and remain visible to users. 8487 * 8488 * <p>This function requires an IPC back to the window manager to retrieve 8489 * the requested information, so should not be used in performance critical 8490 * code like drawing. 8491 * 8492 * @param outRect Filled in with the visible display frame. If the view 8493 * is not attached to a window, this is simply the raw display size. 8494 */ 8495 public void getWindowVisibleDisplayFrame(Rect outRect) { 8496 if (mAttachInfo != null) { 8497 try { 8498 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8499 } catch (RemoteException e) { 8500 return; 8501 } 8502 // XXX This is really broken, and probably all needs to be done 8503 // in the window manager, and we need to know more about whether 8504 // we want the area behind or in front of the IME. 8505 final Rect insets = mAttachInfo.mVisibleInsets; 8506 outRect.left += insets.left; 8507 outRect.top += insets.top; 8508 outRect.right -= insets.right; 8509 outRect.bottom -= insets.bottom; 8510 return; 8511 } 8512 // The view is not attached to a display so we don't have a context. 8513 // Make a best guess about the display size. 8514 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8515 d.getRectSize(outRect); 8516 } 8517 8518 /** 8519 * Dispatch a notification about a resource configuration change down 8520 * the view hierarchy. 8521 * ViewGroups should override to route to their children. 8522 * 8523 * @param newConfig The new resource configuration. 8524 * 8525 * @see #onConfigurationChanged(android.content.res.Configuration) 8526 */ 8527 public void dispatchConfigurationChanged(Configuration newConfig) { 8528 onConfigurationChanged(newConfig); 8529 } 8530 8531 /** 8532 * Called when the current configuration of the resources being used 8533 * by the application have changed. You can use this to decide when 8534 * to reload resources that can changed based on orientation and other 8535 * configuration characterstics. You only need to use this if you are 8536 * not relying on the normal {@link android.app.Activity} mechanism of 8537 * recreating the activity instance upon a configuration change. 8538 * 8539 * @param newConfig The new resource configuration. 8540 */ 8541 protected void onConfigurationChanged(Configuration newConfig) { 8542 } 8543 8544 /** 8545 * Private function to aggregate all per-view attributes in to the view 8546 * root. 8547 */ 8548 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8549 performCollectViewAttributes(attachInfo, visibility); 8550 } 8551 8552 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8553 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8554 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8555 attachInfo.mKeepScreenOn = true; 8556 } 8557 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8558 ListenerInfo li = mListenerInfo; 8559 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8560 attachInfo.mHasSystemUiListeners = true; 8561 } 8562 } 8563 } 8564 8565 void needGlobalAttributesUpdate(boolean force) { 8566 final AttachInfo ai = mAttachInfo; 8567 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8568 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8569 || ai.mHasSystemUiListeners) { 8570 ai.mRecomputeGlobalAttributes = true; 8571 } 8572 } 8573 } 8574 8575 /** 8576 * Returns whether the device is currently in touch mode. Touch mode is entered 8577 * once the user begins interacting with the device by touch, and affects various 8578 * things like whether focus is always visible to the user. 8579 * 8580 * @return Whether the device is in touch mode. 8581 */ 8582 @ViewDebug.ExportedProperty 8583 public boolean isInTouchMode() { 8584 if (mAttachInfo != null) { 8585 return mAttachInfo.mInTouchMode; 8586 } else { 8587 return ViewRootImpl.isInTouchMode(); 8588 } 8589 } 8590 8591 /** 8592 * Returns the context the view is running in, through which it can 8593 * access the current theme, resources, etc. 8594 * 8595 * @return The view's Context. 8596 */ 8597 @ViewDebug.CapturedViewProperty 8598 public final Context getContext() { 8599 return mContext; 8600 } 8601 8602 /** 8603 * Handle a key event before it is processed by any input method 8604 * associated with the view hierarchy. This can be used to intercept 8605 * key events in special situations before the IME consumes them; a 8606 * typical example would be handling the BACK key to update the application's 8607 * UI instead of allowing the IME to see it and close itself. 8608 * 8609 * @param keyCode The value in event.getKeyCode(). 8610 * @param event Description of the key event. 8611 * @return If you handled the event, return true. If you want to allow the 8612 * event to be handled by the next receiver, return false. 8613 */ 8614 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8615 return false; 8616 } 8617 8618 /** 8619 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8620 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8621 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8622 * is released, if the view is enabled and clickable. 8623 * 8624 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8625 * although some may elect to do so in some situations. Do not rely on this to 8626 * catch software key presses. 8627 * 8628 * @param keyCode A key code that represents the button pressed, from 8629 * {@link android.view.KeyEvent}. 8630 * @param event The KeyEvent object that defines the button action. 8631 */ 8632 public boolean onKeyDown(int keyCode, KeyEvent event) { 8633 boolean result = false; 8634 8635 if (KeyEvent.isConfirmKey(keyCode)) { 8636 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8637 return true; 8638 } 8639 // Long clickable items don't necessarily have to be clickable 8640 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8641 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8642 (event.getRepeatCount() == 0)) { 8643 setPressed(true); 8644 checkForLongClick(0); 8645 return true; 8646 } 8647 } 8648 return result; 8649 } 8650 8651 /** 8652 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8653 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8654 * the event). 8655 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8656 * although some may elect to do so in some situations. Do not rely on this to 8657 * catch software key presses. 8658 */ 8659 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8660 return false; 8661 } 8662 8663 /** 8664 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8665 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8666 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8667 * {@link KeyEvent#KEYCODE_ENTER} is released. 8668 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8669 * although some may elect to do so in some situations. Do not rely on this to 8670 * catch software key presses. 8671 * 8672 * @param keyCode A key code that represents the button pressed, from 8673 * {@link android.view.KeyEvent}. 8674 * @param event The KeyEvent object that defines the button action. 8675 */ 8676 public boolean onKeyUp(int keyCode, KeyEvent event) { 8677 if (KeyEvent.isConfirmKey(keyCode)) { 8678 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8679 return true; 8680 } 8681 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8682 setPressed(false); 8683 8684 if (!mHasPerformedLongPress) { 8685 // This is a tap, so remove the longpress check 8686 removeLongPressCallback(); 8687 return performClick(); 8688 } 8689 } 8690 } 8691 return false; 8692 } 8693 8694 /** 8695 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8696 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8697 * the event). 8698 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8699 * although some may elect to do so in some situations. Do not rely on this to 8700 * catch software key presses. 8701 * 8702 * @param keyCode A key code that represents the button pressed, from 8703 * {@link android.view.KeyEvent}. 8704 * @param repeatCount The number of times the action was made. 8705 * @param event The KeyEvent object that defines the button action. 8706 */ 8707 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8708 return false; 8709 } 8710 8711 /** 8712 * Called on the focused view when a key shortcut event is not handled. 8713 * Override this method to implement local key shortcuts for the View. 8714 * Key shortcuts can also be implemented by setting the 8715 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8716 * 8717 * @param keyCode The value in event.getKeyCode(). 8718 * @param event Description of the key event. 8719 * @return If you handled the event, return true. If you want to allow the 8720 * event to be handled by the next receiver, return false. 8721 */ 8722 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8723 return false; 8724 } 8725 8726 /** 8727 * Check whether the called view is a text editor, in which case it 8728 * would make sense to automatically display a soft input window for 8729 * it. Subclasses should override this if they implement 8730 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8731 * a call on that method would return a non-null InputConnection, and 8732 * they are really a first-class editor that the user would normally 8733 * start typing on when the go into a window containing your view. 8734 * 8735 * <p>The default implementation always returns false. This does 8736 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8737 * will not be called or the user can not otherwise perform edits on your 8738 * view; it is just a hint to the system that this is not the primary 8739 * purpose of this view. 8740 * 8741 * @return Returns true if this view is a text editor, else false. 8742 */ 8743 public boolean onCheckIsTextEditor() { 8744 return false; 8745 } 8746 8747 /** 8748 * Create a new InputConnection for an InputMethod to interact 8749 * with the view. The default implementation returns null, since it doesn't 8750 * support input methods. You can override this to implement such support. 8751 * This is only needed for views that take focus and text input. 8752 * 8753 * <p>When implementing this, you probably also want to implement 8754 * {@link #onCheckIsTextEditor()} to indicate you will return a 8755 * non-null InputConnection.</p> 8756 * 8757 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8758 * object correctly and in its entirety, so that the connected IME can rely 8759 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8760 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8761 * must be filled in with the correct cursor position for IMEs to work correctly 8762 * with your application.</p> 8763 * 8764 * @param outAttrs Fill in with attribute information about the connection. 8765 */ 8766 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8767 return null; 8768 } 8769 8770 /** 8771 * Called by the {@link android.view.inputmethod.InputMethodManager} 8772 * when a view who is not the current 8773 * input connection target is trying to make a call on the manager. The 8774 * default implementation returns false; you can override this to return 8775 * true for certain views if you are performing InputConnection proxying 8776 * to them. 8777 * @param view The View that is making the InputMethodManager call. 8778 * @return Return true to allow the call, false to reject. 8779 */ 8780 public boolean checkInputConnectionProxy(View view) { 8781 return false; 8782 } 8783 8784 /** 8785 * Show the context menu for this view. It is not safe to hold on to the 8786 * menu after returning from this method. 8787 * 8788 * You should normally not overload this method. Overload 8789 * {@link #onCreateContextMenu(ContextMenu)} or define an 8790 * {@link OnCreateContextMenuListener} to add items to the context menu. 8791 * 8792 * @param menu The context menu to populate 8793 */ 8794 public void createContextMenu(ContextMenu menu) { 8795 ContextMenuInfo menuInfo = getContextMenuInfo(); 8796 8797 // Sets the current menu info so all items added to menu will have 8798 // my extra info set. 8799 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8800 8801 onCreateContextMenu(menu); 8802 ListenerInfo li = mListenerInfo; 8803 if (li != null && li.mOnCreateContextMenuListener != null) { 8804 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8805 } 8806 8807 // Clear the extra information so subsequent items that aren't mine don't 8808 // have my extra info. 8809 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8810 8811 if (mParent != null) { 8812 mParent.createContextMenu(menu); 8813 } 8814 } 8815 8816 /** 8817 * Views should implement this if they have extra information to associate 8818 * with the context menu. The return result is supplied as a parameter to 8819 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8820 * callback. 8821 * 8822 * @return Extra information about the item for which the context menu 8823 * should be shown. This information will vary across different 8824 * subclasses of View. 8825 */ 8826 protected ContextMenuInfo getContextMenuInfo() { 8827 return null; 8828 } 8829 8830 /** 8831 * Views should implement this if the view itself is going to add items to 8832 * the context menu. 8833 * 8834 * @param menu the context menu to populate 8835 */ 8836 protected void onCreateContextMenu(ContextMenu menu) { 8837 } 8838 8839 /** 8840 * Implement this method to handle trackball motion events. The 8841 * <em>relative</em> movement of the trackball since the last event 8842 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8843 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8844 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8845 * they will often be fractional values, representing the more fine-grained 8846 * movement information available from a trackball). 8847 * 8848 * @param event The motion event. 8849 * @return True if the event was handled, false otherwise. 8850 */ 8851 public boolean onTrackballEvent(MotionEvent event) { 8852 return false; 8853 } 8854 8855 /** 8856 * Implement this method to handle generic motion events. 8857 * <p> 8858 * Generic motion events describe joystick movements, mouse hovers, track pad 8859 * touches, scroll wheel movements and other input events. The 8860 * {@link MotionEvent#getSource() source} of the motion event specifies 8861 * the class of input that was received. Implementations of this method 8862 * must examine the bits in the source before processing the event. 8863 * The following code example shows how this is done. 8864 * </p><p> 8865 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8866 * are delivered to the view under the pointer. All other generic motion events are 8867 * delivered to the focused view. 8868 * </p> 8869 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8870 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8871 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8872 * // process the joystick movement... 8873 * return true; 8874 * } 8875 * } 8876 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8877 * switch (event.getAction()) { 8878 * case MotionEvent.ACTION_HOVER_MOVE: 8879 * // process the mouse hover movement... 8880 * return true; 8881 * case MotionEvent.ACTION_SCROLL: 8882 * // process the scroll wheel movement... 8883 * return true; 8884 * } 8885 * } 8886 * return super.onGenericMotionEvent(event); 8887 * }</pre> 8888 * 8889 * @param event The generic motion event being processed. 8890 * @return True if the event was handled, false otherwise. 8891 */ 8892 public boolean onGenericMotionEvent(MotionEvent event) { 8893 return false; 8894 } 8895 8896 /** 8897 * Implement this method to handle hover events. 8898 * <p> 8899 * This method is called whenever a pointer is hovering into, over, or out of the 8900 * bounds of a view and the view is not currently being touched. 8901 * Hover events are represented as pointer events with action 8902 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8903 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8904 * </p> 8905 * <ul> 8906 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8907 * when the pointer enters the bounds of the view.</li> 8908 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8909 * when the pointer has already entered the bounds of the view and has moved.</li> 8910 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8911 * when the pointer has exited the bounds of the view or when the pointer is 8912 * about to go down due to a button click, tap, or similar user action that 8913 * causes the view to be touched.</li> 8914 * </ul> 8915 * <p> 8916 * The view should implement this method to return true to indicate that it is 8917 * handling the hover event, such as by changing its drawable state. 8918 * </p><p> 8919 * The default implementation calls {@link #setHovered} to update the hovered state 8920 * of the view when a hover enter or hover exit event is received, if the view 8921 * is enabled and is clickable. The default implementation also sends hover 8922 * accessibility events. 8923 * </p> 8924 * 8925 * @param event The motion event that describes the hover. 8926 * @return True if the view handled the hover event. 8927 * 8928 * @see #isHovered 8929 * @see #setHovered 8930 * @see #onHoverChanged 8931 */ 8932 public boolean onHoverEvent(MotionEvent event) { 8933 // The root view may receive hover (or touch) events that are outside the bounds of 8934 // the window. This code ensures that we only send accessibility events for 8935 // hovers that are actually within the bounds of the root view. 8936 final int action = event.getActionMasked(); 8937 if (!mSendingHoverAccessibilityEvents) { 8938 if ((action == MotionEvent.ACTION_HOVER_ENTER 8939 || action == MotionEvent.ACTION_HOVER_MOVE) 8940 && !hasHoveredChild() 8941 && pointInView(event.getX(), event.getY())) { 8942 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8943 mSendingHoverAccessibilityEvents = true; 8944 } 8945 } else { 8946 if (action == MotionEvent.ACTION_HOVER_EXIT 8947 || (action == MotionEvent.ACTION_MOVE 8948 && !pointInView(event.getX(), event.getY()))) { 8949 mSendingHoverAccessibilityEvents = false; 8950 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8951 } 8952 } 8953 8954 if (isHoverable()) { 8955 switch (action) { 8956 case MotionEvent.ACTION_HOVER_ENTER: 8957 setHovered(true); 8958 break; 8959 case MotionEvent.ACTION_HOVER_EXIT: 8960 setHovered(false); 8961 break; 8962 } 8963 8964 // Dispatch the event to onGenericMotionEvent before returning true. 8965 // This is to provide compatibility with existing applications that 8966 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8967 // break because of the new default handling for hoverable views 8968 // in onHoverEvent. 8969 // Note that onGenericMotionEvent will be called by default when 8970 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8971 dispatchGenericMotionEventInternal(event); 8972 // The event was already handled by calling setHovered(), so always 8973 // return true. 8974 return true; 8975 } 8976 8977 return false; 8978 } 8979 8980 /** 8981 * Returns true if the view should handle {@link #onHoverEvent} 8982 * by calling {@link #setHovered} to change its hovered state. 8983 * 8984 * @return True if the view is hoverable. 8985 */ 8986 private boolean isHoverable() { 8987 final int viewFlags = mViewFlags; 8988 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8989 return false; 8990 } 8991 8992 return (viewFlags & CLICKABLE) == CLICKABLE 8993 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8994 } 8995 8996 /** 8997 * Returns true if the view is currently hovered. 8998 * 8999 * @return True if the view is currently hovered. 9000 * 9001 * @see #setHovered 9002 * @see #onHoverChanged 9003 */ 9004 @ViewDebug.ExportedProperty 9005 public boolean isHovered() { 9006 return (mPrivateFlags & PFLAG_HOVERED) != 0; 9007 } 9008 9009 /** 9010 * Sets whether the view is currently hovered. 9011 * <p> 9012 * Calling this method also changes the drawable state of the view. This 9013 * enables the view to react to hover by using different drawable resources 9014 * to change its appearance. 9015 * </p><p> 9016 * The {@link #onHoverChanged} method is called when the hovered state changes. 9017 * </p> 9018 * 9019 * @param hovered True if the view is hovered. 9020 * 9021 * @see #isHovered 9022 * @see #onHoverChanged 9023 */ 9024 public void setHovered(boolean hovered) { 9025 if (hovered) { 9026 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 9027 mPrivateFlags |= PFLAG_HOVERED; 9028 refreshDrawableState(); 9029 onHoverChanged(true); 9030 } 9031 } else { 9032 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 9033 mPrivateFlags &= ~PFLAG_HOVERED; 9034 refreshDrawableState(); 9035 onHoverChanged(false); 9036 } 9037 } 9038 } 9039 9040 /** 9041 * Implement this method to handle hover state changes. 9042 * <p> 9043 * This method is called whenever the hover state changes as a result of a 9044 * call to {@link #setHovered}. 9045 * </p> 9046 * 9047 * @param hovered The current hover state, as returned by {@link #isHovered}. 9048 * 9049 * @see #isHovered 9050 * @see #setHovered 9051 */ 9052 public void onHoverChanged(boolean hovered) { 9053 } 9054 9055 /** 9056 * Implement this method to handle touch screen motion events. 9057 * <p> 9058 * If this method is used to detect click actions, it is recommended that 9059 * the actions be performed by implementing and calling 9060 * {@link #performClick()}. This will ensure consistent system behavior, 9061 * including: 9062 * <ul> 9063 * <li>obeying click sound preferences 9064 * <li>dispatching OnClickListener calls 9065 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9066 * accessibility features are enabled 9067 * </ul> 9068 * 9069 * @param event The motion event. 9070 * @return True if the event was handled, false otherwise. 9071 */ 9072 public boolean onTouchEvent(MotionEvent event) { 9073 final float x = event.getX(); 9074 final float y = event.getY(); 9075 final int viewFlags = mViewFlags; 9076 9077 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9078 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9079 setPressed(false); 9080 } 9081 // A disabled view that is clickable still consumes the touch 9082 // events, it just doesn't respond to them. 9083 return (((viewFlags & CLICKABLE) == CLICKABLE || 9084 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9085 } 9086 9087 if (mTouchDelegate != null) { 9088 if (mTouchDelegate.onTouchEvent(event)) { 9089 return true; 9090 } 9091 } 9092 9093 if (((viewFlags & CLICKABLE) == CLICKABLE || 9094 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9095 switch (event.getAction()) { 9096 case MotionEvent.ACTION_UP: 9097 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9098 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9099 // take focus if we don't have it already and we should in 9100 // touch mode. 9101 boolean focusTaken = false; 9102 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9103 focusTaken = requestFocus(); 9104 } 9105 9106 if (prepressed) { 9107 // The button is being released before we actually 9108 // showed it as pressed. Make it show the pressed 9109 // state now (before scheduling the click) to ensure 9110 // the user sees it. 9111 setPressed(true, x, y); 9112 } 9113 9114 if (!mHasPerformedLongPress) { 9115 // This is a tap, so remove the longpress check 9116 removeLongPressCallback(); 9117 9118 // Only perform take click actions if we were in the pressed state 9119 if (!focusTaken) { 9120 // Use a Runnable and post this rather than calling 9121 // performClick directly. This lets other visual state 9122 // of the view update before click actions start. 9123 if (mPerformClick == null) { 9124 mPerformClick = new PerformClick(); 9125 } 9126 if (!post(mPerformClick)) { 9127 performClick(); 9128 } 9129 } 9130 } 9131 9132 if (mUnsetPressedState == null) { 9133 mUnsetPressedState = new UnsetPressedState(); 9134 } 9135 9136 if (prepressed) { 9137 postDelayed(mUnsetPressedState, 9138 ViewConfiguration.getPressedStateDuration()); 9139 } else if (!post(mUnsetPressedState)) { 9140 // If the post failed, unpress right now 9141 mUnsetPressedState.run(); 9142 } 9143 9144 removeTapCallback(); 9145 } 9146 break; 9147 9148 case MotionEvent.ACTION_DOWN: 9149 mHasPerformedLongPress = false; 9150 9151 if (performButtonActionOnTouchDown(event)) { 9152 break; 9153 } 9154 9155 // Walk up the hierarchy to determine if we're inside a scrolling container. 9156 boolean isInScrollingContainer = isInScrollingContainer(); 9157 9158 // For views inside a scrolling container, delay the pressed feedback for 9159 // a short period in case this is a scroll. 9160 if (isInScrollingContainer) { 9161 mPrivateFlags |= PFLAG_PREPRESSED; 9162 if (mPendingCheckForTap == null) { 9163 mPendingCheckForTap = new CheckForTap(); 9164 } 9165 mPendingCheckForTap.x = event.getX(); 9166 mPendingCheckForTap.y = event.getY(); 9167 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9168 } else { 9169 // Not inside a scrolling container, so show the feedback right away 9170 setPressed(true, x, y); 9171 checkForLongClick(0); 9172 } 9173 break; 9174 9175 case MotionEvent.ACTION_CANCEL: 9176 setPressed(false); 9177 removeTapCallback(); 9178 removeLongPressCallback(); 9179 break; 9180 9181 case MotionEvent.ACTION_MOVE: 9182 drawableHotspotChanged(x, y); 9183 9184 // Be lenient about moving outside of buttons 9185 if (!pointInView(x, y, mTouchSlop)) { 9186 // Outside button 9187 removeTapCallback(); 9188 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9189 // Remove any future long press/tap checks 9190 removeLongPressCallback(); 9191 9192 setPressed(false); 9193 } 9194 } 9195 break; 9196 } 9197 9198 return true; 9199 } 9200 9201 return false; 9202 } 9203 9204 /** 9205 * @hide 9206 */ 9207 public boolean isInScrollingContainer() { 9208 ViewParent p = getParent(); 9209 while (p != null && p instanceof ViewGroup) { 9210 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9211 return true; 9212 } 9213 p = p.getParent(); 9214 } 9215 return false; 9216 } 9217 9218 /** 9219 * Remove the longpress detection timer. 9220 */ 9221 private void removeLongPressCallback() { 9222 if (mPendingCheckForLongPress != null) { 9223 removeCallbacks(mPendingCheckForLongPress); 9224 } 9225 } 9226 9227 /** 9228 * Remove the pending click action 9229 */ 9230 private void removePerformClickCallback() { 9231 if (mPerformClick != null) { 9232 removeCallbacks(mPerformClick); 9233 } 9234 } 9235 9236 /** 9237 * Remove the prepress detection timer. 9238 */ 9239 private void removeUnsetPressCallback() { 9240 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9241 setPressed(false); 9242 removeCallbacks(mUnsetPressedState); 9243 } 9244 } 9245 9246 /** 9247 * Remove the tap detection timer. 9248 */ 9249 private void removeTapCallback() { 9250 if (mPendingCheckForTap != null) { 9251 mPrivateFlags &= ~PFLAG_PREPRESSED; 9252 removeCallbacks(mPendingCheckForTap); 9253 } 9254 } 9255 9256 /** 9257 * Cancels a pending long press. Your subclass can use this if you 9258 * want the context menu to come up if the user presses and holds 9259 * at the same place, but you don't want it to come up if they press 9260 * and then move around enough to cause scrolling. 9261 */ 9262 public void cancelLongPress() { 9263 removeLongPressCallback(); 9264 9265 /* 9266 * The prepressed state handled by the tap callback is a display 9267 * construct, but the tap callback will post a long press callback 9268 * less its own timeout. Remove it here. 9269 */ 9270 removeTapCallback(); 9271 } 9272 9273 /** 9274 * Remove the pending callback for sending a 9275 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9276 */ 9277 private void removeSendViewScrolledAccessibilityEventCallback() { 9278 if (mSendViewScrolledAccessibilityEvent != null) { 9279 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9280 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9281 } 9282 } 9283 9284 /** 9285 * Sets the TouchDelegate for this View. 9286 */ 9287 public void setTouchDelegate(TouchDelegate delegate) { 9288 mTouchDelegate = delegate; 9289 } 9290 9291 /** 9292 * Gets the TouchDelegate for this View. 9293 */ 9294 public TouchDelegate getTouchDelegate() { 9295 return mTouchDelegate; 9296 } 9297 9298 /** 9299 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9300 * 9301 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9302 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9303 * available. This method should only be called for touch events. 9304 * 9305 * <p class="note">This api is not intended for most applications. Buffered dispatch 9306 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9307 * streams will not improve your input latency. Side effects include: increased latency, 9308 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9309 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9310 * you.</p> 9311 */ 9312 public final void requestUnbufferedDispatch(MotionEvent event) { 9313 final int action = event.getAction(); 9314 if (mAttachInfo == null 9315 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9316 || !event.isTouchEvent()) { 9317 return; 9318 } 9319 mAttachInfo.mUnbufferedDispatchRequested = true; 9320 } 9321 9322 /** 9323 * Set flags controlling behavior of this view. 9324 * 9325 * @param flags Constant indicating the value which should be set 9326 * @param mask Constant indicating the bit range that should be changed 9327 */ 9328 void setFlags(int flags, int mask) { 9329 final boolean accessibilityEnabled = 9330 AccessibilityManager.getInstance(mContext).isEnabled(); 9331 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9332 9333 int old = mViewFlags; 9334 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9335 9336 int changed = mViewFlags ^ old; 9337 if (changed == 0) { 9338 return; 9339 } 9340 int privateFlags = mPrivateFlags; 9341 9342 /* Check if the FOCUSABLE bit has changed */ 9343 if (((changed & FOCUSABLE_MASK) != 0) && 9344 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9345 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9346 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9347 /* Give up focus if we are no longer focusable */ 9348 clearFocus(); 9349 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9350 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9351 /* 9352 * Tell the view system that we are now available to take focus 9353 * if no one else already has it. 9354 */ 9355 if (mParent != null) mParent.focusableViewAvailable(this); 9356 } 9357 } 9358 9359 final int newVisibility = flags & VISIBILITY_MASK; 9360 if (newVisibility == VISIBLE) { 9361 if ((changed & VISIBILITY_MASK) != 0) { 9362 /* 9363 * If this view is becoming visible, invalidate it in case it changed while 9364 * it was not visible. Marking it drawn ensures that the invalidation will 9365 * go through. 9366 */ 9367 mPrivateFlags |= PFLAG_DRAWN; 9368 invalidate(true); 9369 9370 needGlobalAttributesUpdate(true); 9371 9372 // a view becoming visible is worth notifying the parent 9373 // about in case nothing has focus. even if this specific view 9374 // isn't focusable, it may contain something that is, so let 9375 // the root view try to give this focus if nothing else does. 9376 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9377 mParent.focusableViewAvailable(this); 9378 } 9379 } 9380 } 9381 9382 /* Check if the GONE bit has changed */ 9383 if ((changed & GONE) != 0) { 9384 needGlobalAttributesUpdate(false); 9385 requestLayout(); 9386 9387 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9388 if (hasFocus()) clearFocus(); 9389 clearAccessibilityFocus(); 9390 destroyDrawingCache(); 9391 if (mParent instanceof View) { 9392 // GONE views noop invalidation, so invalidate the parent 9393 ((View) mParent).invalidate(true); 9394 } 9395 // Mark the view drawn to ensure that it gets invalidated properly the next 9396 // time it is visible and gets invalidated 9397 mPrivateFlags |= PFLAG_DRAWN; 9398 } 9399 if (mAttachInfo != null) { 9400 mAttachInfo.mViewVisibilityChanged = true; 9401 } 9402 } 9403 9404 /* Check if the VISIBLE bit has changed */ 9405 if ((changed & INVISIBLE) != 0) { 9406 needGlobalAttributesUpdate(false); 9407 /* 9408 * If this view is becoming invisible, set the DRAWN flag so that 9409 * the next invalidate() will not be skipped. 9410 */ 9411 mPrivateFlags |= PFLAG_DRAWN; 9412 9413 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9414 // root view becoming invisible shouldn't clear focus and accessibility focus 9415 if (getRootView() != this) { 9416 if (hasFocus()) clearFocus(); 9417 clearAccessibilityFocus(); 9418 } 9419 } 9420 if (mAttachInfo != null) { 9421 mAttachInfo.mViewVisibilityChanged = true; 9422 } 9423 } 9424 9425 if ((changed & VISIBILITY_MASK) != 0) { 9426 // If the view is invisible, cleanup its display list to free up resources 9427 if (newVisibility != VISIBLE && mAttachInfo != null) { 9428 cleanupDraw(); 9429 } 9430 9431 if (mParent instanceof ViewGroup) { 9432 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9433 (changed & VISIBILITY_MASK), newVisibility); 9434 ((View) mParent).invalidate(true); 9435 } else if (mParent != null) { 9436 mParent.invalidateChild(this, null); 9437 } 9438 dispatchVisibilityChanged(this, newVisibility); 9439 9440 notifySubtreeAccessibilityStateChangedIfNeeded(); 9441 } 9442 9443 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9444 destroyDrawingCache(); 9445 } 9446 9447 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9448 destroyDrawingCache(); 9449 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9450 invalidateParentCaches(); 9451 } 9452 9453 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9454 destroyDrawingCache(); 9455 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9456 } 9457 9458 if ((changed & DRAW_MASK) != 0) { 9459 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9460 if (mBackground != null) { 9461 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9462 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9463 } else { 9464 mPrivateFlags |= PFLAG_SKIP_DRAW; 9465 } 9466 } else { 9467 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9468 } 9469 requestLayout(); 9470 invalidate(true); 9471 } 9472 9473 if ((changed & KEEP_SCREEN_ON) != 0) { 9474 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9475 mParent.recomputeViewAttributes(this); 9476 } 9477 } 9478 9479 if (accessibilityEnabled) { 9480 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9481 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9482 if (oldIncludeForAccessibility != includeForAccessibility()) { 9483 notifySubtreeAccessibilityStateChangedIfNeeded(); 9484 } else { 9485 notifyViewAccessibilityStateChangedIfNeeded( 9486 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9487 } 9488 } else if ((changed & ENABLED_MASK) != 0) { 9489 notifyViewAccessibilityStateChangedIfNeeded( 9490 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9491 } 9492 } 9493 } 9494 9495 /** 9496 * Change the view's z order in the tree, so it's on top of other sibling 9497 * views. This ordering change may affect layout, if the parent container 9498 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9499 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9500 * method should be followed by calls to {@link #requestLayout()} and 9501 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9502 * with the new child ordering. 9503 * 9504 * @see ViewGroup#bringChildToFront(View) 9505 */ 9506 public void bringToFront() { 9507 if (mParent != null) { 9508 mParent.bringChildToFront(this); 9509 } 9510 } 9511 9512 /** 9513 * This is called in response to an internal scroll in this view (i.e., the 9514 * view scrolled its own contents). This is typically as a result of 9515 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9516 * called. 9517 * 9518 * @param l Current horizontal scroll origin. 9519 * @param t Current vertical scroll origin. 9520 * @param oldl Previous horizontal scroll origin. 9521 * @param oldt Previous vertical scroll origin. 9522 */ 9523 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9524 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9525 postSendViewScrolledAccessibilityEventCallback(); 9526 } 9527 9528 mBackgroundSizeChanged = true; 9529 9530 final AttachInfo ai = mAttachInfo; 9531 if (ai != null) { 9532 ai.mViewScrollChanged = true; 9533 } 9534 } 9535 9536 /** 9537 * Interface definition for a callback to be invoked when the layout bounds of a view 9538 * changes due to layout processing. 9539 */ 9540 public interface OnLayoutChangeListener { 9541 /** 9542 * Called when the layout bounds of a view changes due to layout processing. 9543 * 9544 * @param v The view whose bounds have changed. 9545 * @param left The new value of the view's left property. 9546 * @param top The new value of the view's top property. 9547 * @param right The new value of the view's right property. 9548 * @param bottom The new value of the view's bottom property. 9549 * @param oldLeft The previous value of the view's left property. 9550 * @param oldTop The previous value of the view's top property. 9551 * @param oldRight The previous value of the view's right property. 9552 * @param oldBottom The previous value of the view's bottom property. 9553 */ 9554 void onLayoutChange(View v, int left, int top, int right, int bottom, 9555 int oldLeft, int oldTop, int oldRight, int oldBottom); 9556 } 9557 9558 /** 9559 * This is called during layout when the size of this view has changed. If 9560 * you were just added to the view hierarchy, you're called with the old 9561 * values of 0. 9562 * 9563 * @param w Current width of this view. 9564 * @param h Current height of this view. 9565 * @param oldw Old width of this view. 9566 * @param oldh Old height of this view. 9567 */ 9568 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9569 } 9570 9571 /** 9572 * Called by draw to draw the child views. This may be overridden 9573 * by derived classes to gain control just before its children are drawn 9574 * (but after its own view has been drawn). 9575 * @param canvas the canvas on which to draw the view 9576 */ 9577 protected void dispatchDraw(Canvas canvas) { 9578 9579 } 9580 9581 /** 9582 * Gets the parent of this view. Note that the parent is a 9583 * ViewParent and not necessarily a View. 9584 * 9585 * @return Parent of this view. 9586 */ 9587 public final ViewParent getParent() { 9588 return mParent; 9589 } 9590 9591 /** 9592 * Set the horizontal scrolled position of your view. This will cause a call to 9593 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9594 * invalidated. 9595 * @param value the x position to scroll to 9596 */ 9597 public void setScrollX(int value) { 9598 scrollTo(value, mScrollY); 9599 } 9600 9601 /** 9602 * Set the vertical scrolled position of your view. This will cause a call to 9603 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9604 * invalidated. 9605 * @param value the y position to scroll to 9606 */ 9607 public void setScrollY(int value) { 9608 scrollTo(mScrollX, value); 9609 } 9610 9611 /** 9612 * Return the scrolled left position of this view. This is the left edge of 9613 * the displayed part of your view. You do not need to draw any pixels 9614 * farther left, since those are outside of the frame of your view on 9615 * screen. 9616 * 9617 * @return The left edge of the displayed part of your view, in pixels. 9618 */ 9619 public final int getScrollX() { 9620 return mScrollX; 9621 } 9622 9623 /** 9624 * Return the scrolled top position of this view. This is the top edge of 9625 * the displayed part of your view. You do not need to draw any pixels above 9626 * it, since those are outside of the frame of your view on screen. 9627 * 9628 * @return The top edge of the displayed part of your view, in pixels. 9629 */ 9630 public final int getScrollY() { 9631 return mScrollY; 9632 } 9633 9634 /** 9635 * Return the width of the your view. 9636 * 9637 * @return The width of your view, in pixels. 9638 */ 9639 @ViewDebug.ExportedProperty(category = "layout") 9640 public final int getWidth() { 9641 return mRight - mLeft; 9642 } 9643 9644 /** 9645 * Return the height of your view. 9646 * 9647 * @return The height of your view, in pixels. 9648 */ 9649 @ViewDebug.ExportedProperty(category = "layout") 9650 public final int getHeight() { 9651 return mBottom - mTop; 9652 } 9653 9654 /** 9655 * Return the visible drawing bounds of your view. Fills in the output 9656 * rectangle with the values from getScrollX(), getScrollY(), 9657 * getWidth(), and getHeight(). These bounds do not account for any 9658 * transformation properties currently set on the view, such as 9659 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9660 * 9661 * @param outRect The (scrolled) drawing bounds of the view. 9662 */ 9663 public void getDrawingRect(Rect outRect) { 9664 outRect.left = mScrollX; 9665 outRect.top = mScrollY; 9666 outRect.right = mScrollX + (mRight - mLeft); 9667 outRect.bottom = mScrollY + (mBottom - mTop); 9668 } 9669 9670 /** 9671 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9672 * raw width component (that is the result is masked by 9673 * {@link #MEASURED_SIZE_MASK}). 9674 * 9675 * @return The raw measured width of this view. 9676 */ 9677 public final int getMeasuredWidth() { 9678 return mMeasuredWidth & MEASURED_SIZE_MASK; 9679 } 9680 9681 /** 9682 * Return the full width measurement information for this view as computed 9683 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9684 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9685 * This should be used during measurement and layout calculations only. Use 9686 * {@link #getWidth()} to see how wide a view is after layout. 9687 * 9688 * @return The measured width of this view as a bit mask. 9689 */ 9690 public final int getMeasuredWidthAndState() { 9691 return mMeasuredWidth; 9692 } 9693 9694 /** 9695 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9696 * raw width component (that is the result is masked by 9697 * {@link #MEASURED_SIZE_MASK}). 9698 * 9699 * @return The raw measured height of this view. 9700 */ 9701 public final int getMeasuredHeight() { 9702 return mMeasuredHeight & MEASURED_SIZE_MASK; 9703 } 9704 9705 /** 9706 * Return the full height measurement information for this view as computed 9707 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9708 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9709 * This should be used during measurement and layout calculations only. Use 9710 * {@link #getHeight()} to see how wide a view is after layout. 9711 * 9712 * @return The measured width of this view as a bit mask. 9713 */ 9714 public final int getMeasuredHeightAndState() { 9715 return mMeasuredHeight; 9716 } 9717 9718 /** 9719 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9720 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9721 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9722 * and the height component is at the shifted bits 9723 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9724 */ 9725 public final int getMeasuredState() { 9726 return (mMeasuredWidth&MEASURED_STATE_MASK) 9727 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9728 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9729 } 9730 9731 /** 9732 * The transform matrix of this view, which is calculated based on the current 9733 * rotation, scale, and pivot properties. 9734 * 9735 * @see #getRotation() 9736 * @see #getScaleX() 9737 * @see #getScaleY() 9738 * @see #getPivotX() 9739 * @see #getPivotY() 9740 * @return The current transform matrix for the view 9741 */ 9742 public Matrix getMatrix() { 9743 ensureTransformationInfo(); 9744 final Matrix matrix = mTransformationInfo.mMatrix; 9745 mRenderNode.getMatrix(matrix); 9746 return matrix; 9747 } 9748 9749 /** 9750 * Returns true if the transform matrix is the identity matrix. 9751 * Recomputes the matrix if necessary. 9752 * 9753 * @return True if the transform matrix is the identity matrix, false otherwise. 9754 */ 9755 final boolean hasIdentityMatrix() { 9756 return mRenderNode.hasIdentityMatrix(); 9757 } 9758 9759 void ensureTransformationInfo() { 9760 if (mTransformationInfo == null) { 9761 mTransformationInfo = new TransformationInfo(); 9762 } 9763 } 9764 9765 /** 9766 * Utility method to retrieve the inverse of the current mMatrix property. 9767 * We cache the matrix to avoid recalculating it when transform properties 9768 * have not changed. 9769 * 9770 * @return The inverse of the current matrix of this view. 9771 */ 9772 final Matrix getInverseMatrix() { 9773 ensureTransformationInfo(); 9774 if (mTransformationInfo.mInverseMatrix == null) { 9775 mTransformationInfo.mInverseMatrix = new Matrix(); 9776 } 9777 final Matrix matrix = mTransformationInfo.mInverseMatrix; 9778 mRenderNode.getInverseMatrix(matrix); 9779 return matrix; 9780 } 9781 9782 /** 9783 * Gets the distance along the Z axis from the camera to this view. 9784 * 9785 * @see #setCameraDistance(float) 9786 * 9787 * @return The distance along the Z axis. 9788 */ 9789 public float getCameraDistance() { 9790 final float dpi = mResources.getDisplayMetrics().densityDpi; 9791 return -(mRenderNode.getCameraDistance() * dpi); 9792 } 9793 9794 /** 9795 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9796 * views are drawn) from the camera to this view. The camera's distance 9797 * affects 3D transformations, for instance rotations around the X and Y 9798 * axis. If the rotationX or rotationY properties are changed and this view is 9799 * large (more than half the size of the screen), it is recommended to always 9800 * use a camera distance that's greater than the height (X axis rotation) or 9801 * the width (Y axis rotation) of this view.</p> 9802 * 9803 * <p>The distance of the camera from the view plane can have an affect on the 9804 * perspective distortion of the view when it is rotated around the x or y axis. 9805 * For example, a large distance will result in a large viewing angle, and there 9806 * will not be much perspective distortion of the view as it rotates. A short 9807 * distance may cause much more perspective distortion upon rotation, and can 9808 * also result in some drawing artifacts if the rotated view ends up partially 9809 * behind the camera (which is why the recommendation is to use a distance at 9810 * least as far as the size of the view, if the view is to be rotated.)</p> 9811 * 9812 * <p>The distance is expressed in "depth pixels." The default distance depends 9813 * on the screen density. For instance, on a medium density display, the 9814 * default distance is 1280. On a high density display, the default distance 9815 * is 1920.</p> 9816 * 9817 * <p>If you want to specify a distance that leads to visually consistent 9818 * results across various densities, use the following formula:</p> 9819 * <pre> 9820 * float scale = context.getResources().getDisplayMetrics().density; 9821 * view.setCameraDistance(distance * scale); 9822 * </pre> 9823 * 9824 * <p>The density scale factor of a high density display is 1.5, 9825 * and 1920 = 1280 * 1.5.</p> 9826 * 9827 * @param distance The distance in "depth pixels", if negative the opposite 9828 * value is used 9829 * 9830 * @see #setRotationX(float) 9831 * @see #setRotationY(float) 9832 */ 9833 public void setCameraDistance(float distance) { 9834 final float dpi = mResources.getDisplayMetrics().densityDpi; 9835 9836 invalidateViewProperty(true, false); 9837 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 9838 invalidateViewProperty(false, false); 9839 9840 invalidateParentIfNeededAndWasQuickRejected(); 9841 } 9842 9843 /** 9844 * The degrees that the view is rotated around the pivot point. 9845 * 9846 * @see #setRotation(float) 9847 * @see #getPivotX() 9848 * @see #getPivotY() 9849 * 9850 * @return The degrees of rotation. 9851 */ 9852 @ViewDebug.ExportedProperty(category = "drawing") 9853 public float getRotation() { 9854 return mRenderNode.getRotation(); 9855 } 9856 9857 /** 9858 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9859 * result in clockwise rotation. 9860 * 9861 * @param rotation The degrees of rotation. 9862 * 9863 * @see #getRotation() 9864 * @see #getPivotX() 9865 * @see #getPivotY() 9866 * @see #setRotationX(float) 9867 * @see #setRotationY(float) 9868 * 9869 * @attr ref android.R.styleable#View_rotation 9870 */ 9871 public void setRotation(float rotation) { 9872 if (rotation != getRotation()) { 9873 // Double-invalidation is necessary to capture view's old and new areas 9874 invalidateViewProperty(true, false); 9875 mRenderNode.setRotation(rotation); 9876 invalidateViewProperty(false, true); 9877 9878 invalidateParentIfNeededAndWasQuickRejected(); 9879 notifySubtreeAccessibilityStateChangedIfNeeded(); 9880 } 9881 } 9882 9883 /** 9884 * The degrees that the view is rotated around the vertical axis through the pivot point. 9885 * 9886 * @see #getPivotX() 9887 * @see #getPivotY() 9888 * @see #setRotationY(float) 9889 * 9890 * @return The degrees of Y rotation. 9891 */ 9892 @ViewDebug.ExportedProperty(category = "drawing") 9893 public float getRotationY() { 9894 return mRenderNode.getRotationY(); 9895 } 9896 9897 /** 9898 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9899 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9900 * down the y axis. 9901 * 9902 * When rotating large views, it is recommended to adjust the camera distance 9903 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9904 * 9905 * @param rotationY The degrees of Y rotation. 9906 * 9907 * @see #getRotationY() 9908 * @see #getPivotX() 9909 * @see #getPivotY() 9910 * @see #setRotation(float) 9911 * @see #setRotationX(float) 9912 * @see #setCameraDistance(float) 9913 * 9914 * @attr ref android.R.styleable#View_rotationY 9915 */ 9916 public void setRotationY(float rotationY) { 9917 if (rotationY != getRotationY()) { 9918 invalidateViewProperty(true, false); 9919 mRenderNode.setRotationY(rotationY); 9920 invalidateViewProperty(false, true); 9921 9922 invalidateParentIfNeededAndWasQuickRejected(); 9923 notifySubtreeAccessibilityStateChangedIfNeeded(); 9924 } 9925 } 9926 9927 /** 9928 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9929 * 9930 * @see #getPivotX() 9931 * @see #getPivotY() 9932 * @see #setRotationX(float) 9933 * 9934 * @return The degrees of X rotation. 9935 */ 9936 @ViewDebug.ExportedProperty(category = "drawing") 9937 public float getRotationX() { 9938 return mRenderNode.getRotationX(); 9939 } 9940 9941 /** 9942 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9943 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9944 * x axis. 9945 * 9946 * When rotating large views, it is recommended to adjust the camera distance 9947 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9948 * 9949 * @param rotationX The degrees of X rotation. 9950 * 9951 * @see #getRotationX() 9952 * @see #getPivotX() 9953 * @see #getPivotY() 9954 * @see #setRotation(float) 9955 * @see #setRotationY(float) 9956 * @see #setCameraDistance(float) 9957 * 9958 * @attr ref android.R.styleable#View_rotationX 9959 */ 9960 public void setRotationX(float rotationX) { 9961 if (rotationX != getRotationX()) { 9962 invalidateViewProperty(true, false); 9963 mRenderNode.setRotationX(rotationX); 9964 invalidateViewProperty(false, true); 9965 9966 invalidateParentIfNeededAndWasQuickRejected(); 9967 notifySubtreeAccessibilityStateChangedIfNeeded(); 9968 } 9969 } 9970 9971 /** 9972 * The amount that the view is scaled in x around the pivot point, as a proportion of 9973 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9974 * 9975 * <p>By default, this is 1.0f. 9976 * 9977 * @see #getPivotX() 9978 * @see #getPivotY() 9979 * @return The scaling factor. 9980 */ 9981 @ViewDebug.ExportedProperty(category = "drawing") 9982 public float getScaleX() { 9983 return mRenderNode.getScaleX(); 9984 } 9985 9986 /** 9987 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9988 * the view's unscaled width. A value of 1 means that no scaling is applied. 9989 * 9990 * @param scaleX The scaling factor. 9991 * @see #getPivotX() 9992 * @see #getPivotY() 9993 * 9994 * @attr ref android.R.styleable#View_scaleX 9995 */ 9996 public void setScaleX(float scaleX) { 9997 if (scaleX != getScaleX()) { 9998 invalidateViewProperty(true, false); 9999 mRenderNode.setScaleX(scaleX); 10000 invalidateViewProperty(false, true); 10001 10002 invalidateParentIfNeededAndWasQuickRejected(); 10003 notifySubtreeAccessibilityStateChangedIfNeeded(); 10004 } 10005 } 10006 10007 /** 10008 * The amount that the view is scaled in y around the pivot point, as a proportion of 10009 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 10010 * 10011 * <p>By default, this is 1.0f. 10012 * 10013 * @see #getPivotX() 10014 * @see #getPivotY() 10015 * @return The scaling factor. 10016 */ 10017 @ViewDebug.ExportedProperty(category = "drawing") 10018 public float getScaleY() { 10019 return mRenderNode.getScaleY(); 10020 } 10021 10022 /** 10023 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 10024 * the view's unscaled width. A value of 1 means that no scaling is applied. 10025 * 10026 * @param scaleY The scaling factor. 10027 * @see #getPivotX() 10028 * @see #getPivotY() 10029 * 10030 * @attr ref android.R.styleable#View_scaleY 10031 */ 10032 public void setScaleY(float scaleY) { 10033 if (scaleY != getScaleY()) { 10034 invalidateViewProperty(true, false); 10035 mRenderNode.setScaleY(scaleY); 10036 invalidateViewProperty(false, true); 10037 10038 invalidateParentIfNeededAndWasQuickRejected(); 10039 notifySubtreeAccessibilityStateChangedIfNeeded(); 10040 } 10041 } 10042 10043 /** 10044 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10045 * and {@link #setScaleX(float) scaled}. 10046 * 10047 * @see #getRotation() 10048 * @see #getScaleX() 10049 * @see #getScaleY() 10050 * @see #getPivotY() 10051 * @return The x location of the pivot point. 10052 * 10053 * @attr ref android.R.styleable#View_transformPivotX 10054 */ 10055 @ViewDebug.ExportedProperty(category = "drawing") 10056 public float getPivotX() { 10057 return mRenderNode.getPivotX(); 10058 } 10059 10060 /** 10061 * Sets the x location of the point around which the view is 10062 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10063 * By default, the pivot point is centered on the object. 10064 * Setting this property disables this behavior and causes the view to use only the 10065 * explicitly set pivotX and pivotY values. 10066 * 10067 * @param pivotX The x location of the pivot point. 10068 * @see #getRotation() 10069 * @see #getScaleX() 10070 * @see #getScaleY() 10071 * @see #getPivotY() 10072 * 10073 * @attr ref android.R.styleable#View_transformPivotX 10074 */ 10075 public void setPivotX(float pivotX) { 10076 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10077 invalidateViewProperty(true, false); 10078 mRenderNode.setPivotX(pivotX); 10079 invalidateViewProperty(false, true); 10080 10081 invalidateParentIfNeededAndWasQuickRejected(); 10082 } 10083 } 10084 10085 /** 10086 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10087 * and {@link #setScaleY(float) scaled}. 10088 * 10089 * @see #getRotation() 10090 * @see #getScaleX() 10091 * @see #getScaleY() 10092 * @see #getPivotY() 10093 * @return The y location of the pivot point. 10094 * 10095 * @attr ref android.R.styleable#View_transformPivotY 10096 */ 10097 @ViewDebug.ExportedProperty(category = "drawing") 10098 public float getPivotY() { 10099 return mRenderNode.getPivotY(); 10100 } 10101 10102 /** 10103 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10104 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10105 * Setting this property disables this behavior and causes the view to use only the 10106 * explicitly set pivotX and pivotY values. 10107 * 10108 * @param pivotY The y location of the pivot point. 10109 * @see #getRotation() 10110 * @see #getScaleX() 10111 * @see #getScaleY() 10112 * @see #getPivotY() 10113 * 10114 * @attr ref android.R.styleable#View_transformPivotY 10115 */ 10116 public void setPivotY(float pivotY) { 10117 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10118 invalidateViewProperty(true, false); 10119 mRenderNode.setPivotY(pivotY); 10120 invalidateViewProperty(false, true); 10121 10122 invalidateParentIfNeededAndWasQuickRejected(); 10123 } 10124 } 10125 10126 /** 10127 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10128 * completely transparent and 1 means the view is completely opaque. 10129 * 10130 * <p>By default this is 1.0f. 10131 * @return The opacity of the view. 10132 */ 10133 @ViewDebug.ExportedProperty(category = "drawing") 10134 public float getAlpha() { 10135 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10136 } 10137 10138 /** 10139 * Returns whether this View has content which overlaps. 10140 * 10141 * <p>This function, intended to be overridden by specific View types, is an optimization when 10142 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10143 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10144 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10145 * directly. An example of overlapping rendering is a TextView with a background image, such as 10146 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10147 * ImageView with only the foreground image. The default implementation returns true; subclasses 10148 * should override if they have cases which can be optimized.</p> 10149 * 10150 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10151 * necessitates that a View return true if it uses the methods internally without passing the 10152 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10153 * 10154 * @return true if the content in this view might overlap, false otherwise. 10155 */ 10156 public boolean hasOverlappingRendering() { 10157 return true; 10158 } 10159 10160 /** 10161 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10162 * completely transparent and 1 means the view is completely opaque.</p> 10163 * 10164 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10165 * performance implications, especially for large views. It is best to use the alpha property 10166 * sparingly and transiently, as in the case of fading animations.</p> 10167 * 10168 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10169 * strongly recommended for performance reasons to either override 10170 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10171 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10172 * 10173 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10174 * responsible for applying the opacity itself.</p> 10175 * 10176 * <p>Note that if the view is backed by a 10177 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10178 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10179 * 1.0 will supercede the alpha of the layer paint.</p> 10180 * 10181 * @param alpha The opacity of the view. 10182 * 10183 * @see #hasOverlappingRendering() 10184 * @see #setLayerType(int, android.graphics.Paint) 10185 * 10186 * @attr ref android.R.styleable#View_alpha 10187 */ 10188 public void setAlpha(float alpha) { 10189 ensureTransformationInfo(); 10190 if (mTransformationInfo.mAlpha != alpha) { 10191 mTransformationInfo.mAlpha = alpha; 10192 if (onSetAlpha((int) (alpha * 255))) { 10193 mPrivateFlags |= PFLAG_ALPHA_SET; 10194 // subclass is handling alpha - don't optimize rendering cache invalidation 10195 invalidateParentCaches(); 10196 invalidate(true); 10197 } else { 10198 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10199 invalidateViewProperty(true, false); 10200 mRenderNode.setAlpha(getFinalAlpha()); 10201 notifyViewAccessibilityStateChangedIfNeeded( 10202 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10203 } 10204 } 10205 } 10206 10207 /** 10208 * Faster version of setAlpha() which performs the same steps except there are 10209 * no calls to invalidate(). The caller of this function should perform proper invalidation 10210 * on the parent and this object. The return value indicates whether the subclass handles 10211 * alpha (the return value for onSetAlpha()). 10212 * 10213 * @param alpha The new value for the alpha property 10214 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10215 * the new value for the alpha property is different from the old value 10216 */ 10217 boolean setAlphaNoInvalidation(float alpha) { 10218 ensureTransformationInfo(); 10219 if (mTransformationInfo.mAlpha != alpha) { 10220 mTransformationInfo.mAlpha = alpha; 10221 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10222 if (subclassHandlesAlpha) { 10223 mPrivateFlags |= PFLAG_ALPHA_SET; 10224 return true; 10225 } else { 10226 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10227 mRenderNode.setAlpha(getFinalAlpha()); 10228 } 10229 } 10230 return false; 10231 } 10232 10233 /** 10234 * This property is hidden and intended only for use by the Fade transition, which 10235 * animates it to produce a visual translucency that does not side-effect (or get 10236 * affected by) the real alpha property. This value is composited with the other 10237 * alpha value (and the AlphaAnimation value, when that is present) to produce 10238 * a final visual translucency result, which is what is passed into the DisplayList. 10239 * 10240 * @hide 10241 */ 10242 public void setTransitionAlpha(float alpha) { 10243 ensureTransformationInfo(); 10244 if (mTransformationInfo.mTransitionAlpha != alpha) { 10245 mTransformationInfo.mTransitionAlpha = alpha; 10246 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10247 invalidateViewProperty(true, false); 10248 mRenderNode.setAlpha(getFinalAlpha()); 10249 } 10250 } 10251 10252 /** 10253 * Calculates the visual alpha of this view, which is a combination of the actual 10254 * alpha value and the transitionAlpha value (if set). 10255 */ 10256 private float getFinalAlpha() { 10257 if (mTransformationInfo != null) { 10258 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10259 } 10260 return 1; 10261 } 10262 10263 /** 10264 * This property is hidden and intended only for use by the Fade transition, which 10265 * animates it to produce a visual translucency that does not side-effect (or get 10266 * affected by) the real alpha property. This value is composited with the other 10267 * alpha value (and the AlphaAnimation value, when that is present) to produce 10268 * a final visual translucency result, which is what is passed into the DisplayList. 10269 * 10270 * @hide 10271 */ 10272 public float getTransitionAlpha() { 10273 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10274 } 10275 10276 /** 10277 * Top position of this view relative to its parent. 10278 * 10279 * @return The top of this view, in pixels. 10280 */ 10281 @ViewDebug.CapturedViewProperty 10282 public final int getTop() { 10283 return mTop; 10284 } 10285 10286 /** 10287 * Sets the top position of this view relative to its parent. This method is meant to be called 10288 * by the layout system and should not generally be called otherwise, because the property 10289 * may be changed at any time by the layout. 10290 * 10291 * @param top The top of this view, in pixels. 10292 */ 10293 public final void setTop(int top) { 10294 if (top != mTop) { 10295 final boolean matrixIsIdentity = hasIdentityMatrix(); 10296 if (matrixIsIdentity) { 10297 if (mAttachInfo != null) { 10298 int minTop; 10299 int yLoc; 10300 if (top < mTop) { 10301 minTop = top; 10302 yLoc = top - mTop; 10303 } else { 10304 minTop = mTop; 10305 yLoc = 0; 10306 } 10307 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10308 } 10309 } else { 10310 // Double-invalidation is necessary to capture view's old and new areas 10311 invalidate(true); 10312 } 10313 10314 int width = mRight - mLeft; 10315 int oldHeight = mBottom - mTop; 10316 10317 mTop = top; 10318 mRenderNode.setTop(mTop); 10319 10320 sizeChange(width, mBottom - mTop, width, oldHeight); 10321 10322 if (!matrixIsIdentity) { 10323 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10324 invalidate(true); 10325 } 10326 mBackgroundSizeChanged = true; 10327 invalidateParentIfNeeded(); 10328 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10329 // View was rejected last time it was drawn by its parent; this may have changed 10330 invalidateParentIfNeeded(); 10331 } 10332 } 10333 } 10334 10335 /** 10336 * Bottom position of this view relative to its parent. 10337 * 10338 * @return The bottom of this view, in pixels. 10339 */ 10340 @ViewDebug.CapturedViewProperty 10341 public final int getBottom() { 10342 return mBottom; 10343 } 10344 10345 /** 10346 * True if this view has changed since the last time being drawn. 10347 * 10348 * @return The dirty state of this view. 10349 */ 10350 public boolean isDirty() { 10351 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10352 } 10353 10354 /** 10355 * Sets the bottom position of this view relative to its parent. This method is meant to be 10356 * called by the layout system and should not generally be called otherwise, because the 10357 * property may be changed at any time by the layout. 10358 * 10359 * @param bottom The bottom of this view, in pixels. 10360 */ 10361 public final void setBottom(int bottom) { 10362 if (bottom != mBottom) { 10363 final boolean matrixIsIdentity = hasIdentityMatrix(); 10364 if (matrixIsIdentity) { 10365 if (mAttachInfo != null) { 10366 int maxBottom; 10367 if (bottom < mBottom) { 10368 maxBottom = mBottom; 10369 } else { 10370 maxBottom = bottom; 10371 } 10372 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10373 } 10374 } else { 10375 // Double-invalidation is necessary to capture view's old and new areas 10376 invalidate(true); 10377 } 10378 10379 int width = mRight - mLeft; 10380 int oldHeight = mBottom - mTop; 10381 10382 mBottom = bottom; 10383 mRenderNode.setBottom(mBottom); 10384 10385 sizeChange(width, mBottom - mTop, width, oldHeight); 10386 10387 if (!matrixIsIdentity) { 10388 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10389 invalidate(true); 10390 } 10391 mBackgroundSizeChanged = true; 10392 invalidateParentIfNeeded(); 10393 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10394 // View was rejected last time it was drawn by its parent; this may have changed 10395 invalidateParentIfNeeded(); 10396 } 10397 } 10398 } 10399 10400 /** 10401 * Left position of this view relative to its parent. 10402 * 10403 * @return The left edge of this view, in pixels. 10404 */ 10405 @ViewDebug.CapturedViewProperty 10406 public final int getLeft() { 10407 return mLeft; 10408 } 10409 10410 /** 10411 * Sets the left position of this view relative to its parent. This method is meant to be called 10412 * by the layout system and should not generally be called otherwise, because the property 10413 * may be changed at any time by the layout. 10414 * 10415 * @param left The left of this view, in pixels. 10416 */ 10417 public final void setLeft(int left) { 10418 if (left != mLeft) { 10419 final boolean matrixIsIdentity = hasIdentityMatrix(); 10420 if (matrixIsIdentity) { 10421 if (mAttachInfo != null) { 10422 int minLeft; 10423 int xLoc; 10424 if (left < mLeft) { 10425 minLeft = left; 10426 xLoc = left - mLeft; 10427 } else { 10428 minLeft = mLeft; 10429 xLoc = 0; 10430 } 10431 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10432 } 10433 } else { 10434 // Double-invalidation is necessary to capture view's old and new areas 10435 invalidate(true); 10436 } 10437 10438 int oldWidth = mRight - mLeft; 10439 int height = mBottom - mTop; 10440 10441 mLeft = left; 10442 mRenderNode.setLeft(left); 10443 10444 sizeChange(mRight - mLeft, height, oldWidth, height); 10445 10446 if (!matrixIsIdentity) { 10447 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10448 invalidate(true); 10449 } 10450 mBackgroundSizeChanged = true; 10451 invalidateParentIfNeeded(); 10452 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10453 // View was rejected last time it was drawn by its parent; this may have changed 10454 invalidateParentIfNeeded(); 10455 } 10456 } 10457 } 10458 10459 /** 10460 * Right position of this view relative to its parent. 10461 * 10462 * @return The right edge of this view, in pixels. 10463 */ 10464 @ViewDebug.CapturedViewProperty 10465 public final int getRight() { 10466 return mRight; 10467 } 10468 10469 /** 10470 * Sets the right position of this view relative to its parent. This method is meant to be called 10471 * by the layout system and should not generally be called otherwise, because the property 10472 * may be changed at any time by the layout. 10473 * 10474 * @param right The right of this view, in pixels. 10475 */ 10476 public final void setRight(int right) { 10477 if (right != mRight) { 10478 final boolean matrixIsIdentity = hasIdentityMatrix(); 10479 if (matrixIsIdentity) { 10480 if (mAttachInfo != null) { 10481 int maxRight; 10482 if (right < mRight) { 10483 maxRight = mRight; 10484 } else { 10485 maxRight = right; 10486 } 10487 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10488 } 10489 } else { 10490 // Double-invalidation is necessary to capture view's old and new areas 10491 invalidate(true); 10492 } 10493 10494 int oldWidth = mRight - mLeft; 10495 int height = mBottom - mTop; 10496 10497 mRight = right; 10498 mRenderNode.setRight(mRight); 10499 10500 sizeChange(mRight - mLeft, height, oldWidth, height); 10501 10502 if (!matrixIsIdentity) { 10503 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10504 invalidate(true); 10505 } 10506 mBackgroundSizeChanged = true; 10507 invalidateParentIfNeeded(); 10508 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10509 // View was rejected last time it was drawn by its parent; this may have changed 10510 invalidateParentIfNeeded(); 10511 } 10512 } 10513 } 10514 10515 /** 10516 * The visual x position of this view, in pixels. This is equivalent to the 10517 * {@link #setTranslationX(float) translationX} property plus the current 10518 * {@link #getLeft() left} property. 10519 * 10520 * @return The visual x position of this view, in pixels. 10521 */ 10522 @ViewDebug.ExportedProperty(category = "drawing") 10523 public float getX() { 10524 return mLeft + getTranslationX(); 10525 } 10526 10527 /** 10528 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10529 * {@link #setTranslationX(float) translationX} property to be the difference between 10530 * the x value passed in and the current {@link #getLeft() left} property. 10531 * 10532 * @param x The visual x position of this view, in pixels. 10533 */ 10534 public void setX(float x) { 10535 setTranslationX(x - mLeft); 10536 } 10537 10538 /** 10539 * The visual y position of this view, in pixels. This is equivalent to the 10540 * {@link #setTranslationY(float) translationY} property plus the current 10541 * {@link #getTop() top} property. 10542 * 10543 * @return The visual y position of this view, in pixels. 10544 */ 10545 @ViewDebug.ExportedProperty(category = "drawing") 10546 public float getY() { 10547 return mTop + getTranslationY(); 10548 } 10549 10550 /** 10551 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10552 * {@link #setTranslationY(float) translationY} property to be the difference between 10553 * the y value passed in and the current {@link #getTop() top} property. 10554 * 10555 * @param y The visual y position of this view, in pixels. 10556 */ 10557 public void setY(float y) { 10558 setTranslationY(y - mTop); 10559 } 10560 10561 /** 10562 * The visual z position of this view, in pixels. This is equivalent to the 10563 * {@link #setTranslationZ(float) translationZ} property plus the current 10564 * {@link #getElevation() elevation} property. 10565 * 10566 * @return The visual z position of this view, in pixels. 10567 */ 10568 @ViewDebug.ExportedProperty(category = "drawing") 10569 public float getZ() { 10570 return getElevation() + getTranslationZ(); 10571 } 10572 10573 /** 10574 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10575 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10576 * the x value passed in and the current {@link #getElevation() elevation} property. 10577 * 10578 * @param z The visual z position of this view, in pixels. 10579 */ 10580 public void setZ(float z) { 10581 setTranslationZ(z - getElevation()); 10582 } 10583 10584 /** 10585 * The base elevation of this view relative to its parent, in pixels. 10586 * 10587 * @return The base depth position of the view, in pixels. 10588 */ 10589 @ViewDebug.ExportedProperty(category = "drawing") 10590 public float getElevation() { 10591 return mRenderNode.getElevation(); 10592 } 10593 10594 /** 10595 * Sets the base elevation of this view, in pixels. 10596 * 10597 * @attr ref android.R.styleable#View_elevation 10598 */ 10599 public void setElevation(float elevation) { 10600 if (elevation != getElevation()) { 10601 invalidateViewProperty(true, false); 10602 mRenderNode.setElevation(elevation); 10603 invalidateViewProperty(false, true); 10604 10605 invalidateParentIfNeededAndWasQuickRejected(); 10606 } 10607 } 10608 10609 /** 10610 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10611 * This position is post-layout, in addition to wherever the object's 10612 * layout placed it. 10613 * 10614 * @return The horizontal position of this view relative to its left position, in pixels. 10615 */ 10616 @ViewDebug.ExportedProperty(category = "drawing") 10617 public float getTranslationX() { 10618 return mRenderNode.getTranslationX(); 10619 } 10620 10621 /** 10622 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10623 * This effectively positions the object post-layout, in addition to wherever the object's 10624 * layout placed it. 10625 * 10626 * @param translationX The horizontal position of this view relative to its left position, 10627 * in pixels. 10628 * 10629 * @attr ref android.R.styleable#View_translationX 10630 */ 10631 public void setTranslationX(float translationX) { 10632 if (translationX != getTranslationX()) { 10633 invalidateViewProperty(true, false); 10634 mRenderNode.setTranslationX(translationX); 10635 invalidateViewProperty(false, true); 10636 10637 invalidateParentIfNeededAndWasQuickRejected(); 10638 notifySubtreeAccessibilityStateChangedIfNeeded(); 10639 } 10640 } 10641 10642 /** 10643 * The vertical location of this view relative to its {@link #getTop() top} position. 10644 * This position is post-layout, in addition to wherever the object's 10645 * layout placed it. 10646 * 10647 * @return The vertical position of this view relative to its top position, 10648 * in pixels. 10649 */ 10650 @ViewDebug.ExportedProperty(category = "drawing") 10651 public float getTranslationY() { 10652 return mRenderNode.getTranslationY(); 10653 } 10654 10655 /** 10656 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10657 * This effectively positions the object post-layout, in addition to wherever the object's 10658 * layout placed it. 10659 * 10660 * @param translationY The vertical position of this view relative to its top position, 10661 * in pixels. 10662 * 10663 * @attr ref android.R.styleable#View_translationY 10664 */ 10665 public void setTranslationY(float translationY) { 10666 if (translationY != getTranslationY()) { 10667 invalidateViewProperty(true, false); 10668 mRenderNode.setTranslationY(translationY); 10669 invalidateViewProperty(false, true); 10670 10671 invalidateParentIfNeededAndWasQuickRejected(); 10672 } 10673 } 10674 10675 /** 10676 * The depth location of this view relative to its {@link #getElevation() elevation}. 10677 * 10678 * @return The depth of this view relative to its elevation. 10679 */ 10680 @ViewDebug.ExportedProperty(category = "drawing") 10681 public float getTranslationZ() { 10682 return mRenderNode.getTranslationZ(); 10683 } 10684 10685 /** 10686 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 10687 * 10688 * @attr ref android.R.styleable#View_translationZ 10689 */ 10690 public void setTranslationZ(float translationZ) { 10691 if (translationZ != getTranslationZ()) { 10692 invalidateViewProperty(true, false); 10693 mRenderNode.setTranslationZ(translationZ); 10694 invalidateViewProperty(false, true); 10695 10696 invalidateParentIfNeededAndWasQuickRejected(); 10697 } 10698 } 10699 10700 /** 10701 * Returns a ValueAnimator which can animate a clearing circle. 10702 * <p> 10703 * The View is prevented from drawing within the circle, so the content 10704 * behind the View shows through. 10705 * 10706 * @param centerX The x coordinate of the center of the animating circle. 10707 * @param centerY The y coordinate of the center of the animating circle. 10708 * @param startRadius The starting radius of the animating circle. 10709 * @param endRadius The ending radius of the animating circle. 10710 * 10711 * @hide 10712 */ 10713 public final ValueAnimator createClearCircleAnimator(int centerX, int centerY, 10714 float startRadius, float endRadius) { 10715 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10716 startRadius, endRadius, true); 10717 } 10718 10719 /** 10720 * Returns the current StateListAnimator if exists. 10721 * 10722 * @return StateListAnimator or null if it does not exists 10723 * @see #setStateListAnimator(android.animation.StateListAnimator) 10724 */ 10725 public StateListAnimator getStateListAnimator() { 10726 return mStateListAnimator; 10727 } 10728 10729 /** 10730 * Attaches the provided StateListAnimator to this View. 10731 * <p> 10732 * Any previously attached StateListAnimator will be detached. 10733 * 10734 * @param stateListAnimator The StateListAnimator to update the view 10735 * @see {@link android.animation.StateListAnimator} 10736 */ 10737 public void setStateListAnimator(StateListAnimator stateListAnimator) { 10738 if (mStateListAnimator == stateListAnimator) { 10739 return; 10740 } 10741 if (mStateListAnimator != null) { 10742 mStateListAnimator.setTarget(null); 10743 } 10744 mStateListAnimator = stateListAnimator; 10745 if (stateListAnimator != null) { 10746 stateListAnimator.setTarget(this); 10747 if (isAttachedToWindow()) { 10748 stateListAnimator.setState(getDrawableState()); 10749 } 10750 } 10751 } 10752 10753 @Deprecated 10754 public void setOutline(@Nullable Outline outline) { 10755 mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED; 10756 10757 if (outline == null || outline.isEmpty()) { 10758 if (mOutline != null) { 10759 mOutline.setEmpty(); 10760 } 10761 } else { 10762 // always copy the path since caller may reuse 10763 if (mOutline == null) { 10764 mOutline = new Outline(); 10765 } 10766 mOutline.set(outline); 10767 } 10768 mRenderNode.setOutline(mOutline); 10769 } 10770 10771 /** 10772 * Returns whether the Outline should be used to clip the contents of the View. 10773 * <p> 10774 * Note that this flag will only be respected if the View's Outline returns true from 10775 * {@link Outline#canClip()}. 10776 * 10777 * @see #setOutlineProvider(ViewOutlineProvider) 10778 * @see #setClipToOutline(boolean) 10779 */ 10780 public final boolean getClipToOutline() { 10781 return mRenderNode.getClipToOutline(); 10782 } 10783 10784 /** 10785 * Sets whether the View's Outline should be used to clip the contents of the View. 10786 * <p> 10787 * Note that this flag will only be respected if the View's Outline returns true from 10788 * {@link Outline#canClip()}. 10789 * 10790 * @see #setOutlineProvider(ViewOutlineProvider) 10791 * @see #getClipToOutline() 10792 */ 10793 public void setClipToOutline(boolean clipToOutline) { 10794 damageInParent(); 10795 if (getClipToOutline() != clipToOutline) { 10796 mRenderNode.setClipToOutline(clipToOutline); 10797 } 10798 } 10799 10800 /** 10801 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 10802 * the shape of the shadow it casts, and enables outline clipping. 10803 * <p> 10804 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 10805 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 10806 * outline provider with this method allows this behavior to be overridden. 10807 * <p> 10808 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 10809 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 10810 * <p> 10811 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 10812 * 10813 * @see #setClipToOutline(boolean) 10814 * @see #getClipToOutline() 10815 * @see #getOutlineProvider() 10816 */ 10817 public void setOutlineProvider(ViewOutlineProvider provider) { 10818 mOutlineProvider = provider; 10819 invalidateOutline(); 10820 } 10821 10822 /** 10823 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 10824 * that defines the shape of the shadow it casts, and enables outline clipping. 10825 * 10826 * @see #setOutlineProvider(ViewOutlineProvider) 10827 */ 10828 public ViewOutlineProvider getOutlineProvider() { 10829 return mOutlineProvider; 10830 } 10831 10832 /** 10833 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 10834 * 10835 * @see #setOutlineProvider(ViewOutlineProvider) 10836 */ 10837 public void invalidateOutline() { 10838 if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) != 0) { 10839 // TODO: remove this when removing old outline code 10840 // setOutline() was called to manually set outline, ignore provider 10841 return; 10842 } 10843 10844 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 10845 if (mAttachInfo == null) return; 10846 10847 final Outline outline = mAttachInfo.mTmpOutline; 10848 outline.setEmpty(); 10849 10850 if (mOutlineProvider == null) { 10851 // no provider, remove outline 10852 mRenderNode.setOutline(null); 10853 } else { 10854 if (mOutlineProvider.getOutline(this, outline)) { 10855 if (outline.isEmpty()) { 10856 throw new IllegalStateException("Outline provider failed to build outline"); 10857 } 10858 // provider has provided 10859 mRenderNode.setOutline(outline); 10860 } else { 10861 // provider failed to provide 10862 mRenderNode.setOutline(null); 10863 } 10864 } 10865 10866 notifySubtreeAccessibilityStateChangedIfNeeded(); 10867 invalidateViewProperty(false, false); 10868 } 10869 10870 /** 10871 * Private API to be used for reveal animation 10872 * 10873 * @hide 10874 */ 10875 public void setRevealClip(boolean shouldClip, boolean inverseClip, 10876 float x, float y, float radius) { 10877 mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius); 10878 // TODO: Handle this invalidate in a better way, or purely in native. 10879 invalidate(); 10880 } 10881 10882 /** 10883 * Hit rectangle in parent's coordinates 10884 * 10885 * @param outRect The hit rectangle of the view. 10886 */ 10887 public void getHitRect(Rect outRect) { 10888 if (hasIdentityMatrix() || mAttachInfo == null) { 10889 outRect.set(mLeft, mTop, mRight, mBottom); 10890 } else { 10891 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10892 tmpRect.set(0, 0, getWidth(), getHeight()); 10893 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 10894 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10895 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10896 } 10897 } 10898 10899 /** 10900 * Determines whether the given point, in local coordinates is inside the view. 10901 */ 10902 /*package*/ final boolean pointInView(float localX, float localY) { 10903 return localX >= 0 && localX < (mRight - mLeft) 10904 && localY >= 0 && localY < (mBottom - mTop); 10905 } 10906 10907 /** 10908 * Utility method to determine whether the given point, in local coordinates, 10909 * is inside the view, where the area of the view is expanded by the slop factor. 10910 * This method is called while processing touch-move events to determine if the event 10911 * is still within the view. 10912 * 10913 * @hide 10914 */ 10915 public boolean pointInView(float localX, float localY, float slop) { 10916 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10917 localY < ((mBottom - mTop) + slop); 10918 } 10919 10920 /** 10921 * When a view has focus and the user navigates away from it, the next view is searched for 10922 * starting from the rectangle filled in by this method. 10923 * 10924 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10925 * of the view. However, if your view maintains some idea of internal selection, 10926 * such as a cursor, or a selected row or column, you should override this method and 10927 * fill in a more specific rectangle. 10928 * 10929 * @param r The rectangle to fill in, in this view's coordinates. 10930 */ 10931 public void getFocusedRect(Rect r) { 10932 getDrawingRect(r); 10933 } 10934 10935 /** 10936 * If some part of this view is not clipped by any of its parents, then 10937 * return that area in r in global (root) coordinates. To convert r to local 10938 * coordinates (without taking possible View rotations into account), offset 10939 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10940 * If the view is completely clipped or translated out, return false. 10941 * 10942 * @param r If true is returned, r holds the global coordinates of the 10943 * visible portion of this view. 10944 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10945 * between this view and its root. globalOffet may be null. 10946 * @return true if r is non-empty (i.e. part of the view is visible at the 10947 * root level. 10948 */ 10949 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10950 int width = mRight - mLeft; 10951 int height = mBottom - mTop; 10952 if (width > 0 && height > 0) { 10953 r.set(0, 0, width, height); 10954 if (globalOffset != null) { 10955 globalOffset.set(-mScrollX, -mScrollY); 10956 } 10957 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10958 } 10959 return false; 10960 } 10961 10962 public final boolean getGlobalVisibleRect(Rect r) { 10963 return getGlobalVisibleRect(r, null); 10964 } 10965 10966 public final boolean getLocalVisibleRect(Rect r) { 10967 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10968 if (getGlobalVisibleRect(r, offset)) { 10969 r.offset(-offset.x, -offset.y); // make r local 10970 return true; 10971 } 10972 return false; 10973 } 10974 10975 /** 10976 * Offset this view's vertical location by the specified number of pixels. 10977 * 10978 * @param offset the number of pixels to offset the view by 10979 */ 10980 public void offsetTopAndBottom(int offset) { 10981 if (offset != 0) { 10982 final boolean matrixIsIdentity = hasIdentityMatrix(); 10983 if (matrixIsIdentity) { 10984 if (isHardwareAccelerated()) { 10985 invalidateViewProperty(false, false); 10986 } else { 10987 final ViewParent p = mParent; 10988 if (p != null && mAttachInfo != null) { 10989 final Rect r = mAttachInfo.mTmpInvalRect; 10990 int minTop; 10991 int maxBottom; 10992 int yLoc; 10993 if (offset < 0) { 10994 minTop = mTop + offset; 10995 maxBottom = mBottom; 10996 yLoc = offset; 10997 } else { 10998 minTop = mTop; 10999 maxBottom = mBottom + offset; 11000 yLoc = 0; 11001 } 11002 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 11003 p.invalidateChild(this, r); 11004 } 11005 } 11006 } else { 11007 invalidateViewProperty(false, false); 11008 } 11009 11010 mTop += offset; 11011 mBottom += offset; 11012 mRenderNode.offsetTopAndBottom(offset); 11013 if (isHardwareAccelerated()) { 11014 invalidateViewProperty(false, false); 11015 } else { 11016 if (!matrixIsIdentity) { 11017 invalidateViewProperty(false, true); 11018 } 11019 invalidateParentIfNeeded(); 11020 } 11021 notifySubtreeAccessibilityStateChangedIfNeeded(); 11022 } 11023 } 11024 11025 /** 11026 * Offset this view's horizontal location by the specified amount of pixels. 11027 * 11028 * @param offset the number of pixels to offset the view by 11029 */ 11030 public void offsetLeftAndRight(int offset) { 11031 if (offset != 0) { 11032 final boolean matrixIsIdentity = hasIdentityMatrix(); 11033 if (matrixIsIdentity) { 11034 if (isHardwareAccelerated()) { 11035 invalidateViewProperty(false, false); 11036 } else { 11037 final ViewParent p = mParent; 11038 if (p != null && mAttachInfo != null) { 11039 final Rect r = mAttachInfo.mTmpInvalRect; 11040 int minLeft; 11041 int maxRight; 11042 if (offset < 0) { 11043 minLeft = mLeft + offset; 11044 maxRight = mRight; 11045 } else { 11046 minLeft = mLeft; 11047 maxRight = mRight + offset; 11048 } 11049 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 11050 p.invalidateChild(this, r); 11051 } 11052 } 11053 } else { 11054 invalidateViewProperty(false, false); 11055 } 11056 11057 mLeft += offset; 11058 mRight += offset; 11059 mRenderNode.offsetLeftAndRight(offset); 11060 if (isHardwareAccelerated()) { 11061 invalidateViewProperty(false, false); 11062 } else { 11063 if (!matrixIsIdentity) { 11064 invalidateViewProperty(false, true); 11065 } 11066 invalidateParentIfNeeded(); 11067 } 11068 notifySubtreeAccessibilityStateChangedIfNeeded(); 11069 } 11070 } 11071 11072 /** 11073 * Get the LayoutParams associated with this view. All views should have 11074 * layout parameters. These supply parameters to the <i>parent</i> of this 11075 * view specifying how it should be arranged. There are many subclasses of 11076 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11077 * of ViewGroup that are responsible for arranging their children. 11078 * 11079 * This method may return null if this View is not attached to a parent 11080 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11081 * was not invoked successfully. When a View is attached to a parent 11082 * ViewGroup, this method must not return null. 11083 * 11084 * @return The LayoutParams associated with this view, or null if no 11085 * parameters have been set yet 11086 */ 11087 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11088 public ViewGroup.LayoutParams getLayoutParams() { 11089 return mLayoutParams; 11090 } 11091 11092 /** 11093 * Set the layout parameters associated with this view. These supply 11094 * parameters to the <i>parent</i> of this view specifying how it should be 11095 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11096 * correspond to the different subclasses of ViewGroup that are responsible 11097 * for arranging their children. 11098 * 11099 * @param params The layout parameters for this view, cannot be null 11100 */ 11101 public void setLayoutParams(ViewGroup.LayoutParams params) { 11102 if (params == null) { 11103 throw new NullPointerException("Layout parameters cannot be null"); 11104 } 11105 mLayoutParams = params; 11106 resolveLayoutParams(); 11107 if (mParent instanceof ViewGroup) { 11108 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11109 } 11110 requestLayout(); 11111 } 11112 11113 /** 11114 * Resolve the layout parameters depending on the resolved layout direction 11115 * 11116 * @hide 11117 */ 11118 public void resolveLayoutParams() { 11119 if (mLayoutParams != null) { 11120 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11121 } 11122 } 11123 11124 /** 11125 * Set the scrolled position of your view. This will cause a call to 11126 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11127 * invalidated. 11128 * @param x the x position to scroll to 11129 * @param y the y position to scroll to 11130 */ 11131 public void scrollTo(int x, int y) { 11132 if (mScrollX != x || mScrollY != y) { 11133 int oldX = mScrollX; 11134 int oldY = mScrollY; 11135 mScrollX = x; 11136 mScrollY = y; 11137 invalidateParentCaches(); 11138 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11139 if (!awakenScrollBars()) { 11140 postInvalidateOnAnimation(); 11141 } 11142 } 11143 } 11144 11145 /** 11146 * Move the scrolled position of your view. This will cause a call to 11147 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11148 * invalidated. 11149 * @param x the amount of pixels to scroll by horizontally 11150 * @param y the amount of pixels to scroll by vertically 11151 */ 11152 public void scrollBy(int x, int y) { 11153 scrollTo(mScrollX + x, mScrollY + y); 11154 } 11155 11156 /** 11157 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11158 * animation to fade the scrollbars out after a default delay. If a subclass 11159 * provides animated scrolling, the start delay should equal the duration 11160 * of the scrolling animation.</p> 11161 * 11162 * <p>The animation starts only if at least one of the scrollbars is 11163 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11164 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11165 * this method returns true, and false otherwise. If the animation is 11166 * started, this method calls {@link #invalidate()}; in that case the 11167 * caller should not call {@link #invalidate()}.</p> 11168 * 11169 * <p>This method should be invoked every time a subclass directly updates 11170 * the scroll parameters.</p> 11171 * 11172 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11173 * and {@link #scrollTo(int, int)}.</p> 11174 * 11175 * @return true if the animation is played, false otherwise 11176 * 11177 * @see #awakenScrollBars(int) 11178 * @see #scrollBy(int, int) 11179 * @see #scrollTo(int, int) 11180 * @see #isHorizontalScrollBarEnabled() 11181 * @see #isVerticalScrollBarEnabled() 11182 * @see #setHorizontalScrollBarEnabled(boolean) 11183 * @see #setVerticalScrollBarEnabled(boolean) 11184 */ 11185 protected boolean awakenScrollBars() { 11186 return mScrollCache != null && 11187 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11188 } 11189 11190 /** 11191 * Trigger the scrollbars to draw. 11192 * This method differs from awakenScrollBars() only in its default duration. 11193 * initialAwakenScrollBars() will show the scroll bars for longer than 11194 * usual to give the user more of a chance to notice them. 11195 * 11196 * @return true if the animation is played, false otherwise. 11197 */ 11198 private boolean initialAwakenScrollBars() { 11199 return mScrollCache != null && 11200 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11201 } 11202 11203 /** 11204 * <p> 11205 * Trigger the scrollbars to draw. When invoked this method starts an 11206 * animation to fade the scrollbars out after a fixed delay. If a subclass 11207 * provides animated scrolling, the start delay should equal the duration of 11208 * the scrolling animation. 11209 * </p> 11210 * 11211 * <p> 11212 * The animation starts only if at least one of the scrollbars is enabled, 11213 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11214 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11215 * this method returns true, and false otherwise. If the animation is 11216 * started, this method calls {@link #invalidate()}; in that case the caller 11217 * should not call {@link #invalidate()}. 11218 * </p> 11219 * 11220 * <p> 11221 * This method should be invoked everytime a subclass directly updates the 11222 * scroll parameters. 11223 * </p> 11224 * 11225 * @param startDelay the delay, in milliseconds, after which the animation 11226 * should start; when the delay is 0, the animation starts 11227 * immediately 11228 * @return true if the animation is played, false otherwise 11229 * 11230 * @see #scrollBy(int, int) 11231 * @see #scrollTo(int, int) 11232 * @see #isHorizontalScrollBarEnabled() 11233 * @see #isVerticalScrollBarEnabled() 11234 * @see #setHorizontalScrollBarEnabled(boolean) 11235 * @see #setVerticalScrollBarEnabled(boolean) 11236 */ 11237 protected boolean awakenScrollBars(int startDelay) { 11238 return awakenScrollBars(startDelay, true); 11239 } 11240 11241 /** 11242 * <p> 11243 * Trigger the scrollbars to draw. When invoked this method starts an 11244 * animation to fade the scrollbars out after a fixed delay. If a subclass 11245 * provides animated scrolling, the start delay should equal the duration of 11246 * the scrolling animation. 11247 * </p> 11248 * 11249 * <p> 11250 * The animation starts only if at least one of the scrollbars is enabled, 11251 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11252 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11253 * this method returns true, and false otherwise. If the animation is 11254 * started, this method calls {@link #invalidate()} if the invalidate parameter 11255 * is set to true; in that case the caller 11256 * should not call {@link #invalidate()}. 11257 * </p> 11258 * 11259 * <p> 11260 * This method should be invoked everytime a subclass directly updates the 11261 * scroll parameters. 11262 * </p> 11263 * 11264 * @param startDelay the delay, in milliseconds, after which the animation 11265 * should start; when the delay is 0, the animation starts 11266 * immediately 11267 * 11268 * @param invalidate Wheter this method should call invalidate 11269 * 11270 * @return true if the animation is played, false otherwise 11271 * 11272 * @see #scrollBy(int, int) 11273 * @see #scrollTo(int, int) 11274 * @see #isHorizontalScrollBarEnabled() 11275 * @see #isVerticalScrollBarEnabled() 11276 * @see #setHorizontalScrollBarEnabled(boolean) 11277 * @see #setVerticalScrollBarEnabled(boolean) 11278 */ 11279 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11280 final ScrollabilityCache scrollCache = mScrollCache; 11281 11282 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11283 return false; 11284 } 11285 11286 if (scrollCache.scrollBar == null) { 11287 scrollCache.scrollBar = new ScrollBarDrawable(); 11288 } 11289 11290 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11291 11292 if (invalidate) { 11293 // Invalidate to show the scrollbars 11294 postInvalidateOnAnimation(); 11295 } 11296 11297 if (scrollCache.state == ScrollabilityCache.OFF) { 11298 // FIXME: this is copied from WindowManagerService. 11299 // We should get this value from the system when it 11300 // is possible to do so. 11301 final int KEY_REPEAT_FIRST_DELAY = 750; 11302 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11303 } 11304 11305 // Tell mScrollCache when we should start fading. This may 11306 // extend the fade start time if one was already scheduled 11307 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11308 scrollCache.fadeStartTime = fadeStartTime; 11309 scrollCache.state = ScrollabilityCache.ON; 11310 11311 // Schedule our fader to run, unscheduling any old ones first 11312 if (mAttachInfo != null) { 11313 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11314 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11315 } 11316 11317 return true; 11318 } 11319 11320 return false; 11321 } 11322 11323 /** 11324 * Do not invalidate views which are not visible and which are not running an animation. They 11325 * will not get drawn and they should not set dirty flags as if they will be drawn 11326 */ 11327 private boolean skipInvalidate() { 11328 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11329 (!(mParent instanceof ViewGroup) || 11330 !((ViewGroup) mParent).isViewTransitioning(this)); 11331 } 11332 11333 /** 11334 * Mark the area defined by dirty as needing to be drawn. If the view is 11335 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11336 * point in the future. 11337 * <p> 11338 * This must be called from a UI thread. To call from a non-UI thread, call 11339 * {@link #postInvalidate()}. 11340 * <p> 11341 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11342 * {@code dirty}. 11343 * 11344 * @param dirty the rectangle representing the bounds of the dirty region 11345 */ 11346 public void invalidate(Rect dirty) { 11347 final int scrollX = mScrollX; 11348 final int scrollY = mScrollY; 11349 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11350 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11351 } 11352 11353 /** 11354 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11355 * coordinates of the dirty rect are relative to the view. If the view is 11356 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11357 * point in the future. 11358 * <p> 11359 * This must be called from a UI thread. To call from a non-UI thread, call 11360 * {@link #postInvalidate()}. 11361 * 11362 * @param l the left position of the dirty region 11363 * @param t the top position of the dirty region 11364 * @param r the right position of the dirty region 11365 * @param b the bottom position of the dirty region 11366 */ 11367 public void invalidate(int l, int t, int r, int b) { 11368 final int scrollX = mScrollX; 11369 final int scrollY = mScrollY; 11370 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11371 } 11372 11373 /** 11374 * Invalidate the whole view. If the view is visible, 11375 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11376 * the future. 11377 * <p> 11378 * This must be called from a UI thread. To call from a non-UI thread, call 11379 * {@link #postInvalidate()}. 11380 */ 11381 public void invalidate() { 11382 invalidate(true); 11383 } 11384 11385 /** 11386 * This is where the invalidate() work actually happens. A full invalidate() 11387 * causes the drawing cache to be invalidated, but this function can be 11388 * called with invalidateCache set to false to skip that invalidation step 11389 * for cases that do not need it (for example, a component that remains at 11390 * the same dimensions with the same content). 11391 * 11392 * @param invalidateCache Whether the drawing cache for this view should be 11393 * invalidated as well. This is usually true for a full 11394 * invalidate, but may be set to false if the View's contents or 11395 * dimensions have not changed. 11396 */ 11397 void invalidate(boolean invalidateCache) { 11398 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11399 } 11400 11401 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11402 boolean fullInvalidate) { 11403 if (skipInvalidate()) { 11404 return; 11405 } 11406 11407 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11408 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11409 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11410 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11411 if (fullInvalidate) { 11412 mLastIsOpaque = isOpaque(); 11413 mPrivateFlags &= ~PFLAG_DRAWN; 11414 } 11415 11416 mPrivateFlags |= PFLAG_DIRTY; 11417 11418 if (invalidateCache) { 11419 mPrivateFlags |= PFLAG_INVALIDATED; 11420 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11421 } 11422 11423 // Propagate the damage rectangle to the parent view. 11424 final AttachInfo ai = mAttachInfo; 11425 final ViewParent p = mParent; 11426 if (p != null && ai != null && l < r && t < b) { 11427 final Rect damage = ai.mTmpInvalRect; 11428 damage.set(l, t, r, b); 11429 p.invalidateChild(this, damage); 11430 } 11431 11432 // Damage the entire projection receiver, if necessary. 11433 if (mBackground != null && mBackground.isProjected()) { 11434 final View receiver = getProjectionReceiver(); 11435 if (receiver != null) { 11436 receiver.damageInParent(); 11437 } 11438 } 11439 11440 // Damage the entire IsolatedZVolume recieving this view's shadow. 11441 if (isHardwareAccelerated() && getZ() != 0) { 11442 damageShadowReceiver(); 11443 } 11444 } 11445 } 11446 11447 /** 11448 * @return this view's projection receiver, or {@code null} if none exists 11449 */ 11450 private View getProjectionReceiver() { 11451 ViewParent p = getParent(); 11452 while (p != null && p instanceof View) { 11453 final View v = (View) p; 11454 if (v.isProjectionReceiver()) { 11455 return v; 11456 } 11457 p = p.getParent(); 11458 } 11459 11460 return null; 11461 } 11462 11463 /** 11464 * @return whether the view is a projection receiver 11465 */ 11466 private boolean isProjectionReceiver() { 11467 return mBackground != null; 11468 } 11469 11470 /** 11471 * Damage area of the screen that can be covered by this View's shadow. 11472 * 11473 * This method will guarantee that any changes to shadows cast by a View 11474 * are damaged on the screen for future redraw. 11475 */ 11476 private void damageShadowReceiver() { 11477 final AttachInfo ai = mAttachInfo; 11478 if (ai != null) { 11479 ViewParent p = getParent(); 11480 if (p != null && p instanceof ViewGroup) { 11481 final ViewGroup vg = (ViewGroup) p; 11482 vg.damageInParent(); 11483 } 11484 } 11485 } 11486 11487 /** 11488 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11489 * set any flags or handle all of the cases handled by the default invalidation methods. 11490 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11491 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11492 * walk up the hierarchy, transforming the dirty rect as necessary. 11493 * 11494 * The method also handles normal invalidation logic if display list properties are not 11495 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11496 * backup approach, to handle these cases used in the various property-setting methods. 11497 * 11498 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11499 * are not being used in this view 11500 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11501 * list properties are not being used in this view 11502 */ 11503 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11504 if (!isHardwareAccelerated() 11505 || !mRenderNode.isValid() 11506 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11507 if (invalidateParent) { 11508 invalidateParentCaches(); 11509 } 11510 if (forceRedraw) { 11511 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11512 } 11513 invalidate(false); 11514 } else { 11515 damageInParent(); 11516 } 11517 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11518 damageShadowReceiver(); 11519 } 11520 } 11521 11522 /** 11523 * Tells the parent view to damage this view's bounds. 11524 * 11525 * @hide 11526 */ 11527 protected void damageInParent() { 11528 final AttachInfo ai = mAttachInfo; 11529 final ViewParent p = mParent; 11530 if (p != null && ai != null) { 11531 final Rect r = ai.mTmpInvalRect; 11532 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11533 if (mParent instanceof ViewGroup) { 11534 ((ViewGroup) mParent).damageChild(this, r); 11535 } else { 11536 mParent.invalidateChild(this, r); 11537 } 11538 } 11539 } 11540 11541 /** 11542 * Utility method to transform a given Rect by the current matrix of this view. 11543 */ 11544 void transformRect(final Rect rect) { 11545 if (!getMatrix().isIdentity()) { 11546 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11547 boundingRect.set(rect); 11548 getMatrix().mapRect(boundingRect); 11549 rect.set((int) Math.floor(boundingRect.left), 11550 (int) Math.floor(boundingRect.top), 11551 (int) Math.ceil(boundingRect.right), 11552 (int) Math.ceil(boundingRect.bottom)); 11553 } 11554 } 11555 11556 /** 11557 * Used to indicate that the parent of this view should clear its caches. This functionality 11558 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11559 * which is necessary when various parent-managed properties of the view change, such as 11560 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11561 * clears the parent caches and does not causes an invalidate event. 11562 * 11563 * @hide 11564 */ 11565 protected void invalidateParentCaches() { 11566 if (mParent instanceof View) { 11567 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11568 } 11569 } 11570 11571 /** 11572 * Used to indicate that the parent of this view should be invalidated. This functionality 11573 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11574 * which is necessary when various parent-managed properties of the view change, such as 11575 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11576 * an invalidation event to the parent. 11577 * 11578 * @hide 11579 */ 11580 protected void invalidateParentIfNeeded() { 11581 if (isHardwareAccelerated() && mParent instanceof View) { 11582 ((View) mParent).invalidate(true); 11583 } 11584 } 11585 11586 /** 11587 * @hide 11588 */ 11589 protected void invalidateParentIfNeededAndWasQuickRejected() { 11590 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11591 // View was rejected last time it was drawn by its parent; this may have changed 11592 invalidateParentIfNeeded(); 11593 } 11594 } 11595 11596 /** 11597 * Indicates whether this View is opaque. An opaque View guarantees that it will 11598 * draw all the pixels overlapping its bounds using a fully opaque color. 11599 * 11600 * Subclasses of View should override this method whenever possible to indicate 11601 * whether an instance is opaque. Opaque Views are treated in a special way by 11602 * the View hierarchy, possibly allowing it to perform optimizations during 11603 * invalidate/draw passes. 11604 * 11605 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11606 */ 11607 @ViewDebug.ExportedProperty(category = "drawing") 11608 public boolean isOpaque() { 11609 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11610 getFinalAlpha() >= 1.0f; 11611 } 11612 11613 /** 11614 * @hide 11615 */ 11616 protected void computeOpaqueFlags() { 11617 // Opaque if: 11618 // - Has a background 11619 // - Background is opaque 11620 // - Doesn't have scrollbars or scrollbars overlay 11621 11622 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11623 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11624 } else { 11625 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11626 } 11627 11628 final int flags = mViewFlags; 11629 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11630 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11631 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11632 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11633 } else { 11634 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11635 } 11636 } 11637 11638 /** 11639 * @hide 11640 */ 11641 protected boolean hasOpaqueScrollbars() { 11642 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11643 } 11644 11645 /** 11646 * @return A handler associated with the thread running the View. This 11647 * handler can be used to pump events in the UI events queue. 11648 */ 11649 public Handler getHandler() { 11650 final AttachInfo attachInfo = mAttachInfo; 11651 if (attachInfo != null) { 11652 return attachInfo.mHandler; 11653 } 11654 return null; 11655 } 11656 11657 /** 11658 * Gets the view root associated with the View. 11659 * @return The view root, or null if none. 11660 * @hide 11661 */ 11662 public ViewRootImpl getViewRootImpl() { 11663 if (mAttachInfo != null) { 11664 return mAttachInfo.mViewRootImpl; 11665 } 11666 return null; 11667 } 11668 11669 /** 11670 * @hide 11671 */ 11672 public HardwareRenderer getHardwareRenderer() { 11673 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11674 } 11675 11676 /** 11677 * <p>Causes the Runnable to be added to the message queue. 11678 * The runnable will be run on the user interface thread.</p> 11679 * 11680 * @param action The Runnable that will be executed. 11681 * 11682 * @return Returns true if the Runnable was successfully placed in to the 11683 * message queue. Returns false on failure, usually because the 11684 * looper processing the message queue is exiting. 11685 * 11686 * @see #postDelayed 11687 * @see #removeCallbacks 11688 */ 11689 public boolean post(Runnable action) { 11690 final AttachInfo attachInfo = mAttachInfo; 11691 if (attachInfo != null) { 11692 return attachInfo.mHandler.post(action); 11693 } 11694 // Assume that post will succeed later 11695 ViewRootImpl.getRunQueue().post(action); 11696 return true; 11697 } 11698 11699 /** 11700 * <p>Causes the Runnable to be added to the message queue, to be run 11701 * after the specified amount of time elapses. 11702 * The runnable will be run on the user interface thread.</p> 11703 * 11704 * @param action The Runnable that will be executed. 11705 * @param delayMillis The delay (in milliseconds) until the Runnable 11706 * will be executed. 11707 * 11708 * @return true if the Runnable was successfully placed in to the 11709 * message queue. Returns false on failure, usually because the 11710 * looper processing the message queue is exiting. Note that a 11711 * result of true does not mean the Runnable will be processed -- 11712 * if the looper is quit before the delivery time of the message 11713 * occurs then the message will be dropped. 11714 * 11715 * @see #post 11716 * @see #removeCallbacks 11717 */ 11718 public boolean postDelayed(Runnable action, long delayMillis) { 11719 final AttachInfo attachInfo = mAttachInfo; 11720 if (attachInfo != null) { 11721 return attachInfo.mHandler.postDelayed(action, delayMillis); 11722 } 11723 // Assume that post will succeed later 11724 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11725 return true; 11726 } 11727 11728 /** 11729 * <p>Causes the Runnable to execute on the next animation time step. 11730 * The runnable will be run on the user interface thread.</p> 11731 * 11732 * @param action The Runnable that will be executed. 11733 * 11734 * @see #postOnAnimationDelayed 11735 * @see #removeCallbacks 11736 */ 11737 public void postOnAnimation(Runnable action) { 11738 final AttachInfo attachInfo = mAttachInfo; 11739 if (attachInfo != null) { 11740 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11741 Choreographer.CALLBACK_ANIMATION, action, null); 11742 } else { 11743 // Assume that post will succeed later 11744 ViewRootImpl.getRunQueue().post(action); 11745 } 11746 } 11747 11748 /** 11749 * <p>Causes the Runnable to execute on the next animation time step, 11750 * after the specified amount of time elapses. 11751 * The runnable will be run on the user interface thread.</p> 11752 * 11753 * @param action The Runnable that will be executed. 11754 * @param delayMillis The delay (in milliseconds) until the Runnable 11755 * will be executed. 11756 * 11757 * @see #postOnAnimation 11758 * @see #removeCallbacks 11759 */ 11760 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11761 final AttachInfo attachInfo = mAttachInfo; 11762 if (attachInfo != null) { 11763 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11764 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11765 } else { 11766 // Assume that post will succeed later 11767 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11768 } 11769 } 11770 11771 /** 11772 * <p>Removes the specified Runnable from the message queue.</p> 11773 * 11774 * @param action The Runnable to remove from the message handling queue 11775 * 11776 * @return true if this view could ask the Handler to remove the Runnable, 11777 * false otherwise. When the returned value is true, the Runnable 11778 * may or may not have been actually removed from the message queue 11779 * (for instance, if the Runnable was not in the queue already.) 11780 * 11781 * @see #post 11782 * @see #postDelayed 11783 * @see #postOnAnimation 11784 * @see #postOnAnimationDelayed 11785 */ 11786 public boolean removeCallbacks(Runnable action) { 11787 if (action != null) { 11788 final AttachInfo attachInfo = mAttachInfo; 11789 if (attachInfo != null) { 11790 attachInfo.mHandler.removeCallbacks(action); 11791 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11792 Choreographer.CALLBACK_ANIMATION, action, null); 11793 } 11794 // Assume that post will succeed later 11795 ViewRootImpl.getRunQueue().removeCallbacks(action); 11796 } 11797 return true; 11798 } 11799 11800 /** 11801 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11802 * Use this to invalidate the View from a non-UI thread.</p> 11803 * 11804 * <p>This method can be invoked from outside of the UI thread 11805 * only when this View is attached to a window.</p> 11806 * 11807 * @see #invalidate() 11808 * @see #postInvalidateDelayed(long) 11809 */ 11810 public void postInvalidate() { 11811 postInvalidateDelayed(0); 11812 } 11813 11814 /** 11815 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11816 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11817 * 11818 * <p>This method can be invoked from outside of the UI thread 11819 * only when this View is attached to a window.</p> 11820 * 11821 * @param left The left coordinate of the rectangle to invalidate. 11822 * @param top The top coordinate of the rectangle to invalidate. 11823 * @param right The right coordinate of the rectangle to invalidate. 11824 * @param bottom The bottom coordinate of the rectangle to invalidate. 11825 * 11826 * @see #invalidate(int, int, int, int) 11827 * @see #invalidate(Rect) 11828 * @see #postInvalidateDelayed(long, int, int, int, int) 11829 */ 11830 public void postInvalidate(int left, int top, int right, int bottom) { 11831 postInvalidateDelayed(0, left, top, right, bottom); 11832 } 11833 11834 /** 11835 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11836 * loop. Waits for the specified amount of time.</p> 11837 * 11838 * <p>This method can be invoked from outside of the UI thread 11839 * only when this View is attached to a window.</p> 11840 * 11841 * @param delayMilliseconds the duration in milliseconds to delay the 11842 * invalidation by 11843 * 11844 * @see #invalidate() 11845 * @see #postInvalidate() 11846 */ 11847 public void postInvalidateDelayed(long delayMilliseconds) { 11848 // We try only with the AttachInfo because there's no point in invalidating 11849 // if we are not attached to our window 11850 final AttachInfo attachInfo = mAttachInfo; 11851 if (attachInfo != null) { 11852 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11853 } 11854 } 11855 11856 /** 11857 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11858 * through the event loop. Waits for the specified amount of time.</p> 11859 * 11860 * <p>This method can be invoked from outside of the UI thread 11861 * only when this View is attached to a window.</p> 11862 * 11863 * @param delayMilliseconds the duration in milliseconds to delay the 11864 * invalidation by 11865 * @param left The left coordinate of the rectangle to invalidate. 11866 * @param top The top coordinate of the rectangle to invalidate. 11867 * @param right The right coordinate of the rectangle to invalidate. 11868 * @param bottom The bottom coordinate of the rectangle to invalidate. 11869 * 11870 * @see #invalidate(int, int, int, int) 11871 * @see #invalidate(Rect) 11872 * @see #postInvalidate(int, int, int, int) 11873 */ 11874 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11875 int right, int bottom) { 11876 11877 // We try only with the AttachInfo because there's no point in invalidating 11878 // if we are not attached to our window 11879 final AttachInfo attachInfo = mAttachInfo; 11880 if (attachInfo != null) { 11881 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11882 info.target = this; 11883 info.left = left; 11884 info.top = top; 11885 info.right = right; 11886 info.bottom = bottom; 11887 11888 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11889 } 11890 } 11891 11892 /** 11893 * <p>Cause an invalidate to happen on the next animation time step, typically the 11894 * next display frame.</p> 11895 * 11896 * <p>This method can be invoked from outside of the UI thread 11897 * only when this View is attached to a window.</p> 11898 * 11899 * @see #invalidate() 11900 */ 11901 public void postInvalidateOnAnimation() { 11902 // We try only with the AttachInfo because there's no point in invalidating 11903 // if we are not attached to our window 11904 final AttachInfo attachInfo = mAttachInfo; 11905 if (attachInfo != null) { 11906 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11907 } 11908 } 11909 11910 /** 11911 * <p>Cause an invalidate of the specified area to happen on the next animation 11912 * time step, typically the next display frame.</p> 11913 * 11914 * <p>This method can be invoked from outside of the UI thread 11915 * only when this View is attached to a window.</p> 11916 * 11917 * @param left The left coordinate of the rectangle to invalidate. 11918 * @param top The top coordinate of the rectangle to invalidate. 11919 * @param right The right coordinate of the rectangle to invalidate. 11920 * @param bottom The bottom coordinate of the rectangle to invalidate. 11921 * 11922 * @see #invalidate(int, int, int, int) 11923 * @see #invalidate(Rect) 11924 */ 11925 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11926 // We try only with the AttachInfo because there's no point in invalidating 11927 // if we are not attached to our window 11928 final AttachInfo attachInfo = mAttachInfo; 11929 if (attachInfo != null) { 11930 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11931 info.target = this; 11932 info.left = left; 11933 info.top = top; 11934 info.right = right; 11935 info.bottom = bottom; 11936 11937 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11938 } 11939 } 11940 11941 /** 11942 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11943 * This event is sent at most once every 11944 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11945 */ 11946 private void postSendViewScrolledAccessibilityEventCallback() { 11947 if (mSendViewScrolledAccessibilityEvent == null) { 11948 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11949 } 11950 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11951 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11952 postDelayed(mSendViewScrolledAccessibilityEvent, 11953 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11954 } 11955 } 11956 11957 /** 11958 * Called by a parent to request that a child update its values for mScrollX 11959 * and mScrollY if necessary. This will typically be done if the child is 11960 * animating a scroll using a {@link android.widget.Scroller Scroller} 11961 * object. 11962 */ 11963 public void computeScroll() { 11964 } 11965 11966 /** 11967 * <p>Indicate whether the horizontal edges are faded when the view is 11968 * scrolled horizontally.</p> 11969 * 11970 * @return true if the horizontal edges should are faded on scroll, false 11971 * otherwise 11972 * 11973 * @see #setHorizontalFadingEdgeEnabled(boolean) 11974 * 11975 * @attr ref android.R.styleable#View_requiresFadingEdge 11976 */ 11977 public boolean isHorizontalFadingEdgeEnabled() { 11978 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11979 } 11980 11981 /** 11982 * <p>Define whether the horizontal edges should be faded when this view 11983 * is scrolled horizontally.</p> 11984 * 11985 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11986 * be faded when the view is scrolled 11987 * horizontally 11988 * 11989 * @see #isHorizontalFadingEdgeEnabled() 11990 * 11991 * @attr ref android.R.styleable#View_requiresFadingEdge 11992 */ 11993 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11994 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11995 if (horizontalFadingEdgeEnabled) { 11996 initScrollCache(); 11997 } 11998 11999 mViewFlags ^= FADING_EDGE_HORIZONTAL; 12000 } 12001 } 12002 12003 /** 12004 * <p>Indicate whether the vertical edges are faded when the view is 12005 * scrolled horizontally.</p> 12006 * 12007 * @return true if the vertical edges should are faded on scroll, false 12008 * otherwise 12009 * 12010 * @see #setVerticalFadingEdgeEnabled(boolean) 12011 * 12012 * @attr ref android.R.styleable#View_requiresFadingEdge 12013 */ 12014 public boolean isVerticalFadingEdgeEnabled() { 12015 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 12016 } 12017 12018 /** 12019 * <p>Define whether the vertical edges should be faded when this view 12020 * is scrolled vertically.</p> 12021 * 12022 * @param verticalFadingEdgeEnabled true if the vertical edges should 12023 * be faded when the view is scrolled 12024 * vertically 12025 * 12026 * @see #isVerticalFadingEdgeEnabled() 12027 * 12028 * @attr ref android.R.styleable#View_requiresFadingEdge 12029 */ 12030 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 12031 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 12032 if (verticalFadingEdgeEnabled) { 12033 initScrollCache(); 12034 } 12035 12036 mViewFlags ^= FADING_EDGE_VERTICAL; 12037 } 12038 } 12039 12040 /** 12041 * Returns the strength, or intensity, of the top faded edge. The strength is 12042 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12043 * returns 0.0 or 1.0 but no value in between. 12044 * 12045 * Subclasses should override this method to provide a smoother fade transition 12046 * when scrolling occurs. 12047 * 12048 * @return the intensity of the top fade as a float between 0.0f and 1.0f 12049 */ 12050 protected float getTopFadingEdgeStrength() { 12051 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 12052 } 12053 12054 /** 12055 * Returns the strength, or intensity, of the bottom faded edge. The strength is 12056 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12057 * returns 0.0 or 1.0 but no value in between. 12058 * 12059 * Subclasses should override this method to provide a smoother fade transition 12060 * when scrolling occurs. 12061 * 12062 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 12063 */ 12064 protected float getBottomFadingEdgeStrength() { 12065 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 12066 computeVerticalScrollRange() ? 1.0f : 0.0f; 12067 } 12068 12069 /** 12070 * Returns the strength, or intensity, of the left faded edge. The strength is 12071 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12072 * returns 0.0 or 1.0 but no value in between. 12073 * 12074 * Subclasses should override this method to provide a smoother fade transition 12075 * when scrolling occurs. 12076 * 12077 * @return the intensity of the left fade as a float between 0.0f and 1.0f 12078 */ 12079 protected float getLeftFadingEdgeStrength() { 12080 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12081 } 12082 12083 /** 12084 * Returns the strength, or intensity, of the right faded edge. The strength is 12085 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12086 * returns 0.0 or 1.0 but no value in between. 12087 * 12088 * Subclasses should override this method to provide a smoother fade transition 12089 * when scrolling occurs. 12090 * 12091 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12092 */ 12093 protected float getRightFadingEdgeStrength() { 12094 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12095 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12096 } 12097 12098 /** 12099 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12100 * scrollbar is not drawn by default.</p> 12101 * 12102 * @return true if the horizontal scrollbar should be painted, false 12103 * otherwise 12104 * 12105 * @see #setHorizontalScrollBarEnabled(boolean) 12106 */ 12107 public boolean isHorizontalScrollBarEnabled() { 12108 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12109 } 12110 12111 /** 12112 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12113 * scrollbar is not drawn by default.</p> 12114 * 12115 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12116 * be painted 12117 * 12118 * @see #isHorizontalScrollBarEnabled() 12119 */ 12120 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12121 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12122 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12123 computeOpaqueFlags(); 12124 resolvePadding(); 12125 } 12126 } 12127 12128 /** 12129 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12130 * scrollbar is not drawn by default.</p> 12131 * 12132 * @return true if the vertical scrollbar should be painted, false 12133 * otherwise 12134 * 12135 * @see #setVerticalScrollBarEnabled(boolean) 12136 */ 12137 public boolean isVerticalScrollBarEnabled() { 12138 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12139 } 12140 12141 /** 12142 * <p>Define whether the vertical scrollbar should be drawn or not. The 12143 * scrollbar is not drawn by default.</p> 12144 * 12145 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12146 * be painted 12147 * 12148 * @see #isVerticalScrollBarEnabled() 12149 */ 12150 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12151 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12152 mViewFlags ^= SCROLLBARS_VERTICAL; 12153 computeOpaqueFlags(); 12154 resolvePadding(); 12155 } 12156 } 12157 12158 /** 12159 * @hide 12160 */ 12161 protected void recomputePadding() { 12162 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12163 } 12164 12165 /** 12166 * Define whether scrollbars will fade when the view is not scrolling. 12167 * 12168 * @param fadeScrollbars wheter to enable fading 12169 * 12170 * @attr ref android.R.styleable#View_fadeScrollbars 12171 */ 12172 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12173 initScrollCache(); 12174 final ScrollabilityCache scrollabilityCache = mScrollCache; 12175 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12176 if (fadeScrollbars) { 12177 scrollabilityCache.state = ScrollabilityCache.OFF; 12178 } else { 12179 scrollabilityCache.state = ScrollabilityCache.ON; 12180 } 12181 } 12182 12183 /** 12184 * 12185 * Returns true if scrollbars will fade when this view is not scrolling 12186 * 12187 * @return true if scrollbar fading is enabled 12188 * 12189 * @attr ref android.R.styleable#View_fadeScrollbars 12190 */ 12191 public boolean isScrollbarFadingEnabled() { 12192 return mScrollCache != null && mScrollCache.fadeScrollBars; 12193 } 12194 12195 /** 12196 * 12197 * Returns the delay before scrollbars fade. 12198 * 12199 * @return the delay before scrollbars fade 12200 * 12201 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12202 */ 12203 public int getScrollBarDefaultDelayBeforeFade() { 12204 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12205 mScrollCache.scrollBarDefaultDelayBeforeFade; 12206 } 12207 12208 /** 12209 * Define the delay before scrollbars fade. 12210 * 12211 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12212 * 12213 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12214 */ 12215 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12216 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12217 } 12218 12219 /** 12220 * 12221 * Returns the scrollbar fade duration. 12222 * 12223 * @return the scrollbar fade duration 12224 * 12225 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12226 */ 12227 public int getScrollBarFadeDuration() { 12228 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12229 mScrollCache.scrollBarFadeDuration; 12230 } 12231 12232 /** 12233 * Define the scrollbar fade duration. 12234 * 12235 * @param scrollBarFadeDuration - the scrollbar fade duration 12236 * 12237 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12238 */ 12239 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12240 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12241 } 12242 12243 /** 12244 * 12245 * Returns the scrollbar size. 12246 * 12247 * @return the scrollbar size 12248 * 12249 * @attr ref android.R.styleable#View_scrollbarSize 12250 */ 12251 public int getScrollBarSize() { 12252 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12253 mScrollCache.scrollBarSize; 12254 } 12255 12256 /** 12257 * Define the scrollbar size. 12258 * 12259 * @param scrollBarSize - the scrollbar size 12260 * 12261 * @attr ref android.R.styleable#View_scrollbarSize 12262 */ 12263 public void setScrollBarSize(int scrollBarSize) { 12264 getScrollCache().scrollBarSize = scrollBarSize; 12265 } 12266 12267 /** 12268 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12269 * inset. When inset, they add to the padding of the view. And the scrollbars 12270 * can be drawn inside the padding area or on the edge of the view. For example, 12271 * if a view has a background drawable and you want to draw the scrollbars 12272 * inside the padding specified by the drawable, you can use 12273 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12274 * appear at the edge of the view, ignoring the padding, then you can use 12275 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12276 * @param style the style of the scrollbars. Should be one of 12277 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12278 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12279 * @see #SCROLLBARS_INSIDE_OVERLAY 12280 * @see #SCROLLBARS_INSIDE_INSET 12281 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12282 * @see #SCROLLBARS_OUTSIDE_INSET 12283 * 12284 * @attr ref android.R.styleable#View_scrollbarStyle 12285 */ 12286 public void setScrollBarStyle(@ScrollBarStyle int style) { 12287 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12288 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12289 computeOpaqueFlags(); 12290 resolvePadding(); 12291 } 12292 } 12293 12294 /** 12295 * <p>Returns the current scrollbar style.</p> 12296 * @return the current scrollbar style 12297 * @see #SCROLLBARS_INSIDE_OVERLAY 12298 * @see #SCROLLBARS_INSIDE_INSET 12299 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12300 * @see #SCROLLBARS_OUTSIDE_INSET 12301 * 12302 * @attr ref android.R.styleable#View_scrollbarStyle 12303 */ 12304 @ViewDebug.ExportedProperty(mapping = { 12305 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12306 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12307 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12308 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12309 }) 12310 @ScrollBarStyle 12311 public int getScrollBarStyle() { 12312 return mViewFlags & SCROLLBARS_STYLE_MASK; 12313 } 12314 12315 /** 12316 * <p>Compute the horizontal range that the horizontal scrollbar 12317 * represents.</p> 12318 * 12319 * <p>The range is expressed in arbitrary units that must be the same as the 12320 * units used by {@link #computeHorizontalScrollExtent()} and 12321 * {@link #computeHorizontalScrollOffset()}.</p> 12322 * 12323 * <p>The default range is the drawing width of this view.</p> 12324 * 12325 * @return the total horizontal range represented by the horizontal 12326 * scrollbar 12327 * 12328 * @see #computeHorizontalScrollExtent() 12329 * @see #computeHorizontalScrollOffset() 12330 * @see android.widget.ScrollBarDrawable 12331 */ 12332 protected int computeHorizontalScrollRange() { 12333 return getWidth(); 12334 } 12335 12336 /** 12337 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12338 * within the horizontal range. This value is used to compute the position 12339 * of the thumb within the scrollbar's track.</p> 12340 * 12341 * <p>The range is expressed in arbitrary units that must be the same as the 12342 * units used by {@link #computeHorizontalScrollRange()} and 12343 * {@link #computeHorizontalScrollExtent()}.</p> 12344 * 12345 * <p>The default offset is the scroll offset of this view.</p> 12346 * 12347 * @return the horizontal offset of the scrollbar's thumb 12348 * 12349 * @see #computeHorizontalScrollRange() 12350 * @see #computeHorizontalScrollExtent() 12351 * @see android.widget.ScrollBarDrawable 12352 */ 12353 protected int computeHorizontalScrollOffset() { 12354 return mScrollX; 12355 } 12356 12357 /** 12358 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12359 * within the horizontal range. This value is used to compute the length 12360 * of the thumb within the scrollbar's track.</p> 12361 * 12362 * <p>The range is expressed in arbitrary units that must be the same as the 12363 * units used by {@link #computeHorizontalScrollRange()} and 12364 * {@link #computeHorizontalScrollOffset()}.</p> 12365 * 12366 * <p>The default extent is the drawing width of this view.</p> 12367 * 12368 * @return the horizontal extent of the scrollbar's thumb 12369 * 12370 * @see #computeHorizontalScrollRange() 12371 * @see #computeHorizontalScrollOffset() 12372 * @see android.widget.ScrollBarDrawable 12373 */ 12374 protected int computeHorizontalScrollExtent() { 12375 return getWidth(); 12376 } 12377 12378 /** 12379 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12380 * 12381 * <p>The range is expressed in arbitrary units that must be the same as the 12382 * units used by {@link #computeVerticalScrollExtent()} and 12383 * {@link #computeVerticalScrollOffset()}.</p> 12384 * 12385 * @return the total vertical range represented by the vertical scrollbar 12386 * 12387 * <p>The default range is the drawing height of this view.</p> 12388 * 12389 * @see #computeVerticalScrollExtent() 12390 * @see #computeVerticalScrollOffset() 12391 * @see android.widget.ScrollBarDrawable 12392 */ 12393 protected int computeVerticalScrollRange() { 12394 return getHeight(); 12395 } 12396 12397 /** 12398 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12399 * within the horizontal range. This value is used to compute the position 12400 * of the thumb within the scrollbar's track.</p> 12401 * 12402 * <p>The range is expressed in arbitrary units that must be the same as the 12403 * units used by {@link #computeVerticalScrollRange()} and 12404 * {@link #computeVerticalScrollExtent()}.</p> 12405 * 12406 * <p>The default offset is the scroll offset of this view.</p> 12407 * 12408 * @return the vertical offset of the scrollbar's thumb 12409 * 12410 * @see #computeVerticalScrollRange() 12411 * @see #computeVerticalScrollExtent() 12412 * @see android.widget.ScrollBarDrawable 12413 */ 12414 protected int computeVerticalScrollOffset() { 12415 return mScrollY; 12416 } 12417 12418 /** 12419 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12420 * within the vertical range. This value is used to compute the length 12421 * of the thumb within the scrollbar's track.</p> 12422 * 12423 * <p>The range is expressed in arbitrary units that must be the same as the 12424 * units used by {@link #computeVerticalScrollRange()} and 12425 * {@link #computeVerticalScrollOffset()}.</p> 12426 * 12427 * <p>The default extent is the drawing height of this view.</p> 12428 * 12429 * @return the vertical extent of the scrollbar's thumb 12430 * 12431 * @see #computeVerticalScrollRange() 12432 * @see #computeVerticalScrollOffset() 12433 * @see android.widget.ScrollBarDrawable 12434 */ 12435 protected int computeVerticalScrollExtent() { 12436 return getHeight(); 12437 } 12438 12439 /** 12440 * Check if this view can be scrolled horizontally in a certain direction. 12441 * 12442 * @param direction Negative to check scrolling left, positive to check scrolling right. 12443 * @return true if this view can be scrolled in the specified direction, false otherwise. 12444 */ 12445 public boolean canScrollHorizontally(int direction) { 12446 final int offset = computeHorizontalScrollOffset(); 12447 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12448 if (range == 0) return false; 12449 if (direction < 0) { 12450 return offset > 0; 12451 } else { 12452 return offset < range - 1; 12453 } 12454 } 12455 12456 /** 12457 * Check if this view can be scrolled vertically in a certain direction. 12458 * 12459 * @param direction Negative to check scrolling up, positive to check scrolling down. 12460 * @return true if this view can be scrolled in the specified direction, false otherwise. 12461 */ 12462 public boolean canScrollVertically(int direction) { 12463 final int offset = computeVerticalScrollOffset(); 12464 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12465 if (range == 0) return false; 12466 if (direction < 0) { 12467 return offset > 0; 12468 } else { 12469 return offset < range - 1; 12470 } 12471 } 12472 12473 /** 12474 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12475 * scrollbars are painted only if they have been awakened first.</p> 12476 * 12477 * @param canvas the canvas on which to draw the scrollbars 12478 * 12479 * @see #awakenScrollBars(int) 12480 */ 12481 protected final void onDrawScrollBars(Canvas canvas) { 12482 // scrollbars are drawn only when the animation is running 12483 final ScrollabilityCache cache = mScrollCache; 12484 if (cache != null) { 12485 12486 int state = cache.state; 12487 12488 if (state == ScrollabilityCache.OFF) { 12489 return; 12490 } 12491 12492 boolean invalidate = false; 12493 12494 if (state == ScrollabilityCache.FADING) { 12495 // We're fading -- get our fade interpolation 12496 if (cache.interpolatorValues == null) { 12497 cache.interpolatorValues = new float[1]; 12498 } 12499 12500 float[] values = cache.interpolatorValues; 12501 12502 // Stops the animation if we're done 12503 if (cache.scrollBarInterpolator.timeToValues(values) == 12504 Interpolator.Result.FREEZE_END) { 12505 cache.state = ScrollabilityCache.OFF; 12506 } else { 12507 cache.scrollBar.setAlpha(Math.round(values[0])); 12508 } 12509 12510 // This will make the scroll bars inval themselves after 12511 // drawing. We only want this when we're fading so that 12512 // we prevent excessive redraws 12513 invalidate = true; 12514 } else { 12515 // We're just on -- but we may have been fading before so 12516 // reset alpha 12517 cache.scrollBar.setAlpha(255); 12518 } 12519 12520 12521 final int viewFlags = mViewFlags; 12522 12523 final boolean drawHorizontalScrollBar = 12524 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12525 final boolean drawVerticalScrollBar = 12526 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12527 && !isVerticalScrollBarHidden(); 12528 12529 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12530 final int width = mRight - mLeft; 12531 final int height = mBottom - mTop; 12532 12533 final ScrollBarDrawable scrollBar = cache.scrollBar; 12534 12535 final int scrollX = mScrollX; 12536 final int scrollY = mScrollY; 12537 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12538 12539 int left; 12540 int top; 12541 int right; 12542 int bottom; 12543 12544 if (drawHorizontalScrollBar) { 12545 int size = scrollBar.getSize(false); 12546 if (size <= 0) { 12547 size = cache.scrollBarSize; 12548 } 12549 12550 scrollBar.setParameters(computeHorizontalScrollRange(), 12551 computeHorizontalScrollOffset(), 12552 computeHorizontalScrollExtent(), false); 12553 final int verticalScrollBarGap = drawVerticalScrollBar ? 12554 getVerticalScrollbarWidth() : 0; 12555 top = scrollY + height - size - (mUserPaddingBottom & inside); 12556 left = scrollX + (mPaddingLeft & inside); 12557 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12558 bottom = top + size; 12559 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12560 if (invalidate) { 12561 invalidate(left, top, right, bottom); 12562 } 12563 } 12564 12565 if (drawVerticalScrollBar) { 12566 int size = scrollBar.getSize(true); 12567 if (size <= 0) { 12568 size = cache.scrollBarSize; 12569 } 12570 12571 scrollBar.setParameters(computeVerticalScrollRange(), 12572 computeVerticalScrollOffset(), 12573 computeVerticalScrollExtent(), true); 12574 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12575 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12576 verticalScrollbarPosition = isLayoutRtl() ? 12577 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12578 } 12579 switch (verticalScrollbarPosition) { 12580 default: 12581 case SCROLLBAR_POSITION_RIGHT: 12582 left = scrollX + width - size - (mUserPaddingRight & inside); 12583 break; 12584 case SCROLLBAR_POSITION_LEFT: 12585 left = scrollX + (mUserPaddingLeft & inside); 12586 break; 12587 } 12588 top = scrollY + (mPaddingTop & inside); 12589 right = left + size; 12590 bottom = scrollY + height - (mUserPaddingBottom & inside); 12591 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12592 if (invalidate) { 12593 invalidate(left, top, right, bottom); 12594 } 12595 } 12596 } 12597 } 12598 } 12599 12600 /** 12601 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12602 * FastScroller is visible. 12603 * @return whether to temporarily hide the vertical scrollbar 12604 * @hide 12605 */ 12606 protected boolean isVerticalScrollBarHidden() { 12607 return false; 12608 } 12609 12610 /** 12611 * <p>Draw the horizontal scrollbar if 12612 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12613 * 12614 * @param canvas the canvas on which to draw the scrollbar 12615 * @param scrollBar the scrollbar's drawable 12616 * 12617 * @see #isHorizontalScrollBarEnabled() 12618 * @see #computeHorizontalScrollRange() 12619 * @see #computeHorizontalScrollExtent() 12620 * @see #computeHorizontalScrollOffset() 12621 * @see android.widget.ScrollBarDrawable 12622 * @hide 12623 */ 12624 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12625 int l, int t, int r, int b) { 12626 scrollBar.setBounds(l, t, r, b); 12627 scrollBar.draw(canvas); 12628 } 12629 12630 /** 12631 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12632 * returns true.</p> 12633 * 12634 * @param canvas the canvas on which to draw the scrollbar 12635 * @param scrollBar the scrollbar's drawable 12636 * 12637 * @see #isVerticalScrollBarEnabled() 12638 * @see #computeVerticalScrollRange() 12639 * @see #computeVerticalScrollExtent() 12640 * @see #computeVerticalScrollOffset() 12641 * @see android.widget.ScrollBarDrawable 12642 * @hide 12643 */ 12644 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12645 int l, int t, int r, int b) { 12646 scrollBar.setBounds(l, t, r, b); 12647 scrollBar.draw(canvas); 12648 } 12649 12650 /** 12651 * Implement this to do your drawing. 12652 * 12653 * @param canvas the canvas on which the background will be drawn 12654 */ 12655 protected void onDraw(Canvas canvas) { 12656 } 12657 12658 /* 12659 * Caller is responsible for calling requestLayout if necessary. 12660 * (This allows addViewInLayout to not request a new layout.) 12661 */ 12662 void assignParent(ViewParent parent) { 12663 if (mParent == null) { 12664 mParent = parent; 12665 } else if (parent == null) { 12666 mParent = null; 12667 } else { 12668 throw new RuntimeException("view " + this + " being added, but" 12669 + " it already has a parent"); 12670 } 12671 } 12672 12673 /** 12674 * This is called when the view is attached to a window. At this point it 12675 * has a Surface and will start drawing. Note that this function is 12676 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12677 * however it may be called any time before the first onDraw -- including 12678 * before or after {@link #onMeasure(int, int)}. 12679 * 12680 * @see #onDetachedFromWindow() 12681 */ 12682 protected void onAttachedToWindow() { 12683 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12684 mParent.requestTransparentRegion(this); 12685 } 12686 12687 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12688 initialAwakenScrollBars(); 12689 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12690 } 12691 12692 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12693 12694 jumpDrawablesToCurrentState(); 12695 12696 resetSubtreeAccessibilityStateChanged(); 12697 12698 invalidateOutline(); 12699 12700 if (isFocused()) { 12701 InputMethodManager imm = InputMethodManager.peekInstance(); 12702 imm.focusIn(this); 12703 } 12704 } 12705 12706 /** 12707 * Resolve all RTL related properties. 12708 * 12709 * @return true if resolution of RTL properties has been done 12710 * 12711 * @hide 12712 */ 12713 public boolean resolveRtlPropertiesIfNeeded() { 12714 if (!needRtlPropertiesResolution()) return false; 12715 12716 // Order is important here: LayoutDirection MUST be resolved first 12717 if (!isLayoutDirectionResolved()) { 12718 resolveLayoutDirection(); 12719 resolveLayoutParams(); 12720 } 12721 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12722 if (!isTextDirectionResolved()) { 12723 resolveTextDirection(); 12724 } 12725 if (!isTextAlignmentResolved()) { 12726 resolveTextAlignment(); 12727 } 12728 // Should resolve Drawables before Padding because we need the layout direction of the 12729 // Drawable to correctly resolve Padding. 12730 if (!isDrawablesResolved()) { 12731 resolveDrawables(); 12732 } 12733 if (!isPaddingResolved()) { 12734 resolvePadding(); 12735 } 12736 onRtlPropertiesChanged(getLayoutDirection()); 12737 return true; 12738 } 12739 12740 /** 12741 * Reset resolution of all RTL related properties. 12742 * 12743 * @hide 12744 */ 12745 public void resetRtlProperties() { 12746 resetResolvedLayoutDirection(); 12747 resetResolvedTextDirection(); 12748 resetResolvedTextAlignment(); 12749 resetResolvedPadding(); 12750 resetResolvedDrawables(); 12751 } 12752 12753 /** 12754 * @see #onScreenStateChanged(int) 12755 */ 12756 void dispatchScreenStateChanged(int screenState) { 12757 onScreenStateChanged(screenState); 12758 } 12759 12760 /** 12761 * This method is called whenever the state of the screen this view is 12762 * attached to changes. A state change will usually occurs when the screen 12763 * turns on or off (whether it happens automatically or the user does it 12764 * manually.) 12765 * 12766 * @param screenState The new state of the screen. Can be either 12767 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12768 */ 12769 public void onScreenStateChanged(int screenState) { 12770 } 12771 12772 /** 12773 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12774 */ 12775 private boolean hasRtlSupport() { 12776 return mContext.getApplicationInfo().hasRtlSupport(); 12777 } 12778 12779 /** 12780 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12781 * RTL not supported) 12782 */ 12783 private boolean isRtlCompatibilityMode() { 12784 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12785 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12786 } 12787 12788 /** 12789 * @return true if RTL properties need resolution. 12790 * 12791 */ 12792 private boolean needRtlPropertiesResolution() { 12793 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12794 } 12795 12796 /** 12797 * Called when any RTL property (layout direction or text direction or text alignment) has 12798 * been changed. 12799 * 12800 * Subclasses need to override this method to take care of cached information that depends on the 12801 * resolved layout direction, or to inform child views that inherit their layout direction. 12802 * 12803 * The default implementation does nothing. 12804 * 12805 * @param layoutDirection the direction of the layout 12806 * 12807 * @see #LAYOUT_DIRECTION_LTR 12808 * @see #LAYOUT_DIRECTION_RTL 12809 */ 12810 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12811 } 12812 12813 /** 12814 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12815 * that the parent directionality can and will be resolved before its children. 12816 * 12817 * @return true if resolution has been done, false otherwise. 12818 * 12819 * @hide 12820 */ 12821 public boolean resolveLayoutDirection() { 12822 // Clear any previous layout direction resolution 12823 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12824 12825 if (hasRtlSupport()) { 12826 // Set resolved depending on layout direction 12827 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12828 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12829 case LAYOUT_DIRECTION_INHERIT: 12830 // We cannot resolve yet. LTR is by default and let the resolution happen again 12831 // later to get the correct resolved value 12832 if (!canResolveLayoutDirection()) return false; 12833 12834 // Parent has not yet resolved, LTR is still the default 12835 try { 12836 if (!mParent.isLayoutDirectionResolved()) return false; 12837 12838 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12839 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12840 } 12841 } catch (AbstractMethodError e) { 12842 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12843 " does not fully implement ViewParent", e); 12844 } 12845 break; 12846 case LAYOUT_DIRECTION_RTL: 12847 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12848 break; 12849 case LAYOUT_DIRECTION_LOCALE: 12850 if((LAYOUT_DIRECTION_RTL == 12851 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12852 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12853 } 12854 break; 12855 default: 12856 // Nothing to do, LTR by default 12857 } 12858 } 12859 12860 // Set to resolved 12861 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12862 return true; 12863 } 12864 12865 /** 12866 * Check if layout direction resolution can be done. 12867 * 12868 * @return true if layout direction resolution can be done otherwise return false. 12869 */ 12870 public boolean canResolveLayoutDirection() { 12871 switch (getRawLayoutDirection()) { 12872 case LAYOUT_DIRECTION_INHERIT: 12873 if (mParent != null) { 12874 try { 12875 return mParent.canResolveLayoutDirection(); 12876 } catch (AbstractMethodError e) { 12877 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12878 " does not fully implement ViewParent", e); 12879 } 12880 } 12881 return false; 12882 12883 default: 12884 return true; 12885 } 12886 } 12887 12888 /** 12889 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12890 * {@link #onMeasure(int, int)}. 12891 * 12892 * @hide 12893 */ 12894 public void resetResolvedLayoutDirection() { 12895 // Reset the current resolved bits 12896 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12897 } 12898 12899 /** 12900 * @return true if the layout direction is inherited. 12901 * 12902 * @hide 12903 */ 12904 public boolean isLayoutDirectionInherited() { 12905 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12906 } 12907 12908 /** 12909 * @return true if layout direction has been resolved. 12910 */ 12911 public boolean isLayoutDirectionResolved() { 12912 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12913 } 12914 12915 /** 12916 * Return if padding has been resolved 12917 * 12918 * @hide 12919 */ 12920 boolean isPaddingResolved() { 12921 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12922 } 12923 12924 /** 12925 * Resolves padding depending on layout direction, if applicable, and 12926 * recomputes internal padding values to adjust for scroll bars. 12927 * 12928 * @hide 12929 */ 12930 public void resolvePadding() { 12931 final int resolvedLayoutDirection = getLayoutDirection(); 12932 12933 if (!isRtlCompatibilityMode()) { 12934 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12935 // If start / end padding are defined, they will be resolved (hence overriding) to 12936 // left / right or right / left depending on the resolved layout direction. 12937 // If start / end padding are not defined, use the left / right ones. 12938 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12939 Rect padding = sThreadLocal.get(); 12940 if (padding == null) { 12941 padding = new Rect(); 12942 sThreadLocal.set(padding); 12943 } 12944 mBackground.getPadding(padding); 12945 if (!mLeftPaddingDefined) { 12946 mUserPaddingLeftInitial = padding.left; 12947 } 12948 if (!mRightPaddingDefined) { 12949 mUserPaddingRightInitial = padding.right; 12950 } 12951 } 12952 switch (resolvedLayoutDirection) { 12953 case LAYOUT_DIRECTION_RTL: 12954 if (mUserPaddingStart != UNDEFINED_PADDING) { 12955 mUserPaddingRight = mUserPaddingStart; 12956 } else { 12957 mUserPaddingRight = mUserPaddingRightInitial; 12958 } 12959 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12960 mUserPaddingLeft = mUserPaddingEnd; 12961 } else { 12962 mUserPaddingLeft = mUserPaddingLeftInitial; 12963 } 12964 break; 12965 case LAYOUT_DIRECTION_LTR: 12966 default: 12967 if (mUserPaddingStart != UNDEFINED_PADDING) { 12968 mUserPaddingLeft = mUserPaddingStart; 12969 } else { 12970 mUserPaddingLeft = mUserPaddingLeftInitial; 12971 } 12972 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12973 mUserPaddingRight = mUserPaddingEnd; 12974 } else { 12975 mUserPaddingRight = mUserPaddingRightInitial; 12976 } 12977 } 12978 12979 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12980 } 12981 12982 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12983 onRtlPropertiesChanged(resolvedLayoutDirection); 12984 12985 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12986 } 12987 12988 /** 12989 * Reset the resolved layout direction. 12990 * 12991 * @hide 12992 */ 12993 public void resetResolvedPadding() { 12994 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12995 } 12996 12997 /** 12998 * This is called when the view is detached from a window. At this point it 12999 * no longer has a surface for drawing. 13000 * 13001 * @see #onAttachedToWindow() 13002 */ 13003 protected void onDetachedFromWindow() { 13004 } 13005 13006 /** 13007 * This is a framework-internal mirror of onDetachedFromWindow() that's called 13008 * after onDetachedFromWindow(). 13009 * 13010 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 13011 * The super method should be called at the end of the overriden method to ensure 13012 * subclasses are destroyed first 13013 * 13014 * @hide 13015 */ 13016 protected void onDetachedFromWindowInternal() { 13017 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 13018 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13019 13020 removeUnsetPressCallback(); 13021 removeLongPressCallback(); 13022 removePerformClickCallback(); 13023 removeSendViewScrolledAccessibilityEventCallback(); 13024 stopNestedScroll(); 13025 13026 destroyDrawingCache(); 13027 13028 cleanupDraw(); 13029 mCurrentAnimation = null; 13030 } 13031 13032 private void cleanupDraw() { 13033 resetDisplayList(); 13034 if (mAttachInfo != null) { 13035 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 13036 } 13037 } 13038 13039 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 13040 } 13041 13042 /** 13043 * @return The number of times this view has been attached to a window 13044 */ 13045 protected int getWindowAttachCount() { 13046 return mWindowAttachCount; 13047 } 13048 13049 /** 13050 * Retrieve a unique token identifying the window this view is attached to. 13051 * @return Return the window's token for use in 13052 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13053 */ 13054 public IBinder getWindowToken() { 13055 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13056 } 13057 13058 /** 13059 * Retrieve the {@link WindowId} for the window this view is 13060 * currently attached to. 13061 */ 13062 public WindowId getWindowId() { 13063 if (mAttachInfo == null) { 13064 return null; 13065 } 13066 if (mAttachInfo.mWindowId == null) { 13067 try { 13068 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13069 mAttachInfo.mWindowToken); 13070 mAttachInfo.mWindowId = new WindowId( 13071 mAttachInfo.mIWindowId); 13072 } catch (RemoteException e) { 13073 } 13074 } 13075 return mAttachInfo.mWindowId; 13076 } 13077 13078 /** 13079 * Retrieve a unique token identifying the top-level "real" window of 13080 * the window that this view is attached to. That is, this is like 13081 * {@link #getWindowToken}, except if the window this view in is a panel 13082 * window (attached to another containing window), then the token of 13083 * the containing window is returned instead. 13084 * 13085 * @return Returns the associated window token, either 13086 * {@link #getWindowToken()} or the containing window's token. 13087 */ 13088 public IBinder getApplicationWindowToken() { 13089 AttachInfo ai = mAttachInfo; 13090 if (ai != null) { 13091 IBinder appWindowToken = ai.mPanelParentWindowToken; 13092 if (appWindowToken == null) { 13093 appWindowToken = ai.mWindowToken; 13094 } 13095 return appWindowToken; 13096 } 13097 return null; 13098 } 13099 13100 /** 13101 * Gets the logical display to which the view's window has been attached. 13102 * 13103 * @return The logical display, or null if the view is not currently attached to a window. 13104 */ 13105 public Display getDisplay() { 13106 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13107 } 13108 13109 /** 13110 * Retrieve private session object this view hierarchy is using to 13111 * communicate with the window manager. 13112 * @return the session object to communicate with the window manager 13113 */ 13114 /*package*/ IWindowSession getWindowSession() { 13115 return mAttachInfo != null ? mAttachInfo.mSession : null; 13116 } 13117 13118 /** 13119 * @param info the {@link android.view.View.AttachInfo} to associated with 13120 * this view 13121 */ 13122 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13123 //System.out.println("Attached! " + this); 13124 mAttachInfo = info; 13125 if (mOverlay != null) { 13126 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13127 } 13128 mWindowAttachCount++; 13129 // We will need to evaluate the drawable state at least once. 13130 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13131 if (mFloatingTreeObserver != null) { 13132 info.mTreeObserver.merge(mFloatingTreeObserver); 13133 mFloatingTreeObserver = null; 13134 } 13135 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13136 mAttachInfo.mScrollContainers.add(this); 13137 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13138 } 13139 performCollectViewAttributes(mAttachInfo, visibility); 13140 onAttachedToWindow(); 13141 13142 ListenerInfo li = mListenerInfo; 13143 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13144 li != null ? li.mOnAttachStateChangeListeners : null; 13145 if (listeners != null && listeners.size() > 0) { 13146 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13147 // perform the dispatching. The iterator is a safe guard against listeners that 13148 // could mutate the list by calling the various add/remove methods. This prevents 13149 // the array from being modified while we iterate it. 13150 for (OnAttachStateChangeListener listener : listeners) { 13151 listener.onViewAttachedToWindow(this); 13152 } 13153 } 13154 13155 int vis = info.mWindowVisibility; 13156 if (vis != GONE) { 13157 onWindowVisibilityChanged(vis); 13158 } 13159 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13160 // If nobody has evaluated the drawable state yet, then do it now. 13161 refreshDrawableState(); 13162 } 13163 needGlobalAttributesUpdate(false); 13164 } 13165 13166 void dispatchDetachedFromWindow() { 13167 AttachInfo info = mAttachInfo; 13168 if (info != null) { 13169 int vis = info.mWindowVisibility; 13170 if (vis != GONE) { 13171 onWindowVisibilityChanged(GONE); 13172 } 13173 } 13174 13175 onDetachedFromWindow(); 13176 onDetachedFromWindowInternal(); 13177 13178 ListenerInfo li = mListenerInfo; 13179 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13180 li != null ? li.mOnAttachStateChangeListeners : null; 13181 if (listeners != null && listeners.size() > 0) { 13182 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13183 // perform the dispatching. The iterator is a safe guard against listeners that 13184 // could mutate the list by calling the various add/remove methods. This prevents 13185 // the array from being modified while we iterate it. 13186 for (OnAttachStateChangeListener listener : listeners) { 13187 listener.onViewDetachedFromWindow(this); 13188 } 13189 } 13190 13191 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13192 mAttachInfo.mScrollContainers.remove(this); 13193 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13194 } 13195 13196 mAttachInfo = null; 13197 if (mOverlay != null) { 13198 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13199 } 13200 } 13201 13202 /** 13203 * Cancel any deferred high-level input events that were previously posted to the event queue. 13204 * 13205 * <p>Many views post high-level events such as click handlers to the event queue 13206 * to run deferred in order to preserve a desired user experience - clearing visible 13207 * pressed states before executing, etc. This method will abort any events of this nature 13208 * that are currently in flight.</p> 13209 * 13210 * <p>Custom views that generate their own high-level deferred input events should override 13211 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13212 * 13213 * <p>This will also cancel pending input events for any child views.</p> 13214 * 13215 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13216 * This will not impact newer events posted after this call that may occur as a result of 13217 * lower-level input events still waiting in the queue. If you are trying to prevent 13218 * double-submitted events for the duration of some sort of asynchronous transaction 13219 * you should also take other steps to protect against unexpected double inputs e.g. calling 13220 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13221 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13222 */ 13223 public final void cancelPendingInputEvents() { 13224 dispatchCancelPendingInputEvents(); 13225 } 13226 13227 /** 13228 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13229 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13230 */ 13231 void dispatchCancelPendingInputEvents() { 13232 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13233 onCancelPendingInputEvents(); 13234 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13235 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13236 " did not call through to super.onCancelPendingInputEvents()"); 13237 } 13238 } 13239 13240 /** 13241 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13242 * a parent view. 13243 * 13244 * <p>This method is responsible for removing any pending high-level input events that were 13245 * posted to the event queue to run later. Custom view classes that post their own deferred 13246 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13247 * {@link android.os.Handler} should override this method, call 13248 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13249 * </p> 13250 */ 13251 public void onCancelPendingInputEvents() { 13252 removePerformClickCallback(); 13253 cancelLongPress(); 13254 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13255 } 13256 13257 /** 13258 * Store this view hierarchy's frozen state into the given container. 13259 * 13260 * @param container The SparseArray in which to save the view's state. 13261 * 13262 * @see #restoreHierarchyState(android.util.SparseArray) 13263 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13264 * @see #onSaveInstanceState() 13265 */ 13266 public void saveHierarchyState(SparseArray<Parcelable> container) { 13267 dispatchSaveInstanceState(container); 13268 } 13269 13270 /** 13271 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13272 * this view and its children. May be overridden to modify how freezing happens to a 13273 * view's children; for example, some views may want to not store state for their children. 13274 * 13275 * @param container The SparseArray in which to save the view's state. 13276 * 13277 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13278 * @see #saveHierarchyState(android.util.SparseArray) 13279 * @see #onSaveInstanceState() 13280 */ 13281 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13282 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13283 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13284 Parcelable state = onSaveInstanceState(); 13285 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13286 throw new IllegalStateException( 13287 "Derived class did not call super.onSaveInstanceState()"); 13288 } 13289 if (state != null) { 13290 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13291 // + ": " + state); 13292 container.put(mID, state); 13293 } 13294 } 13295 } 13296 13297 /** 13298 * Hook allowing a view to generate a representation of its internal state 13299 * that can later be used to create a new instance with that same state. 13300 * This state should only contain information that is not persistent or can 13301 * not be reconstructed later. For example, you will never store your 13302 * current position on screen because that will be computed again when a 13303 * new instance of the view is placed in its view hierarchy. 13304 * <p> 13305 * Some examples of things you may store here: the current cursor position 13306 * in a text view (but usually not the text itself since that is stored in a 13307 * content provider or other persistent storage), the currently selected 13308 * item in a list view. 13309 * 13310 * @return Returns a Parcelable object containing the view's current dynamic 13311 * state, or null if there is nothing interesting to save. The 13312 * default implementation returns null. 13313 * @see #onRestoreInstanceState(android.os.Parcelable) 13314 * @see #saveHierarchyState(android.util.SparseArray) 13315 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13316 * @see #setSaveEnabled(boolean) 13317 */ 13318 protected Parcelable onSaveInstanceState() { 13319 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13320 return BaseSavedState.EMPTY_STATE; 13321 } 13322 13323 /** 13324 * Restore this view hierarchy's frozen state from the given container. 13325 * 13326 * @param container The SparseArray which holds previously frozen states. 13327 * 13328 * @see #saveHierarchyState(android.util.SparseArray) 13329 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13330 * @see #onRestoreInstanceState(android.os.Parcelable) 13331 */ 13332 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13333 dispatchRestoreInstanceState(container); 13334 } 13335 13336 /** 13337 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13338 * state for this view and its children. May be overridden to modify how restoring 13339 * happens to a view's children; for example, some views may want to not store state 13340 * for their children. 13341 * 13342 * @param container The SparseArray which holds previously saved state. 13343 * 13344 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13345 * @see #restoreHierarchyState(android.util.SparseArray) 13346 * @see #onRestoreInstanceState(android.os.Parcelable) 13347 */ 13348 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13349 if (mID != NO_ID) { 13350 Parcelable state = container.get(mID); 13351 if (state != null) { 13352 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13353 // + ": " + state); 13354 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13355 onRestoreInstanceState(state); 13356 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13357 throw new IllegalStateException( 13358 "Derived class did not call super.onRestoreInstanceState()"); 13359 } 13360 } 13361 } 13362 } 13363 13364 /** 13365 * Hook allowing a view to re-apply a representation of its internal state that had previously 13366 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13367 * null state. 13368 * 13369 * @param state The frozen state that had previously been returned by 13370 * {@link #onSaveInstanceState}. 13371 * 13372 * @see #onSaveInstanceState() 13373 * @see #restoreHierarchyState(android.util.SparseArray) 13374 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13375 */ 13376 protected void onRestoreInstanceState(Parcelable state) { 13377 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13378 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13379 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13380 + "received " + state.getClass().toString() + " instead. This usually happens " 13381 + "when two views of different type have the same id in the same hierarchy. " 13382 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13383 + "other views do not use the same id."); 13384 } 13385 } 13386 13387 /** 13388 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13389 * 13390 * @return the drawing start time in milliseconds 13391 */ 13392 public long getDrawingTime() { 13393 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13394 } 13395 13396 /** 13397 * <p>Enables or disables the duplication of the parent's state into this view. When 13398 * duplication is enabled, this view gets its drawable state from its parent rather 13399 * than from its own internal properties.</p> 13400 * 13401 * <p>Note: in the current implementation, setting this property to true after the 13402 * view was added to a ViewGroup might have no effect at all. This property should 13403 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13404 * 13405 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13406 * property is enabled, an exception will be thrown.</p> 13407 * 13408 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13409 * parent, these states should not be affected by this method.</p> 13410 * 13411 * @param enabled True to enable duplication of the parent's drawable state, false 13412 * to disable it. 13413 * 13414 * @see #getDrawableState() 13415 * @see #isDuplicateParentStateEnabled() 13416 */ 13417 public void setDuplicateParentStateEnabled(boolean enabled) { 13418 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13419 } 13420 13421 /** 13422 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13423 * 13424 * @return True if this view's drawable state is duplicated from the parent, 13425 * false otherwise 13426 * 13427 * @see #getDrawableState() 13428 * @see #setDuplicateParentStateEnabled(boolean) 13429 */ 13430 public boolean isDuplicateParentStateEnabled() { 13431 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13432 } 13433 13434 /** 13435 * <p>Specifies the type of layer backing this view. The layer can be 13436 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13437 * {@link #LAYER_TYPE_HARDWARE}.</p> 13438 * 13439 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13440 * instance that controls how the layer is composed on screen. The following 13441 * properties of the paint are taken into account when composing the layer:</p> 13442 * <ul> 13443 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13444 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13445 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13446 * </ul> 13447 * 13448 * <p>If this view has an alpha value set to < 1.0 by calling 13449 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13450 * by this view's alpha value.</p> 13451 * 13452 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13453 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13454 * for more information on when and how to use layers.</p> 13455 * 13456 * @param layerType The type of layer to use with this view, must be one of 13457 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13458 * {@link #LAYER_TYPE_HARDWARE} 13459 * @param paint The paint used to compose the layer. This argument is optional 13460 * and can be null. It is ignored when the layer type is 13461 * {@link #LAYER_TYPE_NONE} 13462 * 13463 * @see #getLayerType() 13464 * @see #LAYER_TYPE_NONE 13465 * @see #LAYER_TYPE_SOFTWARE 13466 * @see #LAYER_TYPE_HARDWARE 13467 * @see #setAlpha(float) 13468 * 13469 * @attr ref android.R.styleable#View_layerType 13470 */ 13471 public void setLayerType(int layerType, Paint paint) { 13472 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13473 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13474 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13475 } 13476 13477 boolean typeChanged = mRenderNode.setLayerType(layerType); 13478 13479 if (!typeChanged) { 13480 setLayerPaint(paint); 13481 return; 13482 } 13483 13484 // Destroy any previous software drawing cache if needed 13485 if (mLayerType == LAYER_TYPE_SOFTWARE) { 13486 destroyDrawingCache(); 13487 } 13488 13489 mLayerType = layerType; 13490 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 13491 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13492 mRenderNode.setLayerPaint(mLayerPaint); 13493 13494 // draw() behaves differently if we are on a layer, so we need to 13495 // invalidate() here 13496 invalidateParentCaches(); 13497 invalidate(true); 13498 } 13499 13500 /** 13501 * Updates the {@link Paint} object used with the current layer (used only if the current 13502 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13503 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13504 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13505 * ensure that the view gets redrawn immediately. 13506 * 13507 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13508 * instance that controls how the layer is composed on screen. The following 13509 * properties of the paint are taken into account when composing the layer:</p> 13510 * <ul> 13511 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13512 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13513 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13514 * </ul> 13515 * 13516 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13517 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13518 * 13519 * @param paint The paint used to compose the layer. This argument is optional 13520 * and can be null. It is ignored when the layer type is 13521 * {@link #LAYER_TYPE_NONE} 13522 * 13523 * @see #setLayerType(int, android.graphics.Paint) 13524 */ 13525 public void setLayerPaint(Paint paint) { 13526 int layerType = getLayerType(); 13527 if (layerType != LAYER_TYPE_NONE) { 13528 mLayerPaint = paint == null ? new Paint() : paint; 13529 if (layerType == LAYER_TYPE_HARDWARE) { 13530 if (mRenderNode.setLayerPaint(mLayerPaint)) { 13531 invalidateViewProperty(false, false); 13532 } 13533 } else { 13534 invalidate(); 13535 } 13536 } 13537 } 13538 13539 /** 13540 * Indicates whether this view has a static layer. A view with layer type 13541 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13542 * dynamic. 13543 */ 13544 boolean hasStaticLayer() { 13545 return true; 13546 } 13547 13548 /** 13549 * Indicates what type of layer is currently associated with this view. By default 13550 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13551 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13552 * for more information on the different types of layers. 13553 * 13554 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13555 * {@link #LAYER_TYPE_HARDWARE} 13556 * 13557 * @see #setLayerType(int, android.graphics.Paint) 13558 * @see #buildLayer() 13559 * @see #LAYER_TYPE_NONE 13560 * @see #LAYER_TYPE_SOFTWARE 13561 * @see #LAYER_TYPE_HARDWARE 13562 */ 13563 public int getLayerType() { 13564 return mLayerType; 13565 } 13566 13567 /** 13568 * Forces this view's layer to be created and this view to be rendered 13569 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13570 * invoking this method will have no effect. 13571 * 13572 * This method can for instance be used to render a view into its layer before 13573 * starting an animation. If this view is complex, rendering into the layer 13574 * before starting the animation will avoid skipping frames. 13575 * 13576 * @throws IllegalStateException If this view is not attached to a window 13577 * 13578 * @see #setLayerType(int, android.graphics.Paint) 13579 */ 13580 public void buildLayer() { 13581 if (mLayerType == LAYER_TYPE_NONE) return; 13582 13583 final AttachInfo attachInfo = mAttachInfo; 13584 if (attachInfo == null) { 13585 throw new IllegalStateException("This view must be attached to a window first"); 13586 } 13587 13588 if (getWidth() == 0 || getHeight() == 0) { 13589 return; 13590 } 13591 13592 switch (mLayerType) { 13593 case LAYER_TYPE_HARDWARE: 13594 // The only part of a hardware layer we can build in response to 13595 // this call is to ensure the display list is up to date. 13596 // The actual rendering of the display list into the layer must 13597 // be done at playback time 13598 updateDisplayListIfDirty(); 13599 break; 13600 case LAYER_TYPE_SOFTWARE: 13601 buildDrawingCache(true); 13602 break; 13603 } 13604 } 13605 13606 /** 13607 * If this View draws with a HardwareLayer, returns it. 13608 * Otherwise returns null 13609 * 13610 * TODO: Only TextureView uses this, can we eliminate it? 13611 */ 13612 HardwareLayer getHardwareLayer() { 13613 return null; 13614 } 13615 13616 /** 13617 * Destroys all hardware rendering resources. This method is invoked 13618 * when the system needs to reclaim resources. Upon execution of this 13619 * method, you should free any OpenGL resources created by the view. 13620 * 13621 * Note: you <strong>must</strong> call 13622 * <code>super.destroyHardwareResources()</code> when overriding 13623 * this method. 13624 * 13625 * @hide 13626 */ 13627 protected void destroyHardwareResources() { 13628 resetDisplayList(); 13629 } 13630 13631 /** 13632 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13633 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13634 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13635 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13636 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13637 * null.</p> 13638 * 13639 * <p>Enabling the drawing cache is similar to 13640 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13641 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13642 * drawing cache has no effect on rendering because the system uses a different mechanism 13643 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13644 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13645 * for information on how to enable software and hardware layers.</p> 13646 * 13647 * <p>This API can be used to manually generate 13648 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13649 * {@link #getDrawingCache()}.</p> 13650 * 13651 * @param enabled true to enable the drawing cache, false otherwise 13652 * 13653 * @see #isDrawingCacheEnabled() 13654 * @see #getDrawingCache() 13655 * @see #buildDrawingCache() 13656 * @see #setLayerType(int, android.graphics.Paint) 13657 */ 13658 public void setDrawingCacheEnabled(boolean enabled) { 13659 mCachingFailed = false; 13660 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13661 } 13662 13663 /** 13664 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13665 * 13666 * @return true if the drawing cache is enabled 13667 * 13668 * @see #setDrawingCacheEnabled(boolean) 13669 * @see #getDrawingCache() 13670 */ 13671 @ViewDebug.ExportedProperty(category = "drawing") 13672 public boolean isDrawingCacheEnabled() { 13673 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13674 } 13675 13676 /** 13677 * Debugging utility which recursively outputs the dirty state of a view and its 13678 * descendants. 13679 * 13680 * @hide 13681 */ 13682 @SuppressWarnings({"UnusedDeclaration"}) 13683 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13684 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13685 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13686 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13687 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13688 if (clear) { 13689 mPrivateFlags &= clearMask; 13690 } 13691 if (this instanceof ViewGroup) { 13692 ViewGroup parent = (ViewGroup) this; 13693 final int count = parent.getChildCount(); 13694 for (int i = 0; i < count; i++) { 13695 final View child = parent.getChildAt(i); 13696 child.outputDirtyFlags(indent + " ", clear, clearMask); 13697 } 13698 } 13699 } 13700 13701 /** 13702 * This method is used by ViewGroup to cause its children to restore or recreate their 13703 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13704 * to recreate its own display list, which would happen if it went through the normal 13705 * draw/dispatchDraw mechanisms. 13706 * 13707 * @hide 13708 */ 13709 protected void dispatchGetDisplayList() {} 13710 13711 /** 13712 * A view that is not attached or hardware accelerated cannot create a display list. 13713 * This method checks these conditions and returns the appropriate result. 13714 * 13715 * @return true if view has the ability to create a display list, false otherwise. 13716 * 13717 * @hide 13718 */ 13719 public boolean canHaveDisplayList() { 13720 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13721 } 13722 13723 private void updateDisplayListIfDirty() { 13724 final RenderNode renderNode = mRenderNode; 13725 if (!canHaveDisplayList()) { 13726 // can't populate RenderNode, don't try 13727 return; 13728 } 13729 13730 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13731 || !renderNode.isValid() 13732 || (mRecreateDisplayList)) { 13733 // Don't need to recreate the display list, just need to tell our 13734 // children to restore/recreate theirs 13735 if (renderNode.isValid() 13736 && !mRecreateDisplayList) { 13737 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13738 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13739 dispatchGetDisplayList(); 13740 13741 return; // no work needed 13742 } 13743 13744 // If we got here, we're recreating it. Mark it as such to ensure that 13745 // we copy in child display lists into ours in drawChild() 13746 mRecreateDisplayList = true; 13747 13748 int width = mRight - mLeft; 13749 int height = mBottom - mTop; 13750 int layerType = getLayerType(); 13751 13752 final HardwareCanvas canvas = renderNode.start(width, height); 13753 13754 try { 13755 final HardwareLayer layer = getHardwareLayer(); 13756 if (layer != null && layer.isValid()) { 13757 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13758 } else if (layerType == LAYER_TYPE_SOFTWARE) { 13759 buildDrawingCache(true); 13760 Bitmap cache = getDrawingCache(true); 13761 if (cache != null) { 13762 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13763 } 13764 } else { 13765 computeScroll(); 13766 13767 canvas.translate(-mScrollX, -mScrollY); 13768 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13769 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13770 13771 // Fast path for layouts with no backgrounds 13772 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13773 dispatchDraw(canvas); 13774 if (mOverlay != null && !mOverlay.isEmpty()) { 13775 mOverlay.getOverlayView().draw(canvas); 13776 } 13777 } else { 13778 draw(canvas); 13779 } 13780 } 13781 } finally { 13782 renderNode.end(canvas); 13783 setDisplayListProperties(renderNode); 13784 } 13785 } else { 13786 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13787 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13788 } 13789 } 13790 13791 /** 13792 * Returns a RenderNode with View draw content recorded, which can be 13793 * used to draw this view again without executing its draw method. 13794 * 13795 * @return A RenderNode ready to replay, or null if caching is not enabled. 13796 * 13797 * @hide 13798 */ 13799 public RenderNode getDisplayList() { 13800 updateDisplayListIfDirty(); 13801 return mRenderNode; 13802 } 13803 13804 private void resetDisplayList() { 13805 if (mRenderNode.isValid()) { 13806 mRenderNode.destroyDisplayListData(); 13807 } 13808 13809 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 13810 mBackgroundRenderNode.destroyDisplayListData(); 13811 } 13812 } 13813 13814 /** 13815 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13816 * 13817 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13818 * 13819 * @see #getDrawingCache(boolean) 13820 */ 13821 public Bitmap getDrawingCache() { 13822 return getDrawingCache(false); 13823 } 13824 13825 /** 13826 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13827 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13828 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13829 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13830 * request the drawing cache by calling this method and draw it on screen if the 13831 * returned bitmap is not null.</p> 13832 * 13833 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13834 * this method will create a bitmap of the same size as this view. Because this bitmap 13835 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13836 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13837 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13838 * size than the view. This implies that your application must be able to handle this 13839 * size.</p> 13840 * 13841 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13842 * the current density of the screen when the application is in compatibility 13843 * mode. 13844 * 13845 * @return A bitmap representing this view or null if cache is disabled. 13846 * 13847 * @see #setDrawingCacheEnabled(boolean) 13848 * @see #isDrawingCacheEnabled() 13849 * @see #buildDrawingCache(boolean) 13850 * @see #destroyDrawingCache() 13851 */ 13852 public Bitmap getDrawingCache(boolean autoScale) { 13853 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13854 return null; 13855 } 13856 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13857 buildDrawingCache(autoScale); 13858 } 13859 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13860 } 13861 13862 /** 13863 * <p>Frees the resources used by the drawing cache. If you call 13864 * {@link #buildDrawingCache()} manually without calling 13865 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13866 * should cleanup the cache with this method afterwards.</p> 13867 * 13868 * @see #setDrawingCacheEnabled(boolean) 13869 * @see #buildDrawingCache() 13870 * @see #getDrawingCache() 13871 */ 13872 public void destroyDrawingCache() { 13873 if (mDrawingCache != null) { 13874 mDrawingCache.recycle(); 13875 mDrawingCache = null; 13876 } 13877 if (mUnscaledDrawingCache != null) { 13878 mUnscaledDrawingCache.recycle(); 13879 mUnscaledDrawingCache = null; 13880 } 13881 } 13882 13883 /** 13884 * Setting a solid background color for the drawing cache's bitmaps will improve 13885 * performance and memory usage. Note, though that this should only be used if this 13886 * view will always be drawn on top of a solid color. 13887 * 13888 * @param color The background color to use for the drawing cache's bitmap 13889 * 13890 * @see #setDrawingCacheEnabled(boolean) 13891 * @see #buildDrawingCache() 13892 * @see #getDrawingCache() 13893 */ 13894 public void setDrawingCacheBackgroundColor(int color) { 13895 if (color != mDrawingCacheBackgroundColor) { 13896 mDrawingCacheBackgroundColor = color; 13897 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13898 } 13899 } 13900 13901 /** 13902 * @see #setDrawingCacheBackgroundColor(int) 13903 * 13904 * @return The background color to used for the drawing cache's bitmap 13905 */ 13906 public int getDrawingCacheBackgroundColor() { 13907 return mDrawingCacheBackgroundColor; 13908 } 13909 13910 /** 13911 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13912 * 13913 * @see #buildDrawingCache(boolean) 13914 */ 13915 public void buildDrawingCache() { 13916 buildDrawingCache(false); 13917 } 13918 13919 /** 13920 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13921 * 13922 * <p>If you call {@link #buildDrawingCache()} manually without calling 13923 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13924 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13925 * 13926 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13927 * this method will create a bitmap of the same size as this view. Because this bitmap 13928 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13929 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13930 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13931 * size than the view. This implies that your application must be able to handle this 13932 * size.</p> 13933 * 13934 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13935 * you do not need the drawing cache bitmap, calling this method will increase memory 13936 * usage and cause the view to be rendered in software once, thus negatively impacting 13937 * performance.</p> 13938 * 13939 * @see #getDrawingCache() 13940 * @see #destroyDrawingCache() 13941 */ 13942 public void buildDrawingCache(boolean autoScale) { 13943 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13944 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13945 mCachingFailed = false; 13946 13947 int width = mRight - mLeft; 13948 int height = mBottom - mTop; 13949 13950 final AttachInfo attachInfo = mAttachInfo; 13951 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13952 13953 if (autoScale && scalingRequired) { 13954 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13955 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13956 } 13957 13958 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13959 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13960 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13961 13962 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13963 final long drawingCacheSize = 13964 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13965 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13966 if (width > 0 && height > 0) { 13967 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13968 + projectedBitmapSize + " bytes, only " 13969 + drawingCacheSize + " available"); 13970 } 13971 destroyDrawingCache(); 13972 mCachingFailed = true; 13973 return; 13974 } 13975 13976 boolean clear = true; 13977 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13978 13979 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13980 Bitmap.Config quality; 13981 if (!opaque) { 13982 // Never pick ARGB_4444 because it looks awful 13983 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13984 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13985 case DRAWING_CACHE_QUALITY_AUTO: 13986 case DRAWING_CACHE_QUALITY_LOW: 13987 case DRAWING_CACHE_QUALITY_HIGH: 13988 default: 13989 quality = Bitmap.Config.ARGB_8888; 13990 break; 13991 } 13992 } else { 13993 // Optimization for translucent windows 13994 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13995 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13996 } 13997 13998 // Try to cleanup memory 13999 if (bitmap != null) bitmap.recycle(); 14000 14001 try { 14002 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14003 width, height, quality); 14004 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14005 if (autoScale) { 14006 mDrawingCache = bitmap; 14007 } else { 14008 mUnscaledDrawingCache = bitmap; 14009 } 14010 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14011 } catch (OutOfMemoryError e) { 14012 // If there is not enough memory to create the bitmap cache, just 14013 // ignore the issue as bitmap caches are not required to draw the 14014 // view hierarchy 14015 if (autoScale) { 14016 mDrawingCache = null; 14017 } else { 14018 mUnscaledDrawingCache = null; 14019 } 14020 mCachingFailed = true; 14021 return; 14022 } 14023 14024 clear = drawingCacheBackgroundColor != 0; 14025 } 14026 14027 Canvas canvas; 14028 if (attachInfo != null) { 14029 canvas = attachInfo.mCanvas; 14030 if (canvas == null) { 14031 canvas = new Canvas(); 14032 } 14033 canvas.setBitmap(bitmap); 14034 // Temporarily clobber the cached Canvas in case one of our children 14035 // is also using a drawing cache. Without this, the children would 14036 // steal the canvas by attaching their own bitmap to it and bad, bad 14037 // thing would happen (invisible views, corrupted drawings, etc.) 14038 attachInfo.mCanvas = null; 14039 } else { 14040 // This case should hopefully never or seldom happen 14041 canvas = new Canvas(bitmap); 14042 } 14043 14044 if (clear) { 14045 bitmap.eraseColor(drawingCacheBackgroundColor); 14046 } 14047 14048 computeScroll(); 14049 final int restoreCount = canvas.save(); 14050 14051 if (autoScale && scalingRequired) { 14052 final float scale = attachInfo.mApplicationScale; 14053 canvas.scale(scale, scale); 14054 } 14055 14056 canvas.translate(-mScrollX, -mScrollY); 14057 14058 mPrivateFlags |= PFLAG_DRAWN; 14059 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14060 mLayerType != LAYER_TYPE_NONE) { 14061 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14062 } 14063 14064 // Fast path for layouts with no backgrounds 14065 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14066 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14067 dispatchDraw(canvas); 14068 if (mOverlay != null && !mOverlay.isEmpty()) { 14069 mOverlay.getOverlayView().draw(canvas); 14070 } 14071 } else { 14072 draw(canvas); 14073 } 14074 14075 canvas.restoreToCount(restoreCount); 14076 canvas.setBitmap(null); 14077 14078 if (attachInfo != null) { 14079 // Restore the cached Canvas for our siblings 14080 attachInfo.mCanvas = canvas; 14081 } 14082 } 14083 } 14084 14085 /** 14086 * Create a snapshot of the view into a bitmap. We should probably make 14087 * some form of this public, but should think about the API. 14088 */ 14089 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14090 int width = mRight - mLeft; 14091 int height = mBottom - mTop; 14092 14093 final AttachInfo attachInfo = mAttachInfo; 14094 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14095 width = (int) ((width * scale) + 0.5f); 14096 height = (int) ((height * scale) + 0.5f); 14097 14098 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14099 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14100 if (bitmap == null) { 14101 throw new OutOfMemoryError(); 14102 } 14103 14104 Resources resources = getResources(); 14105 if (resources != null) { 14106 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14107 } 14108 14109 Canvas canvas; 14110 if (attachInfo != null) { 14111 canvas = attachInfo.mCanvas; 14112 if (canvas == null) { 14113 canvas = new Canvas(); 14114 } 14115 canvas.setBitmap(bitmap); 14116 // Temporarily clobber the cached Canvas in case one of our children 14117 // is also using a drawing cache. Without this, the children would 14118 // steal the canvas by attaching their own bitmap to it and bad, bad 14119 // things would happen (invisible views, corrupted drawings, etc.) 14120 attachInfo.mCanvas = null; 14121 } else { 14122 // This case should hopefully never or seldom happen 14123 canvas = new Canvas(bitmap); 14124 } 14125 14126 if ((backgroundColor & 0xff000000) != 0) { 14127 bitmap.eraseColor(backgroundColor); 14128 } 14129 14130 computeScroll(); 14131 final int restoreCount = canvas.save(); 14132 canvas.scale(scale, scale); 14133 canvas.translate(-mScrollX, -mScrollY); 14134 14135 // Temporarily remove the dirty mask 14136 int flags = mPrivateFlags; 14137 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14138 14139 // Fast path for layouts with no backgrounds 14140 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14141 dispatchDraw(canvas); 14142 if (mOverlay != null && !mOverlay.isEmpty()) { 14143 mOverlay.getOverlayView().draw(canvas); 14144 } 14145 } else { 14146 draw(canvas); 14147 } 14148 14149 mPrivateFlags = flags; 14150 14151 canvas.restoreToCount(restoreCount); 14152 canvas.setBitmap(null); 14153 14154 if (attachInfo != null) { 14155 // Restore the cached Canvas for our siblings 14156 attachInfo.mCanvas = canvas; 14157 } 14158 14159 return bitmap; 14160 } 14161 14162 /** 14163 * Indicates whether this View is currently in edit mode. A View is usually 14164 * in edit mode when displayed within a developer tool. For instance, if 14165 * this View is being drawn by a visual user interface builder, this method 14166 * should return true. 14167 * 14168 * Subclasses should check the return value of this method to provide 14169 * different behaviors if their normal behavior might interfere with the 14170 * host environment. For instance: the class spawns a thread in its 14171 * constructor, the drawing code relies on device-specific features, etc. 14172 * 14173 * This method is usually checked in the drawing code of custom widgets. 14174 * 14175 * @return True if this View is in edit mode, false otherwise. 14176 */ 14177 public boolean isInEditMode() { 14178 return false; 14179 } 14180 14181 /** 14182 * If the View draws content inside its padding and enables fading edges, 14183 * it needs to support padding offsets. Padding offsets are added to the 14184 * fading edges to extend the length of the fade so that it covers pixels 14185 * drawn inside the padding. 14186 * 14187 * Subclasses of this class should override this method if they need 14188 * to draw content inside the padding. 14189 * 14190 * @return True if padding offset must be applied, false otherwise. 14191 * 14192 * @see #getLeftPaddingOffset() 14193 * @see #getRightPaddingOffset() 14194 * @see #getTopPaddingOffset() 14195 * @see #getBottomPaddingOffset() 14196 * 14197 * @since CURRENT 14198 */ 14199 protected boolean isPaddingOffsetRequired() { 14200 return false; 14201 } 14202 14203 /** 14204 * Amount by which to extend the left fading region. Called only when 14205 * {@link #isPaddingOffsetRequired()} returns true. 14206 * 14207 * @return The left padding offset in pixels. 14208 * 14209 * @see #isPaddingOffsetRequired() 14210 * 14211 * @since CURRENT 14212 */ 14213 protected int getLeftPaddingOffset() { 14214 return 0; 14215 } 14216 14217 /** 14218 * Amount by which to extend the right fading region. Called only when 14219 * {@link #isPaddingOffsetRequired()} returns true. 14220 * 14221 * @return The right padding offset in pixels. 14222 * 14223 * @see #isPaddingOffsetRequired() 14224 * 14225 * @since CURRENT 14226 */ 14227 protected int getRightPaddingOffset() { 14228 return 0; 14229 } 14230 14231 /** 14232 * Amount by which to extend the top fading region. Called only when 14233 * {@link #isPaddingOffsetRequired()} returns true. 14234 * 14235 * @return The top padding offset in pixels. 14236 * 14237 * @see #isPaddingOffsetRequired() 14238 * 14239 * @since CURRENT 14240 */ 14241 protected int getTopPaddingOffset() { 14242 return 0; 14243 } 14244 14245 /** 14246 * Amount by which to extend the bottom fading region. Called only when 14247 * {@link #isPaddingOffsetRequired()} returns true. 14248 * 14249 * @return The bottom padding offset in pixels. 14250 * 14251 * @see #isPaddingOffsetRequired() 14252 * 14253 * @since CURRENT 14254 */ 14255 protected int getBottomPaddingOffset() { 14256 return 0; 14257 } 14258 14259 /** 14260 * @hide 14261 * @param offsetRequired 14262 */ 14263 protected int getFadeTop(boolean offsetRequired) { 14264 int top = mPaddingTop; 14265 if (offsetRequired) top += getTopPaddingOffset(); 14266 return top; 14267 } 14268 14269 /** 14270 * @hide 14271 * @param offsetRequired 14272 */ 14273 protected int getFadeHeight(boolean offsetRequired) { 14274 int padding = mPaddingTop; 14275 if (offsetRequired) padding += getTopPaddingOffset(); 14276 return mBottom - mTop - mPaddingBottom - padding; 14277 } 14278 14279 /** 14280 * <p>Indicates whether this view is attached to a hardware accelerated 14281 * window or not.</p> 14282 * 14283 * <p>Even if this method returns true, it does not mean that every call 14284 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14285 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14286 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14287 * window is hardware accelerated, 14288 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14289 * return false, and this method will return true.</p> 14290 * 14291 * @return True if the view is attached to a window and the window is 14292 * hardware accelerated; false in any other case. 14293 */ 14294 @ViewDebug.ExportedProperty(category = "drawing") 14295 public boolean isHardwareAccelerated() { 14296 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14297 } 14298 14299 /** 14300 * Sets a rectangular area on this view to which the view will be clipped 14301 * when it is drawn. Setting the value to null will remove the clip bounds 14302 * and the view will draw normally, using its full bounds. 14303 * 14304 * @param clipBounds The rectangular area, in the local coordinates of 14305 * this view, to which future drawing operations will be clipped. 14306 */ 14307 public void setClipBounds(Rect clipBounds) { 14308 if (clipBounds != null) { 14309 if (clipBounds.equals(mClipBounds)) { 14310 return; 14311 } 14312 if (mClipBounds == null) { 14313 invalidate(); 14314 mClipBounds = new Rect(clipBounds); 14315 } else { 14316 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14317 Math.min(mClipBounds.top, clipBounds.top), 14318 Math.max(mClipBounds.right, clipBounds.right), 14319 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14320 mClipBounds.set(clipBounds); 14321 } 14322 } else { 14323 if (mClipBounds != null) { 14324 invalidate(); 14325 mClipBounds = null; 14326 } 14327 } 14328 } 14329 14330 /** 14331 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14332 * 14333 * @return A copy of the current clip bounds if clip bounds are set, 14334 * otherwise null. 14335 */ 14336 public Rect getClipBounds() { 14337 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14338 } 14339 14340 /** 14341 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14342 * case of an active Animation being run on the view. 14343 */ 14344 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14345 Animation a, boolean scalingRequired) { 14346 Transformation invalidationTransform; 14347 final int flags = parent.mGroupFlags; 14348 final boolean initialized = a.isInitialized(); 14349 if (!initialized) { 14350 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14351 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14352 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14353 onAnimationStart(); 14354 } 14355 14356 final Transformation t = parent.getChildTransformation(); 14357 boolean more = a.getTransformation(drawingTime, t, 1f); 14358 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14359 if (parent.mInvalidationTransformation == null) { 14360 parent.mInvalidationTransformation = new Transformation(); 14361 } 14362 invalidationTransform = parent.mInvalidationTransformation; 14363 a.getTransformation(drawingTime, invalidationTransform, 1f); 14364 } else { 14365 invalidationTransform = t; 14366 } 14367 14368 if (more) { 14369 if (!a.willChangeBounds()) { 14370 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14371 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14372 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14373 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14374 // The child need to draw an animation, potentially offscreen, so 14375 // make sure we do not cancel invalidate requests 14376 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14377 parent.invalidate(mLeft, mTop, mRight, mBottom); 14378 } 14379 } else { 14380 if (parent.mInvalidateRegion == null) { 14381 parent.mInvalidateRegion = new RectF(); 14382 } 14383 final RectF region = parent.mInvalidateRegion; 14384 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14385 invalidationTransform); 14386 14387 // The child need to draw an animation, potentially offscreen, so 14388 // make sure we do not cancel invalidate requests 14389 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14390 14391 final int left = mLeft + (int) region.left; 14392 final int top = mTop + (int) region.top; 14393 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14394 top + (int) (region.height() + .5f)); 14395 } 14396 } 14397 return more; 14398 } 14399 14400 /** 14401 * This method is called by getDisplayList() when a display list is recorded for a View. 14402 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14403 */ 14404 void setDisplayListProperties(RenderNode renderNode) { 14405 if (renderNode != null) { 14406 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14407 if (mParent instanceof ViewGroup) { 14408 renderNode.setClipToBounds( 14409 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14410 } 14411 float alpha = 1; 14412 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14413 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14414 ViewGroup parentVG = (ViewGroup) mParent; 14415 final Transformation t = parentVG.getChildTransformation(); 14416 if (parentVG.getChildStaticTransformation(this, t)) { 14417 final int transformType = t.getTransformationType(); 14418 if (transformType != Transformation.TYPE_IDENTITY) { 14419 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14420 alpha = t.getAlpha(); 14421 } 14422 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14423 renderNode.setStaticMatrix(t.getMatrix()); 14424 } 14425 } 14426 } 14427 } 14428 if (mTransformationInfo != null) { 14429 alpha *= getFinalAlpha(); 14430 if (alpha < 1) { 14431 final int multipliedAlpha = (int) (255 * alpha); 14432 if (onSetAlpha(multipliedAlpha)) { 14433 alpha = 1; 14434 } 14435 } 14436 renderNode.setAlpha(alpha); 14437 } else if (alpha < 1) { 14438 renderNode.setAlpha(alpha); 14439 } 14440 } 14441 } 14442 14443 /** 14444 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14445 * This draw() method is an implementation detail and is not intended to be overridden or 14446 * to be called from anywhere else other than ViewGroup.drawChild(). 14447 */ 14448 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14449 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14450 boolean more = false; 14451 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14452 final int flags = parent.mGroupFlags; 14453 14454 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14455 parent.getChildTransformation().clear(); 14456 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14457 } 14458 14459 Transformation transformToApply = null; 14460 boolean concatMatrix = false; 14461 14462 boolean scalingRequired = false; 14463 boolean caching; 14464 int layerType = getLayerType(); 14465 14466 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14467 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14468 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14469 caching = true; 14470 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14471 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14472 } else { 14473 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14474 } 14475 14476 final Animation a = getAnimation(); 14477 if (a != null) { 14478 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14479 concatMatrix = a.willChangeTransformationMatrix(); 14480 if (concatMatrix) { 14481 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14482 } 14483 transformToApply = parent.getChildTransformation(); 14484 } else { 14485 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14486 // No longer animating: clear out old animation matrix 14487 mRenderNode.setAnimationMatrix(null); 14488 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14489 } 14490 if (!useDisplayListProperties && 14491 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14492 final Transformation t = parent.getChildTransformation(); 14493 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14494 if (hasTransform) { 14495 final int transformType = t.getTransformationType(); 14496 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14497 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14498 } 14499 } 14500 } 14501 14502 concatMatrix |= !childHasIdentityMatrix; 14503 14504 // Sets the flag as early as possible to allow draw() implementations 14505 // to call invalidate() successfully when doing animations 14506 mPrivateFlags |= PFLAG_DRAWN; 14507 14508 if (!concatMatrix && 14509 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14510 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14511 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14512 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14513 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14514 return more; 14515 } 14516 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14517 14518 if (hardwareAccelerated) { 14519 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14520 // retain the flag's value temporarily in the mRecreateDisplayList flag 14521 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14522 mPrivateFlags &= ~PFLAG_INVALIDATED; 14523 } 14524 14525 RenderNode renderNode = null; 14526 Bitmap cache = null; 14527 boolean hasDisplayList = false; 14528 if (caching) { 14529 if (!hardwareAccelerated) { 14530 if (layerType != LAYER_TYPE_NONE) { 14531 layerType = LAYER_TYPE_SOFTWARE; 14532 buildDrawingCache(true); 14533 } 14534 cache = getDrawingCache(true); 14535 } else { 14536 switch (layerType) { 14537 case LAYER_TYPE_SOFTWARE: 14538 if (useDisplayListProperties) { 14539 hasDisplayList = canHaveDisplayList(); 14540 } else { 14541 buildDrawingCache(true); 14542 cache = getDrawingCache(true); 14543 } 14544 break; 14545 case LAYER_TYPE_HARDWARE: 14546 if (useDisplayListProperties) { 14547 hasDisplayList = canHaveDisplayList(); 14548 } 14549 break; 14550 case LAYER_TYPE_NONE: 14551 // Delay getting the display list until animation-driven alpha values are 14552 // set up and possibly passed on to the view 14553 hasDisplayList = canHaveDisplayList(); 14554 break; 14555 } 14556 } 14557 } 14558 useDisplayListProperties &= hasDisplayList; 14559 if (useDisplayListProperties) { 14560 renderNode = getDisplayList(); 14561 if (!renderNode.isValid()) { 14562 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14563 // to getDisplayList(), the display list will be marked invalid and we should not 14564 // try to use it again. 14565 renderNode = null; 14566 hasDisplayList = false; 14567 useDisplayListProperties = false; 14568 } 14569 } 14570 14571 int sx = 0; 14572 int sy = 0; 14573 if (!hasDisplayList) { 14574 computeScroll(); 14575 sx = mScrollX; 14576 sy = mScrollY; 14577 } 14578 14579 final boolean hasNoCache = cache == null || hasDisplayList; 14580 final boolean offsetForScroll = cache == null && !hasDisplayList && 14581 layerType != LAYER_TYPE_HARDWARE; 14582 14583 int restoreTo = -1; 14584 if (!useDisplayListProperties || transformToApply != null) { 14585 restoreTo = canvas.save(); 14586 } 14587 if (offsetForScroll) { 14588 canvas.translate(mLeft - sx, mTop - sy); 14589 } else { 14590 if (!useDisplayListProperties) { 14591 canvas.translate(mLeft, mTop); 14592 } 14593 if (scalingRequired) { 14594 if (useDisplayListProperties) { 14595 // TODO: Might not need this if we put everything inside the DL 14596 restoreTo = canvas.save(); 14597 } 14598 // mAttachInfo cannot be null, otherwise scalingRequired == false 14599 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14600 canvas.scale(scale, scale); 14601 } 14602 } 14603 14604 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14605 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14606 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14607 if (transformToApply != null || !childHasIdentityMatrix) { 14608 int transX = 0; 14609 int transY = 0; 14610 14611 if (offsetForScroll) { 14612 transX = -sx; 14613 transY = -sy; 14614 } 14615 14616 if (transformToApply != null) { 14617 if (concatMatrix) { 14618 if (useDisplayListProperties) { 14619 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 14620 } else { 14621 // Undo the scroll translation, apply the transformation matrix, 14622 // then redo the scroll translate to get the correct result. 14623 canvas.translate(-transX, -transY); 14624 canvas.concat(transformToApply.getMatrix()); 14625 canvas.translate(transX, transY); 14626 } 14627 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14628 } 14629 14630 float transformAlpha = transformToApply.getAlpha(); 14631 if (transformAlpha < 1) { 14632 alpha *= transformAlpha; 14633 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14634 } 14635 } 14636 14637 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14638 canvas.translate(-transX, -transY); 14639 canvas.concat(getMatrix()); 14640 canvas.translate(transX, transY); 14641 } 14642 } 14643 14644 // Deal with alpha if it is or used to be <1 14645 if (alpha < 1 || 14646 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14647 if (alpha < 1) { 14648 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14649 } else { 14650 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14651 } 14652 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14653 if (hasNoCache) { 14654 final int multipliedAlpha = (int) (255 * alpha); 14655 if (!onSetAlpha(multipliedAlpha)) { 14656 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14657 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14658 layerType != LAYER_TYPE_NONE) { 14659 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14660 } 14661 if (useDisplayListProperties) { 14662 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14663 } else if (layerType == LAYER_TYPE_NONE) { 14664 final int scrollX = hasDisplayList ? 0 : sx; 14665 final int scrollY = hasDisplayList ? 0 : sy; 14666 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14667 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14668 } 14669 } else { 14670 // Alpha is handled by the child directly, clobber the layer's alpha 14671 mPrivateFlags |= PFLAG_ALPHA_SET; 14672 } 14673 } 14674 } 14675 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14676 onSetAlpha(255); 14677 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14678 } 14679 14680 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14681 !useDisplayListProperties && cache == null) { 14682 if (offsetForScroll) { 14683 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14684 } else { 14685 if (!scalingRequired || cache == null) { 14686 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14687 } else { 14688 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14689 } 14690 } 14691 } 14692 14693 if (!useDisplayListProperties && hasDisplayList) { 14694 renderNode = getDisplayList(); 14695 if (!renderNode.isValid()) { 14696 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14697 // to getDisplayList(), the display list will be marked invalid and we should not 14698 // try to use it again. 14699 renderNode = null; 14700 hasDisplayList = false; 14701 } 14702 } 14703 14704 if (hasNoCache) { 14705 boolean layerRendered = false; 14706 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14707 final HardwareLayer layer = getHardwareLayer(); 14708 if (layer != null && layer.isValid()) { 14709 mLayerPaint.setAlpha((int) (alpha * 255)); 14710 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14711 layerRendered = true; 14712 } else { 14713 final int scrollX = hasDisplayList ? 0 : sx; 14714 final int scrollY = hasDisplayList ? 0 : sy; 14715 canvas.saveLayer(scrollX, scrollY, 14716 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14717 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14718 } 14719 } 14720 14721 if (!layerRendered) { 14722 if (!hasDisplayList) { 14723 // Fast path for layouts with no backgrounds 14724 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14725 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14726 dispatchDraw(canvas); 14727 } else { 14728 draw(canvas); 14729 } 14730 } else { 14731 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14732 ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags); 14733 } 14734 } 14735 } else if (cache != null) { 14736 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14737 Paint cachePaint; 14738 14739 if (layerType == LAYER_TYPE_NONE) { 14740 cachePaint = parent.mCachePaint; 14741 if (cachePaint == null) { 14742 cachePaint = new Paint(); 14743 cachePaint.setDither(false); 14744 parent.mCachePaint = cachePaint; 14745 } 14746 if (alpha < 1) { 14747 cachePaint.setAlpha((int) (alpha * 255)); 14748 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14749 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14750 cachePaint.setAlpha(255); 14751 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14752 } 14753 } else { 14754 cachePaint = mLayerPaint; 14755 cachePaint.setAlpha((int) (alpha * 255)); 14756 } 14757 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14758 } 14759 14760 if (restoreTo >= 0) { 14761 canvas.restoreToCount(restoreTo); 14762 } 14763 14764 if (a != null && !more) { 14765 if (!hardwareAccelerated && !a.getFillAfter()) { 14766 onSetAlpha(255); 14767 } 14768 parent.finishAnimatingView(this, a); 14769 } 14770 14771 if (more && hardwareAccelerated) { 14772 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14773 // alpha animations should cause the child to recreate its display list 14774 invalidate(true); 14775 } 14776 } 14777 14778 mRecreateDisplayList = false; 14779 14780 return more; 14781 } 14782 14783 /** 14784 * Manually render this view (and all of its children) to the given Canvas. 14785 * The view must have already done a full layout before this function is 14786 * called. When implementing a view, implement 14787 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14788 * If you do need to override this method, call the superclass version. 14789 * 14790 * @param canvas The Canvas to which the View is rendered. 14791 */ 14792 public void draw(Canvas canvas) { 14793 if (mClipBounds != null) { 14794 canvas.clipRect(mClipBounds); 14795 } 14796 final int privateFlags = mPrivateFlags; 14797 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14798 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14799 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14800 14801 /* 14802 * Draw traversal performs several drawing steps which must be executed 14803 * in the appropriate order: 14804 * 14805 * 1. Draw the background 14806 * 2. If necessary, save the canvas' layers to prepare for fading 14807 * 3. Draw view's content 14808 * 4. Draw children 14809 * 5. If necessary, draw the fading edges and restore layers 14810 * 6. Draw decorations (scrollbars for instance) 14811 */ 14812 14813 // Step 1, draw the background, if needed 14814 int saveCount; 14815 14816 if (!dirtyOpaque) { 14817 drawBackground(canvas); 14818 } 14819 14820 // skip step 2 & 5 if possible (common case) 14821 final int viewFlags = mViewFlags; 14822 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14823 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14824 if (!verticalEdges && !horizontalEdges) { 14825 // Step 3, draw the content 14826 if (!dirtyOpaque) onDraw(canvas); 14827 14828 // Step 4, draw the children 14829 dispatchDraw(canvas); 14830 14831 // Step 6, draw decorations (scrollbars) 14832 onDrawScrollBars(canvas); 14833 14834 if (mOverlay != null && !mOverlay.isEmpty()) { 14835 mOverlay.getOverlayView().dispatchDraw(canvas); 14836 } 14837 14838 // we're done... 14839 return; 14840 } 14841 14842 /* 14843 * Here we do the full fledged routine... 14844 * (this is an uncommon case where speed matters less, 14845 * this is why we repeat some of the tests that have been 14846 * done above) 14847 */ 14848 14849 boolean drawTop = false; 14850 boolean drawBottom = false; 14851 boolean drawLeft = false; 14852 boolean drawRight = false; 14853 14854 float topFadeStrength = 0.0f; 14855 float bottomFadeStrength = 0.0f; 14856 float leftFadeStrength = 0.0f; 14857 float rightFadeStrength = 0.0f; 14858 14859 // Step 2, save the canvas' layers 14860 int paddingLeft = mPaddingLeft; 14861 14862 final boolean offsetRequired = isPaddingOffsetRequired(); 14863 if (offsetRequired) { 14864 paddingLeft += getLeftPaddingOffset(); 14865 } 14866 14867 int left = mScrollX + paddingLeft; 14868 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14869 int top = mScrollY + getFadeTop(offsetRequired); 14870 int bottom = top + getFadeHeight(offsetRequired); 14871 14872 if (offsetRequired) { 14873 right += getRightPaddingOffset(); 14874 bottom += getBottomPaddingOffset(); 14875 } 14876 14877 final ScrollabilityCache scrollabilityCache = mScrollCache; 14878 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14879 int length = (int) fadeHeight; 14880 14881 // clip the fade length if top and bottom fades overlap 14882 // overlapping fades produce odd-looking artifacts 14883 if (verticalEdges && (top + length > bottom - length)) { 14884 length = (bottom - top) / 2; 14885 } 14886 14887 // also clip horizontal fades if necessary 14888 if (horizontalEdges && (left + length > right - length)) { 14889 length = (right - left) / 2; 14890 } 14891 14892 if (verticalEdges) { 14893 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14894 drawTop = topFadeStrength * fadeHeight > 1.0f; 14895 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14896 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14897 } 14898 14899 if (horizontalEdges) { 14900 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14901 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14902 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14903 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14904 } 14905 14906 saveCount = canvas.getSaveCount(); 14907 14908 int solidColor = getSolidColor(); 14909 if (solidColor == 0) { 14910 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14911 14912 if (drawTop) { 14913 canvas.saveLayer(left, top, right, top + length, null, flags); 14914 } 14915 14916 if (drawBottom) { 14917 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14918 } 14919 14920 if (drawLeft) { 14921 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14922 } 14923 14924 if (drawRight) { 14925 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14926 } 14927 } else { 14928 scrollabilityCache.setFadeColor(solidColor); 14929 } 14930 14931 // Step 3, draw the content 14932 if (!dirtyOpaque) onDraw(canvas); 14933 14934 // Step 4, draw the children 14935 dispatchDraw(canvas); 14936 14937 // Step 5, draw the fade effect and restore layers 14938 final Paint p = scrollabilityCache.paint; 14939 final Matrix matrix = scrollabilityCache.matrix; 14940 final Shader fade = scrollabilityCache.shader; 14941 14942 if (drawTop) { 14943 matrix.setScale(1, fadeHeight * topFadeStrength); 14944 matrix.postTranslate(left, top); 14945 fade.setLocalMatrix(matrix); 14946 canvas.drawRect(left, top, right, top + length, p); 14947 } 14948 14949 if (drawBottom) { 14950 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14951 matrix.postRotate(180); 14952 matrix.postTranslate(left, bottom); 14953 fade.setLocalMatrix(matrix); 14954 canvas.drawRect(left, bottom - length, right, bottom, p); 14955 } 14956 14957 if (drawLeft) { 14958 matrix.setScale(1, fadeHeight * leftFadeStrength); 14959 matrix.postRotate(-90); 14960 matrix.postTranslate(left, top); 14961 fade.setLocalMatrix(matrix); 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 canvas.drawRect(right - length, top, right, bottom, p); 14971 } 14972 14973 canvas.restoreToCount(saveCount); 14974 14975 // Step 6, draw decorations (scrollbars) 14976 onDrawScrollBars(canvas); 14977 14978 if (mOverlay != null && !mOverlay.isEmpty()) { 14979 mOverlay.getOverlayView().dispatchDraw(canvas); 14980 } 14981 } 14982 14983 /** 14984 * Draws the background onto the specified canvas. 14985 * 14986 * @param canvas Canvas on which to draw the background 14987 */ 14988 private void drawBackground(Canvas canvas) { 14989 final Drawable background = mBackground; 14990 if (background == null) { 14991 return; 14992 } 14993 14994 if (mBackgroundSizeChanged) { 14995 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14996 mBackgroundSizeChanged = false; 14997 } 14998 14999 // Attempt to use a display list if requested. 15000 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15001 && mAttachInfo.mHardwareRenderer != null) { 15002 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 15003 15004 final RenderNode displayList = mBackgroundRenderNode; 15005 if (displayList != null && displayList.isValid()) { 15006 setBackgroundDisplayListProperties(displayList); 15007 ((HardwareCanvas) canvas).drawRenderNode(displayList); 15008 return; 15009 } 15010 } 15011 15012 final int scrollX = mScrollX; 15013 final int scrollY = mScrollY; 15014 if ((scrollX | scrollY) == 0) { 15015 background.draw(canvas); 15016 } else { 15017 canvas.translate(scrollX, scrollY); 15018 background.draw(canvas); 15019 canvas.translate(-scrollX, -scrollY); 15020 } 15021 } 15022 15023 /** 15024 * Set up background drawable display list properties. 15025 * 15026 * @param displayList Valid display list for the background drawable 15027 */ 15028 private void setBackgroundDisplayListProperties(RenderNode displayList) { 15029 displayList.setTranslationX(mScrollX); 15030 displayList.setTranslationY(mScrollY); 15031 } 15032 15033 /** 15034 * Creates a new display list or updates the existing display list for the 15035 * specified Drawable. 15036 * 15037 * @param drawable Drawable for which to create a display list 15038 * @param renderNode Existing RenderNode, or {@code null} 15039 * @return A valid display list for the specified drawable 15040 */ 15041 private static RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 15042 if (renderNode == null) { 15043 renderNode = RenderNode.create(drawable.getClass().getName()); 15044 } 15045 15046 final Rect bounds = drawable.getBounds(); 15047 final int width = bounds.width(); 15048 final int height = bounds.height(); 15049 final HardwareCanvas canvas = renderNode.start(width, height); 15050 try { 15051 drawable.draw(canvas); 15052 } finally { 15053 renderNode.end(canvas); 15054 } 15055 15056 // Set up drawable properties that are view-independent. 15057 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15058 renderNode.setProjectBackwards(drawable.isProjected()); 15059 renderNode.setProjectionReceiver(true); 15060 renderNode.setClipToBounds(false); 15061 return renderNode; 15062 } 15063 15064 /** 15065 * Returns the overlay for this view, creating it if it does not yet exist. 15066 * Adding drawables to the overlay will cause them to be displayed whenever 15067 * the view itself is redrawn. Objects in the overlay should be actively 15068 * managed: remove them when they should not be displayed anymore. The 15069 * overlay will always have the same size as its host view. 15070 * 15071 * <p>Note: Overlays do not currently work correctly with {@link 15072 * SurfaceView} or {@link TextureView}; contents in overlays for these 15073 * types of views may not display correctly.</p> 15074 * 15075 * @return The ViewOverlay object for this view. 15076 * @see ViewOverlay 15077 */ 15078 public ViewOverlay getOverlay() { 15079 if (mOverlay == null) { 15080 mOverlay = new ViewOverlay(mContext, this); 15081 } 15082 return mOverlay; 15083 } 15084 15085 /** 15086 * Override this if your view is known to always be drawn on top of a solid color background, 15087 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15088 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15089 * should be set to 0xFF. 15090 * 15091 * @see #setVerticalFadingEdgeEnabled(boolean) 15092 * @see #setHorizontalFadingEdgeEnabled(boolean) 15093 * 15094 * @return The known solid color background for this view, or 0 if the color may vary 15095 */ 15096 @ViewDebug.ExportedProperty(category = "drawing") 15097 public int getSolidColor() { 15098 return 0; 15099 } 15100 15101 /** 15102 * Build a human readable string representation of the specified view flags. 15103 * 15104 * @param flags the view flags to convert to a string 15105 * @return a String representing the supplied flags 15106 */ 15107 private static String printFlags(int flags) { 15108 String output = ""; 15109 int numFlags = 0; 15110 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15111 output += "TAKES_FOCUS"; 15112 numFlags++; 15113 } 15114 15115 switch (flags & VISIBILITY_MASK) { 15116 case INVISIBLE: 15117 if (numFlags > 0) { 15118 output += " "; 15119 } 15120 output += "INVISIBLE"; 15121 // USELESS HERE numFlags++; 15122 break; 15123 case GONE: 15124 if (numFlags > 0) { 15125 output += " "; 15126 } 15127 output += "GONE"; 15128 // USELESS HERE numFlags++; 15129 break; 15130 default: 15131 break; 15132 } 15133 return output; 15134 } 15135 15136 /** 15137 * Build a human readable string representation of the specified private 15138 * view flags. 15139 * 15140 * @param privateFlags the private view flags to convert to a string 15141 * @return a String representing the supplied flags 15142 */ 15143 private static String printPrivateFlags(int privateFlags) { 15144 String output = ""; 15145 int numFlags = 0; 15146 15147 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15148 output += "WANTS_FOCUS"; 15149 numFlags++; 15150 } 15151 15152 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15153 if (numFlags > 0) { 15154 output += " "; 15155 } 15156 output += "FOCUSED"; 15157 numFlags++; 15158 } 15159 15160 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15161 if (numFlags > 0) { 15162 output += " "; 15163 } 15164 output += "SELECTED"; 15165 numFlags++; 15166 } 15167 15168 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15169 if (numFlags > 0) { 15170 output += " "; 15171 } 15172 output += "IS_ROOT_NAMESPACE"; 15173 numFlags++; 15174 } 15175 15176 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15177 if (numFlags > 0) { 15178 output += " "; 15179 } 15180 output += "HAS_BOUNDS"; 15181 numFlags++; 15182 } 15183 15184 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15185 if (numFlags > 0) { 15186 output += " "; 15187 } 15188 output += "DRAWN"; 15189 // USELESS HERE numFlags++; 15190 } 15191 return output; 15192 } 15193 15194 /** 15195 * <p>Indicates whether or not this view's layout will be requested during 15196 * the next hierarchy layout pass.</p> 15197 * 15198 * @return true if the layout will be forced during next layout pass 15199 */ 15200 public boolean isLayoutRequested() { 15201 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15202 } 15203 15204 /** 15205 * Return true if o is a ViewGroup that is laying out using optical bounds. 15206 * @hide 15207 */ 15208 public static boolean isLayoutModeOptical(Object o) { 15209 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15210 } 15211 15212 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15213 Insets parentInsets = mParent instanceof View ? 15214 ((View) mParent).getOpticalInsets() : Insets.NONE; 15215 Insets childInsets = getOpticalInsets(); 15216 return setFrame( 15217 left + parentInsets.left - childInsets.left, 15218 top + parentInsets.top - childInsets.top, 15219 right + parentInsets.left + childInsets.right, 15220 bottom + parentInsets.top + childInsets.bottom); 15221 } 15222 15223 /** 15224 * Assign a size and position to a view and all of its 15225 * descendants 15226 * 15227 * <p>This is the second phase of the layout mechanism. 15228 * (The first is measuring). In this phase, each parent calls 15229 * layout on all of its children to position them. 15230 * This is typically done using the child measurements 15231 * that were stored in the measure pass().</p> 15232 * 15233 * <p>Derived classes should not override this method. 15234 * Derived classes with children should override 15235 * onLayout. In that method, they should 15236 * call layout on each of their children.</p> 15237 * 15238 * @param l Left position, relative to parent 15239 * @param t Top position, relative to parent 15240 * @param r Right position, relative to parent 15241 * @param b Bottom position, relative to parent 15242 */ 15243 @SuppressWarnings({"unchecked"}) 15244 public void layout(int l, int t, int r, int b) { 15245 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15246 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15247 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15248 } 15249 15250 int oldL = mLeft; 15251 int oldT = mTop; 15252 int oldB = mBottom; 15253 int oldR = mRight; 15254 15255 boolean changed = isLayoutModeOptical(mParent) ? 15256 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15257 15258 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15259 onLayout(changed, l, t, r, b); 15260 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15261 15262 ListenerInfo li = mListenerInfo; 15263 if (li != null && li.mOnLayoutChangeListeners != null) { 15264 ArrayList<OnLayoutChangeListener> listenersCopy = 15265 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15266 int numListeners = listenersCopy.size(); 15267 for (int i = 0; i < numListeners; ++i) { 15268 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15269 } 15270 } 15271 } 15272 15273 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15274 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15275 } 15276 15277 /** 15278 * Called from layout when this view should 15279 * assign a size and position to each of its children. 15280 * 15281 * Derived classes with children should override 15282 * this method and call layout on each of 15283 * their children. 15284 * @param changed This is a new size or position for this view 15285 * @param left Left position, relative to parent 15286 * @param top Top position, relative to parent 15287 * @param right Right position, relative to parent 15288 * @param bottom Bottom position, relative to parent 15289 */ 15290 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15291 } 15292 15293 /** 15294 * Assign a size and position to this view. 15295 * 15296 * This is called from layout. 15297 * 15298 * @param left Left position, relative to parent 15299 * @param top Top position, relative to parent 15300 * @param right Right position, relative to parent 15301 * @param bottom Bottom position, relative to parent 15302 * @return true if the new size and position are different than the 15303 * previous ones 15304 * {@hide} 15305 */ 15306 protected boolean setFrame(int left, int top, int right, int bottom) { 15307 boolean changed = false; 15308 15309 if (DBG) { 15310 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15311 + right + "," + bottom + ")"); 15312 } 15313 15314 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15315 changed = true; 15316 15317 // Remember our drawn bit 15318 int drawn = mPrivateFlags & PFLAG_DRAWN; 15319 15320 int oldWidth = mRight - mLeft; 15321 int oldHeight = mBottom - mTop; 15322 int newWidth = right - left; 15323 int newHeight = bottom - top; 15324 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15325 15326 // Invalidate our old position 15327 invalidate(sizeChanged); 15328 15329 mLeft = left; 15330 mTop = top; 15331 mRight = right; 15332 mBottom = bottom; 15333 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15334 15335 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15336 15337 15338 if (sizeChanged) { 15339 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15340 } 15341 15342 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15343 // If we are visible, force the DRAWN bit to on so that 15344 // this invalidate will go through (at least to our parent). 15345 // This is because someone may have invalidated this view 15346 // before this call to setFrame came in, thereby clearing 15347 // the DRAWN bit. 15348 mPrivateFlags |= PFLAG_DRAWN; 15349 invalidate(sizeChanged); 15350 // parent display list may need to be recreated based on a change in the bounds 15351 // of any child 15352 invalidateParentCaches(); 15353 } 15354 15355 // Reset drawn bit to original value (invalidate turns it off) 15356 mPrivateFlags |= drawn; 15357 15358 mBackgroundSizeChanged = true; 15359 15360 notifySubtreeAccessibilityStateChangedIfNeeded(); 15361 } 15362 return changed; 15363 } 15364 15365 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15366 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15367 if (mOverlay != null) { 15368 mOverlay.getOverlayView().setRight(newWidth); 15369 mOverlay.getOverlayView().setBottom(newHeight); 15370 } 15371 invalidateOutline(); 15372 } 15373 15374 /** 15375 * Finalize inflating a view from XML. This is called as the last phase 15376 * of inflation, after all child views have been added. 15377 * 15378 * <p>Even if the subclass overrides onFinishInflate, they should always be 15379 * sure to call the super method, so that we get called. 15380 */ 15381 protected void onFinishInflate() { 15382 } 15383 15384 /** 15385 * Returns the resources associated with this view. 15386 * 15387 * @return Resources object. 15388 */ 15389 public Resources getResources() { 15390 return mResources; 15391 } 15392 15393 /** 15394 * Invalidates the specified Drawable. 15395 * 15396 * @param drawable the drawable to invalidate 15397 */ 15398 @Override 15399 public void invalidateDrawable(@NonNull Drawable drawable) { 15400 if (verifyDrawable(drawable)) { 15401 final Rect dirty = drawable.getDirtyBounds(); 15402 final int scrollX = mScrollX; 15403 final int scrollY = mScrollY; 15404 15405 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15406 dirty.right + scrollX, dirty.bottom + scrollY); 15407 15408 invalidateOutline(); 15409 } 15410 } 15411 15412 /** 15413 * Schedules an action on a drawable to occur at a specified time. 15414 * 15415 * @param who the recipient of the action 15416 * @param what the action to run on the drawable 15417 * @param when the time at which the action must occur. Uses the 15418 * {@link SystemClock#uptimeMillis} timebase. 15419 */ 15420 @Override 15421 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15422 if (verifyDrawable(who) && what != null) { 15423 final long delay = when - SystemClock.uptimeMillis(); 15424 if (mAttachInfo != null) { 15425 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15426 Choreographer.CALLBACK_ANIMATION, what, who, 15427 Choreographer.subtractFrameDelay(delay)); 15428 } else { 15429 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15430 } 15431 } 15432 } 15433 15434 /** 15435 * Cancels a scheduled action on a drawable. 15436 * 15437 * @param who the recipient of the action 15438 * @param what the action to cancel 15439 */ 15440 @Override 15441 public void unscheduleDrawable(Drawable who, Runnable what) { 15442 if (verifyDrawable(who) && what != null) { 15443 if (mAttachInfo != null) { 15444 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15445 Choreographer.CALLBACK_ANIMATION, what, who); 15446 } 15447 ViewRootImpl.getRunQueue().removeCallbacks(what); 15448 } 15449 } 15450 15451 /** 15452 * Unschedule any events associated with the given Drawable. This can be 15453 * used when selecting a new Drawable into a view, so that the previous 15454 * one is completely unscheduled. 15455 * 15456 * @param who The Drawable to unschedule. 15457 * 15458 * @see #drawableStateChanged 15459 */ 15460 public void unscheduleDrawable(Drawable who) { 15461 if (mAttachInfo != null && who != null) { 15462 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15463 Choreographer.CALLBACK_ANIMATION, null, who); 15464 } 15465 } 15466 15467 /** 15468 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15469 * that the View directionality can and will be resolved before its Drawables. 15470 * 15471 * Will call {@link View#onResolveDrawables} when resolution is done. 15472 * 15473 * @hide 15474 */ 15475 protected void resolveDrawables() { 15476 // Drawables resolution may need to happen before resolving the layout direction (which is 15477 // done only during the measure() call). 15478 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15479 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15480 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15481 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15482 // direction to be resolved as its resolved value will be the same as its raw value. 15483 if (!isLayoutDirectionResolved() && 15484 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15485 return; 15486 } 15487 15488 final int layoutDirection = isLayoutDirectionResolved() ? 15489 getLayoutDirection() : getRawLayoutDirection(); 15490 15491 if (mBackground != null) { 15492 mBackground.setLayoutDirection(layoutDirection); 15493 } 15494 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15495 onResolveDrawables(layoutDirection); 15496 } 15497 15498 /** 15499 * Called when layout direction has been resolved. 15500 * 15501 * The default implementation does nothing. 15502 * 15503 * @param layoutDirection The resolved layout direction. 15504 * 15505 * @see #LAYOUT_DIRECTION_LTR 15506 * @see #LAYOUT_DIRECTION_RTL 15507 * 15508 * @hide 15509 */ 15510 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15511 } 15512 15513 /** 15514 * @hide 15515 */ 15516 protected void resetResolvedDrawables() { 15517 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15518 } 15519 15520 private boolean isDrawablesResolved() { 15521 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15522 } 15523 15524 /** 15525 * If your view subclass is displaying its own Drawable objects, it should 15526 * override this function and return true for any Drawable it is 15527 * displaying. This allows animations for those drawables to be 15528 * scheduled. 15529 * 15530 * <p>Be sure to call through to the super class when overriding this 15531 * function. 15532 * 15533 * @param who The Drawable to verify. Return true if it is one you are 15534 * displaying, else return the result of calling through to the 15535 * super class. 15536 * 15537 * @return boolean If true than the Drawable is being displayed in the 15538 * view; else false and it is not allowed to animate. 15539 * 15540 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15541 * @see #drawableStateChanged() 15542 */ 15543 protected boolean verifyDrawable(Drawable who) { 15544 return who == mBackground; 15545 } 15546 15547 /** 15548 * This function is called whenever the state of the view changes in such 15549 * a way that it impacts the state of drawables being shown. 15550 * <p> 15551 * If the View has a StateListAnimator, it will also be called to run necessary state 15552 * change animations. 15553 * <p> 15554 * Be sure to call through to the superclass when overriding this function. 15555 * 15556 * @see Drawable#setState(int[]) 15557 */ 15558 protected void drawableStateChanged() { 15559 final Drawable d = mBackground; 15560 if (d != null && d.isStateful()) { 15561 d.setState(getDrawableState()); 15562 } 15563 15564 if (mStateListAnimator != null) { 15565 mStateListAnimator.setState(getDrawableState()); 15566 } 15567 } 15568 15569 /** 15570 * This function is called whenever the drawable hotspot changes. 15571 * <p> 15572 * Be sure to call through to the superclass when overriding this function. 15573 * 15574 * @param x hotspot x coordinate 15575 * @param y hotspot y coordinate 15576 */ 15577 public void drawableHotspotChanged(float x, float y) { 15578 if (mBackground != null) { 15579 mBackground.setHotspot(x, y); 15580 } 15581 } 15582 15583 /** 15584 * Call this to force a view to update its drawable state. This will cause 15585 * drawableStateChanged to be called on this view. Views that are interested 15586 * in the new state should call getDrawableState. 15587 * 15588 * @see #drawableStateChanged 15589 * @see #getDrawableState 15590 */ 15591 public void refreshDrawableState() { 15592 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15593 drawableStateChanged(); 15594 15595 ViewParent parent = mParent; 15596 if (parent != null) { 15597 parent.childDrawableStateChanged(this); 15598 } 15599 } 15600 15601 /** 15602 * Return an array of resource IDs of the drawable states representing the 15603 * current state of the view. 15604 * 15605 * @return The current drawable state 15606 * 15607 * @see Drawable#setState(int[]) 15608 * @see #drawableStateChanged() 15609 * @see #onCreateDrawableState(int) 15610 */ 15611 public final int[] getDrawableState() { 15612 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15613 return mDrawableState; 15614 } else { 15615 mDrawableState = onCreateDrawableState(0); 15616 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15617 return mDrawableState; 15618 } 15619 } 15620 15621 /** 15622 * Generate the new {@link android.graphics.drawable.Drawable} state for 15623 * this view. This is called by the view 15624 * system when the cached Drawable state is determined to be invalid. To 15625 * retrieve the current state, you should use {@link #getDrawableState}. 15626 * 15627 * @param extraSpace if non-zero, this is the number of extra entries you 15628 * would like in the returned array in which you can place your own 15629 * states. 15630 * 15631 * @return Returns an array holding the current {@link Drawable} state of 15632 * the view. 15633 * 15634 * @see #mergeDrawableStates(int[], int[]) 15635 */ 15636 protected int[] onCreateDrawableState(int extraSpace) { 15637 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15638 mParent instanceof View) { 15639 return ((View) mParent).onCreateDrawableState(extraSpace); 15640 } 15641 15642 int[] drawableState; 15643 15644 int privateFlags = mPrivateFlags; 15645 15646 int viewStateIndex = 0; 15647 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15648 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15649 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15650 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15651 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15652 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15653 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15654 HardwareRenderer.isAvailable()) { 15655 // This is set if HW acceleration is requested, even if the current 15656 // process doesn't allow it. This is just to allow app preview 15657 // windows to better match their app. 15658 viewStateIndex |= VIEW_STATE_ACCELERATED; 15659 } 15660 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15661 15662 final int privateFlags2 = mPrivateFlags2; 15663 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15664 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15665 15666 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15667 15668 //noinspection ConstantIfStatement 15669 if (false) { 15670 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15671 Log.i("View", toString() 15672 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15673 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15674 + " fo=" + hasFocus() 15675 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15676 + " wf=" + hasWindowFocus() 15677 + ": " + Arrays.toString(drawableState)); 15678 } 15679 15680 if (extraSpace == 0) { 15681 return drawableState; 15682 } 15683 15684 final int[] fullState; 15685 if (drawableState != null) { 15686 fullState = new int[drawableState.length + extraSpace]; 15687 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15688 } else { 15689 fullState = new int[extraSpace]; 15690 } 15691 15692 return fullState; 15693 } 15694 15695 /** 15696 * Merge your own state values in <var>additionalState</var> into the base 15697 * state values <var>baseState</var> that were returned by 15698 * {@link #onCreateDrawableState(int)}. 15699 * 15700 * @param baseState The base state values returned by 15701 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15702 * own additional state values. 15703 * 15704 * @param additionalState The additional state values you would like 15705 * added to <var>baseState</var>; this array is not modified. 15706 * 15707 * @return As a convenience, the <var>baseState</var> array you originally 15708 * passed into the function is returned. 15709 * 15710 * @see #onCreateDrawableState(int) 15711 */ 15712 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15713 final int N = baseState.length; 15714 int i = N - 1; 15715 while (i >= 0 && baseState[i] == 0) { 15716 i--; 15717 } 15718 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15719 return baseState; 15720 } 15721 15722 /** 15723 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15724 * on all Drawable objects associated with this view. 15725 * <p> 15726 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 15727 * attached to this view. 15728 */ 15729 public void jumpDrawablesToCurrentState() { 15730 if (mBackground != null) { 15731 mBackground.jumpToCurrentState(); 15732 } 15733 if (mStateListAnimator != null) { 15734 mStateListAnimator.jumpToCurrentState(); 15735 } 15736 } 15737 15738 /** 15739 * Sets the background color for this view. 15740 * @param color the color of the background 15741 */ 15742 @RemotableViewMethod 15743 public void setBackgroundColor(int color) { 15744 if (mBackground instanceof ColorDrawable) { 15745 ((ColorDrawable) mBackground.mutate()).setColor(color); 15746 computeOpaqueFlags(); 15747 mBackgroundResource = 0; 15748 } else { 15749 setBackground(new ColorDrawable(color)); 15750 } 15751 } 15752 15753 /** 15754 * Set the background to a given resource. The resource should refer to 15755 * a Drawable object or 0 to remove the background. 15756 * @param resid The identifier of the resource. 15757 * 15758 * @attr ref android.R.styleable#View_background 15759 */ 15760 @RemotableViewMethod 15761 public void setBackgroundResource(int resid) { 15762 if (resid != 0 && resid == mBackgroundResource) { 15763 return; 15764 } 15765 15766 Drawable d = null; 15767 if (resid != 0) { 15768 d = mContext.getDrawable(resid); 15769 } 15770 setBackground(d); 15771 15772 mBackgroundResource = resid; 15773 } 15774 15775 /** 15776 * Set the background to a given Drawable, or remove the background. If the 15777 * background has padding, this View's padding is set to the background's 15778 * padding. However, when a background is removed, this View's padding isn't 15779 * touched. If setting the padding is desired, please use 15780 * {@link #setPadding(int, int, int, int)}. 15781 * 15782 * @param background The Drawable to use as the background, or null to remove the 15783 * background 15784 */ 15785 public void setBackground(Drawable background) { 15786 //noinspection deprecation 15787 setBackgroundDrawable(background); 15788 } 15789 15790 /** 15791 * @deprecated use {@link #setBackground(Drawable)} instead 15792 */ 15793 @Deprecated 15794 public void setBackgroundDrawable(Drawable background) { 15795 computeOpaqueFlags(); 15796 15797 if (background == mBackground) { 15798 return; 15799 } 15800 15801 boolean requestLayout = false; 15802 15803 mBackgroundResource = 0; 15804 15805 /* 15806 * Regardless of whether we're setting a new background or not, we want 15807 * to clear the previous drawable. 15808 */ 15809 if (mBackground != null) { 15810 mBackground.setCallback(null); 15811 unscheduleDrawable(mBackground); 15812 } 15813 15814 if (background != null) { 15815 Rect padding = sThreadLocal.get(); 15816 if (padding == null) { 15817 padding = new Rect(); 15818 sThreadLocal.set(padding); 15819 } 15820 resetResolvedDrawables(); 15821 background.setLayoutDirection(getLayoutDirection()); 15822 if (background.getPadding(padding)) { 15823 resetResolvedPadding(); 15824 switch (background.getLayoutDirection()) { 15825 case LAYOUT_DIRECTION_RTL: 15826 mUserPaddingLeftInitial = padding.right; 15827 mUserPaddingRightInitial = padding.left; 15828 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15829 break; 15830 case LAYOUT_DIRECTION_LTR: 15831 default: 15832 mUserPaddingLeftInitial = padding.left; 15833 mUserPaddingRightInitial = padding.right; 15834 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15835 } 15836 mLeftPaddingDefined = false; 15837 mRightPaddingDefined = false; 15838 } 15839 15840 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15841 // if it has a different minimum size, we should layout again 15842 if (mBackground == null 15843 || mBackground.getMinimumHeight() != background.getMinimumHeight() 15844 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15845 requestLayout = true; 15846 } 15847 15848 background.setCallback(this); 15849 if (background.isStateful()) { 15850 background.setState(getDrawableState()); 15851 } 15852 background.setVisible(getVisibility() == VISIBLE, false); 15853 mBackground = background; 15854 15855 applyBackgroundTint(); 15856 15857 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15858 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15859 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15860 requestLayout = true; 15861 } 15862 } else { 15863 /* Remove the background */ 15864 mBackground = null; 15865 15866 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15867 /* 15868 * This view ONLY drew the background before and we're removing 15869 * the background, so now it won't draw anything 15870 * (hence we SKIP_DRAW) 15871 */ 15872 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15873 mPrivateFlags |= PFLAG_SKIP_DRAW; 15874 } 15875 15876 /* 15877 * When the background is set, we try to apply its padding to this 15878 * View. When the background is removed, we don't touch this View's 15879 * padding. This is noted in the Javadocs. Hence, we don't need to 15880 * requestLayout(), the invalidate() below is sufficient. 15881 */ 15882 15883 // The old background's minimum size could have affected this 15884 // View's layout, so let's requestLayout 15885 requestLayout = true; 15886 } 15887 15888 computeOpaqueFlags(); 15889 15890 if (requestLayout) { 15891 requestLayout(); 15892 } 15893 15894 mBackgroundSizeChanged = true; 15895 invalidate(true); 15896 } 15897 15898 /** 15899 * Gets the background drawable 15900 * 15901 * @return The drawable used as the background for this view, if any. 15902 * 15903 * @see #setBackground(Drawable) 15904 * 15905 * @attr ref android.R.styleable#View_background 15906 */ 15907 public Drawable getBackground() { 15908 return mBackground; 15909 } 15910 15911 /** 15912 * Applies a tint to the background drawable. 15913 * <p> 15914 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 15915 * mutate the drawable and apply the specified tint and tint mode using 15916 * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}. 15917 * 15918 * @param tint the tint to apply, may be {@code null} to clear tint 15919 * @param tintMode the blending mode used to apply the tint, may be 15920 * {@code null} to clear tint 15921 * 15922 * @attr ref android.R.styleable#View_backgroundTint 15923 * @attr ref android.R.styleable#View_backgroundTintMode 15924 * @see Drawable#setTint(ColorStateList, PorterDuff.Mode) 15925 */ 15926 private void setBackgroundTint(@Nullable ColorStateList tint, 15927 @Nullable PorterDuff.Mode tintMode) { 15928 mBackgroundTint = tint; 15929 mBackgroundTintMode = tintMode; 15930 mHasBackgroundTint = true; 15931 15932 applyBackgroundTint(); 15933 } 15934 15935 /** 15936 * Applies a tint to the background drawable. Does not modify the current tint 15937 * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default. 15938 * <p> 15939 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 15940 * mutate the drawable and apply the specified tint and tint mode using 15941 * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}. 15942 * 15943 * @param tint the tint to apply, may be {@code null} to clear tint 15944 * 15945 * @attr ref android.R.styleable#View_backgroundTint 15946 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15947 */ 15948 public void setBackgroundTint(@Nullable ColorStateList tint) { 15949 setBackgroundTint(tint, mBackgroundTintMode); 15950 } 15951 15952 /** 15953 * @return the tint applied to the background drawable 15954 * @attr ref android.R.styleable#View_backgroundTint 15955 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15956 */ 15957 @Nullable 15958 public ColorStateList getBackgroundTint() { 15959 return mBackgroundTint; 15960 } 15961 15962 /** 15963 * Specifies the blending mode used to apply the tint specified by 15964 * {@link #setBackgroundTint(ColorStateList)}} to the background drawable. 15965 * The default mode is {@link PorterDuff.Mode#SRC_ATOP}. 15966 * 15967 * @param tintMode the blending mode used to apply the tint, may be 15968 * {@code null} to clear tint 15969 * @attr ref android.R.styleable#View_backgroundTintMode 15970 * @see #setBackgroundTint(ColorStateList) 15971 */ 15972 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 15973 setBackgroundTint(mBackgroundTint, tintMode); 15974 } 15975 15976 /** 15977 * @return the blending mode used to apply the tint to the background drawable 15978 * @attr ref android.R.styleable#View_backgroundTintMode 15979 * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode) 15980 */ 15981 @Nullable 15982 public PorterDuff.Mode getBackgroundTintMode() { 15983 return mBackgroundTintMode; 15984 } 15985 15986 private void applyBackgroundTint() { 15987 if (mBackground != null && mHasBackgroundTint) { 15988 mBackground = mBackground.mutate(); 15989 mBackground.setTint(mBackgroundTint, mBackgroundTintMode); 15990 } 15991 } 15992 15993 /** 15994 * Sets the padding. The view may add on the space required to display 15995 * the scrollbars, depending on the style and visibility of the scrollbars. 15996 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15997 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15998 * from the values set in this call. 15999 * 16000 * @attr ref android.R.styleable#View_padding 16001 * @attr ref android.R.styleable#View_paddingBottom 16002 * @attr ref android.R.styleable#View_paddingLeft 16003 * @attr ref android.R.styleable#View_paddingRight 16004 * @attr ref android.R.styleable#View_paddingTop 16005 * @param left the left padding in pixels 16006 * @param top the top padding in pixels 16007 * @param right the right padding in pixels 16008 * @param bottom the bottom padding in pixels 16009 */ 16010 public void setPadding(int left, int top, int right, int bottom) { 16011 resetResolvedPadding(); 16012 16013 mUserPaddingStart = UNDEFINED_PADDING; 16014 mUserPaddingEnd = UNDEFINED_PADDING; 16015 16016 mUserPaddingLeftInitial = left; 16017 mUserPaddingRightInitial = right; 16018 16019 mLeftPaddingDefined = true; 16020 mRightPaddingDefined = true; 16021 16022 internalSetPadding(left, top, right, bottom); 16023 } 16024 16025 /** 16026 * @hide 16027 */ 16028 protected void internalSetPadding(int left, int top, int right, int bottom) { 16029 mUserPaddingLeft = left; 16030 mUserPaddingRight = right; 16031 mUserPaddingBottom = bottom; 16032 16033 final int viewFlags = mViewFlags; 16034 boolean changed = false; 16035 16036 // Common case is there are no scroll bars. 16037 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 16038 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 16039 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 16040 ? 0 : getVerticalScrollbarWidth(); 16041 switch (mVerticalScrollbarPosition) { 16042 case SCROLLBAR_POSITION_DEFAULT: 16043 if (isLayoutRtl()) { 16044 left += offset; 16045 } else { 16046 right += offset; 16047 } 16048 break; 16049 case SCROLLBAR_POSITION_RIGHT: 16050 right += offset; 16051 break; 16052 case SCROLLBAR_POSITION_LEFT: 16053 left += offset; 16054 break; 16055 } 16056 } 16057 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16058 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16059 ? 0 : getHorizontalScrollbarHeight(); 16060 } 16061 } 16062 16063 if (mPaddingLeft != left) { 16064 changed = true; 16065 mPaddingLeft = left; 16066 } 16067 if (mPaddingTop != top) { 16068 changed = true; 16069 mPaddingTop = top; 16070 } 16071 if (mPaddingRight != right) { 16072 changed = true; 16073 mPaddingRight = right; 16074 } 16075 if (mPaddingBottom != bottom) { 16076 changed = true; 16077 mPaddingBottom = bottom; 16078 } 16079 16080 if (changed) { 16081 requestLayout(); 16082 } 16083 } 16084 16085 /** 16086 * Sets the relative padding. The view may add on the space required to display 16087 * the scrollbars, depending on the style and visibility of the scrollbars. 16088 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16089 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16090 * from the values set in this call. 16091 * 16092 * @attr ref android.R.styleable#View_padding 16093 * @attr ref android.R.styleable#View_paddingBottom 16094 * @attr ref android.R.styleable#View_paddingStart 16095 * @attr ref android.R.styleable#View_paddingEnd 16096 * @attr ref android.R.styleable#View_paddingTop 16097 * @param start the start padding in pixels 16098 * @param top the top padding in pixels 16099 * @param end the end padding in pixels 16100 * @param bottom the bottom padding in pixels 16101 */ 16102 public void setPaddingRelative(int start, int top, int end, int bottom) { 16103 resetResolvedPadding(); 16104 16105 mUserPaddingStart = start; 16106 mUserPaddingEnd = end; 16107 mLeftPaddingDefined = true; 16108 mRightPaddingDefined = true; 16109 16110 switch(getLayoutDirection()) { 16111 case LAYOUT_DIRECTION_RTL: 16112 mUserPaddingLeftInitial = end; 16113 mUserPaddingRightInitial = start; 16114 internalSetPadding(end, top, start, bottom); 16115 break; 16116 case LAYOUT_DIRECTION_LTR: 16117 default: 16118 mUserPaddingLeftInitial = start; 16119 mUserPaddingRightInitial = end; 16120 internalSetPadding(start, top, end, bottom); 16121 } 16122 } 16123 16124 /** 16125 * Returns the top padding of this view. 16126 * 16127 * @return the top padding in pixels 16128 */ 16129 public int getPaddingTop() { 16130 return mPaddingTop; 16131 } 16132 16133 /** 16134 * Returns the bottom padding of this view. If there are inset and enabled 16135 * scrollbars, this value may include the space required to display the 16136 * scrollbars as well. 16137 * 16138 * @return the bottom padding in pixels 16139 */ 16140 public int getPaddingBottom() { 16141 return mPaddingBottom; 16142 } 16143 16144 /** 16145 * Returns the left padding of this view. If there are inset and enabled 16146 * scrollbars, this value may include the space required to display the 16147 * scrollbars as well. 16148 * 16149 * @return the left padding in pixels 16150 */ 16151 public int getPaddingLeft() { 16152 if (!isPaddingResolved()) { 16153 resolvePadding(); 16154 } 16155 return mPaddingLeft; 16156 } 16157 16158 /** 16159 * Returns the start padding of this view depending on its resolved layout direction. 16160 * If there are inset and enabled scrollbars, this value may include the space 16161 * required to display the scrollbars as well. 16162 * 16163 * @return the start padding in pixels 16164 */ 16165 public int getPaddingStart() { 16166 if (!isPaddingResolved()) { 16167 resolvePadding(); 16168 } 16169 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16170 mPaddingRight : mPaddingLeft; 16171 } 16172 16173 /** 16174 * Returns the right padding of this view. If there are inset and enabled 16175 * scrollbars, this value may include the space required to display the 16176 * scrollbars as well. 16177 * 16178 * @return the right padding in pixels 16179 */ 16180 public int getPaddingRight() { 16181 if (!isPaddingResolved()) { 16182 resolvePadding(); 16183 } 16184 return mPaddingRight; 16185 } 16186 16187 /** 16188 * Returns the end padding of this view depending on its resolved layout direction. 16189 * If there are inset and enabled scrollbars, this value may include the space 16190 * required to display the scrollbars as well. 16191 * 16192 * @return the end padding in pixels 16193 */ 16194 public int getPaddingEnd() { 16195 if (!isPaddingResolved()) { 16196 resolvePadding(); 16197 } 16198 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16199 mPaddingLeft : mPaddingRight; 16200 } 16201 16202 /** 16203 * Return if the padding as been set thru relative values 16204 * {@link #setPaddingRelative(int, int, int, int)} or thru 16205 * @attr ref android.R.styleable#View_paddingStart or 16206 * @attr ref android.R.styleable#View_paddingEnd 16207 * 16208 * @return true if the padding is relative or false if it is not. 16209 */ 16210 public boolean isPaddingRelative() { 16211 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16212 } 16213 16214 Insets computeOpticalInsets() { 16215 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16216 } 16217 16218 /** 16219 * @hide 16220 */ 16221 public void resetPaddingToInitialValues() { 16222 if (isRtlCompatibilityMode()) { 16223 mPaddingLeft = mUserPaddingLeftInitial; 16224 mPaddingRight = mUserPaddingRightInitial; 16225 return; 16226 } 16227 if (isLayoutRtl()) { 16228 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16229 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16230 } else { 16231 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16232 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16233 } 16234 } 16235 16236 /** 16237 * @hide 16238 */ 16239 public Insets getOpticalInsets() { 16240 if (mLayoutInsets == null) { 16241 mLayoutInsets = computeOpticalInsets(); 16242 } 16243 return mLayoutInsets; 16244 } 16245 16246 /** 16247 * Set this view's optical insets. 16248 * 16249 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16250 * property. Views that compute their own optical insets should call it as part of measurement. 16251 * This method does not request layout. If you are setting optical insets outside of 16252 * measure/layout itself you will want to call requestLayout() yourself. 16253 * </p> 16254 * @hide 16255 */ 16256 public void setOpticalInsets(Insets insets) { 16257 mLayoutInsets = insets; 16258 } 16259 16260 /** 16261 * Changes the selection state of this view. A view can be selected or not. 16262 * Note that selection is not the same as focus. Views are typically 16263 * selected in the context of an AdapterView like ListView or GridView; 16264 * the selected view is the view that is highlighted. 16265 * 16266 * @param selected true if the view must be selected, false otherwise 16267 */ 16268 public void setSelected(boolean selected) { 16269 //noinspection DoubleNegation 16270 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16271 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16272 if (!selected) resetPressedState(); 16273 invalidate(true); 16274 refreshDrawableState(); 16275 dispatchSetSelected(selected); 16276 notifyViewAccessibilityStateChangedIfNeeded( 16277 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16278 } 16279 } 16280 16281 /** 16282 * Dispatch setSelected to all of this View's children. 16283 * 16284 * @see #setSelected(boolean) 16285 * 16286 * @param selected The new selected state 16287 */ 16288 protected void dispatchSetSelected(boolean selected) { 16289 } 16290 16291 /** 16292 * Indicates the selection state of this view. 16293 * 16294 * @return true if the view is selected, false otherwise 16295 */ 16296 @ViewDebug.ExportedProperty 16297 public boolean isSelected() { 16298 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16299 } 16300 16301 /** 16302 * Changes the activated state of this view. A view can be activated or not. 16303 * Note that activation is not the same as selection. Selection is 16304 * a transient property, representing the view (hierarchy) the user is 16305 * currently interacting with. Activation is a longer-term state that the 16306 * user can move views in and out of. For example, in a list view with 16307 * single or multiple selection enabled, the views in the current selection 16308 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16309 * here.) The activated state is propagated down to children of the view it 16310 * is set on. 16311 * 16312 * @param activated true if the view must be activated, false otherwise 16313 */ 16314 public void setActivated(boolean activated) { 16315 //noinspection DoubleNegation 16316 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16317 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16318 invalidate(true); 16319 refreshDrawableState(); 16320 dispatchSetActivated(activated); 16321 } 16322 } 16323 16324 /** 16325 * Dispatch setActivated to all of this View's children. 16326 * 16327 * @see #setActivated(boolean) 16328 * 16329 * @param activated The new activated state 16330 */ 16331 protected void dispatchSetActivated(boolean activated) { 16332 } 16333 16334 /** 16335 * Indicates the activation state of this view. 16336 * 16337 * @return true if the view is activated, false otherwise 16338 */ 16339 @ViewDebug.ExportedProperty 16340 public boolean isActivated() { 16341 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16342 } 16343 16344 /** 16345 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16346 * observer can be used to get notifications when global events, like 16347 * layout, happen. 16348 * 16349 * The returned ViewTreeObserver observer is not guaranteed to remain 16350 * valid for the lifetime of this View. If the caller of this method keeps 16351 * a long-lived reference to ViewTreeObserver, it should always check for 16352 * the return value of {@link ViewTreeObserver#isAlive()}. 16353 * 16354 * @return The ViewTreeObserver for this view's hierarchy. 16355 */ 16356 public ViewTreeObserver getViewTreeObserver() { 16357 if (mAttachInfo != null) { 16358 return mAttachInfo.mTreeObserver; 16359 } 16360 if (mFloatingTreeObserver == null) { 16361 mFloatingTreeObserver = new ViewTreeObserver(); 16362 } 16363 return mFloatingTreeObserver; 16364 } 16365 16366 /** 16367 * <p>Finds the topmost view in the current view hierarchy.</p> 16368 * 16369 * @return the topmost view containing this view 16370 */ 16371 public View getRootView() { 16372 if (mAttachInfo != null) { 16373 final View v = mAttachInfo.mRootView; 16374 if (v != null) { 16375 return v; 16376 } 16377 } 16378 16379 View parent = this; 16380 16381 while (parent.mParent != null && parent.mParent instanceof View) { 16382 parent = (View) parent.mParent; 16383 } 16384 16385 return parent; 16386 } 16387 16388 /** 16389 * Transforms a motion event from view-local coordinates to on-screen 16390 * coordinates. 16391 * 16392 * @param ev the view-local motion event 16393 * @return false if the transformation could not be applied 16394 * @hide 16395 */ 16396 public boolean toGlobalMotionEvent(MotionEvent ev) { 16397 final AttachInfo info = mAttachInfo; 16398 if (info == null) { 16399 return false; 16400 } 16401 16402 final Matrix m = info.mTmpMatrix; 16403 m.set(Matrix.IDENTITY_MATRIX); 16404 transformMatrixToGlobal(m); 16405 ev.transform(m); 16406 return true; 16407 } 16408 16409 /** 16410 * Transforms a motion event from on-screen coordinates to view-local 16411 * coordinates. 16412 * 16413 * @param ev the on-screen motion event 16414 * @return false if the transformation could not be applied 16415 * @hide 16416 */ 16417 public boolean toLocalMotionEvent(MotionEvent ev) { 16418 final AttachInfo info = mAttachInfo; 16419 if (info == null) { 16420 return false; 16421 } 16422 16423 final Matrix m = info.mTmpMatrix; 16424 m.set(Matrix.IDENTITY_MATRIX); 16425 transformMatrixToLocal(m); 16426 ev.transform(m); 16427 return true; 16428 } 16429 16430 /** 16431 * Modifies the input matrix such that it maps view-local coordinates to 16432 * on-screen coordinates. 16433 * 16434 * @param m input matrix to modify 16435 */ 16436 void transformMatrixToGlobal(Matrix m) { 16437 final ViewParent parent = mParent; 16438 if (parent instanceof View) { 16439 final View vp = (View) parent; 16440 vp.transformMatrixToGlobal(m); 16441 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16442 } else if (parent instanceof ViewRootImpl) { 16443 final ViewRootImpl vr = (ViewRootImpl) parent; 16444 vr.transformMatrixToGlobal(m); 16445 m.postTranslate(0, -vr.mCurScrollY); 16446 } 16447 16448 m.postTranslate(mLeft, mTop); 16449 16450 if (!hasIdentityMatrix()) { 16451 m.postConcat(getMatrix()); 16452 } 16453 } 16454 16455 /** 16456 * Modifies the input matrix such that it maps on-screen coordinates to 16457 * view-local coordinates. 16458 * 16459 * @param m input matrix to modify 16460 */ 16461 void transformMatrixToLocal(Matrix m) { 16462 final ViewParent parent = mParent; 16463 if (parent instanceof View) { 16464 final View vp = (View) parent; 16465 vp.transformMatrixToLocal(m); 16466 m.preTranslate(vp.mScrollX, vp.mScrollY); 16467 } else if (parent instanceof ViewRootImpl) { 16468 final ViewRootImpl vr = (ViewRootImpl) parent; 16469 vr.transformMatrixToLocal(m); 16470 m.preTranslate(0, vr.mCurScrollY); 16471 } 16472 16473 m.preTranslate(-mLeft, -mTop); 16474 16475 if (!hasIdentityMatrix()) { 16476 m.preConcat(getInverseMatrix()); 16477 } 16478 } 16479 16480 /** 16481 * <p>Computes the coordinates of this view on the screen. The argument 16482 * must be an array of two integers. After the method returns, the array 16483 * contains the x and y location in that order.</p> 16484 * 16485 * @param location an array of two integers in which to hold the coordinates 16486 */ 16487 public void getLocationOnScreen(int[] location) { 16488 getLocationInWindow(location); 16489 16490 final AttachInfo info = mAttachInfo; 16491 if (info != null) { 16492 location[0] += info.mWindowLeft; 16493 location[1] += info.mWindowTop; 16494 } 16495 } 16496 16497 /** 16498 * <p>Computes the coordinates of this view in its window. The argument 16499 * must be an array of two integers. After the method returns, the array 16500 * contains the x and y location in that order.</p> 16501 * 16502 * @param location an array of two integers in which to hold the coordinates 16503 */ 16504 public void getLocationInWindow(int[] location) { 16505 if (location == null || location.length < 2) { 16506 throw new IllegalArgumentException("location must be an array of two integers"); 16507 } 16508 16509 if (mAttachInfo == null) { 16510 // When the view is not attached to a window, this method does not make sense 16511 location[0] = location[1] = 0; 16512 return; 16513 } 16514 16515 float[] position = mAttachInfo.mTmpTransformLocation; 16516 position[0] = position[1] = 0.0f; 16517 16518 if (!hasIdentityMatrix()) { 16519 getMatrix().mapPoints(position); 16520 } 16521 16522 position[0] += mLeft; 16523 position[1] += mTop; 16524 16525 ViewParent viewParent = mParent; 16526 while (viewParent instanceof View) { 16527 final View view = (View) viewParent; 16528 16529 position[0] -= view.mScrollX; 16530 position[1] -= view.mScrollY; 16531 16532 if (!view.hasIdentityMatrix()) { 16533 view.getMatrix().mapPoints(position); 16534 } 16535 16536 position[0] += view.mLeft; 16537 position[1] += view.mTop; 16538 16539 viewParent = view.mParent; 16540 } 16541 16542 if (viewParent instanceof ViewRootImpl) { 16543 // *cough* 16544 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16545 position[1] -= vr.mCurScrollY; 16546 } 16547 16548 location[0] = (int) (position[0] + 0.5f); 16549 location[1] = (int) (position[1] + 0.5f); 16550 } 16551 16552 /** 16553 * {@hide} 16554 * @param id the id of the view to be found 16555 * @return the view of the specified id, null if cannot be found 16556 */ 16557 protected View findViewTraversal(int id) { 16558 if (id == mID) { 16559 return this; 16560 } 16561 return null; 16562 } 16563 16564 /** 16565 * {@hide} 16566 * @param tag the tag of the view to be found 16567 * @return the view of specified tag, null if cannot be found 16568 */ 16569 protected View findViewWithTagTraversal(Object tag) { 16570 if (tag != null && tag.equals(mTag)) { 16571 return this; 16572 } 16573 return null; 16574 } 16575 16576 /** 16577 * {@hide} 16578 * @param predicate The predicate to evaluate. 16579 * @param childToSkip If not null, ignores this child during the recursive traversal. 16580 * @return The first view that matches the predicate or null. 16581 */ 16582 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16583 if (predicate.apply(this)) { 16584 return this; 16585 } 16586 return null; 16587 } 16588 16589 /** 16590 * Look for a child view with the given id. If this view has the given 16591 * id, return this view. 16592 * 16593 * @param id The id to search for. 16594 * @return The view that has the given id in the hierarchy or null 16595 */ 16596 public final View findViewById(int id) { 16597 if (id < 0) { 16598 return null; 16599 } 16600 return findViewTraversal(id); 16601 } 16602 16603 /** 16604 * Finds a view by its unuque and stable accessibility id. 16605 * 16606 * @param accessibilityId The searched accessibility id. 16607 * @return The found view. 16608 */ 16609 final View findViewByAccessibilityId(int accessibilityId) { 16610 if (accessibilityId < 0) { 16611 return null; 16612 } 16613 return findViewByAccessibilityIdTraversal(accessibilityId); 16614 } 16615 16616 /** 16617 * Performs the traversal to find a view by its unuque and stable accessibility id. 16618 * 16619 * <strong>Note:</strong>This method does not stop at the root namespace 16620 * boundary since the user can touch the screen at an arbitrary location 16621 * potentially crossing the root namespace bounday which will send an 16622 * accessibility event to accessibility services and they should be able 16623 * to obtain the event source. Also accessibility ids are guaranteed to be 16624 * unique in the window. 16625 * 16626 * @param accessibilityId The accessibility id. 16627 * @return The found view. 16628 * 16629 * @hide 16630 */ 16631 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16632 if (getAccessibilityViewId() == accessibilityId) { 16633 return this; 16634 } 16635 return null; 16636 } 16637 16638 /** 16639 * Look for a child view with the given tag. If this view has the given 16640 * tag, return this view. 16641 * 16642 * @param tag The tag to search for, using "tag.equals(getTag())". 16643 * @return The View that has the given tag in the hierarchy or null 16644 */ 16645 public final View findViewWithTag(Object tag) { 16646 if (tag == null) { 16647 return null; 16648 } 16649 return findViewWithTagTraversal(tag); 16650 } 16651 16652 /** 16653 * {@hide} 16654 * Look for a child view that matches the specified predicate. 16655 * If this view matches the predicate, return this view. 16656 * 16657 * @param predicate The predicate to evaluate. 16658 * @return The first view that matches the predicate or null. 16659 */ 16660 public final View findViewByPredicate(Predicate<View> predicate) { 16661 return findViewByPredicateTraversal(predicate, null); 16662 } 16663 16664 /** 16665 * {@hide} 16666 * Look for a child view that matches the specified predicate, 16667 * starting with the specified view and its descendents and then 16668 * recusively searching the ancestors and siblings of that view 16669 * until this view is reached. 16670 * 16671 * This method is useful in cases where the predicate does not match 16672 * a single unique view (perhaps multiple views use the same id) 16673 * and we are trying to find the view that is "closest" in scope to the 16674 * starting view. 16675 * 16676 * @param start The view to start from. 16677 * @param predicate The predicate to evaluate. 16678 * @return The first view that matches the predicate or null. 16679 */ 16680 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16681 View childToSkip = null; 16682 for (;;) { 16683 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16684 if (view != null || start == this) { 16685 return view; 16686 } 16687 16688 ViewParent parent = start.getParent(); 16689 if (parent == null || !(parent instanceof View)) { 16690 return null; 16691 } 16692 16693 childToSkip = start; 16694 start = (View) parent; 16695 } 16696 } 16697 16698 /** 16699 * Sets the identifier for this view. The identifier does not have to be 16700 * unique in this view's hierarchy. The identifier should be a positive 16701 * number. 16702 * 16703 * @see #NO_ID 16704 * @see #getId() 16705 * @see #findViewById(int) 16706 * 16707 * @param id a number used to identify the view 16708 * 16709 * @attr ref android.R.styleable#View_id 16710 */ 16711 public void setId(int id) { 16712 mID = id; 16713 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16714 mID = generateViewId(); 16715 } 16716 } 16717 16718 /** 16719 * {@hide} 16720 * 16721 * @param isRoot true if the view belongs to the root namespace, false 16722 * otherwise 16723 */ 16724 public void setIsRootNamespace(boolean isRoot) { 16725 if (isRoot) { 16726 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16727 } else { 16728 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16729 } 16730 } 16731 16732 /** 16733 * {@hide} 16734 * 16735 * @return true if the view belongs to the root namespace, false otherwise 16736 */ 16737 public boolean isRootNamespace() { 16738 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16739 } 16740 16741 /** 16742 * Returns this view's identifier. 16743 * 16744 * @return a positive integer used to identify the view or {@link #NO_ID} 16745 * if the view has no ID 16746 * 16747 * @see #setId(int) 16748 * @see #findViewById(int) 16749 * @attr ref android.R.styleable#View_id 16750 */ 16751 @ViewDebug.CapturedViewProperty 16752 public int getId() { 16753 return mID; 16754 } 16755 16756 /** 16757 * Returns this view's tag. 16758 * 16759 * @return the Object stored in this view as a tag, or {@code null} if not 16760 * set 16761 * 16762 * @see #setTag(Object) 16763 * @see #getTag(int) 16764 */ 16765 @ViewDebug.ExportedProperty 16766 public Object getTag() { 16767 return mTag; 16768 } 16769 16770 /** 16771 * Sets the tag associated with this view. A tag can be used to mark 16772 * a view in its hierarchy and does not have to be unique within the 16773 * hierarchy. Tags can also be used to store data within a view without 16774 * resorting to another data structure. 16775 * 16776 * @param tag an Object to tag the view with 16777 * 16778 * @see #getTag() 16779 * @see #setTag(int, Object) 16780 */ 16781 public void setTag(final Object tag) { 16782 mTag = tag; 16783 } 16784 16785 /** 16786 * Returns the tag associated with this view and the specified key. 16787 * 16788 * @param key The key identifying the tag 16789 * 16790 * @return the Object stored in this view as a tag, or {@code null} if not 16791 * set 16792 * 16793 * @see #setTag(int, Object) 16794 * @see #getTag() 16795 */ 16796 public Object getTag(int key) { 16797 if (mKeyedTags != null) return mKeyedTags.get(key); 16798 return null; 16799 } 16800 16801 /** 16802 * Sets a tag associated with this view and a key. A tag can be used 16803 * to mark a view in its hierarchy and does not have to be unique within 16804 * the hierarchy. Tags can also be used to store data within a view 16805 * without resorting to another data structure. 16806 * 16807 * The specified key should be an id declared in the resources of the 16808 * application to ensure it is unique (see the <a 16809 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16810 * Keys identified as belonging to 16811 * the Android framework or not associated with any package will cause 16812 * an {@link IllegalArgumentException} to be thrown. 16813 * 16814 * @param key The key identifying the tag 16815 * @param tag An Object to tag the view with 16816 * 16817 * @throws IllegalArgumentException If they specified key is not valid 16818 * 16819 * @see #setTag(Object) 16820 * @see #getTag(int) 16821 */ 16822 public void setTag(int key, final Object tag) { 16823 // If the package id is 0x00 or 0x01, it's either an undefined package 16824 // or a framework id 16825 if ((key >>> 24) < 2) { 16826 throw new IllegalArgumentException("The key must be an application-specific " 16827 + "resource id."); 16828 } 16829 16830 setKeyedTag(key, tag); 16831 } 16832 16833 /** 16834 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16835 * framework id. 16836 * 16837 * @hide 16838 */ 16839 public void setTagInternal(int key, Object tag) { 16840 if ((key >>> 24) != 0x1) { 16841 throw new IllegalArgumentException("The key must be a framework-specific " 16842 + "resource id."); 16843 } 16844 16845 setKeyedTag(key, tag); 16846 } 16847 16848 private void setKeyedTag(int key, Object tag) { 16849 if (mKeyedTags == null) { 16850 mKeyedTags = new SparseArray<Object>(2); 16851 } 16852 16853 mKeyedTags.put(key, tag); 16854 } 16855 16856 /** 16857 * Prints information about this view in the log output, with the tag 16858 * {@link #VIEW_LOG_TAG}. 16859 * 16860 * @hide 16861 */ 16862 public void debug() { 16863 debug(0); 16864 } 16865 16866 /** 16867 * Prints information about this view in the log output, with the tag 16868 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16869 * indentation defined by the <code>depth</code>. 16870 * 16871 * @param depth the indentation level 16872 * 16873 * @hide 16874 */ 16875 protected void debug(int depth) { 16876 String output = debugIndent(depth - 1); 16877 16878 output += "+ " + this; 16879 int id = getId(); 16880 if (id != -1) { 16881 output += " (id=" + id + ")"; 16882 } 16883 Object tag = getTag(); 16884 if (tag != null) { 16885 output += " (tag=" + tag + ")"; 16886 } 16887 Log.d(VIEW_LOG_TAG, output); 16888 16889 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16890 output = debugIndent(depth) + " FOCUSED"; 16891 Log.d(VIEW_LOG_TAG, output); 16892 } 16893 16894 output = debugIndent(depth); 16895 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16896 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16897 + "} "; 16898 Log.d(VIEW_LOG_TAG, output); 16899 16900 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16901 || mPaddingBottom != 0) { 16902 output = debugIndent(depth); 16903 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16904 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16905 Log.d(VIEW_LOG_TAG, output); 16906 } 16907 16908 output = debugIndent(depth); 16909 output += "mMeasureWidth=" + mMeasuredWidth + 16910 " mMeasureHeight=" + mMeasuredHeight; 16911 Log.d(VIEW_LOG_TAG, output); 16912 16913 output = debugIndent(depth); 16914 if (mLayoutParams == null) { 16915 output += "BAD! no layout params"; 16916 } else { 16917 output = mLayoutParams.debug(output); 16918 } 16919 Log.d(VIEW_LOG_TAG, output); 16920 16921 output = debugIndent(depth); 16922 output += "flags={"; 16923 output += View.printFlags(mViewFlags); 16924 output += "}"; 16925 Log.d(VIEW_LOG_TAG, output); 16926 16927 output = debugIndent(depth); 16928 output += "privateFlags={"; 16929 output += View.printPrivateFlags(mPrivateFlags); 16930 output += "}"; 16931 Log.d(VIEW_LOG_TAG, output); 16932 } 16933 16934 /** 16935 * Creates a string of whitespaces used for indentation. 16936 * 16937 * @param depth the indentation level 16938 * @return a String containing (depth * 2 + 3) * 2 white spaces 16939 * 16940 * @hide 16941 */ 16942 protected static String debugIndent(int depth) { 16943 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16944 for (int i = 0; i < (depth * 2) + 3; i++) { 16945 spaces.append(' ').append(' '); 16946 } 16947 return spaces.toString(); 16948 } 16949 16950 /** 16951 * <p>Return the offset of the widget's text baseline from the widget's top 16952 * boundary. If this widget does not support baseline alignment, this 16953 * method returns -1. </p> 16954 * 16955 * @return the offset of the baseline within the widget's bounds or -1 16956 * if baseline alignment is not supported 16957 */ 16958 @ViewDebug.ExportedProperty(category = "layout") 16959 public int getBaseline() { 16960 return -1; 16961 } 16962 16963 /** 16964 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16965 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16966 * a layout pass. 16967 * 16968 * @return whether the view hierarchy is currently undergoing a layout pass 16969 */ 16970 public boolean isInLayout() { 16971 ViewRootImpl viewRoot = getViewRootImpl(); 16972 return (viewRoot != null && viewRoot.isInLayout()); 16973 } 16974 16975 /** 16976 * Call this when something has changed which has invalidated the 16977 * layout of this view. This will schedule a layout pass of the view 16978 * tree. This should not be called while the view hierarchy is currently in a layout 16979 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16980 * end of the current layout pass (and then layout will run again) or after the current 16981 * frame is drawn and the next layout occurs. 16982 * 16983 * <p>Subclasses which override this method should call the superclass method to 16984 * handle possible request-during-layout errors correctly.</p> 16985 */ 16986 public void requestLayout() { 16987 if (mMeasureCache != null) mMeasureCache.clear(); 16988 16989 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16990 // Only trigger request-during-layout logic if this is the view requesting it, 16991 // not the views in its parent hierarchy 16992 ViewRootImpl viewRoot = getViewRootImpl(); 16993 if (viewRoot != null && viewRoot.isInLayout()) { 16994 if (!viewRoot.requestLayoutDuringLayout(this)) { 16995 return; 16996 } 16997 } 16998 mAttachInfo.mViewRequestingLayout = this; 16999 } 17000 17001 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17002 mPrivateFlags |= PFLAG_INVALIDATED; 17003 17004 if (mParent != null && !mParent.isLayoutRequested()) { 17005 mParent.requestLayout(); 17006 } 17007 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 17008 mAttachInfo.mViewRequestingLayout = null; 17009 } 17010 } 17011 17012 /** 17013 * Forces this view to be laid out during the next layout pass. 17014 * This method does not call requestLayout() or forceLayout() 17015 * on the parent. 17016 */ 17017 public void forceLayout() { 17018 if (mMeasureCache != null) mMeasureCache.clear(); 17019 17020 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17021 mPrivateFlags |= PFLAG_INVALIDATED; 17022 } 17023 17024 /** 17025 * <p> 17026 * This is called to find out how big a view should be. The parent 17027 * supplies constraint information in the width and height parameters. 17028 * </p> 17029 * 17030 * <p> 17031 * The actual measurement work of a view is performed in 17032 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 17033 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 17034 * </p> 17035 * 17036 * 17037 * @param widthMeasureSpec Horizontal space requirements as imposed by the 17038 * parent 17039 * @param heightMeasureSpec Vertical space requirements as imposed by the 17040 * parent 17041 * 17042 * @see #onMeasure(int, int) 17043 */ 17044 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 17045 boolean optical = isLayoutModeOptical(this); 17046 if (optical != isLayoutModeOptical(mParent)) { 17047 Insets insets = getOpticalInsets(); 17048 int oWidth = insets.left + insets.right; 17049 int oHeight = insets.top + insets.bottom; 17050 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 17051 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 17052 } 17053 17054 // Suppress sign extension for the low bytes 17055 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 17056 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 17057 17058 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 17059 widthMeasureSpec != mOldWidthMeasureSpec || 17060 heightMeasureSpec != mOldHeightMeasureSpec) { 17061 17062 // first clears the measured dimension flag 17063 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 17064 17065 resolveRtlPropertiesIfNeeded(); 17066 17067 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 17068 mMeasureCache.indexOfKey(key); 17069 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17070 // measure ourselves, this should set the measured dimension flag back 17071 onMeasure(widthMeasureSpec, heightMeasureSpec); 17072 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17073 } else { 17074 long value = mMeasureCache.valueAt(cacheIndex); 17075 // Casting a long to int drops the high 32 bits, no mask needed 17076 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17077 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17078 } 17079 17080 // flag not set, setMeasuredDimension() was not invoked, we raise 17081 // an exception to warn the developer 17082 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17083 throw new IllegalStateException("onMeasure() did not set the" 17084 + " measured dimension by calling" 17085 + " setMeasuredDimension()"); 17086 } 17087 17088 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17089 } 17090 17091 mOldWidthMeasureSpec = widthMeasureSpec; 17092 mOldHeightMeasureSpec = heightMeasureSpec; 17093 17094 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17095 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17096 } 17097 17098 /** 17099 * <p> 17100 * Measure the view and its content to determine the measured width and the 17101 * measured height. This method is invoked by {@link #measure(int, int)} and 17102 * should be overriden by subclasses to provide accurate and efficient 17103 * measurement of their contents. 17104 * </p> 17105 * 17106 * <p> 17107 * <strong>CONTRACT:</strong> When overriding this method, you 17108 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17109 * measured width and height of this view. Failure to do so will trigger an 17110 * <code>IllegalStateException</code>, thrown by 17111 * {@link #measure(int, int)}. Calling the superclass' 17112 * {@link #onMeasure(int, int)} is a valid use. 17113 * </p> 17114 * 17115 * <p> 17116 * The base class implementation of measure defaults to the background size, 17117 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17118 * override {@link #onMeasure(int, int)} to provide better measurements of 17119 * their content. 17120 * </p> 17121 * 17122 * <p> 17123 * If this method is overridden, it is the subclass's responsibility to make 17124 * sure the measured height and width are at least the view's minimum height 17125 * and width ({@link #getSuggestedMinimumHeight()} and 17126 * {@link #getSuggestedMinimumWidth()}). 17127 * </p> 17128 * 17129 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17130 * The requirements are encoded with 17131 * {@link android.view.View.MeasureSpec}. 17132 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17133 * The requirements are encoded with 17134 * {@link android.view.View.MeasureSpec}. 17135 * 17136 * @see #getMeasuredWidth() 17137 * @see #getMeasuredHeight() 17138 * @see #setMeasuredDimension(int, int) 17139 * @see #getSuggestedMinimumHeight() 17140 * @see #getSuggestedMinimumWidth() 17141 * @see android.view.View.MeasureSpec#getMode(int) 17142 * @see android.view.View.MeasureSpec#getSize(int) 17143 */ 17144 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17145 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17146 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17147 } 17148 17149 /** 17150 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17151 * measured width and measured height. Failing to do so will trigger an 17152 * exception at measurement time.</p> 17153 * 17154 * @param measuredWidth The measured width of this view. May be a complex 17155 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17156 * {@link #MEASURED_STATE_TOO_SMALL}. 17157 * @param measuredHeight The measured height of this view. May be a complex 17158 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17159 * {@link #MEASURED_STATE_TOO_SMALL}. 17160 */ 17161 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17162 boolean optical = isLayoutModeOptical(this); 17163 if (optical != isLayoutModeOptical(mParent)) { 17164 Insets insets = getOpticalInsets(); 17165 int opticalWidth = insets.left + insets.right; 17166 int opticalHeight = insets.top + insets.bottom; 17167 17168 measuredWidth += optical ? opticalWidth : -opticalWidth; 17169 measuredHeight += optical ? opticalHeight : -opticalHeight; 17170 } 17171 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17172 } 17173 17174 /** 17175 * Sets the measured dimension without extra processing for things like optical bounds. 17176 * Useful for reapplying consistent values that have already been cooked with adjustments 17177 * for optical bounds, etc. such as those from the measurement cache. 17178 * 17179 * @param measuredWidth The measured width of this view. May be a complex 17180 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17181 * {@link #MEASURED_STATE_TOO_SMALL}. 17182 * @param measuredHeight The measured height of this view. May be a complex 17183 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17184 * {@link #MEASURED_STATE_TOO_SMALL}. 17185 */ 17186 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17187 mMeasuredWidth = measuredWidth; 17188 mMeasuredHeight = measuredHeight; 17189 17190 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17191 } 17192 17193 /** 17194 * Merge two states as returned by {@link #getMeasuredState()}. 17195 * @param curState The current state as returned from a view or the result 17196 * of combining multiple views. 17197 * @param newState The new view state to combine. 17198 * @return Returns a new integer reflecting the combination of the two 17199 * states. 17200 */ 17201 public static int combineMeasuredStates(int curState, int newState) { 17202 return curState | newState; 17203 } 17204 17205 /** 17206 * Version of {@link #resolveSizeAndState(int, int, int)} 17207 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17208 */ 17209 public static int resolveSize(int size, int measureSpec) { 17210 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17211 } 17212 17213 /** 17214 * Utility to reconcile a desired size and state, with constraints imposed 17215 * by a MeasureSpec. Will take the desired size, unless a different size 17216 * is imposed by the constraints. The returned value is a compound integer, 17217 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17218 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17219 * size is smaller than the size the view wants to be. 17220 * 17221 * @param size How big the view wants to be 17222 * @param measureSpec Constraints imposed by the parent 17223 * @return Size information bit mask as defined by 17224 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17225 */ 17226 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17227 int result = size; 17228 int specMode = MeasureSpec.getMode(measureSpec); 17229 int specSize = MeasureSpec.getSize(measureSpec); 17230 switch (specMode) { 17231 case MeasureSpec.UNSPECIFIED: 17232 result = size; 17233 break; 17234 case MeasureSpec.AT_MOST: 17235 if (specSize < size) { 17236 result = specSize | MEASURED_STATE_TOO_SMALL; 17237 } else { 17238 result = size; 17239 } 17240 break; 17241 case MeasureSpec.EXACTLY: 17242 result = specSize; 17243 break; 17244 } 17245 return result | (childMeasuredState&MEASURED_STATE_MASK); 17246 } 17247 17248 /** 17249 * Utility to return a default size. Uses the supplied size if the 17250 * MeasureSpec imposed no constraints. Will get larger if allowed 17251 * by the MeasureSpec. 17252 * 17253 * @param size Default size for this view 17254 * @param measureSpec Constraints imposed by the parent 17255 * @return The size this view should be. 17256 */ 17257 public static int getDefaultSize(int size, int measureSpec) { 17258 int result = size; 17259 int specMode = MeasureSpec.getMode(measureSpec); 17260 int specSize = MeasureSpec.getSize(measureSpec); 17261 17262 switch (specMode) { 17263 case MeasureSpec.UNSPECIFIED: 17264 result = size; 17265 break; 17266 case MeasureSpec.AT_MOST: 17267 case MeasureSpec.EXACTLY: 17268 result = specSize; 17269 break; 17270 } 17271 return result; 17272 } 17273 17274 /** 17275 * Returns the suggested minimum height that the view should use. This 17276 * returns the maximum of the view's minimum height 17277 * and the background's minimum height 17278 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17279 * <p> 17280 * When being used in {@link #onMeasure(int, int)}, the caller should still 17281 * ensure the returned height is within the requirements of the parent. 17282 * 17283 * @return The suggested minimum height of the view. 17284 */ 17285 protected int getSuggestedMinimumHeight() { 17286 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17287 17288 } 17289 17290 /** 17291 * Returns the suggested minimum width that the view should use. This 17292 * returns the maximum of the view's minimum width) 17293 * and the background's minimum width 17294 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17295 * <p> 17296 * When being used in {@link #onMeasure(int, int)}, the caller should still 17297 * ensure the returned width is within the requirements of the parent. 17298 * 17299 * @return The suggested minimum width of the view. 17300 */ 17301 protected int getSuggestedMinimumWidth() { 17302 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17303 } 17304 17305 /** 17306 * Returns the minimum height of the view. 17307 * 17308 * @return the minimum height the view will try to be. 17309 * 17310 * @see #setMinimumHeight(int) 17311 * 17312 * @attr ref android.R.styleable#View_minHeight 17313 */ 17314 public int getMinimumHeight() { 17315 return mMinHeight; 17316 } 17317 17318 /** 17319 * Sets the minimum height of the view. It is not guaranteed the view will 17320 * be able to achieve this minimum height (for example, if its parent layout 17321 * constrains it with less available height). 17322 * 17323 * @param minHeight The minimum height the view will try to be. 17324 * 17325 * @see #getMinimumHeight() 17326 * 17327 * @attr ref android.R.styleable#View_minHeight 17328 */ 17329 public void setMinimumHeight(int minHeight) { 17330 mMinHeight = minHeight; 17331 requestLayout(); 17332 } 17333 17334 /** 17335 * Returns the minimum width of the view. 17336 * 17337 * @return the minimum width the view will try to be. 17338 * 17339 * @see #setMinimumWidth(int) 17340 * 17341 * @attr ref android.R.styleable#View_minWidth 17342 */ 17343 public int getMinimumWidth() { 17344 return mMinWidth; 17345 } 17346 17347 /** 17348 * Sets the minimum width of the view. It is not guaranteed the view will 17349 * be able to achieve this minimum width (for example, if its parent layout 17350 * constrains it with less available width). 17351 * 17352 * @param minWidth The minimum width the view will try to be. 17353 * 17354 * @see #getMinimumWidth() 17355 * 17356 * @attr ref android.R.styleable#View_minWidth 17357 */ 17358 public void setMinimumWidth(int minWidth) { 17359 mMinWidth = minWidth; 17360 requestLayout(); 17361 17362 } 17363 17364 /** 17365 * Get the animation currently associated with this view. 17366 * 17367 * @return The animation that is currently playing or 17368 * scheduled to play for this view. 17369 */ 17370 public Animation getAnimation() { 17371 return mCurrentAnimation; 17372 } 17373 17374 /** 17375 * Start the specified animation now. 17376 * 17377 * @param animation the animation to start now 17378 */ 17379 public void startAnimation(Animation animation) { 17380 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17381 setAnimation(animation); 17382 invalidateParentCaches(); 17383 invalidate(true); 17384 } 17385 17386 /** 17387 * Cancels any animations for this view. 17388 */ 17389 public void clearAnimation() { 17390 if (mCurrentAnimation != null) { 17391 mCurrentAnimation.detach(); 17392 } 17393 mCurrentAnimation = null; 17394 invalidateParentIfNeeded(); 17395 } 17396 17397 /** 17398 * Sets the next animation to play for this view. 17399 * If you want the animation to play immediately, use 17400 * {@link #startAnimation(android.view.animation.Animation)} instead. 17401 * This method provides allows fine-grained 17402 * control over the start time and invalidation, but you 17403 * must make sure that 1) the animation has a start time set, and 17404 * 2) the view's parent (which controls animations on its children) 17405 * will be invalidated when the animation is supposed to 17406 * start. 17407 * 17408 * @param animation The next animation, or null. 17409 */ 17410 public void setAnimation(Animation animation) { 17411 mCurrentAnimation = animation; 17412 17413 if (animation != null) { 17414 // If the screen is off assume the animation start time is now instead of 17415 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17416 // would cause the animation to start when the screen turns back on 17417 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17418 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17419 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17420 } 17421 animation.reset(); 17422 } 17423 } 17424 17425 /** 17426 * Invoked by a parent ViewGroup to notify the start of the animation 17427 * currently associated with this view. If you override this method, 17428 * always call super.onAnimationStart(); 17429 * 17430 * @see #setAnimation(android.view.animation.Animation) 17431 * @see #getAnimation() 17432 */ 17433 protected void onAnimationStart() { 17434 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17435 } 17436 17437 /** 17438 * Invoked by a parent ViewGroup to notify the end of the animation 17439 * currently associated with this view. If you override this method, 17440 * always call super.onAnimationEnd(); 17441 * 17442 * @see #setAnimation(android.view.animation.Animation) 17443 * @see #getAnimation() 17444 */ 17445 protected void onAnimationEnd() { 17446 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17447 } 17448 17449 /** 17450 * Invoked if there is a Transform that involves alpha. Subclass that can 17451 * draw themselves with the specified alpha should return true, and then 17452 * respect that alpha when their onDraw() is called. If this returns false 17453 * then the view may be redirected to draw into an offscreen buffer to 17454 * fulfill the request, which will look fine, but may be slower than if the 17455 * subclass handles it internally. The default implementation returns false. 17456 * 17457 * @param alpha The alpha (0..255) to apply to the view's drawing 17458 * @return true if the view can draw with the specified alpha. 17459 */ 17460 protected boolean onSetAlpha(int alpha) { 17461 return false; 17462 } 17463 17464 /** 17465 * This is used by the RootView to perform an optimization when 17466 * the view hierarchy contains one or several SurfaceView. 17467 * SurfaceView is always considered transparent, but its children are not, 17468 * therefore all View objects remove themselves from the global transparent 17469 * region (passed as a parameter to this function). 17470 * 17471 * @param region The transparent region for this ViewAncestor (window). 17472 * 17473 * @return Returns true if the effective visibility of the view at this 17474 * point is opaque, regardless of the transparent region; returns false 17475 * if it is possible for underlying windows to be seen behind the view. 17476 * 17477 * {@hide} 17478 */ 17479 public boolean gatherTransparentRegion(Region region) { 17480 final AttachInfo attachInfo = mAttachInfo; 17481 if (region != null && attachInfo != null) { 17482 final int pflags = mPrivateFlags; 17483 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17484 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17485 // remove it from the transparent region. 17486 final int[] location = attachInfo.mTransparentLocation; 17487 getLocationInWindow(location); 17488 region.op(location[0], location[1], location[0] + mRight - mLeft, 17489 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17490 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 17491 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17492 // exists, so we remove the background drawable's non-transparent 17493 // parts from this transparent region. 17494 applyDrawableToTransparentRegion(mBackground, region); 17495 } 17496 } 17497 return true; 17498 } 17499 17500 /** 17501 * Play a sound effect for this view. 17502 * 17503 * <p>The framework will play sound effects for some built in actions, such as 17504 * clicking, but you may wish to play these effects in your widget, 17505 * for instance, for internal navigation. 17506 * 17507 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17508 * {@link #isSoundEffectsEnabled()} is true. 17509 * 17510 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17511 */ 17512 public void playSoundEffect(int soundConstant) { 17513 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17514 return; 17515 } 17516 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17517 } 17518 17519 /** 17520 * BZZZTT!!1! 17521 * 17522 * <p>Provide haptic feedback to the user for this view. 17523 * 17524 * <p>The framework will provide haptic feedback for some built in actions, 17525 * such as long presses, but you may wish to provide feedback for your 17526 * own widget. 17527 * 17528 * <p>The feedback will only be performed if 17529 * {@link #isHapticFeedbackEnabled()} is true. 17530 * 17531 * @param feedbackConstant One of the constants defined in 17532 * {@link HapticFeedbackConstants} 17533 */ 17534 public boolean performHapticFeedback(int feedbackConstant) { 17535 return performHapticFeedback(feedbackConstant, 0); 17536 } 17537 17538 /** 17539 * BZZZTT!!1! 17540 * 17541 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17542 * 17543 * @param feedbackConstant One of the constants defined in 17544 * {@link HapticFeedbackConstants} 17545 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17546 */ 17547 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17548 if (mAttachInfo == null) { 17549 return false; 17550 } 17551 //noinspection SimplifiableIfStatement 17552 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17553 && !isHapticFeedbackEnabled()) { 17554 return false; 17555 } 17556 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17557 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17558 } 17559 17560 /** 17561 * Request that the visibility of the status bar or other screen/window 17562 * decorations be changed. 17563 * 17564 * <p>This method is used to put the over device UI into temporary modes 17565 * where the user's attention is focused more on the application content, 17566 * by dimming or hiding surrounding system affordances. This is typically 17567 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17568 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17569 * to be placed behind the action bar (and with these flags other system 17570 * affordances) so that smooth transitions between hiding and showing them 17571 * can be done. 17572 * 17573 * <p>Two representative examples of the use of system UI visibility is 17574 * implementing a content browsing application (like a magazine reader) 17575 * and a video playing application. 17576 * 17577 * <p>The first code shows a typical implementation of a View in a content 17578 * browsing application. In this implementation, the application goes 17579 * into a content-oriented mode by hiding the status bar and action bar, 17580 * and putting the navigation elements into lights out mode. The user can 17581 * then interact with content while in this mode. Such an application should 17582 * provide an easy way for the user to toggle out of the mode (such as to 17583 * check information in the status bar or access notifications). In the 17584 * implementation here, this is done simply by tapping on the content. 17585 * 17586 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17587 * content} 17588 * 17589 * <p>This second code sample shows a typical implementation of a View 17590 * in a video playing application. In this situation, while the video is 17591 * playing the application would like to go into a complete full-screen mode, 17592 * to use as much of the display as possible for the video. When in this state 17593 * the user can not interact with the application; the system intercepts 17594 * touching on the screen to pop the UI out of full screen mode. See 17595 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17596 * 17597 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17598 * content} 17599 * 17600 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17601 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17602 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17603 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17604 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17605 */ 17606 public void setSystemUiVisibility(int visibility) { 17607 if (visibility != mSystemUiVisibility) { 17608 mSystemUiVisibility = visibility; 17609 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17610 mParent.recomputeViewAttributes(this); 17611 } 17612 } 17613 } 17614 17615 /** 17616 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17617 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17618 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17619 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17620 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17621 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17622 */ 17623 public int getSystemUiVisibility() { 17624 return mSystemUiVisibility; 17625 } 17626 17627 /** 17628 * Returns the current system UI visibility that is currently set for 17629 * the entire window. This is the combination of the 17630 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17631 * views in the window. 17632 */ 17633 public int getWindowSystemUiVisibility() { 17634 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17635 } 17636 17637 /** 17638 * Override to find out when the window's requested system UI visibility 17639 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17640 * This is different from the callbacks received through 17641 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17642 * in that this is only telling you about the local request of the window, 17643 * not the actual values applied by the system. 17644 */ 17645 public void onWindowSystemUiVisibilityChanged(int visible) { 17646 } 17647 17648 /** 17649 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17650 * the view hierarchy. 17651 */ 17652 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17653 onWindowSystemUiVisibilityChanged(visible); 17654 } 17655 17656 /** 17657 * Set a listener to receive callbacks when the visibility of the system bar changes. 17658 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17659 */ 17660 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17661 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17662 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17663 mParent.recomputeViewAttributes(this); 17664 } 17665 } 17666 17667 /** 17668 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17669 * the view hierarchy. 17670 */ 17671 public void dispatchSystemUiVisibilityChanged(int visibility) { 17672 ListenerInfo li = mListenerInfo; 17673 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17674 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17675 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17676 } 17677 } 17678 17679 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17680 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17681 if (val != mSystemUiVisibility) { 17682 setSystemUiVisibility(val); 17683 return true; 17684 } 17685 return false; 17686 } 17687 17688 /** @hide */ 17689 public void setDisabledSystemUiVisibility(int flags) { 17690 if (mAttachInfo != null) { 17691 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17692 mAttachInfo.mDisabledSystemUiVisibility = flags; 17693 if (mParent != null) { 17694 mParent.recomputeViewAttributes(this); 17695 } 17696 } 17697 } 17698 } 17699 17700 /** 17701 * Creates an image that the system displays during the drag and drop 17702 * operation. This is called a "drag shadow". The default implementation 17703 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17704 * appearance as the given View. The default also positions the center of the drag shadow 17705 * directly under the touch point. If no View is provided (the constructor with no parameters 17706 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17707 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17708 * default is an invisible drag shadow. 17709 * <p> 17710 * You are not required to use the View you provide to the constructor as the basis of the 17711 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17712 * anything you want as the drag shadow. 17713 * </p> 17714 * <p> 17715 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17716 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17717 * size and position of the drag shadow. It uses this data to construct a 17718 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17719 * so that your application can draw the shadow image in the Canvas. 17720 * </p> 17721 * 17722 * <div class="special reference"> 17723 * <h3>Developer Guides</h3> 17724 * <p>For a guide to implementing drag and drop features, read the 17725 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17726 * </div> 17727 */ 17728 public static class DragShadowBuilder { 17729 private final WeakReference<View> mView; 17730 17731 /** 17732 * Constructs a shadow image builder based on a View. By default, the resulting drag 17733 * shadow will have the same appearance and dimensions as the View, with the touch point 17734 * over the center of the View. 17735 * @param view A View. Any View in scope can be used. 17736 */ 17737 public DragShadowBuilder(View view) { 17738 mView = new WeakReference<View>(view); 17739 } 17740 17741 /** 17742 * Construct a shadow builder object with no associated View. This 17743 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17744 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17745 * to supply the drag shadow's dimensions and appearance without 17746 * reference to any View object. If they are not overridden, then the result is an 17747 * invisible drag shadow. 17748 */ 17749 public DragShadowBuilder() { 17750 mView = new WeakReference<View>(null); 17751 } 17752 17753 /** 17754 * Returns the View object that had been passed to the 17755 * {@link #View.DragShadowBuilder(View)} 17756 * constructor. If that View parameter was {@code null} or if the 17757 * {@link #View.DragShadowBuilder()} 17758 * constructor was used to instantiate the builder object, this method will return 17759 * null. 17760 * 17761 * @return The View object associate with this builder object. 17762 */ 17763 @SuppressWarnings({"JavadocReference"}) 17764 final public View getView() { 17765 return mView.get(); 17766 } 17767 17768 /** 17769 * Provides the metrics for the shadow image. These include the dimensions of 17770 * the shadow image, and the point within that shadow that should 17771 * be centered under the touch location while dragging. 17772 * <p> 17773 * The default implementation sets the dimensions of the shadow to be the 17774 * same as the dimensions of the View itself and centers the shadow under 17775 * the touch point. 17776 * </p> 17777 * 17778 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17779 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17780 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17781 * image. 17782 * 17783 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17784 * shadow image that should be underneath the touch point during the drag and drop 17785 * operation. Your application must set {@link android.graphics.Point#x} to the 17786 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17787 */ 17788 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17789 final View view = mView.get(); 17790 if (view != null) { 17791 shadowSize.set(view.getWidth(), view.getHeight()); 17792 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17793 } else { 17794 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17795 } 17796 } 17797 17798 /** 17799 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17800 * based on the dimensions it received from the 17801 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17802 * 17803 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17804 */ 17805 public void onDrawShadow(Canvas canvas) { 17806 final View view = mView.get(); 17807 if (view != null) { 17808 view.draw(canvas); 17809 } else { 17810 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17811 } 17812 } 17813 } 17814 17815 /** 17816 * Starts a drag and drop operation. When your application calls this method, it passes a 17817 * {@link android.view.View.DragShadowBuilder} object to the system. The 17818 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17819 * to get metrics for the drag shadow, and then calls the object's 17820 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17821 * <p> 17822 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17823 * drag events to all the View objects in your application that are currently visible. It does 17824 * this either by calling the View object's drag listener (an implementation of 17825 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17826 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17827 * Both are passed a {@link android.view.DragEvent} object that has a 17828 * {@link android.view.DragEvent#getAction()} value of 17829 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17830 * </p> 17831 * <p> 17832 * Your application can invoke startDrag() on any attached View object. The View object does not 17833 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17834 * be related to the View the user selected for dragging. 17835 * </p> 17836 * @param data A {@link android.content.ClipData} object pointing to the data to be 17837 * transferred by the drag and drop operation. 17838 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17839 * drag shadow. 17840 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17841 * drop operation. This Object is put into every DragEvent object sent by the system during the 17842 * current drag. 17843 * <p> 17844 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17845 * to the target Views. For example, it can contain flags that differentiate between a 17846 * a copy operation and a move operation. 17847 * </p> 17848 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17849 * so the parameter should be set to 0. 17850 * @return {@code true} if the method completes successfully, or 17851 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17852 * do a drag, and so no drag operation is in progress. 17853 */ 17854 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17855 Object myLocalState, int flags) { 17856 if (ViewDebug.DEBUG_DRAG) { 17857 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17858 } 17859 boolean okay = false; 17860 17861 Point shadowSize = new Point(); 17862 Point shadowTouchPoint = new Point(); 17863 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17864 17865 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17866 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17867 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17868 } 17869 17870 if (ViewDebug.DEBUG_DRAG) { 17871 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17872 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17873 } 17874 Surface surface = new Surface(); 17875 try { 17876 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17877 flags, shadowSize.x, shadowSize.y, surface); 17878 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17879 + " surface=" + surface); 17880 if (token != null) { 17881 Canvas canvas = surface.lockCanvas(null); 17882 try { 17883 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17884 shadowBuilder.onDrawShadow(canvas); 17885 } finally { 17886 surface.unlockCanvasAndPost(canvas); 17887 } 17888 17889 final ViewRootImpl root = getViewRootImpl(); 17890 17891 // Cache the local state object for delivery with DragEvents 17892 root.setLocalDragState(myLocalState); 17893 17894 // repurpose 'shadowSize' for the last touch point 17895 root.getLastTouchPoint(shadowSize); 17896 17897 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17898 shadowSize.x, shadowSize.y, 17899 shadowTouchPoint.x, shadowTouchPoint.y, data); 17900 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17901 17902 // Off and running! Release our local surface instance; the drag 17903 // shadow surface is now managed by the system process. 17904 surface.release(); 17905 } 17906 } catch (Exception e) { 17907 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17908 surface.destroy(); 17909 } 17910 17911 return okay; 17912 } 17913 17914 /** 17915 * Handles drag events sent by the system following a call to 17916 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17917 *<p> 17918 * When the system calls this method, it passes a 17919 * {@link android.view.DragEvent} object. A call to 17920 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17921 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17922 * operation. 17923 * @param event The {@link android.view.DragEvent} sent by the system. 17924 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17925 * in DragEvent, indicating the type of drag event represented by this object. 17926 * @return {@code true} if the method was successful, otherwise {@code false}. 17927 * <p> 17928 * The method should return {@code true} in response to an action type of 17929 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17930 * operation. 17931 * </p> 17932 * <p> 17933 * The method should also return {@code true} in response to an action type of 17934 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17935 * {@code false} if it didn't. 17936 * </p> 17937 */ 17938 public boolean onDragEvent(DragEvent event) { 17939 return false; 17940 } 17941 17942 /** 17943 * Detects if this View is enabled and has a drag event listener. 17944 * If both are true, then it calls the drag event listener with the 17945 * {@link android.view.DragEvent} it received. If the drag event listener returns 17946 * {@code true}, then dispatchDragEvent() returns {@code true}. 17947 * <p> 17948 * For all other cases, the method calls the 17949 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17950 * method and returns its result. 17951 * </p> 17952 * <p> 17953 * This ensures that a drag event is always consumed, even if the View does not have a drag 17954 * event listener. However, if the View has a listener and the listener returns true, then 17955 * onDragEvent() is not called. 17956 * </p> 17957 */ 17958 public boolean dispatchDragEvent(DragEvent event) { 17959 ListenerInfo li = mListenerInfo; 17960 //noinspection SimplifiableIfStatement 17961 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17962 && li.mOnDragListener.onDrag(this, event)) { 17963 return true; 17964 } 17965 return onDragEvent(event); 17966 } 17967 17968 boolean canAcceptDrag() { 17969 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17970 } 17971 17972 /** 17973 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17974 * it is ever exposed at all. 17975 * @hide 17976 */ 17977 public void onCloseSystemDialogs(String reason) { 17978 } 17979 17980 /** 17981 * Given a Drawable whose bounds have been set to draw into this view, 17982 * update a Region being computed for 17983 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17984 * that any non-transparent parts of the Drawable are removed from the 17985 * given transparent region. 17986 * 17987 * @param dr The Drawable whose transparency is to be applied to the region. 17988 * @param region A Region holding the current transparency information, 17989 * where any parts of the region that are set are considered to be 17990 * transparent. On return, this region will be modified to have the 17991 * transparency information reduced by the corresponding parts of the 17992 * Drawable that are not transparent. 17993 * {@hide} 17994 */ 17995 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17996 if (DBG) { 17997 Log.i("View", "Getting transparent region for: " + this); 17998 } 17999 final Region r = dr.getTransparentRegion(); 18000 final Rect db = dr.getBounds(); 18001 final AttachInfo attachInfo = mAttachInfo; 18002 if (r != null && attachInfo != null) { 18003 final int w = getRight()-getLeft(); 18004 final int h = getBottom()-getTop(); 18005 if (db.left > 0) { 18006 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 18007 r.op(0, 0, db.left, h, Region.Op.UNION); 18008 } 18009 if (db.right < w) { 18010 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 18011 r.op(db.right, 0, w, h, Region.Op.UNION); 18012 } 18013 if (db.top > 0) { 18014 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 18015 r.op(0, 0, w, db.top, Region.Op.UNION); 18016 } 18017 if (db.bottom < h) { 18018 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 18019 r.op(0, db.bottom, w, h, Region.Op.UNION); 18020 } 18021 final int[] location = attachInfo.mTransparentLocation; 18022 getLocationInWindow(location); 18023 r.translate(location[0], location[1]); 18024 region.op(r, Region.Op.INTERSECT); 18025 } else { 18026 region.op(db, Region.Op.DIFFERENCE); 18027 } 18028 } 18029 18030 private void checkForLongClick(int delayOffset) { 18031 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 18032 mHasPerformedLongPress = false; 18033 18034 if (mPendingCheckForLongPress == null) { 18035 mPendingCheckForLongPress = new CheckForLongPress(); 18036 } 18037 mPendingCheckForLongPress.rememberWindowAttachCount(); 18038 postDelayed(mPendingCheckForLongPress, 18039 ViewConfiguration.getLongPressTimeout() - delayOffset); 18040 } 18041 } 18042 18043 /** 18044 * Inflate a view from an XML resource. This convenience method wraps the {@link 18045 * LayoutInflater} class, which provides a full range of options for view inflation. 18046 * 18047 * @param context The Context object for your activity or application. 18048 * @param resource The resource ID to inflate 18049 * @param root A view group that will be the parent. Used to properly inflate the 18050 * layout_* parameters. 18051 * @see LayoutInflater 18052 */ 18053 public static View inflate(Context context, int resource, ViewGroup root) { 18054 LayoutInflater factory = LayoutInflater.from(context); 18055 return factory.inflate(resource, root); 18056 } 18057 18058 /** 18059 * Scroll the view with standard behavior for scrolling beyond the normal 18060 * content boundaries. Views that call this method should override 18061 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 18062 * results of an over-scroll operation. 18063 * 18064 * Views can use this method to handle any touch or fling-based scrolling. 18065 * 18066 * @param deltaX Change in X in pixels 18067 * @param deltaY Change in Y in pixels 18068 * @param scrollX Current X scroll value in pixels before applying deltaX 18069 * @param scrollY Current Y scroll value in pixels before applying deltaY 18070 * @param scrollRangeX Maximum content scroll range along the X axis 18071 * @param scrollRangeY Maximum content scroll range along the Y axis 18072 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18073 * along the X axis. 18074 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18075 * along the Y axis. 18076 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18077 * @return true if scrolling was clamped to an over-scroll boundary along either 18078 * axis, false otherwise. 18079 */ 18080 @SuppressWarnings({"UnusedParameters"}) 18081 protected boolean overScrollBy(int deltaX, int deltaY, 18082 int scrollX, int scrollY, 18083 int scrollRangeX, int scrollRangeY, 18084 int maxOverScrollX, int maxOverScrollY, 18085 boolean isTouchEvent) { 18086 final int overScrollMode = mOverScrollMode; 18087 final boolean canScrollHorizontal = 18088 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18089 final boolean canScrollVertical = 18090 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18091 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18092 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18093 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18094 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18095 18096 int newScrollX = scrollX + deltaX; 18097 if (!overScrollHorizontal) { 18098 maxOverScrollX = 0; 18099 } 18100 18101 int newScrollY = scrollY + deltaY; 18102 if (!overScrollVertical) { 18103 maxOverScrollY = 0; 18104 } 18105 18106 // Clamp values if at the limits and record 18107 final int left = -maxOverScrollX; 18108 final int right = maxOverScrollX + scrollRangeX; 18109 final int top = -maxOverScrollY; 18110 final int bottom = maxOverScrollY + scrollRangeY; 18111 18112 boolean clampedX = false; 18113 if (newScrollX > right) { 18114 newScrollX = right; 18115 clampedX = true; 18116 } else if (newScrollX < left) { 18117 newScrollX = left; 18118 clampedX = true; 18119 } 18120 18121 boolean clampedY = false; 18122 if (newScrollY > bottom) { 18123 newScrollY = bottom; 18124 clampedY = true; 18125 } else if (newScrollY < top) { 18126 newScrollY = top; 18127 clampedY = true; 18128 } 18129 18130 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18131 18132 return clampedX || clampedY; 18133 } 18134 18135 /** 18136 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18137 * respond to the results of an over-scroll operation. 18138 * 18139 * @param scrollX New X scroll value in pixels 18140 * @param scrollY New Y scroll value in pixels 18141 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18142 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18143 */ 18144 protected void onOverScrolled(int scrollX, int scrollY, 18145 boolean clampedX, boolean clampedY) { 18146 // Intentionally empty. 18147 } 18148 18149 /** 18150 * Returns the over-scroll mode for this view. The result will be 18151 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18152 * (allow over-scrolling only if the view content is larger than the container), 18153 * or {@link #OVER_SCROLL_NEVER}. 18154 * 18155 * @return This view's over-scroll mode. 18156 */ 18157 public int getOverScrollMode() { 18158 return mOverScrollMode; 18159 } 18160 18161 /** 18162 * Set the over-scroll mode for this view. Valid over-scroll modes are 18163 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18164 * (allow over-scrolling only if the view content is larger than the container), 18165 * or {@link #OVER_SCROLL_NEVER}. 18166 * 18167 * Setting the over-scroll mode of a view will have an effect only if the 18168 * view is capable of scrolling. 18169 * 18170 * @param overScrollMode The new over-scroll mode for this view. 18171 */ 18172 public void setOverScrollMode(int overScrollMode) { 18173 if (overScrollMode != OVER_SCROLL_ALWAYS && 18174 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18175 overScrollMode != OVER_SCROLL_NEVER) { 18176 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18177 } 18178 mOverScrollMode = overScrollMode; 18179 } 18180 18181 /** 18182 * Enable or disable nested scrolling for this view. 18183 * 18184 * <p>If this property is set to true the view will be permitted to initiate nested 18185 * scrolling operations with a compatible parent view in the current hierarchy. If this 18186 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18187 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18188 * the nested scroll.</p> 18189 * 18190 * @param enabled true to enable nested scrolling, false to disable 18191 * 18192 * @see #isNestedScrollingEnabled() 18193 */ 18194 public void setNestedScrollingEnabled(boolean enabled) { 18195 if (enabled) { 18196 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18197 } else { 18198 stopNestedScroll(); 18199 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18200 } 18201 } 18202 18203 /** 18204 * Returns true if nested scrolling is enabled for this view. 18205 * 18206 * <p>If nested scrolling is enabled and this View class implementation supports it, 18207 * this view will act as a nested scrolling child view when applicable, forwarding data 18208 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18209 * parent.</p> 18210 * 18211 * @return true if nested scrolling is enabled 18212 * 18213 * @see #setNestedScrollingEnabled(boolean) 18214 */ 18215 public boolean isNestedScrollingEnabled() { 18216 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18217 PFLAG3_NESTED_SCROLLING_ENABLED; 18218 } 18219 18220 /** 18221 * Begin a nestable scroll operation along the given axes. 18222 * 18223 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18224 * 18225 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18226 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18227 * In the case of touch scrolling the nested scroll will be terminated automatically in 18228 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18229 * In the event of programmatic scrolling the caller must explicitly call 18230 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18231 * 18232 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18233 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18234 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18235 * 18236 * <p>At each incremental step of the scroll the caller should invoke 18237 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18238 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18239 * parent at least partially consumed the scroll and the caller should adjust the amount it 18240 * scrolls by.</p> 18241 * 18242 * <p>After applying the remainder of the scroll delta the caller should invoke 18243 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18244 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18245 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18246 * </p> 18247 * 18248 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18249 * {@link #SCROLL_AXIS_VERTICAL}. 18250 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18251 * the current gesture. 18252 * 18253 * @see #stopNestedScroll() 18254 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18255 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18256 */ 18257 public boolean startNestedScroll(int axes) { 18258 if (hasNestedScrollingParent()) { 18259 // Already in progress 18260 return true; 18261 } 18262 if (isNestedScrollingEnabled()) { 18263 ViewParent p = getParent(); 18264 View child = this; 18265 while (p != null) { 18266 try { 18267 if (p.onStartNestedScroll(child, this, axes)) { 18268 mNestedScrollingParent = p; 18269 p.onNestedScrollAccepted(child, this, axes); 18270 return true; 18271 } 18272 } catch (AbstractMethodError e) { 18273 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18274 "method onStartNestedScroll", e); 18275 // Allow the search upward to continue 18276 } 18277 if (p instanceof View) { 18278 child = (View) p; 18279 } 18280 p = p.getParent(); 18281 } 18282 } 18283 return false; 18284 } 18285 18286 /** 18287 * Stop a nested scroll in progress. 18288 * 18289 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18290 * 18291 * @see #startNestedScroll(int) 18292 */ 18293 public void stopNestedScroll() { 18294 if (mNestedScrollingParent != null) { 18295 mNestedScrollingParent.onStopNestedScroll(this); 18296 mNestedScrollingParent = null; 18297 } 18298 } 18299 18300 /** 18301 * Returns true if this view has a nested scrolling parent. 18302 * 18303 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18304 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18305 * 18306 * @return whether this view has a nested scrolling parent 18307 */ 18308 public boolean hasNestedScrollingParent() { 18309 return mNestedScrollingParent != null; 18310 } 18311 18312 /** 18313 * Dispatch one step of a nested scroll in progress. 18314 * 18315 * <p>Implementations of views that support nested scrolling should call this to report 18316 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18317 * is not currently in progress or nested scrolling is not 18318 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18319 * 18320 * <p>Compatible View implementations should also call 18321 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18322 * consuming a component of the scroll event themselves.</p> 18323 * 18324 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18325 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18326 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18327 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18328 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18329 * in local view coordinates of this view from before this operation 18330 * to after it completes. View implementations may use this to adjust 18331 * expected input coordinate tracking. 18332 * @return true if the event was dispatched, false if it could not be dispatched. 18333 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18334 */ 18335 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18336 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18337 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18338 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18339 int startX = 0; 18340 int startY = 0; 18341 if (offsetInWindow != null) { 18342 getLocationInWindow(offsetInWindow); 18343 startX = offsetInWindow[0]; 18344 startY = offsetInWindow[1]; 18345 } 18346 18347 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18348 dxUnconsumed, dyUnconsumed); 18349 18350 if (offsetInWindow != null) { 18351 getLocationInWindow(offsetInWindow); 18352 offsetInWindow[0] -= startX; 18353 offsetInWindow[1] -= startY; 18354 } 18355 return true; 18356 } else if (offsetInWindow != null) { 18357 // No motion, no dispatch. Keep offsetInWindow up to date. 18358 offsetInWindow[0] = 0; 18359 offsetInWindow[1] = 0; 18360 } 18361 } 18362 return false; 18363 } 18364 18365 /** 18366 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18367 * 18368 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18369 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18370 * scrolling operation to consume some or all of the scroll operation before the child view 18371 * consumes it.</p> 18372 * 18373 * @param dx Horizontal scroll distance in pixels 18374 * @param dy Vertical scroll distance in pixels 18375 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18376 * and consumed[1] the consumed dy. 18377 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18378 * in local view coordinates of this view from before this operation 18379 * to after it completes. View implementations may use this to adjust 18380 * expected input coordinate tracking. 18381 * @return true if the parent consumed some or all of the scroll delta 18382 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18383 */ 18384 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18385 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18386 if (dx != 0 || dy != 0) { 18387 int startX = 0; 18388 int startY = 0; 18389 if (offsetInWindow != null) { 18390 getLocationInWindow(offsetInWindow); 18391 startX = offsetInWindow[0]; 18392 startY = offsetInWindow[1]; 18393 } 18394 18395 if (consumed == null) { 18396 if (mTempNestedScrollConsumed == null) { 18397 mTempNestedScrollConsumed = new int[2]; 18398 } 18399 consumed = mTempNestedScrollConsumed; 18400 } 18401 consumed[0] = 0; 18402 consumed[1] = 0; 18403 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18404 18405 if (offsetInWindow != null) { 18406 getLocationInWindow(offsetInWindow); 18407 offsetInWindow[0] -= startX; 18408 offsetInWindow[1] -= startY; 18409 } 18410 return consumed[0] != 0 || consumed[1] != 0; 18411 } else if (offsetInWindow != null) { 18412 offsetInWindow[0] = 0; 18413 offsetInWindow[1] = 0; 18414 } 18415 } 18416 return false; 18417 } 18418 18419 /** 18420 * Dispatch a fling to a nested scrolling parent. 18421 * 18422 * <p>This method should be used to indicate that a nested scrolling child has detected 18423 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18424 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18425 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18426 * along a scrollable axis.</p> 18427 * 18428 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18429 * its own content, it can use this method to delegate the fling to its nested scrolling 18430 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18431 * 18432 * @param velocityX Horizontal fling velocity in pixels per second 18433 * @param velocityY Vertical fling velocity in pixels per second 18434 * @param consumed true if the child consumed the fling, false otherwise 18435 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18436 */ 18437 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18438 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18439 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18440 } 18441 return false; 18442 } 18443 18444 /** 18445 * Gets a scale factor that determines the distance the view should scroll 18446 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18447 * @return The vertical scroll scale factor. 18448 * @hide 18449 */ 18450 protected float getVerticalScrollFactor() { 18451 if (mVerticalScrollFactor == 0) { 18452 TypedValue outValue = new TypedValue(); 18453 if (!mContext.getTheme().resolveAttribute( 18454 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18455 throw new IllegalStateException( 18456 "Expected theme to define listPreferredItemHeight."); 18457 } 18458 mVerticalScrollFactor = outValue.getDimension( 18459 mContext.getResources().getDisplayMetrics()); 18460 } 18461 return mVerticalScrollFactor; 18462 } 18463 18464 /** 18465 * Gets a scale factor that determines the distance the view should scroll 18466 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18467 * @return The horizontal scroll scale factor. 18468 * @hide 18469 */ 18470 protected float getHorizontalScrollFactor() { 18471 // TODO: Should use something else. 18472 return getVerticalScrollFactor(); 18473 } 18474 18475 /** 18476 * Return the value specifying the text direction or policy that was set with 18477 * {@link #setTextDirection(int)}. 18478 * 18479 * @return the defined text direction. It can be one of: 18480 * 18481 * {@link #TEXT_DIRECTION_INHERIT}, 18482 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18483 * {@link #TEXT_DIRECTION_ANY_RTL}, 18484 * {@link #TEXT_DIRECTION_LTR}, 18485 * {@link #TEXT_DIRECTION_RTL}, 18486 * {@link #TEXT_DIRECTION_LOCALE} 18487 * 18488 * @attr ref android.R.styleable#View_textDirection 18489 * 18490 * @hide 18491 */ 18492 @ViewDebug.ExportedProperty(category = "text", mapping = { 18493 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18494 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18495 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18496 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18497 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18498 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18499 }) 18500 public int getRawTextDirection() { 18501 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18502 } 18503 18504 /** 18505 * Set the text direction. 18506 * 18507 * @param textDirection the direction to set. Should be one of: 18508 * 18509 * {@link #TEXT_DIRECTION_INHERIT}, 18510 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18511 * {@link #TEXT_DIRECTION_ANY_RTL}, 18512 * {@link #TEXT_DIRECTION_LTR}, 18513 * {@link #TEXT_DIRECTION_RTL}, 18514 * {@link #TEXT_DIRECTION_LOCALE} 18515 * 18516 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18517 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18518 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18519 * 18520 * @attr ref android.R.styleable#View_textDirection 18521 */ 18522 public void setTextDirection(int textDirection) { 18523 if (getRawTextDirection() != textDirection) { 18524 // Reset the current text direction and the resolved one 18525 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18526 resetResolvedTextDirection(); 18527 // Set the new text direction 18528 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18529 // Do resolution 18530 resolveTextDirection(); 18531 // Notify change 18532 onRtlPropertiesChanged(getLayoutDirection()); 18533 // Refresh 18534 requestLayout(); 18535 invalidate(true); 18536 } 18537 } 18538 18539 /** 18540 * Return the resolved text direction. 18541 * 18542 * @return the resolved text direction. Returns one of: 18543 * 18544 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18545 * {@link #TEXT_DIRECTION_ANY_RTL}, 18546 * {@link #TEXT_DIRECTION_LTR}, 18547 * {@link #TEXT_DIRECTION_RTL}, 18548 * {@link #TEXT_DIRECTION_LOCALE} 18549 * 18550 * @attr ref android.R.styleable#View_textDirection 18551 */ 18552 @ViewDebug.ExportedProperty(category = "text", mapping = { 18553 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18554 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18555 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18556 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18557 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18558 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18559 }) 18560 public int getTextDirection() { 18561 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18562 } 18563 18564 /** 18565 * Resolve the text direction. 18566 * 18567 * @return true if resolution has been done, false otherwise. 18568 * 18569 * @hide 18570 */ 18571 public boolean resolveTextDirection() { 18572 // Reset any previous text direction resolution 18573 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18574 18575 if (hasRtlSupport()) { 18576 // Set resolved text direction flag depending on text direction flag 18577 final int textDirection = getRawTextDirection(); 18578 switch(textDirection) { 18579 case TEXT_DIRECTION_INHERIT: 18580 if (!canResolveTextDirection()) { 18581 // We cannot do the resolution if there is no parent, so use the default one 18582 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18583 // Resolution will need to happen again later 18584 return false; 18585 } 18586 18587 // Parent has not yet resolved, so we still return the default 18588 try { 18589 if (!mParent.isTextDirectionResolved()) { 18590 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18591 // Resolution will need to happen again later 18592 return false; 18593 } 18594 } catch (AbstractMethodError e) { 18595 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18596 " does not fully implement ViewParent", e); 18597 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18598 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18599 return true; 18600 } 18601 18602 // Set current resolved direction to the same value as the parent's one 18603 int parentResolvedDirection; 18604 try { 18605 parentResolvedDirection = mParent.getTextDirection(); 18606 } catch (AbstractMethodError e) { 18607 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18608 " does not fully implement ViewParent", e); 18609 parentResolvedDirection = TEXT_DIRECTION_LTR; 18610 } 18611 switch (parentResolvedDirection) { 18612 case TEXT_DIRECTION_FIRST_STRONG: 18613 case TEXT_DIRECTION_ANY_RTL: 18614 case TEXT_DIRECTION_LTR: 18615 case TEXT_DIRECTION_RTL: 18616 case TEXT_DIRECTION_LOCALE: 18617 mPrivateFlags2 |= 18618 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18619 break; 18620 default: 18621 // Default resolved direction is "first strong" heuristic 18622 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18623 } 18624 break; 18625 case TEXT_DIRECTION_FIRST_STRONG: 18626 case TEXT_DIRECTION_ANY_RTL: 18627 case TEXT_DIRECTION_LTR: 18628 case TEXT_DIRECTION_RTL: 18629 case TEXT_DIRECTION_LOCALE: 18630 // Resolved direction is the same as text direction 18631 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18632 break; 18633 default: 18634 // Default resolved direction is "first strong" heuristic 18635 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18636 } 18637 } else { 18638 // Default resolved direction is "first strong" heuristic 18639 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18640 } 18641 18642 // Set to resolved 18643 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18644 return true; 18645 } 18646 18647 /** 18648 * Check if text direction resolution can be done. 18649 * 18650 * @return true if text direction resolution can be done otherwise return false. 18651 */ 18652 public boolean canResolveTextDirection() { 18653 switch (getRawTextDirection()) { 18654 case TEXT_DIRECTION_INHERIT: 18655 if (mParent != null) { 18656 try { 18657 return mParent.canResolveTextDirection(); 18658 } catch (AbstractMethodError e) { 18659 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18660 " does not fully implement ViewParent", e); 18661 } 18662 } 18663 return false; 18664 18665 default: 18666 return true; 18667 } 18668 } 18669 18670 /** 18671 * Reset resolved text direction. Text direction will be resolved during a call to 18672 * {@link #onMeasure(int, int)}. 18673 * 18674 * @hide 18675 */ 18676 public void resetResolvedTextDirection() { 18677 // Reset any previous text direction resolution 18678 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18679 // Set to default value 18680 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18681 } 18682 18683 /** 18684 * @return true if text direction is inherited. 18685 * 18686 * @hide 18687 */ 18688 public boolean isTextDirectionInherited() { 18689 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18690 } 18691 18692 /** 18693 * @return true if text direction is resolved. 18694 */ 18695 public boolean isTextDirectionResolved() { 18696 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18697 } 18698 18699 /** 18700 * Return the value specifying the text alignment or policy that was set with 18701 * {@link #setTextAlignment(int)}. 18702 * 18703 * @return the defined text alignment. It can be one of: 18704 * 18705 * {@link #TEXT_ALIGNMENT_INHERIT}, 18706 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18707 * {@link #TEXT_ALIGNMENT_CENTER}, 18708 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18709 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18710 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18711 * {@link #TEXT_ALIGNMENT_VIEW_END} 18712 * 18713 * @attr ref android.R.styleable#View_textAlignment 18714 * 18715 * @hide 18716 */ 18717 @ViewDebug.ExportedProperty(category = "text", mapping = { 18718 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18719 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18720 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18721 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18722 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18723 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18724 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18725 }) 18726 @TextAlignment 18727 public int getRawTextAlignment() { 18728 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18729 } 18730 18731 /** 18732 * Set the text alignment. 18733 * 18734 * @param textAlignment The text alignment to set. Should be one of 18735 * 18736 * {@link #TEXT_ALIGNMENT_INHERIT}, 18737 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18738 * {@link #TEXT_ALIGNMENT_CENTER}, 18739 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18740 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18741 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18742 * {@link #TEXT_ALIGNMENT_VIEW_END} 18743 * 18744 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18745 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18746 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18747 * 18748 * @attr ref android.R.styleable#View_textAlignment 18749 */ 18750 public void setTextAlignment(@TextAlignment int textAlignment) { 18751 if (textAlignment != getRawTextAlignment()) { 18752 // Reset the current and resolved text alignment 18753 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18754 resetResolvedTextAlignment(); 18755 // Set the new text alignment 18756 mPrivateFlags2 |= 18757 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18758 // Do resolution 18759 resolveTextAlignment(); 18760 // Notify change 18761 onRtlPropertiesChanged(getLayoutDirection()); 18762 // Refresh 18763 requestLayout(); 18764 invalidate(true); 18765 } 18766 } 18767 18768 /** 18769 * Return the resolved text alignment. 18770 * 18771 * @return the resolved text alignment. Returns one of: 18772 * 18773 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18774 * {@link #TEXT_ALIGNMENT_CENTER}, 18775 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18776 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18777 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18778 * {@link #TEXT_ALIGNMENT_VIEW_END} 18779 * 18780 * @attr ref android.R.styleable#View_textAlignment 18781 */ 18782 @ViewDebug.ExportedProperty(category = "text", mapping = { 18783 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18784 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18785 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18786 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18787 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18788 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18789 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18790 }) 18791 @TextAlignment 18792 public int getTextAlignment() { 18793 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18794 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18795 } 18796 18797 /** 18798 * Resolve the text alignment. 18799 * 18800 * @return true if resolution has been done, false otherwise. 18801 * 18802 * @hide 18803 */ 18804 public boolean resolveTextAlignment() { 18805 // Reset any previous text alignment resolution 18806 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18807 18808 if (hasRtlSupport()) { 18809 // Set resolved text alignment flag depending on text alignment flag 18810 final int textAlignment = getRawTextAlignment(); 18811 switch (textAlignment) { 18812 case TEXT_ALIGNMENT_INHERIT: 18813 // Check if we can resolve the text alignment 18814 if (!canResolveTextAlignment()) { 18815 // We cannot do the resolution if there is no parent so use the default 18816 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18817 // Resolution will need to happen again later 18818 return false; 18819 } 18820 18821 // Parent has not yet resolved, so we still return the default 18822 try { 18823 if (!mParent.isTextAlignmentResolved()) { 18824 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18825 // Resolution will need to happen again later 18826 return false; 18827 } 18828 } catch (AbstractMethodError e) { 18829 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18830 " does not fully implement ViewParent", e); 18831 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18832 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18833 return true; 18834 } 18835 18836 int parentResolvedTextAlignment; 18837 try { 18838 parentResolvedTextAlignment = mParent.getTextAlignment(); 18839 } catch (AbstractMethodError e) { 18840 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18841 " does not fully implement ViewParent", e); 18842 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18843 } 18844 switch (parentResolvedTextAlignment) { 18845 case TEXT_ALIGNMENT_GRAVITY: 18846 case TEXT_ALIGNMENT_TEXT_START: 18847 case TEXT_ALIGNMENT_TEXT_END: 18848 case TEXT_ALIGNMENT_CENTER: 18849 case TEXT_ALIGNMENT_VIEW_START: 18850 case TEXT_ALIGNMENT_VIEW_END: 18851 // Resolved text alignment is the same as the parent resolved 18852 // text alignment 18853 mPrivateFlags2 |= 18854 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18855 break; 18856 default: 18857 // Use default resolved text alignment 18858 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18859 } 18860 break; 18861 case TEXT_ALIGNMENT_GRAVITY: 18862 case TEXT_ALIGNMENT_TEXT_START: 18863 case TEXT_ALIGNMENT_TEXT_END: 18864 case TEXT_ALIGNMENT_CENTER: 18865 case TEXT_ALIGNMENT_VIEW_START: 18866 case TEXT_ALIGNMENT_VIEW_END: 18867 // Resolved text alignment is the same as text alignment 18868 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18869 break; 18870 default: 18871 // Use default resolved text alignment 18872 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18873 } 18874 } else { 18875 // Use default resolved text alignment 18876 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18877 } 18878 18879 // Set the resolved 18880 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18881 return true; 18882 } 18883 18884 /** 18885 * Check if text alignment resolution can be done. 18886 * 18887 * @return true if text alignment resolution can be done otherwise return false. 18888 */ 18889 public boolean canResolveTextAlignment() { 18890 switch (getRawTextAlignment()) { 18891 case TEXT_DIRECTION_INHERIT: 18892 if (mParent != null) { 18893 try { 18894 return mParent.canResolveTextAlignment(); 18895 } catch (AbstractMethodError e) { 18896 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18897 " does not fully implement ViewParent", e); 18898 } 18899 } 18900 return false; 18901 18902 default: 18903 return true; 18904 } 18905 } 18906 18907 /** 18908 * Reset resolved text alignment. Text alignment will be resolved during a call to 18909 * {@link #onMeasure(int, int)}. 18910 * 18911 * @hide 18912 */ 18913 public void resetResolvedTextAlignment() { 18914 // Reset any previous text alignment resolution 18915 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18916 // Set to default 18917 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18918 } 18919 18920 /** 18921 * @return true if text alignment is inherited. 18922 * 18923 * @hide 18924 */ 18925 public boolean isTextAlignmentInherited() { 18926 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18927 } 18928 18929 /** 18930 * @return true if text alignment is resolved. 18931 */ 18932 public boolean isTextAlignmentResolved() { 18933 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18934 } 18935 18936 /** 18937 * Generate a value suitable for use in {@link #setId(int)}. 18938 * This value will not collide with ID values generated at build time by aapt for R.id. 18939 * 18940 * @return a generated ID value 18941 */ 18942 public static int generateViewId() { 18943 for (;;) { 18944 final int result = sNextGeneratedId.get(); 18945 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18946 int newValue = result + 1; 18947 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18948 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18949 return result; 18950 } 18951 } 18952 } 18953 18954 /** 18955 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 18956 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 18957 * a normal View or a ViewGroup with 18958 * {@link android.view.ViewGroup#isTransitionGroup()} true. 18959 * @hide 18960 */ 18961 public void captureTransitioningViews(List<View> transitioningViews) { 18962 if (getVisibility() == View.VISIBLE) { 18963 transitioningViews.add(this); 18964 } 18965 } 18966 18967 /** 18968 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 18969 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 18970 * @hide 18971 */ 18972 public void findNamedViews(Map<String, View> namedElements) { 18973 if (getVisibility() == VISIBLE) { 18974 String transitionName = getTransitionName(); 18975 if (transitionName != null) { 18976 namedElements.put(transitionName, this); 18977 } 18978 } 18979 } 18980 18981 // 18982 // Properties 18983 // 18984 /** 18985 * A Property wrapper around the <code>alpha</code> functionality handled by the 18986 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18987 */ 18988 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18989 @Override 18990 public void setValue(View object, float value) { 18991 object.setAlpha(value); 18992 } 18993 18994 @Override 18995 public Float get(View object) { 18996 return object.getAlpha(); 18997 } 18998 }; 18999 19000 /** 19001 * A Property wrapper around the <code>translationX</code> functionality handled by the 19002 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 19003 */ 19004 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 19005 @Override 19006 public void setValue(View object, float value) { 19007 object.setTranslationX(value); 19008 } 19009 19010 @Override 19011 public Float get(View object) { 19012 return object.getTranslationX(); 19013 } 19014 }; 19015 19016 /** 19017 * A Property wrapper around the <code>translationY</code> functionality handled by the 19018 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 19019 */ 19020 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 19021 @Override 19022 public void setValue(View object, float value) { 19023 object.setTranslationY(value); 19024 } 19025 19026 @Override 19027 public Float get(View object) { 19028 return object.getTranslationY(); 19029 } 19030 }; 19031 19032 /** 19033 * A Property wrapper around the <code>translationZ</code> functionality handled by the 19034 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 19035 */ 19036 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 19037 @Override 19038 public void setValue(View object, float value) { 19039 object.setTranslationZ(value); 19040 } 19041 19042 @Override 19043 public Float get(View object) { 19044 return object.getTranslationZ(); 19045 } 19046 }; 19047 19048 /** 19049 * A Property wrapper around the <code>x</code> functionality handled by the 19050 * {@link View#setX(float)} and {@link View#getX()} methods. 19051 */ 19052 public static final Property<View, Float> X = new FloatProperty<View>("x") { 19053 @Override 19054 public void setValue(View object, float value) { 19055 object.setX(value); 19056 } 19057 19058 @Override 19059 public Float get(View object) { 19060 return object.getX(); 19061 } 19062 }; 19063 19064 /** 19065 * A Property wrapper around the <code>y</code> functionality handled by the 19066 * {@link View#setY(float)} and {@link View#getY()} methods. 19067 */ 19068 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 19069 @Override 19070 public void setValue(View object, float value) { 19071 object.setY(value); 19072 } 19073 19074 @Override 19075 public Float get(View object) { 19076 return object.getY(); 19077 } 19078 }; 19079 19080 /** 19081 * A Property wrapper around the <code>z</code> functionality handled by the 19082 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19083 */ 19084 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19085 @Override 19086 public void setValue(View object, float value) { 19087 object.setZ(value); 19088 } 19089 19090 @Override 19091 public Float get(View object) { 19092 return object.getZ(); 19093 } 19094 }; 19095 19096 /** 19097 * A Property wrapper around the <code>rotation</code> functionality handled by the 19098 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19099 */ 19100 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19101 @Override 19102 public void setValue(View object, float value) { 19103 object.setRotation(value); 19104 } 19105 19106 @Override 19107 public Float get(View object) { 19108 return object.getRotation(); 19109 } 19110 }; 19111 19112 /** 19113 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19114 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19115 */ 19116 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19117 @Override 19118 public void setValue(View object, float value) { 19119 object.setRotationX(value); 19120 } 19121 19122 @Override 19123 public Float get(View object) { 19124 return object.getRotationX(); 19125 } 19126 }; 19127 19128 /** 19129 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19130 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19131 */ 19132 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19133 @Override 19134 public void setValue(View object, float value) { 19135 object.setRotationY(value); 19136 } 19137 19138 @Override 19139 public Float get(View object) { 19140 return object.getRotationY(); 19141 } 19142 }; 19143 19144 /** 19145 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19146 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19147 */ 19148 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19149 @Override 19150 public void setValue(View object, float value) { 19151 object.setScaleX(value); 19152 } 19153 19154 @Override 19155 public Float get(View object) { 19156 return object.getScaleX(); 19157 } 19158 }; 19159 19160 /** 19161 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19162 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19163 */ 19164 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19165 @Override 19166 public void setValue(View object, float value) { 19167 object.setScaleY(value); 19168 } 19169 19170 @Override 19171 public Float get(View object) { 19172 return object.getScaleY(); 19173 } 19174 }; 19175 19176 /** 19177 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19178 * Each MeasureSpec represents a requirement for either the width or the height. 19179 * A MeasureSpec is comprised of a size and a mode. There are three possible 19180 * modes: 19181 * <dl> 19182 * <dt>UNSPECIFIED</dt> 19183 * <dd> 19184 * The parent has not imposed any constraint on the child. It can be whatever size 19185 * it wants. 19186 * </dd> 19187 * 19188 * <dt>EXACTLY</dt> 19189 * <dd> 19190 * The parent has determined an exact size for the child. The child is going to be 19191 * given those bounds regardless of how big it wants to be. 19192 * </dd> 19193 * 19194 * <dt>AT_MOST</dt> 19195 * <dd> 19196 * The child can be as large as it wants up to the specified size. 19197 * </dd> 19198 * </dl> 19199 * 19200 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19201 * is provided to pack and unpack the <size, mode> tuple into the int. 19202 */ 19203 public static class MeasureSpec { 19204 private static final int MODE_SHIFT = 30; 19205 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19206 19207 /** 19208 * Measure specification mode: The parent has not imposed any constraint 19209 * on the child. It can be whatever size it wants. 19210 */ 19211 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19212 19213 /** 19214 * Measure specification mode: The parent has determined an exact size 19215 * for the child. The child is going to be given those bounds regardless 19216 * of how big it wants to be. 19217 */ 19218 public static final int EXACTLY = 1 << MODE_SHIFT; 19219 19220 /** 19221 * Measure specification mode: The child can be as large as it wants up 19222 * to the specified size. 19223 */ 19224 public static final int AT_MOST = 2 << MODE_SHIFT; 19225 19226 /** 19227 * Creates a measure specification based on the supplied size and mode. 19228 * 19229 * The mode must always be one of the following: 19230 * <ul> 19231 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19232 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19233 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19234 * </ul> 19235 * 19236 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19237 * implementation was such that the order of arguments did not matter 19238 * and overflow in either value could impact the resulting MeasureSpec. 19239 * {@link android.widget.RelativeLayout} was affected by this bug. 19240 * Apps targeting API levels greater than 17 will get the fixed, more strict 19241 * behavior.</p> 19242 * 19243 * @param size the size of the measure specification 19244 * @param mode the mode of the measure specification 19245 * @return the measure specification based on size and mode 19246 */ 19247 public static int makeMeasureSpec(int size, int mode) { 19248 if (sUseBrokenMakeMeasureSpec) { 19249 return size + mode; 19250 } else { 19251 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19252 } 19253 } 19254 19255 /** 19256 * Extracts the mode from the supplied measure specification. 19257 * 19258 * @param measureSpec the measure specification to extract the mode from 19259 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19260 * {@link android.view.View.MeasureSpec#AT_MOST} or 19261 * {@link android.view.View.MeasureSpec#EXACTLY} 19262 */ 19263 public static int getMode(int measureSpec) { 19264 return (measureSpec & MODE_MASK); 19265 } 19266 19267 /** 19268 * Extracts the size from the supplied measure specification. 19269 * 19270 * @param measureSpec the measure specification to extract the size from 19271 * @return the size in pixels defined in the supplied measure specification 19272 */ 19273 public static int getSize(int measureSpec) { 19274 return (measureSpec & ~MODE_MASK); 19275 } 19276 19277 static int adjust(int measureSpec, int delta) { 19278 final int mode = getMode(measureSpec); 19279 if (mode == UNSPECIFIED) { 19280 // No need to adjust size for UNSPECIFIED mode. 19281 return makeMeasureSpec(0, UNSPECIFIED); 19282 } 19283 int size = getSize(measureSpec) + delta; 19284 if (size < 0) { 19285 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19286 ") spec: " + toString(measureSpec) + " delta: " + delta); 19287 size = 0; 19288 } 19289 return makeMeasureSpec(size, mode); 19290 } 19291 19292 /** 19293 * Returns a String representation of the specified measure 19294 * specification. 19295 * 19296 * @param measureSpec the measure specification to convert to a String 19297 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19298 */ 19299 public static String toString(int measureSpec) { 19300 int mode = getMode(measureSpec); 19301 int size = getSize(measureSpec); 19302 19303 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19304 19305 if (mode == UNSPECIFIED) 19306 sb.append("UNSPECIFIED "); 19307 else if (mode == EXACTLY) 19308 sb.append("EXACTLY "); 19309 else if (mode == AT_MOST) 19310 sb.append("AT_MOST "); 19311 else 19312 sb.append(mode).append(" "); 19313 19314 sb.append(size); 19315 return sb.toString(); 19316 } 19317 } 19318 19319 private final class CheckForLongPress implements Runnable { 19320 private int mOriginalWindowAttachCount; 19321 19322 @Override 19323 public void run() { 19324 if (isPressed() && (mParent != null) 19325 && mOriginalWindowAttachCount == mWindowAttachCount) { 19326 if (performLongClick()) { 19327 mHasPerformedLongPress = true; 19328 } 19329 } 19330 } 19331 19332 public void rememberWindowAttachCount() { 19333 mOriginalWindowAttachCount = mWindowAttachCount; 19334 } 19335 } 19336 19337 private final class CheckForTap implements Runnable { 19338 public float x; 19339 public float y; 19340 19341 @Override 19342 public void run() { 19343 mPrivateFlags &= ~PFLAG_PREPRESSED; 19344 setPressed(true, x, y); 19345 checkForLongClick(ViewConfiguration.getTapTimeout()); 19346 } 19347 } 19348 19349 private final class PerformClick implements Runnable { 19350 @Override 19351 public void run() { 19352 performClick(); 19353 } 19354 } 19355 19356 /** @hide */ 19357 public void hackTurnOffWindowResizeAnim(boolean off) { 19358 mAttachInfo.mTurnOffWindowResizeAnim = off; 19359 } 19360 19361 /** 19362 * This method returns a ViewPropertyAnimator object, which can be used to animate 19363 * specific properties on this View. 19364 * 19365 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19366 */ 19367 public ViewPropertyAnimator animate() { 19368 if (mAnimator == null) { 19369 mAnimator = new ViewPropertyAnimator(this); 19370 } 19371 return mAnimator; 19372 } 19373 19374 /** 19375 * Sets the name of the View to be used to identify Views in Transitions. 19376 * Names should be unique in the View hierarchy. 19377 * 19378 * @param transitionName The name of the View to uniquely identify it for Transitions. 19379 */ 19380 public final void setTransitionName(String transitionName) { 19381 mTransitionName = transitionName; 19382 } 19383 19384 /** 19385 * To be removed before L release. 19386 * @hide 19387 */ 19388 public final void setViewName(String transitionName) { 19389 setTransitionName(transitionName); 19390 } 19391 19392 /** 19393 * Returns the name of the View to be used to identify Views in Transitions. 19394 * Names should be unique in the View hierarchy. 19395 * 19396 * <p>This returns null if the View has not been given a name.</p> 19397 * 19398 * @return The name used of the View to be used to identify Views in Transitions or null 19399 * if no name has been given. 19400 */ 19401 public String getTransitionName() { 19402 return mTransitionName; 19403 } 19404 19405 /** 19406 * To be removed before L release. 19407 * @hide 19408 */ 19409 public String getViewName() { return getTransitionName(); } 19410 19411 /** 19412 * Interface definition for a callback to be invoked when a hardware key event is 19413 * dispatched to this view. The callback will be invoked before the key event is 19414 * given to the view. This is only useful for hardware keyboards; a software input 19415 * method has no obligation to trigger this listener. 19416 */ 19417 public interface OnKeyListener { 19418 /** 19419 * Called when a hardware key is dispatched to a view. This allows listeners to 19420 * get a chance to respond before the target view. 19421 * <p>Key presses in software keyboards will generally NOT trigger this method, 19422 * although some may elect to do so in some situations. Do not assume a 19423 * software input method has to be key-based; even if it is, it may use key presses 19424 * in a different way than you expect, so there is no way to reliably catch soft 19425 * input key presses. 19426 * 19427 * @param v The view the key has been dispatched to. 19428 * @param keyCode The code for the physical key that was pressed 19429 * @param event The KeyEvent object containing full information about 19430 * the event. 19431 * @return True if the listener has consumed the event, false otherwise. 19432 */ 19433 boolean onKey(View v, int keyCode, KeyEvent event); 19434 } 19435 19436 /** 19437 * Interface definition for a callback to be invoked when a touch event is 19438 * dispatched to this view. The callback will be invoked before the touch 19439 * event is given to the view. 19440 */ 19441 public interface OnTouchListener { 19442 /** 19443 * Called when a touch event is dispatched to a view. This allows listeners to 19444 * get a chance to respond before the target view. 19445 * 19446 * @param v The view the touch event has been dispatched to. 19447 * @param event The MotionEvent object containing full information about 19448 * the event. 19449 * @return True if the listener has consumed the event, false otherwise. 19450 */ 19451 boolean onTouch(View v, MotionEvent event); 19452 } 19453 19454 /** 19455 * Interface definition for a callback to be invoked when a hover event is 19456 * dispatched to this view. The callback will be invoked before the hover 19457 * event is given to the view. 19458 */ 19459 public interface OnHoverListener { 19460 /** 19461 * Called when a hover event is dispatched to a view. This allows listeners to 19462 * get a chance to respond before the target view. 19463 * 19464 * @param v The view the hover event has been dispatched to. 19465 * @param event The MotionEvent object containing full information about 19466 * the event. 19467 * @return True if the listener has consumed the event, false otherwise. 19468 */ 19469 boolean onHover(View v, MotionEvent event); 19470 } 19471 19472 /** 19473 * Interface definition for a callback to be invoked when a generic motion event is 19474 * dispatched to this view. The callback will be invoked before the generic motion 19475 * event is given to the view. 19476 */ 19477 public interface OnGenericMotionListener { 19478 /** 19479 * Called when a generic motion event is dispatched to a view. This allows listeners to 19480 * get a chance to respond before the target view. 19481 * 19482 * @param v The view the generic motion event has been dispatched to. 19483 * @param event The MotionEvent object containing full information about 19484 * the event. 19485 * @return True if the listener has consumed the event, false otherwise. 19486 */ 19487 boolean onGenericMotion(View v, MotionEvent event); 19488 } 19489 19490 /** 19491 * Interface definition for a callback to be invoked when a view has been clicked and held. 19492 */ 19493 public interface OnLongClickListener { 19494 /** 19495 * Called when a view has been clicked and held. 19496 * 19497 * @param v The view that was clicked and held. 19498 * 19499 * @return true if the callback consumed the long click, false otherwise. 19500 */ 19501 boolean onLongClick(View v); 19502 } 19503 19504 /** 19505 * Interface definition for a callback to be invoked when a drag is being dispatched 19506 * to this view. The callback will be invoked before the hosting view's own 19507 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19508 * onDrag(event) behavior, it should return 'false' from this callback. 19509 * 19510 * <div class="special reference"> 19511 * <h3>Developer Guides</h3> 19512 * <p>For a guide to implementing drag and drop features, read the 19513 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19514 * </div> 19515 */ 19516 public interface OnDragListener { 19517 /** 19518 * Called when a drag event is dispatched to a view. This allows listeners 19519 * to get a chance to override base View behavior. 19520 * 19521 * @param v The View that received the drag event. 19522 * @param event The {@link android.view.DragEvent} object for the drag event. 19523 * @return {@code true} if the drag event was handled successfully, or {@code false} 19524 * if the drag event was not handled. Note that {@code false} will trigger the View 19525 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19526 */ 19527 boolean onDrag(View v, DragEvent event); 19528 } 19529 19530 /** 19531 * Interface definition for a callback to be invoked when the focus state of 19532 * a view changed. 19533 */ 19534 public interface OnFocusChangeListener { 19535 /** 19536 * Called when the focus state of a view has changed. 19537 * 19538 * @param v The view whose state has changed. 19539 * @param hasFocus The new focus state of v. 19540 */ 19541 void onFocusChange(View v, boolean hasFocus); 19542 } 19543 19544 /** 19545 * Interface definition for a callback to be invoked when a view is clicked. 19546 */ 19547 public interface OnClickListener { 19548 /** 19549 * Called when a view has been clicked. 19550 * 19551 * @param v The view that was clicked. 19552 */ 19553 void onClick(View v); 19554 } 19555 19556 /** 19557 * Interface definition for a callback to be invoked when the context menu 19558 * for this view is being built. 19559 */ 19560 public interface OnCreateContextMenuListener { 19561 /** 19562 * Called when the context menu for this view is being built. It is not 19563 * safe to hold onto the menu after this method returns. 19564 * 19565 * @param menu The context menu that is being built 19566 * @param v The view for which the context menu is being built 19567 * @param menuInfo Extra information about the item for which the 19568 * context menu should be shown. This information will vary 19569 * depending on the class of v. 19570 */ 19571 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19572 } 19573 19574 /** 19575 * Interface definition for a callback to be invoked when the status bar changes 19576 * visibility. This reports <strong>global</strong> changes to the system UI 19577 * state, not what the application is requesting. 19578 * 19579 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19580 */ 19581 public interface OnSystemUiVisibilityChangeListener { 19582 /** 19583 * Called when the status bar changes visibility because of a call to 19584 * {@link View#setSystemUiVisibility(int)}. 19585 * 19586 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19587 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19588 * This tells you the <strong>global</strong> state of these UI visibility 19589 * flags, not what your app is currently applying. 19590 */ 19591 public void onSystemUiVisibilityChange(int visibility); 19592 } 19593 19594 /** 19595 * Interface definition for a callback to be invoked when this view is attached 19596 * or detached from its window. 19597 */ 19598 public interface OnAttachStateChangeListener { 19599 /** 19600 * Called when the view is attached to a window. 19601 * @param v The view that was attached 19602 */ 19603 public void onViewAttachedToWindow(View v); 19604 /** 19605 * Called when the view is detached from a window. 19606 * @param v The view that was detached 19607 */ 19608 public void onViewDetachedFromWindow(View v); 19609 } 19610 19611 /** 19612 * Listener for applying window insets on a view in a custom way. 19613 * 19614 * <p>Apps may choose to implement this interface if they want to apply custom policy 19615 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19616 * is set, its 19617 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19618 * method will be called instead of the View's own 19619 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19620 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19621 * the View's normal behavior as part of its own.</p> 19622 */ 19623 public interface OnApplyWindowInsetsListener { 19624 /** 19625 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19626 * on a View, this listener method will be called instead of the view's own 19627 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19628 * 19629 * @param v The view applying window insets 19630 * @param insets The insets to apply 19631 * @return The insets supplied, minus any insets that were consumed 19632 */ 19633 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19634 } 19635 19636 private final class UnsetPressedState implements Runnable { 19637 @Override 19638 public void run() { 19639 setPressed(false); 19640 } 19641 } 19642 19643 /** 19644 * Base class for derived classes that want to save and restore their own 19645 * state in {@link android.view.View#onSaveInstanceState()}. 19646 */ 19647 public static class BaseSavedState extends AbsSavedState { 19648 /** 19649 * Constructor used when reading from a parcel. Reads the state of the superclass. 19650 * 19651 * @param source 19652 */ 19653 public BaseSavedState(Parcel source) { 19654 super(source); 19655 } 19656 19657 /** 19658 * Constructor called by derived classes when creating their SavedState objects 19659 * 19660 * @param superState The state of the superclass of this view 19661 */ 19662 public BaseSavedState(Parcelable superState) { 19663 super(superState); 19664 } 19665 19666 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19667 new Parcelable.Creator<BaseSavedState>() { 19668 public BaseSavedState createFromParcel(Parcel in) { 19669 return new BaseSavedState(in); 19670 } 19671 19672 public BaseSavedState[] newArray(int size) { 19673 return new BaseSavedState[size]; 19674 } 19675 }; 19676 } 19677 19678 /** 19679 * A set of information given to a view when it is attached to its parent 19680 * window. 19681 */ 19682 final static class AttachInfo { 19683 interface Callbacks { 19684 void playSoundEffect(int effectId); 19685 boolean performHapticFeedback(int effectId, boolean always); 19686 } 19687 19688 /** 19689 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19690 * to a Handler. This class contains the target (View) to invalidate and 19691 * the coordinates of the dirty rectangle. 19692 * 19693 * For performance purposes, this class also implements a pool of up to 19694 * POOL_LIMIT objects that get reused. This reduces memory allocations 19695 * whenever possible. 19696 */ 19697 static class InvalidateInfo { 19698 private static final int POOL_LIMIT = 10; 19699 19700 private static final SynchronizedPool<InvalidateInfo> sPool = 19701 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19702 19703 View target; 19704 19705 int left; 19706 int top; 19707 int right; 19708 int bottom; 19709 19710 public static InvalidateInfo obtain() { 19711 InvalidateInfo instance = sPool.acquire(); 19712 return (instance != null) ? instance : new InvalidateInfo(); 19713 } 19714 19715 public void recycle() { 19716 target = null; 19717 sPool.release(this); 19718 } 19719 } 19720 19721 final IWindowSession mSession; 19722 19723 final IWindow mWindow; 19724 19725 final IBinder mWindowToken; 19726 19727 final Display mDisplay; 19728 19729 final Callbacks mRootCallbacks; 19730 19731 IWindowId mIWindowId; 19732 WindowId mWindowId; 19733 19734 /** 19735 * The top view of the hierarchy. 19736 */ 19737 View mRootView; 19738 19739 IBinder mPanelParentWindowToken; 19740 19741 boolean mHardwareAccelerated; 19742 boolean mHardwareAccelerationRequested; 19743 HardwareRenderer mHardwareRenderer; 19744 19745 /** 19746 * The state of the display to which the window is attached, as reported 19747 * by {@link Display#getState()}. Note that the display state constants 19748 * declared by {@link Display} do not exactly line up with the screen state 19749 * constants declared by {@link View} (there are more display states than 19750 * screen states). 19751 */ 19752 int mDisplayState = Display.STATE_UNKNOWN; 19753 19754 /** 19755 * Scale factor used by the compatibility mode 19756 */ 19757 float mApplicationScale; 19758 19759 /** 19760 * Indicates whether the application is in compatibility mode 19761 */ 19762 boolean mScalingRequired; 19763 19764 /** 19765 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19766 */ 19767 boolean mTurnOffWindowResizeAnim; 19768 19769 /** 19770 * Left position of this view's window 19771 */ 19772 int mWindowLeft; 19773 19774 /** 19775 * Top position of this view's window 19776 */ 19777 int mWindowTop; 19778 19779 /** 19780 * Indicates whether views need to use 32-bit drawing caches 19781 */ 19782 boolean mUse32BitDrawingCache; 19783 19784 /** 19785 * For windows that are full-screen but using insets to layout inside 19786 * of the screen areas, these are the current insets to appear inside 19787 * the overscan area of the display. 19788 */ 19789 final Rect mOverscanInsets = new Rect(); 19790 19791 /** 19792 * For windows that are full-screen but using insets to layout inside 19793 * of the screen decorations, these are the current insets for the 19794 * content of the window. 19795 */ 19796 final Rect mContentInsets = new Rect(); 19797 19798 /** 19799 * For windows that are full-screen but using insets to layout inside 19800 * of the screen decorations, these are the current insets for the 19801 * actual visible parts of the window. 19802 */ 19803 final Rect mVisibleInsets = new Rect(); 19804 19805 /** 19806 * For windows that are full-screen but using insets to layout inside 19807 * of the screen decorations, these are the current insets for the 19808 * stable system windows. 19809 */ 19810 final Rect mStableInsets = new Rect(); 19811 19812 /** 19813 * The internal insets given by this window. This value is 19814 * supplied by the client (through 19815 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19816 * be given to the window manager when changed to be used in laying 19817 * out windows behind it. 19818 */ 19819 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19820 = new ViewTreeObserver.InternalInsetsInfo(); 19821 19822 /** 19823 * Set to true when mGivenInternalInsets is non-empty. 19824 */ 19825 boolean mHasNonEmptyGivenInternalInsets; 19826 19827 /** 19828 * All views in the window's hierarchy that serve as scroll containers, 19829 * used to determine if the window can be resized or must be panned 19830 * to adjust for a soft input area. 19831 */ 19832 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19833 19834 final KeyEvent.DispatcherState mKeyDispatchState 19835 = new KeyEvent.DispatcherState(); 19836 19837 /** 19838 * Indicates whether the view's window currently has the focus. 19839 */ 19840 boolean mHasWindowFocus; 19841 19842 /** 19843 * The current visibility of the window. 19844 */ 19845 int mWindowVisibility; 19846 19847 /** 19848 * Indicates the time at which drawing started to occur. 19849 */ 19850 long mDrawingTime; 19851 19852 /** 19853 * Indicates whether or not ignoring the DIRTY_MASK flags. 19854 */ 19855 boolean mIgnoreDirtyState; 19856 19857 /** 19858 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19859 * to avoid clearing that flag prematurely. 19860 */ 19861 boolean mSetIgnoreDirtyState = false; 19862 19863 /** 19864 * Indicates whether the view's window is currently in touch mode. 19865 */ 19866 boolean mInTouchMode; 19867 19868 /** 19869 * Indicates whether the view has requested unbuffered input dispatching for the current 19870 * event stream. 19871 */ 19872 boolean mUnbufferedDispatchRequested; 19873 19874 /** 19875 * Indicates that ViewAncestor should trigger a global layout change 19876 * the next time it performs a traversal 19877 */ 19878 boolean mRecomputeGlobalAttributes; 19879 19880 /** 19881 * Always report new attributes at next traversal. 19882 */ 19883 boolean mForceReportNewAttributes; 19884 19885 /** 19886 * Set during a traveral if any views want to keep the screen on. 19887 */ 19888 boolean mKeepScreenOn; 19889 19890 /** 19891 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19892 */ 19893 int mSystemUiVisibility; 19894 19895 /** 19896 * Hack to force certain system UI visibility flags to be cleared. 19897 */ 19898 int mDisabledSystemUiVisibility; 19899 19900 /** 19901 * Last global system UI visibility reported by the window manager. 19902 */ 19903 int mGlobalSystemUiVisibility; 19904 19905 /** 19906 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19907 * attached. 19908 */ 19909 boolean mHasSystemUiListeners; 19910 19911 /** 19912 * Set if the window has requested to extend into the overscan region 19913 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19914 */ 19915 boolean mOverscanRequested; 19916 19917 /** 19918 * Set if the visibility of any views has changed. 19919 */ 19920 boolean mViewVisibilityChanged; 19921 19922 /** 19923 * Set to true if a view has been scrolled. 19924 */ 19925 boolean mViewScrollChanged; 19926 19927 /** 19928 * Global to the view hierarchy used as a temporary for dealing with 19929 * x/y points in the transparent region computations. 19930 */ 19931 final int[] mTransparentLocation = new int[2]; 19932 19933 /** 19934 * Global to the view hierarchy used as a temporary for dealing with 19935 * x/y points in the ViewGroup.invalidateChild implementation. 19936 */ 19937 final int[] mInvalidateChildLocation = new int[2]; 19938 19939 /** 19940 * Global to the view hierarchy used as a temporary for dealng with 19941 * computing absolute on-screen location. 19942 */ 19943 final int[] mTmpLocation = new int[2]; 19944 19945 /** 19946 * Global to the view hierarchy used as a temporary for dealing with 19947 * x/y location when view is transformed. 19948 */ 19949 final float[] mTmpTransformLocation = new float[2]; 19950 19951 /** 19952 * The view tree observer used to dispatch global events like 19953 * layout, pre-draw, touch mode change, etc. 19954 */ 19955 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19956 19957 /** 19958 * A Canvas used by the view hierarchy to perform bitmap caching. 19959 */ 19960 Canvas mCanvas; 19961 19962 /** 19963 * The view root impl. 19964 */ 19965 final ViewRootImpl mViewRootImpl; 19966 19967 /** 19968 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19969 * handler can be used to pump events in the UI events queue. 19970 */ 19971 final Handler mHandler; 19972 19973 /** 19974 * Temporary for use in computing invalidate rectangles while 19975 * calling up the hierarchy. 19976 */ 19977 final Rect mTmpInvalRect = new Rect(); 19978 19979 /** 19980 * Temporary for use in computing hit areas with transformed views 19981 */ 19982 final RectF mTmpTransformRect = new RectF(); 19983 19984 /** 19985 * Temporary for use in transforming invalidation rect 19986 */ 19987 final Matrix mTmpMatrix = new Matrix(); 19988 19989 /** 19990 * Temporary for use in transforming invalidation rect 19991 */ 19992 final Transformation mTmpTransformation = new Transformation(); 19993 19994 /** 19995 * Temporary for use in querying outlines from OutlineProviders 19996 */ 19997 final Outline mTmpOutline = new Outline(); 19998 19999 /** 20000 * Temporary list for use in collecting focusable descendents of a view. 20001 */ 20002 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 20003 20004 /** 20005 * The id of the window for accessibility purposes. 20006 */ 20007 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 20008 20009 /** 20010 * Flags related to accessibility processing. 20011 * 20012 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 20013 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 20014 */ 20015 int mAccessibilityFetchFlags; 20016 20017 /** 20018 * The drawable for highlighting accessibility focus. 20019 */ 20020 Drawable mAccessibilityFocusDrawable; 20021 20022 /** 20023 * Show where the margins, bounds and layout bounds are for each view. 20024 */ 20025 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 20026 20027 /** 20028 * Point used to compute visible regions. 20029 */ 20030 final Point mPoint = new Point(); 20031 20032 /** 20033 * Used to track which View originated a requestLayout() call, used when 20034 * requestLayout() is called during layout. 20035 */ 20036 View mViewRequestingLayout; 20037 20038 /** 20039 * Creates a new set of attachment information with the specified 20040 * events handler and thread. 20041 * 20042 * @param handler the events handler the view must use 20043 */ 20044 AttachInfo(IWindowSession session, IWindow window, Display display, 20045 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 20046 mSession = session; 20047 mWindow = window; 20048 mWindowToken = window.asBinder(); 20049 mDisplay = display; 20050 mViewRootImpl = viewRootImpl; 20051 mHandler = handler; 20052 mRootCallbacks = effectPlayer; 20053 } 20054 } 20055 20056 /** 20057 * <p>ScrollabilityCache holds various fields used by a View when scrolling 20058 * is supported. This avoids keeping too many unused fields in most 20059 * instances of View.</p> 20060 */ 20061 private static class ScrollabilityCache implements Runnable { 20062 20063 /** 20064 * Scrollbars are not visible 20065 */ 20066 public static final int OFF = 0; 20067 20068 /** 20069 * Scrollbars are visible 20070 */ 20071 public static final int ON = 1; 20072 20073 /** 20074 * Scrollbars are fading away 20075 */ 20076 public static final int FADING = 2; 20077 20078 public boolean fadeScrollBars; 20079 20080 public int fadingEdgeLength; 20081 public int scrollBarDefaultDelayBeforeFade; 20082 public int scrollBarFadeDuration; 20083 20084 public int scrollBarSize; 20085 public ScrollBarDrawable scrollBar; 20086 public float[] interpolatorValues; 20087 public View host; 20088 20089 public final Paint paint; 20090 public final Matrix matrix; 20091 public Shader shader; 20092 20093 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 20094 20095 private static final float[] OPAQUE = { 255 }; 20096 private static final float[] TRANSPARENT = { 0.0f }; 20097 20098 /** 20099 * When fading should start. This time moves into the future every time 20100 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20101 */ 20102 public long fadeStartTime; 20103 20104 20105 /** 20106 * The current state of the scrollbars: ON, OFF, or FADING 20107 */ 20108 public int state = OFF; 20109 20110 private int mLastColor; 20111 20112 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20113 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20114 scrollBarSize = configuration.getScaledScrollBarSize(); 20115 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20116 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20117 20118 paint = new Paint(); 20119 matrix = new Matrix(); 20120 // use use a height of 1, and then wack the matrix each time we 20121 // actually use it. 20122 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20123 paint.setShader(shader); 20124 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20125 20126 this.host = host; 20127 } 20128 20129 public void setFadeColor(int color) { 20130 if (color != mLastColor) { 20131 mLastColor = color; 20132 20133 if (color != 0) { 20134 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20135 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20136 paint.setShader(shader); 20137 // Restore the default transfer mode (src_over) 20138 paint.setXfermode(null); 20139 } else { 20140 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20141 paint.setShader(shader); 20142 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20143 } 20144 } 20145 } 20146 20147 public void run() { 20148 long now = AnimationUtils.currentAnimationTimeMillis(); 20149 if (now >= fadeStartTime) { 20150 20151 // the animation fades the scrollbars out by changing 20152 // the opacity (alpha) from fully opaque to fully 20153 // transparent 20154 int nextFrame = (int) now; 20155 int framesCount = 0; 20156 20157 Interpolator interpolator = scrollBarInterpolator; 20158 20159 // Start opaque 20160 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20161 20162 // End transparent 20163 nextFrame += scrollBarFadeDuration; 20164 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20165 20166 state = FADING; 20167 20168 // Kick off the fade animation 20169 host.invalidate(true); 20170 } 20171 } 20172 } 20173 20174 /** 20175 * Resuable callback for sending 20176 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20177 */ 20178 private class SendViewScrolledAccessibilityEvent implements Runnable { 20179 public volatile boolean mIsPending; 20180 20181 public void run() { 20182 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20183 mIsPending = false; 20184 } 20185 } 20186 20187 /** 20188 * <p> 20189 * This class represents a delegate that can be registered in a {@link View} 20190 * to enhance accessibility support via composition rather via inheritance. 20191 * It is specifically targeted to widget developers that extend basic View 20192 * classes i.e. classes in package android.view, that would like their 20193 * applications to be backwards compatible. 20194 * </p> 20195 * <div class="special reference"> 20196 * <h3>Developer Guides</h3> 20197 * <p>For more information about making applications accessible, read the 20198 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20199 * developer guide.</p> 20200 * </div> 20201 * <p> 20202 * A scenario in which a developer would like to use an accessibility delegate 20203 * is overriding a method introduced in a later API version then the minimal API 20204 * version supported by the application. For example, the method 20205 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20206 * in API version 4 when the accessibility APIs were first introduced. If a 20207 * developer would like his application to run on API version 4 devices (assuming 20208 * all other APIs used by the application are version 4 or lower) and take advantage 20209 * of this method, instead of overriding the method which would break the application's 20210 * backwards compatibility, he can override the corresponding method in this 20211 * delegate and register the delegate in the target View if the API version of 20212 * the system is high enough i.e. the API version is same or higher to the API 20213 * version that introduced 20214 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20215 * </p> 20216 * <p> 20217 * Here is an example implementation: 20218 * </p> 20219 * <code><pre><p> 20220 * if (Build.VERSION.SDK_INT >= 14) { 20221 * // If the API version is equal of higher than the version in 20222 * // which onInitializeAccessibilityNodeInfo was introduced we 20223 * // register a delegate with a customized implementation. 20224 * View view = findViewById(R.id.view_id); 20225 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20226 * public void onInitializeAccessibilityNodeInfo(View host, 20227 * AccessibilityNodeInfo info) { 20228 * // Let the default implementation populate the info. 20229 * super.onInitializeAccessibilityNodeInfo(host, info); 20230 * // Set some other information. 20231 * info.setEnabled(host.isEnabled()); 20232 * } 20233 * }); 20234 * } 20235 * </code></pre></p> 20236 * <p> 20237 * This delegate contains methods that correspond to the accessibility methods 20238 * in View. If a delegate has been specified the implementation in View hands 20239 * off handling to the corresponding method in this delegate. The default 20240 * implementation the delegate methods behaves exactly as the corresponding 20241 * method in View for the case of no accessibility delegate been set. Hence, 20242 * to customize the behavior of a View method, clients can override only the 20243 * corresponding delegate method without altering the behavior of the rest 20244 * accessibility related methods of the host view. 20245 * </p> 20246 */ 20247 public static class AccessibilityDelegate { 20248 20249 /** 20250 * Sends an accessibility event of the given type. If accessibility is not 20251 * enabled this method has no effect. 20252 * <p> 20253 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20254 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20255 * been set. 20256 * </p> 20257 * 20258 * @param host The View hosting the delegate. 20259 * @param eventType The type of the event to send. 20260 * 20261 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20262 */ 20263 public void sendAccessibilityEvent(View host, int eventType) { 20264 host.sendAccessibilityEventInternal(eventType); 20265 } 20266 20267 /** 20268 * Performs the specified accessibility action on the view. For 20269 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20270 * <p> 20271 * The default implementation behaves as 20272 * {@link View#performAccessibilityAction(int, Bundle) 20273 * View#performAccessibilityAction(int, Bundle)} for the case of 20274 * no accessibility delegate been set. 20275 * </p> 20276 * 20277 * @param action The action to perform. 20278 * @return Whether the action was performed. 20279 * 20280 * @see View#performAccessibilityAction(int, Bundle) 20281 * View#performAccessibilityAction(int, Bundle) 20282 */ 20283 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20284 return host.performAccessibilityActionInternal(action, args); 20285 } 20286 20287 /** 20288 * Sends an accessibility event. This method behaves exactly as 20289 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20290 * empty {@link AccessibilityEvent} and does not perform a check whether 20291 * accessibility is enabled. 20292 * <p> 20293 * The default implementation behaves as 20294 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20295 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20296 * the case of no accessibility delegate been set. 20297 * </p> 20298 * 20299 * @param host The View hosting the delegate. 20300 * @param event The event to send. 20301 * 20302 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20303 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20304 */ 20305 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20306 host.sendAccessibilityEventUncheckedInternal(event); 20307 } 20308 20309 /** 20310 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20311 * to its children for adding their text content to the event. 20312 * <p> 20313 * The default implementation behaves as 20314 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20315 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20316 * the case of no accessibility delegate been set. 20317 * </p> 20318 * 20319 * @param host The View hosting the delegate. 20320 * @param event The event. 20321 * @return True if the event population was completed. 20322 * 20323 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20324 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20325 */ 20326 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20327 return host.dispatchPopulateAccessibilityEventInternal(event); 20328 } 20329 20330 /** 20331 * Gives a chance to the host View to populate the accessibility event with its 20332 * text content. 20333 * <p> 20334 * The default implementation behaves as 20335 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20336 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20337 * the case of no accessibility delegate been set. 20338 * </p> 20339 * 20340 * @param host The View hosting the delegate. 20341 * @param event The accessibility event which to populate. 20342 * 20343 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20344 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20345 */ 20346 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20347 host.onPopulateAccessibilityEventInternal(event); 20348 } 20349 20350 /** 20351 * Initializes an {@link AccessibilityEvent} with information about the 20352 * the host View which is the event source. 20353 * <p> 20354 * The default implementation behaves as 20355 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20356 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20357 * the case of no accessibility delegate been set. 20358 * </p> 20359 * 20360 * @param host The View hosting the delegate. 20361 * @param event The event to initialize. 20362 * 20363 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20364 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20365 */ 20366 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20367 host.onInitializeAccessibilityEventInternal(event); 20368 } 20369 20370 /** 20371 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20372 * <p> 20373 * The default implementation behaves as 20374 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20375 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20376 * the case of no accessibility delegate been set. 20377 * </p> 20378 * 20379 * @param host The View hosting the delegate. 20380 * @param info The instance to initialize. 20381 * 20382 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20383 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20384 */ 20385 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20386 host.onInitializeAccessibilityNodeInfoInternal(info); 20387 } 20388 20389 /** 20390 * Called when a child of the host View has requested sending an 20391 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20392 * to augment the event. 20393 * <p> 20394 * The default implementation behaves as 20395 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20396 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20397 * the case of no accessibility delegate been set. 20398 * </p> 20399 * 20400 * @param host The View hosting the delegate. 20401 * @param child The child which requests sending the event. 20402 * @param event The event to be sent. 20403 * @return True if the event should be sent 20404 * 20405 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20406 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20407 */ 20408 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20409 AccessibilityEvent event) { 20410 return host.onRequestSendAccessibilityEventInternal(child, event); 20411 } 20412 20413 /** 20414 * Gets the provider for managing a virtual view hierarchy rooted at this View 20415 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20416 * that explore the window content. 20417 * <p> 20418 * The default implementation behaves as 20419 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20420 * the case of no accessibility delegate been set. 20421 * </p> 20422 * 20423 * @return The provider. 20424 * 20425 * @see AccessibilityNodeProvider 20426 */ 20427 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20428 return null; 20429 } 20430 20431 /** 20432 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20433 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20434 * This method is responsible for obtaining an accessibility node info from a 20435 * pool of reusable instances and calling 20436 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20437 * view to initialize the former. 20438 * <p> 20439 * <strong>Note:</strong> The client is responsible for recycling the obtained 20440 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20441 * creation. 20442 * </p> 20443 * <p> 20444 * The default implementation behaves as 20445 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20446 * the case of no accessibility delegate been set. 20447 * </p> 20448 * @return A populated {@link AccessibilityNodeInfo}. 20449 * 20450 * @see AccessibilityNodeInfo 20451 * 20452 * @hide 20453 */ 20454 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20455 return host.createAccessibilityNodeInfoInternal(); 20456 } 20457 } 20458 20459 private class MatchIdPredicate implements Predicate<View> { 20460 public int mId; 20461 20462 @Override 20463 public boolean apply(View view) { 20464 return (view.mID == mId); 20465 } 20466 } 20467 20468 private class MatchLabelForPredicate implements Predicate<View> { 20469 private int mLabeledId; 20470 20471 @Override 20472 public boolean apply(View view) { 20473 return (view.mLabelForId == mLabeledId); 20474 } 20475 } 20476 20477 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20478 private int mChangeTypes = 0; 20479 private boolean mPosted; 20480 private boolean mPostedWithDelay; 20481 private long mLastEventTimeMillis; 20482 20483 @Override 20484 public void run() { 20485 mPosted = false; 20486 mPostedWithDelay = false; 20487 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20488 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20489 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20490 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20491 event.setContentChangeTypes(mChangeTypes); 20492 sendAccessibilityEventUnchecked(event); 20493 } 20494 mChangeTypes = 0; 20495 } 20496 20497 public void runOrPost(int changeType) { 20498 mChangeTypes |= changeType; 20499 20500 // If this is a live region or the child of a live region, collect 20501 // all events from this frame and send them on the next frame. 20502 if (inLiveRegion()) { 20503 // If we're already posted with a delay, remove that. 20504 if (mPostedWithDelay) { 20505 removeCallbacks(this); 20506 mPostedWithDelay = false; 20507 } 20508 // Only post if we're not already posted. 20509 if (!mPosted) { 20510 post(this); 20511 mPosted = true; 20512 } 20513 return; 20514 } 20515 20516 if (mPosted) { 20517 return; 20518 } 20519 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20520 final long minEventIntevalMillis = 20521 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20522 if (timeSinceLastMillis >= minEventIntevalMillis) { 20523 removeCallbacks(this); 20524 run(); 20525 } else { 20526 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20527 mPosted = true; 20528 mPostedWithDelay = true; 20529 } 20530 } 20531 } 20532 20533 private boolean inLiveRegion() { 20534 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20535 return true; 20536 } 20537 20538 ViewParent parent = getParent(); 20539 while (parent instanceof View) { 20540 if (((View) parent).getAccessibilityLiveRegion() 20541 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20542 return true; 20543 } 20544 parent = parent.getParent(); 20545 } 20546 20547 return false; 20548 } 20549 20550 /** 20551 * Dump all private flags in readable format, useful for documentation and 20552 * sanity checking. 20553 */ 20554 private static void dumpFlags() { 20555 final HashMap<String, String> found = Maps.newHashMap(); 20556 try { 20557 for (Field field : View.class.getDeclaredFields()) { 20558 final int modifiers = field.getModifiers(); 20559 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20560 if (field.getType().equals(int.class)) { 20561 final int value = field.getInt(null); 20562 dumpFlag(found, field.getName(), value); 20563 } else if (field.getType().equals(int[].class)) { 20564 final int[] values = (int[]) field.get(null); 20565 for (int i = 0; i < values.length; i++) { 20566 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20567 } 20568 } 20569 } 20570 } 20571 } catch (IllegalAccessException e) { 20572 throw new RuntimeException(e); 20573 } 20574 20575 final ArrayList<String> keys = Lists.newArrayList(); 20576 keys.addAll(found.keySet()); 20577 Collections.sort(keys); 20578 for (String key : keys) { 20579 Log.d(VIEW_LOG_TAG, found.get(key)); 20580 } 20581 } 20582 20583 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20584 // Sort flags by prefix, then by bits, always keeping unique keys 20585 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20586 final int prefix = name.indexOf('_'); 20587 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20588 final String output = bits + " " + name; 20589 found.put(key, output); 20590 } 20591} 20592