View.java revision 9029e5ecd09759cf566f34429a57b69af70c335f
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.StateListAnimator; 21import android.annotation.IntDef; 22import android.annotation.NonNull; 23import android.annotation.Nullable; 24import android.content.ClipData; 25import android.content.Context; 26import android.content.res.ColorStateList; 27import android.content.res.Configuration; 28import android.content.res.Resources; 29import android.content.res.TypedArray; 30import android.graphics.Bitmap; 31import android.graphics.Canvas; 32import android.graphics.Insets; 33import android.graphics.Interpolator; 34import android.graphics.LinearGradient; 35import android.graphics.Matrix; 36import android.graphics.Outline; 37import android.graphics.Paint; 38import android.graphics.Path; 39import android.graphics.PathMeasure; 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; 94import com.google.android.collect.Lists; 95import com.google.android.collect.Maps; 96 97import java.lang.annotation.Retention; 98import java.lang.annotation.RetentionPolicy; 99import java.lang.ref.WeakReference; 100import java.lang.reflect.Field; 101import java.lang.reflect.InvocationTargetException; 102import java.lang.reflect.Method; 103import java.lang.reflect.Modifier; 104import java.util.ArrayList; 105import java.util.Arrays; 106import java.util.Collections; 107import java.util.HashMap; 108import java.util.List; 109import java.util.Locale; 110import java.util.Map; 111import java.util.concurrent.CopyOnWriteArrayList; 112import java.util.concurrent.atomic.AtomicInteger; 113 114/** 115 * <p> 116 * This class represents the basic building block for user interface components. A View 117 * occupies a rectangular area on the screen and is responsible for drawing and 118 * event handling. View is the base class for <em>widgets</em>, which are 119 * used to create interactive UI components (buttons, text fields, etc.). The 120 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 121 * are invisible containers that hold other Views (or other ViewGroups) and define 122 * their layout properties. 123 * </p> 124 * 125 * <div class="special reference"> 126 * <h3>Developer Guides</h3> 127 * <p>For information about using this class to develop your application's user interface, 128 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 129 * </div> 130 * 131 * <a name="Using"></a> 132 * <h3>Using Views</h3> 133 * <p> 134 * All of the views in a window are arranged in a single tree. You can add views 135 * either from code or by specifying a tree of views in one or more XML layout 136 * files. There are many specialized subclasses of views that act as controls or 137 * are capable of displaying text, images, or other content. 138 * </p> 139 * <p> 140 * Once you have created a tree of views, there are typically a few types of 141 * common operations you may wish to perform: 142 * <ul> 143 * <li><strong>Set properties:</strong> for example setting the text of a 144 * {@link android.widget.TextView}. The available properties and the methods 145 * that set them will vary among the different subclasses of views. Note that 146 * properties that are known at build time can be set in the XML layout 147 * files.</li> 148 * <li><strong>Set focus:</strong> The framework will handled moving focus in 149 * response to user input. To force focus to a specific view, call 150 * {@link #requestFocus}.</li> 151 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 152 * that will be notified when something interesting happens to the view. For 153 * example, all views will let you set a listener to be notified when the view 154 * gains or loses focus. You can register such a listener using 155 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 156 * Other view subclasses offer more specialized listeners. For example, a Button 157 * exposes a listener to notify clients when the button is clicked.</li> 158 * <li><strong>Set visibility:</strong> You can hide or show views using 159 * {@link #setVisibility(int)}.</li> 160 * </ul> 161 * </p> 162 * <p><em> 163 * Note: The Android framework is responsible for measuring, laying out and 164 * drawing views. You should not call methods that perform these actions on 165 * views yourself unless you are actually implementing a 166 * {@link android.view.ViewGroup}. 167 * </em></p> 168 * 169 * <a name="Lifecycle"></a> 170 * <h3>Implementing a Custom View</h3> 171 * 172 * <p> 173 * To implement a custom view, you will usually begin by providing overrides for 174 * some of the standard methods that the framework calls on all views. You do 175 * not need to override all of these methods. In fact, you can start by just 176 * overriding {@link #onDraw(android.graphics.Canvas)}. 177 * <table border="2" width="85%" align="center" cellpadding="5"> 178 * <thead> 179 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 180 * </thead> 181 * 182 * <tbody> 183 * <tr> 184 * <td rowspan="2">Creation</td> 185 * <td>Constructors</td> 186 * <td>There is a form of the constructor that are called when the view 187 * is created from code and a form that is called when the view is 188 * inflated from a layout file. The second form should parse and apply 189 * any attributes defined in the layout file. 190 * </td> 191 * </tr> 192 * <tr> 193 * <td><code>{@link #onFinishInflate()}</code></td> 194 * <td>Called after a view and all of its children has been inflated 195 * from XML.</td> 196 * </tr> 197 * 198 * <tr> 199 * <td rowspan="3">Layout</td> 200 * <td><code>{@link #onMeasure(int, int)}</code></td> 201 * <td>Called to determine the size requirements for this view and all 202 * of its children. 203 * </td> 204 * </tr> 205 * <tr> 206 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 207 * <td>Called when this view should assign a size and position to all 208 * of its children. 209 * </td> 210 * </tr> 211 * <tr> 212 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 213 * <td>Called when the size of this view has changed. 214 * </td> 215 * </tr> 216 * 217 * <tr> 218 * <td>Drawing</td> 219 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 220 * <td>Called when the view should render its content. 221 * </td> 222 * </tr> 223 * 224 * <tr> 225 * <td rowspan="4">Event processing</td> 226 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 227 * <td>Called when a new hardware key event occurs. 228 * </td> 229 * </tr> 230 * <tr> 231 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 232 * <td>Called when a hardware key up event occurs. 233 * </td> 234 * </tr> 235 * <tr> 236 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 237 * <td>Called when a trackball motion event occurs. 238 * </td> 239 * </tr> 240 * <tr> 241 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 242 * <td>Called when a touch screen motion event occurs. 243 * </td> 244 * </tr> 245 * 246 * <tr> 247 * <td rowspan="2">Focus</td> 248 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 249 * <td>Called when the view gains or loses focus. 250 * </td> 251 * </tr> 252 * 253 * <tr> 254 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 255 * <td>Called when the window containing the view gains or loses focus. 256 * </td> 257 * </tr> 258 * 259 * <tr> 260 * <td rowspan="3">Attaching</td> 261 * <td><code>{@link #onAttachedToWindow()}</code></td> 262 * <td>Called when the view is attached to a window. 263 * </td> 264 * </tr> 265 * 266 * <tr> 267 * <td><code>{@link #onDetachedFromWindow}</code></td> 268 * <td>Called when the view is detached from its window. 269 * </td> 270 * </tr> 271 * 272 * <tr> 273 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 274 * <td>Called when the visibility of the window containing the view 275 * has changed. 276 * </td> 277 * </tr> 278 * </tbody> 279 * 280 * </table> 281 * </p> 282 * 283 * <a name="IDs"></a> 284 * <h3>IDs</h3> 285 * Views may have an integer id associated with them. These ids are typically 286 * assigned in the layout XML files, and are used to find specific views within 287 * the view tree. A common pattern is to: 288 * <ul> 289 * <li>Define a Button in the layout file and assign it a unique ID. 290 * <pre> 291 * <Button 292 * android:id="@+id/my_button" 293 * android:layout_width="wrap_content" 294 * android:layout_height="wrap_content" 295 * android:text="@string/my_button_text"/> 296 * </pre></li> 297 * <li>From the onCreate method of an Activity, find the Button 298 * <pre class="prettyprint"> 299 * Button myButton = (Button) findViewById(R.id.my_button); 300 * </pre></li> 301 * </ul> 302 * <p> 303 * View IDs need not be unique throughout the tree, but it is good practice to 304 * ensure that they are at least unique within the part of the tree you are 305 * searching. 306 * </p> 307 * 308 * <a name="Position"></a> 309 * <h3>Position</h3> 310 * <p> 311 * The geometry of a view is that of a rectangle. A view has a location, 312 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 313 * two dimensions, expressed as a width and a height. The unit for location 314 * and dimensions is the pixel. 315 * </p> 316 * 317 * <p> 318 * It is possible to retrieve the location of a view by invoking the methods 319 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 320 * coordinate of the rectangle representing the view. The latter returns the 321 * top, or Y, coordinate of the rectangle representing the view. These methods 322 * both return the location of the view relative to its parent. For instance, 323 * when getLeft() returns 20, that means the view is located 20 pixels to the 324 * right of the left edge of its direct parent. 325 * </p> 326 * 327 * <p> 328 * In addition, several convenience methods are offered to avoid unnecessary 329 * computations, namely {@link #getRight()} and {@link #getBottom()}. 330 * These methods return the coordinates of the right and bottom edges of the 331 * rectangle representing the view. For instance, calling {@link #getRight()} 332 * is similar to the following computation: <code>getLeft() + getWidth()</code> 333 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 334 * </p> 335 * 336 * <a name="SizePaddingMargins"></a> 337 * <h3>Size, padding and margins</h3> 338 * <p> 339 * The size of a view is expressed with a width and a height. A view actually 340 * possess two pairs of width and height values. 341 * </p> 342 * 343 * <p> 344 * The first pair is known as <em>measured width</em> and 345 * <em>measured height</em>. These dimensions define how big a view wants to be 346 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 347 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 348 * and {@link #getMeasuredHeight()}. 349 * </p> 350 * 351 * <p> 352 * The second pair is simply known as <em>width</em> and <em>height</em>, or 353 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 354 * dimensions define the actual size of the view on screen, at drawing time and 355 * after layout. These values may, but do not have to, be different from the 356 * measured width and height. The width and height can be obtained by calling 357 * {@link #getWidth()} and {@link #getHeight()}. 358 * </p> 359 * 360 * <p> 361 * To measure its dimensions, a view takes into account its padding. The padding 362 * is expressed in pixels for the left, top, right and bottom parts of the view. 363 * Padding can be used to offset the content of the view by a specific amount of 364 * pixels. For instance, a left padding of 2 will push the view's content by 365 * 2 pixels to the right of the left edge. Padding can be set using the 366 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 367 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 368 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 369 * {@link #getPaddingEnd()}. 370 * </p> 371 * 372 * <p> 373 * Even though a view can define a padding, it does not provide any support for 374 * margins. However, view groups provide such a support. Refer to 375 * {@link android.view.ViewGroup} and 376 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 377 * </p> 378 * 379 * <a name="Layout"></a> 380 * <h3>Layout</h3> 381 * <p> 382 * Layout is a two pass process: a measure pass and a layout pass. The measuring 383 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 384 * of the view tree. Each view pushes dimension specifications down the tree 385 * during the recursion. At the end of the measure pass, every view has stored 386 * its measurements. The second pass happens in 387 * {@link #layout(int,int,int,int)} and is also top-down. During 388 * this pass each parent is responsible for positioning all of its children 389 * using the sizes computed in the measure pass. 390 * </p> 391 * 392 * <p> 393 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 394 * {@link #getMeasuredHeight()} values must be set, along with those for all of 395 * that view's descendants. A view's measured width and measured height values 396 * must respect the constraints imposed by the view's parents. This guarantees 397 * that at the end of the measure pass, all parents accept all of their 398 * children's measurements. A parent view may call measure() more than once on 399 * its children. For example, the parent may measure each child once with 400 * unspecified dimensions to find out how big they want to be, then call 401 * measure() on them again with actual numbers if the sum of all the children's 402 * unconstrained sizes is too big or too small. 403 * </p> 404 * 405 * <p> 406 * The measure pass uses two classes to communicate dimensions. The 407 * {@link MeasureSpec} class is used by views to tell their parents how they 408 * want to be measured and positioned. The base LayoutParams class just 409 * describes how big the view wants to be for both width and height. For each 410 * dimension, it can specify one of: 411 * <ul> 412 * <li> an exact number 413 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 414 * (minus padding) 415 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 416 * enclose its content (plus padding). 417 * </ul> 418 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 419 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 420 * an X and Y value. 421 * </p> 422 * 423 * <p> 424 * MeasureSpecs are used to push requirements down the tree from parent to 425 * child. A MeasureSpec can be in one of three modes: 426 * <ul> 427 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 428 * of a child view. For example, a LinearLayout may call measure() on its child 429 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 430 * tall the child view wants to be given a width of 240 pixels. 431 * <li>EXACTLY: This is used by the parent to impose an exact size on the 432 * child. The child must use this size, and guarantee that all of its 433 * descendants will fit within this size. 434 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 435 * child. The child must guarantee that it and all of its descendants will fit 436 * within this size. 437 * </ul> 438 * </p> 439 * 440 * <p> 441 * To intiate a layout, call {@link #requestLayout}. This method is typically 442 * called by a view on itself when it believes that is can no longer fit within 443 * its current bounds. 444 * </p> 445 * 446 * <a name="Drawing"></a> 447 * <h3>Drawing</h3> 448 * <p> 449 * Drawing is handled by walking the tree and recording the drawing commands of 450 * any View that needs to update. After this, the drawing commands of the 451 * entire tree are issued to screen, clipped to the newly damaged area. 452 * </p> 453 * 454 * <p> 455 * The tree is largely recorded and drawn in order, with parents drawn before 456 * (i.e., behind) their children, with siblings drawn in the order they appear 457 * in the tree. If you set a background drawable for a View, then the View will 458 * draw it before calling back to its <code>onDraw()</code> method. The child 459 * drawing order can be overridden with 460 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 461 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 462 * </p> 463 * 464 * <p> 465 * To force a view to draw, call {@link #invalidate()}. 466 * </p> 467 * 468 * <a name="EventHandlingThreading"></a> 469 * <h3>Event Handling and Threading</h3> 470 * <p> 471 * The basic cycle of a view is as follows: 472 * <ol> 473 * <li>An event comes in and is dispatched to the appropriate view. The view 474 * handles the event and notifies any listeners.</li> 475 * <li>If in the course of processing the event, the view's bounds may need 476 * to be changed, the view will call {@link #requestLayout()}.</li> 477 * <li>Similarly, if in the course of processing the event the view's appearance 478 * may need to be changed, the view will call {@link #invalidate()}.</li> 479 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 480 * the framework will take care of measuring, laying out, and drawing the tree 481 * as appropriate.</li> 482 * </ol> 483 * </p> 484 * 485 * <p><em>Note: The entire view tree is single threaded. You must always be on 486 * the UI thread when calling any method on any view.</em> 487 * If you are doing work on other threads and want to update the state of a view 488 * from that thread, you should use a {@link Handler}. 489 * </p> 490 * 491 * <a name="FocusHandling"></a> 492 * <h3>Focus Handling</h3> 493 * <p> 494 * The framework will handle routine focus movement in response to user input. 495 * This includes changing the focus as views are removed or hidden, or as new 496 * views become available. Views indicate their willingness to take focus 497 * through the {@link #isFocusable} method. To change whether a view can take 498 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 499 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 500 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 501 * </p> 502 * <p> 503 * Focus movement is based on an algorithm which finds the nearest neighbor in a 504 * given direction. In rare cases, the default algorithm may not match the 505 * intended behavior of the developer. In these situations, you can provide 506 * explicit overrides by using these XML attributes in the layout file: 507 * <pre> 508 * nextFocusDown 509 * nextFocusLeft 510 * nextFocusRight 511 * nextFocusUp 512 * </pre> 513 * </p> 514 * 515 * 516 * <p> 517 * To get a particular view to take focus, call {@link #requestFocus()}. 518 * </p> 519 * 520 * <a name="TouchMode"></a> 521 * <h3>Touch Mode</h3> 522 * <p> 523 * When a user is navigating a user interface via directional keys such as a D-pad, it is 524 * necessary to give focus to actionable items such as buttons so the user can see 525 * what will take input. If the device has touch capabilities, however, and the user 526 * begins interacting with the interface by touching it, it is no longer necessary to 527 * always highlight, or give focus to, a particular view. This motivates a mode 528 * for interaction named 'touch mode'. 529 * </p> 530 * <p> 531 * For a touch capable device, once the user touches the screen, the device 532 * will enter touch mode. From this point onward, only views for which 533 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 534 * Other views that are touchable, like buttons, will not take focus when touched; they will 535 * only fire the on click listeners. 536 * </p> 537 * <p> 538 * Any time a user hits a directional key, such as a D-pad direction, the view device will 539 * exit touch mode, and find a view to take focus, so that the user may resume interacting 540 * with the user interface without touching the screen again. 541 * </p> 542 * <p> 543 * The touch mode state is maintained across {@link android.app.Activity}s. Call 544 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 545 * </p> 546 * 547 * <a name="Scrolling"></a> 548 * <h3>Scrolling</h3> 549 * <p> 550 * The framework provides basic support for views that wish to internally 551 * scroll their content. This includes keeping track of the X and Y scroll 552 * offset as well as mechanisms for drawing scrollbars. See 553 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 554 * {@link #awakenScrollBars()} for more details. 555 * </p> 556 * 557 * <a name="Tags"></a> 558 * <h3>Tags</h3> 559 * <p> 560 * Unlike IDs, tags are not used to identify views. Tags are essentially an 561 * extra piece of information that can be associated with a view. They are most 562 * often used as a convenience to store data related to views in the views 563 * themselves rather than by putting them in a separate structure. 564 * </p> 565 * 566 * <a name="Properties"></a> 567 * <h3>Properties</h3> 568 * <p> 569 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 570 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 571 * available both in the {@link Property} form as well as in similarly-named setter/getter 572 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 573 * be used to set persistent state associated with these rendering-related properties on the view. 574 * The properties and methods can also be used in conjunction with 575 * {@link android.animation.Animator Animator}-based animations, described more in the 576 * <a href="#Animation">Animation</a> section. 577 * </p> 578 * 579 * <a name="Animation"></a> 580 * <h3>Animation</h3> 581 * <p> 582 * Starting with Android 3.0, the preferred way of animating views is to use the 583 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 584 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 585 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 586 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 587 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 588 * makes animating these View properties particularly easy and efficient. 589 * </p> 590 * <p> 591 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 592 * You can attach an {@link Animation} object to a view using 593 * {@link #setAnimation(Animation)} or 594 * {@link #startAnimation(Animation)}. The animation can alter the scale, 595 * rotation, translation and alpha of a view over time. If the animation is 596 * attached to a view that has children, the animation will affect the entire 597 * subtree rooted by that node. When an animation is started, the framework will 598 * take care of redrawing the appropriate views until the animation completes. 599 * </p> 600 * 601 * <a name="Security"></a> 602 * <h3>Security</h3> 603 * <p> 604 * Sometimes it is essential that an application be able to verify that an action 605 * is being performed with the full knowledge and consent of the user, such as 606 * granting a permission request, making a purchase or clicking on an advertisement. 607 * Unfortunately, a malicious application could try to spoof the user into 608 * performing these actions, unaware, by concealing the intended purpose of the view. 609 * As a remedy, the framework offers a touch filtering mechanism that can be used to 610 * improve the security of views that provide access to sensitive functionality. 611 * </p><p> 612 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 613 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 614 * will discard touches that are received whenever the view's window is obscured by 615 * another visible window. As a result, the view will not receive touches whenever a 616 * toast, dialog or other window appears above the view's window. 617 * </p><p> 618 * For more fine-grained control over security, consider overriding the 619 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 620 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 621 * </p> 622 * 623 * @attr ref android.R.styleable#View_alpha 624 * @attr ref android.R.styleable#View_background 625 * @attr ref android.R.styleable#View_clickable 626 * @attr ref android.R.styleable#View_contentDescription 627 * @attr ref android.R.styleable#View_drawingCacheQuality 628 * @attr ref android.R.styleable#View_duplicateParentState 629 * @attr ref android.R.styleable#View_id 630 * @attr ref android.R.styleable#View_requiresFadingEdge 631 * @attr ref android.R.styleable#View_fadeScrollbars 632 * @attr ref android.R.styleable#View_fadingEdgeLength 633 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 634 * @attr ref android.R.styleable#View_fitsSystemWindows 635 * @attr ref android.R.styleable#View_isScrollContainer 636 * @attr ref android.R.styleable#View_focusable 637 * @attr ref android.R.styleable#View_focusableInTouchMode 638 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 639 * @attr ref android.R.styleable#View_keepScreenOn 640 * @attr ref android.R.styleable#View_layerType 641 * @attr ref android.R.styleable#View_layoutDirection 642 * @attr ref android.R.styleable#View_longClickable 643 * @attr ref android.R.styleable#View_minHeight 644 * @attr ref android.R.styleable#View_minWidth 645 * @attr ref android.R.styleable#View_nextFocusDown 646 * @attr ref android.R.styleable#View_nextFocusLeft 647 * @attr ref android.R.styleable#View_nextFocusRight 648 * @attr ref android.R.styleable#View_nextFocusUp 649 * @attr ref android.R.styleable#View_onClick 650 * @attr ref android.R.styleable#View_padding 651 * @attr ref android.R.styleable#View_paddingBottom 652 * @attr ref android.R.styleable#View_paddingLeft 653 * @attr ref android.R.styleable#View_paddingRight 654 * @attr ref android.R.styleable#View_paddingTop 655 * @attr ref android.R.styleable#View_paddingStart 656 * @attr ref android.R.styleable#View_paddingEnd 657 * @attr ref android.R.styleable#View_saveEnabled 658 * @attr ref android.R.styleable#View_rotation 659 * @attr ref android.R.styleable#View_rotationX 660 * @attr ref android.R.styleable#View_rotationY 661 * @attr ref android.R.styleable#View_scaleX 662 * @attr ref android.R.styleable#View_scaleY 663 * @attr ref android.R.styleable#View_scrollX 664 * @attr ref android.R.styleable#View_scrollY 665 * @attr ref android.R.styleable#View_scrollbarSize 666 * @attr ref android.R.styleable#View_scrollbarStyle 667 * @attr ref android.R.styleable#View_scrollbars 668 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 669 * @attr ref android.R.styleable#View_scrollbarFadeDuration 670 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 671 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 672 * @attr ref android.R.styleable#View_scrollbarThumbVertical 673 * @attr ref android.R.styleable#View_scrollbarTrackVertical 674 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 675 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 676 * @attr ref android.R.styleable#View_stateListAnimator 677 * @attr ref android.R.styleable#View_transitionName 678 * @attr ref android.R.styleable#View_soundEffectsEnabled 679 * @attr ref android.R.styleable#View_tag 680 * @attr ref android.R.styleable#View_textAlignment 681 * @attr ref android.R.styleable#View_textDirection 682 * @attr ref android.R.styleable#View_transformPivotX 683 * @attr ref android.R.styleable#View_transformPivotY 684 * @attr ref android.R.styleable#View_translationX 685 * @attr ref android.R.styleable#View_translationY 686 * @attr ref android.R.styleable#View_translationZ 687 * @attr ref android.R.styleable#View_visibility 688 * 689 * @see android.view.ViewGroup 690 */ 691public class View implements Drawable.Callback, KeyEvent.Callback, 692 AccessibilityEventSource { 693 private static final boolean DBG = false; 694 695 /** 696 * The logging tag used by this class with android.util.Log. 697 */ 698 protected static final String VIEW_LOG_TAG = "View"; 699 700 /** 701 * When set to true, apps will draw debugging information about their layouts. 702 * 703 * @hide 704 */ 705 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 706 707 /** 708 * When set to true, this view will save its attribute data. 709 * 710 * @hide 711 */ 712 public static boolean mDebugViewAttributes = false; 713 714 /** 715 * Used to mark a View that has no ID. 716 */ 717 public static final int NO_ID = -1; 718 719 /** 720 * Signals that compatibility booleans have been initialized according to 721 * target SDK versions. 722 */ 723 private static boolean sCompatibilityDone = false; 724 725 /** 726 * Use the old (broken) way of building MeasureSpecs. 727 */ 728 private static boolean sUseBrokenMakeMeasureSpec = false; 729 730 /** 731 * Ignore any optimizations using the measure cache. 732 */ 733 private static boolean sIgnoreMeasureCache = false; 734 735 /** 736 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 737 * calling setFlags. 738 */ 739 private static final int NOT_FOCUSABLE = 0x00000000; 740 741 /** 742 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 743 * setFlags. 744 */ 745 private static final int FOCUSABLE = 0x00000001; 746 747 /** 748 * Mask for use with setFlags indicating bits used for focus. 749 */ 750 private static final int FOCUSABLE_MASK = 0x00000001; 751 752 /** 753 * This view will adjust its padding to fit sytem windows (e.g. status bar) 754 */ 755 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 756 757 /** @hide */ 758 @IntDef({VISIBLE, INVISIBLE, GONE}) 759 @Retention(RetentionPolicy.SOURCE) 760 public @interface Visibility {} 761 762 /** 763 * This view is visible. 764 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 765 * android:visibility}. 766 */ 767 public static final int VISIBLE = 0x00000000; 768 769 /** 770 * This view is invisible, but it still takes up space for layout purposes. 771 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 772 * android:visibility}. 773 */ 774 public static final int INVISIBLE = 0x00000004; 775 776 /** 777 * This view is invisible, and it doesn't take any space for layout 778 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 779 * android:visibility}. 780 */ 781 public static final int GONE = 0x00000008; 782 783 /** 784 * Mask for use with setFlags indicating bits used for visibility. 785 * {@hide} 786 */ 787 static final int VISIBILITY_MASK = 0x0000000C; 788 789 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 790 791 /** 792 * This view is enabled. Interpretation varies by subclass. 793 * Use with ENABLED_MASK when calling setFlags. 794 * {@hide} 795 */ 796 static final int ENABLED = 0x00000000; 797 798 /** 799 * This view is disabled. Interpretation varies by subclass. 800 * Use with ENABLED_MASK when calling setFlags. 801 * {@hide} 802 */ 803 static final int DISABLED = 0x00000020; 804 805 /** 806 * Mask for use with setFlags indicating bits used for indicating whether 807 * this view is enabled 808 * {@hide} 809 */ 810 static final int ENABLED_MASK = 0x00000020; 811 812 /** 813 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 814 * called and further optimizations will be performed. It is okay to have 815 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 816 * {@hide} 817 */ 818 static final int WILL_NOT_DRAW = 0x00000080; 819 820 /** 821 * Mask for use with setFlags indicating bits used for indicating whether 822 * this view is will draw 823 * {@hide} 824 */ 825 static final int DRAW_MASK = 0x00000080; 826 827 /** 828 * <p>This view doesn't show scrollbars.</p> 829 * {@hide} 830 */ 831 static final int SCROLLBARS_NONE = 0x00000000; 832 833 /** 834 * <p>This view shows horizontal scrollbars.</p> 835 * {@hide} 836 */ 837 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 838 839 /** 840 * <p>This view shows vertical scrollbars.</p> 841 * {@hide} 842 */ 843 static final int SCROLLBARS_VERTICAL = 0x00000200; 844 845 /** 846 * <p>Mask for use with setFlags indicating bits used for indicating which 847 * scrollbars are enabled.</p> 848 * {@hide} 849 */ 850 static final int SCROLLBARS_MASK = 0x00000300; 851 852 /** 853 * Indicates that the view should filter touches when its window is obscured. 854 * Refer to the class comments for more information about this security feature. 855 * {@hide} 856 */ 857 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 858 859 /** 860 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 861 * that they are optional and should be skipped if the window has 862 * requested system UI flags that ignore those insets for layout. 863 */ 864 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 865 866 /** 867 * <p>This view doesn't show fading edges.</p> 868 * {@hide} 869 */ 870 static final int FADING_EDGE_NONE = 0x00000000; 871 872 /** 873 * <p>This view shows horizontal fading edges.</p> 874 * {@hide} 875 */ 876 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 877 878 /** 879 * <p>This view shows vertical fading edges.</p> 880 * {@hide} 881 */ 882 static final int FADING_EDGE_VERTICAL = 0x00002000; 883 884 /** 885 * <p>Mask for use with setFlags indicating bits used for indicating which 886 * fading edges are enabled.</p> 887 * {@hide} 888 */ 889 static final int FADING_EDGE_MASK = 0x00003000; 890 891 /** 892 * <p>Indicates this view can be clicked. When clickable, a View reacts 893 * to clicks by notifying the OnClickListener.<p> 894 * {@hide} 895 */ 896 static final int CLICKABLE = 0x00004000; 897 898 /** 899 * <p>Indicates this view is caching its drawing into a bitmap.</p> 900 * {@hide} 901 */ 902 static final int DRAWING_CACHE_ENABLED = 0x00008000; 903 904 /** 905 * <p>Indicates that no icicle should be saved for this view.<p> 906 * {@hide} 907 */ 908 static final int SAVE_DISABLED = 0x000010000; 909 910 /** 911 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 912 * property.</p> 913 * {@hide} 914 */ 915 static final int SAVE_DISABLED_MASK = 0x000010000; 916 917 /** 918 * <p>Indicates that no drawing cache should ever be created for this view.<p> 919 * {@hide} 920 */ 921 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 922 923 /** 924 * <p>Indicates this view can take / keep focus when int touch mode.</p> 925 * {@hide} 926 */ 927 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 928 929 /** @hide */ 930 @Retention(RetentionPolicy.SOURCE) 931 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 932 public @interface DrawingCacheQuality {} 933 934 /** 935 * <p>Enables low quality mode for the drawing cache.</p> 936 */ 937 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 938 939 /** 940 * <p>Enables high quality mode for the drawing cache.</p> 941 */ 942 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 943 944 /** 945 * <p>Enables automatic quality mode for the drawing cache.</p> 946 */ 947 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 948 949 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 950 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 951 }; 952 953 /** 954 * <p>Mask for use with setFlags indicating bits used for the cache 955 * quality property.</p> 956 * {@hide} 957 */ 958 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 959 960 /** 961 * <p> 962 * Indicates this view can be long clicked. When long clickable, a View 963 * reacts to long clicks by notifying the OnLongClickListener or showing a 964 * context menu. 965 * </p> 966 * {@hide} 967 */ 968 static final int LONG_CLICKABLE = 0x00200000; 969 970 /** 971 * <p>Indicates that this view gets its drawable states from its direct parent 972 * and ignores its original internal states.</p> 973 * 974 * @hide 975 */ 976 static final int DUPLICATE_PARENT_STATE = 0x00400000; 977 978 /** @hide */ 979 @IntDef({ 980 SCROLLBARS_INSIDE_OVERLAY, 981 SCROLLBARS_INSIDE_INSET, 982 SCROLLBARS_OUTSIDE_OVERLAY, 983 SCROLLBARS_OUTSIDE_INSET 984 }) 985 @Retention(RetentionPolicy.SOURCE) 986 public @interface ScrollBarStyle {} 987 988 /** 989 * The scrollbar style to display the scrollbars inside the content area, 990 * without increasing the padding. The scrollbars will be overlaid with 991 * translucency on the view's content. 992 */ 993 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 994 995 /** 996 * The scrollbar style to display the scrollbars inside the padded area, 997 * increasing the padding of the view. The scrollbars will not overlap the 998 * content area of the view. 999 */ 1000 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1001 1002 /** 1003 * The scrollbar style to display the scrollbars at the edge of the view, 1004 * without increasing the padding. The scrollbars will be overlaid with 1005 * translucency. 1006 */ 1007 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1008 1009 /** 1010 * The scrollbar style to display the scrollbars at the edge of the view, 1011 * increasing the padding of the view. The scrollbars will only overlap the 1012 * background, if any. 1013 */ 1014 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1015 1016 /** 1017 * Mask to check if the scrollbar style is overlay or inset. 1018 * {@hide} 1019 */ 1020 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1021 1022 /** 1023 * Mask to check if the scrollbar style is inside or outside. 1024 * {@hide} 1025 */ 1026 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1027 1028 /** 1029 * Mask for scrollbar style. 1030 * {@hide} 1031 */ 1032 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1033 1034 /** 1035 * View flag indicating that the screen should remain on while the 1036 * window containing this view is visible to the user. This effectively 1037 * takes care of automatically setting the WindowManager's 1038 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1039 */ 1040 public static final int KEEP_SCREEN_ON = 0x04000000; 1041 1042 /** 1043 * View flag indicating whether this view should have sound effects enabled 1044 * for events such as clicking and touching. 1045 */ 1046 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1047 1048 /** 1049 * View flag indicating whether this view should have haptic feedback 1050 * enabled for events such as long presses. 1051 */ 1052 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1053 1054 /** 1055 * <p>Indicates that the view hierarchy should stop saving state when 1056 * it reaches this view. If state saving is initiated immediately at 1057 * the view, it will be allowed. 1058 * {@hide} 1059 */ 1060 static final int PARENT_SAVE_DISABLED = 0x20000000; 1061 1062 /** 1063 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1064 * {@hide} 1065 */ 1066 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1067 1068 /** @hide */ 1069 @IntDef(flag = true, 1070 value = { 1071 FOCUSABLES_ALL, 1072 FOCUSABLES_TOUCH_MODE 1073 }) 1074 @Retention(RetentionPolicy.SOURCE) 1075 public @interface FocusableMode {} 1076 1077 /** 1078 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1079 * should add all focusable Views regardless if they are focusable in touch mode. 1080 */ 1081 public static final int FOCUSABLES_ALL = 0x00000000; 1082 1083 /** 1084 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1085 * should add only Views focusable in touch mode. 1086 */ 1087 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1088 1089 /** @hide */ 1090 @IntDef({ 1091 FOCUS_BACKWARD, 1092 FOCUS_FORWARD, 1093 FOCUS_LEFT, 1094 FOCUS_UP, 1095 FOCUS_RIGHT, 1096 FOCUS_DOWN 1097 }) 1098 @Retention(RetentionPolicy.SOURCE) 1099 public @interface FocusDirection {} 1100 1101 /** @hide */ 1102 @IntDef({ 1103 FOCUS_LEFT, 1104 FOCUS_UP, 1105 FOCUS_RIGHT, 1106 FOCUS_DOWN 1107 }) 1108 @Retention(RetentionPolicy.SOURCE) 1109 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1110 1111 /** 1112 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1113 * item. 1114 */ 1115 public static final int FOCUS_BACKWARD = 0x00000001; 1116 1117 /** 1118 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1119 * item. 1120 */ 1121 public static final int FOCUS_FORWARD = 0x00000002; 1122 1123 /** 1124 * Use with {@link #focusSearch(int)}. Move focus to the left. 1125 */ 1126 public static final int FOCUS_LEFT = 0x00000011; 1127 1128 /** 1129 * Use with {@link #focusSearch(int)}. Move focus up. 1130 */ 1131 public static final int FOCUS_UP = 0x00000021; 1132 1133 /** 1134 * Use with {@link #focusSearch(int)}. Move focus to the right. 1135 */ 1136 public static final int FOCUS_RIGHT = 0x00000042; 1137 1138 /** 1139 * Use with {@link #focusSearch(int)}. Move focus down. 1140 */ 1141 public static final int FOCUS_DOWN = 0x00000082; 1142 1143 /** 1144 * Bits of {@link #getMeasuredWidthAndState()} and 1145 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1146 */ 1147 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1148 1149 /** 1150 * Bits of {@link #getMeasuredWidthAndState()} and 1151 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1152 */ 1153 public static final int MEASURED_STATE_MASK = 0xff000000; 1154 1155 /** 1156 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1157 * for functions that combine both width and height into a single int, 1158 * such as {@link #getMeasuredState()} and the childState argument of 1159 * {@link #resolveSizeAndState(int, int, int)}. 1160 */ 1161 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1162 1163 /** 1164 * Bit of {@link #getMeasuredWidthAndState()} and 1165 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1166 * is smaller that the space the view would like to have. 1167 */ 1168 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1169 1170 /** 1171 * Base View state sets 1172 */ 1173 // Singles 1174 /** 1175 * Indicates the view has no states set. States are used with 1176 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1177 * view depending on its state. 1178 * 1179 * @see android.graphics.drawable.Drawable 1180 * @see #getDrawableState() 1181 */ 1182 protected static final int[] EMPTY_STATE_SET; 1183 /** 1184 * Indicates the view is enabled. States are used with 1185 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1186 * view depending on its state. 1187 * 1188 * @see android.graphics.drawable.Drawable 1189 * @see #getDrawableState() 1190 */ 1191 protected static final int[] ENABLED_STATE_SET; 1192 /** 1193 * Indicates the view is focused. States are used with 1194 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1195 * view depending on its state. 1196 * 1197 * @see android.graphics.drawable.Drawable 1198 * @see #getDrawableState() 1199 */ 1200 protected static final int[] FOCUSED_STATE_SET; 1201 /** 1202 * Indicates the view is selected. States are used with 1203 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1204 * view depending on its state. 1205 * 1206 * @see android.graphics.drawable.Drawable 1207 * @see #getDrawableState() 1208 */ 1209 protected static final int[] SELECTED_STATE_SET; 1210 /** 1211 * Indicates the view is pressed. States are used with 1212 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1213 * view depending on its state. 1214 * 1215 * @see android.graphics.drawable.Drawable 1216 * @see #getDrawableState() 1217 */ 1218 protected static final int[] PRESSED_STATE_SET; 1219 /** 1220 * Indicates the view's window has focus. States are used with 1221 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1222 * view depending on its state. 1223 * 1224 * @see android.graphics.drawable.Drawable 1225 * @see #getDrawableState() 1226 */ 1227 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1228 // Doubles 1229 /** 1230 * Indicates the view is enabled and has the focus. 1231 * 1232 * @see #ENABLED_STATE_SET 1233 * @see #FOCUSED_STATE_SET 1234 */ 1235 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1236 /** 1237 * Indicates the view is enabled and selected. 1238 * 1239 * @see #ENABLED_STATE_SET 1240 * @see #SELECTED_STATE_SET 1241 */ 1242 protected static final int[] ENABLED_SELECTED_STATE_SET; 1243 /** 1244 * Indicates the view is enabled and that its window has focus. 1245 * 1246 * @see #ENABLED_STATE_SET 1247 * @see #WINDOW_FOCUSED_STATE_SET 1248 */ 1249 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1250 /** 1251 * Indicates the view is focused and selected. 1252 * 1253 * @see #FOCUSED_STATE_SET 1254 * @see #SELECTED_STATE_SET 1255 */ 1256 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1257 /** 1258 * Indicates the view has the focus and that its window has the focus. 1259 * 1260 * @see #FOCUSED_STATE_SET 1261 * @see #WINDOW_FOCUSED_STATE_SET 1262 */ 1263 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1264 /** 1265 * Indicates the view is selected and that its window has the focus. 1266 * 1267 * @see #SELECTED_STATE_SET 1268 * @see #WINDOW_FOCUSED_STATE_SET 1269 */ 1270 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1271 // Triples 1272 /** 1273 * Indicates the view is enabled, focused and selected. 1274 * 1275 * @see #ENABLED_STATE_SET 1276 * @see #FOCUSED_STATE_SET 1277 * @see #SELECTED_STATE_SET 1278 */ 1279 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1280 /** 1281 * Indicates the view is enabled, focused and its window has the focus. 1282 * 1283 * @see #ENABLED_STATE_SET 1284 * @see #FOCUSED_STATE_SET 1285 * @see #WINDOW_FOCUSED_STATE_SET 1286 */ 1287 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1288 /** 1289 * Indicates the view is enabled, selected and its window has the focus. 1290 * 1291 * @see #ENABLED_STATE_SET 1292 * @see #SELECTED_STATE_SET 1293 * @see #WINDOW_FOCUSED_STATE_SET 1294 */ 1295 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1296 /** 1297 * Indicates the view is focused, selected and its window has the focus. 1298 * 1299 * @see #FOCUSED_STATE_SET 1300 * @see #SELECTED_STATE_SET 1301 * @see #WINDOW_FOCUSED_STATE_SET 1302 */ 1303 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1304 /** 1305 * Indicates the view is enabled, focused, selected and its window 1306 * has the focus. 1307 * 1308 * @see #ENABLED_STATE_SET 1309 * @see #FOCUSED_STATE_SET 1310 * @see #SELECTED_STATE_SET 1311 * @see #WINDOW_FOCUSED_STATE_SET 1312 */ 1313 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1314 /** 1315 * Indicates the view is pressed and its window has the focus. 1316 * 1317 * @see #PRESSED_STATE_SET 1318 * @see #WINDOW_FOCUSED_STATE_SET 1319 */ 1320 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1321 /** 1322 * Indicates the view is pressed and selected. 1323 * 1324 * @see #PRESSED_STATE_SET 1325 * @see #SELECTED_STATE_SET 1326 */ 1327 protected static final int[] PRESSED_SELECTED_STATE_SET; 1328 /** 1329 * Indicates the view is pressed, selected and its window has the focus. 1330 * 1331 * @see #PRESSED_STATE_SET 1332 * @see #SELECTED_STATE_SET 1333 * @see #WINDOW_FOCUSED_STATE_SET 1334 */ 1335 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1336 /** 1337 * Indicates the view is pressed and focused. 1338 * 1339 * @see #PRESSED_STATE_SET 1340 * @see #FOCUSED_STATE_SET 1341 */ 1342 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1343 /** 1344 * Indicates the view is pressed, focused and its window has the focus. 1345 * 1346 * @see #PRESSED_STATE_SET 1347 * @see #FOCUSED_STATE_SET 1348 * @see #WINDOW_FOCUSED_STATE_SET 1349 */ 1350 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1351 /** 1352 * Indicates the view is pressed, focused and selected. 1353 * 1354 * @see #PRESSED_STATE_SET 1355 * @see #SELECTED_STATE_SET 1356 * @see #FOCUSED_STATE_SET 1357 */ 1358 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1359 /** 1360 * Indicates the view is pressed, focused, selected and its window has the focus. 1361 * 1362 * @see #PRESSED_STATE_SET 1363 * @see #FOCUSED_STATE_SET 1364 * @see #SELECTED_STATE_SET 1365 * @see #WINDOW_FOCUSED_STATE_SET 1366 */ 1367 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1368 /** 1369 * Indicates the view is pressed and enabled. 1370 * 1371 * @see #PRESSED_STATE_SET 1372 * @see #ENABLED_STATE_SET 1373 */ 1374 protected static final int[] PRESSED_ENABLED_STATE_SET; 1375 /** 1376 * Indicates the view is pressed, enabled and its window has the focus. 1377 * 1378 * @see #PRESSED_STATE_SET 1379 * @see #ENABLED_STATE_SET 1380 * @see #WINDOW_FOCUSED_STATE_SET 1381 */ 1382 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1383 /** 1384 * Indicates the view is pressed, enabled and selected. 1385 * 1386 * @see #PRESSED_STATE_SET 1387 * @see #ENABLED_STATE_SET 1388 * @see #SELECTED_STATE_SET 1389 */ 1390 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1391 /** 1392 * Indicates the view is pressed, enabled, selected and its window has the 1393 * focus. 1394 * 1395 * @see #PRESSED_STATE_SET 1396 * @see #ENABLED_STATE_SET 1397 * @see #SELECTED_STATE_SET 1398 * @see #WINDOW_FOCUSED_STATE_SET 1399 */ 1400 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1401 /** 1402 * Indicates the view is pressed, enabled and focused. 1403 * 1404 * @see #PRESSED_STATE_SET 1405 * @see #ENABLED_STATE_SET 1406 * @see #FOCUSED_STATE_SET 1407 */ 1408 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1409 /** 1410 * Indicates the view is pressed, enabled, focused and its window has the 1411 * focus. 1412 * 1413 * @see #PRESSED_STATE_SET 1414 * @see #ENABLED_STATE_SET 1415 * @see #FOCUSED_STATE_SET 1416 * @see #WINDOW_FOCUSED_STATE_SET 1417 */ 1418 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1419 /** 1420 * Indicates the view is pressed, enabled, focused and selected. 1421 * 1422 * @see #PRESSED_STATE_SET 1423 * @see #ENABLED_STATE_SET 1424 * @see #SELECTED_STATE_SET 1425 * @see #FOCUSED_STATE_SET 1426 */ 1427 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1428 /** 1429 * Indicates the view is pressed, enabled, focused, selected and its window 1430 * has the focus. 1431 * 1432 * @see #PRESSED_STATE_SET 1433 * @see #ENABLED_STATE_SET 1434 * @see #SELECTED_STATE_SET 1435 * @see #FOCUSED_STATE_SET 1436 * @see #WINDOW_FOCUSED_STATE_SET 1437 */ 1438 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1439 1440 /** 1441 * The order here is very important to {@link #getDrawableState()} 1442 */ 1443 private static final int[][] VIEW_STATE_SETS; 1444 1445 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1446 static final int VIEW_STATE_SELECTED = 1 << 1; 1447 static final int VIEW_STATE_FOCUSED = 1 << 2; 1448 static final int VIEW_STATE_ENABLED = 1 << 3; 1449 static final int VIEW_STATE_PRESSED = 1 << 4; 1450 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1451 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1452 static final int VIEW_STATE_HOVERED = 1 << 7; 1453 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1454 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1455 1456 static final int[] VIEW_STATE_IDS = new int[] { 1457 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1458 R.attr.state_selected, VIEW_STATE_SELECTED, 1459 R.attr.state_focused, VIEW_STATE_FOCUSED, 1460 R.attr.state_enabled, VIEW_STATE_ENABLED, 1461 R.attr.state_pressed, VIEW_STATE_PRESSED, 1462 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1463 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1464 R.attr.state_hovered, VIEW_STATE_HOVERED, 1465 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1466 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1467 }; 1468 1469 static { 1470 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1471 throw new IllegalStateException( 1472 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1473 } 1474 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1475 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1476 int viewState = R.styleable.ViewDrawableStates[i]; 1477 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1478 if (VIEW_STATE_IDS[j] == viewState) { 1479 orderedIds[i * 2] = viewState; 1480 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1481 } 1482 } 1483 } 1484 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1485 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1486 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1487 int numBits = Integer.bitCount(i); 1488 int[] set = new int[numBits]; 1489 int pos = 0; 1490 for (int j = 0; j < orderedIds.length; j += 2) { 1491 if ((i & orderedIds[j+1]) != 0) { 1492 set[pos++] = orderedIds[j]; 1493 } 1494 } 1495 VIEW_STATE_SETS[i] = set; 1496 } 1497 1498 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1499 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1500 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1501 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1502 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1503 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1504 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1505 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1506 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1507 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1508 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1509 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1510 | VIEW_STATE_FOCUSED]; 1511 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1512 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1513 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1514 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1515 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1516 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1517 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1518 | VIEW_STATE_ENABLED]; 1519 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1520 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1521 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1522 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1523 | VIEW_STATE_ENABLED]; 1524 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1525 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1526 | VIEW_STATE_ENABLED]; 1527 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1528 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1529 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1530 1531 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1532 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1533 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1534 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1535 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1536 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1537 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1538 | VIEW_STATE_PRESSED]; 1539 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1540 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1541 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1542 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1543 | VIEW_STATE_PRESSED]; 1544 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1545 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1546 | VIEW_STATE_PRESSED]; 1547 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1548 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1549 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1550 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1551 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1552 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1553 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1554 | VIEW_STATE_PRESSED]; 1555 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1556 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1557 | VIEW_STATE_PRESSED]; 1558 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1559 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1560 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1561 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1562 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1563 | VIEW_STATE_PRESSED]; 1564 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1565 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1566 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1567 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1568 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1569 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1570 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1571 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1572 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1573 | VIEW_STATE_PRESSED]; 1574 } 1575 1576 /** 1577 * Accessibility event types that are dispatched for text population. 1578 */ 1579 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1580 AccessibilityEvent.TYPE_VIEW_CLICKED 1581 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1582 | AccessibilityEvent.TYPE_VIEW_SELECTED 1583 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1584 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1585 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1586 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1587 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1588 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1589 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1590 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1591 1592 /** 1593 * Temporary Rect currently for use in setBackground(). This will probably 1594 * be extended in the future to hold our own class with more than just 1595 * a Rect. :) 1596 */ 1597 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1598 1599 /** 1600 * Map used to store views' tags. 1601 */ 1602 private SparseArray<Object> mKeyedTags; 1603 1604 /** 1605 * The next available accessibility id. 1606 */ 1607 private static int sNextAccessibilityViewId; 1608 1609 /** 1610 * The animation currently associated with this view. 1611 * @hide 1612 */ 1613 protected Animation mCurrentAnimation = null; 1614 1615 /** 1616 * Width as measured during measure pass. 1617 * {@hide} 1618 */ 1619 @ViewDebug.ExportedProperty(category = "measurement") 1620 int mMeasuredWidth; 1621 1622 /** 1623 * Height as measured during measure pass. 1624 * {@hide} 1625 */ 1626 @ViewDebug.ExportedProperty(category = "measurement") 1627 int mMeasuredHeight; 1628 1629 /** 1630 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1631 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1632 * its display list. This flag, used only when hw accelerated, allows us to clear the 1633 * flag while retaining this information until it's needed (at getDisplayList() time and 1634 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1635 * 1636 * {@hide} 1637 */ 1638 boolean mRecreateDisplayList = false; 1639 1640 /** 1641 * The view's identifier. 1642 * {@hide} 1643 * 1644 * @see #setId(int) 1645 * @see #getId() 1646 */ 1647 @ViewDebug.ExportedProperty(resolveId = true) 1648 int mID = NO_ID; 1649 1650 /** 1651 * The stable ID of this view for accessibility purposes. 1652 */ 1653 int mAccessibilityViewId = NO_ID; 1654 1655 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1656 1657 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1658 1659 /** 1660 * The view's tag. 1661 * {@hide} 1662 * 1663 * @see #setTag(Object) 1664 * @see #getTag() 1665 */ 1666 protected Object mTag = null; 1667 1668 // for mPrivateFlags: 1669 /** {@hide} */ 1670 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1671 /** {@hide} */ 1672 static final int PFLAG_FOCUSED = 0x00000002; 1673 /** {@hide} */ 1674 static final int PFLAG_SELECTED = 0x00000004; 1675 /** {@hide} */ 1676 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1677 /** {@hide} */ 1678 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1679 /** {@hide} */ 1680 static final int PFLAG_DRAWN = 0x00000020; 1681 /** 1682 * When this flag is set, this view is running an animation on behalf of its 1683 * children and should therefore not cancel invalidate requests, even if they 1684 * lie outside of this view's bounds. 1685 * 1686 * {@hide} 1687 */ 1688 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1689 /** {@hide} */ 1690 static final int PFLAG_SKIP_DRAW = 0x00000080; 1691 /** {@hide} */ 1692 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1693 /** {@hide} */ 1694 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1695 /** {@hide} */ 1696 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1697 /** {@hide} */ 1698 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1699 /** {@hide} */ 1700 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1701 /** {@hide} */ 1702 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1703 1704 private static final int PFLAG_PRESSED = 0x00004000; 1705 1706 /** {@hide} */ 1707 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1708 /** 1709 * Flag used to indicate that this view should be drawn once more (and only once 1710 * more) after its animation has completed. 1711 * {@hide} 1712 */ 1713 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1714 1715 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1716 1717 /** 1718 * Indicates that the View returned true when onSetAlpha() was called and that 1719 * the alpha must be restored. 1720 * {@hide} 1721 */ 1722 static final int PFLAG_ALPHA_SET = 0x00040000; 1723 1724 /** 1725 * Set by {@link #setScrollContainer(boolean)}. 1726 */ 1727 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1728 1729 /** 1730 * Set by {@link #setScrollContainer(boolean)}. 1731 */ 1732 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1733 1734 /** 1735 * View flag indicating whether this view was invalidated (fully or partially.) 1736 * 1737 * @hide 1738 */ 1739 static final int PFLAG_DIRTY = 0x00200000; 1740 1741 /** 1742 * View flag indicating whether this view was invalidated by an opaque 1743 * invalidate request. 1744 * 1745 * @hide 1746 */ 1747 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1748 1749 /** 1750 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1751 * 1752 * @hide 1753 */ 1754 static final int PFLAG_DIRTY_MASK = 0x00600000; 1755 1756 /** 1757 * Indicates whether the background is opaque. 1758 * 1759 * @hide 1760 */ 1761 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1762 1763 /** 1764 * Indicates whether the scrollbars are opaque. 1765 * 1766 * @hide 1767 */ 1768 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1769 1770 /** 1771 * Indicates whether the view is opaque. 1772 * 1773 * @hide 1774 */ 1775 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1776 1777 /** 1778 * Indicates a prepressed state; 1779 * the short time between ACTION_DOWN and recognizing 1780 * a 'real' press. Prepressed is used to recognize quick taps 1781 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1782 * 1783 * @hide 1784 */ 1785 private static final int PFLAG_PREPRESSED = 0x02000000; 1786 1787 /** 1788 * Indicates whether the view is temporarily detached. 1789 * 1790 * @hide 1791 */ 1792 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1793 1794 /** 1795 * Indicates that we should awaken scroll bars once attached 1796 * 1797 * @hide 1798 */ 1799 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1800 1801 /** 1802 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1803 * @hide 1804 */ 1805 private static final int PFLAG_HOVERED = 0x10000000; 1806 1807 /** 1808 * no longer needed, should be reused 1809 */ 1810 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1811 1812 /** {@hide} */ 1813 static final int PFLAG_ACTIVATED = 0x40000000; 1814 1815 /** 1816 * Indicates that this view was specifically invalidated, not just dirtied because some 1817 * child view was invalidated. The flag is used to determine when we need to recreate 1818 * a view's display list (as opposed to just returning a reference to its existing 1819 * display list). 1820 * 1821 * @hide 1822 */ 1823 static final int PFLAG_INVALIDATED = 0x80000000; 1824 1825 /** 1826 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1827 * 1828 * |-------|-------|-------|-------| 1829 * 1 PFLAG2_DRAG_CAN_ACCEPT 1830 * 1 PFLAG2_DRAG_HOVERED 1831 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1832 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1833 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1834 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1835 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1836 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1837 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1838 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1839 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1840 * 111 PFLAG2_TEXT_DIRECTION_MASK 1841 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1842 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1843 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1844 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1845 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1846 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1847 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1848 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1849 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1850 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1851 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1852 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1853 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1854 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1855 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1856 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1857 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1858 * 1 PFLAG2_VIEW_QUICK_REJECTED 1859 * 1 PFLAG2_PADDING_RESOLVED 1860 * 1 PFLAG2_DRAWABLE_RESOLVED 1861 * 1 PFLAG2_HAS_TRANSIENT_STATE 1862 * |-------|-------|-------|-------| 1863 */ 1864 1865 /** 1866 * Indicates that this view has reported that it can accept the current drag's content. 1867 * Cleared when the drag operation concludes. 1868 * @hide 1869 */ 1870 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1871 1872 /** 1873 * Indicates that this view is currently directly under the drag location in a 1874 * drag-and-drop operation involving content that it can accept. Cleared when 1875 * the drag exits the view, or when the drag operation concludes. 1876 * @hide 1877 */ 1878 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1879 1880 /** @hide */ 1881 @IntDef({ 1882 LAYOUT_DIRECTION_LTR, 1883 LAYOUT_DIRECTION_RTL, 1884 LAYOUT_DIRECTION_INHERIT, 1885 LAYOUT_DIRECTION_LOCALE 1886 }) 1887 @Retention(RetentionPolicy.SOURCE) 1888 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1889 public @interface LayoutDir {} 1890 1891 /** @hide */ 1892 @IntDef({ 1893 LAYOUT_DIRECTION_LTR, 1894 LAYOUT_DIRECTION_RTL 1895 }) 1896 @Retention(RetentionPolicy.SOURCE) 1897 public @interface ResolvedLayoutDir {} 1898 1899 /** 1900 * Horizontal layout direction of this view is from Left to Right. 1901 * Use with {@link #setLayoutDirection}. 1902 */ 1903 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1904 1905 /** 1906 * Horizontal layout direction of this view is from Right to Left. 1907 * Use with {@link #setLayoutDirection}. 1908 */ 1909 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1910 1911 /** 1912 * Horizontal layout direction of this view is inherited from its parent. 1913 * Use with {@link #setLayoutDirection}. 1914 */ 1915 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1916 1917 /** 1918 * Horizontal layout direction of this view is from deduced from the default language 1919 * script for the locale. Use with {@link #setLayoutDirection}. 1920 */ 1921 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1922 1923 /** 1924 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1925 * @hide 1926 */ 1927 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1928 1929 /** 1930 * Mask for use with private flags indicating bits used for horizontal layout direction. 1931 * @hide 1932 */ 1933 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1934 1935 /** 1936 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1937 * right-to-left direction. 1938 * @hide 1939 */ 1940 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1941 1942 /** 1943 * Indicates whether the view horizontal layout direction has been resolved. 1944 * @hide 1945 */ 1946 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1947 1948 /** 1949 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1950 * @hide 1951 */ 1952 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1953 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1954 1955 /* 1956 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1957 * flag value. 1958 * @hide 1959 */ 1960 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1961 LAYOUT_DIRECTION_LTR, 1962 LAYOUT_DIRECTION_RTL, 1963 LAYOUT_DIRECTION_INHERIT, 1964 LAYOUT_DIRECTION_LOCALE 1965 }; 1966 1967 /** 1968 * Default horizontal layout direction. 1969 */ 1970 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1971 1972 /** 1973 * Default horizontal layout direction. 1974 * @hide 1975 */ 1976 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1977 1978 /** 1979 * Text direction is inherited thru {@link ViewGroup} 1980 */ 1981 public static final int TEXT_DIRECTION_INHERIT = 0; 1982 1983 /** 1984 * Text direction is using "first strong algorithm". The first strong directional character 1985 * determines the paragraph direction. If there is no strong directional character, the 1986 * paragraph direction is the view's resolved layout direction. 1987 */ 1988 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1989 1990 /** 1991 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1992 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1993 * If there are neither, the paragraph direction is the view's resolved layout direction. 1994 */ 1995 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1996 1997 /** 1998 * Text direction is forced to LTR. 1999 */ 2000 public static final int TEXT_DIRECTION_LTR = 3; 2001 2002 /** 2003 * Text direction is forced to RTL. 2004 */ 2005 public static final int TEXT_DIRECTION_RTL = 4; 2006 2007 /** 2008 * Text direction is coming from the system Locale. 2009 */ 2010 public static final int TEXT_DIRECTION_LOCALE = 5; 2011 2012 /** 2013 * Default text direction is inherited 2014 */ 2015 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2016 2017 /** 2018 * Default resolved text direction 2019 * @hide 2020 */ 2021 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2022 2023 /** 2024 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2025 * @hide 2026 */ 2027 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2028 2029 /** 2030 * Mask for use with private flags indicating bits used for text direction. 2031 * @hide 2032 */ 2033 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2034 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2035 2036 /** 2037 * Array of text direction flags for mapping attribute "textDirection" to correct 2038 * flag value. 2039 * @hide 2040 */ 2041 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2042 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2043 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2044 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2045 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2046 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2047 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2048 }; 2049 2050 /** 2051 * Indicates whether the view text direction has been resolved. 2052 * @hide 2053 */ 2054 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2055 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2056 2057 /** 2058 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2059 * @hide 2060 */ 2061 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2062 2063 /** 2064 * Mask for use with private flags indicating bits used for resolved text direction. 2065 * @hide 2066 */ 2067 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2068 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2069 2070 /** 2071 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2072 * @hide 2073 */ 2074 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2075 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2076 2077 /** @hide */ 2078 @IntDef({ 2079 TEXT_ALIGNMENT_INHERIT, 2080 TEXT_ALIGNMENT_GRAVITY, 2081 TEXT_ALIGNMENT_CENTER, 2082 TEXT_ALIGNMENT_TEXT_START, 2083 TEXT_ALIGNMENT_TEXT_END, 2084 TEXT_ALIGNMENT_VIEW_START, 2085 TEXT_ALIGNMENT_VIEW_END 2086 }) 2087 @Retention(RetentionPolicy.SOURCE) 2088 public @interface TextAlignment {} 2089 2090 /** 2091 * Default text alignment. The text alignment of this View is inherited from its parent. 2092 * Use with {@link #setTextAlignment(int)} 2093 */ 2094 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2095 2096 /** 2097 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2098 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2099 * 2100 * Use with {@link #setTextAlignment(int)} 2101 */ 2102 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2103 2104 /** 2105 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2106 * 2107 * Use with {@link #setTextAlignment(int)} 2108 */ 2109 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2110 2111 /** 2112 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2113 * 2114 * Use with {@link #setTextAlignment(int)} 2115 */ 2116 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2117 2118 /** 2119 * Center the paragraph, e.g. ALIGN_CENTER. 2120 * 2121 * Use with {@link #setTextAlignment(int)} 2122 */ 2123 public static final int TEXT_ALIGNMENT_CENTER = 4; 2124 2125 /** 2126 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2127 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2128 * 2129 * Use with {@link #setTextAlignment(int)} 2130 */ 2131 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2132 2133 /** 2134 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2135 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2136 * 2137 * Use with {@link #setTextAlignment(int)} 2138 */ 2139 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2140 2141 /** 2142 * Default text alignment is inherited 2143 */ 2144 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2145 2146 /** 2147 * Default resolved text alignment 2148 * @hide 2149 */ 2150 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2151 2152 /** 2153 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2154 * @hide 2155 */ 2156 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2157 2158 /** 2159 * Mask for use with private flags indicating bits used for text alignment. 2160 * @hide 2161 */ 2162 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2163 2164 /** 2165 * Array of text direction flags for mapping attribute "textAlignment" to correct 2166 * flag value. 2167 * @hide 2168 */ 2169 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2170 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2171 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2172 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2173 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2174 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2175 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2176 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2177 }; 2178 2179 /** 2180 * Indicates whether the view text alignment has been resolved. 2181 * @hide 2182 */ 2183 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2184 2185 /** 2186 * Bit shift to get the resolved text alignment. 2187 * @hide 2188 */ 2189 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2190 2191 /** 2192 * Mask for use with private flags indicating bits used for text alignment. 2193 * @hide 2194 */ 2195 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2196 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2197 2198 /** 2199 * Indicates whether if the view text alignment has been resolved to gravity 2200 */ 2201 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2202 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2203 2204 // Accessiblity constants for mPrivateFlags2 2205 2206 /** 2207 * Shift for the bits in {@link #mPrivateFlags2} related to the 2208 * "importantForAccessibility" attribute. 2209 */ 2210 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2211 2212 /** 2213 * Automatically determine whether a view is important for accessibility. 2214 */ 2215 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2216 2217 /** 2218 * The view is important for accessibility. 2219 */ 2220 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2221 2222 /** 2223 * The view is not important for accessibility. 2224 */ 2225 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2226 2227 /** 2228 * The view is not important for accessibility, nor are any of its 2229 * descendant views. 2230 */ 2231 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2232 2233 /** 2234 * The default whether the view is important for accessibility. 2235 */ 2236 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2237 2238 /** 2239 * Mask for obtainig the bits which specify how to determine 2240 * whether a view is important for accessibility. 2241 */ 2242 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2243 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2244 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2245 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2246 2247 /** 2248 * Shift for the bits in {@link #mPrivateFlags2} related to the 2249 * "accessibilityLiveRegion" attribute. 2250 */ 2251 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2252 2253 /** 2254 * Live region mode specifying that accessibility services should not 2255 * automatically announce changes to this view. This is the default live 2256 * region mode for most views. 2257 * <p> 2258 * Use with {@link #setAccessibilityLiveRegion(int)}. 2259 */ 2260 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2261 2262 /** 2263 * Live region mode specifying that accessibility services should announce 2264 * changes to this view. 2265 * <p> 2266 * Use with {@link #setAccessibilityLiveRegion(int)}. 2267 */ 2268 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2269 2270 /** 2271 * Live region mode specifying that accessibility services should interrupt 2272 * ongoing speech to immediately announce changes to this view. 2273 * <p> 2274 * Use with {@link #setAccessibilityLiveRegion(int)}. 2275 */ 2276 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2277 2278 /** 2279 * The default whether the view is important for accessibility. 2280 */ 2281 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2282 2283 /** 2284 * Mask for obtaining the bits which specify a view's accessibility live 2285 * region mode. 2286 */ 2287 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2288 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2289 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2290 2291 /** 2292 * Flag indicating whether a view has accessibility focus. 2293 */ 2294 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2295 2296 /** 2297 * Flag whether the accessibility state of the subtree rooted at this view changed. 2298 */ 2299 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2300 2301 /** 2302 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2303 * is used to check whether later changes to the view's transform should invalidate the 2304 * view to force the quickReject test to run again. 2305 */ 2306 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2307 2308 /** 2309 * Flag indicating that start/end padding has been resolved into left/right padding 2310 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2311 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2312 * during measurement. In some special cases this is required such as when an adapter-based 2313 * view measures prospective children without attaching them to a window. 2314 */ 2315 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2316 2317 /** 2318 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2319 */ 2320 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2321 2322 /** 2323 * Indicates that the view is tracking some sort of transient state 2324 * that the app should not need to be aware of, but that the framework 2325 * should take special care to preserve. 2326 */ 2327 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2328 2329 /** 2330 * Group of bits indicating that RTL properties resolution is done. 2331 */ 2332 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2333 PFLAG2_TEXT_DIRECTION_RESOLVED | 2334 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2335 PFLAG2_PADDING_RESOLVED | 2336 PFLAG2_DRAWABLE_RESOLVED; 2337 2338 // There are a couple of flags left in mPrivateFlags2 2339 2340 /* End of masks for mPrivateFlags2 */ 2341 2342 /** 2343 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2344 * 2345 * |-------|-------|-------|-------| 2346 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2347 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2348 * 1 PFLAG3_IS_LAID_OUT 2349 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2350 * 1 PFLAG3_CALLED_SUPER 2351 * |-------|-------|-------|-------| 2352 */ 2353 2354 /** 2355 * Flag indicating that view has a transform animation set on it. This is used to track whether 2356 * an animation is cleared between successive frames, in order to tell the associated 2357 * DisplayList to clear its animation matrix. 2358 */ 2359 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2360 2361 /** 2362 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2363 * animation is cleared between successive frames, in order to tell the associated 2364 * DisplayList to restore its alpha value. 2365 */ 2366 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2367 2368 /** 2369 * Flag indicating that the view has been through at least one layout since it 2370 * was last attached to a window. 2371 */ 2372 static final int PFLAG3_IS_LAID_OUT = 0x4; 2373 2374 /** 2375 * Flag indicating that a call to measure() was skipped and should be done 2376 * instead when layout() is invoked. 2377 */ 2378 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2379 2380 /** 2381 * Flag indicating that an overridden method correctly called down to 2382 * the superclass implementation as required by the API spec. 2383 */ 2384 static final int PFLAG3_CALLED_SUPER = 0x10; 2385 2386 /** 2387 * Flag indicating that we're in the process of applying window insets. 2388 */ 2389 static final int PFLAG3_APPLYING_INSETS = 0x20; 2390 2391 /** 2392 * Flag indicating that we're in the process of fitting system windows using the old method. 2393 */ 2394 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2395 2396 /** 2397 * Flag indicating that nested scrolling is enabled for this view. 2398 * The view will optionally cooperate with views up its parent chain to allow for 2399 * integrated nested scrolling along the same axis. 2400 */ 2401 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2402 2403 /** 2404 * Flag indicating that outline was invalidated and should be rebuilt the next time 2405 * the DisplayList is updated. 2406 */ 2407 static final int PFLAG3_OUTLINE_INVALID = 0x100; 2408 2409 /* End of masks for mPrivateFlags3 */ 2410 2411 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2412 2413 /** 2414 * Always allow a user to over-scroll this view, provided it is a 2415 * view that can scroll. 2416 * 2417 * @see #getOverScrollMode() 2418 * @see #setOverScrollMode(int) 2419 */ 2420 public static final int OVER_SCROLL_ALWAYS = 0; 2421 2422 /** 2423 * Allow a user to over-scroll this view only if the content is large 2424 * enough to meaningfully scroll, provided it is a view that can scroll. 2425 * 2426 * @see #getOverScrollMode() 2427 * @see #setOverScrollMode(int) 2428 */ 2429 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2430 2431 /** 2432 * Never allow a user to over-scroll this view. 2433 * 2434 * @see #getOverScrollMode() 2435 * @see #setOverScrollMode(int) 2436 */ 2437 public static final int OVER_SCROLL_NEVER = 2; 2438 2439 /** 2440 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2441 * requested the system UI (status bar) to be visible (the default). 2442 * 2443 * @see #setSystemUiVisibility(int) 2444 */ 2445 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2446 2447 /** 2448 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2449 * system UI to enter an unobtrusive "low profile" mode. 2450 * 2451 * <p>This is for use in games, book readers, video players, or any other 2452 * "immersive" application where the usual system chrome is deemed too distracting. 2453 * 2454 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2455 * 2456 * @see #setSystemUiVisibility(int) 2457 */ 2458 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2459 2460 /** 2461 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2462 * system navigation be temporarily hidden. 2463 * 2464 * <p>This is an even less obtrusive state than that called for by 2465 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2466 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2467 * those to disappear. This is useful (in conjunction with the 2468 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2469 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2470 * window flags) for displaying content using every last pixel on the display. 2471 * 2472 * <p>There is a limitation: because navigation controls are so important, the least user 2473 * interaction will cause them to reappear immediately. When this happens, both 2474 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2475 * so that both elements reappear at the same time. 2476 * 2477 * @see #setSystemUiVisibility(int) 2478 */ 2479 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2480 2481 /** 2482 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2483 * into the normal fullscreen mode so that its content can take over the screen 2484 * while still allowing the user to interact with the application. 2485 * 2486 * <p>This has the same visual effect as 2487 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2488 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2489 * meaning that non-critical screen decorations (such as the status bar) will be 2490 * hidden while the user is in the View's window, focusing the experience on 2491 * that content. Unlike the window flag, if you are using ActionBar in 2492 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2493 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2494 * hide the action bar. 2495 * 2496 * <p>This approach to going fullscreen is best used over the window flag when 2497 * it is a transient state -- that is, the application does this at certain 2498 * points in its user interaction where it wants to allow the user to focus 2499 * on content, but not as a continuous state. For situations where the application 2500 * would like to simply stay full screen the entire time (such as a game that 2501 * wants to take over the screen), the 2502 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2503 * is usually a better approach. The state set here will be removed by the system 2504 * in various situations (such as the user moving to another application) like 2505 * the other system UI states. 2506 * 2507 * <p>When using this flag, the application should provide some easy facility 2508 * for the user to go out of it. A common example would be in an e-book 2509 * reader, where tapping on the screen brings back whatever screen and UI 2510 * decorations that had been hidden while the user was immersed in reading 2511 * the book. 2512 * 2513 * @see #setSystemUiVisibility(int) 2514 */ 2515 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2516 2517 /** 2518 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2519 * flags, we would like a stable view of the content insets given to 2520 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2521 * will always represent the worst case that the application can expect 2522 * as a continuous state. In the stock Android UI this is the space for 2523 * the system bar, nav bar, and status bar, but not more transient elements 2524 * such as an input method. 2525 * 2526 * The stable layout your UI sees is based on the system UI modes you can 2527 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2528 * then you will get a stable layout for changes of the 2529 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2530 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2531 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2532 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2533 * with a stable layout. (Note that you should avoid using 2534 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2535 * 2536 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2537 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2538 * then a hidden status bar will be considered a "stable" state for purposes 2539 * here. This allows your UI to continually hide the status bar, while still 2540 * using the system UI flags to hide the action bar while still retaining 2541 * a stable layout. Note that changing the window fullscreen flag will never 2542 * provide a stable layout for a clean transition. 2543 * 2544 * <p>If you are using ActionBar in 2545 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2546 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2547 * insets it adds to those given to the application. 2548 */ 2549 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2550 2551 /** 2552 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2553 * to be layed out as if it has requested 2554 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2555 * allows it to avoid artifacts when switching in and out of that mode, at 2556 * the expense that some of its user interface may be covered by screen 2557 * decorations when they are shown. You can perform layout of your inner 2558 * UI elements to account for the navigation system UI through the 2559 * {@link #fitSystemWindows(Rect)} method. 2560 */ 2561 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2562 2563 /** 2564 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2565 * to be layed out as if it has requested 2566 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2567 * allows it to avoid artifacts when switching in and out of that mode, at 2568 * the expense that some of its user interface may be covered by screen 2569 * decorations when they are shown. You can perform layout of your inner 2570 * UI elements to account for non-fullscreen system UI through the 2571 * {@link #fitSystemWindows(Rect)} method. 2572 */ 2573 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2574 2575 /** 2576 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2577 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2578 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2579 * user interaction. 2580 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2581 * has an effect when used in combination with that flag.</p> 2582 */ 2583 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2584 2585 /** 2586 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2587 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2588 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2589 * experience while also hiding the system bars. If this flag is not set, 2590 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2591 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2592 * if the user swipes from the top of the screen. 2593 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2594 * system gestures, such as swiping from the top of the screen. These transient system bars 2595 * will overlay app’s content, may have some degree of transparency, and will automatically 2596 * hide after a short timeout. 2597 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2598 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2599 * with one or both of those flags.</p> 2600 */ 2601 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2602 2603 /** 2604 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2605 */ 2606 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2607 2608 /** 2609 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2610 */ 2611 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2612 2613 /** 2614 * @hide 2615 * 2616 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2617 * out of the public fields to keep the undefined bits out of the developer's way. 2618 * 2619 * Flag to make the status bar not expandable. Unless you also 2620 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2621 */ 2622 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2623 2624 /** 2625 * @hide 2626 * 2627 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2628 * out of the public fields to keep the undefined bits out of the developer's way. 2629 * 2630 * Flag to hide notification icons and scrolling ticker text. 2631 */ 2632 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2633 2634 /** 2635 * @hide 2636 * 2637 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2638 * out of the public fields to keep the undefined bits out of the developer's way. 2639 * 2640 * Flag to disable incoming notification alerts. This will not block 2641 * icons, but it will block sound, vibrating and other visual or aural notifications. 2642 */ 2643 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2644 2645 /** 2646 * @hide 2647 * 2648 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2649 * out of the public fields to keep the undefined bits out of the developer's way. 2650 * 2651 * Flag to hide only the scrolling ticker. Note that 2652 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2653 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2654 */ 2655 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2656 2657 /** 2658 * @hide 2659 * 2660 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2661 * out of the public fields to keep the undefined bits out of the developer's way. 2662 * 2663 * Flag to hide the center system info area. 2664 */ 2665 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2666 2667 /** 2668 * @hide 2669 * 2670 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2671 * out of the public fields to keep the undefined bits out of the developer's way. 2672 * 2673 * Flag to hide only the home button. Don't use this 2674 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2675 */ 2676 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2677 2678 /** 2679 * @hide 2680 * 2681 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2682 * out of the public fields to keep the undefined bits out of the developer's way. 2683 * 2684 * Flag to hide only the back button. Don't use this 2685 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2686 */ 2687 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2688 2689 /** 2690 * @hide 2691 * 2692 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2693 * out of the public fields to keep the undefined bits out of the developer's way. 2694 * 2695 * Flag to hide only the clock. You might use this if your activity has 2696 * its own clock making the status bar's clock redundant. 2697 */ 2698 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2699 2700 /** 2701 * @hide 2702 * 2703 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2704 * out of the public fields to keep the undefined bits out of the developer's way. 2705 * 2706 * Flag to hide only the recent apps button. Don't use this 2707 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2708 */ 2709 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2710 2711 /** 2712 * @hide 2713 * 2714 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2715 * out of the public fields to keep the undefined bits out of the developer's way. 2716 * 2717 * Flag to disable the global search gesture. Don't use this 2718 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2719 */ 2720 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2721 2722 /** 2723 * @hide 2724 * 2725 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2726 * out of the public fields to keep the undefined bits out of the developer's way. 2727 * 2728 * Flag to specify that the status bar is displayed in transient mode. 2729 */ 2730 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2731 2732 /** 2733 * @hide 2734 * 2735 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2736 * out of the public fields to keep the undefined bits out of the developer's way. 2737 * 2738 * Flag to specify that the navigation bar is displayed in transient mode. 2739 */ 2740 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2741 2742 /** 2743 * @hide 2744 * 2745 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2746 * out of the public fields to keep the undefined bits out of the developer's way. 2747 * 2748 * Flag to specify that the hidden status bar would like to be shown. 2749 */ 2750 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2751 2752 /** 2753 * @hide 2754 * 2755 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2756 * out of the public fields to keep the undefined bits out of the developer's way. 2757 * 2758 * Flag to specify that the hidden navigation bar would like to be shown. 2759 */ 2760 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2761 2762 /** 2763 * @hide 2764 * 2765 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2766 * out of the public fields to keep the undefined bits out of the developer's way. 2767 * 2768 * Flag to specify that the status bar is displayed in translucent mode. 2769 */ 2770 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2771 2772 /** 2773 * @hide 2774 * 2775 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2776 * out of the public fields to keep the undefined bits out of the developer's way. 2777 * 2778 * Flag to specify that the navigation bar is displayed in translucent mode. 2779 */ 2780 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2781 2782 /** 2783 * @hide 2784 * 2785 * Whether Recents is visible or not. 2786 */ 2787 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2788 2789 /** 2790 * @hide 2791 * 2792 * Makes system ui transparent. 2793 */ 2794 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2795 2796 /** 2797 * @hide 2798 */ 2799 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2800 2801 /** 2802 * These are the system UI flags that can be cleared by events outside 2803 * of an application. Currently this is just the ability to tap on the 2804 * screen while hiding the navigation bar to have it return. 2805 * @hide 2806 */ 2807 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2808 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2809 | SYSTEM_UI_FLAG_FULLSCREEN; 2810 2811 /** 2812 * Flags that can impact the layout in relation to system UI. 2813 */ 2814 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2815 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2816 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2817 2818 /** @hide */ 2819 @IntDef(flag = true, 2820 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2821 @Retention(RetentionPolicy.SOURCE) 2822 public @interface FindViewFlags {} 2823 2824 /** 2825 * Find views that render the specified text. 2826 * 2827 * @see #findViewsWithText(ArrayList, CharSequence, int) 2828 */ 2829 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2830 2831 /** 2832 * Find find views that contain the specified content description. 2833 * 2834 * @see #findViewsWithText(ArrayList, CharSequence, int) 2835 */ 2836 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2837 2838 /** 2839 * Find views that contain {@link AccessibilityNodeProvider}. Such 2840 * a View is a root of virtual view hierarchy and may contain the searched 2841 * text. If this flag is set Views with providers are automatically 2842 * added and it is a responsibility of the client to call the APIs of 2843 * the provider to determine whether the virtual tree rooted at this View 2844 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2845 * representing the virtual views with this text. 2846 * 2847 * @see #findViewsWithText(ArrayList, CharSequence, int) 2848 * 2849 * @hide 2850 */ 2851 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2852 2853 /** 2854 * The undefined cursor position. 2855 * 2856 * @hide 2857 */ 2858 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2859 2860 /** 2861 * Indicates that the screen has changed state and is now off. 2862 * 2863 * @see #onScreenStateChanged(int) 2864 */ 2865 public static final int SCREEN_STATE_OFF = 0x0; 2866 2867 /** 2868 * Indicates that the screen has changed state and is now on. 2869 * 2870 * @see #onScreenStateChanged(int) 2871 */ 2872 public static final int SCREEN_STATE_ON = 0x1; 2873 2874 /** 2875 * Indicates no axis of view scrolling. 2876 */ 2877 public static final int SCROLL_AXIS_NONE = 0; 2878 2879 /** 2880 * Indicates scrolling along the horizontal axis. 2881 */ 2882 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2883 2884 /** 2885 * Indicates scrolling along the vertical axis. 2886 */ 2887 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2888 2889 /** 2890 * Controls the over-scroll mode for this view. 2891 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2892 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2893 * and {@link #OVER_SCROLL_NEVER}. 2894 */ 2895 private int mOverScrollMode; 2896 2897 /** 2898 * The parent this view is attached to. 2899 * {@hide} 2900 * 2901 * @see #getParent() 2902 */ 2903 protected ViewParent mParent; 2904 2905 /** 2906 * {@hide} 2907 */ 2908 AttachInfo mAttachInfo; 2909 2910 /** 2911 * {@hide} 2912 */ 2913 @ViewDebug.ExportedProperty(flagMapping = { 2914 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2915 name = "FORCE_LAYOUT"), 2916 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2917 name = "LAYOUT_REQUIRED"), 2918 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2919 name = "DRAWING_CACHE_INVALID", outputIf = false), 2920 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2921 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2922 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2923 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2924 }, formatToHexString = true) 2925 int mPrivateFlags; 2926 int mPrivateFlags2; 2927 int mPrivateFlags3; 2928 2929 /** 2930 * This view's request for the visibility of the status bar. 2931 * @hide 2932 */ 2933 @ViewDebug.ExportedProperty(flagMapping = { 2934 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2935 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2936 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2937 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2938 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2939 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2940 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2941 equals = SYSTEM_UI_FLAG_VISIBLE, 2942 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2943 }, formatToHexString = true) 2944 int mSystemUiVisibility; 2945 2946 /** 2947 * Reference count for transient state. 2948 * @see #setHasTransientState(boolean) 2949 */ 2950 int mTransientStateCount = 0; 2951 2952 /** 2953 * Count of how many windows this view has been attached to. 2954 */ 2955 int mWindowAttachCount; 2956 2957 /** 2958 * The layout parameters associated with this view and used by the parent 2959 * {@link android.view.ViewGroup} to determine how this view should be 2960 * laid out. 2961 * {@hide} 2962 */ 2963 protected ViewGroup.LayoutParams mLayoutParams; 2964 2965 /** 2966 * The view flags hold various views states. 2967 * {@hide} 2968 */ 2969 @ViewDebug.ExportedProperty(formatToHexString = true) 2970 int mViewFlags; 2971 2972 static class TransformationInfo { 2973 /** 2974 * The transform matrix for the View. This transform is calculated internally 2975 * based on the translation, rotation, and scale properties. 2976 * 2977 * Do *not* use this variable directly; instead call getMatrix(), which will 2978 * load the value from the View's RenderNode. 2979 */ 2980 private final Matrix mMatrix = new Matrix(); 2981 2982 /** 2983 * The inverse transform matrix for the View. This transform is calculated 2984 * internally based on the translation, rotation, and scale properties. 2985 * 2986 * Do *not* use this variable directly; instead call getInverseMatrix(), 2987 * which will load the value from the View's RenderNode. 2988 */ 2989 private Matrix mInverseMatrix; 2990 2991 /** 2992 * The opacity of the View. This is a value from 0 to 1, where 0 means 2993 * completely transparent and 1 means completely opaque. 2994 */ 2995 @ViewDebug.ExportedProperty 2996 float mAlpha = 1f; 2997 2998 /** 2999 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3000 * property only used by transitions, which is composited with the other alpha 3001 * values to calculate the final visual alpha value. 3002 */ 3003 float mTransitionAlpha = 1f; 3004 } 3005 3006 TransformationInfo mTransformationInfo; 3007 3008 /** 3009 * Current clip bounds. to which all drawing of this view are constrained. 3010 */ 3011 Rect mClipBounds = null; 3012 3013 private boolean mLastIsOpaque; 3014 3015 /** 3016 * The distance in pixels from the left edge of this view's parent 3017 * to the left edge of this view. 3018 * {@hide} 3019 */ 3020 @ViewDebug.ExportedProperty(category = "layout") 3021 protected int mLeft; 3022 /** 3023 * The distance in pixels from the left edge of this view's parent 3024 * to the right edge of this view. 3025 * {@hide} 3026 */ 3027 @ViewDebug.ExportedProperty(category = "layout") 3028 protected int mRight; 3029 /** 3030 * The distance in pixels from the top edge of this view's parent 3031 * to the top edge of this view. 3032 * {@hide} 3033 */ 3034 @ViewDebug.ExportedProperty(category = "layout") 3035 protected int mTop; 3036 /** 3037 * The distance in pixels from the top edge of this view's parent 3038 * to the bottom edge of this view. 3039 * {@hide} 3040 */ 3041 @ViewDebug.ExportedProperty(category = "layout") 3042 protected int mBottom; 3043 3044 /** 3045 * The offset, in pixels, by which the content of this view is scrolled 3046 * horizontally. 3047 * {@hide} 3048 */ 3049 @ViewDebug.ExportedProperty(category = "scrolling") 3050 protected int mScrollX; 3051 /** 3052 * The offset, in pixels, by which the content of this view is scrolled 3053 * vertically. 3054 * {@hide} 3055 */ 3056 @ViewDebug.ExportedProperty(category = "scrolling") 3057 protected int mScrollY; 3058 3059 /** 3060 * The left padding in pixels, that is the distance in pixels between the 3061 * left edge of this view and the left edge of its content. 3062 * {@hide} 3063 */ 3064 @ViewDebug.ExportedProperty(category = "padding") 3065 protected int mPaddingLeft = 0; 3066 /** 3067 * The right padding in pixels, that is the distance in pixels between the 3068 * right edge of this view and the right edge of its content. 3069 * {@hide} 3070 */ 3071 @ViewDebug.ExportedProperty(category = "padding") 3072 protected int mPaddingRight = 0; 3073 /** 3074 * The top padding in pixels, that is the distance in pixels between the 3075 * top edge of this view and the top edge of its content. 3076 * {@hide} 3077 */ 3078 @ViewDebug.ExportedProperty(category = "padding") 3079 protected int mPaddingTop; 3080 /** 3081 * The bottom padding in pixels, that is the distance in pixels between the 3082 * bottom edge of this view and the bottom edge of its content. 3083 * {@hide} 3084 */ 3085 @ViewDebug.ExportedProperty(category = "padding") 3086 protected int mPaddingBottom; 3087 3088 /** 3089 * The layout insets in pixels, that is the distance in pixels between the 3090 * visible edges of this view its bounds. 3091 */ 3092 private Insets mLayoutInsets; 3093 3094 /** 3095 * Briefly describes the view and is primarily used for accessibility support. 3096 */ 3097 private CharSequence mContentDescription; 3098 3099 /** 3100 * Specifies the id of a view for which this view serves as a label for 3101 * accessibility purposes. 3102 */ 3103 private int mLabelForId = View.NO_ID; 3104 3105 /** 3106 * Predicate for matching labeled view id with its label for 3107 * accessibility purposes. 3108 */ 3109 private MatchLabelForPredicate mMatchLabelForPredicate; 3110 3111 /** 3112 * Specifies a view before which this one is visited in accessibility traversal. 3113 */ 3114 private int mAccessibilityTraversalBeforeId = NO_ID; 3115 3116 /** 3117 * Specifies a view after which this one is visited in accessibility traversal. 3118 */ 3119 private int mAccessibilityTraversalAfterId = NO_ID; 3120 3121 /** 3122 * Predicate for matching a view by its id. 3123 */ 3124 private MatchIdPredicate mMatchIdPredicate; 3125 3126 /** 3127 * Cache the paddingRight set by the user to append to the scrollbar's size. 3128 * 3129 * @hide 3130 */ 3131 @ViewDebug.ExportedProperty(category = "padding") 3132 protected int mUserPaddingRight; 3133 3134 /** 3135 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3136 * 3137 * @hide 3138 */ 3139 @ViewDebug.ExportedProperty(category = "padding") 3140 protected int mUserPaddingBottom; 3141 3142 /** 3143 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3144 * 3145 * @hide 3146 */ 3147 @ViewDebug.ExportedProperty(category = "padding") 3148 protected int mUserPaddingLeft; 3149 3150 /** 3151 * Cache the paddingStart set by the user to append to the scrollbar's size. 3152 * 3153 */ 3154 @ViewDebug.ExportedProperty(category = "padding") 3155 int mUserPaddingStart; 3156 3157 /** 3158 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3159 * 3160 */ 3161 @ViewDebug.ExportedProperty(category = "padding") 3162 int mUserPaddingEnd; 3163 3164 /** 3165 * Cache initial left padding. 3166 * 3167 * @hide 3168 */ 3169 int mUserPaddingLeftInitial; 3170 3171 /** 3172 * Cache initial right padding. 3173 * 3174 * @hide 3175 */ 3176 int mUserPaddingRightInitial; 3177 3178 /** 3179 * Default undefined padding 3180 */ 3181 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3182 3183 /** 3184 * Cache if a left padding has been defined 3185 */ 3186 private boolean mLeftPaddingDefined = false; 3187 3188 /** 3189 * Cache if a right padding has been defined 3190 */ 3191 private boolean mRightPaddingDefined = false; 3192 3193 /** 3194 * @hide 3195 */ 3196 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3197 /** 3198 * @hide 3199 */ 3200 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3201 3202 private LongSparseLongArray mMeasureCache; 3203 3204 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3205 private Drawable mBackground; 3206 private TintInfo mBackgroundTint; 3207 3208 /** 3209 * RenderNode used for backgrounds. 3210 * <p> 3211 * When non-null and valid, this is expected to contain an up-to-date copy 3212 * of the background drawable. It is cleared on temporary detach, and reset 3213 * on cleanup. 3214 */ 3215 private RenderNode mBackgroundRenderNode; 3216 3217 private int mBackgroundResource; 3218 private boolean mBackgroundSizeChanged; 3219 3220 private String mTransitionName; 3221 3222 private static class TintInfo { 3223 ColorStateList mTintList; 3224 PorterDuff.Mode mTintMode; 3225 boolean mHasTintMode; 3226 boolean mHasTintList; 3227 } 3228 3229 static class ListenerInfo { 3230 /** 3231 * Listener used to dispatch focus change events. 3232 * This field should be made private, so it is hidden from the SDK. 3233 * {@hide} 3234 */ 3235 protected OnFocusChangeListener mOnFocusChangeListener; 3236 3237 /** 3238 * Listeners for layout change events. 3239 */ 3240 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3241 3242 protected OnScrollChangeListener mOnScrollChangeListener; 3243 3244 /** 3245 * Listeners for attach events. 3246 */ 3247 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3248 3249 /** 3250 * Listener used to dispatch click events. 3251 * This field should be made private, so it is hidden from the SDK. 3252 * {@hide} 3253 */ 3254 public OnClickListener mOnClickListener; 3255 3256 /** 3257 * Listener used to dispatch long click events. 3258 * This field should be made private, so it is hidden from the SDK. 3259 * {@hide} 3260 */ 3261 protected OnLongClickListener mOnLongClickListener; 3262 3263 /** 3264 * Listener used to build the context menu. 3265 * This field should be made private, so it is hidden from the SDK. 3266 * {@hide} 3267 */ 3268 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3269 3270 private OnKeyListener mOnKeyListener; 3271 3272 private OnTouchListener mOnTouchListener; 3273 3274 private OnHoverListener mOnHoverListener; 3275 3276 private OnGenericMotionListener mOnGenericMotionListener; 3277 3278 private OnDragListener mOnDragListener; 3279 3280 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3281 3282 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3283 } 3284 3285 ListenerInfo mListenerInfo; 3286 3287 /** 3288 * The application environment this view lives in. 3289 * This field should be made private, so it is hidden from the SDK. 3290 * {@hide} 3291 */ 3292 @ViewDebug.ExportedProperty(deepExport = true) 3293 protected Context mContext; 3294 3295 private final Resources mResources; 3296 3297 private ScrollabilityCache mScrollCache; 3298 3299 private int[] mDrawableState = null; 3300 3301 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3302 3303 /** 3304 * Animator that automatically runs based on state changes. 3305 */ 3306 private StateListAnimator mStateListAnimator; 3307 3308 /** 3309 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3310 * the user may specify which view to go to next. 3311 */ 3312 private int mNextFocusLeftId = View.NO_ID; 3313 3314 /** 3315 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3316 * the user may specify which view to go to next. 3317 */ 3318 private int mNextFocusRightId = View.NO_ID; 3319 3320 /** 3321 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3322 * the user may specify which view to go to next. 3323 */ 3324 private int mNextFocusUpId = View.NO_ID; 3325 3326 /** 3327 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3328 * the user may specify which view to go to next. 3329 */ 3330 private int mNextFocusDownId = View.NO_ID; 3331 3332 /** 3333 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3334 * the user may specify which view to go to next. 3335 */ 3336 int mNextFocusForwardId = View.NO_ID; 3337 3338 private CheckForLongPress mPendingCheckForLongPress; 3339 private CheckForTap mPendingCheckForTap = null; 3340 private PerformClick mPerformClick; 3341 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3342 3343 private UnsetPressedState mUnsetPressedState; 3344 3345 /** 3346 * Whether the long press's action has been invoked. The tap's action is invoked on the 3347 * up event while a long press is invoked as soon as the long press duration is reached, so 3348 * a long press could be performed before the tap is checked, in which case the tap's action 3349 * should not be invoked. 3350 */ 3351 private boolean mHasPerformedLongPress; 3352 3353 /** 3354 * The minimum height of the view. We'll try our best to have the height 3355 * of this view to at least this amount. 3356 */ 3357 @ViewDebug.ExportedProperty(category = "measurement") 3358 private int mMinHeight; 3359 3360 /** 3361 * The minimum width of the view. We'll try our best to have the width 3362 * of this view to at least this amount. 3363 */ 3364 @ViewDebug.ExportedProperty(category = "measurement") 3365 private int mMinWidth; 3366 3367 /** 3368 * The delegate to handle touch events that are physically in this view 3369 * but should be handled by another view. 3370 */ 3371 private TouchDelegate mTouchDelegate = null; 3372 3373 /** 3374 * Solid color to use as a background when creating the drawing cache. Enables 3375 * the cache to use 16 bit bitmaps instead of 32 bit. 3376 */ 3377 private int mDrawingCacheBackgroundColor = 0; 3378 3379 /** 3380 * Special tree observer used when mAttachInfo is null. 3381 */ 3382 private ViewTreeObserver mFloatingTreeObserver; 3383 3384 /** 3385 * Cache the touch slop from the context that created the view. 3386 */ 3387 private int mTouchSlop; 3388 3389 /** 3390 * Object that handles automatic animation of view properties. 3391 */ 3392 private ViewPropertyAnimator mAnimator = null; 3393 3394 /** 3395 * Flag indicating that a drag can cross window boundaries. When 3396 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3397 * with this flag set, all visible applications will be able to participate 3398 * in the drag operation and receive the dragged content. 3399 * 3400 * @hide 3401 */ 3402 public static final int DRAG_FLAG_GLOBAL = 1; 3403 3404 /** 3405 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3406 */ 3407 private float mVerticalScrollFactor; 3408 3409 /** 3410 * Position of the vertical scroll bar. 3411 */ 3412 private int mVerticalScrollbarPosition; 3413 3414 /** 3415 * Position the scroll bar at the default position as determined by the system. 3416 */ 3417 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3418 3419 /** 3420 * Position the scroll bar along the left edge. 3421 */ 3422 public static final int SCROLLBAR_POSITION_LEFT = 1; 3423 3424 /** 3425 * Position the scroll bar along the right edge. 3426 */ 3427 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3428 3429 /** 3430 * Indicates that the view does not have a layer. 3431 * 3432 * @see #getLayerType() 3433 * @see #setLayerType(int, android.graphics.Paint) 3434 * @see #LAYER_TYPE_SOFTWARE 3435 * @see #LAYER_TYPE_HARDWARE 3436 */ 3437 public static final int LAYER_TYPE_NONE = 0; 3438 3439 /** 3440 * <p>Indicates that the view has a software layer. A software layer is backed 3441 * by a bitmap and causes the view to be rendered using Android's software 3442 * rendering pipeline, even if hardware acceleration is enabled.</p> 3443 * 3444 * <p>Software layers have various usages:</p> 3445 * <p>When the application is not using hardware acceleration, a software layer 3446 * is useful to apply a specific color filter and/or blending mode and/or 3447 * translucency to a view and all its children.</p> 3448 * <p>When the application is using hardware acceleration, a software layer 3449 * is useful to render drawing primitives not supported by the hardware 3450 * accelerated pipeline. It can also be used to cache a complex view tree 3451 * into a texture and reduce the complexity of drawing operations. For instance, 3452 * when animating a complex view tree with a translation, a software layer can 3453 * be used to render the view tree only once.</p> 3454 * <p>Software layers should be avoided when the affected view tree updates 3455 * often. Every update will require to re-render the software layer, which can 3456 * potentially be slow (particularly when hardware acceleration is turned on 3457 * since the layer will have to be uploaded into a hardware texture after every 3458 * update.)</p> 3459 * 3460 * @see #getLayerType() 3461 * @see #setLayerType(int, android.graphics.Paint) 3462 * @see #LAYER_TYPE_NONE 3463 * @see #LAYER_TYPE_HARDWARE 3464 */ 3465 public static final int LAYER_TYPE_SOFTWARE = 1; 3466 3467 /** 3468 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3469 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3470 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3471 * rendering pipeline, but only if hardware acceleration is turned on for the 3472 * view hierarchy. When hardware acceleration is turned off, hardware layers 3473 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3474 * 3475 * <p>A hardware layer is useful to apply a specific color filter and/or 3476 * blending mode and/or translucency to a view and all its children.</p> 3477 * <p>A hardware layer can be used to cache a complex view tree into a 3478 * texture and reduce the complexity of drawing operations. For instance, 3479 * when animating a complex view tree with a translation, a hardware layer can 3480 * be used to render the view tree only once.</p> 3481 * <p>A hardware layer can also be used to increase the rendering quality when 3482 * rotation transformations are applied on a view. It can also be used to 3483 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3484 * 3485 * @see #getLayerType() 3486 * @see #setLayerType(int, android.graphics.Paint) 3487 * @see #LAYER_TYPE_NONE 3488 * @see #LAYER_TYPE_SOFTWARE 3489 */ 3490 public static final int LAYER_TYPE_HARDWARE = 2; 3491 3492 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3493 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3494 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3495 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3496 }) 3497 int mLayerType = LAYER_TYPE_NONE; 3498 Paint mLayerPaint; 3499 3500 /** 3501 * Set to true when drawing cache is enabled and cannot be created. 3502 * 3503 * @hide 3504 */ 3505 public boolean mCachingFailed; 3506 private Bitmap mDrawingCache; 3507 private Bitmap mUnscaledDrawingCache; 3508 3509 /** 3510 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3511 * <p> 3512 * When non-null and valid, this is expected to contain an up-to-date copy 3513 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3514 * cleanup. 3515 */ 3516 final RenderNode mRenderNode; 3517 3518 /** 3519 * Set to true when the view is sending hover accessibility events because it 3520 * is the innermost hovered view. 3521 */ 3522 private boolean mSendingHoverAccessibilityEvents; 3523 3524 /** 3525 * Delegate for injecting accessibility functionality. 3526 */ 3527 AccessibilityDelegate mAccessibilityDelegate; 3528 3529 /** 3530 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3531 * and add/remove objects to/from the overlay directly through the Overlay methods. 3532 */ 3533 ViewOverlay mOverlay; 3534 3535 /** 3536 * The currently active parent view for receiving delegated nested scrolling events. 3537 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3538 * by {@link #stopNestedScroll()} at the same point where we clear 3539 * requestDisallowInterceptTouchEvent. 3540 */ 3541 private ViewParent mNestedScrollingParent; 3542 3543 /** 3544 * Consistency verifier for debugging purposes. 3545 * @hide 3546 */ 3547 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3548 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3549 new InputEventConsistencyVerifier(this, 0) : null; 3550 3551 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3552 3553 private int[] mTempNestedScrollConsumed; 3554 3555 /** 3556 * An overlay is going to draw this View instead of being drawn as part of this 3557 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3558 * when this view is invalidated. 3559 */ 3560 GhostView mGhostView; 3561 3562 /** 3563 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3564 * @hide 3565 */ 3566 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3567 public String[] mAttributes; 3568 3569 /** 3570 * Maps a Resource id to its name. 3571 */ 3572 private static SparseArray<String> mAttributeMap; 3573 3574 /** 3575 * Simple constructor to use when creating a view from code. 3576 * 3577 * @param context The Context the view is running in, through which it can 3578 * access the current theme, resources, etc. 3579 */ 3580 public View(Context context) { 3581 mContext = context; 3582 mResources = context != null ? context.getResources() : null; 3583 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3584 // Set some flags defaults 3585 mPrivateFlags2 = 3586 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3587 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3588 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3589 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3590 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3591 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3592 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3593 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3594 mUserPaddingStart = UNDEFINED_PADDING; 3595 mUserPaddingEnd = UNDEFINED_PADDING; 3596 mRenderNode = RenderNode.create(getClass().getName(), this); 3597 3598 if (!sCompatibilityDone && context != null) { 3599 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3600 3601 // Older apps may need this compatibility hack for measurement. 3602 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3603 3604 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3605 // of whether a layout was requested on that View. 3606 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3607 3608 sCompatibilityDone = true; 3609 } 3610 } 3611 3612 /** 3613 * Constructor that is called when inflating a view from XML. This is called 3614 * when a view is being constructed from an XML file, supplying attributes 3615 * that were specified in the XML file. This version uses a default style of 3616 * 0, so the only attribute values applied are those in the Context's Theme 3617 * and the given AttributeSet. 3618 * 3619 * <p> 3620 * The method onFinishInflate() will be called after all children have been 3621 * added. 3622 * 3623 * @param context The Context the view is running in, through which it can 3624 * access the current theme, resources, etc. 3625 * @param attrs The attributes of the XML tag that is inflating the view. 3626 * @see #View(Context, AttributeSet, int) 3627 */ 3628 public View(Context context, AttributeSet attrs) { 3629 this(context, attrs, 0); 3630 } 3631 3632 /** 3633 * Perform inflation from XML and apply a class-specific base style from a 3634 * theme attribute. This constructor of View allows subclasses to use their 3635 * own base style when they are inflating. For example, a Button class's 3636 * constructor would call this version of the super class constructor and 3637 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3638 * allows the theme's button style to modify all of the base view attributes 3639 * (in particular its background) as well as the Button class's attributes. 3640 * 3641 * @param context The Context the view is running in, through which it can 3642 * access the current theme, resources, etc. 3643 * @param attrs The attributes of the XML tag that is inflating the view. 3644 * @param defStyleAttr An attribute in the current theme that contains a 3645 * reference to a style resource that supplies default values for 3646 * the view. Can be 0 to not look for defaults. 3647 * @see #View(Context, AttributeSet) 3648 */ 3649 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3650 this(context, attrs, defStyleAttr, 0); 3651 } 3652 3653 /** 3654 * Perform inflation from XML and apply a class-specific base style from a 3655 * theme attribute or style resource. This constructor of View allows 3656 * subclasses to use their own base style when they are inflating. 3657 * <p> 3658 * When determining the final value of a particular attribute, there are 3659 * four inputs that come into play: 3660 * <ol> 3661 * <li>Any attribute values in the given AttributeSet. 3662 * <li>The style resource specified in the AttributeSet (named "style"). 3663 * <li>The default style specified by <var>defStyleAttr</var>. 3664 * <li>The default style specified by <var>defStyleRes</var>. 3665 * <li>The base values in this theme. 3666 * </ol> 3667 * <p> 3668 * Each of these inputs is considered in-order, with the first listed taking 3669 * precedence over the following ones. In other words, if in the 3670 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3671 * , then the button's text will <em>always</em> be black, regardless of 3672 * what is specified in any of the styles. 3673 * 3674 * @param context The Context the view is running in, through which it can 3675 * access the current theme, resources, etc. 3676 * @param attrs The attributes of the XML tag that is inflating the view. 3677 * @param defStyleAttr An attribute in the current theme that contains a 3678 * reference to a style resource that supplies default values for 3679 * the view. Can be 0 to not look for defaults. 3680 * @param defStyleRes A resource identifier of a style resource that 3681 * supplies default values for the view, used only if 3682 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3683 * to not look for defaults. 3684 * @see #View(Context, AttributeSet, int) 3685 */ 3686 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3687 this(context); 3688 3689 final TypedArray a = context.obtainStyledAttributes( 3690 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3691 3692 if (mDebugViewAttributes) { 3693 saveAttributeData(attrs, a); 3694 } 3695 3696 Drawable background = null; 3697 3698 int leftPadding = -1; 3699 int topPadding = -1; 3700 int rightPadding = -1; 3701 int bottomPadding = -1; 3702 int startPadding = UNDEFINED_PADDING; 3703 int endPadding = UNDEFINED_PADDING; 3704 3705 int padding = -1; 3706 3707 int viewFlagValues = 0; 3708 int viewFlagMasks = 0; 3709 3710 boolean setScrollContainer = false; 3711 3712 int x = 0; 3713 int y = 0; 3714 3715 float tx = 0; 3716 float ty = 0; 3717 float tz = 0; 3718 float elevation = 0; 3719 float rotation = 0; 3720 float rotationX = 0; 3721 float rotationY = 0; 3722 float sx = 1f; 3723 float sy = 1f; 3724 boolean transformSet = false; 3725 3726 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3727 int overScrollMode = mOverScrollMode; 3728 boolean initializeScrollbars = false; 3729 3730 boolean startPaddingDefined = false; 3731 boolean endPaddingDefined = false; 3732 boolean leftPaddingDefined = false; 3733 boolean rightPaddingDefined = false; 3734 3735 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3736 3737 final int N = a.getIndexCount(); 3738 for (int i = 0; i < N; i++) { 3739 int attr = a.getIndex(i); 3740 switch (attr) { 3741 case com.android.internal.R.styleable.View_background: 3742 background = a.getDrawable(attr); 3743 break; 3744 case com.android.internal.R.styleable.View_padding: 3745 padding = a.getDimensionPixelSize(attr, -1); 3746 mUserPaddingLeftInitial = padding; 3747 mUserPaddingRightInitial = padding; 3748 leftPaddingDefined = true; 3749 rightPaddingDefined = true; 3750 break; 3751 case com.android.internal.R.styleable.View_paddingLeft: 3752 leftPadding = a.getDimensionPixelSize(attr, -1); 3753 mUserPaddingLeftInitial = leftPadding; 3754 leftPaddingDefined = true; 3755 break; 3756 case com.android.internal.R.styleable.View_paddingTop: 3757 topPadding = a.getDimensionPixelSize(attr, -1); 3758 break; 3759 case com.android.internal.R.styleable.View_paddingRight: 3760 rightPadding = a.getDimensionPixelSize(attr, -1); 3761 mUserPaddingRightInitial = rightPadding; 3762 rightPaddingDefined = true; 3763 break; 3764 case com.android.internal.R.styleable.View_paddingBottom: 3765 bottomPadding = a.getDimensionPixelSize(attr, -1); 3766 break; 3767 case com.android.internal.R.styleable.View_paddingStart: 3768 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3769 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3770 break; 3771 case com.android.internal.R.styleable.View_paddingEnd: 3772 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3773 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3774 break; 3775 case com.android.internal.R.styleable.View_scrollX: 3776 x = a.getDimensionPixelOffset(attr, 0); 3777 break; 3778 case com.android.internal.R.styleable.View_scrollY: 3779 y = a.getDimensionPixelOffset(attr, 0); 3780 break; 3781 case com.android.internal.R.styleable.View_alpha: 3782 setAlpha(a.getFloat(attr, 1f)); 3783 break; 3784 case com.android.internal.R.styleable.View_transformPivotX: 3785 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3786 break; 3787 case com.android.internal.R.styleable.View_transformPivotY: 3788 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3789 break; 3790 case com.android.internal.R.styleable.View_translationX: 3791 tx = a.getDimensionPixelOffset(attr, 0); 3792 transformSet = true; 3793 break; 3794 case com.android.internal.R.styleable.View_translationY: 3795 ty = a.getDimensionPixelOffset(attr, 0); 3796 transformSet = true; 3797 break; 3798 case com.android.internal.R.styleable.View_translationZ: 3799 tz = a.getDimensionPixelOffset(attr, 0); 3800 transformSet = true; 3801 break; 3802 case com.android.internal.R.styleable.View_elevation: 3803 elevation = a.getDimensionPixelOffset(attr, 0); 3804 transformSet = true; 3805 break; 3806 case com.android.internal.R.styleable.View_rotation: 3807 rotation = a.getFloat(attr, 0); 3808 transformSet = true; 3809 break; 3810 case com.android.internal.R.styleable.View_rotationX: 3811 rotationX = a.getFloat(attr, 0); 3812 transformSet = true; 3813 break; 3814 case com.android.internal.R.styleable.View_rotationY: 3815 rotationY = a.getFloat(attr, 0); 3816 transformSet = true; 3817 break; 3818 case com.android.internal.R.styleable.View_scaleX: 3819 sx = a.getFloat(attr, 1f); 3820 transformSet = true; 3821 break; 3822 case com.android.internal.R.styleable.View_scaleY: 3823 sy = a.getFloat(attr, 1f); 3824 transformSet = true; 3825 break; 3826 case com.android.internal.R.styleable.View_id: 3827 mID = a.getResourceId(attr, NO_ID); 3828 break; 3829 case com.android.internal.R.styleable.View_tag: 3830 mTag = a.getText(attr); 3831 break; 3832 case com.android.internal.R.styleable.View_fitsSystemWindows: 3833 if (a.getBoolean(attr, false)) { 3834 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3835 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3836 } 3837 break; 3838 case com.android.internal.R.styleable.View_focusable: 3839 if (a.getBoolean(attr, false)) { 3840 viewFlagValues |= FOCUSABLE; 3841 viewFlagMasks |= FOCUSABLE_MASK; 3842 } 3843 break; 3844 case com.android.internal.R.styleable.View_focusableInTouchMode: 3845 if (a.getBoolean(attr, false)) { 3846 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3847 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3848 } 3849 break; 3850 case com.android.internal.R.styleable.View_clickable: 3851 if (a.getBoolean(attr, false)) { 3852 viewFlagValues |= CLICKABLE; 3853 viewFlagMasks |= CLICKABLE; 3854 } 3855 break; 3856 case com.android.internal.R.styleable.View_longClickable: 3857 if (a.getBoolean(attr, false)) { 3858 viewFlagValues |= LONG_CLICKABLE; 3859 viewFlagMasks |= LONG_CLICKABLE; 3860 } 3861 break; 3862 case com.android.internal.R.styleable.View_saveEnabled: 3863 if (!a.getBoolean(attr, true)) { 3864 viewFlagValues |= SAVE_DISABLED; 3865 viewFlagMasks |= SAVE_DISABLED_MASK; 3866 } 3867 break; 3868 case com.android.internal.R.styleable.View_duplicateParentState: 3869 if (a.getBoolean(attr, false)) { 3870 viewFlagValues |= DUPLICATE_PARENT_STATE; 3871 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3872 } 3873 break; 3874 case com.android.internal.R.styleable.View_visibility: 3875 final int visibility = a.getInt(attr, 0); 3876 if (visibility != 0) { 3877 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3878 viewFlagMasks |= VISIBILITY_MASK; 3879 } 3880 break; 3881 case com.android.internal.R.styleable.View_layoutDirection: 3882 // Clear any layout direction flags (included resolved bits) already set 3883 mPrivateFlags2 &= 3884 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3885 // Set the layout direction flags depending on the value of the attribute 3886 final int layoutDirection = a.getInt(attr, -1); 3887 final int value = (layoutDirection != -1) ? 3888 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3889 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3890 break; 3891 case com.android.internal.R.styleable.View_drawingCacheQuality: 3892 final int cacheQuality = a.getInt(attr, 0); 3893 if (cacheQuality != 0) { 3894 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3895 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3896 } 3897 break; 3898 case com.android.internal.R.styleable.View_contentDescription: 3899 setContentDescription(a.getString(attr)); 3900 break; 3901 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 3902 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 3903 break; 3904 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 3905 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 3906 break; 3907 case com.android.internal.R.styleable.View_labelFor: 3908 setLabelFor(a.getResourceId(attr, NO_ID)); 3909 break; 3910 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3911 if (!a.getBoolean(attr, true)) { 3912 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3913 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3914 } 3915 break; 3916 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3917 if (!a.getBoolean(attr, true)) { 3918 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3919 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3920 } 3921 break; 3922 case R.styleable.View_scrollbars: 3923 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3924 if (scrollbars != SCROLLBARS_NONE) { 3925 viewFlagValues |= scrollbars; 3926 viewFlagMasks |= SCROLLBARS_MASK; 3927 initializeScrollbars = true; 3928 } 3929 break; 3930 //noinspection deprecation 3931 case R.styleable.View_fadingEdge: 3932 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3933 // Ignore the attribute starting with ICS 3934 break; 3935 } 3936 // With builds < ICS, fall through and apply fading edges 3937 case R.styleable.View_requiresFadingEdge: 3938 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3939 if (fadingEdge != FADING_EDGE_NONE) { 3940 viewFlagValues |= fadingEdge; 3941 viewFlagMasks |= FADING_EDGE_MASK; 3942 initializeFadingEdgeInternal(a); 3943 } 3944 break; 3945 case R.styleable.View_scrollbarStyle: 3946 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3947 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3948 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3949 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3950 } 3951 break; 3952 case R.styleable.View_isScrollContainer: 3953 setScrollContainer = true; 3954 if (a.getBoolean(attr, false)) { 3955 setScrollContainer(true); 3956 } 3957 break; 3958 case com.android.internal.R.styleable.View_keepScreenOn: 3959 if (a.getBoolean(attr, false)) { 3960 viewFlagValues |= KEEP_SCREEN_ON; 3961 viewFlagMasks |= KEEP_SCREEN_ON; 3962 } 3963 break; 3964 case R.styleable.View_filterTouchesWhenObscured: 3965 if (a.getBoolean(attr, false)) { 3966 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3967 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3968 } 3969 break; 3970 case R.styleable.View_nextFocusLeft: 3971 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3972 break; 3973 case R.styleable.View_nextFocusRight: 3974 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3975 break; 3976 case R.styleable.View_nextFocusUp: 3977 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3978 break; 3979 case R.styleable.View_nextFocusDown: 3980 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3981 break; 3982 case R.styleable.View_nextFocusForward: 3983 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3984 break; 3985 case R.styleable.View_minWidth: 3986 mMinWidth = a.getDimensionPixelSize(attr, 0); 3987 break; 3988 case R.styleable.View_minHeight: 3989 mMinHeight = a.getDimensionPixelSize(attr, 0); 3990 break; 3991 case R.styleable.View_onClick: 3992 if (context.isRestricted()) { 3993 throw new IllegalStateException("The android:onClick attribute cannot " 3994 + "be used within a restricted context"); 3995 } 3996 3997 final String handlerName = a.getString(attr); 3998 if (handlerName != null) { 3999 setOnClickListener(new OnClickListener() { 4000 private Method mHandler; 4001 4002 public void onClick(View v) { 4003 if (mHandler == null) { 4004 try { 4005 mHandler = getContext().getClass().getMethod(handlerName, 4006 View.class); 4007 } catch (NoSuchMethodException e) { 4008 int id = getId(); 4009 String idText = id == NO_ID ? "" : " with id '" 4010 + getContext().getResources().getResourceEntryName( 4011 id) + "'"; 4012 throw new IllegalStateException("Could not find a method " + 4013 handlerName + "(View) in the activity " 4014 + getContext().getClass() + " for onClick handler" 4015 + " on view " + View.this.getClass() + idText, e); 4016 } 4017 } 4018 4019 try { 4020 mHandler.invoke(getContext(), View.this); 4021 } catch (IllegalAccessException e) { 4022 throw new IllegalStateException("Could not execute non " 4023 + "public method of the activity", e); 4024 } catch (InvocationTargetException e) { 4025 throw new IllegalStateException("Could not execute " 4026 + "method of the activity", e); 4027 } 4028 } 4029 }); 4030 } 4031 break; 4032 case R.styleable.View_overScrollMode: 4033 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4034 break; 4035 case R.styleable.View_verticalScrollbarPosition: 4036 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4037 break; 4038 case R.styleable.View_layerType: 4039 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4040 break; 4041 case R.styleable.View_textDirection: 4042 // Clear any text direction flag already set 4043 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4044 // Set the text direction flags depending on the value of the attribute 4045 final int textDirection = a.getInt(attr, -1); 4046 if (textDirection != -1) { 4047 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4048 } 4049 break; 4050 case R.styleable.View_textAlignment: 4051 // Clear any text alignment flag already set 4052 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4053 // Set the text alignment flag depending on the value of the attribute 4054 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4055 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4056 break; 4057 case R.styleable.View_importantForAccessibility: 4058 setImportantForAccessibility(a.getInt(attr, 4059 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4060 break; 4061 case R.styleable.View_accessibilityLiveRegion: 4062 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4063 break; 4064 case R.styleable.View_transitionName: 4065 setTransitionName(a.getString(attr)); 4066 break; 4067 case R.styleable.View_nestedScrollingEnabled: 4068 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4069 break; 4070 case R.styleable.View_stateListAnimator: 4071 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4072 a.getResourceId(attr, 0))); 4073 break; 4074 case R.styleable.View_backgroundTint: 4075 // This will get applied later during setBackground(). 4076 if (mBackgroundTint == null) { 4077 mBackgroundTint = new TintInfo(); 4078 } 4079 mBackgroundTint.mTintList = a.getColorStateList( 4080 R.styleable.View_backgroundTint); 4081 mBackgroundTint.mHasTintList = true; 4082 break; 4083 case R.styleable.View_backgroundTintMode: 4084 // This will get applied later during setBackground(). 4085 if (mBackgroundTint == null) { 4086 mBackgroundTint = new TintInfo(); 4087 } 4088 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4089 R.styleable.View_backgroundTintMode, -1), null); 4090 mBackgroundTint.mHasTintMode = true; 4091 break; 4092 case R.styleable.View_outlineProvider: 4093 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4094 PROVIDER_BACKGROUND)); 4095 break; 4096 } 4097 } 4098 4099 setOverScrollMode(overScrollMode); 4100 4101 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4102 // the resolved layout direction). Those cached values will be used later during padding 4103 // resolution. 4104 mUserPaddingStart = startPadding; 4105 mUserPaddingEnd = endPadding; 4106 4107 if (background != null) { 4108 setBackground(background); 4109 } 4110 4111 // setBackground above will record that padding is currently provided by the background. 4112 // If we have padding specified via xml, record that here instead and use it. 4113 mLeftPaddingDefined = leftPaddingDefined; 4114 mRightPaddingDefined = rightPaddingDefined; 4115 4116 if (padding >= 0) { 4117 leftPadding = padding; 4118 topPadding = padding; 4119 rightPadding = padding; 4120 bottomPadding = padding; 4121 mUserPaddingLeftInitial = padding; 4122 mUserPaddingRightInitial = padding; 4123 } 4124 4125 if (isRtlCompatibilityMode()) { 4126 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4127 // left / right padding are used if defined (meaning here nothing to do). If they are not 4128 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4129 // start / end and resolve them as left / right (layout direction is not taken into account). 4130 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4131 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4132 // defined. 4133 if (!mLeftPaddingDefined && startPaddingDefined) { 4134 leftPadding = startPadding; 4135 } 4136 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4137 if (!mRightPaddingDefined && endPaddingDefined) { 4138 rightPadding = endPadding; 4139 } 4140 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4141 } else { 4142 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4143 // values defined. Otherwise, left /right values are used. 4144 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4145 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4146 // defined. 4147 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4148 4149 if (mLeftPaddingDefined && !hasRelativePadding) { 4150 mUserPaddingLeftInitial = leftPadding; 4151 } 4152 if (mRightPaddingDefined && !hasRelativePadding) { 4153 mUserPaddingRightInitial = rightPadding; 4154 } 4155 } 4156 4157 internalSetPadding( 4158 mUserPaddingLeftInitial, 4159 topPadding >= 0 ? topPadding : mPaddingTop, 4160 mUserPaddingRightInitial, 4161 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4162 4163 if (viewFlagMasks != 0) { 4164 setFlags(viewFlagValues, viewFlagMasks); 4165 } 4166 4167 if (initializeScrollbars) { 4168 initializeScrollbarsInternal(a); 4169 } 4170 4171 a.recycle(); 4172 4173 // Needs to be called after mViewFlags is set 4174 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4175 recomputePadding(); 4176 } 4177 4178 if (x != 0 || y != 0) { 4179 scrollTo(x, y); 4180 } 4181 4182 if (transformSet) { 4183 setTranslationX(tx); 4184 setTranslationY(ty); 4185 setTranslationZ(tz); 4186 setElevation(elevation); 4187 setRotation(rotation); 4188 setRotationX(rotationX); 4189 setRotationY(rotationY); 4190 setScaleX(sx); 4191 setScaleY(sy); 4192 } 4193 4194 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4195 setScrollContainer(true); 4196 } 4197 4198 computeOpaqueFlags(); 4199 } 4200 4201 /** 4202 * Non-public constructor for use in testing 4203 */ 4204 View() { 4205 mResources = null; 4206 mRenderNode = RenderNode.create(getClass().getName(), this); 4207 } 4208 4209 private static SparseArray<String> getAttributeMap() { 4210 if (mAttributeMap == null) { 4211 mAttributeMap = new SparseArray<String>(); 4212 } 4213 return mAttributeMap; 4214 } 4215 4216 private void saveAttributeData(AttributeSet attrs, TypedArray a) { 4217 int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2; 4218 mAttributes = new String[length]; 4219 4220 int i = 0; 4221 if (attrs != null) { 4222 for (i = 0; i < attrs.getAttributeCount(); i += 2) { 4223 mAttributes[i] = attrs.getAttributeName(i); 4224 mAttributes[i + 1] = attrs.getAttributeValue(i); 4225 } 4226 4227 } 4228 4229 SparseArray<String> attributeMap = getAttributeMap(); 4230 for (int j = 0; j < a.length(); ++j) { 4231 if (a.hasValue(j)) { 4232 try { 4233 int resourceId = a.getResourceId(j, 0); 4234 if (resourceId == 0) { 4235 continue; 4236 } 4237 4238 String resourceName = attributeMap.get(resourceId); 4239 if (resourceName == null) { 4240 resourceName = a.getResources().getResourceName(resourceId); 4241 attributeMap.put(resourceId, resourceName); 4242 } 4243 4244 mAttributes[i] = resourceName; 4245 mAttributes[i + 1] = a.getText(j).toString(); 4246 i += 2; 4247 } catch (Resources.NotFoundException e) { 4248 // if we can't get the resource name, we just ignore it 4249 } 4250 } 4251 } 4252 } 4253 4254 public String toString() { 4255 StringBuilder out = new StringBuilder(128); 4256 out.append(getClass().getName()); 4257 out.append('{'); 4258 out.append(Integer.toHexString(System.identityHashCode(this))); 4259 out.append(' '); 4260 switch (mViewFlags&VISIBILITY_MASK) { 4261 case VISIBLE: out.append('V'); break; 4262 case INVISIBLE: out.append('I'); break; 4263 case GONE: out.append('G'); break; 4264 default: out.append('.'); break; 4265 } 4266 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4267 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4268 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4269 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4270 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4271 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4272 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4273 out.append(' '); 4274 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4275 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4276 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4277 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4278 out.append('p'); 4279 } else { 4280 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4281 } 4282 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4283 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4284 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4285 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4286 out.append(' '); 4287 out.append(mLeft); 4288 out.append(','); 4289 out.append(mTop); 4290 out.append('-'); 4291 out.append(mRight); 4292 out.append(','); 4293 out.append(mBottom); 4294 final int id = getId(); 4295 if (id != NO_ID) { 4296 out.append(" #"); 4297 out.append(Integer.toHexString(id)); 4298 final Resources r = mResources; 4299 if (Resources.resourceHasPackage(id) && r != null) { 4300 try { 4301 String pkgname; 4302 switch (id&0xff000000) { 4303 case 0x7f000000: 4304 pkgname="app"; 4305 break; 4306 case 0x01000000: 4307 pkgname="android"; 4308 break; 4309 default: 4310 pkgname = r.getResourcePackageName(id); 4311 break; 4312 } 4313 String typename = r.getResourceTypeName(id); 4314 String entryname = r.getResourceEntryName(id); 4315 out.append(" "); 4316 out.append(pkgname); 4317 out.append(":"); 4318 out.append(typename); 4319 out.append("/"); 4320 out.append(entryname); 4321 } catch (Resources.NotFoundException e) { 4322 } 4323 } 4324 } 4325 out.append("}"); 4326 return out.toString(); 4327 } 4328 4329 /** 4330 * <p> 4331 * Initializes the fading edges from a given set of styled attributes. This 4332 * method should be called by subclasses that need fading edges and when an 4333 * instance of these subclasses is created programmatically rather than 4334 * being inflated from XML. This method is automatically called when the XML 4335 * is inflated. 4336 * </p> 4337 * 4338 * @param a the styled attributes set to initialize the fading edges from 4339 * 4340 * @removed 4341 */ 4342 protected void initializeFadingEdge(TypedArray a) { 4343 // This method probably shouldn't have been included in the SDK to begin with. 4344 // It relies on 'a' having been initialized using an attribute filter array that is 4345 // not publicly available to the SDK. The old method has been renamed 4346 // to initializeFadingEdgeInternal and hidden for framework use only; 4347 // this one initializes using defaults to make it safe to call for apps. 4348 4349 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4350 4351 initializeFadingEdgeInternal(arr); 4352 4353 arr.recycle(); 4354 } 4355 4356 /** 4357 * <p> 4358 * Initializes the fading edges from a given set of styled attributes. This 4359 * method should be called by subclasses that need fading edges and when an 4360 * instance of these subclasses is created programmatically rather than 4361 * being inflated from XML. This method is automatically called when the XML 4362 * is inflated. 4363 * </p> 4364 * 4365 * @param a the styled attributes set to initialize the fading edges from 4366 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4367 */ 4368 protected void initializeFadingEdgeInternal(TypedArray a) { 4369 initScrollCache(); 4370 4371 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4372 R.styleable.View_fadingEdgeLength, 4373 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4374 } 4375 4376 /** 4377 * Returns the size of the vertical faded edges used to indicate that more 4378 * content in this view is visible. 4379 * 4380 * @return The size in pixels of the vertical faded edge or 0 if vertical 4381 * faded edges are not enabled for this view. 4382 * @attr ref android.R.styleable#View_fadingEdgeLength 4383 */ 4384 public int getVerticalFadingEdgeLength() { 4385 if (isVerticalFadingEdgeEnabled()) { 4386 ScrollabilityCache cache = mScrollCache; 4387 if (cache != null) { 4388 return cache.fadingEdgeLength; 4389 } 4390 } 4391 return 0; 4392 } 4393 4394 /** 4395 * Set the size of the faded edge used to indicate that more content in this 4396 * view is available. Will not change whether the fading edge is enabled; use 4397 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4398 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4399 * for the vertical or horizontal fading edges. 4400 * 4401 * @param length The size in pixels of the faded edge used to indicate that more 4402 * content in this view is visible. 4403 */ 4404 public void setFadingEdgeLength(int length) { 4405 initScrollCache(); 4406 mScrollCache.fadingEdgeLength = length; 4407 } 4408 4409 /** 4410 * Returns the size of the horizontal faded edges used to indicate that more 4411 * content in this view is visible. 4412 * 4413 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4414 * faded edges are not enabled for this view. 4415 * @attr ref android.R.styleable#View_fadingEdgeLength 4416 */ 4417 public int getHorizontalFadingEdgeLength() { 4418 if (isHorizontalFadingEdgeEnabled()) { 4419 ScrollabilityCache cache = mScrollCache; 4420 if (cache != null) { 4421 return cache.fadingEdgeLength; 4422 } 4423 } 4424 return 0; 4425 } 4426 4427 /** 4428 * Returns the width of the vertical scrollbar. 4429 * 4430 * @return The width in pixels of the vertical scrollbar or 0 if there 4431 * is no vertical scrollbar. 4432 */ 4433 public int getVerticalScrollbarWidth() { 4434 ScrollabilityCache cache = mScrollCache; 4435 if (cache != null) { 4436 ScrollBarDrawable scrollBar = cache.scrollBar; 4437 if (scrollBar != null) { 4438 int size = scrollBar.getSize(true); 4439 if (size <= 0) { 4440 size = cache.scrollBarSize; 4441 } 4442 return size; 4443 } 4444 return 0; 4445 } 4446 return 0; 4447 } 4448 4449 /** 4450 * Returns the height of the horizontal scrollbar. 4451 * 4452 * @return The height in pixels of the horizontal scrollbar or 0 if 4453 * there is no horizontal scrollbar. 4454 */ 4455 protected int getHorizontalScrollbarHeight() { 4456 ScrollabilityCache cache = mScrollCache; 4457 if (cache != null) { 4458 ScrollBarDrawable scrollBar = cache.scrollBar; 4459 if (scrollBar != null) { 4460 int size = scrollBar.getSize(false); 4461 if (size <= 0) { 4462 size = cache.scrollBarSize; 4463 } 4464 return size; 4465 } 4466 return 0; 4467 } 4468 return 0; 4469 } 4470 4471 /** 4472 * <p> 4473 * Initializes the scrollbars from a given set of styled attributes. This 4474 * method should be called by subclasses that need scrollbars and when an 4475 * instance of these subclasses is created programmatically rather than 4476 * being inflated from XML. This method is automatically called when the XML 4477 * is inflated. 4478 * </p> 4479 * 4480 * @param a the styled attributes set to initialize the scrollbars from 4481 * 4482 * @removed 4483 */ 4484 protected void initializeScrollbars(TypedArray a) { 4485 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4486 // using the View filter array which is not available to the SDK. As such, internal 4487 // framework usage now uses initializeScrollbarsInternal and we grab a default 4488 // TypedArray with the right filter instead here. 4489 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4490 4491 initializeScrollbarsInternal(arr); 4492 4493 // We ignored the method parameter. Recycle the one we actually did use. 4494 arr.recycle(); 4495 } 4496 4497 /** 4498 * <p> 4499 * Initializes the scrollbars from a given set of styled attributes. This 4500 * method should be called by subclasses that need scrollbars and when an 4501 * instance of these subclasses is created programmatically rather than 4502 * being inflated from XML. This method is automatically called when the XML 4503 * is inflated. 4504 * </p> 4505 * 4506 * @param a the styled attributes set to initialize the scrollbars from 4507 * @hide 4508 */ 4509 protected void initializeScrollbarsInternal(TypedArray a) { 4510 initScrollCache(); 4511 4512 final ScrollabilityCache scrollabilityCache = mScrollCache; 4513 4514 if (scrollabilityCache.scrollBar == null) { 4515 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4516 } 4517 4518 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4519 4520 if (!fadeScrollbars) { 4521 scrollabilityCache.state = ScrollabilityCache.ON; 4522 } 4523 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4524 4525 4526 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4527 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4528 .getScrollBarFadeDuration()); 4529 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4530 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4531 ViewConfiguration.getScrollDefaultDelay()); 4532 4533 4534 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4535 com.android.internal.R.styleable.View_scrollbarSize, 4536 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4537 4538 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4539 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4540 4541 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4542 if (thumb != null) { 4543 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4544 } 4545 4546 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4547 false); 4548 if (alwaysDraw) { 4549 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4550 } 4551 4552 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4553 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4554 4555 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4556 if (thumb != null) { 4557 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4558 } 4559 4560 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4561 false); 4562 if (alwaysDraw) { 4563 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4564 } 4565 4566 // Apply layout direction to the new Drawables if needed 4567 final int layoutDirection = getLayoutDirection(); 4568 if (track != null) { 4569 track.setLayoutDirection(layoutDirection); 4570 } 4571 if (thumb != null) { 4572 thumb.setLayoutDirection(layoutDirection); 4573 } 4574 4575 // Re-apply user/background padding so that scrollbar(s) get added 4576 resolvePadding(); 4577 } 4578 4579 /** 4580 * <p> 4581 * Initalizes the scrollability cache if necessary. 4582 * </p> 4583 */ 4584 private void initScrollCache() { 4585 if (mScrollCache == null) { 4586 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4587 } 4588 } 4589 4590 private ScrollabilityCache getScrollCache() { 4591 initScrollCache(); 4592 return mScrollCache; 4593 } 4594 4595 /** 4596 * Set the position of the vertical scroll bar. Should be one of 4597 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4598 * {@link #SCROLLBAR_POSITION_RIGHT}. 4599 * 4600 * @param position Where the vertical scroll bar should be positioned. 4601 */ 4602 public void setVerticalScrollbarPosition(int position) { 4603 if (mVerticalScrollbarPosition != position) { 4604 mVerticalScrollbarPosition = position; 4605 computeOpaqueFlags(); 4606 resolvePadding(); 4607 } 4608 } 4609 4610 /** 4611 * @return The position where the vertical scroll bar will show, if applicable. 4612 * @see #setVerticalScrollbarPosition(int) 4613 */ 4614 public int getVerticalScrollbarPosition() { 4615 return mVerticalScrollbarPosition; 4616 } 4617 4618 ListenerInfo getListenerInfo() { 4619 if (mListenerInfo != null) { 4620 return mListenerInfo; 4621 } 4622 mListenerInfo = new ListenerInfo(); 4623 return mListenerInfo; 4624 } 4625 4626 /** 4627 * Register a callback to be invoked when the scroll position of this view 4628 * changed. 4629 * 4630 * @param l The callback that will run. 4631 * @hide Only used internally. 4632 */ 4633 public void setOnScrollChangeListener(OnScrollChangeListener l) { 4634 getListenerInfo().mOnScrollChangeListener = l; 4635 } 4636 4637 /** 4638 * Register a callback to be invoked when focus of this view changed. 4639 * 4640 * @param l The callback that will run. 4641 */ 4642 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4643 getListenerInfo().mOnFocusChangeListener = l; 4644 } 4645 4646 /** 4647 * Add a listener that will be called when the bounds of the view change due to 4648 * layout processing. 4649 * 4650 * @param listener The listener that will be called when layout bounds change. 4651 */ 4652 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4653 ListenerInfo li = getListenerInfo(); 4654 if (li.mOnLayoutChangeListeners == null) { 4655 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4656 } 4657 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4658 li.mOnLayoutChangeListeners.add(listener); 4659 } 4660 } 4661 4662 /** 4663 * Remove a listener for layout changes. 4664 * 4665 * @param listener The listener for layout bounds change. 4666 */ 4667 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4668 ListenerInfo li = mListenerInfo; 4669 if (li == null || li.mOnLayoutChangeListeners == null) { 4670 return; 4671 } 4672 li.mOnLayoutChangeListeners.remove(listener); 4673 } 4674 4675 /** 4676 * Add a listener for attach state changes. 4677 * 4678 * This listener will be called whenever this view is attached or detached 4679 * from a window. Remove the listener using 4680 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4681 * 4682 * @param listener Listener to attach 4683 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4684 */ 4685 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4686 ListenerInfo li = getListenerInfo(); 4687 if (li.mOnAttachStateChangeListeners == null) { 4688 li.mOnAttachStateChangeListeners 4689 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4690 } 4691 li.mOnAttachStateChangeListeners.add(listener); 4692 } 4693 4694 /** 4695 * Remove a listener for attach state changes. The listener will receive no further 4696 * notification of window attach/detach events. 4697 * 4698 * @param listener Listener to remove 4699 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4700 */ 4701 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4702 ListenerInfo li = mListenerInfo; 4703 if (li == null || li.mOnAttachStateChangeListeners == null) { 4704 return; 4705 } 4706 li.mOnAttachStateChangeListeners.remove(listener); 4707 } 4708 4709 /** 4710 * Returns the focus-change callback registered for this view. 4711 * 4712 * @return The callback, or null if one is not registered. 4713 */ 4714 public OnFocusChangeListener getOnFocusChangeListener() { 4715 ListenerInfo li = mListenerInfo; 4716 return li != null ? li.mOnFocusChangeListener : null; 4717 } 4718 4719 /** 4720 * Register a callback to be invoked when this view is clicked. If this view is not 4721 * clickable, it becomes clickable. 4722 * 4723 * @param l The callback that will run 4724 * 4725 * @see #setClickable(boolean) 4726 */ 4727 public void setOnClickListener(OnClickListener l) { 4728 if (!isClickable()) { 4729 setClickable(true); 4730 } 4731 getListenerInfo().mOnClickListener = l; 4732 } 4733 4734 /** 4735 * Return whether this view has an attached OnClickListener. Returns 4736 * true if there is a listener, false if there is none. 4737 */ 4738 public boolean hasOnClickListeners() { 4739 ListenerInfo li = mListenerInfo; 4740 return (li != null && li.mOnClickListener != null); 4741 } 4742 4743 /** 4744 * Register a callback to be invoked when this view is clicked and held. If this view is not 4745 * long clickable, it becomes long clickable. 4746 * 4747 * @param l The callback that will run 4748 * 4749 * @see #setLongClickable(boolean) 4750 */ 4751 public void setOnLongClickListener(OnLongClickListener l) { 4752 if (!isLongClickable()) { 4753 setLongClickable(true); 4754 } 4755 getListenerInfo().mOnLongClickListener = l; 4756 } 4757 4758 /** 4759 * Register a callback to be invoked when the context menu for this view is 4760 * being built. If this view is not long clickable, it becomes long clickable. 4761 * 4762 * @param l The callback that will run 4763 * 4764 */ 4765 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4766 if (!isLongClickable()) { 4767 setLongClickable(true); 4768 } 4769 getListenerInfo().mOnCreateContextMenuListener = l; 4770 } 4771 4772 /** 4773 * Call this view's OnClickListener, if it is defined. Performs all normal 4774 * actions associated with clicking: reporting accessibility event, playing 4775 * a sound, etc. 4776 * 4777 * @return True there was an assigned OnClickListener that was called, false 4778 * otherwise is returned. 4779 */ 4780 public boolean performClick() { 4781 final boolean result; 4782 final ListenerInfo li = mListenerInfo; 4783 if (li != null && li.mOnClickListener != null) { 4784 playSoundEffect(SoundEffectConstants.CLICK); 4785 li.mOnClickListener.onClick(this); 4786 result = true; 4787 } else { 4788 result = false; 4789 } 4790 4791 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4792 return result; 4793 } 4794 4795 /** 4796 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4797 * this only calls the listener, and does not do any associated clicking 4798 * actions like reporting an accessibility event. 4799 * 4800 * @return True there was an assigned OnClickListener that was called, false 4801 * otherwise is returned. 4802 */ 4803 public boolean callOnClick() { 4804 ListenerInfo li = mListenerInfo; 4805 if (li != null && li.mOnClickListener != null) { 4806 li.mOnClickListener.onClick(this); 4807 return true; 4808 } 4809 return false; 4810 } 4811 4812 /** 4813 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4814 * OnLongClickListener did not consume the event. 4815 * 4816 * @return True if one of the above receivers consumed the event, false otherwise. 4817 */ 4818 public boolean performLongClick() { 4819 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4820 4821 boolean handled = false; 4822 ListenerInfo li = mListenerInfo; 4823 if (li != null && li.mOnLongClickListener != null) { 4824 handled = li.mOnLongClickListener.onLongClick(View.this); 4825 } 4826 if (!handled) { 4827 handled = showContextMenu(); 4828 } 4829 if (handled) { 4830 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4831 } 4832 return handled; 4833 } 4834 4835 /** 4836 * Performs button-related actions during a touch down event. 4837 * 4838 * @param event The event. 4839 * @return True if the down was consumed. 4840 * 4841 * @hide 4842 */ 4843 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4844 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4845 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4846 return true; 4847 } 4848 } 4849 return false; 4850 } 4851 4852 /** 4853 * Bring up the context menu for this view. 4854 * 4855 * @return Whether a context menu was displayed. 4856 */ 4857 public boolean showContextMenu() { 4858 return getParent().showContextMenuForChild(this); 4859 } 4860 4861 /** 4862 * Bring up the context menu for this view, referring to the item under the specified point. 4863 * 4864 * @param x The referenced x coordinate. 4865 * @param y The referenced y coordinate. 4866 * @param metaState The keyboard modifiers that were pressed. 4867 * @return Whether a context menu was displayed. 4868 * 4869 * @hide 4870 */ 4871 public boolean showContextMenu(float x, float y, int metaState) { 4872 return showContextMenu(); 4873 } 4874 4875 /** 4876 * Start an action mode. 4877 * 4878 * @param callback Callback that will control the lifecycle of the action mode 4879 * @return The new action mode if it is started, null otherwise 4880 * 4881 * @see ActionMode 4882 */ 4883 public ActionMode startActionMode(ActionMode.Callback callback) { 4884 ViewParent parent = getParent(); 4885 if (parent == null) return null; 4886 return parent.startActionModeForChild(this, callback); 4887 } 4888 4889 /** 4890 * Register a callback to be invoked when a hardware key is pressed in this view. 4891 * Key presses in software input methods will generally not trigger the methods of 4892 * this listener. 4893 * @param l the key listener to attach to this view 4894 */ 4895 public void setOnKeyListener(OnKeyListener l) { 4896 getListenerInfo().mOnKeyListener = l; 4897 } 4898 4899 /** 4900 * Register a callback to be invoked when a touch event is sent to this view. 4901 * @param l the touch listener to attach to this view 4902 */ 4903 public void setOnTouchListener(OnTouchListener l) { 4904 getListenerInfo().mOnTouchListener = l; 4905 } 4906 4907 /** 4908 * Register a callback to be invoked when a generic motion event is sent to this view. 4909 * @param l the generic motion listener to attach to this view 4910 */ 4911 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4912 getListenerInfo().mOnGenericMotionListener = l; 4913 } 4914 4915 /** 4916 * Register a callback to be invoked when a hover event is sent to this view. 4917 * @param l the hover listener to attach to this view 4918 */ 4919 public void setOnHoverListener(OnHoverListener l) { 4920 getListenerInfo().mOnHoverListener = l; 4921 } 4922 4923 /** 4924 * Register a drag event listener callback object for this View. The parameter is 4925 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4926 * View, the system calls the 4927 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4928 * @param l An implementation of {@link android.view.View.OnDragListener}. 4929 */ 4930 public void setOnDragListener(OnDragListener l) { 4931 getListenerInfo().mOnDragListener = l; 4932 } 4933 4934 /** 4935 * Give this view focus. This will cause 4936 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4937 * 4938 * Note: this does not check whether this {@link View} should get focus, it just 4939 * gives it focus no matter what. It should only be called internally by framework 4940 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4941 * 4942 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4943 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4944 * focus moved when requestFocus() is called. It may not always 4945 * apply, in which case use the default View.FOCUS_DOWN. 4946 * @param previouslyFocusedRect The rectangle of the view that had focus 4947 * prior in this View's coordinate system. 4948 */ 4949 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4950 if (DBG) { 4951 System.out.println(this + " requestFocus()"); 4952 } 4953 4954 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4955 mPrivateFlags |= PFLAG_FOCUSED; 4956 4957 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4958 4959 if (mParent != null) { 4960 mParent.requestChildFocus(this, this); 4961 } 4962 4963 if (mAttachInfo != null) { 4964 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4965 } 4966 4967 onFocusChanged(true, direction, previouslyFocusedRect); 4968 refreshDrawableState(); 4969 } 4970 } 4971 4972 /** 4973 * Populates <code>outRect</code> with the hotspot bounds. By default, 4974 * the hotspot bounds are identical to the screen bounds. 4975 * 4976 * @param outRect rect to populate with hotspot bounds 4977 * @hide Only for internal use by views and widgets. 4978 */ 4979 public void getHotspotBounds(Rect outRect) { 4980 final Drawable background = getBackground(); 4981 if (background != null) { 4982 background.getHotspotBounds(outRect); 4983 } else { 4984 getBoundsOnScreen(outRect); 4985 } 4986 } 4987 4988 /** 4989 * Request that a rectangle of this view be visible on the screen, 4990 * scrolling if necessary just enough. 4991 * 4992 * <p>A View should call this if it maintains some notion of which part 4993 * of its content is interesting. For example, a text editing view 4994 * should call this when its cursor moves. 4995 * 4996 * @param rectangle The rectangle. 4997 * @return Whether any parent scrolled. 4998 */ 4999 public boolean requestRectangleOnScreen(Rect rectangle) { 5000 return requestRectangleOnScreen(rectangle, false); 5001 } 5002 5003 /** 5004 * Request that a rectangle of this view be visible on the screen, 5005 * scrolling if necessary just enough. 5006 * 5007 * <p>A View should call this if it maintains some notion of which part 5008 * of its content is interesting. For example, a text editing view 5009 * should call this when its cursor moves. 5010 * 5011 * <p>When <code>immediate</code> is set to true, scrolling will not be 5012 * animated. 5013 * 5014 * @param rectangle The rectangle. 5015 * @param immediate True to forbid animated scrolling, false otherwise 5016 * @return Whether any parent scrolled. 5017 */ 5018 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 5019 if (mParent == null) { 5020 return false; 5021 } 5022 5023 View child = this; 5024 5025 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 5026 position.set(rectangle); 5027 5028 ViewParent parent = mParent; 5029 boolean scrolled = false; 5030 while (parent != null) { 5031 rectangle.set((int) position.left, (int) position.top, 5032 (int) position.right, (int) position.bottom); 5033 5034 scrolled |= parent.requestChildRectangleOnScreen(child, 5035 rectangle, immediate); 5036 5037 if (!child.hasIdentityMatrix()) { 5038 child.getMatrix().mapRect(position); 5039 } 5040 5041 position.offset(child.mLeft, child.mTop); 5042 5043 if (!(parent instanceof View)) { 5044 break; 5045 } 5046 5047 View parentView = (View) parent; 5048 5049 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 5050 5051 child = parentView; 5052 parent = child.getParent(); 5053 } 5054 5055 return scrolled; 5056 } 5057 5058 /** 5059 * Called when this view wants to give up focus. If focus is cleared 5060 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 5061 * <p> 5062 * <strong>Note:</strong> When a View clears focus the framework is trying 5063 * to give focus to the first focusable View from the top. Hence, if this 5064 * View is the first from the top that can take focus, then all callbacks 5065 * related to clearing focus will be invoked after which the framework will 5066 * give focus to this view. 5067 * </p> 5068 */ 5069 public void clearFocus() { 5070 if (DBG) { 5071 System.out.println(this + " clearFocus()"); 5072 } 5073 5074 clearFocusInternal(null, true, true); 5075 } 5076 5077 /** 5078 * Clears focus from the view, optionally propagating the change up through 5079 * the parent hierarchy and requesting that the root view place new focus. 5080 * 5081 * @param propagate whether to propagate the change up through the parent 5082 * hierarchy 5083 * @param refocus when propagate is true, specifies whether to request the 5084 * root view place new focus 5085 */ 5086 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 5087 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 5088 mPrivateFlags &= ~PFLAG_FOCUSED; 5089 5090 if (propagate && mParent != null) { 5091 mParent.clearChildFocus(this); 5092 } 5093 5094 onFocusChanged(false, 0, null); 5095 refreshDrawableState(); 5096 5097 if (propagate && (!refocus || !rootViewRequestFocus())) { 5098 notifyGlobalFocusCleared(this); 5099 } 5100 } 5101 } 5102 5103 void notifyGlobalFocusCleared(View oldFocus) { 5104 if (oldFocus != null && mAttachInfo != null) { 5105 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 5106 } 5107 } 5108 5109 boolean rootViewRequestFocus() { 5110 final View root = getRootView(); 5111 return root != null && root.requestFocus(); 5112 } 5113 5114 /** 5115 * Called internally by the view system when a new view is getting focus. 5116 * This is what clears the old focus. 5117 * <p> 5118 * <b>NOTE:</b> The parent view's focused child must be updated manually 5119 * after calling this method. Otherwise, the view hierarchy may be left in 5120 * an inconstent state. 5121 */ 5122 void unFocus(View focused) { 5123 if (DBG) { 5124 System.out.println(this + " unFocus()"); 5125 } 5126 5127 clearFocusInternal(focused, false, false); 5128 } 5129 5130 /** 5131 * Returns true if this view has focus iteself, or is the ancestor of the 5132 * view that has focus. 5133 * 5134 * @return True if this view has or contains focus, false otherwise. 5135 */ 5136 @ViewDebug.ExportedProperty(category = "focus") 5137 public boolean hasFocus() { 5138 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5139 } 5140 5141 /** 5142 * Returns true if this view is focusable or if it contains a reachable View 5143 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5144 * is a View whose parents do not block descendants focus. 5145 * 5146 * Only {@link #VISIBLE} views are considered focusable. 5147 * 5148 * @return True if the view is focusable or if the view contains a focusable 5149 * View, false otherwise. 5150 * 5151 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5152 * @see ViewGroup#getTouchscreenBlocksFocus() 5153 */ 5154 public boolean hasFocusable() { 5155 if (!isFocusableInTouchMode()) { 5156 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 5157 final ViewGroup g = (ViewGroup) p; 5158 if (g.shouldBlockFocusForTouchscreen()) { 5159 return false; 5160 } 5161 } 5162 } 5163 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5164 } 5165 5166 /** 5167 * Called by the view system when the focus state of this view changes. 5168 * When the focus change event is caused by directional navigation, direction 5169 * and previouslyFocusedRect provide insight into where the focus is coming from. 5170 * When overriding, be sure to call up through to the super class so that 5171 * the standard focus handling will occur. 5172 * 5173 * @param gainFocus True if the View has focus; false otherwise. 5174 * @param direction The direction focus has moved when requestFocus() 5175 * is called to give this view focus. Values are 5176 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5177 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5178 * It may not always apply, in which case use the default. 5179 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5180 * system, of the previously focused view. If applicable, this will be 5181 * passed in as finer grained information about where the focus is coming 5182 * from (in addition to direction). Will be <code>null</code> otherwise. 5183 */ 5184 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5185 @Nullable Rect previouslyFocusedRect) { 5186 if (gainFocus) { 5187 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5188 } else { 5189 notifyViewAccessibilityStateChangedIfNeeded( 5190 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5191 } 5192 5193 InputMethodManager imm = InputMethodManager.peekInstance(); 5194 if (!gainFocus) { 5195 if (isPressed()) { 5196 setPressed(false); 5197 } 5198 if (imm != null && mAttachInfo != null 5199 && mAttachInfo.mHasWindowFocus) { 5200 imm.focusOut(this); 5201 } 5202 onFocusLost(); 5203 } else if (imm != null && mAttachInfo != null 5204 && mAttachInfo.mHasWindowFocus) { 5205 imm.focusIn(this); 5206 } 5207 5208 invalidate(true); 5209 ListenerInfo li = mListenerInfo; 5210 if (li != null && li.mOnFocusChangeListener != null) { 5211 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5212 } 5213 5214 if (mAttachInfo != null) { 5215 mAttachInfo.mKeyDispatchState.reset(this); 5216 } 5217 } 5218 5219 /** 5220 * Sends an accessibility event of the given type. If accessibility is 5221 * not enabled this method has no effect. The default implementation calls 5222 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5223 * to populate information about the event source (this View), then calls 5224 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5225 * populate the text content of the event source including its descendants, 5226 * and last calls 5227 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5228 * on its parent to resuest sending of the event to interested parties. 5229 * <p> 5230 * If an {@link AccessibilityDelegate} has been specified via calling 5231 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5232 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5233 * responsible for handling this call. 5234 * </p> 5235 * 5236 * @param eventType The type of the event to send, as defined by several types from 5237 * {@link android.view.accessibility.AccessibilityEvent}, such as 5238 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5239 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5240 * 5241 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5242 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5243 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5244 * @see AccessibilityDelegate 5245 */ 5246 public void sendAccessibilityEvent(int eventType) { 5247 if (mAccessibilityDelegate != null) { 5248 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5249 } else { 5250 sendAccessibilityEventInternal(eventType); 5251 } 5252 } 5253 5254 /** 5255 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5256 * {@link AccessibilityEvent} to make an announcement which is related to some 5257 * sort of a context change for which none of the events representing UI transitions 5258 * is a good fit. For example, announcing a new page in a book. If accessibility 5259 * is not enabled this method does nothing. 5260 * 5261 * @param text The announcement text. 5262 */ 5263 public void announceForAccessibility(CharSequence text) { 5264 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5265 AccessibilityEvent event = AccessibilityEvent.obtain( 5266 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5267 onInitializeAccessibilityEvent(event); 5268 event.getText().add(text); 5269 event.setContentDescription(null); 5270 mParent.requestSendAccessibilityEvent(this, event); 5271 } 5272 } 5273 5274 /** 5275 * @see #sendAccessibilityEvent(int) 5276 * 5277 * Note: Called from the default {@link AccessibilityDelegate}. 5278 */ 5279 void sendAccessibilityEventInternal(int eventType) { 5280 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5281 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5282 } 5283 } 5284 5285 /** 5286 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5287 * takes as an argument an empty {@link AccessibilityEvent} and does not 5288 * perform a check whether accessibility is enabled. 5289 * <p> 5290 * If an {@link AccessibilityDelegate} has been specified via calling 5291 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5292 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5293 * is responsible for handling this call. 5294 * </p> 5295 * 5296 * @param event The event to send. 5297 * 5298 * @see #sendAccessibilityEvent(int) 5299 */ 5300 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5301 if (mAccessibilityDelegate != null) { 5302 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5303 } else { 5304 sendAccessibilityEventUncheckedInternal(event); 5305 } 5306 } 5307 5308 /** 5309 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5310 * 5311 * Note: Called from the default {@link AccessibilityDelegate}. 5312 */ 5313 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5314 if (!isShown()) { 5315 return; 5316 } 5317 onInitializeAccessibilityEvent(event); 5318 // Only a subset of accessibility events populates text content. 5319 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5320 dispatchPopulateAccessibilityEvent(event); 5321 } 5322 // In the beginning we called #isShown(), so we know that getParent() is not null. 5323 getParent().requestSendAccessibilityEvent(this, event); 5324 } 5325 5326 /** 5327 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5328 * to its children for adding their text content to the event. Note that the 5329 * event text is populated in a separate dispatch path since we add to the 5330 * event not only the text of the source but also the text of all its descendants. 5331 * A typical implementation will call 5332 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5333 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5334 * on each child. Override this method if custom population of the event text 5335 * content is required. 5336 * <p> 5337 * If an {@link AccessibilityDelegate} has been specified via calling 5338 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5339 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5340 * is responsible for handling this call. 5341 * </p> 5342 * <p> 5343 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5344 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5345 * </p> 5346 * 5347 * @param event The event. 5348 * 5349 * @return True if the event population was completed. 5350 */ 5351 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5352 if (mAccessibilityDelegate != null) { 5353 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5354 } else { 5355 return dispatchPopulateAccessibilityEventInternal(event); 5356 } 5357 } 5358 5359 /** 5360 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5361 * 5362 * Note: Called from the default {@link AccessibilityDelegate}. 5363 */ 5364 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5365 onPopulateAccessibilityEvent(event); 5366 return false; 5367 } 5368 5369 /** 5370 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5371 * giving a chance to this View to populate the accessibility event with its 5372 * text content. While this method is free to modify event 5373 * attributes other than text content, doing so should normally be performed in 5374 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5375 * <p> 5376 * Example: Adding formatted date string to an accessibility event in addition 5377 * to the text added by the super implementation: 5378 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5379 * super.onPopulateAccessibilityEvent(event); 5380 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5381 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5382 * mCurrentDate.getTimeInMillis(), flags); 5383 * event.getText().add(selectedDateUtterance); 5384 * }</pre> 5385 * <p> 5386 * If an {@link AccessibilityDelegate} has been specified via calling 5387 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5388 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5389 * is responsible for handling this call. 5390 * </p> 5391 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5392 * information to the event, in case the default implementation has basic information to add. 5393 * </p> 5394 * 5395 * @param event The accessibility event which to populate. 5396 * 5397 * @see #sendAccessibilityEvent(int) 5398 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5399 */ 5400 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5401 if (mAccessibilityDelegate != null) { 5402 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5403 } else { 5404 onPopulateAccessibilityEventInternal(event); 5405 } 5406 } 5407 5408 /** 5409 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5410 * 5411 * Note: Called from the default {@link AccessibilityDelegate}. 5412 */ 5413 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5414 } 5415 5416 /** 5417 * Initializes an {@link AccessibilityEvent} with information about 5418 * this View which is the event source. In other words, the source of 5419 * an accessibility event is the view whose state change triggered firing 5420 * the event. 5421 * <p> 5422 * Example: Setting the password property of an event in addition 5423 * to properties set by the super implementation: 5424 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5425 * super.onInitializeAccessibilityEvent(event); 5426 * event.setPassword(true); 5427 * }</pre> 5428 * <p> 5429 * If an {@link AccessibilityDelegate} has been specified via calling 5430 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5431 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5432 * is responsible for handling this call. 5433 * </p> 5434 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5435 * information to the event, in case the default implementation has basic information to add. 5436 * </p> 5437 * @param event The event to initialize. 5438 * 5439 * @see #sendAccessibilityEvent(int) 5440 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5441 */ 5442 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5443 if (mAccessibilityDelegate != null) { 5444 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5445 } else { 5446 onInitializeAccessibilityEventInternal(event); 5447 } 5448 } 5449 5450 /** 5451 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5452 * 5453 * Note: Called from the default {@link AccessibilityDelegate}. 5454 */ 5455 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5456 event.setSource(this); 5457 event.setClassName(View.class.getName()); 5458 event.setPackageName(getContext().getPackageName()); 5459 event.setEnabled(isEnabled()); 5460 event.setContentDescription(mContentDescription); 5461 5462 switch (event.getEventType()) { 5463 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5464 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5465 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5466 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5467 event.setItemCount(focusablesTempList.size()); 5468 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5469 if (mAttachInfo != null) { 5470 focusablesTempList.clear(); 5471 } 5472 } break; 5473 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5474 CharSequence text = getIterableTextForAccessibility(); 5475 if (text != null && text.length() > 0) { 5476 event.setFromIndex(getAccessibilitySelectionStart()); 5477 event.setToIndex(getAccessibilitySelectionEnd()); 5478 event.setItemCount(text.length()); 5479 } 5480 } break; 5481 } 5482 } 5483 5484 /** 5485 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5486 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5487 * This method is responsible for obtaining an accessibility node info from a 5488 * pool of reusable instances and calling 5489 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5490 * initialize the former. 5491 * <p> 5492 * Note: The client is responsible for recycling the obtained instance by calling 5493 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5494 * </p> 5495 * 5496 * @return A populated {@link AccessibilityNodeInfo}. 5497 * 5498 * @see AccessibilityNodeInfo 5499 */ 5500 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5501 if (mAccessibilityDelegate != null) { 5502 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5503 } else { 5504 return createAccessibilityNodeInfoInternal(); 5505 } 5506 } 5507 5508 /** 5509 * @see #createAccessibilityNodeInfo() 5510 */ 5511 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5512 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5513 if (provider != null) { 5514 return provider.createAccessibilityNodeInfo(View.NO_ID); 5515 } else { 5516 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5517 onInitializeAccessibilityNodeInfo(info); 5518 return info; 5519 } 5520 } 5521 5522 /** 5523 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5524 * The base implementation sets: 5525 * <ul> 5526 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5527 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5528 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5529 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5530 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5531 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5532 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5533 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5534 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5535 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5536 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5537 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5538 * </ul> 5539 * <p> 5540 * Subclasses should override this method, call the super implementation, 5541 * and set additional attributes. 5542 * </p> 5543 * <p> 5544 * If an {@link AccessibilityDelegate} has been specified via calling 5545 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5546 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5547 * is responsible for handling this call. 5548 * </p> 5549 * 5550 * @param info The instance to initialize. 5551 */ 5552 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5553 if (mAccessibilityDelegate != null) { 5554 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5555 } else { 5556 onInitializeAccessibilityNodeInfoInternal(info); 5557 } 5558 } 5559 5560 /** 5561 * Gets the location of this view in screen coordintates. 5562 * 5563 * @param outRect The output location 5564 * @hide 5565 */ 5566 public void getBoundsOnScreen(Rect outRect) { 5567 if (mAttachInfo == null) { 5568 return; 5569 } 5570 5571 RectF position = mAttachInfo.mTmpTransformRect; 5572 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5573 5574 if (!hasIdentityMatrix()) { 5575 getMatrix().mapRect(position); 5576 } 5577 5578 position.offset(mLeft, mTop); 5579 5580 ViewParent parent = mParent; 5581 while (parent instanceof View) { 5582 View parentView = (View) parent; 5583 5584 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5585 5586 if (!parentView.hasIdentityMatrix()) { 5587 parentView.getMatrix().mapRect(position); 5588 } 5589 5590 position.offset(parentView.mLeft, parentView.mTop); 5591 5592 parent = parentView.mParent; 5593 } 5594 5595 if (parent instanceof ViewRootImpl) { 5596 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5597 position.offset(0, -viewRootImpl.mCurScrollY); 5598 } 5599 5600 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5601 5602 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5603 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5604 } 5605 5606 /** 5607 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5608 * 5609 * Note: Called from the default {@link AccessibilityDelegate}. 5610 */ 5611 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5612 Rect bounds = mAttachInfo.mTmpInvalRect; 5613 5614 getDrawingRect(bounds); 5615 info.setBoundsInParent(bounds); 5616 5617 getBoundsOnScreen(bounds); 5618 info.setBoundsInScreen(bounds); 5619 5620 ViewParent parent = getParentForAccessibility(); 5621 if (parent instanceof View) { 5622 info.setParent((View) parent); 5623 } 5624 5625 if (mID != View.NO_ID) { 5626 View rootView = getRootView(); 5627 if (rootView == null) { 5628 rootView = this; 5629 } 5630 5631 View label = rootView.findLabelForView(this, mID); 5632 if (label != null) { 5633 info.setLabeledBy(label); 5634 } 5635 5636 if ((mAttachInfo.mAccessibilityFetchFlags 5637 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5638 && Resources.resourceHasPackage(mID)) { 5639 try { 5640 String viewId = getResources().getResourceName(mID); 5641 info.setViewIdResourceName(viewId); 5642 } catch (Resources.NotFoundException nfe) { 5643 /* ignore */ 5644 } 5645 } 5646 } 5647 5648 if (mLabelForId != View.NO_ID) { 5649 View rootView = getRootView(); 5650 if (rootView == null) { 5651 rootView = this; 5652 } 5653 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5654 if (labeled != null) { 5655 info.setLabelFor(labeled); 5656 } 5657 } 5658 5659 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 5660 View rootView = getRootView(); 5661 if (rootView == null) { 5662 rootView = this; 5663 } 5664 View next = rootView.findViewInsideOutShouldExist(this, 5665 mAccessibilityTraversalBeforeId); 5666 if (next != null) { 5667 info.setTraversalBefore(next); 5668 } 5669 } 5670 5671 if (mAccessibilityTraversalAfterId != View.NO_ID) { 5672 View rootView = getRootView(); 5673 if (rootView == null) { 5674 rootView = this; 5675 } 5676 View next = rootView.findViewInsideOutShouldExist(this, 5677 mAccessibilityTraversalAfterId); 5678 if (next != null) { 5679 info.setTraversalAfter(next); 5680 } 5681 } 5682 5683 info.setVisibleToUser(isVisibleToUser()); 5684 5685 info.setPackageName(mContext.getPackageName()); 5686 info.setClassName(View.class.getName()); 5687 info.setContentDescription(getContentDescription()); 5688 5689 info.setEnabled(isEnabled()); 5690 info.setClickable(isClickable()); 5691 info.setFocusable(isFocusable()); 5692 info.setFocused(isFocused()); 5693 info.setAccessibilityFocused(isAccessibilityFocused()); 5694 info.setSelected(isSelected()); 5695 info.setLongClickable(isLongClickable()); 5696 info.setLiveRegion(getAccessibilityLiveRegion()); 5697 5698 // TODO: These make sense only if we are in an AdapterView but all 5699 // views can be selected. Maybe from accessibility perspective 5700 // we should report as selectable view in an AdapterView. 5701 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5702 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5703 5704 if (isFocusable()) { 5705 if (isFocused()) { 5706 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5707 } else { 5708 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5709 } 5710 } 5711 5712 if (!isAccessibilityFocused()) { 5713 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5714 } else { 5715 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5716 } 5717 5718 if (isClickable() && isEnabled()) { 5719 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5720 } 5721 5722 if (isLongClickable() && isEnabled()) { 5723 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5724 } 5725 5726 CharSequence text = getIterableTextForAccessibility(); 5727 if (text != null && text.length() > 0) { 5728 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5729 5730 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5731 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5732 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5733 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5734 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5735 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5736 } 5737 } 5738 5739 private View findLabelForView(View view, int labeledId) { 5740 if (mMatchLabelForPredicate == null) { 5741 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5742 } 5743 mMatchLabelForPredicate.mLabeledId = labeledId; 5744 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5745 } 5746 5747 /** 5748 * Computes whether this view is visible to the user. Such a view is 5749 * attached, visible, all its predecessors are visible, it is not clipped 5750 * entirely by its predecessors, and has an alpha greater than zero. 5751 * 5752 * @return Whether the view is visible on the screen. 5753 * 5754 * @hide 5755 */ 5756 protected boolean isVisibleToUser() { 5757 return isVisibleToUser(null); 5758 } 5759 5760 /** 5761 * Computes whether the given portion of this view is visible to the user. 5762 * Such a view is attached, visible, all its predecessors are visible, 5763 * has an alpha greater than zero, and the specified portion is not 5764 * clipped entirely by its predecessors. 5765 * 5766 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5767 * <code>null</code>, and the entire view will be tested in this case. 5768 * When <code>true</code> is returned by the function, the actual visible 5769 * region will be stored in this parameter; that is, if boundInView is fully 5770 * contained within the view, no modification will be made, otherwise regions 5771 * outside of the visible area of the view will be clipped. 5772 * 5773 * @return Whether the specified portion of the view is visible on the screen. 5774 * 5775 * @hide 5776 */ 5777 protected boolean isVisibleToUser(Rect boundInView) { 5778 if (mAttachInfo != null) { 5779 // Attached to invisible window means this view is not visible. 5780 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5781 return false; 5782 } 5783 // An invisible predecessor or one with alpha zero means 5784 // that this view is not visible to the user. 5785 Object current = this; 5786 while (current instanceof View) { 5787 View view = (View) current; 5788 // We have attach info so this view is attached and there is no 5789 // need to check whether we reach to ViewRootImpl on the way up. 5790 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5791 view.getVisibility() != VISIBLE) { 5792 return false; 5793 } 5794 current = view.mParent; 5795 } 5796 // Check if the view is entirely covered by its predecessors. 5797 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5798 Point offset = mAttachInfo.mPoint; 5799 if (!getGlobalVisibleRect(visibleRect, offset)) { 5800 return false; 5801 } 5802 // Check if the visible portion intersects the rectangle of interest. 5803 if (boundInView != null) { 5804 visibleRect.offset(-offset.x, -offset.y); 5805 return boundInView.intersect(visibleRect); 5806 } 5807 return true; 5808 } 5809 return false; 5810 } 5811 5812 /** 5813 * Computes a point on which a sequence of a down/up event can be sent to 5814 * trigger clicking this view. This method is for the exclusive use by the 5815 * accessibility layer to determine where to send a click event in explore 5816 * by touch mode. 5817 * 5818 * @param interactiveRegion The interactive portion of this window. 5819 * @param outPoint The point to populate. 5820 * @return True of such a point exists. 5821 */ 5822 boolean computeClickPointInScreenForAccessibility(Region interactiveRegion, 5823 Point outPoint) { 5824 // Since the interactive portion of the view is a region but as a view 5825 // may have a transformation matrix which cannot be applied to a 5826 // region we compute the view bounds rectangle and all interactive 5827 // predecessor's and sibling's (siblings of predecessors included) 5828 // rectangles that intersect the view bounds. At the 5829 // end if the view was partially covered by another interactive 5830 // view we compute the view's interactive region and pick a point 5831 // on its boundary path as regions do not offer APIs to get inner 5832 // points. Note that the the code is optimized to fail early and 5833 // avoid unnecessary allocations plus computations. 5834 5835 // The current approach has edge cases that may produce false 5836 // positives or false negatives. For example, a portion of the 5837 // view may be covered by an interactive descendant of a 5838 // predecessor, which we do not compute. Also a view may be handling 5839 // raw touch events instead registering click listeners, which 5840 // we cannot compute. Despite these limitations this approach will 5841 // work most of the time and it is a huge improvement over just 5842 // blindly sending the down and up events in the center of the 5843 // view. 5844 5845 // Cannot click on an unattached view. 5846 if (mAttachInfo == null) { 5847 return false; 5848 } 5849 5850 // Attached to an invisible window means this view is not visible. 5851 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5852 return false; 5853 } 5854 5855 RectF bounds = mAttachInfo.mTmpTransformRect; 5856 bounds.set(0, 0, getWidth(), getHeight()); 5857 List<RectF> intersections = mAttachInfo.mTmpRectList; 5858 intersections.clear(); 5859 5860 if (mParent instanceof ViewGroup) { 5861 ViewGroup parentGroup = (ViewGroup) mParent; 5862 if (!parentGroup.translateBoundsAndIntersectionsInWindowCoordinates( 5863 this, bounds, intersections)) { 5864 intersections.clear(); 5865 return false; 5866 } 5867 } 5868 5869 // Take into account the window location. 5870 final int dx = mAttachInfo.mWindowLeft; 5871 final int dy = mAttachInfo.mWindowTop; 5872 bounds.offset(dx, dy); 5873 offsetRects(intersections, dx, dy); 5874 5875 if (intersections.isEmpty() && interactiveRegion == null) { 5876 outPoint.set((int) bounds.centerX(), (int) bounds.centerY()); 5877 } else { 5878 // This view is partially covered by other views, then compute 5879 // the not covered region and pick a point on its boundary. 5880 Region region = new Region(); 5881 region.set((int) bounds.left, (int) bounds.top, 5882 (int) bounds.right, (int) bounds.bottom); 5883 5884 final int intersectionCount = intersections.size(); 5885 for (int i = intersectionCount - 1; i >= 0; i--) { 5886 RectF intersection = intersections.remove(i); 5887 region.op((int) intersection.left, (int) intersection.top, 5888 (int) intersection.right, (int) intersection.bottom, 5889 Region.Op.DIFFERENCE); 5890 } 5891 5892 // If the view is completely covered, done. 5893 if (region.isEmpty()) { 5894 return false; 5895 } 5896 5897 // Take into account the interactive portion of the window 5898 // as the rest is covered by other windows. If no such a region 5899 // then the whole window is interactive. 5900 if (interactiveRegion != null) { 5901 region.op(interactiveRegion, Region.Op.INTERSECT); 5902 } 5903 5904 // Take into account the window bounds. 5905 final View root = getRootView(); 5906 if (root != null) { 5907 region.op(dx, dy, root.getWidth() + dx, root.getHeight() + dy, Region.Op.INTERSECT); 5908 } 5909 5910 // If the view is completely covered, done. 5911 if (region.isEmpty()) { 5912 return false; 5913 } 5914 5915 // Try a shortcut here. 5916 if (region.isRect()) { 5917 Rect regionBounds = mAttachInfo.mTmpInvalRect; 5918 region.getBounds(regionBounds); 5919 outPoint.set(regionBounds.centerX(), regionBounds.centerY()); 5920 return true; 5921 } 5922 5923 // Get the a point on the region boundary path. 5924 Path path = region.getBoundaryPath(); 5925 PathMeasure pathMeasure = new PathMeasure(path, false); 5926 final float[] coordinates = mAttachInfo.mTmpTransformLocation; 5927 5928 // Without loss of generality pick a point. 5929 final float point = pathMeasure.getLength() * 0.01f; 5930 if (!pathMeasure.getPosTan(point, coordinates, null)) { 5931 return false; 5932 } 5933 5934 outPoint.set(Math.round(coordinates[0]), Math.round(coordinates[1])); 5935 } 5936 5937 return true; 5938 } 5939 5940 /** 5941 * Adds the clickable rectangles withing the bounds of this view. They 5942 * may overlap. This method is intended for use only by the accessibility 5943 * layer. 5944 * 5945 * @param outRects List to which to add clickable areas. 5946 */ 5947 void addClickableRectsForAccessibility(List<RectF> outRects) { 5948 if (isClickable() || isLongClickable()) { 5949 RectF bounds = new RectF(); 5950 bounds.set(0, 0, getWidth(), getHeight()); 5951 outRects.add(bounds); 5952 } 5953 } 5954 5955 static void offsetRects(List<RectF> rects, float offsetX, float offsetY) { 5956 final int rectCount = rects.size(); 5957 for (int i = 0; i < rectCount; i++) { 5958 RectF intersection = rects.get(i); 5959 intersection.offset(offsetX, offsetY); 5960 } 5961 } 5962 5963 /** 5964 * Returns the delegate for implementing accessibility support via 5965 * composition. For more details see {@link AccessibilityDelegate}. 5966 * 5967 * @return The delegate, or null if none set. 5968 * 5969 * @hide 5970 */ 5971 public AccessibilityDelegate getAccessibilityDelegate() { 5972 return mAccessibilityDelegate; 5973 } 5974 5975 /** 5976 * Sets a delegate for implementing accessibility support via composition as 5977 * opposed to inheritance. The delegate's primary use is for implementing 5978 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5979 * 5980 * @param delegate The delegate instance. 5981 * 5982 * @see AccessibilityDelegate 5983 */ 5984 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5985 mAccessibilityDelegate = delegate; 5986 } 5987 5988 /** 5989 * Gets the provider for managing a virtual view hierarchy rooted at this View 5990 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5991 * that explore the window content. 5992 * <p> 5993 * If this method returns an instance, this instance is responsible for managing 5994 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5995 * View including the one representing the View itself. Similarly the returned 5996 * instance is responsible for performing accessibility actions on any virtual 5997 * view or the root view itself. 5998 * </p> 5999 * <p> 6000 * If an {@link AccessibilityDelegate} has been specified via calling 6001 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6002 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 6003 * is responsible for handling this call. 6004 * </p> 6005 * 6006 * @return The provider. 6007 * 6008 * @see AccessibilityNodeProvider 6009 */ 6010 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 6011 if (mAccessibilityDelegate != null) { 6012 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 6013 } else { 6014 return null; 6015 } 6016 } 6017 6018 /** 6019 * Gets the unique identifier of this view on the screen for accessibility purposes. 6020 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 6021 * 6022 * @return The view accessibility id. 6023 * 6024 * @hide 6025 */ 6026 public int getAccessibilityViewId() { 6027 if (mAccessibilityViewId == NO_ID) { 6028 mAccessibilityViewId = sNextAccessibilityViewId++; 6029 } 6030 return mAccessibilityViewId; 6031 } 6032 6033 /** 6034 * Gets the unique identifier of the window in which this View reseides. 6035 * 6036 * @return The window accessibility id. 6037 * 6038 * @hide 6039 */ 6040 public int getAccessibilityWindowId() { 6041 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 6042 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6043 } 6044 6045 /** 6046 * Gets the {@link View} description. It briefly describes the view and is 6047 * primarily used for accessibility support. Set this property to enable 6048 * better accessibility support for your application. This is especially 6049 * true for views that do not have textual representation (For example, 6050 * ImageButton). 6051 * 6052 * @return The content description. 6053 * 6054 * @attr ref android.R.styleable#View_contentDescription 6055 */ 6056 @ViewDebug.ExportedProperty(category = "accessibility") 6057 public CharSequence getContentDescription() { 6058 return mContentDescription; 6059 } 6060 6061 /** 6062 * Sets the {@link View} description. It briefly describes the view and is 6063 * primarily used for accessibility support. Set this property to enable 6064 * better accessibility support for your application. This is especially 6065 * true for views that do not have textual representation (For example, 6066 * ImageButton). 6067 * 6068 * @param contentDescription The content description. 6069 * 6070 * @attr ref android.R.styleable#View_contentDescription 6071 */ 6072 @RemotableViewMethod 6073 public void setContentDescription(CharSequence contentDescription) { 6074 if (mContentDescription == null) { 6075 if (contentDescription == null) { 6076 return; 6077 } 6078 } else if (mContentDescription.equals(contentDescription)) { 6079 return; 6080 } 6081 mContentDescription = contentDescription; 6082 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 6083 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 6084 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 6085 notifySubtreeAccessibilityStateChangedIfNeeded(); 6086 } else { 6087 notifyViewAccessibilityStateChangedIfNeeded( 6088 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 6089 } 6090 } 6091 6092 /** 6093 * Sets the id of a view before which this one is visited in accessibility traversal. 6094 * A screen-reader must visit the content of this view before the content of the one 6095 * it precedes. For example, if view B is set to be before view A, then a screen-reader 6096 * will traverse the entire content of B before traversing the entire content of A, 6097 * regardles of what traversal strategy it is using. 6098 * <p> 6099 * Views that do not have specified before/after relationships are traversed in order 6100 * determined by the screen-reader. 6101 * </p> 6102 * <p> 6103 * Setting that this view is before a view that is not important for accessibility 6104 * or if this view is not important for accessibility will have no effect as the 6105 * screen-reader is not aware of unimportant views. 6106 * </p> 6107 * 6108 * @param beforeId The id of a view this one precedes in accessibility traversal. 6109 * 6110 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 6111 * 6112 * @see #setImportantForAccessibility(int) 6113 */ 6114 @RemotableViewMethod 6115 public void setAccessibilityTraversalBefore(int beforeId) { 6116 if (mAccessibilityTraversalBeforeId == beforeId) { 6117 return; 6118 } 6119 mAccessibilityTraversalBeforeId = beforeId; 6120 notifyViewAccessibilityStateChangedIfNeeded( 6121 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6122 } 6123 6124 /** 6125 * Gets the id of a view before which this one is visited in accessibility traversal. 6126 * 6127 * @return The id of a view this one precedes in accessibility traversal if 6128 * specified, otherwise {@link #NO_ID}. 6129 * 6130 * @see #setAccessibilityTraversalBefore(int) 6131 */ 6132 public int getAccessibilityTraversalBefore() { 6133 return mAccessibilityTraversalBeforeId; 6134 } 6135 6136 /** 6137 * Sets the id of a view after which this one is visited in accessibility traversal. 6138 * A screen-reader must visit the content of the other view before the content of this 6139 * one. For example, if view B is set to be after view A, then a screen-reader 6140 * will traverse the entire content of A before traversing the entire content of B, 6141 * regardles of what traversal strategy it is using. 6142 * <p> 6143 * Views that do not have specified before/after relationships are traversed in order 6144 * determined by the screen-reader. 6145 * </p> 6146 * <p> 6147 * Setting that this view is after a view that is not important for accessibility 6148 * or if this view is not important for accessibility will have no effect as the 6149 * screen-reader is not aware of unimportant views. 6150 * </p> 6151 * 6152 * @param afterId The id of a view this one succedees in accessibility traversal. 6153 * 6154 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 6155 * 6156 * @see #setImportantForAccessibility(int) 6157 */ 6158 @RemotableViewMethod 6159 public void setAccessibilityTraversalAfter(int afterId) { 6160 if (mAccessibilityTraversalAfterId == afterId) { 6161 return; 6162 } 6163 mAccessibilityTraversalAfterId = afterId; 6164 notifyViewAccessibilityStateChangedIfNeeded( 6165 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6166 } 6167 6168 /** 6169 * Gets the id of a view after which this one is visited in accessibility traversal. 6170 * 6171 * @return The id of a view this one succeedes in accessibility traversal if 6172 * specified, otherwise {@link #NO_ID}. 6173 * 6174 * @see #setAccessibilityTraversalAfter(int) 6175 */ 6176 public int getAccessibilityTraversalAfter() { 6177 return mAccessibilityTraversalAfterId; 6178 } 6179 6180 /** 6181 * Gets the id of a view for which this view serves as a label for 6182 * accessibility purposes. 6183 * 6184 * @return The labeled view id. 6185 */ 6186 @ViewDebug.ExportedProperty(category = "accessibility") 6187 public int getLabelFor() { 6188 return mLabelForId; 6189 } 6190 6191 /** 6192 * Sets the id of a view for which this view serves as a label for 6193 * accessibility purposes. 6194 * 6195 * @param id The labeled view id. 6196 */ 6197 @RemotableViewMethod 6198 public void setLabelFor(int id) { 6199 if (mLabelForId == id) { 6200 return; 6201 } 6202 mLabelForId = id; 6203 if (mLabelForId != View.NO_ID 6204 && mID == View.NO_ID) { 6205 mID = generateViewId(); 6206 } 6207 notifyViewAccessibilityStateChangedIfNeeded( 6208 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6209 } 6210 6211 /** 6212 * Invoked whenever this view loses focus, either by losing window focus or by losing 6213 * focus within its window. This method can be used to clear any state tied to the 6214 * focus. For instance, if a button is held pressed with the trackball and the window 6215 * loses focus, this method can be used to cancel the press. 6216 * 6217 * Subclasses of View overriding this method should always call super.onFocusLost(). 6218 * 6219 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 6220 * @see #onWindowFocusChanged(boolean) 6221 * 6222 * @hide pending API council approval 6223 */ 6224 protected void onFocusLost() { 6225 resetPressedState(); 6226 } 6227 6228 private void resetPressedState() { 6229 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6230 return; 6231 } 6232 6233 if (isPressed()) { 6234 setPressed(false); 6235 6236 if (!mHasPerformedLongPress) { 6237 removeLongPressCallback(); 6238 } 6239 } 6240 } 6241 6242 /** 6243 * Returns true if this view has focus 6244 * 6245 * @return True if this view has focus, false otherwise. 6246 */ 6247 @ViewDebug.ExportedProperty(category = "focus") 6248 public boolean isFocused() { 6249 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6250 } 6251 6252 /** 6253 * Find the view in the hierarchy rooted at this view that currently has 6254 * focus. 6255 * 6256 * @return The view that currently has focus, or null if no focused view can 6257 * be found. 6258 */ 6259 public View findFocus() { 6260 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 6261 } 6262 6263 /** 6264 * Indicates whether this view is one of the set of scrollable containers in 6265 * its window. 6266 * 6267 * @return whether this view is one of the set of scrollable containers in 6268 * its window 6269 * 6270 * @attr ref android.R.styleable#View_isScrollContainer 6271 */ 6272 public boolean isScrollContainer() { 6273 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 6274 } 6275 6276 /** 6277 * Change whether this view is one of the set of scrollable containers in 6278 * its window. This will be used to determine whether the window can 6279 * resize or must pan when a soft input area is open -- scrollable 6280 * containers allow the window to use resize mode since the container 6281 * will appropriately shrink. 6282 * 6283 * @attr ref android.R.styleable#View_isScrollContainer 6284 */ 6285 public void setScrollContainer(boolean isScrollContainer) { 6286 if (isScrollContainer) { 6287 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 6288 mAttachInfo.mScrollContainers.add(this); 6289 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 6290 } 6291 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 6292 } else { 6293 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 6294 mAttachInfo.mScrollContainers.remove(this); 6295 } 6296 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 6297 } 6298 } 6299 6300 /** 6301 * Returns the quality of the drawing cache. 6302 * 6303 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6304 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6305 * 6306 * @see #setDrawingCacheQuality(int) 6307 * @see #setDrawingCacheEnabled(boolean) 6308 * @see #isDrawingCacheEnabled() 6309 * 6310 * @attr ref android.R.styleable#View_drawingCacheQuality 6311 */ 6312 @DrawingCacheQuality 6313 public int getDrawingCacheQuality() { 6314 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 6315 } 6316 6317 /** 6318 * Set the drawing cache quality of this view. This value is used only when the 6319 * drawing cache is enabled 6320 * 6321 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6322 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6323 * 6324 * @see #getDrawingCacheQuality() 6325 * @see #setDrawingCacheEnabled(boolean) 6326 * @see #isDrawingCacheEnabled() 6327 * 6328 * @attr ref android.R.styleable#View_drawingCacheQuality 6329 */ 6330 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 6331 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 6332 } 6333 6334 /** 6335 * Returns whether the screen should remain on, corresponding to the current 6336 * value of {@link #KEEP_SCREEN_ON}. 6337 * 6338 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 6339 * 6340 * @see #setKeepScreenOn(boolean) 6341 * 6342 * @attr ref android.R.styleable#View_keepScreenOn 6343 */ 6344 public boolean getKeepScreenOn() { 6345 return (mViewFlags & KEEP_SCREEN_ON) != 0; 6346 } 6347 6348 /** 6349 * Controls whether the screen should remain on, modifying the 6350 * value of {@link #KEEP_SCREEN_ON}. 6351 * 6352 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 6353 * 6354 * @see #getKeepScreenOn() 6355 * 6356 * @attr ref android.R.styleable#View_keepScreenOn 6357 */ 6358 public void setKeepScreenOn(boolean keepScreenOn) { 6359 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 6360 } 6361 6362 /** 6363 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6364 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6365 * 6366 * @attr ref android.R.styleable#View_nextFocusLeft 6367 */ 6368 public int getNextFocusLeftId() { 6369 return mNextFocusLeftId; 6370 } 6371 6372 /** 6373 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6374 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 6375 * decide automatically. 6376 * 6377 * @attr ref android.R.styleable#View_nextFocusLeft 6378 */ 6379 public void setNextFocusLeftId(int nextFocusLeftId) { 6380 mNextFocusLeftId = nextFocusLeftId; 6381 } 6382 6383 /** 6384 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6385 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6386 * 6387 * @attr ref android.R.styleable#View_nextFocusRight 6388 */ 6389 public int getNextFocusRightId() { 6390 return mNextFocusRightId; 6391 } 6392 6393 /** 6394 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6395 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 6396 * decide automatically. 6397 * 6398 * @attr ref android.R.styleable#View_nextFocusRight 6399 */ 6400 public void setNextFocusRightId(int nextFocusRightId) { 6401 mNextFocusRightId = nextFocusRightId; 6402 } 6403 6404 /** 6405 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6406 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6407 * 6408 * @attr ref android.R.styleable#View_nextFocusUp 6409 */ 6410 public int getNextFocusUpId() { 6411 return mNextFocusUpId; 6412 } 6413 6414 /** 6415 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6416 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6417 * decide automatically. 6418 * 6419 * @attr ref android.R.styleable#View_nextFocusUp 6420 */ 6421 public void setNextFocusUpId(int nextFocusUpId) { 6422 mNextFocusUpId = nextFocusUpId; 6423 } 6424 6425 /** 6426 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6427 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6428 * 6429 * @attr ref android.R.styleable#View_nextFocusDown 6430 */ 6431 public int getNextFocusDownId() { 6432 return mNextFocusDownId; 6433 } 6434 6435 /** 6436 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6437 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6438 * decide automatically. 6439 * 6440 * @attr ref android.R.styleable#View_nextFocusDown 6441 */ 6442 public void setNextFocusDownId(int nextFocusDownId) { 6443 mNextFocusDownId = nextFocusDownId; 6444 } 6445 6446 /** 6447 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6448 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6449 * 6450 * @attr ref android.R.styleable#View_nextFocusForward 6451 */ 6452 public int getNextFocusForwardId() { 6453 return mNextFocusForwardId; 6454 } 6455 6456 /** 6457 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6458 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6459 * decide automatically. 6460 * 6461 * @attr ref android.R.styleable#View_nextFocusForward 6462 */ 6463 public void setNextFocusForwardId(int nextFocusForwardId) { 6464 mNextFocusForwardId = nextFocusForwardId; 6465 } 6466 6467 /** 6468 * Returns the visibility of this view and all of its ancestors 6469 * 6470 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6471 */ 6472 public boolean isShown() { 6473 View current = this; 6474 //noinspection ConstantConditions 6475 do { 6476 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6477 return false; 6478 } 6479 ViewParent parent = current.mParent; 6480 if (parent == null) { 6481 return false; // We are not attached to the view root 6482 } 6483 if (!(parent instanceof View)) { 6484 return true; 6485 } 6486 current = (View) parent; 6487 } while (current != null); 6488 6489 return false; 6490 } 6491 6492 /** 6493 * Called by the view hierarchy when the content insets for a window have 6494 * changed, to allow it to adjust its content to fit within those windows. 6495 * The content insets tell you the space that the status bar, input method, 6496 * and other system windows infringe on the application's window. 6497 * 6498 * <p>You do not normally need to deal with this function, since the default 6499 * window decoration given to applications takes care of applying it to the 6500 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6501 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6502 * and your content can be placed under those system elements. You can then 6503 * use this method within your view hierarchy if you have parts of your UI 6504 * which you would like to ensure are not being covered. 6505 * 6506 * <p>The default implementation of this method simply applies the content 6507 * insets to the view's padding, consuming that content (modifying the 6508 * insets to be 0), and returning true. This behavior is off by default, but can 6509 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6510 * 6511 * <p>This function's traversal down the hierarchy is depth-first. The same content 6512 * insets object is propagated down the hierarchy, so any changes made to it will 6513 * be seen by all following views (including potentially ones above in 6514 * the hierarchy since this is a depth-first traversal). The first view 6515 * that returns true will abort the entire traversal. 6516 * 6517 * <p>The default implementation works well for a situation where it is 6518 * used with a container that covers the entire window, allowing it to 6519 * apply the appropriate insets to its content on all edges. If you need 6520 * a more complicated layout (such as two different views fitting system 6521 * windows, one on the top of the window, and one on the bottom), 6522 * you can override the method and handle the insets however you would like. 6523 * Note that the insets provided by the framework are always relative to the 6524 * far edges of the window, not accounting for the location of the called view 6525 * within that window. (In fact when this method is called you do not yet know 6526 * where the layout will place the view, as it is done before layout happens.) 6527 * 6528 * <p>Note: unlike many View methods, there is no dispatch phase to this 6529 * call. If you are overriding it in a ViewGroup and want to allow the 6530 * call to continue to your children, you must be sure to call the super 6531 * implementation. 6532 * 6533 * <p>Here is a sample layout that makes use of fitting system windows 6534 * to have controls for a video view placed inside of the window decorations 6535 * that it hides and shows. This can be used with code like the second 6536 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6537 * 6538 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6539 * 6540 * @param insets Current content insets of the window. Prior to 6541 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6542 * the insets or else you and Android will be unhappy. 6543 * 6544 * @return {@code true} if this view applied the insets and it should not 6545 * continue propagating further down the hierarchy, {@code false} otherwise. 6546 * @see #getFitsSystemWindows() 6547 * @see #setFitsSystemWindows(boolean) 6548 * @see #setSystemUiVisibility(int) 6549 * 6550 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6551 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6552 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6553 * to implement handling their own insets. 6554 */ 6555 protected boolean fitSystemWindows(Rect insets) { 6556 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6557 if (insets == null) { 6558 // Null insets by definition have already been consumed. 6559 // This call cannot apply insets since there are none to apply, 6560 // so return false. 6561 return false; 6562 } 6563 // If we're not in the process of dispatching the newer apply insets call, 6564 // that means we're not in the compatibility path. Dispatch into the newer 6565 // apply insets path and take things from there. 6566 try { 6567 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6568 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 6569 } finally { 6570 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6571 } 6572 } else { 6573 // We're being called from the newer apply insets path. 6574 // Perform the standard fallback behavior. 6575 return fitSystemWindowsInt(insets); 6576 } 6577 } 6578 6579 private boolean fitSystemWindowsInt(Rect insets) { 6580 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6581 mUserPaddingStart = UNDEFINED_PADDING; 6582 mUserPaddingEnd = UNDEFINED_PADDING; 6583 Rect localInsets = sThreadLocal.get(); 6584 if (localInsets == null) { 6585 localInsets = new Rect(); 6586 sThreadLocal.set(localInsets); 6587 } 6588 boolean res = computeFitSystemWindows(insets, localInsets); 6589 mUserPaddingLeftInitial = localInsets.left; 6590 mUserPaddingRightInitial = localInsets.right; 6591 internalSetPadding(localInsets.left, localInsets.top, 6592 localInsets.right, localInsets.bottom); 6593 return res; 6594 } 6595 return false; 6596 } 6597 6598 /** 6599 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6600 * 6601 * <p>This method should be overridden by views that wish to apply a policy different from or 6602 * in addition to the default behavior. Clients that wish to force a view subtree 6603 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6604 * 6605 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6606 * it will be called during dispatch instead of this method. The listener may optionally 6607 * call this method from its own implementation if it wishes to apply the view's default 6608 * insets policy in addition to its own.</p> 6609 * 6610 * <p>Implementations of this method should either return the insets parameter unchanged 6611 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6612 * that this view applied itself. This allows new inset types added in future platform 6613 * versions to pass through existing implementations unchanged without being erroneously 6614 * consumed.</p> 6615 * 6616 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6617 * property is set then the view will consume the system window insets and apply them 6618 * as padding for the view.</p> 6619 * 6620 * @param insets Insets to apply 6621 * @return The supplied insets with any applied insets consumed 6622 */ 6623 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6624 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6625 // We weren't called from within a direct call to fitSystemWindows, 6626 // call into it as a fallback in case we're in a class that overrides it 6627 // and has logic to perform. 6628 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6629 return insets.consumeSystemWindowInsets(); 6630 } 6631 } else { 6632 // We were called from within a direct call to fitSystemWindows. 6633 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6634 return insets.consumeSystemWindowInsets(); 6635 } 6636 } 6637 return insets; 6638 } 6639 6640 /** 6641 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6642 * window insets to this view. The listener's 6643 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6644 * method will be called instead of the view's 6645 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6646 * 6647 * @param listener Listener to set 6648 * 6649 * @see #onApplyWindowInsets(WindowInsets) 6650 */ 6651 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6652 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6653 } 6654 6655 /** 6656 * Request to apply the given window insets to this view or another view in its subtree. 6657 * 6658 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6659 * obscured by window decorations or overlays. This can include the status and navigation bars, 6660 * action bars, input methods and more. New inset categories may be added in the future. 6661 * The method returns the insets provided minus any that were applied by this view or its 6662 * children.</p> 6663 * 6664 * <p>Clients wishing to provide custom behavior should override the 6665 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6666 * {@link OnApplyWindowInsetsListener} via the 6667 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6668 * method.</p> 6669 * 6670 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6671 * </p> 6672 * 6673 * @param insets Insets to apply 6674 * @return The provided insets minus the insets that were consumed 6675 */ 6676 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6677 try { 6678 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6679 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6680 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6681 } else { 6682 return onApplyWindowInsets(insets); 6683 } 6684 } finally { 6685 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6686 } 6687 } 6688 6689 /** 6690 * @hide Compute the insets that should be consumed by this view and the ones 6691 * that should propagate to those under it. 6692 */ 6693 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6694 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6695 || mAttachInfo == null 6696 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6697 && !mAttachInfo.mOverscanRequested)) { 6698 outLocalInsets.set(inoutInsets); 6699 inoutInsets.set(0, 0, 0, 0); 6700 return true; 6701 } else { 6702 // The application wants to take care of fitting system window for 6703 // the content... however we still need to take care of any overscan here. 6704 final Rect overscan = mAttachInfo.mOverscanInsets; 6705 outLocalInsets.set(overscan); 6706 inoutInsets.left -= overscan.left; 6707 inoutInsets.top -= overscan.top; 6708 inoutInsets.right -= overscan.right; 6709 inoutInsets.bottom -= overscan.bottom; 6710 return false; 6711 } 6712 } 6713 6714 /** 6715 * Compute insets that should be consumed by this view and the ones that should propagate 6716 * to those under it. 6717 * 6718 * @param in Insets currently being processed by this View, likely received as a parameter 6719 * to {@link #onApplyWindowInsets(WindowInsets)}. 6720 * @param outLocalInsets A Rect that will receive the insets that should be consumed 6721 * by this view 6722 * @return Insets that should be passed along to views under this one 6723 */ 6724 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 6725 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6726 || mAttachInfo == null 6727 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 6728 outLocalInsets.set(in.getSystemWindowInsets()); 6729 return in.consumeSystemWindowInsets(); 6730 } else { 6731 outLocalInsets.set(0, 0, 0, 0); 6732 return in; 6733 } 6734 } 6735 6736 /** 6737 * Sets whether or not this view should account for system screen decorations 6738 * such as the status bar and inset its content; that is, controlling whether 6739 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6740 * executed. See that method for more details. 6741 * 6742 * <p>Note that if you are providing your own implementation of 6743 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6744 * flag to true -- your implementation will be overriding the default 6745 * implementation that checks this flag. 6746 * 6747 * @param fitSystemWindows If true, then the default implementation of 6748 * {@link #fitSystemWindows(Rect)} will be executed. 6749 * 6750 * @attr ref android.R.styleable#View_fitsSystemWindows 6751 * @see #getFitsSystemWindows() 6752 * @see #fitSystemWindows(Rect) 6753 * @see #setSystemUiVisibility(int) 6754 */ 6755 public void setFitsSystemWindows(boolean fitSystemWindows) { 6756 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6757 } 6758 6759 /** 6760 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6761 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6762 * will be executed. 6763 * 6764 * @return {@code true} if the default implementation of 6765 * {@link #fitSystemWindows(Rect)} will be executed. 6766 * 6767 * @attr ref android.R.styleable#View_fitsSystemWindows 6768 * @see #setFitsSystemWindows(boolean) 6769 * @see #fitSystemWindows(Rect) 6770 * @see #setSystemUiVisibility(int) 6771 */ 6772 @ViewDebug.ExportedProperty 6773 public boolean getFitsSystemWindows() { 6774 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6775 } 6776 6777 /** @hide */ 6778 public boolean fitsSystemWindows() { 6779 return getFitsSystemWindows(); 6780 } 6781 6782 /** 6783 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6784 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6785 */ 6786 public void requestFitSystemWindows() { 6787 if (mParent != null) { 6788 mParent.requestFitSystemWindows(); 6789 } 6790 } 6791 6792 /** 6793 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6794 */ 6795 public void requestApplyInsets() { 6796 requestFitSystemWindows(); 6797 } 6798 6799 /** 6800 * For use by PhoneWindow to make its own system window fitting optional. 6801 * @hide 6802 */ 6803 public void makeOptionalFitsSystemWindows() { 6804 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6805 } 6806 6807 /** 6808 * Returns the visibility status for this view. 6809 * 6810 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6811 * @attr ref android.R.styleable#View_visibility 6812 */ 6813 @ViewDebug.ExportedProperty(mapping = { 6814 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6815 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6816 @ViewDebug.IntToString(from = GONE, to = "GONE") 6817 }) 6818 @Visibility 6819 public int getVisibility() { 6820 return mViewFlags & VISIBILITY_MASK; 6821 } 6822 6823 /** 6824 * Set the enabled state of this view. 6825 * 6826 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6827 * @attr ref android.R.styleable#View_visibility 6828 */ 6829 @RemotableViewMethod 6830 public void setVisibility(@Visibility int visibility) { 6831 setFlags(visibility, VISIBILITY_MASK); 6832 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6833 } 6834 6835 /** 6836 * Returns the enabled status for this view. The interpretation of the 6837 * enabled state varies by subclass. 6838 * 6839 * @return True if this view is enabled, false otherwise. 6840 */ 6841 @ViewDebug.ExportedProperty 6842 public boolean isEnabled() { 6843 return (mViewFlags & ENABLED_MASK) == ENABLED; 6844 } 6845 6846 /** 6847 * Set the enabled state of this view. The interpretation of the enabled 6848 * state varies by subclass. 6849 * 6850 * @param enabled True if this view is enabled, false otherwise. 6851 */ 6852 @RemotableViewMethod 6853 public void setEnabled(boolean enabled) { 6854 if (enabled == isEnabled()) return; 6855 6856 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6857 6858 /* 6859 * The View most likely has to change its appearance, so refresh 6860 * the drawable state. 6861 */ 6862 refreshDrawableState(); 6863 6864 // Invalidate too, since the default behavior for views is to be 6865 // be drawn at 50% alpha rather than to change the drawable. 6866 invalidate(true); 6867 6868 if (!enabled) { 6869 cancelPendingInputEvents(); 6870 } 6871 } 6872 6873 /** 6874 * Set whether this view can receive the focus. 6875 * 6876 * Setting this to false will also ensure that this view is not focusable 6877 * in touch mode. 6878 * 6879 * @param focusable If true, this view can receive the focus. 6880 * 6881 * @see #setFocusableInTouchMode(boolean) 6882 * @attr ref android.R.styleable#View_focusable 6883 */ 6884 public void setFocusable(boolean focusable) { 6885 if (!focusable) { 6886 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6887 } 6888 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6889 } 6890 6891 /** 6892 * Set whether this view can receive focus while in touch mode. 6893 * 6894 * Setting this to true will also ensure that this view is focusable. 6895 * 6896 * @param focusableInTouchMode If true, this view can receive the focus while 6897 * in touch mode. 6898 * 6899 * @see #setFocusable(boolean) 6900 * @attr ref android.R.styleable#View_focusableInTouchMode 6901 */ 6902 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6903 // Focusable in touch mode should always be set before the focusable flag 6904 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6905 // which, in touch mode, will not successfully request focus on this view 6906 // because the focusable in touch mode flag is not set 6907 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6908 if (focusableInTouchMode) { 6909 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6910 } 6911 } 6912 6913 /** 6914 * Set whether this view should have sound effects enabled for events such as 6915 * clicking and touching. 6916 * 6917 * <p>You may wish to disable sound effects for a view if you already play sounds, 6918 * for instance, a dial key that plays dtmf tones. 6919 * 6920 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6921 * @see #isSoundEffectsEnabled() 6922 * @see #playSoundEffect(int) 6923 * @attr ref android.R.styleable#View_soundEffectsEnabled 6924 */ 6925 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6926 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6927 } 6928 6929 /** 6930 * @return whether this view should have sound effects enabled for events such as 6931 * clicking and touching. 6932 * 6933 * @see #setSoundEffectsEnabled(boolean) 6934 * @see #playSoundEffect(int) 6935 * @attr ref android.R.styleable#View_soundEffectsEnabled 6936 */ 6937 @ViewDebug.ExportedProperty 6938 public boolean isSoundEffectsEnabled() { 6939 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6940 } 6941 6942 /** 6943 * Set whether this view should have haptic feedback for events such as 6944 * long presses. 6945 * 6946 * <p>You may wish to disable haptic feedback if your view already controls 6947 * its own haptic feedback. 6948 * 6949 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6950 * @see #isHapticFeedbackEnabled() 6951 * @see #performHapticFeedback(int) 6952 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6953 */ 6954 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6955 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6956 } 6957 6958 /** 6959 * @return whether this view should have haptic feedback enabled for events 6960 * long presses. 6961 * 6962 * @see #setHapticFeedbackEnabled(boolean) 6963 * @see #performHapticFeedback(int) 6964 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6965 */ 6966 @ViewDebug.ExportedProperty 6967 public boolean isHapticFeedbackEnabled() { 6968 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6969 } 6970 6971 /** 6972 * Returns the layout direction for this view. 6973 * 6974 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6975 * {@link #LAYOUT_DIRECTION_RTL}, 6976 * {@link #LAYOUT_DIRECTION_INHERIT} or 6977 * {@link #LAYOUT_DIRECTION_LOCALE}. 6978 * 6979 * @attr ref android.R.styleable#View_layoutDirection 6980 * 6981 * @hide 6982 */ 6983 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6984 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6985 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6986 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6987 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6988 }) 6989 @LayoutDir 6990 public int getRawLayoutDirection() { 6991 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6992 } 6993 6994 /** 6995 * Set the layout direction for this view. This will propagate a reset of layout direction 6996 * resolution to the view's children and resolve layout direction for this view. 6997 * 6998 * @param layoutDirection the layout direction to set. Should be one of: 6999 * 7000 * {@link #LAYOUT_DIRECTION_LTR}, 7001 * {@link #LAYOUT_DIRECTION_RTL}, 7002 * {@link #LAYOUT_DIRECTION_INHERIT}, 7003 * {@link #LAYOUT_DIRECTION_LOCALE}. 7004 * 7005 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 7006 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 7007 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 7008 * 7009 * @attr ref android.R.styleable#View_layoutDirection 7010 */ 7011 @RemotableViewMethod 7012 public void setLayoutDirection(@LayoutDir int layoutDirection) { 7013 if (getRawLayoutDirection() != layoutDirection) { 7014 // Reset the current layout direction and the resolved one 7015 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 7016 resetRtlProperties(); 7017 // Set the new layout direction (filtered) 7018 mPrivateFlags2 |= 7019 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 7020 // We need to resolve all RTL properties as they all depend on layout direction 7021 resolveRtlPropertiesIfNeeded(); 7022 requestLayout(); 7023 invalidate(true); 7024 } 7025 } 7026 7027 /** 7028 * Returns the resolved layout direction for this view. 7029 * 7030 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 7031 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 7032 * 7033 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 7034 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 7035 * 7036 * @attr ref android.R.styleable#View_layoutDirection 7037 */ 7038 @ViewDebug.ExportedProperty(category = "layout", mapping = { 7039 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 7040 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 7041 }) 7042 @ResolvedLayoutDir 7043 public int getLayoutDirection() { 7044 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 7045 if (targetSdkVersion < JELLY_BEAN_MR1) { 7046 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 7047 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 7048 } 7049 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 7050 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 7051 } 7052 7053 /** 7054 * Indicates whether or not this view's layout is right-to-left. This is resolved from 7055 * layout attribute and/or the inherited value from the parent 7056 * 7057 * @return true if the layout is right-to-left. 7058 * 7059 * @hide 7060 */ 7061 @ViewDebug.ExportedProperty(category = "layout") 7062 public boolean isLayoutRtl() { 7063 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 7064 } 7065 7066 /** 7067 * Indicates whether the view is currently tracking transient state that the 7068 * app should not need to concern itself with saving and restoring, but that 7069 * the framework should take special note to preserve when possible. 7070 * 7071 * <p>A view with transient state cannot be trivially rebound from an external 7072 * data source, such as an adapter binding item views in a list. This may be 7073 * because the view is performing an animation, tracking user selection 7074 * of content, or similar.</p> 7075 * 7076 * @return true if the view has transient state 7077 */ 7078 @ViewDebug.ExportedProperty(category = "layout") 7079 public boolean hasTransientState() { 7080 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 7081 } 7082 7083 /** 7084 * Set whether this view is currently tracking transient state that the 7085 * framework should attempt to preserve when possible. This flag is reference counted, 7086 * so every call to setHasTransientState(true) should be paired with a later call 7087 * to setHasTransientState(false). 7088 * 7089 * <p>A view with transient state cannot be trivially rebound from an external 7090 * data source, such as an adapter binding item views in a list. This may be 7091 * because the view is performing an animation, tracking user selection 7092 * of content, or similar.</p> 7093 * 7094 * @param hasTransientState true if this view has transient state 7095 */ 7096 public void setHasTransientState(boolean hasTransientState) { 7097 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 7098 mTransientStateCount - 1; 7099 if (mTransientStateCount < 0) { 7100 mTransientStateCount = 0; 7101 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 7102 "unmatched pair of setHasTransientState calls"); 7103 } else if ((hasTransientState && mTransientStateCount == 1) || 7104 (!hasTransientState && mTransientStateCount == 0)) { 7105 // update flag if we've just incremented up from 0 or decremented down to 0 7106 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 7107 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 7108 if (mParent != null) { 7109 try { 7110 mParent.childHasTransientStateChanged(this, hasTransientState); 7111 } catch (AbstractMethodError e) { 7112 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7113 " does not fully implement ViewParent", e); 7114 } 7115 } 7116 } 7117 } 7118 7119 /** 7120 * Returns true if this view is currently attached to a window. 7121 */ 7122 public boolean isAttachedToWindow() { 7123 return mAttachInfo != null; 7124 } 7125 7126 /** 7127 * Returns true if this view has been through at least one layout since it 7128 * was last attached to or detached from a window. 7129 */ 7130 public boolean isLaidOut() { 7131 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 7132 } 7133 7134 /** 7135 * If this view doesn't do any drawing on its own, set this flag to 7136 * allow further optimizations. By default, this flag is not set on 7137 * View, but could be set on some View subclasses such as ViewGroup. 7138 * 7139 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 7140 * you should clear this flag. 7141 * 7142 * @param willNotDraw whether or not this View draw on its own 7143 */ 7144 public void setWillNotDraw(boolean willNotDraw) { 7145 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 7146 } 7147 7148 /** 7149 * Returns whether or not this View draws on its own. 7150 * 7151 * @return true if this view has nothing to draw, false otherwise 7152 */ 7153 @ViewDebug.ExportedProperty(category = "drawing") 7154 public boolean willNotDraw() { 7155 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 7156 } 7157 7158 /** 7159 * When a View's drawing cache is enabled, drawing is redirected to an 7160 * offscreen bitmap. Some views, like an ImageView, must be able to 7161 * bypass this mechanism if they already draw a single bitmap, to avoid 7162 * unnecessary usage of the memory. 7163 * 7164 * @param willNotCacheDrawing true if this view does not cache its 7165 * drawing, false otherwise 7166 */ 7167 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 7168 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 7169 } 7170 7171 /** 7172 * Returns whether or not this View can cache its drawing or not. 7173 * 7174 * @return true if this view does not cache its drawing, false otherwise 7175 */ 7176 @ViewDebug.ExportedProperty(category = "drawing") 7177 public boolean willNotCacheDrawing() { 7178 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 7179 } 7180 7181 /** 7182 * Indicates whether this view reacts to click events or not. 7183 * 7184 * @return true if the view is clickable, false otherwise 7185 * 7186 * @see #setClickable(boolean) 7187 * @attr ref android.R.styleable#View_clickable 7188 */ 7189 @ViewDebug.ExportedProperty 7190 public boolean isClickable() { 7191 return (mViewFlags & CLICKABLE) == CLICKABLE; 7192 } 7193 7194 /** 7195 * Enables or disables click events for this view. When a view 7196 * is clickable it will change its state to "pressed" on every click. 7197 * Subclasses should set the view clickable to visually react to 7198 * user's clicks. 7199 * 7200 * @param clickable true to make the view clickable, false otherwise 7201 * 7202 * @see #isClickable() 7203 * @attr ref android.R.styleable#View_clickable 7204 */ 7205 public void setClickable(boolean clickable) { 7206 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 7207 } 7208 7209 /** 7210 * Indicates whether this view reacts to long click events or not. 7211 * 7212 * @return true if the view is long clickable, false otherwise 7213 * 7214 * @see #setLongClickable(boolean) 7215 * @attr ref android.R.styleable#View_longClickable 7216 */ 7217 public boolean isLongClickable() { 7218 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 7219 } 7220 7221 /** 7222 * Enables or disables long click events for this view. When a view is long 7223 * clickable it reacts to the user holding down the button for a longer 7224 * duration than a tap. This event can either launch the listener or a 7225 * context menu. 7226 * 7227 * @param longClickable true to make the view long clickable, false otherwise 7228 * @see #isLongClickable() 7229 * @attr ref android.R.styleable#View_longClickable 7230 */ 7231 public void setLongClickable(boolean longClickable) { 7232 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 7233 } 7234 7235 /** 7236 * Sets the pressed state for this view and provides a touch coordinate for 7237 * animation hinting. 7238 * 7239 * @param pressed Pass true to set the View's internal state to "pressed", 7240 * or false to reverts the View's internal state from a 7241 * previously set "pressed" state. 7242 * @param x The x coordinate of the touch that caused the press 7243 * @param y The y coordinate of the touch that caused the press 7244 */ 7245 private void setPressed(boolean pressed, float x, float y) { 7246 if (pressed) { 7247 drawableHotspotChanged(x, y); 7248 } 7249 7250 setPressed(pressed); 7251 } 7252 7253 /** 7254 * Sets the pressed state for this view. 7255 * 7256 * @see #isClickable() 7257 * @see #setClickable(boolean) 7258 * 7259 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 7260 * the View's internal state from a previously set "pressed" state. 7261 */ 7262 public void setPressed(boolean pressed) { 7263 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 7264 7265 if (pressed) { 7266 mPrivateFlags |= PFLAG_PRESSED; 7267 } else { 7268 mPrivateFlags &= ~PFLAG_PRESSED; 7269 } 7270 7271 if (needsRefresh) { 7272 refreshDrawableState(); 7273 } 7274 dispatchSetPressed(pressed); 7275 } 7276 7277 /** 7278 * Dispatch setPressed to all of this View's children. 7279 * 7280 * @see #setPressed(boolean) 7281 * 7282 * @param pressed The new pressed state 7283 */ 7284 protected void dispatchSetPressed(boolean pressed) { 7285 } 7286 7287 /** 7288 * Indicates whether the view is currently in pressed state. Unless 7289 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 7290 * the pressed state. 7291 * 7292 * @see #setPressed(boolean) 7293 * @see #isClickable() 7294 * @see #setClickable(boolean) 7295 * 7296 * @return true if the view is currently pressed, false otherwise 7297 */ 7298 @ViewDebug.ExportedProperty 7299 public boolean isPressed() { 7300 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 7301 } 7302 7303 /** 7304 * Indicates whether this view will save its state (that is, 7305 * whether its {@link #onSaveInstanceState} method will be called). 7306 * 7307 * @return Returns true if the view state saving is enabled, else false. 7308 * 7309 * @see #setSaveEnabled(boolean) 7310 * @attr ref android.R.styleable#View_saveEnabled 7311 */ 7312 public boolean isSaveEnabled() { 7313 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 7314 } 7315 7316 /** 7317 * Controls whether the saving of this view's state is 7318 * enabled (that is, whether its {@link #onSaveInstanceState} method 7319 * will be called). Note that even if freezing is enabled, the 7320 * view still must have an id assigned to it (via {@link #setId(int)}) 7321 * for its state to be saved. This flag can only disable the 7322 * saving of this view; any child views may still have their state saved. 7323 * 7324 * @param enabled Set to false to <em>disable</em> state saving, or true 7325 * (the default) to allow it. 7326 * 7327 * @see #isSaveEnabled() 7328 * @see #setId(int) 7329 * @see #onSaveInstanceState() 7330 * @attr ref android.R.styleable#View_saveEnabled 7331 */ 7332 public void setSaveEnabled(boolean enabled) { 7333 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 7334 } 7335 7336 /** 7337 * Gets whether the framework should discard touches when the view's 7338 * window is obscured by another visible window. 7339 * Refer to the {@link View} security documentation for more details. 7340 * 7341 * @return True if touch filtering is enabled. 7342 * 7343 * @see #setFilterTouchesWhenObscured(boolean) 7344 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7345 */ 7346 @ViewDebug.ExportedProperty 7347 public boolean getFilterTouchesWhenObscured() { 7348 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 7349 } 7350 7351 /** 7352 * Sets whether the framework should discard touches when the view's 7353 * window is obscured by another visible window. 7354 * Refer to the {@link View} security documentation for more details. 7355 * 7356 * @param enabled True if touch filtering should be enabled. 7357 * 7358 * @see #getFilterTouchesWhenObscured 7359 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7360 */ 7361 public void setFilterTouchesWhenObscured(boolean enabled) { 7362 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 7363 FILTER_TOUCHES_WHEN_OBSCURED); 7364 } 7365 7366 /** 7367 * Indicates whether the entire hierarchy under this view will save its 7368 * state when a state saving traversal occurs from its parent. The default 7369 * is true; if false, these views will not be saved unless 7370 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7371 * 7372 * @return Returns true if the view state saving from parent is enabled, else false. 7373 * 7374 * @see #setSaveFromParentEnabled(boolean) 7375 */ 7376 public boolean isSaveFromParentEnabled() { 7377 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 7378 } 7379 7380 /** 7381 * Controls whether the entire hierarchy under this view will save its 7382 * state when a state saving traversal occurs from its parent. The default 7383 * is true; if false, these views will not be saved unless 7384 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7385 * 7386 * @param enabled Set to false to <em>disable</em> state saving, or true 7387 * (the default) to allow it. 7388 * 7389 * @see #isSaveFromParentEnabled() 7390 * @see #setId(int) 7391 * @see #onSaveInstanceState() 7392 */ 7393 public void setSaveFromParentEnabled(boolean enabled) { 7394 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 7395 } 7396 7397 7398 /** 7399 * Returns whether this View is able to take focus. 7400 * 7401 * @return True if this view can take focus, or false otherwise. 7402 * @attr ref android.R.styleable#View_focusable 7403 */ 7404 @ViewDebug.ExportedProperty(category = "focus") 7405 public final boolean isFocusable() { 7406 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 7407 } 7408 7409 /** 7410 * When a view is focusable, it may not want to take focus when in touch mode. 7411 * For example, a button would like focus when the user is navigating via a D-pad 7412 * so that the user can click on it, but once the user starts touching the screen, 7413 * the button shouldn't take focus 7414 * @return Whether the view is focusable in touch mode. 7415 * @attr ref android.R.styleable#View_focusableInTouchMode 7416 */ 7417 @ViewDebug.ExportedProperty 7418 public final boolean isFocusableInTouchMode() { 7419 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 7420 } 7421 7422 /** 7423 * Find the nearest view in the specified direction that can take focus. 7424 * This does not actually give focus to that view. 7425 * 7426 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7427 * 7428 * @return The nearest focusable in the specified direction, or null if none 7429 * can be found. 7430 */ 7431 public View focusSearch(@FocusRealDirection int direction) { 7432 if (mParent != null) { 7433 return mParent.focusSearch(this, direction); 7434 } else { 7435 return null; 7436 } 7437 } 7438 7439 /** 7440 * This method is the last chance for the focused view and its ancestors to 7441 * respond to an arrow key. This is called when the focused view did not 7442 * consume the key internally, nor could the view system find a new view in 7443 * the requested direction to give focus to. 7444 * 7445 * @param focused The currently focused view. 7446 * @param direction The direction focus wants to move. One of FOCUS_UP, 7447 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 7448 * @return True if the this view consumed this unhandled move. 7449 */ 7450 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 7451 return false; 7452 } 7453 7454 /** 7455 * If a user manually specified the next view id for a particular direction, 7456 * use the root to look up the view. 7457 * @param root The root view of the hierarchy containing this view. 7458 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 7459 * or FOCUS_BACKWARD. 7460 * @return The user specified next view, or null if there is none. 7461 */ 7462 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7463 switch (direction) { 7464 case FOCUS_LEFT: 7465 if (mNextFocusLeftId == View.NO_ID) return null; 7466 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7467 case FOCUS_RIGHT: 7468 if (mNextFocusRightId == View.NO_ID) return null; 7469 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7470 case FOCUS_UP: 7471 if (mNextFocusUpId == View.NO_ID) return null; 7472 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7473 case FOCUS_DOWN: 7474 if (mNextFocusDownId == View.NO_ID) return null; 7475 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7476 case FOCUS_FORWARD: 7477 if (mNextFocusForwardId == View.NO_ID) return null; 7478 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7479 case FOCUS_BACKWARD: { 7480 if (mID == View.NO_ID) return null; 7481 final int id = mID; 7482 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7483 @Override 7484 public boolean apply(View t) { 7485 return t.mNextFocusForwardId == id; 7486 } 7487 }); 7488 } 7489 } 7490 return null; 7491 } 7492 7493 private View findViewInsideOutShouldExist(View root, int id) { 7494 if (mMatchIdPredicate == null) { 7495 mMatchIdPredicate = new MatchIdPredicate(); 7496 } 7497 mMatchIdPredicate.mId = id; 7498 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7499 if (result == null) { 7500 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7501 } 7502 return result; 7503 } 7504 7505 /** 7506 * Find and return all focusable views that are descendants of this view, 7507 * possibly including this view if it is focusable itself. 7508 * 7509 * @param direction The direction of the focus 7510 * @return A list of focusable views 7511 */ 7512 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7513 ArrayList<View> result = new ArrayList<View>(24); 7514 addFocusables(result, direction); 7515 return result; 7516 } 7517 7518 /** 7519 * Add any focusable views that are descendants of this view (possibly 7520 * including this view if it is focusable itself) to views. If we are in touch mode, 7521 * only add views that are also focusable in touch mode. 7522 * 7523 * @param views Focusable views found so far 7524 * @param direction The direction of the focus 7525 */ 7526 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7527 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7528 } 7529 7530 /** 7531 * Adds any focusable views that are descendants of this view (possibly 7532 * including this view if it is focusable itself) to views. This method 7533 * adds all focusable views regardless if we are in touch mode or 7534 * only views focusable in touch mode if we are in touch mode or 7535 * only views that can take accessibility focus if accessibility is enabeld 7536 * depending on the focusable mode paramater. 7537 * 7538 * @param views Focusable views found so far or null if all we are interested is 7539 * the number of focusables. 7540 * @param direction The direction of the focus. 7541 * @param focusableMode The type of focusables to be added. 7542 * 7543 * @see #FOCUSABLES_ALL 7544 * @see #FOCUSABLES_TOUCH_MODE 7545 */ 7546 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7547 @FocusableMode int focusableMode) { 7548 if (views == null) { 7549 return; 7550 } 7551 if (!isFocusable()) { 7552 return; 7553 } 7554 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7555 && isInTouchMode() && !isFocusableInTouchMode()) { 7556 return; 7557 } 7558 views.add(this); 7559 } 7560 7561 /** 7562 * Finds the Views that contain given text. The containment is case insensitive. 7563 * The search is performed by either the text that the View renders or the content 7564 * description that describes the view for accessibility purposes and the view does 7565 * not render or both. Clients can specify how the search is to be performed via 7566 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7567 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7568 * 7569 * @param outViews The output list of matching Views. 7570 * @param searched The text to match against. 7571 * 7572 * @see #FIND_VIEWS_WITH_TEXT 7573 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7574 * @see #setContentDescription(CharSequence) 7575 */ 7576 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7577 @FindViewFlags int flags) { 7578 if (getAccessibilityNodeProvider() != null) { 7579 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7580 outViews.add(this); 7581 } 7582 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7583 && (searched != null && searched.length() > 0) 7584 && (mContentDescription != null && mContentDescription.length() > 0)) { 7585 String searchedLowerCase = searched.toString().toLowerCase(); 7586 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7587 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7588 outViews.add(this); 7589 } 7590 } 7591 } 7592 7593 /** 7594 * Find and return all touchable views that are descendants of this view, 7595 * possibly including this view if it is touchable itself. 7596 * 7597 * @return A list of touchable views 7598 */ 7599 public ArrayList<View> getTouchables() { 7600 ArrayList<View> result = new ArrayList<View>(); 7601 addTouchables(result); 7602 return result; 7603 } 7604 7605 /** 7606 * Add any touchable views that are descendants of this view (possibly 7607 * including this view if it is touchable itself) to views. 7608 * 7609 * @param views Touchable views found so far 7610 */ 7611 public void addTouchables(ArrayList<View> views) { 7612 final int viewFlags = mViewFlags; 7613 7614 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7615 && (viewFlags & ENABLED_MASK) == ENABLED) { 7616 views.add(this); 7617 } 7618 } 7619 7620 /** 7621 * Returns whether this View is accessibility focused. 7622 * 7623 * @return True if this View is accessibility focused. 7624 */ 7625 public boolean isAccessibilityFocused() { 7626 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7627 } 7628 7629 /** 7630 * Call this to try to give accessibility focus to this view. 7631 * 7632 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7633 * returns false or the view is no visible or the view already has accessibility 7634 * focus. 7635 * 7636 * See also {@link #focusSearch(int)}, which is what you call to say that you 7637 * have focus, and you want your parent to look for the next one. 7638 * 7639 * @return Whether this view actually took accessibility focus. 7640 * 7641 * @hide 7642 */ 7643 public boolean requestAccessibilityFocus() { 7644 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7645 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7646 return false; 7647 } 7648 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7649 return false; 7650 } 7651 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7652 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7653 ViewRootImpl viewRootImpl = getViewRootImpl(); 7654 if (viewRootImpl != null) { 7655 viewRootImpl.setAccessibilityFocus(this, null); 7656 } 7657 invalidate(); 7658 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7659 return true; 7660 } 7661 return false; 7662 } 7663 7664 /** 7665 * Call this to try to clear accessibility focus of this view. 7666 * 7667 * See also {@link #focusSearch(int)}, which is what you call to say that you 7668 * have focus, and you want your parent to look for the next one. 7669 * 7670 * @hide 7671 */ 7672 public void clearAccessibilityFocus() { 7673 clearAccessibilityFocusNoCallbacks(); 7674 // Clear the global reference of accessibility focus if this 7675 // view or any of its descendants had accessibility focus. 7676 ViewRootImpl viewRootImpl = getViewRootImpl(); 7677 if (viewRootImpl != null) { 7678 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7679 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7680 viewRootImpl.setAccessibilityFocus(null, null); 7681 } 7682 } 7683 } 7684 7685 private void sendAccessibilityHoverEvent(int eventType) { 7686 // Since we are not delivering to a client accessibility events from not 7687 // important views (unless the clinet request that) we need to fire the 7688 // event from the deepest view exposed to the client. As a consequence if 7689 // the user crosses a not exposed view the client will see enter and exit 7690 // of the exposed predecessor followed by and enter and exit of that same 7691 // predecessor when entering and exiting the not exposed descendant. This 7692 // is fine since the client has a clear idea which view is hovered at the 7693 // price of a couple more events being sent. This is a simple and 7694 // working solution. 7695 View source = this; 7696 while (true) { 7697 if (source.includeForAccessibility()) { 7698 source.sendAccessibilityEvent(eventType); 7699 return; 7700 } 7701 ViewParent parent = source.getParent(); 7702 if (parent instanceof View) { 7703 source = (View) parent; 7704 } else { 7705 return; 7706 } 7707 } 7708 } 7709 7710 /** 7711 * Clears accessibility focus without calling any callback methods 7712 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7713 * is used for clearing accessibility focus when giving this focus to 7714 * another view. 7715 */ 7716 void clearAccessibilityFocusNoCallbacks() { 7717 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7718 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7719 invalidate(); 7720 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7721 } 7722 } 7723 7724 /** 7725 * Call this to try to give focus to a specific view or to one of its 7726 * descendants. 7727 * 7728 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7729 * false), or if it is focusable and it is not focusable in touch mode 7730 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7731 * 7732 * See also {@link #focusSearch(int)}, which is what you call to say that you 7733 * have focus, and you want your parent to look for the next one. 7734 * 7735 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7736 * {@link #FOCUS_DOWN} and <code>null</code>. 7737 * 7738 * @return Whether this view or one of its descendants actually took focus. 7739 */ 7740 public final boolean requestFocus() { 7741 return requestFocus(View.FOCUS_DOWN); 7742 } 7743 7744 /** 7745 * Call this to try to give focus to a specific view or to one of its 7746 * descendants and give it a hint about what direction focus is heading. 7747 * 7748 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7749 * false), or if it is focusable and it is not focusable in touch mode 7750 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7751 * 7752 * See also {@link #focusSearch(int)}, which is what you call to say that you 7753 * have focus, and you want your parent to look for the next one. 7754 * 7755 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7756 * <code>null</code> set for the previously focused rectangle. 7757 * 7758 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7759 * @return Whether this view or one of its descendants actually took focus. 7760 */ 7761 public final boolean requestFocus(int direction) { 7762 return requestFocus(direction, null); 7763 } 7764 7765 /** 7766 * Call this to try to give focus to a specific view or to one of its descendants 7767 * and give it hints about the direction and a specific rectangle that the focus 7768 * is coming from. The rectangle can help give larger views a finer grained hint 7769 * about where focus is coming from, and therefore, where to show selection, or 7770 * forward focus change internally. 7771 * 7772 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7773 * false), or if it is focusable and it is not focusable in touch mode 7774 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7775 * 7776 * A View will not take focus if it is not visible. 7777 * 7778 * A View will not take focus if one of its parents has 7779 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7780 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7781 * 7782 * See also {@link #focusSearch(int)}, which is what you call to say that you 7783 * have focus, and you want your parent to look for the next one. 7784 * 7785 * You may wish to override this method if your custom {@link View} has an internal 7786 * {@link View} that it wishes to forward the request to. 7787 * 7788 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7789 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7790 * to give a finer grained hint about where focus is coming from. May be null 7791 * if there is no hint. 7792 * @return Whether this view or one of its descendants actually took focus. 7793 */ 7794 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7795 return requestFocusNoSearch(direction, previouslyFocusedRect); 7796 } 7797 7798 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7799 // need to be focusable 7800 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7801 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7802 return false; 7803 } 7804 7805 // need to be focusable in touch mode if in touch mode 7806 if (isInTouchMode() && 7807 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7808 return false; 7809 } 7810 7811 // need to not have any parents blocking us 7812 if (hasAncestorThatBlocksDescendantFocus()) { 7813 return false; 7814 } 7815 7816 handleFocusGainInternal(direction, previouslyFocusedRect); 7817 return true; 7818 } 7819 7820 /** 7821 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7822 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7823 * touch mode to request focus when they are touched. 7824 * 7825 * @return Whether this view or one of its descendants actually took focus. 7826 * 7827 * @see #isInTouchMode() 7828 * 7829 */ 7830 public final boolean requestFocusFromTouch() { 7831 // Leave touch mode if we need to 7832 if (isInTouchMode()) { 7833 ViewRootImpl viewRoot = getViewRootImpl(); 7834 if (viewRoot != null) { 7835 viewRoot.ensureTouchMode(false); 7836 } 7837 } 7838 return requestFocus(View.FOCUS_DOWN); 7839 } 7840 7841 /** 7842 * @return Whether any ancestor of this view blocks descendant focus. 7843 */ 7844 private boolean hasAncestorThatBlocksDescendantFocus() { 7845 final boolean focusableInTouchMode = isFocusableInTouchMode(); 7846 ViewParent ancestor = mParent; 7847 while (ancestor instanceof ViewGroup) { 7848 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7849 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 7850 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 7851 return true; 7852 } else { 7853 ancestor = vgAncestor.getParent(); 7854 } 7855 } 7856 return false; 7857 } 7858 7859 /** 7860 * Gets the mode for determining whether this View is important for accessibility 7861 * which is if it fires accessibility events and if it is reported to 7862 * accessibility services that query the screen. 7863 * 7864 * @return The mode for determining whether a View is important for accessibility. 7865 * 7866 * @attr ref android.R.styleable#View_importantForAccessibility 7867 * 7868 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7869 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7870 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7871 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7872 */ 7873 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7874 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7875 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7876 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7877 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7878 to = "noHideDescendants") 7879 }) 7880 public int getImportantForAccessibility() { 7881 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7882 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7883 } 7884 7885 /** 7886 * Sets the live region mode for this view. This indicates to accessibility 7887 * services whether they should automatically notify the user about changes 7888 * to the view's content description or text, or to the content descriptions 7889 * or text of the view's children (where applicable). 7890 * <p> 7891 * For example, in a login screen with a TextView that displays an "incorrect 7892 * password" notification, that view should be marked as a live region with 7893 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7894 * <p> 7895 * To disable change notifications for this view, use 7896 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7897 * mode for most views. 7898 * <p> 7899 * To indicate that the user should be notified of changes, use 7900 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7901 * <p> 7902 * If the view's changes should interrupt ongoing speech and notify the user 7903 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7904 * 7905 * @param mode The live region mode for this view, one of: 7906 * <ul> 7907 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7908 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7909 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7910 * </ul> 7911 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7912 */ 7913 public void setAccessibilityLiveRegion(int mode) { 7914 if (mode != getAccessibilityLiveRegion()) { 7915 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7916 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7917 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7918 notifyViewAccessibilityStateChangedIfNeeded( 7919 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7920 } 7921 } 7922 7923 /** 7924 * Gets the live region mode for this View. 7925 * 7926 * @return The live region mode for the view. 7927 * 7928 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7929 * 7930 * @see #setAccessibilityLiveRegion(int) 7931 */ 7932 public int getAccessibilityLiveRegion() { 7933 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7934 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7935 } 7936 7937 /** 7938 * Sets how to determine whether this view is important for accessibility 7939 * which is if it fires accessibility events and if it is reported to 7940 * accessibility services that query the screen. 7941 * 7942 * @param mode How to determine whether this view is important for accessibility. 7943 * 7944 * @attr ref android.R.styleable#View_importantForAccessibility 7945 * 7946 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7947 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7948 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7949 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7950 */ 7951 public void setImportantForAccessibility(int mode) { 7952 final int oldMode = getImportantForAccessibility(); 7953 if (mode != oldMode) { 7954 // If we're moving between AUTO and another state, we might not need 7955 // to send a subtree changed notification. We'll store the computed 7956 // importance, since we'll need to check it later to make sure. 7957 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7958 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7959 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7960 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7961 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7962 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7963 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7964 notifySubtreeAccessibilityStateChangedIfNeeded(); 7965 } else { 7966 notifyViewAccessibilityStateChangedIfNeeded( 7967 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7968 } 7969 } 7970 } 7971 7972 /** 7973 * Computes whether this view should be exposed for accessibility. In 7974 * general, views that are interactive or provide information are exposed 7975 * while views that serve only as containers are hidden. 7976 * <p> 7977 * If an ancestor of this view has importance 7978 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7979 * returns <code>false</code>. 7980 * <p> 7981 * Otherwise, the value is computed according to the view's 7982 * {@link #getImportantForAccessibility()} value: 7983 * <ol> 7984 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7985 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7986 * </code> 7987 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7988 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7989 * view satisfies any of the following: 7990 * <ul> 7991 * <li>Is actionable, e.g. {@link #isClickable()}, 7992 * {@link #isLongClickable()}, or {@link #isFocusable()} 7993 * <li>Has an {@link AccessibilityDelegate} 7994 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7995 * {@link OnKeyListener}, etc. 7996 * <li>Is an accessibility live region, e.g. 7997 * {@link #getAccessibilityLiveRegion()} is not 7998 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7999 * </ul> 8000 * </ol> 8001 * 8002 * @return Whether the view is exposed for accessibility. 8003 * @see #setImportantForAccessibility(int) 8004 * @see #getImportantForAccessibility() 8005 */ 8006 public boolean isImportantForAccessibility() { 8007 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 8008 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 8009 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 8010 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 8011 return false; 8012 } 8013 8014 // Check parent mode to ensure we're not hidden. 8015 ViewParent parent = mParent; 8016 while (parent instanceof View) { 8017 if (((View) parent).getImportantForAccessibility() 8018 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 8019 return false; 8020 } 8021 parent = parent.getParent(); 8022 } 8023 8024 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 8025 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 8026 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 8027 } 8028 8029 /** 8030 * Gets the parent for accessibility purposes. Note that the parent for 8031 * accessibility is not necessary the immediate parent. It is the first 8032 * predecessor that is important for accessibility. 8033 * 8034 * @return The parent for accessibility purposes. 8035 */ 8036 public ViewParent getParentForAccessibility() { 8037 if (mParent instanceof View) { 8038 View parentView = (View) mParent; 8039 if (parentView.includeForAccessibility()) { 8040 return mParent; 8041 } else { 8042 return mParent.getParentForAccessibility(); 8043 } 8044 } 8045 return null; 8046 } 8047 8048 /** 8049 * Adds the children of a given View for accessibility. Since some Views are 8050 * not important for accessibility the children for accessibility are not 8051 * necessarily direct children of the view, rather they are the first level of 8052 * descendants important for accessibility. 8053 * 8054 * @param children The list of children for accessibility. 8055 */ 8056 public void addChildrenForAccessibility(ArrayList<View> children) { 8057 8058 } 8059 8060 /** 8061 * Whether to regard this view for accessibility. A view is regarded for 8062 * accessibility if it is important for accessibility or the querying 8063 * accessibility service has explicitly requested that view not 8064 * important for accessibility are regarded. 8065 * 8066 * @return Whether to regard the view for accessibility. 8067 * 8068 * @hide 8069 */ 8070 public boolean includeForAccessibility() { 8071 if (mAttachInfo != null) { 8072 return (mAttachInfo.mAccessibilityFetchFlags 8073 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 8074 || isImportantForAccessibility(); 8075 } 8076 return false; 8077 } 8078 8079 /** 8080 * Returns whether the View is considered actionable from 8081 * accessibility perspective. Such view are important for 8082 * accessibility. 8083 * 8084 * @return True if the view is actionable for accessibility. 8085 * 8086 * @hide 8087 */ 8088 public boolean isActionableForAccessibility() { 8089 return (isClickable() || isLongClickable() || isFocusable()); 8090 } 8091 8092 /** 8093 * Returns whether the View has registered callbacks which makes it 8094 * important for accessibility. 8095 * 8096 * @return True if the view is actionable for accessibility. 8097 */ 8098 private boolean hasListenersForAccessibility() { 8099 ListenerInfo info = getListenerInfo(); 8100 return mTouchDelegate != null || info.mOnKeyListener != null 8101 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 8102 || info.mOnHoverListener != null || info.mOnDragListener != null; 8103 } 8104 8105 /** 8106 * Notifies that the accessibility state of this view changed. The change 8107 * is local to this view and does not represent structural changes such 8108 * as children and parent. For example, the view became focusable. The 8109 * notification is at at most once every 8110 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 8111 * to avoid unnecessary load to the system. Also once a view has a pending 8112 * notification this method is a NOP until the notification has been sent. 8113 * 8114 * @hide 8115 */ 8116 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 8117 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 8118 return; 8119 } 8120 if (mSendViewStateChangedAccessibilityEvent == null) { 8121 mSendViewStateChangedAccessibilityEvent = 8122 new SendViewStateChangedAccessibilityEvent(); 8123 } 8124 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 8125 } 8126 8127 /** 8128 * Notifies that the accessibility state of this view changed. The change 8129 * is *not* local to this view and does represent structural changes such 8130 * as children and parent. For example, the view size changed. The 8131 * notification is at at most once every 8132 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 8133 * to avoid unnecessary load to the system. Also once a view has a pending 8134 * notification this method is a NOP until the notification has been sent. 8135 * 8136 * @hide 8137 */ 8138 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 8139 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 8140 return; 8141 } 8142 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 8143 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8144 if (mParent != null) { 8145 try { 8146 mParent.notifySubtreeAccessibilityStateChanged( 8147 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 8148 } catch (AbstractMethodError e) { 8149 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8150 " does not fully implement ViewParent", e); 8151 } 8152 } 8153 } 8154 } 8155 8156 /** 8157 * Reset the flag indicating the accessibility state of the subtree rooted 8158 * at this view changed. 8159 */ 8160 void resetSubtreeAccessibilityStateChanged() { 8161 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8162 } 8163 8164 /** 8165 * Performs the specified accessibility action on the view. For 8166 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 8167 * <p> 8168 * If an {@link AccessibilityDelegate} has been specified via calling 8169 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 8170 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 8171 * is responsible for handling this call. 8172 * </p> 8173 * 8174 * @param action The action to perform. 8175 * @param arguments Optional action arguments. 8176 * @return Whether the action was performed. 8177 */ 8178 public boolean performAccessibilityAction(int action, Bundle arguments) { 8179 if (mAccessibilityDelegate != null) { 8180 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 8181 } else { 8182 return performAccessibilityActionInternal(action, arguments); 8183 } 8184 } 8185 8186 /** 8187 * @see #performAccessibilityAction(int, Bundle) 8188 * 8189 * Note: Called from the default {@link AccessibilityDelegate}. 8190 */ 8191 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 8192 switch (action) { 8193 case AccessibilityNodeInfo.ACTION_CLICK: { 8194 if (isClickable()) { 8195 performClick(); 8196 return true; 8197 } 8198 } break; 8199 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 8200 if (isLongClickable()) { 8201 performLongClick(); 8202 return true; 8203 } 8204 } break; 8205 case AccessibilityNodeInfo.ACTION_FOCUS: { 8206 if (!hasFocus()) { 8207 // Get out of touch mode since accessibility 8208 // wants to move focus around. 8209 getViewRootImpl().ensureTouchMode(false); 8210 return requestFocus(); 8211 } 8212 } break; 8213 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 8214 if (hasFocus()) { 8215 clearFocus(); 8216 return !isFocused(); 8217 } 8218 } break; 8219 case AccessibilityNodeInfo.ACTION_SELECT: { 8220 if (!isSelected()) { 8221 setSelected(true); 8222 return isSelected(); 8223 } 8224 } break; 8225 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 8226 if (isSelected()) { 8227 setSelected(false); 8228 return !isSelected(); 8229 } 8230 } break; 8231 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 8232 if (!isAccessibilityFocused()) { 8233 return requestAccessibilityFocus(); 8234 } 8235 } break; 8236 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 8237 if (isAccessibilityFocused()) { 8238 clearAccessibilityFocus(); 8239 return true; 8240 } 8241 } break; 8242 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 8243 if (arguments != null) { 8244 final int granularity = arguments.getInt( 8245 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8246 final boolean extendSelection = arguments.getBoolean( 8247 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8248 return traverseAtGranularity(granularity, true, extendSelection); 8249 } 8250 } break; 8251 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 8252 if (arguments != null) { 8253 final int granularity = arguments.getInt( 8254 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8255 final boolean extendSelection = arguments.getBoolean( 8256 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8257 return traverseAtGranularity(granularity, false, extendSelection); 8258 } 8259 } break; 8260 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 8261 CharSequence text = getIterableTextForAccessibility(); 8262 if (text == null) { 8263 return false; 8264 } 8265 final int start = (arguments != null) ? arguments.getInt( 8266 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 8267 final int end = (arguments != null) ? arguments.getInt( 8268 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 8269 // Only cursor position can be specified (selection length == 0) 8270 if ((getAccessibilitySelectionStart() != start 8271 || getAccessibilitySelectionEnd() != end) 8272 && (start == end)) { 8273 setAccessibilitySelection(start, end); 8274 notifyViewAccessibilityStateChangedIfNeeded( 8275 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8276 return true; 8277 } 8278 } break; 8279 } 8280 return false; 8281 } 8282 8283 private boolean traverseAtGranularity(int granularity, boolean forward, 8284 boolean extendSelection) { 8285 CharSequence text = getIterableTextForAccessibility(); 8286 if (text == null || text.length() == 0) { 8287 return false; 8288 } 8289 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 8290 if (iterator == null) { 8291 return false; 8292 } 8293 int current = getAccessibilitySelectionEnd(); 8294 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8295 current = forward ? 0 : text.length(); 8296 } 8297 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 8298 if (range == null) { 8299 return false; 8300 } 8301 final int segmentStart = range[0]; 8302 final int segmentEnd = range[1]; 8303 int selectionStart; 8304 int selectionEnd; 8305 if (extendSelection && isAccessibilitySelectionExtendable()) { 8306 selectionStart = getAccessibilitySelectionStart(); 8307 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8308 selectionStart = forward ? segmentStart : segmentEnd; 8309 } 8310 selectionEnd = forward ? segmentEnd : segmentStart; 8311 } else { 8312 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 8313 } 8314 setAccessibilitySelection(selectionStart, selectionEnd); 8315 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 8316 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 8317 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 8318 return true; 8319 } 8320 8321 /** 8322 * Gets the text reported for accessibility purposes. 8323 * 8324 * @return The accessibility text. 8325 * 8326 * @hide 8327 */ 8328 public CharSequence getIterableTextForAccessibility() { 8329 return getContentDescription(); 8330 } 8331 8332 /** 8333 * Gets whether accessibility selection can be extended. 8334 * 8335 * @return If selection is extensible. 8336 * 8337 * @hide 8338 */ 8339 public boolean isAccessibilitySelectionExtendable() { 8340 return false; 8341 } 8342 8343 /** 8344 * @hide 8345 */ 8346 public int getAccessibilitySelectionStart() { 8347 return mAccessibilityCursorPosition; 8348 } 8349 8350 /** 8351 * @hide 8352 */ 8353 public int getAccessibilitySelectionEnd() { 8354 return getAccessibilitySelectionStart(); 8355 } 8356 8357 /** 8358 * @hide 8359 */ 8360 public void setAccessibilitySelection(int start, int end) { 8361 if (start == end && end == mAccessibilityCursorPosition) { 8362 return; 8363 } 8364 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 8365 mAccessibilityCursorPosition = start; 8366 } else { 8367 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 8368 } 8369 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 8370 } 8371 8372 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 8373 int fromIndex, int toIndex) { 8374 if (mParent == null) { 8375 return; 8376 } 8377 AccessibilityEvent event = AccessibilityEvent.obtain( 8378 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 8379 onInitializeAccessibilityEvent(event); 8380 onPopulateAccessibilityEvent(event); 8381 event.setFromIndex(fromIndex); 8382 event.setToIndex(toIndex); 8383 event.setAction(action); 8384 event.setMovementGranularity(granularity); 8385 mParent.requestSendAccessibilityEvent(this, event); 8386 } 8387 8388 /** 8389 * @hide 8390 */ 8391 public TextSegmentIterator getIteratorForGranularity(int granularity) { 8392 switch (granularity) { 8393 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 8394 CharSequence text = getIterableTextForAccessibility(); 8395 if (text != null && text.length() > 0) { 8396 CharacterTextSegmentIterator iterator = 8397 CharacterTextSegmentIterator.getInstance( 8398 mContext.getResources().getConfiguration().locale); 8399 iterator.initialize(text.toString()); 8400 return iterator; 8401 } 8402 } break; 8403 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 8404 CharSequence text = getIterableTextForAccessibility(); 8405 if (text != null && text.length() > 0) { 8406 WordTextSegmentIterator iterator = 8407 WordTextSegmentIterator.getInstance( 8408 mContext.getResources().getConfiguration().locale); 8409 iterator.initialize(text.toString()); 8410 return iterator; 8411 } 8412 } break; 8413 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 8414 CharSequence text = getIterableTextForAccessibility(); 8415 if (text != null && text.length() > 0) { 8416 ParagraphTextSegmentIterator iterator = 8417 ParagraphTextSegmentIterator.getInstance(); 8418 iterator.initialize(text.toString()); 8419 return iterator; 8420 } 8421 } break; 8422 } 8423 return null; 8424 } 8425 8426 /** 8427 * @hide 8428 */ 8429 public void dispatchStartTemporaryDetach() { 8430 onStartTemporaryDetach(); 8431 } 8432 8433 /** 8434 * This is called when a container is going to temporarily detach a child, with 8435 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 8436 * It will either be followed by {@link #onFinishTemporaryDetach()} or 8437 * {@link #onDetachedFromWindow()} when the container is done. 8438 */ 8439 public void onStartTemporaryDetach() { 8440 removeUnsetPressCallback(); 8441 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 8442 } 8443 8444 /** 8445 * @hide 8446 */ 8447 public void dispatchFinishTemporaryDetach() { 8448 onFinishTemporaryDetach(); 8449 } 8450 8451 /** 8452 * Called after {@link #onStartTemporaryDetach} when the container is done 8453 * changing the view. 8454 */ 8455 public void onFinishTemporaryDetach() { 8456 } 8457 8458 /** 8459 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8460 * for this view's window. Returns null if the view is not currently attached 8461 * to the window. Normally you will not need to use this directly, but 8462 * just use the standard high-level event callbacks like 8463 * {@link #onKeyDown(int, KeyEvent)}. 8464 */ 8465 public KeyEvent.DispatcherState getKeyDispatcherState() { 8466 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8467 } 8468 8469 /** 8470 * Dispatch a key event before it is processed by any input method 8471 * associated with the view hierarchy. This can be used to intercept 8472 * key events in special situations before the IME consumes them; a 8473 * typical example would be handling the BACK key to update the application's 8474 * UI instead of allowing the IME to see it and close itself. 8475 * 8476 * @param event The key event to be dispatched. 8477 * @return True if the event was handled, false otherwise. 8478 */ 8479 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8480 return onKeyPreIme(event.getKeyCode(), event); 8481 } 8482 8483 /** 8484 * Dispatch a key event to the next view on the focus path. This path runs 8485 * from the top of the view tree down to the currently focused view. If this 8486 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8487 * the next node down the focus path. This method also fires any key 8488 * listeners. 8489 * 8490 * @param event The key event to be dispatched. 8491 * @return True if the event was handled, false otherwise. 8492 */ 8493 public boolean dispatchKeyEvent(KeyEvent event) { 8494 if (mInputEventConsistencyVerifier != null) { 8495 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8496 } 8497 8498 // Give any attached key listener a first crack at the event. 8499 //noinspection SimplifiableIfStatement 8500 ListenerInfo li = mListenerInfo; 8501 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8502 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8503 return true; 8504 } 8505 8506 if (event.dispatch(this, mAttachInfo != null 8507 ? mAttachInfo.mKeyDispatchState : null, this)) { 8508 return true; 8509 } 8510 8511 if (mInputEventConsistencyVerifier != null) { 8512 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8513 } 8514 return false; 8515 } 8516 8517 /** 8518 * Dispatches a key shortcut event. 8519 * 8520 * @param event The key event to be dispatched. 8521 * @return True if the event was handled by the view, false otherwise. 8522 */ 8523 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8524 return onKeyShortcut(event.getKeyCode(), event); 8525 } 8526 8527 /** 8528 * Pass the touch screen motion event down to the target view, or this 8529 * view if it is the target. 8530 * 8531 * @param event The motion event to be dispatched. 8532 * @return True if the event was handled by the view, false otherwise. 8533 */ 8534 public boolean dispatchTouchEvent(MotionEvent event) { 8535 boolean result = false; 8536 8537 if (mInputEventConsistencyVerifier != null) { 8538 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8539 } 8540 8541 final int actionMasked = event.getActionMasked(); 8542 if (actionMasked == MotionEvent.ACTION_DOWN) { 8543 // Defensive cleanup for new gesture 8544 stopNestedScroll(); 8545 } 8546 8547 if (onFilterTouchEventForSecurity(event)) { 8548 //noinspection SimplifiableIfStatement 8549 ListenerInfo li = mListenerInfo; 8550 if (li != null && li.mOnTouchListener != null 8551 && (mViewFlags & ENABLED_MASK) == ENABLED 8552 && li.mOnTouchListener.onTouch(this, event)) { 8553 result = true; 8554 } 8555 8556 if (!result && onTouchEvent(event)) { 8557 result = true; 8558 } 8559 } 8560 8561 if (!result && mInputEventConsistencyVerifier != null) { 8562 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8563 } 8564 8565 // Clean up after nested scrolls if this is the end of a gesture; 8566 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8567 // of the gesture. 8568 if (actionMasked == MotionEvent.ACTION_UP || 8569 actionMasked == MotionEvent.ACTION_CANCEL || 8570 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8571 stopNestedScroll(); 8572 } 8573 8574 return result; 8575 } 8576 8577 /** 8578 * Filter the touch event to apply security policies. 8579 * 8580 * @param event The motion event to be filtered. 8581 * @return True if the event should be dispatched, false if the event should be dropped. 8582 * 8583 * @see #getFilterTouchesWhenObscured 8584 */ 8585 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8586 //noinspection RedundantIfStatement 8587 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8588 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8589 // Window is obscured, drop this touch. 8590 return false; 8591 } 8592 return true; 8593 } 8594 8595 /** 8596 * Pass a trackball motion event down to the focused view. 8597 * 8598 * @param event The motion event to be dispatched. 8599 * @return True if the event was handled by the view, false otherwise. 8600 */ 8601 public boolean dispatchTrackballEvent(MotionEvent event) { 8602 if (mInputEventConsistencyVerifier != null) { 8603 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8604 } 8605 8606 return onTrackballEvent(event); 8607 } 8608 8609 /** 8610 * Dispatch a generic motion event. 8611 * <p> 8612 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8613 * are delivered to the view under the pointer. All other generic motion events are 8614 * delivered to the focused view. Hover events are handled specially and are delivered 8615 * to {@link #onHoverEvent(MotionEvent)}. 8616 * </p> 8617 * 8618 * @param event The motion event to be dispatched. 8619 * @return True if the event was handled by the view, false otherwise. 8620 */ 8621 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8622 if (mInputEventConsistencyVerifier != null) { 8623 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8624 } 8625 8626 final int source = event.getSource(); 8627 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8628 final int action = event.getAction(); 8629 if (action == MotionEvent.ACTION_HOVER_ENTER 8630 || action == MotionEvent.ACTION_HOVER_MOVE 8631 || action == MotionEvent.ACTION_HOVER_EXIT) { 8632 if (dispatchHoverEvent(event)) { 8633 return true; 8634 } 8635 } else if (dispatchGenericPointerEvent(event)) { 8636 return true; 8637 } 8638 } else if (dispatchGenericFocusedEvent(event)) { 8639 return true; 8640 } 8641 8642 if (dispatchGenericMotionEventInternal(event)) { 8643 return true; 8644 } 8645 8646 if (mInputEventConsistencyVerifier != null) { 8647 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8648 } 8649 return false; 8650 } 8651 8652 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8653 //noinspection SimplifiableIfStatement 8654 ListenerInfo li = mListenerInfo; 8655 if (li != null && li.mOnGenericMotionListener != null 8656 && (mViewFlags & ENABLED_MASK) == ENABLED 8657 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8658 return true; 8659 } 8660 8661 if (onGenericMotionEvent(event)) { 8662 return true; 8663 } 8664 8665 if (mInputEventConsistencyVerifier != null) { 8666 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8667 } 8668 return false; 8669 } 8670 8671 /** 8672 * Dispatch a hover event. 8673 * <p> 8674 * Do not call this method directly. 8675 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8676 * </p> 8677 * 8678 * @param event The motion event to be dispatched. 8679 * @return True if the event was handled by the view, false otherwise. 8680 */ 8681 protected boolean dispatchHoverEvent(MotionEvent event) { 8682 ListenerInfo li = mListenerInfo; 8683 //noinspection SimplifiableIfStatement 8684 if (li != null && li.mOnHoverListener != null 8685 && (mViewFlags & ENABLED_MASK) == ENABLED 8686 && li.mOnHoverListener.onHover(this, event)) { 8687 return true; 8688 } 8689 8690 return onHoverEvent(event); 8691 } 8692 8693 /** 8694 * Returns true if the view has a child to which it has recently sent 8695 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8696 * it does not have a hovered child, then it must be the innermost hovered view. 8697 * @hide 8698 */ 8699 protected boolean hasHoveredChild() { 8700 return false; 8701 } 8702 8703 /** 8704 * Dispatch a generic motion event to the view under the first pointer. 8705 * <p> 8706 * Do not call this method directly. 8707 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8708 * </p> 8709 * 8710 * @param event The motion event to be dispatched. 8711 * @return True if the event was handled by the view, false otherwise. 8712 */ 8713 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8714 return false; 8715 } 8716 8717 /** 8718 * Dispatch a generic motion event to the currently focused view. 8719 * <p> 8720 * Do not call this method directly. 8721 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8722 * </p> 8723 * 8724 * @param event The motion event to be dispatched. 8725 * @return True if the event was handled by the view, false otherwise. 8726 */ 8727 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8728 return false; 8729 } 8730 8731 /** 8732 * Dispatch a pointer event. 8733 * <p> 8734 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8735 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8736 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8737 * and should not be expected to handle other pointing device features. 8738 * </p> 8739 * 8740 * @param event The motion event to be dispatched. 8741 * @return True if the event was handled by the view, false otherwise. 8742 * @hide 8743 */ 8744 public final boolean dispatchPointerEvent(MotionEvent event) { 8745 if (event.isTouchEvent()) { 8746 return dispatchTouchEvent(event); 8747 } else { 8748 return dispatchGenericMotionEvent(event); 8749 } 8750 } 8751 8752 /** 8753 * Called when the window containing this view gains or loses window focus. 8754 * ViewGroups should override to route to their children. 8755 * 8756 * @param hasFocus True if the window containing this view now has focus, 8757 * false otherwise. 8758 */ 8759 public void dispatchWindowFocusChanged(boolean hasFocus) { 8760 onWindowFocusChanged(hasFocus); 8761 } 8762 8763 /** 8764 * Called when the window containing this view gains or loses focus. Note 8765 * that this is separate from view focus: to receive key events, both 8766 * your view and its window must have focus. If a window is displayed 8767 * on top of yours that takes input focus, then your own window will lose 8768 * focus but the view focus will remain unchanged. 8769 * 8770 * @param hasWindowFocus True if the window containing this view now has 8771 * focus, false otherwise. 8772 */ 8773 public void onWindowFocusChanged(boolean hasWindowFocus) { 8774 InputMethodManager imm = InputMethodManager.peekInstance(); 8775 if (!hasWindowFocus) { 8776 if (isPressed()) { 8777 setPressed(false); 8778 } 8779 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8780 imm.focusOut(this); 8781 } 8782 removeLongPressCallback(); 8783 removeTapCallback(); 8784 onFocusLost(); 8785 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8786 imm.focusIn(this); 8787 } 8788 refreshDrawableState(); 8789 } 8790 8791 /** 8792 * Returns true if this view is in a window that currently has window focus. 8793 * Note that this is not the same as the view itself having focus. 8794 * 8795 * @return True if this view is in a window that currently has window focus. 8796 */ 8797 public boolean hasWindowFocus() { 8798 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8799 } 8800 8801 /** 8802 * Dispatch a view visibility change down the view hierarchy. 8803 * ViewGroups should override to route to their children. 8804 * @param changedView The view whose visibility changed. Could be 'this' or 8805 * an ancestor view. 8806 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8807 * {@link #INVISIBLE} or {@link #GONE}. 8808 */ 8809 protected void dispatchVisibilityChanged(@NonNull View changedView, 8810 @Visibility int visibility) { 8811 onVisibilityChanged(changedView, visibility); 8812 } 8813 8814 /** 8815 * Called when the visibility of the view or an ancestor of the view is changed. 8816 * @param changedView The view whose visibility changed. Could be 'this' or 8817 * an ancestor view. 8818 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8819 * {@link #INVISIBLE} or {@link #GONE}. 8820 */ 8821 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8822 if (visibility == VISIBLE) { 8823 if (mAttachInfo != null) { 8824 initialAwakenScrollBars(); 8825 } else { 8826 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8827 } 8828 } 8829 } 8830 8831 /** 8832 * Dispatch a hint about whether this view is displayed. For instance, when 8833 * a View moves out of the screen, it might receives a display hint indicating 8834 * the view is not displayed. Applications should not <em>rely</em> on this hint 8835 * as there is no guarantee that they will receive one. 8836 * 8837 * @param hint A hint about whether or not this view is displayed: 8838 * {@link #VISIBLE} or {@link #INVISIBLE}. 8839 */ 8840 public void dispatchDisplayHint(@Visibility int hint) { 8841 onDisplayHint(hint); 8842 } 8843 8844 /** 8845 * Gives this view a hint about whether is displayed or not. For instance, when 8846 * a View moves out of the screen, it might receives a display hint indicating 8847 * the view is not displayed. Applications should not <em>rely</em> on this hint 8848 * as there is no guarantee that they will receive one. 8849 * 8850 * @param hint A hint about whether or not this view is displayed: 8851 * {@link #VISIBLE} or {@link #INVISIBLE}. 8852 */ 8853 protected void onDisplayHint(@Visibility int hint) { 8854 } 8855 8856 /** 8857 * Dispatch a window visibility change down the view hierarchy. 8858 * ViewGroups should override to route to their children. 8859 * 8860 * @param visibility The new visibility of the window. 8861 * 8862 * @see #onWindowVisibilityChanged(int) 8863 */ 8864 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8865 onWindowVisibilityChanged(visibility); 8866 } 8867 8868 /** 8869 * Called when the window containing has change its visibility 8870 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8871 * that this tells you whether or not your window is being made visible 8872 * to the window manager; this does <em>not</em> tell you whether or not 8873 * your window is obscured by other windows on the screen, even if it 8874 * is itself visible. 8875 * 8876 * @param visibility The new visibility of the window. 8877 */ 8878 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8879 if (visibility == VISIBLE) { 8880 initialAwakenScrollBars(); 8881 } 8882 } 8883 8884 /** 8885 * Returns the current visibility of the window this view is attached to 8886 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8887 * 8888 * @return Returns the current visibility of the view's window. 8889 */ 8890 @Visibility 8891 public int getWindowVisibility() { 8892 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8893 } 8894 8895 /** 8896 * Retrieve the overall visible display size in which the window this view is 8897 * attached to has been positioned in. This takes into account screen 8898 * decorations above the window, for both cases where the window itself 8899 * is being position inside of them or the window is being placed under 8900 * then and covered insets are used for the window to position its content 8901 * inside. In effect, this tells you the available area where content can 8902 * be placed and remain visible to users. 8903 * 8904 * <p>This function requires an IPC back to the window manager to retrieve 8905 * the requested information, so should not be used in performance critical 8906 * code like drawing. 8907 * 8908 * @param outRect Filled in with the visible display frame. If the view 8909 * is not attached to a window, this is simply the raw display size. 8910 */ 8911 public void getWindowVisibleDisplayFrame(Rect outRect) { 8912 if (mAttachInfo != null) { 8913 try { 8914 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8915 } catch (RemoteException e) { 8916 return; 8917 } 8918 // XXX This is really broken, and probably all needs to be done 8919 // in the window manager, and we need to know more about whether 8920 // we want the area behind or in front of the IME. 8921 final Rect insets = mAttachInfo.mVisibleInsets; 8922 outRect.left += insets.left; 8923 outRect.top += insets.top; 8924 outRect.right -= insets.right; 8925 outRect.bottom -= insets.bottom; 8926 return; 8927 } 8928 // The view is not attached to a display so we don't have a context. 8929 // Make a best guess about the display size. 8930 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8931 d.getRectSize(outRect); 8932 } 8933 8934 /** 8935 * Dispatch a notification about a resource configuration change down 8936 * the view hierarchy. 8937 * ViewGroups should override to route to their children. 8938 * 8939 * @param newConfig The new resource configuration. 8940 * 8941 * @see #onConfigurationChanged(android.content.res.Configuration) 8942 */ 8943 public void dispatchConfigurationChanged(Configuration newConfig) { 8944 onConfigurationChanged(newConfig); 8945 } 8946 8947 /** 8948 * Called when the current configuration of the resources being used 8949 * by the application have changed. You can use this to decide when 8950 * to reload resources that can changed based on orientation and other 8951 * configuration characterstics. You only need to use this if you are 8952 * not relying on the normal {@link android.app.Activity} mechanism of 8953 * recreating the activity instance upon a configuration change. 8954 * 8955 * @param newConfig The new resource configuration. 8956 */ 8957 protected void onConfigurationChanged(Configuration newConfig) { 8958 } 8959 8960 /** 8961 * Private function to aggregate all per-view attributes in to the view 8962 * root. 8963 */ 8964 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8965 performCollectViewAttributes(attachInfo, visibility); 8966 } 8967 8968 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8969 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8970 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8971 attachInfo.mKeepScreenOn = true; 8972 } 8973 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8974 ListenerInfo li = mListenerInfo; 8975 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8976 attachInfo.mHasSystemUiListeners = true; 8977 } 8978 } 8979 } 8980 8981 void needGlobalAttributesUpdate(boolean force) { 8982 final AttachInfo ai = mAttachInfo; 8983 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8984 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8985 || ai.mHasSystemUiListeners) { 8986 ai.mRecomputeGlobalAttributes = true; 8987 } 8988 } 8989 } 8990 8991 /** 8992 * Returns whether the device is currently in touch mode. Touch mode is entered 8993 * once the user begins interacting with the device by touch, and affects various 8994 * things like whether focus is always visible to the user. 8995 * 8996 * @return Whether the device is in touch mode. 8997 */ 8998 @ViewDebug.ExportedProperty 8999 public boolean isInTouchMode() { 9000 if (mAttachInfo != null) { 9001 return mAttachInfo.mInTouchMode; 9002 } else { 9003 return ViewRootImpl.isInTouchMode(); 9004 } 9005 } 9006 9007 /** 9008 * Returns the context the view is running in, through which it can 9009 * access the current theme, resources, etc. 9010 * 9011 * @return The view's Context. 9012 */ 9013 @ViewDebug.CapturedViewProperty 9014 public final Context getContext() { 9015 return mContext; 9016 } 9017 9018 /** 9019 * Handle a key event before it is processed by any input method 9020 * associated with the view hierarchy. This can be used to intercept 9021 * key events in special situations before the IME consumes them; a 9022 * typical example would be handling the BACK key to update the application's 9023 * UI instead of allowing the IME to see it and close itself. 9024 * 9025 * @param keyCode The value in event.getKeyCode(). 9026 * @param event Description of the key event. 9027 * @return If you handled the event, return true. If you want to allow the 9028 * event to be handled by the next receiver, return false. 9029 */ 9030 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 9031 return false; 9032 } 9033 9034 /** 9035 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 9036 * KeyEvent.Callback.onKeyDown()}: perform press of the view 9037 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 9038 * is released, if the view is enabled and clickable. 9039 * 9040 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9041 * although some may elect to do so in some situations. Do not rely on this to 9042 * catch software key presses. 9043 * 9044 * @param keyCode A key code that represents the button pressed, from 9045 * {@link android.view.KeyEvent}. 9046 * @param event The KeyEvent object that defines the button action. 9047 */ 9048 public boolean onKeyDown(int keyCode, KeyEvent event) { 9049 boolean result = false; 9050 9051 if (KeyEvent.isConfirmKey(keyCode)) { 9052 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9053 return true; 9054 } 9055 // Long clickable items don't necessarily have to be clickable 9056 if (((mViewFlags & CLICKABLE) == CLICKABLE || 9057 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 9058 (event.getRepeatCount() == 0)) { 9059 setPressed(true); 9060 checkForLongClick(0); 9061 return true; 9062 } 9063 } 9064 return result; 9065 } 9066 9067 /** 9068 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 9069 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 9070 * the event). 9071 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9072 * although some may elect to do so in some situations. Do not rely on this to 9073 * catch software key presses. 9074 */ 9075 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 9076 return false; 9077 } 9078 9079 /** 9080 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 9081 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 9082 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 9083 * {@link KeyEvent#KEYCODE_ENTER} is released. 9084 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9085 * although some may elect to do so in some situations. Do not rely on this to 9086 * catch software key presses. 9087 * 9088 * @param keyCode A key code that represents the button pressed, from 9089 * {@link android.view.KeyEvent}. 9090 * @param event The KeyEvent object that defines the button action. 9091 */ 9092 public boolean onKeyUp(int keyCode, KeyEvent event) { 9093 if (KeyEvent.isConfirmKey(keyCode)) { 9094 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9095 return true; 9096 } 9097 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 9098 setPressed(false); 9099 9100 if (!mHasPerformedLongPress) { 9101 // This is a tap, so remove the longpress check 9102 removeLongPressCallback(); 9103 return performClick(); 9104 } 9105 } 9106 } 9107 return false; 9108 } 9109 9110 /** 9111 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 9112 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 9113 * the event). 9114 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9115 * although some may elect to do so in some situations. Do not rely on this to 9116 * catch software key presses. 9117 * 9118 * @param keyCode A key code that represents the button pressed, from 9119 * {@link android.view.KeyEvent}. 9120 * @param repeatCount The number of times the action was made. 9121 * @param event The KeyEvent object that defines the button action. 9122 */ 9123 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 9124 return false; 9125 } 9126 9127 /** 9128 * Called on the focused view when a key shortcut event is not handled. 9129 * Override this method to implement local key shortcuts for the View. 9130 * Key shortcuts can also be implemented by setting the 9131 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 9132 * 9133 * @param keyCode The value in event.getKeyCode(). 9134 * @param event Description of the key event. 9135 * @return If you handled the event, return true. If you want to allow the 9136 * event to be handled by the next receiver, return false. 9137 */ 9138 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 9139 return false; 9140 } 9141 9142 /** 9143 * Check whether the called view is a text editor, in which case it 9144 * would make sense to automatically display a soft input window for 9145 * it. Subclasses should override this if they implement 9146 * {@link #onCreateInputConnection(EditorInfo)} to return true if 9147 * a call on that method would return a non-null InputConnection, and 9148 * they are really a first-class editor that the user would normally 9149 * start typing on when the go into a window containing your view. 9150 * 9151 * <p>The default implementation always returns false. This does 9152 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 9153 * will not be called or the user can not otherwise perform edits on your 9154 * view; it is just a hint to the system that this is not the primary 9155 * purpose of this view. 9156 * 9157 * @return Returns true if this view is a text editor, else false. 9158 */ 9159 public boolean onCheckIsTextEditor() { 9160 return false; 9161 } 9162 9163 /** 9164 * Create a new InputConnection for an InputMethod to interact 9165 * with the view. The default implementation returns null, since it doesn't 9166 * support input methods. You can override this to implement such support. 9167 * This is only needed for views that take focus and text input. 9168 * 9169 * <p>When implementing this, you probably also want to implement 9170 * {@link #onCheckIsTextEditor()} to indicate you will return a 9171 * non-null InputConnection.</p> 9172 * 9173 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 9174 * object correctly and in its entirety, so that the connected IME can rely 9175 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 9176 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 9177 * must be filled in with the correct cursor position for IMEs to work correctly 9178 * with your application.</p> 9179 * 9180 * @param outAttrs Fill in with attribute information about the connection. 9181 */ 9182 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 9183 return null; 9184 } 9185 9186 /** 9187 * Called by the {@link android.view.inputmethod.InputMethodManager} 9188 * when a view who is not the current 9189 * input connection target is trying to make a call on the manager. The 9190 * default implementation returns false; you can override this to return 9191 * true for certain views if you are performing InputConnection proxying 9192 * to them. 9193 * @param view The View that is making the InputMethodManager call. 9194 * @return Return true to allow the call, false to reject. 9195 */ 9196 public boolean checkInputConnectionProxy(View view) { 9197 return false; 9198 } 9199 9200 /** 9201 * Show the context menu for this view. It is not safe to hold on to the 9202 * menu after returning from this method. 9203 * 9204 * You should normally not overload this method. Overload 9205 * {@link #onCreateContextMenu(ContextMenu)} or define an 9206 * {@link OnCreateContextMenuListener} to add items to the context menu. 9207 * 9208 * @param menu The context menu to populate 9209 */ 9210 public void createContextMenu(ContextMenu menu) { 9211 ContextMenuInfo menuInfo = getContextMenuInfo(); 9212 9213 // Sets the current menu info so all items added to menu will have 9214 // my extra info set. 9215 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 9216 9217 onCreateContextMenu(menu); 9218 ListenerInfo li = mListenerInfo; 9219 if (li != null && li.mOnCreateContextMenuListener != null) { 9220 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 9221 } 9222 9223 // Clear the extra information so subsequent items that aren't mine don't 9224 // have my extra info. 9225 ((MenuBuilder)menu).setCurrentMenuInfo(null); 9226 9227 if (mParent != null) { 9228 mParent.createContextMenu(menu); 9229 } 9230 } 9231 9232 /** 9233 * Views should implement this if they have extra information to associate 9234 * with the context menu. The return result is supplied as a parameter to 9235 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 9236 * callback. 9237 * 9238 * @return Extra information about the item for which the context menu 9239 * should be shown. This information will vary across different 9240 * subclasses of View. 9241 */ 9242 protected ContextMenuInfo getContextMenuInfo() { 9243 return null; 9244 } 9245 9246 /** 9247 * Views should implement this if the view itself is going to add items to 9248 * the context menu. 9249 * 9250 * @param menu the context menu to populate 9251 */ 9252 protected void onCreateContextMenu(ContextMenu menu) { 9253 } 9254 9255 /** 9256 * Implement this method to handle trackball motion events. The 9257 * <em>relative</em> movement of the trackball since the last event 9258 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 9259 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 9260 * that a movement of 1 corresponds to the user pressing one DPAD key (so 9261 * they will often be fractional values, representing the more fine-grained 9262 * movement information available from a trackball). 9263 * 9264 * @param event The motion event. 9265 * @return True if the event was handled, false otherwise. 9266 */ 9267 public boolean onTrackballEvent(MotionEvent event) { 9268 return false; 9269 } 9270 9271 /** 9272 * Implement this method to handle generic motion events. 9273 * <p> 9274 * Generic motion events describe joystick movements, mouse hovers, track pad 9275 * touches, scroll wheel movements and other input events. The 9276 * {@link MotionEvent#getSource() source} of the motion event specifies 9277 * the class of input that was received. Implementations of this method 9278 * must examine the bits in the source before processing the event. 9279 * The following code example shows how this is done. 9280 * </p><p> 9281 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9282 * are delivered to the view under the pointer. All other generic motion events are 9283 * delivered to the focused view. 9284 * </p> 9285 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 9286 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 9287 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 9288 * // process the joystick movement... 9289 * return true; 9290 * } 9291 * } 9292 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 9293 * switch (event.getAction()) { 9294 * case MotionEvent.ACTION_HOVER_MOVE: 9295 * // process the mouse hover movement... 9296 * return true; 9297 * case MotionEvent.ACTION_SCROLL: 9298 * // process the scroll wheel movement... 9299 * return true; 9300 * } 9301 * } 9302 * return super.onGenericMotionEvent(event); 9303 * }</pre> 9304 * 9305 * @param event The generic motion event being processed. 9306 * @return True if the event was handled, false otherwise. 9307 */ 9308 public boolean onGenericMotionEvent(MotionEvent event) { 9309 return false; 9310 } 9311 9312 /** 9313 * Implement this method to handle hover events. 9314 * <p> 9315 * This method is called whenever a pointer is hovering into, over, or out of the 9316 * bounds of a view and the view is not currently being touched. 9317 * Hover events are represented as pointer events with action 9318 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 9319 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 9320 * </p> 9321 * <ul> 9322 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 9323 * when the pointer enters the bounds of the view.</li> 9324 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 9325 * when the pointer has already entered the bounds of the view and has moved.</li> 9326 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 9327 * when the pointer has exited the bounds of the view or when the pointer is 9328 * about to go down due to a button click, tap, or similar user action that 9329 * causes the view to be touched.</li> 9330 * </ul> 9331 * <p> 9332 * The view should implement this method to return true to indicate that it is 9333 * handling the hover event, such as by changing its drawable state. 9334 * </p><p> 9335 * The default implementation calls {@link #setHovered} to update the hovered state 9336 * of the view when a hover enter or hover exit event is received, if the view 9337 * is enabled and is clickable. The default implementation also sends hover 9338 * accessibility events. 9339 * </p> 9340 * 9341 * @param event The motion event that describes the hover. 9342 * @return True if the view handled the hover event. 9343 * 9344 * @see #isHovered 9345 * @see #setHovered 9346 * @see #onHoverChanged 9347 */ 9348 public boolean onHoverEvent(MotionEvent event) { 9349 // The root view may receive hover (or touch) events that are outside the bounds of 9350 // the window. This code ensures that we only send accessibility events for 9351 // hovers that are actually within the bounds of the root view. 9352 final int action = event.getActionMasked(); 9353 if (!mSendingHoverAccessibilityEvents) { 9354 if ((action == MotionEvent.ACTION_HOVER_ENTER 9355 || action == MotionEvent.ACTION_HOVER_MOVE) 9356 && !hasHoveredChild() 9357 && pointInView(event.getX(), event.getY())) { 9358 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 9359 mSendingHoverAccessibilityEvents = true; 9360 } 9361 } else { 9362 if (action == MotionEvent.ACTION_HOVER_EXIT 9363 || (action == MotionEvent.ACTION_MOVE 9364 && !pointInView(event.getX(), event.getY()))) { 9365 mSendingHoverAccessibilityEvents = false; 9366 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 9367 } 9368 } 9369 9370 if (isHoverable()) { 9371 switch (action) { 9372 case MotionEvent.ACTION_HOVER_ENTER: 9373 setHovered(true); 9374 break; 9375 case MotionEvent.ACTION_HOVER_EXIT: 9376 setHovered(false); 9377 break; 9378 } 9379 9380 // Dispatch the event to onGenericMotionEvent before returning true. 9381 // This is to provide compatibility with existing applications that 9382 // handled HOVER_MOVE events in onGenericMotionEvent and that would 9383 // break because of the new default handling for hoverable views 9384 // in onHoverEvent. 9385 // Note that onGenericMotionEvent will be called by default when 9386 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 9387 dispatchGenericMotionEventInternal(event); 9388 // The event was already handled by calling setHovered(), so always 9389 // return true. 9390 return true; 9391 } 9392 9393 return false; 9394 } 9395 9396 /** 9397 * Returns true if the view should handle {@link #onHoverEvent} 9398 * by calling {@link #setHovered} to change its hovered state. 9399 * 9400 * @return True if the view is hoverable. 9401 */ 9402 private boolean isHoverable() { 9403 final int viewFlags = mViewFlags; 9404 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9405 return false; 9406 } 9407 9408 return (viewFlags & CLICKABLE) == CLICKABLE 9409 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 9410 } 9411 9412 /** 9413 * Returns true if the view is currently hovered. 9414 * 9415 * @return True if the view is currently hovered. 9416 * 9417 * @see #setHovered 9418 * @see #onHoverChanged 9419 */ 9420 @ViewDebug.ExportedProperty 9421 public boolean isHovered() { 9422 return (mPrivateFlags & PFLAG_HOVERED) != 0; 9423 } 9424 9425 /** 9426 * Sets whether the view is currently hovered. 9427 * <p> 9428 * Calling this method also changes the drawable state of the view. This 9429 * enables the view to react to hover by using different drawable resources 9430 * to change its appearance. 9431 * </p><p> 9432 * The {@link #onHoverChanged} method is called when the hovered state changes. 9433 * </p> 9434 * 9435 * @param hovered True if the view is hovered. 9436 * 9437 * @see #isHovered 9438 * @see #onHoverChanged 9439 */ 9440 public void setHovered(boolean hovered) { 9441 if (hovered) { 9442 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 9443 mPrivateFlags |= PFLAG_HOVERED; 9444 refreshDrawableState(); 9445 onHoverChanged(true); 9446 } 9447 } else { 9448 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 9449 mPrivateFlags &= ~PFLAG_HOVERED; 9450 refreshDrawableState(); 9451 onHoverChanged(false); 9452 } 9453 } 9454 } 9455 9456 /** 9457 * Implement this method to handle hover state changes. 9458 * <p> 9459 * This method is called whenever the hover state changes as a result of a 9460 * call to {@link #setHovered}. 9461 * </p> 9462 * 9463 * @param hovered The current hover state, as returned by {@link #isHovered}. 9464 * 9465 * @see #isHovered 9466 * @see #setHovered 9467 */ 9468 public void onHoverChanged(boolean hovered) { 9469 } 9470 9471 /** 9472 * Implement this method to handle touch screen motion events. 9473 * <p> 9474 * If this method is used to detect click actions, it is recommended that 9475 * the actions be performed by implementing and calling 9476 * {@link #performClick()}. This will ensure consistent system behavior, 9477 * including: 9478 * <ul> 9479 * <li>obeying click sound preferences 9480 * <li>dispatching OnClickListener calls 9481 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9482 * accessibility features are enabled 9483 * </ul> 9484 * 9485 * @param event The motion event. 9486 * @return True if the event was handled, false otherwise. 9487 */ 9488 public boolean onTouchEvent(MotionEvent event) { 9489 final float x = event.getX(); 9490 final float y = event.getY(); 9491 final int viewFlags = mViewFlags; 9492 9493 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9494 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9495 setPressed(false); 9496 } 9497 // A disabled view that is clickable still consumes the touch 9498 // events, it just doesn't respond to them. 9499 return (((viewFlags & CLICKABLE) == CLICKABLE || 9500 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9501 } 9502 9503 if (mTouchDelegate != null) { 9504 if (mTouchDelegate.onTouchEvent(event)) { 9505 return true; 9506 } 9507 } 9508 9509 if (((viewFlags & CLICKABLE) == CLICKABLE || 9510 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9511 switch (event.getAction()) { 9512 case MotionEvent.ACTION_UP: 9513 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9514 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9515 // take focus if we don't have it already and we should in 9516 // touch mode. 9517 boolean focusTaken = false; 9518 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9519 focusTaken = requestFocus(); 9520 } 9521 9522 if (prepressed) { 9523 // The button is being released before we actually 9524 // showed it as pressed. Make it show the pressed 9525 // state now (before scheduling the click) to ensure 9526 // the user sees it. 9527 setPressed(true, x, y); 9528 } 9529 9530 if (!mHasPerformedLongPress) { 9531 // This is a tap, so remove the longpress check 9532 removeLongPressCallback(); 9533 9534 // Only perform take click actions if we were in the pressed state 9535 if (!focusTaken) { 9536 // Use a Runnable and post this rather than calling 9537 // performClick directly. This lets other visual state 9538 // of the view update before click actions start. 9539 if (mPerformClick == null) { 9540 mPerformClick = new PerformClick(); 9541 } 9542 if (!post(mPerformClick)) { 9543 performClick(); 9544 } 9545 } 9546 } 9547 9548 if (mUnsetPressedState == null) { 9549 mUnsetPressedState = new UnsetPressedState(); 9550 } 9551 9552 if (prepressed) { 9553 postDelayed(mUnsetPressedState, 9554 ViewConfiguration.getPressedStateDuration()); 9555 } else if (!post(mUnsetPressedState)) { 9556 // If the post failed, unpress right now 9557 mUnsetPressedState.run(); 9558 } 9559 9560 removeTapCallback(); 9561 } 9562 break; 9563 9564 case MotionEvent.ACTION_DOWN: 9565 mHasPerformedLongPress = false; 9566 9567 if (performButtonActionOnTouchDown(event)) { 9568 break; 9569 } 9570 9571 // Walk up the hierarchy to determine if we're inside a scrolling container. 9572 boolean isInScrollingContainer = isInScrollingContainer(); 9573 9574 // For views inside a scrolling container, delay the pressed feedback for 9575 // a short period in case this is a scroll. 9576 if (isInScrollingContainer) { 9577 mPrivateFlags |= PFLAG_PREPRESSED; 9578 if (mPendingCheckForTap == null) { 9579 mPendingCheckForTap = new CheckForTap(); 9580 } 9581 mPendingCheckForTap.x = event.getX(); 9582 mPendingCheckForTap.y = event.getY(); 9583 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9584 } else { 9585 // Not inside a scrolling container, so show the feedback right away 9586 setPressed(true, x, y); 9587 checkForLongClick(0); 9588 } 9589 break; 9590 9591 case MotionEvent.ACTION_CANCEL: 9592 setPressed(false); 9593 removeTapCallback(); 9594 removeLongPressCallback(); 9595 break; 9596 9597 case MotionEvent.ACTION_MOVE: 9598 drawableHotspotChanged(x, y); 9599 9600 // Be lenient about moving outside of buttons 9601 if (!pointInView(x, y, mTouchSlop)) { 9602 // Outside button 9603 removeTapCallback(); 9604 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9605 // Remove any future long press/tap checks 9606 removeLongPressCallback(); 9607 9608 setPressed(false); 9609 } 9610 } 9611 break; 9612 } 9613 9614 return true; 9615 } 9616 9617 return false; 9618 } 9619 9620 /** 9621 * @hide 9622 */ 9623 public boolean isInScrollingContainer() { 9624 ViewParent p = getParent(); 9625 while (p != null && p instanceof ViewGroup) { 9626 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9627 return true; 9628 } 9629 p = p.getParent(); 9630 } 9631 return false; 9632 } 9633 9634 /** 9635 * Remove the longpress detection timer. 9636 */ 9637 private void removeLongPressCallback() { 9638 if (mPendingCheckForLongPress != null) { 9639 removeCallbacks(mPendingCheckForLongPress); 9640 } 9641 } 9642 9643 /** 9644 * Remove the pending click action 9645 */ 9646 private void removePerformClickCallback() { 9647 if (mPerformClick != null) { 9648 removeCallbacks(mPerformClick); 9649 } 9650 } 9651 9652 /** 9653 * Remove the prepress detection timer. 9654 */ 9655 private void removeUnsetPressCallback() { 9656 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9657 setPressed(false); 9658 removeCallbacks(mUnsetPressedState); 9659 } 9660 } 9661 9662 /** 9663 * Remove the tap detection timer. 9664 */ 9665 private void removeTapCallback() { 9666 if (mPendingCheckForTap != null) { 9667 mPrivateFlags &= ~PFLAG_PREPRESSED; 9668 removeCallbacks(mPendingCheckForTap); 9669 } 9670 } 9671 9672 /** 9673 * Cancels a pending long press. Your subclass can use this if you 9674 * want the context menu to come up if the user presses and holds 9675 * at the same place, but you don't want it to come up if they press 9676 * and then move around enough to cause scrolling. 9677 */ 9678 public void cancelLongPress() { 9679 removeLongPressCallback(); 9680 9681 /* 9682 * The prepressed state handled by the tap callback is a display 9683 * construct, but the tap callback will post a long press callback 9684 * less its own timeout. Remove it here. 9685 */ 9686 removeTapCallback(); 9687 } 9688 9689 /** 9690 * Remove the pending callback for sending a 9691 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9692 */ 9693 private void removeSendViewScrolledAccessibilityEventCallback() { 9694 if (mSendViewScrolledAccessibilityEvent != null) { 9695 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9696 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9697 } 9698 } 9699 9700 /** 9701 * Sets the TouchDelegate for this View. 9702 */ 9703 public void setTouchDelegate(TouchDelegate delegate) { 9704 mTouchDelegate = delegate; 9705 } 9706 9707 /** 9708 * Gets the TouchDelegate for this View. 9709 */ 9710 public TouchDelegate getTouchDelegate() { 9711 return mTouchDelegate; 9712 } 9713 9714 /** 9715 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9716 * 9717 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9718 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9719 * available. This method should only be called for touch events. 9720 * 9721 * <p class="note">This api is not intended for most applications. Buffered dispatch 9722 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9723 * streams will not improve your input latency. Side effects include: increased latency, 9724 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9725 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9726 * you.</p> 9727 */ 9728 public final void requestUnbufferedDispatch(MotionEvent event) { 9729 final int action = event.getAction(); 9730 if (mAttachInfo == null 9731 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9732 || !event.isTouchEvent()) { 9733 return; 9734 } 9735 mAttachInfo.mUnbufferedDispatchRequested = true; 9736 } 9737 9738 /** 9739 * Set flags controlling behavior of this view. 9740 * 9741 * @param flags Constant indicating the value which should be set 9742 * @param mask Constant indicating the bit range that should be changed 9743 */ 9744 void setFlags(int flags, int mask) { 9745 final boolean accessibilityEnabled = 9746 AccessibilityManager.getInstance(mContext).isEnabled(); 9747 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9748 9749 int old = mViewFlags; 9750 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9751 9752 int changed = mViewFlags ^ old; 9753 if (changed == 0) { 9754 return; 9755 } 9756 int privateFlags = mPrivateFlags; 9757 9758 /* Check if the FOCUSABLE bit has changed */ 9759 if (((changed & FOCUSABLE_MASK) != 0) && 9760 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9761 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9762 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9763 /* Give up focus if we are no longer focusable */ 9764 clearFocus(); 9765 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9766 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9767 /* 9768 * Tell the view system that we are now available to take focus 9769 * if no one else already has it. 9770 */ 9771 if (mParent != null) mParent.focusableViewAvailable(this); 9772 } 9773 } 9774 9775 final int newVisibility = flags & VISIBILITY_MASK; 9776 if (newVisibility == VISIBLE) { 9777 if ((changed & VISIBILITY_MASK) != 0) { 9778 /* 9779 * If this view is becoming visible, invalidate it in case it changed while 9780 * it was not visible. Marking it drawn ensures that the invalidation will 9781 * go through. 9782 */ 9783 mPrivateFlags |= PFLAG_DRAWN; 9784 invalidate(true); 9785 9786 needGlobalAttributesUpdate(true); 9787 9788 // a view becoming visible is worth notifying the parent 9789 // about in case nothing has focus. even if this specific view 9790 // isn't focusable, it may contain something that is, so let 9791 // the root view try to give this focus if nothing else does. 9792 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9793 mParent.focusableViewAvailable(this); 9794 } 9795 } 9796 } 9797 9798 /* Check if the GONE bit has changed */ 9799 if ((changed & GONE) != 0) { 9800 needGlobalAttributesUpdate(false); 9801 requestLayout(); 9802 9803 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9804 if (hasFocus()) clearFocus(); 9805 clearAccessibilityFocus(); 9806 destroyDrawingCache(); 9807 if (mParent instanceof View) { 9808 // GONE views noop invalidation, so invalidate the parent 9809 ((View) mParent).invalidate(true); 9810 } 9811 // Mark the view drawn to ensure that it gets invalidated properly the next 9812 // time it is visible and gets invalidated 9813 mPrivateFlags |= PFLAG_DRAWN; 9814 } 9815 if (mAttachInfo != null) { 9816 mAttachInfo.mViewVisibilityChanged = true; 9817 } 9818 } 9819 9820 /* Check if the VISIBLE bit has changed */ 9821 if ((changed & INVISIBLE) != 0) { 9822 needGlobalAttributesUpdate(false); 9823 /* 9824 * If this view is becoming invisible, set the DRAWN flag so that 9825 * the next invalidate() will not be skipped. 9826 */ 9827 mPrivateFlags |= PFLAG_DRAWN; 9828 9829 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9830 // root view becoming invisible shouldn't clear focus and accessibility focus 9831 if (getRootView() != this) { 9832 if (hasFocus()) clearFocus(); 9833 clearAccessibilityFocus(); 9834 } 9835 } 9836 if (mAttachInfo != null) { 9837 mAttachInfo.mViewVisibilityChanged = true; 9838 } 9839 } 9840 9841 if ((changed & VISIBILITY_MASK) != 0) { 9842 // If the view is invisible, cleanup its display list to free up resources 9843 if (newVisibility != VISIBLE && mAttachInfo != null) { 9844 cleanupDraw(); 9845 } 9846 9847 if (mParent instanceof ViewGroup) { 9848 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9849 (changed & VISIBILITY_MASK), newVisibility); 9850 ((View) mParent).invalidate(true); 9851 } else if (mParent != null) { 9852 mParent.invalidateChild(this, null); 9853 } 9854 dispatchVisibilityChanged(this, newVisibility); 9855 9856 notifySubtreeAccessibilityStateChangedIfNeeded(); 9857 } 9858 9859 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9860 destroyDrawingCache(); 9861 } 9862 9863 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9864 destroyDrawingCache(); 9865 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9866 invalidateParentCaches(); 9867 } 9868 9869 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9870 destroyDrawingCache(); 9871 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9872 } 9873 9874 if ((changed & DRAW_MASK) != 0) { 9875 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9876 if (mBackground != null) { 9877 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9878 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9879 } else { 9880 mPrivateFlags |= PFLAG_SKIP_DRAW; 9881 } 9882 } else { 9883 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9884 } 9885 requestLayout(); 9886 invalidate(true); 9887 } 9888 9889 if ((changed & KEEP_SCREEN_ON) != 0) { 9890 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9891 mParent.recomputeViewAttributes(this); 9892 } 9893 } 9894 9895 if (accessibilityEnabled) { 9896 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9897 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9898 if (oldIncludeForAccessibility != includeForAccessibility()) { 9899 notifySubtreeAccessibilityStateChangedIfNeeded(); 9900 } else { 9901 notifyViewAccessibilityStateChangedIfNeeded( 9902 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9903 } 9904 } else if ((changed & ENABLED_MASK) != 0) { 9905 notifyViewAccessibilityStateChangedIfNeeded( 9906 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9907 } 9908 } 9909 } 9910 9911 /** 9912 * Change the view's z order in the tree, so it's on top of other sibling 9913 * views. This ordering change may affect layout, if the parent container 9914 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9915 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9916 * method should be followed by calls to {@link #requestLayout()} and 9917 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9918 * with the new child ordering. 9919 * 9920 * @see ViewGroup#bringChildToFront(View) 9921 */ 9922 public void bringToFront() { 9923 if (mParent != null) { 9924 mParent.bringChildToFront(this); 9925 } 9926 } 9927 9928 /** 9929 * This is called in response to an internal scroll in this view (i.e., the 9930 * view scrolled its own contents). This is typically as a result of 9931 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9932 * called. 9933 * 9934 * @param l Current horizontal scroll origin. 9935 * @param t Current vertical scroll origin. 9936 * @param oldl Previous horizontal scroll origin. 9937 * @param oldt Previous vertical scroll origin. 9938 */ 9939 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9940 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9941 postSendViewScrolledAccessibilityEventCallback(); 9942 } 9943 9944 mBackgroundSizeChanged = true; 9945 9946 final AttachInfo ai = mAttachInfo; 9947 if (ai != null) { 9948 ai.mViewScrollChanged = true; 9949 } 9950 9951 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 9952 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 9953 } 9954 } 9955 9956 /** 9957 * Interface definition for a callback to be invoked when the scroll 9958 * position of a view changes. 9959 * 9960 * @hide Only used internally. 9961 */ 9962 public interface OnScrollChangeListener { 9963 /** 9964 * Called when the scroll position of a view changes. 9965 * 9966 * @param v The view whose scroll position has changed. 9967 * @param scrollX Current horizontal scroll origin. 9968 * @param scrollY Current vertical scroll origin. 9969 * @param oldScrollX Previous horizontal scroll origin. 9970 * @param oldScrollY Previous vertical scroll origin. 9971 */ 9972 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 9973 } 9974 9975 /** 9976 * Interface definition for a callback to be invoked when the layout bounds of a view 9977 * changes due to layout processing. 9978 */ 9979 public interface OnLayoutChangeListener { 9980 /** 9981 * Called when the layout bounds of a view changes due to layout processing. 9982 * 9983 * @param v The view whose bounds have changed. 9984 * @param left The new value of the view's left property. 9985 * @param top The new value of the view's top property. 9986 * @param right The new value of the view's right property. 9987 * @param bottom The new value of the view's bottom property. 9988 * @param oldLeft The previous value of the view's left property. 9989 * @param oldTop The previous value of the view's top property. 9990 * @param oldRight The previous value of the view's right property. 9991 * @param oldBottom The previous value of the view's bottom property. 9992 */ 9993 void onLayoutChange(View v, int left, int top, int right, int bottom, 9994 int oldLeft, int oldTop, int oldRight, int oldBottom); 9995 } 9996 9997 /** 9998 * This is called during layout when the size of this view has changed. If 9999 * you were just added to the view hierarchy, you're called with the old 10000 * values of 0. 10001 * 10002 * @param w Current width of this view. 10003 * @param h Current height of this view. 10004 * @param oldw Old width of this view. 10005 * @param oldh Old height of this view. 10006 */ 10007 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 10008 } 10009 10010 /** 10011 * Called by draw to draw the child views. This may be overridden 10012 * by derived classes to gain control just before its children are drawn 10013 * (but after its own view has been drawn). 10014 * @param canvas the canvas on which to draw the view 10015 */ 10016 protected void dispatchDraw(Canvas canvas) { 10017 10018 } 10019 10020 /** 10021 * Gets the parent of this view. Note that the parent is a 10022 * ViewParent and not necessarily a View. 10023 * 10024 * @return Parent of this view. 10025 */ 10026 public final ViewParent getParent() { 10027 return mParent; 10028 } 10029 10030 /** 10031 * Set the horizontal scrolled position of your view. This will cause a call to 10032 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10033 * invalidated. 10034 * @param value the x position to scroll to 10035 */ 10036 public void setScrollX(int value) { 10037 scrollTo(value, mScrollY); 10038 } 10039 10040 /** 10041 * Set the vertical scrolled position of your view. This will cause a call to 10042 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10043 * invalidated. 10044 * @param value the y position to scroll to 10045 */ 10046 public void setScrollY(int value) { 10047 scrollTo(mScrollX, value); 10048 } 10049 10050 /** 10051 * Return the scrolled left position of this view. This is the left edge of 10052 * the displayed part of your view. You do not need to draw any pixels 10053 * farther left, since those are outside of the frame of your view on 10054 * screen. 10055 * 10056 * @return The left edge of the displayed part of your view, in pixels. 10057 */ 10058 public final int getScrollX() { 10059 return mScrollX; 10060 } 10061 10062 /** 10063 * Return the scrolled top position of this view. This is the top edge of 10064 * the displayed part of your view. You do not need to draw any pixels above 10065 * it, since those are outside of the frame of your view on screen. 10066 * 10067 * @return The top edge of the displayed part of your view, in pixels. 10068 */ 10069 public final int getScrollY() { 10070 return mScrollY; 10071 } 10072 10073 /** 10074 * Return the width of the your view. 10075 * 10076 * @return The width of your view, in pixels. 10077 */ 10078 @ViewDebug.ExportedProperty(category = "layout") 10079 public final int getWidth() { 10080 return mRight - mLeft; 10081 } 10082 10083 /** 10084 * Return the height of your view. 10085 * 10086 * @return The height of your view, in pixels. 10087 */ 10088 @ViewDebug.ExportedProperty(category = "layout") 10089 public final int getHeight() { 10090 return mBottom - mTop; 10091 } 10092 10093 /** 10094 * Return the visible drawing bounds of your view. Fills in the output 10095 * rectangle with the values from getScrollX(), getScrollY(), 10096 * getWidth(), and getHeight(). These bounds do not account for any 10097 * transformation properties currently set on the view, such as 10098 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 10099 * 10100 * @param outRect The (scrolled) drawing bounds of the view. 10101 */ 10102 public void getDrawingRect(Rect outRect) { 10103 outRect.left = mScrollX; 10104 outRect.top = mScrollY; 10105 outRect.right = mScrollX + (mRight - mLeft); 10106 outRect.bottom = mScrollY + (mBottom - mTop); 10107 } 10108 10109 /** 10110 * Like {@link #getMeasuredWidthAndState()}, but only returns the 10111 * raw width component (that is the result is masked by 10112 * {@link #MEASURED_SIZE_MASK}). 10113 * 10114 * @return The raw measured width of this view. 10115 */ 10116 public final int getMeasuredWidth() { 10117 return mMeasuredWidth & MEASURED_SIZE_MASK; 10118 } 10119 10120 /** 10121 * Return the full width measurement information for this view as computed 10122 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10123 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10124 * This should be used during measurement and layout calculations only. Use 10125 * {@link #getWidth()} to see how wide a view is after layout. 10126 * 10127 * @return The measured width of this view as a bit mask. 10128 */ 10129 public final int getMeasuredWidthAndState() { 10130 return mMeasuredWidth; 10131 } 10132 10133 /** 10134 * Like {@link #getMeasuredHeightAndState()}, but only returns the 10135 * raw width component (that is the result is masked by 10136 * {@link #MEASURED_SIZE_MASK}). 10137 * 10138 * @return The raw measured height of this view. 10139 */ 10140 public final int getMeasuredHeight() { 10141 return mMeasuredHeight & MEASURED_SIZE_MASK; 10142 } 10143 10144 /** 10145 * Return the full height measurement information for this view as computed 10146 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10147 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10148 * This should be used during measurement and layout calculations only. Use 10149 * {@link #getHeight()} to see how wide a view is after layout. 10150 * 10151 * @return The measured width of this view as a bit mask. 10152 */ 10153 public final int getMeasuredHeightAndState() { 10154 return mMeasuredHeight; 10155 } 10156 10157 /** 10158 * Return only the state bits of {@link #getMeasuredWidthAndState()} 10159 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 10160 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 10161 * and the height component is at the shifted bits 10162 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 10163 */ 10164 public final int getMeasuredState() { 10165 return (mMeasuredWidth&MEASURED_STATE_MASK) 10166 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 10167 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 10168 } 10169 10170 /** 10171 * The transform matrix of this view, which is calculated based on the current 10172 * rotation, scale, and pivot properties. 10173 * 10174 * @see #getRotation() 10175 * @see #getScaleX() 10176 * @see #getScaleY() 10177 * @see #getPivotX() 10178 * @see #getPivotY() 10179 * @return The current transform matrix for the view 10180 */ 10181 public Matrix getMatrix() { 10182 ensureTransformationInfo(); 10183 final Matrix matrix = mTransformationInfo.mMatrix; 10184 mRenderNode.getMatrix(matrix); 10185 return matrix; 10186 } 10187 10188 /** 10189 * Returns true if the transform matrix is the identity matrix. 10190 * Recomputes the matrix if necessary. 10191 * 10192 * @return True if the transform matrix is the identity matrix, false otherwise. 10193 */ 10194 final boolean hasIdentityMatrix() { 10195 return mRenderNode.hasIdentityMatrix(); 10196 } 10197 10198 void ensureTransformationInfo() { 10199 if (mTransformationInfo == null) { 10200 mTransformationInfo = new TransformationInfo(); 10201 } 10202 } 10203 10204 /** 10205 * Utility method to retrieve the inverse of the current mMatrix property. 10206 * We cache the matrix to avoid recalculating it when transform properties 10207 * have not changed. 10208 * 10209 * @return The inverse of the current matrix of this view. 10210 * @hide 10211 */ 10212 public final Matrix getInverseMatrix() { 10213 ensureTransformationInfo(); 10214 if (mTransformationInfo.mInverseMatrix == null) { 10215 mTransformationInfo.mInverseMatrix = new Matrix(); 10216 } 10217 final Matrix matrix = mTransformationInfo.mInverseMatrix; 10218 mRenderNode.getInverseMatrix(matrix); 10219 return matrix; 10220 } 10221 10222 /** 10223 * Gets the distance along the Z axis from the camera to this view. 10224 * 10225 * @see #setCameraDistance(float) 10226 * 10227 * @return The distance along the Z axis. 10228 */ 10229 public float getCameraDistance() { 10230 final float dpi = mResources.getDisplayMetrics().densityDpi; 10231 return -(mRenderNode.getCameraDistance() * dpi); 10232 } 10233 10234 /** 10235 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 10236 * views are drawn) from the camera to this view. The camera's distance 10237 * affects 3D transformations, for instance rotations around the X and Y 10238 * axis. If the rotationX or rotationY properties are changed and this view is 10239 * large (more than half the size of the screen), it is recommended to always 10240 * use a camera distance that's greater than the height (X axis rotation) or 10241 * the width (Y axis rotation) of this view.</p> 10242 * 10243 * <p>The distance of the camera from the view plane can have an affect on the 10244 * perspective distortion of the view when it is rotated around the x or y axis. 10245 * For example, a large distance will result in a large viewing angle, and there 10246 * will not be much perspective distortion of the view as it rotates. A short 10247 * distance may cause much more perspective distortion upon rotation, and can 10248 * also result in some drawing artifacts if the rotated view ends up partially 10249 * behind the camera (which is why the recommendation is to use a distance at 10250 * least as far as the size of the view, if the view is to be rotated.)</p> 10251 * 10252 * <p>The distance is expressed in "depth pixels." The default distance depends 10253 * on the screen density. For instance, on a medium density display, the 10254 * default distance is 1280. On a high density display, the default distance 10255 * is 1920.</p> 10256 * 10257 * <p>If you want to specify a distance that leads to visually consistent 10258 * results across various densities, use the following formula:</p> 10259 * <pre> 10260 * float scale = context.getResources().getDisplayMetrics().density; 10261 * view.setCameraDistance(distance * scale); 10262 * </pre> 10263 * 10264 * <p>The density scale factor of a high density display is 1.5, 10265 * and 1920 = 1280 * 1.5.</p> 10266 * 10267 * @param distance The distance in "depth pixels", if negative the opposite 10268 * value is used 10269 * 10270 * @see #setRotationX(float) 10271 * @see #setRotationY(float) 10272 */ 10273 public void setCameraDistance(float distance) { 10274 final float dpi = mResources.getDisplayMetrics().densityDpi; 10275 10276 invalidateViewProperty(true, false); 10277 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 10278 invalidateViewProperty(false, false); 10279 10280 invalidateParentIfNeededAndWasQuickRejected(); 10281 } 10282 10283 /** 10284 * The degrees that the view is rotated around the pivot point. 10285 * 10286 * @see #setRotation(float) 10287 * @see #getPivotX() 10288 * @see #getPivotY() 10289 * 10290 * @return The degrees of rotation. 10291 */ 10292 @ViewDebug.ExportedProperty(category = "drawing") 10293 public float getRotation() { 10294 return mRenderNode.getRotation(); 10295 } 10296 10297 /** 10298 * Sets the degrees that the view is rotated around the pivot point. Increasing values 10299 * result in clockwise rotation. 10300 * 10301 * @param rotation The degrees of rotation. 10302 * 10303 * @see #getRotation() 10304 * @see #getPivotX() 10305 * @see #getPivotY() 10306 * @see #setRotationX(float) 10307 * @see #setRotationY(float) 10308 * 10309 * @attr ref android.R.styleable#View_rotation 10310 */ 10311 public void setRotation(float rotation) { 10312 if (rotation != getRotation()) { 10313 // Double-invalidation is necessary to capture view's old and new areas 10314 invalidateViewProperty(true, false); 10315 mRenderNode.setRotation(rotation); 10316 invalidateViewProperty(false, true); 10317 10318 invalidateParentIfNeededAndWasQuickRejected(); 10319 notifySubtreeAccessibilityStateChangedIfNeeded(); 10320 } 10321 } 10322 10323 /** 10324 * The degrees that the view is rotated around the vertical axis through the pivot point. 10325 * 10326 * @see #getPivotX() 10327 * @see #getPivotY() 10328 * @see #setRotationY(float) 10329 * 10330 * @return The degrees of Y rotation. 10331 */ 10332 @ViewDebug.ExportedProperty(category = "drawing") 10333 public float getRotationY() { 10334 return mRenderNode.getRotationY(); 10335 } 10336 10337 /** 10338 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 10339 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 10340 * down the y axis. 10341 * 10342 * When rotating large views, it is recommended to adjust the camera distance 10343 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10344 * 10345 * @param rotationY The degrees of Y rotation. 10346 * 10347 * @see #getRotationY() 10348 * @see #getPivotX() 10349 * @see #getPivotY() 10350 * @see #setRotation(float) 10351 * @see #setRotationX(float) 10352 * @see #setCameraDistance(float) 10353 * 10354 * @attr ref android.R.styleable#View_rotationY 10355 */ 10356 public void setRotationY(float rotationY) { 10357 if (rotationY != getRotationY()) { 10358 invalidateViewProperty(true, false); 10359 mRenderNode.setRotationY(rotationY); 10360 invalidateViewProperty(false, true); 10361 10362 invalidateParentIfNeededAndWasQuickRejected(); 10363 notifySubtreeAccessibilityStateChangedIfNeeded(); 10364 } 10365 } 10366 10367 /** 10368 * The degrees that the view is rotated around the horizontal axis through the pivot point. 10369 * 10370 * @see #getPivotX() 10371 * @see #getPivotY() 10372 * @see #setRotationX(float) 10373 * 10374 * @return The degrees of X rotation. 10375 */ 10376 @ViewDebug.ExportedProperty(category = "drawing") 10377 public float getRotationX() { 10378 return mRenderNode.getRotationX(); 10379 } 10380 10381 /** 10382 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 10383 * Increasing values result in clockwise rotation from the viewpoint of looking down the 10384 * x axis. 10385 * 10386 * When rotating large views, it is recommended to adjust the camera distance 10387 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10388 * 10389 * @param rotationX The degrees of X rotation. 10390 * 10391 * @see #getRotationX() 10392 * @see #getPivotX() 10393 * @see #getPivotY() 10394 * @see #setRotation(float) 10395 * @see #setRotationY(float) 10396 * @see #setCameraDistance(float) 10397 * 10398 * @attr ref android.R.styleable#View_rotationX 10399 */ 10400 public void setRotationX(float rotationX) { 10401 if (rotationX != getRotationX()) { 10402 invalidateViewProperty(true, false); 10403 mRenderNode.setRotationX(rotationX); 10404 invalidateViewProperty(false, true); 10405 10406 invalidateParentIfNeededAndWasQuickRejected(); 10407 notifySubtreeAccessibilityStateChangedIfNeeded(); 10408 } 10409 } 10410 10411 /** 10412 * The amount that the view is scaled in x around the pivot point, as a proportion of 10413 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 10414 * 10415 * <p>By default, this is 1.0f. 10416 * 10417 * @see #getPivotX() 10418 * @see #getPivotY() 10419 * @return The scaling factor. 10420 */ 10421 @ViewDebug.ExportedProperty(category = "drawing") 10422 public float getScaleX() { 10423 return mRenderNode.getScaleX(); 10424 } 10425 10426 /** 10427 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 10428 * the view's unscaled width. A value of 1 means that no scaling is applied. 10429 * 10430 * @param scaleX The scaling factor. 10431 * @see #getPivotX() 10432 * @see #getPivotY() 10433 * 10434 * @attr ref android.R.styleable#View_scaleX 10435 */ 10436 public void setScaleX(float scaleX) { 10437 if (scaleX != getScaleX()) { 10438 invalidateViewProperty(true, false); 10439 mRenderNode.setScaleX(scaleX); 10440 invalidateViewProperty(false, true); 10441 10442 invalidateParentIfNeededAndWasQuickRejected(); 10443 notifySubtreeAccessibilityStateChangedIfNeeded(); 10444 } 10445 } 10446 10447 /** 10448 * The amount that the view is scaled in y around the pivot point, as a proportion of 10449 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 10450 * 10451 * <p>By default, this is 1.0f. 10452 * 10453 * @see #getPivotX() 10454 * @see #getPivotY() 10455 * @return The scaling factor. 10456 */ 10457 @ViewDebug.ExportedProperty(category = "drawing") 10458 public float getScaleY() { 10459 return mRenderNode.getScaleY(); 10460 } 10461 10462 /** 10463 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 10464 * the view's unscaled width. A value of 1 means that no scaling is applied. 10465 * 10466 * @param scaleY The scaling factor. 10467 * @see #getPivotX() 10468 * @see #getPivotY() 10469 * 10470 * @attr ref android.R.styleable#View_scaleY 10471 */ 10472 public void setScaleY(float scaleY) { 10473 if (scaleY != getScaleY()) { 10474 invalidateViewProperty(true, false); 10475 mRenderNode.setScaleY(scaleY); 10476 invalidateViewProperty(false, true); 10477 10478 invalidateParentIfNeededAndWasQuickRejected(); 10479 notifySubtreeAccessibilityStateChangedIfNeeded(); 10480 } 10481 } 10482 10483 /** 10484 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10485 * and {@link #setScaleX(float) scaled}. 10486 * 10487 * @see #getRotation() 10488 * @see #getScaleX() 10489 * @see #getScaleY() 10490 * @see #getPivotY() 10491 * @return The x location of the pivot point. 10492 * 10493 * @attr ref android.R.styleable#View_transformPivotX 10494 */ 10495 @ViewDebug.ExportedProperty(category = "drawing") 10496 public float getPivotX() { 10497 return mRenderNode.getPivotX(); 10498 } 10499 10500 /** 10501 * Sets the x location of the point around which the view is 10502 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10503 * By default, the pivot point is centered on the object. 10504 * Setting this property disables this behavior and causes the view to use only the 10505 * explicitly set pivotX and pivotY values. 10506 * 10507 * @param pivotX The x location of the pivot point. 10508 * @see #getRotation() 10509 * @see #getScaleX() 10510 * @see #getScaleY() 10511 * @see #getPivotY() 10512 * 10513 * @attr ref android.R.styleable#View_transformPivotX 10514 */ 10515 public void setPivotX(float pivotX) { 10516 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10517 invalidateViewProperty(true, false); 10518 mRenderNode.setPivotX(pivotX); 10519 invalidateViewProperty(false, true); 10520 10521 invalidateParentIfNeededAndWasQuickRejected(); 10522 } 10523 } 10524 10525 /** 10526 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10527 * and {@link #setScaleY(float) scaled}. 10528 * 10529 * @see #getRotation() 10530 * @see #getScaleX() 10531 * @see #getScaleY() 10532 * @see #getPivotY() 10533 * @return The y location of the pivot point. 10534 * 10535 * @attr ref android.R.styleable#View_transformPivotY 10536 */ 10537 @ViewDebug.ExportedProperty(category = "drawing") 10538 public float getPivotY() { 10539 return mRenderNode.getPivotY(); 10540 } 10541 10542 /** 10543 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10544 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10545 * Setting this property disables this behavior and causes the view to use only the 10546 * explicitly set pivotX and pivotY values. 10547 * 10548 * @param pivotY The y location of the pivot point. 10549 * @see #getRotation() 10550 * @see #getScaleX() 10551 * @see #getScaleY() 10552 * @see #getPivotY() 10553 * 10554 * @attr ref android.R.styleable#View_transformPivotY 10555 */ 10556 public void setPivotY(float pivotY) { 10557 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10558 invalidateViewProperty(true, false); 10559 mRenderNode.setPivotY(pivotY); 10560 invalidateViewProperty(false, true); 10561 10562 invalidateParentIfNeededAndWasQuickRejected(); 10563 } 10564 } 10565 10566 /** 10567 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10568 * completely transparent and 1 means the view is completely opaque. 10569 * 10570 * <p>By default this is 1.0f. 10571 * @return The opacity of the view. 10572 */ 10573 @ViewDebug.ExportedProperty(category = "drawing") 10574 public float getAlpha() { 10575 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10576 } 10577 10578 /** 10579 * Returns whether this View has content which overlaps. 10580 * 10581 * <p>This function, intended to be overridden by specific View types, is an optimization when 10582 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10583 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10584 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10585 * directly. An example of overlapping rendering is a TextView with a background image, such as 10586 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10587 * ImageView with only the foreground image. The default implementation returns true; subclasses 10588 * should override if they have cases which can be optimized.</p> 10589 * 10590 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10591 * necessitates that a View return true if it uses the methods internally without passing the 10592 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10593 * 10594 * @return true if the content in this view might overlap, false otherwise. 10595 */ 10596 @ViewDebug.ExportedProperty(category = "drawing") 10597 public boolean hasOverlappingRendering() { 10598 return true; 10599 } 10600 10601 /** 10602 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10603 * completely transparent and 1 means the view is completely opaque.</p> 10604 * 10605 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10606 * performance implications, especially for large views. It is best to use the alpha property 10607 * sparingly and transiently, as in the case of fading animations.</p> 10608 * 10609 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10610 * strongly recommended for performance reasons to either override 10611 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10612 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10613 * 10614 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10615 * responsible for applying the opacity itself.</p> 10616 * 10617 * <p>Note that if the view is backed by a 10618 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10619 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10620 * 1.0 will supercede the alpha of the layer paint.</p> 10621 * 10622 * @param alpha The opacity of the view. 10623 * 10624 * @see #hasOverlappingRendering() 10625 * @see #setLayerType(int, android.graphics.Paint) 10626 * 10627 * @attr ref android.R.styleable#View_alpha 10628 */ 10629 public void setAlpha(float alpha) { 10630 ensureTransformationInfo(); 10631 if (mTransformationInfo.mAlpha != alpha) { 10632 mTransformationInfo.mAlpha = alpha; 10633 if (onSetAlpha((int) (alpha * 255))) { 10634 mPrivateFlags |= PFLAG_ALPHA_SET; 10635 // subclass is handling alpha - don't optimize rendering cache invalidation 10636 invalidateParentCaches(); 10637 invalidate(true); 10638 } else { 10639 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10640 invalidateViewProperty(true, false); 10641 mRenderNode.setAlpha(getFinalAlpha()); 10642 notifyViewAccessibilityStateChangedIfNeeded( 10643 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10644 } 10645 } 10646 } 10647 10648 /** 10649 * Faster version of setAlpha() which performs the same steps except there are 10650 * no calls to invalidate(). The caller of this function should perform proper invalidation 10651 * on the parent and this object. The return value indicates whether the subclass handles 10652 * alpha (the return value for onSetAlpha()). 10653 * 10654 * @param alpha The new value for the alpha property 10655 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10656 * the new value for the alpha property is different from the old value 10657 */ 10658 boolean setAlphaNoInvalidation(float alpha) { 10659 ensureTransformationInfo(); 10660 if (mTransformationInfo.mAlpha != alpha) { 10661 mTransformationInfo.mAlpha = alpha; 10662 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10663 if (subclassHandlesAlpha) { 10664 mPrivateFlags |= PFLAG_ALPHA_SET; 10665 return true; 10666 } else { 10667 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10668 mRenderNode.setAlpha(getFinalAlpha()); 10669 } 10670 } 10671 return false; 10672 } 10673 10674 /** 10675 * This property is hidden and intended only for use by the Fade transition, which 10676 * animates it to produce a visual translucency that does not side-effect (or get 10677 * affected by) the real alpha property. This value is composited with the other 10678 * alpha value (and the AlphaAnimation value, when that is present) to produce 10679 * a final visual translucency result, which is what is passed into the DisplayList. 10680 * 10681 * @hide 10682 */ 10683 public void setTransitionAlpha(float alpha) { 10684 ensureTransformationInfo(); 10685 if (mTransformationInfo.mTransitionAlpha != alpha) { 10686 mTransformationInfo.mTransitionAlpha = alpha; 10687 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10688 invalidateViewProperty(true, false); 10689 mRenderNode.setAlpha(getFinalAlpha()); 10690 } 10691 } 10692 10693 /** 10694 * Calculates the visual alpha of this view, which is a combination of the actual 10695 * alpha value and the transitionAlpha value (if set). 10696 */ 10697 private float getFinalAlpha() { 10698 if (mTransformationInfo != null) { 10699 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10700 } 10701 return 1; 10702 } 10703 10704 /** 10705 * This property is hidden and intended only for use by the Fade transition, which 10706 * animates it to produce a visual translucency that does not side-effect (or get 10707 * affected by) the real alpha property. This value is composited with the other 10708 * alpha value (and the AlphaAnimation value, when that is present) to produce 10709 * a final visual translucency result, which is what is passed into the DisplayList. 10710 * 10711 * @hide 10712 */ 10713 @ViewDebug.ExportedProperty(category = "drawing") 10714 public float getTransitionAlpha() { 10715 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10716 } 10717 10718 /** 10719 * Top position of this view relative to its parent. 10720 * 10721 * @return The top of this view, in pixels. 10722 */ 10723 @ViewDebug.CapturedViewProperty 10724 public final int getTop() { 10725 return mTop; 10726 } 10727 10728 /** 10729 * Sets the top position of this view relative to its parent. This method is meant to be called 10730 * by the layout system and should not generally be called otherwise, because the property 10731 * may be changed at any time by the layout. 10732 * 10733 * @param top The top of this view, in pixels. 10734 */ 10735 public final void setTop(int top) { 10736 if (top != mTop) { 10737 final boolean matrixIsIdentity = hasIdentityMatrix(); 10738 if (matrixIsIdentity) { 10739 if (mAttachInfo != null) { 10740 int minTop; 10741 int yLoc; 10742 if (top < mTop) { 10743 minTop = top; 10744 yLoc = top - mTop; 10745 } else { 10746 minTop = mTop; 10747 yLoc = 0; 10748 } 10749 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10750 } 10751 } else { 10752 // Double-invalidation is necessary to capture view's old and new areas 10753 invalidate(true); 10754 } 10755 10756 int width = mRight - mLeft; 10757 int oldHeight = mBottom - mTop; 10758 10759 mTop = top; 10760 mRenderNode.setTop(mTop); 10761 10762 sizeChange(width, mBottom - mTop, width, oldHeight); 10763 10764 if (!matrixIsIdentity) { 10765 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10766 invalidate(true); 10767 } 10768 mBackgroundSizeChanged = true; 10769 invalidateParentIfNeeded(); 10770 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10771 // View was rejected last time it was drawn by its parent; this may have changed 10772 invalidateParentIfNeeded(); 10773 } 10774 } 10775 } 10776 10777 /** 10778 * Bottom position of this view relative to its parent. 10779 * 10780 * @return The bottom of this view, in pixels. 10781 */ 10782 @ViewDebug.CapturedViewProperty 10783 public final int getBottom() { 10784 return mBottom; 10785 } 10786 10787 /** 10788 * True if this view has changed since the last time being drawn. 10789 * 10790 * @return The dirty state of this view. 10791 */ 10792 public boolean isDirty() { 10793 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10794 } 10795 10796 /** 10797 * Sets the bottom position of this view relative to its parent. This method is meant to be 10798 * called by the layout system and should not generally be called otherwise, because the 10799 * property may be changed at any time by the layout. 10800 * 10801 * @param bottom The bottom of this view, in pixels. 10802 */ 10803 public final void setBottom(int bottom) { 10804 if (bottom != mBottom) { 10805 final boolean matrixIsIdentity = hasIdentityMatrix(); 10806 if (matrixIsIdentity) { 10807 if (mAttachInfo != null) { 10808 int maxBottom; 10809 if (bottom < mBottom) { 10810 maxBottom = mBottom; 10811 } else { 10812 maxBottom = bottom; 10813 } 10814 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10815 } 10816 } else { 10817 // Double-invalidation is necessary to capture view's old and new areas 10818 invalidate(true); 10819 } 10820 10821 int width = mRight - mLeft; 10822 int oldHeight = mBottom - mTop; 10823 10824 mBottom = bottom; 10825 mRenderNode.setBottom(mBottom); 10826 10827 sizeChange(width, mBottom - mTop, width, oldHeight); 10828 10829 if (!matrixIsIdentity) { 10830 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10831 invalidate(true); 10832 } 10833 mBackgroundSizeChanged = true; 10834 invalidateParentIfNeeded(); 10835 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10836 // View was rejected last time it was drawn by its parent; this may have changed 10837 invalidateParentIfNeeded(); 10838 } 10839 } 10840 } 10841 10842 /** 10843 * Left position of this view relative to its parent. 10844 * 10845 * @return The left edge of this view, in pixels. 10846 */ 10847 @ViewDebug.CapturedViewProperty 10848 public final int getLeft() { 10849 return mLeft; 10850 } 10851 10852 /** 10853 * Sets the left position of this view relative to its parent. This method is meant to be called 10854 * by the layout system and should not generally be called otherwise, because the property 10855 * may be changed at any time by the layout. 10856 * 10857 * @param left The left of this view, in pixels. 10858 */ 10859 public final void setLeft(int left) { 10860 if (left != mLeft) { 10861 final boolean matrixIsIdentity = hasIdentityMatrix(); 10862 if (matrixIsIdentity) { 10863 if (mAttachInfo != null) { 10864 int minLeft; 10865 int xLoc; 10866 if (left < mLeft) { 10867 minLeft = left; 10868 xLoc = left - mLeft; 10869 } else { 10870 minLeft = mLeft; 10871 xLoc = 0; 10872 } 10873 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10874 } 10875 } else { 10876 // Double-invalidation is necessary to capture view's old and new areas 10877 invalidate(true); 10878 } 10879 10880 int oldWidth = mRight - mLeft; 10881 int height = mBottom - mTop; 10882 10883 mLeft = left; 10884 mRenderNode.setLeft(left); 10885 10886 sizeChange(mRight - mLeft, height, oldWidth, height); 10887 10888 if (!matrixIsIdentity) { 10889 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10890 invalidate(true); 10891 } 10892 mBackgroundSizeChanged = true; 10893 invalidateParentIfNeeded(); 10894 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10895 // View was rejected last time it was drawn by its parent; this may have changed 10896 invalidateParentIfNeeded(); 10897 } 10898 } 10899 } 10900 10901 /** 10902 * Right position of this view relative to its parent. 10903 * 10904 * @return The right edge of this view, in pixels. 10905 */ 10906 @ViewDebug.CapturedViewProperty 10907 public final int getRight() { 10908 return mRight; 10909 } 10910 10911 /** 10912 * Sets the right position of this view relative to its parent. This method is meant to be called 10913 * by the layout system and should not generally be called otherwise, because the property 10914 * may be changed at any time by the layout. 10915 * 10916 * @param right The right of this view, in pixels. 10917 */ 10918 public final void setRight(int right) { 10919 if (right != mRight) { 10920 final boolean matrixIsIdentity = hasIdentityMatrix(); 10921 if (matrixIsIdentity) { 10922 if (mAttachInfo != null) { 10923 int maxRight; 10924 if (right < mRight) { 10925 maxRight = mRight; 10926 } else { 10927 maxRight = right; 10928 } 10929 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10930 } 10931 } else { 10932 // Double-invalidation is necessary to capture view's old and new areas 10933 invalidate(true); 10934 } 10935 10936 int oldWidth = mRight - mLeft; 10937 int height = mBottom - mTop; 10938 10939 mRight = right; 10940 mRenderNode.setRight(mRight); 10941 10942 sizeChange(mRight - mLeft, height, oldWidth, height); 10943 10944 if (!matrixIsIdentity) { 10945 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10946 invalidate(true); 10947 } 10948 mBackgroundSizeChanged = true; 10949 invalidateParentIfNeeded(); 10950 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10951 // View was rejected last time it was drawn by its parent; this may have changed 10952 invalidateParentIfNeeded(); 10953 } 10954 } 10955 } 10956 10957 /** 10958 * The visual x position of this view, in pixels. This is equivalent to the 10959 * {@link #setTranslationX(float) translationX} property plus the current 10960 * {@link #getLeft() left} property. 10961 * 10962 * @return The visual x position of this view, in pixels. 10963 */ 10964 @ViewDebug.ExportedProperty(category = "drawing") 10965 public float getX() { 10966 return mLeft + getTranslationX(); 10967 } 10968 10969 /** 10970 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10971 * {@link #setTranslationX(float) translationX} property to be the difference between 10972 * the x value passed in and the current {@link #getLeft() left} property. 10973 * 10974 * @param x The visual x position of this view, in pixels. 10975 */ 10976 public void setX(float x) { 10977 setTranslationX(x - mLeft); 10978 } 10979 10980 /** 10981 * The visual y position of this view, in pixels. This is equivalent to the 10982 * {@link #setTranslationY(float) translationY} property plus the current 10983 * {@link #getTop() top} property. 10984 * 10985 * @return The visual y position of this view, in pixels. 10986 */ 10987 @ViewDebug.ExportedProperty(category = "drawing") 10988 public float getY() { 10989 return mTop + getTranslationY(); 10990 } 10991 10992 /** 10993 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10994 * {@link #setTranslationY(float) translationY} property to be the difference between 10995 * the y value passed in and the current {@link #getTop() top} property. 10996 * 10997 * @param y The visual y position of this view, in pixels. 10998 */ 10999 public void setY(float y) { 11000 setTranslationY(y - mTop); 11001 } 11002 11003 /** 11004 * The visual z position of this view, in pixels. This is equivalent to the 11005 * {@link #setTranslationZ(float) translationZ} property plus the current 11006 * {@link #getElevation() elevation} property. 11007 * 11008 * @return The visual z position of this view, in pixels. 11009 */ 11010 @ViewDebug.ExportedProperty(category = "drawing") 11011 public float getZ() { 11012 return getElevation() + getTranslationZ(); 11013 } 11014 11015 /** 11016 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 11017 * {@link #setTranslationZ(float) translationZ} property to be the difference between 11018 * the x value passed in and the current {@link #getElevation() elevation} property. 11019 * 11020 * @param z The visual z position of this view, in pixels. 11021 */ 11022 public void setZ(float z) { 11023 setTranslationZ(z - getElevation()); 11024 } 11025 11026 /** 11027 * The base elevation of this view relative to its parent, in pixels. 11028 * 11029 * @return The base depth position of the view, in pixels. 11030 */ 11031 @ViewDebug.ExportedProperty(category = "drawing") 11032 public float getElevation() { 11033 return mRenderNode.getElevation(); 11034 } 11035 11036 /** 11037 * Sets the base elevation of this view, in pixels. 11038 * 11039 * @attr ref android.R.styleable#View_elevation 11040 */ 11041 public void setElevation(float elevation) { 11042 if (elevation != getElevation()) { 11043 invalidateViewProperty(true, false); 11044 mRenderNode.setElevation(elevation); 11045 invalidateViewProperty(false, true); 11046 11047 invalidateParentIfNeededAndWasQuickRejected(); 11048 } 11049 } 11050 11051 /** 11052 * The horizontal location of this view relative to its {@link #getLeft() left} position. 11053 * This position is post-layout, in addition to wherever the object's 11054 * layout placed it. 11055 * 11056 * @return The horizontal position of this view relative to its left position, in pixels. 11057 */ 11058 @ViewDebug.ExportedProperty(category = "drawing") 11059 public float getTranslationX() { 11060 return mRenderNode.getTranslationX(); 11061 } 11062 11063 /** 11064 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 11065 * This effectively positions the object post-layout, in addition to wherever the object's 11066 * layout placed it. 11067 * 11068 * @param translationX The horizontal position of this view relative to its left position, 11069 * in pixels. 11070 * 11071 * @attr ref android.R.styleable#View_translationX 11072 */ 11073 public void setTranslationX(float translationX) { 11074 if (translationX != getTranslationX()) { 11075 invalidateViewProperty(true, false); 11076 mRenderNode.setTranslationX(translationX); 11077 invalidateViewProperty(false, true); 11078 11079 invalidateParentIfNeededAndWasQuickRejected(); 11080 notifySubtreeAccessibilityStateChangedIfNeeded(); 11081 } 11082 } 11083 11084 /** 11085 * The vertical location of this view relative to its {@link #getTop() top} position. 11086 * This position is post-layout, in addition to wherever the object's 11087 * layout placed it. 11088 * 11089 * @return The vertical position of this view relative to its top position, 11090 * in pixels. 11091 */ 11092 @ViewDebug.ExportedProperty(category = "drawing") 11093 public float getTranslationY() { 11094 return mRenderNode.getTranslationY(); 11095 } 11096 11097 /** 11098 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 11099 * This effectively positions the object post-layout, in addition to wherever the object's 11100 * layout placed it. 11101 * 11102 * @param translationY The vertical position of this view relative to its top position, 11103 * in pixels. 11104 * 11105 * @attr ref android.R.styleable#View_translationY 11106 */ 11107 public void setTranslationY(float translationY) { 11108 if (translationY != getTranslationY()) { 11109 invalidateViewProperty(true, false); 11110 mRenderNode.setTranslationY(translationY); 11111 invalidateViewProperty(false, true); 11112 11113 invalidateParentIfNeededAndWasQuickRejected(); 11114 } 11115 } 11116 11117 /** 11118 * The depth location of this view relative to its {@link #getElevation() elevation}. 11119 * 11120 * @return The depth of this view relative to its elevation. 11121 */ 11122 @ViewDebug.ExportedProperty(category = "drawing") 11123 public float getTranslationZ() { 11124 return mRenderNode.getTranslationZ(); 11125 } 11126 11127 /** 11128 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 11129 * 11130 * @attr ref android.R.styleable#View_translationZ 11131 */ 11132 public void setTranslationZ(float translationZ) { 11133 if (translationZ != getTranslationZ()) { 11134 invalidateViewProperty(true, false); 11135 mRenderNode.setTranslationZ(translationZ); 11136 invalidateViewProperty(false, true); 11137 11138 invalidateParentIfNeededAndWasQuickRejected(); 11139 } 11140 } 11141 11142 /** @hide */ 11143 public void setAnimationMatrix(Matrix matrix) { 11144 invalidateViewProperty(true, false); 11145 mRenderNode.setAnimationMatrix(matrix); 11146 invalidateViewProperty(false, true); 11147 11148 invalidateParentIfNeededAndWasQuickRejected(); 11149 } 11150 11151 /** 11152 * Returns the current StateListAnimator if exists. 11153 * 11154 * @return StateListAnimator or null if it does not exists 11155 * @see #setStateListAnimator(android.animation.StateListAnimator) 11156 */ 11157 public StateListAnimator getStateListAnimator() { 11158 return mStateListAnimator; 11159 } 11160 11161 /** 11162 * Attaches the provided StateListAnimator to this View. 11163 * <p> 11164 * Any previously attached StateListAnimator will be detached. 11165 * 11166 * @param stateListAnimator The StateListAnimator to update the view 11167 * @see {@link android.animation.StateListAnimator} 11168 */ 11169 public void setStateListAnimator(StateListAnimator stateListAnimator) { 11170 if (mStateListAnimator == stateListAnimator) { 11171 return; 11172 } 11173 if (mStateListAnimator != null) { 11174 mStateListAnimator.setTarget(null); 11175 } 11176 mStateListAnimator = stateListAnimator; 11177 if (stateListAnimator != null) { 11178 stateListAnimator.setTarget(this); 11179 if (isAttachedToWindow()) { 11180 stateListAnimator.setState(getDrawableState()); 11181 } 11182 } 11183 } 11184 11185 /** 11186 * Returns whether the Outline should be used to clip the contents of the View. 11187 * <p> 11188 * Note that this flag will only be respected if the View's Outline returns true from 11189 * {@link Outline#canClip()}. 11190 * 11191 * @see #setOutlineProvider(ViewOutlineProvider) 11192 * @see #setClipToOutline(boolean) 11193 */ 11194 public final boolean getClipToOutline() { 11195 return mRenderNode.getClipToOutline(); 11196 } 11197 11198 /** 11199 * Sets whether the View's Outline should be used to clip the contents of the View. 11200 * <p> 11201 * Only a single non-rectangular clip can be applied on a View at any time. 11202 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 11203 * circular reveal} animation take priority over Outline clipping, and 11204 * child Outline clipping takes priority over Outline clipping done by a 11205 * parent. 11206 * <p> 11207 * Note that this flag will only be respected if the View's Outline returns true from 11208 * {@link Outline#canClip()}. 11209 * 11210 * @see #setOutlineProvider(ViewOutlineProvider) 11211 * @see #getClipToOutline() 11212 */ 11213 public void setClipToOutline(boolean clipToOutline) { 11214 damageInParent(); 11215 if (getClipToOutline() != clipToOutline) { 11216 mRenderNode.setClipToOutline(clipToOutline); 11217 } 11218 } 11219 11220 // correspond to the enum values of View_outlineProvider 11221 private static final int PROVIDER_BACKGROUND = 0; 11222 private static final int PROVIDER_NONE = 1; 11223 private static final int PROVIDER_BOUNDS = 2; 11224 private static final int PROVIDER_PADDED_BOUNDS = 3; 11225 private void setOutlineProviderFromAttribute(int providerInt) { 11226 switch (providerInt) { 11227 case PROVIDER_BACKGROUND: 11228 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 11229 break; 11230 case PROVIDER_NONE: 11231 setOutlineProvider(null); 11232 break; 11233 case PROVIDER_BOUNDS: 11234 setOutlineProvider(ViewOutlineProvider.BOUNDS); 11235 break; 11236 case PROVIDER_PADDED_BOUNDS: 11237 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 11238 break; 11239 } 11240 } 11241 11242 /** 11243 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 11244 * the shape of the shadow it casts, and enables outline clipping. 11245 * <p> 11246 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 11247 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 11248 * outline provider with this method allows this behavior to be overridden. 11249 * <p> 11250 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 11251 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 11252 * <p> 11253 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 11254 * 11255 * @see #setClipToOutline(boolean) 11256 * @see #getClipToOutline() 11257 * @see #getOutlineProvider() 11258 */ 11259 public void setOutlineProvider(ViewOutlineProvider provider) { 11260 mOutlineProvider = provider; 11261 invalidateOutline(); 11262 } 11263 11264 /** 11265 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 11266 * that defines the shape of the shadow it casts, and enables outline clipping. 11267 * 11268 * @see #setOutlineProvider(ViewOutlineProvider) 11269 */ 11270 public ViewOutlineProvider getOutlineProvider() { 11271 return mOutlineProvider; 11272 } 11273 11274 /** 11275 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 11276 * 11277 * @see #setOutlineProvider(ViewOutlineProvider) 11278 */ 11279 public void invalidateOutline() { 11280 mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID; 11281 11282 notifySubtreeAccessibilityStateChangedIfNeeded(); 11283 invalidateViewProperty(false, false); 11284 } 11285 11286 /** 11287 * Internal version of {@link #invalidateOutline()} which invalidates the 11288 * outline without invalidating the view itself. This is intended to be called from 11289 * within methods in the View class itself which are the result of the view being 11290 * invalidated already. For example, when we are drawing the background of a View, 11291 * we invalidate the outline in case it changed in the meantime, but we do not 11292 * need to invalidate the view because we're already drawing the background as part 11293 * of drawing the view in response to an earlier invalidation of the view. 11294 */ 11295 private void rebuildOutline() { 11296 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 11297 if (mAttachInfo == null) return; 11298 11299 if (mOutlineProvider == null) { 11300 // no provider, remove outline 11301 mRenderNode.setOutline(null); 11302 } else { 11303 final Outline outline = mAttachInfo.mTmpOutline; 11304 outline.setEmpty(); 11305 outline.setAlpha(1.0f); 11306 11307 mOutlineProvider.getOutline(this, outline); 11308 mRenderNode.setOutline(outline); 11309 } 11310 } 11311 11312 /** 11313 * HierarchyViewer only 11314 * 11315 * @hide 11316 */ 11317 @ViewDebug.ExportedProperty(category = "drawing") 11318 public boolean hasShadow() { 11319 return mRenderNode.hasShadow(); 11320 } 11321 11322 11323 /** @hide */ 11324 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 11325 mRenderNode.setRevealClip(shouldClip, x, y, radius); 11326 invalidateViewProperty(false, false); 11327 } 11328 11329 /** 11330 * Hit rectangle in parent's coordinates 11331 * 11332 * @param outRect The hit rectangle of the view. 11333 */ 11334 public void getHitRect(Rect outRect) { 11335 if (hasIdentityMatrix() || mAttachInfo == null) { 11336 outRect.set(mLeft, mTop, mRight, mBottom); 11337 } else { 11338 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 11339 tmpRect.set(0, 0, getWidth(), getHeight()); 11340 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 11341 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 11342 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 11343 } 11344 } 11345 11346 /** 11347 * Determines whether the given point, in local coordinates is inside the view. 11348 */ 11349 /*package*/ final boolean pointInView(float localX, float localY) { 11350 return localX >= 0 && localX < (mRight - mLeft) 11351 && localY >= 0 && localY < (mBottom - mTop); 11352 } 11353 11354 /** 11355 * Utility method to determine whether the given point, in local coordinates, 11356 * is inside the view, where the area of the view is expanded by the slop factor. 11357 * This method is called while processing touch-move events to determine if the event 11358 * is still within the view. 11359 * 11360 * @hide 11361 */ 11362 public boolean pointInView(float localX, float localY, float slop) { 11363 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 11364 localY < ((mBottom - mTop) + slop); 11365 } 11366 11367 /** 11368 * When a view has focus and the user navigates away from it, the next view is searched for 11369 * starting from the rectangle filled in by this method. 11370 * 11371 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 11372 * of the view. However, if your view maintains some idea of internal selection, 11373 * such as a cursor, or a selected row or column, you should override this method and 11374 * fill in a more specific rectangle. 11375 * 11376 * @param r The rectangle to fill in, in this view's coordinates. 11377 */ 11378 public void getFocusedRect(Rect r) { 11379 getDrawingRect(r); 11380 } 11381 11382 /** 11383 * If some part of this view is not clipped by any of its parents, then 11384 * return that area in r in global (root) coordinates. To convert r to local 11385 * coordinates (without taking possible View rotations into account), offset 11386 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 11387 * If the view is completely clipped or translated out, return false. 11388 * 11389 * @param r If true is returned, r holds the global coordinates of the 11390 * visible portion of this view. 11391 * @param globalOffset If true is returned, globalOffset holds the dx,dy 11392 * between this view and its root. globalOffet may be null. 11393 * @return true if r is non-empty (i.e. part of the view is visible at the 11394 * root level. 11395 */ 11396 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 11397 int width = mRight - mLeft; 11398 int height = mBottom - mTop; 11399 if (width > 0 && height > 0) { 11400 r.set(0, 0, width, height); 11401 if (globalOffset != null) { 11402 globalOffset.set(-mScrollX, -mScrollY); 11403 } 11404 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 11405 } 11406 return false; 11407 } 11408 11409 public final boolean getGlobalVisibleRect(Rect r) { 11410 return getGlobalVisibleRect(r, null); 11411 } 11412 11413 public final boolean getLocalVisibleRect(Rect r) { 11414 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 11415 if (getGlobalVisibleRect(r, offset)) { 11416 r.offset(-offset.x, -offset.y); // make r local 11417 return true; 11418 } 11419 return false; 11420 } 11421 11422 /** 11423 * Offset this view's vertical location by the specified number of pixels. 11424 * 11425 * @param offset the number of pixels to offset the view by 11426 */ 11427 public void offsetTopAndBottom(int offset) { 11428 if (offset != 0) { 11429 final boolean matrixIsIdentity = hasIdentityMatrix(); 11430 if (matrixIsIdentity) { 11431 if (isHardwareAccelerated()) { 11432 invalidateViewProperty(false, false); 11433 } else { 11434 final ViewParent p = mParent; 11435 if (p != null && mAttachInfo != null) { 11436 final Rect r = mAttachInfo.mTmpInvalRect; 11437 int minTop; 11438 int maxBottom; 11439 int yLoc; 11440 if (offset < 0) { 11441 minTop = mTop + offset; 11442 maxBottom = mBottom; 11443 yLoc = offset; 11444 } else { 11445 minTop = mTop; 11446 maxBottom = mBottom + offset; 11447 yLoc = 0; 11448 } 11449 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 11450 p.invalidateChild(this, r); 11451 } 11452 } 11453 } else { 11454 invalidateViewProperty(false, false); 11455 } 11456 11457 mTop += offset; 11458 mBottom += offset; 11459 mRenderNode.offsetTopAndBottom(offset); 11460 if (isHardwareAccelerated()) { 11461 invalidateViewProperty(false, false); 11462 } else { 11463 if (!matrixIsIdentity) { 11464 invalidateViewProperty(false, true); 11465 } 11466 invalidateParentIfNeeded(); 11467 } 11468 notifySubtreeAccessibilityStateChangedIfNeeded(); 11469 } 11470 } 11471 11472 /** 11473 * Offset this view's horizontal location by the specified amount of pixels. 11474 * 11475 * @param offset the number of pixels to offset the view by 11476 */ 11477 public void offsetLeftAndRight(int offset) { 11478 if (offset != 0) { 11479 final boolean matrixIsIdentity = hasIdentityMatrix(); 11480 if (matrixIsIdentity) { 11481 if (isHardwareAccelerated()) { 11482 invalidateViewProperty(false, false); 11483 } else { 11484 final ViewParent p = mParent; 11485 if (p != null && mAttachInfo != null) { 11486 final Rect r = mAttachInfo.mTmpInvalRect; 11487 int minLeft; 11488 int maxRight; 11489 if (offset < 0) { 11490 minLeft = mLeft + offset; 11491 maxRight = mRight; 11492 } else { 11493 minLeft = mLeft; 11494 maxRight = mRight + offset; 11495 } 11496 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 11497 p.invalidateChild(this, r); 11498 } 11499 } 11500 } else { 11501 invalidateViewProperty(false, false); 11502 } 11503 11504 mLeft += offset; 11505 mRight += offset; 11506 mRenderNode.offsetLeftAndRight(offset); 11507 if (isHardwareAccelerated()) { 11508 invalidateViewProperty(false, false); 11509 } else { 11510 if (!matrixIsIdentity) { 11511 invalidateViewProperty(false, true); 11512 } 11513 invalidateParentIfNeeded(); 11514 } 11515 notifySubtreeAccessibilityStateChangedIfNeeded(); 11516 } 11517 } 11518 11519 /** 11520 * Get the LayoutParams associated with this view. All views should have 11521 * layout parameters. These supply parameters to the <i>parent</i> of this 11522 * view specifying how it should be arranged. There are many subclasses of 11523 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11524 * of ViewGroup that are responsible for arranging their children. 11525 * 11526 * This method may return null if this View is not attached to a parent 11527 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11528 * was not invoked successfully. When a View is attached to a parent 11529 * ViewGroup, this method must not return null. 11530 * 11531 * @return The LayoutParams associated with this view, or null if no 11532 * parameters have been set yet 11533 */ 11534 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11535 public ViewGroup.LayoutParams getLayoutParams() { 11536 return mLayoutParams; 11537 } 11538 11539 /** 11540 * Set the layout parameters associated with this view. These supply 11541 * parameters to the <i>parent</i> of this view specifying how it should be 11542 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11543 * correspond to the different subclasses of ViewGroup that are responsible 11544 * for arranging their children. 11545 * 11546 * @param params The layout parameters for this view, cannot be null 11547 */ 11548 public void setLayoutParams(ViewGroup.LayoutParams params) { 11549 if (params == null) { 11550 throw new NullPointerException("Layout parameters cannot be null"); 11551 } 11552 mLayoutParams = params; 11553 resolveLayoutParams(); 11554 if (mParent instanceof ViewGroup) { 11555 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11556 } 11557 requestLayout(); 11558 } 11559 11560 /** 11561 * Resolve the layout parameters depending on the resolved layout direction 11562 * 11563 * @hide 11564 */ 11565 public void resolveLayoutParams() { 11566 if (mLayoutParams != null) { 11567 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11568 } 11569 } 11570 11571 /** 11572 * Set the scrolled position of your view. This will cause a call to 11573 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11574 * invalidated. 11575 * @param x the x position to scroll to 11576 * @param y the y position to scroll to 11577 */ 11578 public void scrollTo(int x, int y) { 11579 if (mScrollX != x || mScrollY != y) { 11580 int oldX = mScrollX; 11581 int oldY = mScrollY; 11582 mScrollX = x; 11583 mScrollY = y; 11584 invalidateParentCaches(); 11585 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11586 if (!awakenScrollBars()) { 11587 postInvalidateOnAnimation(); 11588 } 11589 } 11590 } 11591 11592 /** 11593 * Move the scrolled position of your view. This will cause a call to 11594 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11595 * invalidated. 11596 * @param x the amount of pixels to scroll by horizontally 11597 * @param y the amount of pixels to scroll by vertically 11598 */ 11599 public void scrollBy(int x, int y) { 11600 scrollTo(mScrollX + x, mScrollY + y); 11601 } 11602 11603 /** 11604 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11605 * animation to fade the scrollbars out after a default delay. If a subclass 11606 * provides animated scrolling, the start delay should equal the duration 11607 * of the scrolling animation.</p> 11608 * 11609 * <p>The animation starts only if at least one of the scrollbars is 11610 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11611 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11612 * this method returns true, and false otherwise. If the animation is 11613 * started, this method calls {@link #invalidate()}; in that case the 11614 * caller should not call {@link #invalidate()}.</p> 11615 * 11616 * <p>This method should be invoked every time a subclass directly updates 11617 * the scroll parameters.</p> 11618 * 11619 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11620 * and {@link #scrollTo(int, int)}.</p> 11621 * 11622 * @return true if the animation is played, false otherwise 11623 * 11624 * @see #awakenScrollBars(int) 11625 * @see #scrollBy(int, int) 11626 * @see #scrollTo(int, int) 11627 * @see #isHorizontalScrollBarEnabled() 11628 * @see #isVerticalScrollBarEnabled() 11629 * @see #setHorizontalScrollBarEnabled(boolean) 11630 * @see #setVerticalScrollBarEnabled(boolean) 11631 */ 11632 protected boolean awakenScrollBars() { 11633 return mScrollCache != null && 11634 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11635 } 11636 11637 /** 11638 * Trigger the scrollbars to draw. 11639 * This method differs from awakenScrollBars() only in its default duration. 11640 * initialAwakenScrollBars() will show the scroll bars for longer than 11641 * usual to give the user more of a chance to notice them. 11642 * 11643 * @return true if the animation is played, false otherwise. 11644 */ 11645 private boolean initialAwakenScrollBars() { 11646 return mScrollCache != null && 11647 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11648 } 11649 11650 /** 11651 * <p> 11652 * Trigger the scrollbars to draw. When invoked this method starts an 11653 * animation to fade the scrollbars out after a fixed delay. If a subclass 11654 * provides animated scrolling, the start delay should equal the duration of 11655 * the scrolling animation. 11656 * </p> 11657 * 11658 * <p> 11659 * The animation starts only if at least one of the scrollbars is enabled, 11660 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11661 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11662 * this method returns true, and false otherwise. If the animation is 11663 * started, this method calls {@link #invalidate()}; in that case the caller 11664 * should not call {@link #invalidate()}. 11665 * </p> 11666 * 11667 * <p> 11668 * This method should be invoked everytime a subclass directly updates the 11669 * scroll parameters. 11670 * </p> 11671 * 11672 * @param startDelay the delay, in milliseconds, after which the animation 11673 * should start; when the delay is 0, the animation starts 11674 * immediately 11675 * @return true if the animation is played, false otherwise 11676 * 11677 * @see #scrollBy(int, int) 11678 * @see #scrollTo(int, int) 11679 * @see #isHorizontalScrollBarEnabled() 11680 * @see #isVerticalScrollBarEnabled() 11681 * @see #setHorizontalScrollBarEnabled(boolean) 11682 * @see #setVerticalScrollBarEnabled(boolean) 11683 */ 11684 protected boolean awakenScrollBars(int startDelay) { 11685 return awakenScrollBars(startDelay, true); 11686 } 11687 11688 /** 11689 * <p> 11690 * Trigger the scrollbars to draw. When invoked this method starts an 11691 * animation to fade the scrollbars out after a fixed delay. If a subclass 11692 * provides animated scrolling, the start delay should equal the duration of 11693 * the scrolling animation. 11694 * </p> 11695 * 11696 * <p> 11697 * The animation starts only if at least one of the scrollbars is enabled, 11698 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11699 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11700 * this method returns true, and false otherwise. If the animation is 11701 * started, this method calls {@link #invalidate()} if the invalidate parameter 11702 * is set to true; in that case the caller 11703 * should not call {@link #invalidate()}. 11704 * </p> 11705 * 11706 * <p> 11707 * This method should be invoked everytime a subclass directly updates the 11708 * scroll parameters. 11709 * </p> 11710 * 11711 * @param startDelay the delay, in milliseconds, after which the animation 11712 * should start; when the delay is 0, the animation starts 11713 * immediately 11714 * 11715 * @param invalidate Wheter this method should call invalidate 11716 * 11717 * @return true if the animation is played, false otherwise 11718 * 11719 * @see #scrollBy(int, int) 11720 * @see #scrollTo(int, int) 11721 * @see #isHorizontalScrollBarEnabled() 11722 * @see #isVerticalScrollBarEnabled() 11723 * @see #setHorizontalScrollBarEnabled(boolean) 11724 * @see #setVerticalScrollBarEnabled(boolean) 11725 */ 11726 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11727 final ScrollabilityCache scrollCache = mScrollCache; 11728 11729 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11730 return false; 11731 } 11732 11733 if (scrollCache.scrollBar == null) { 11734 scrollCache.scrollBar = new ScrollBarDrawable(); 11735 } 11736 11737 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11738 11739 if (invalidate) { 11740 // Invalidate to show the scrollbars 11741 postInvalidateOnAnimation(); 11742 } 11743 11744 if (scrollCache.state == ScrollabilityCache.OFF) { 11745 // FIXME: this is copied from WindowManagerService. 11746 // We should get this value from the system when it 11747 // is possible to do so. 11748 final int KEY_REPEAT_FIRST_DELAY = 750; 11749 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11750 } 11751 11752 // Tell mScrollCache when we should start fading. This may 11753 // extend the fade start time if one was already scheduled 11754 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11755 scrollCache.fadeStartTime = fadeStartTime; 11756 scrollCache.state = ScrollabilityCache.ON; 11757 11758 // Schedule our fader to run, unscheduling any old ones first 11759 if (mAttachInfo != null) { 11760 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11761 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11762 } 11763 11764 return true; 11765 } 11766 11767 return false; 11768 } 11769 11770 /** 11771 * Do not invalidate views which are not visible and which are not running an animation. They 11772 * will not get drawn and they should not set dirty flags as if they will be drawn 11773 */ 11774 private boolean skipInvalidate() { 11775 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11776 (!(mParent instanceof ViewGroup) || 11777 !((ViewGroup) mParent).isViewTransitioning(this)); 11778 } 11779 11780 /** 11781 * Mark the area defined by dirty as needing to be drawn. If the view is 11782 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11783 * point in the future. 11784 * <p> 11785 * This must be called from a UI thread. To call from a non-UI thread, call 11786 * {@link #postInvalidate()}. 11787 * <p> 11788 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11789 * {@code dirty}. 11790 * 11791 * @param dirty the rectangle representing the bounds of the dirty region 11792 */ 11793 public void invalidate(Rect dirty) { 11794 final int scrollX = mScrollX; 11795 final int scrollY = mScrollY; 11796 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11797 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11798 } 11799 11800 /** 11801 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11802 * coordinates of the dirty rect are relative to the view. If the view is 11803 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11804 * point in the future. 11805 * <p> 11806 * This must be called from a UI thread. To call from a non-UI thread, call 11807 * {@link #postInvalidate()}. 11808 * 11809 * @param l the left position of the dirty region 11810 * @param t the top position of the dirty region 11811 * @param r the right position of the dirty region 11812 * @param b the bottom position of the dirty region 11813 */ 11814 public void invalidate(int l, int t, int r, int b) { 11815 final int scrollX = mScrollX; 11816 final int scrollY = mScrollY; 11817 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11818 } 11819 11820 /** 11821 * Invalidate the whole view. If the view is visible, 11822 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11823 * the future. 11824 * <p> 11825 * This must be called from a UI thread. To call from a non-UI thread, call 11826 * {@link #postInvalidate()}. 11827 */ 11828 public void invalidate() { 11829 invalidate(true); 11830 } 11831 11832 /** 11833 * This is where the invalidate() work actually happens. A full invalidate() 11834 * causes the drawing cache to be invalidated, but this function can be 11835 * called with invalidateCache set to false to skip that invalidation step 11836 * for cases that do not need it (for example, a component that remains at 11837 * the same dimensions with the same content). 11838 * 11839 * @param invalidateCache Whether the drawing cache for this view should be 11840 * invalidated as well. This is usually true for a full 11841 * invalidate, but may be set to false if the View's contents or 11842 * dimensions have not changed. 11843 */ 11844 void invalidate(boolean invalidateCache) { 11845 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11846 } 11847 11848 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11849 boolean fullInvalidate) { 11850 if (mGhostView != null) { 11851 mGhostView.invalidate(true); 11852 return; 11853 } 11854 11855 if (skipInvalidate()) { 11856 return; 11857 } 11858 11859 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11860 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11861 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11862 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11863 if (fullInvalidate) { 11864 mLastIsOpaque = isOpaque(); 11865 mPrivateFlags &= ~PFLAG_DRAWN; 11866 } 11867 11868 mPrivateFlags |= PFLAG_DIRTY; 11869 11870 if (invalidateCache) { 11871 mPrivateFlags |= PFLAG_INVALIDATED; 11872 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11873 } 11874 11875 // Propagate the damage rectangle to the parent view. 11876 final AttachInfo ai = mAttachInfo; 11877 final ViewParent p = mParent; 11878 if (p != null && ai != null && l < r && t < b) { 11879 final Rect damage = ai.mTmpInvalRect; 11880 damage.set(l, t, r, b); 11881 p.invalidateChild(this, damage); 11882 } 11883 11884 // Damage the entire projection receiver, if necessary. 11885 if (mBackground != null && mBackground.isProjected()) { 11886 final View receiver = getProjectionReceiver(); 11887 if (receiver != null) { 11888 receiver.damageInParent(); 11889 } 11890 } 11891 11892 // Damage the entire IsolatedZVolume receiving this view's shadow. 11893 if (isHardwareAccelerated() && getZ() != 0) { 11894 damageShadowReceiver(); 11895 } 11896 } 11897 } 11898 11899 /** 11900 * @return this view's projection receiver, or {@code null} if none exists 11901 */ 11902 private View getProjectionReceiver() { 11903 ViewParent p = getParent(); 11904 while (p != null && p instanceof View) { 11905 final View v = (View) p; 11906 if (v.isProjectionReceiver()) { 11907 return v; 11908 } 11909 p = p.getParent(); 11910 } 11911 11912 return null; 11913 } 11914 11915 /** 11916 * @return whether the view is a projection receiver 11917 */ 11918 private boolean isProjectionReceiver() { 11919 return mBackground != null; 11920 } 11921 11922 /** 11923 * Damage area of the screen that can be covered by this View's shadow. 11924 * 11925 * This method will guarantee that any changes to shadows cast by a View 11926 * are damaged on the screen for future redraw. 11927 */ 11928 private void damageShadowReceiver() { 11929 final AttachInfo ai = mAttachInfo; 11930 if (ai != null) { 11931 ViewParent p = getParent(); 11932 if (p != null && p instanceof ViewGroup) { 11933 final ViewGroup vg = (ViewGroup) p; 11934 vg.damageInParent(); 11935 } 11936 } 11937 } 11938 11939 /** 11940 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11941 * set any flags or handle all of the cases handled by the default invalidation methods. 11942 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11943 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11944 * walk up the hierarchy, transforming the dirty rect as necessary. 11945 * 11946 * The method also handles normal invalidation logic if display list properties are not 11947 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11948 * backup approach, to handle these cases used in the various property-setting methods. 11949 * 11950 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11951 * are not being used in this view 11952 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11953 * list properties are not being used in this view 11954 */ 11955 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11956 if (!isHardwareAccelerated() 11957 || !mRenderNode.isValid() 11958 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11959 if (invalidateParent) { 11960 invalidateParentCaches(); 11961 } 11962 if (forceRedraw) { 11963 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11964 } 11965 invalidate(false); 11966 } else { 11967 damageInParent(); 11968 } 11969 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11970 damageShadowReceiver(); 11971 } 11972 } 11973 11974 /** 11975 * Tells the parent view to damage this view's bounds. 11976 * 11977 * @hide 11978 */ 11979 protected void damageInParent() { 11980 final AttachInfo ai = mAttachInfo; 11981 final ViewParent p = mParent; 11982 if (p != null && ai != null) { 11983 final Rect r = ai.mTmpInvalRect; 11984 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11985 if (mParent instanceof ViewGroup) { 11986 ((ViewGroup) mParent).damageChild(this, r); 11987 } else { 11988 mParent.invalidateChild(this, r); 11989 } 11990 } 11991 } 11992 11993 /** 11994 * Utility method to transform a given Rect by the current matrix of this view. 11995 */ 11996 void transformRect(final Rect rect) { 11997 if (!getMatrix().isIdentity()) { 11998 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11999 boundingRect.set(rect); 12000 getMatrix().mapRect(boundingRect); 12001 rect.set((int) Math.floor(boundingRect.left), 12002 (int) Math.floor(boundingRect.top), 12003 (int) Math.ceil(boundingRect.right), 12004 (int) Math.ceil(boundingRect.bottom)); 12005 } 12006 } 12007 12008 /** 12009 * Used to indicate that the parent of this view should clear its caches. This functionality 12010 * is used to force the parent to rebuild its display list (when hardware-accelerated), 12011 * which is necessary when various parent-managed properties of the view change, such as 12012 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 12013 * clears the parent caches and does not causes an invalidate event. 12014 * 12015 * @hide 12016 */ 12017 protected void invalidateParentCaches() { 12018 if (mParent instanceof View) { 12019 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 12020 } 12021 } 12022 12023 /** 12024 * Used to indicate that the parent of this view should be invalidated. This functionality 12025 * is used to force the parent to rebuild its display list (when hardware-accelerated), 12026 * which is necessary when various parent-managed properties of the view change, such as 12027 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 12028 * an invalidation event to the parent. 12029 * 12030 * @hide 12031 */ 12032 protected void invalidateParentIfNeeded() { 12033 if (isHardwareAccelerated() && mParent instanceof View) { 12034 ((View) mParent).invalidate(true); 12035 } 12036 } 12037 12038 /** 12039 * @hide 12040 */ 12041 protected void invalidateParentIfNeededAndWasQuickRejected() { 12042 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 12043 // View was rejected last time it was drawn by its parent; this may have changed 12044 invalidateParentIfNeeded(); 12045 } 12046 } 12047 12048 /** 12049 * Indicates whether this View is opaque. An opaque View guarantees that it will 12050 * draw all the pixels overlapping its bounds using a fully opaque color. 12051 * 12052 * Subclasses of View should override this method whenever possible to indicate 12053 * whether an instance is opaque. Opaque Views are treated in a special way by 12054 * the View hierarchy, possibly allowing it to perform optimizations during 12055 * invalidate/draw passes. 12056 * 12057 * @return True if this View is guaranteed to be fully opaque, false otherwise. 12058 */ 12059 @ViewDebug.ExportedProperty(category = "drawing") 12060 public boolean isOpaque() { 12061 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 12062 getFinalAlpha() >= 1.0f; 12063 } 12064 12065 /** 12066 * @hide 12067 */ 12068 protected void computeOpaqueFlags() { 12069 // Opaque if: 12070 // - Has a background 12071 // - Background is opaque 12072 // - Doesn't have scrollbars or scrollbars overlay 12073 12074 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 12075 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 12076 } else { 12077 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 12078 } 12079 12080 final int flags = mViewFlags; 12081 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 12082 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 12083 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 12084 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 12085 } else { 12086 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 12087 } 12088 } 12089 12090 /** 12091 * @hide 12092 */ 12093 protected boolean hasOpaqueScrollbars() { 12094 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 12095 } 12096 12097 /** 12098 * @return A handler associated with the thread running the View. This 12099 * handler can be used to pump events in the UI events queue. 12100 */ 12101 public Handler getHandler() { 12102 final AttachInfo attachInfo = mAttachInfo; 12103 if (attachInfo != null) { 12104 return attachInfo.mHandler; 12105 } 12106 return null; 12107 } 12108 12109 /** 12110 * Gets the view root associated with the View. 12111 * @return The view root, or null if none. 12112 * @hide 12113 */ 12114 public ViewRootImpl getViewRootImpl() { 12115 if (mAttachInfo != null) { 12116 return mAttachInfo.mViewRootImpl; 12117 } 12118 return null; 12119 } 12120 12121 /** 12122 * @hide 12123 */ 12124 public HardwareRenderer getHardwareRenderer() { 12125 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 12126 } 12127 12128 /** 12129 * <p>Causes the Runnable to be added to the message queue. 12130 * The runnable will be run on the user interface thread.</p> 12131 * 12132 * @param action The Runnable that will be executed. 12133 * 12134 * @return Returns true if the Runnable was successfully placed in to the 12135 * message queue. Returns false on failure, usually because the 12136 * looper processing the message queue is exiting. 12137 * 12138 * @see #postDelayed 12139 * @see #removeCallbacks 12140 */ 12141 public boolean post(Runnable action) { 12142 final AttachInfo attachInfo = mAttachInfo; 12143 if (attachInfo != null) { 12144 return attachInfo.mHandler.post(action); 12145 } 12146 // Assume that post will succeed later 12147 ViewRootImpl.getRunQueue().post(action); 12148 return true; 12149 } 12150 12151 /** 12152 * <p>Causes the Runnable to be added to the message queue, to be run 12153 * after the specified amount of time elapses. 12154 * The runnable will be run on the user interface thread.</p> 12155 * 12156 * @param action The Runnable that will be executed. 12157 * @param delayMillis The delay (in milliseconds) until the Runnable 12158 * will be executed. 12159 * 12160 * @return true if the Runnable was successfully placed in to the 12161 * message queue. Returns false on failure, usually because the 12162 * looper processing the message queue is exiting. Note that a 12163 * result of true does not mean the Runnable will be processed -- 12164 * if the looper is quit before the delivery time of the message 12165 * occurs then the message will be dropped. 12166 * 12167 * @see #post 12168 * @see #removeCallbacks 12169 */ 12170 public boolean postDelayed(Runnable action, long delayMillis) { 12171 final AttachInfo attachInfo = mAttachInfo; 12172 if (attachInfo != null) { 12173 return attachInfo.mHandler.postDelayed(action, delayMillis); 12174 } 12175 // Assume that post will succeed later 12176 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 12177 return true; 12178 } 12179 12180 /** 12181 * <p>Causes the Runnable to execute on the next animation time step. 12182 * The runnable will be run on the user interface thread.</p> 12183 * 12184 * @param action The Runnable that will be executed. 12185 * 12186 * @see #postOnAnimationDelayed 12187 * @see #removeCallbacks 12188 */ 12189 public void postOnAnimation(Runnable action) { 12190 final AttachInfo attachInfo = mAttachInfo; 12191 if (attachInfo != null) { 12192 attachInfo.mViewRootImpl.mChoreographer.postCallback( 12193 Choreographer.CALLBACK_ANIMATION, action, null); 12194 } else { 12195 // Assume that post will succeed later 12196 ViewRootImpl.getRunQueue().post(action); 12197 } 12198 } 12199 12200 /** 12201 * <p>Causes the Runnable to execute on the next animation time step, 12202 * after the specified amount of time elapses. 12203 * The runnable will be run on the user interface thread.</p> 12204 * 12205 * @param action The Runnable that will be executed. 12206 * @param delayMillis The delay (in milliseconds) until the Runnable 12207 * will be executed. 12208 * 12209 * @see #postOnAnimation 12210 * @see #removeCallbacks 12211 */ 12212 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 12213 final AttachInfo attachInfo = mAttachInfo; 12214 if (attachInfo != null) { 12215 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 12216 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 12217 } else { 12218 // Assume that post will succeed later 12219 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 12220 } 12221 } 12222 12223 /** 12224 * <p>Removes the specified Runnable from the message queue.</p> 12225 * 12226 * @param action The Runnable to remove from the message handling queue 12227 * 12228 * @return true if this view could ask the Handler to remove the Runnable, 12229 * false otherwise. When the returned value is true, the Runnable 12230 * may or may not have been actually removed from the message queue 12231 * (for instance, if the Runnable was not in the queue already.) 12232 * 12233 * @see #post 12234 * @see #postDelayed 12235 * @see #postOnAnimation 12236 * @see #postOnAnimationDelayed 12237 */ 12238 public boolean removeCallbacks(Runnable action) { 12239 if (action != null) { 12240 final AttachInfo attachInfo = mAttachInfo; 12241 if (attachInfo != null) { 12242 attachInfo.mHandler.removeCallbacks(action); 12243 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 12244 Choreographer.CALLBACK_ANIMATION, action, null); 12245 } 12246 // Assume that post will succeed later 12247 ViewRootImpl.getRunQueue().removeCallbacks(action); 12248 } 12249 return true; 12250 } 12251 12252 /** 12253 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 12254 * Use this to invalidate the View from a non-UI thread.</p> 12255 * 12256 * <p>This method can be invoked from outside of the UI thread 12257 * only when this View is attached to a window.</p> 12258 * 12259 * @see #invalidate() 12260 * @see #postInvalidateDelayed(long) 12261 */ 12262 public void postInvalidate() { 12263 postInvalidateDelayed(0); 12264 } 12265 12266 /** 12267 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12268 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 12269 * 12270 * <p>This method can be invoked from outside of the UI thread 12271 * only when this View is attached to a window.</p> 12272 * 12273 * @param left The left coordinate of the rectangle to invalidate. 12274 * @param top The top coordinate of the rectangle to invalidate. 12275 * @param right The right coordinate of the rectangle to invalidate. 12276 * @param bottom The bottom coordinate of the rectangle to invalidate. 12277 * 12278 * @see #invalidate(int, int, int, int) 12279 * @see #invalidate(Rect) 12280 * @see #postInvalidateDelayed(long, int, int, int, int) 12281 */ 12282 public void postInvalidate(int left, int top, int right, int bottom) { 12283 postInvalidateDelayed(0, left, top, right, bottom); 12284 } 12285 12286 /** 12287 * <p>Cause an invalidate to happen on a subsequent cycle through the event 12288 * loop. Waits for the specified amount of time.</p> 12289 * 12290 * <p>This method can be invoked from outside of the UI thread 12291 * only when this View is attached to a window.</p> 12292 * 12293 * @param delayMilliseconds the duration in milliseconds to delay the 12294 * invalidation by 12295 * 12296 * @see #invalidate() 12297 * @see #postInvalidate() 12298 */ 12299 public void postInvalidateDelayed(long delayMilliseconds) { 12300 // We try only with the AttachInfo because there's no point in invalidating 12301 // if we are not attached to our window 12302 final AttachInfo attachInfo = mAttachInfo; 12303 if (attachInfo != null) { 12304 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 12305 } 12306 } 12307 12308 /** 12309 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12310 * through the event loop. Waits for the specified amount of time.</p> 12311 * 12312 * <p>This method can be invoked from outside of the UI thread 12313 * only when this View is attached to a window.</p> 12314 * 12315 * @param delayMilliseconds the duration in milliseconds to delay the 12316 * invalidation by 12317 * @param left The left coordinate of the rectangle to invalidate. 12318 * @param top The top coordinate of the rectangle to invalidate. 12319 * @param right The right coordinate of the rectangle to invalidate. 12320 * @param bottom The bottom coordinate of the rectangle to invalidate. 12321 * 12322 * @see #invalidate(int, int, int, int) 12323 * @see #invalidate(Rect) 12324 * @see #postInvalidate(int, int, int, int) 12325 */ 12326 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 12327 int right, int bottom) { 12328 12329 // We try only with the AttachInfo because there's no point in invalidating 12330 // if we are not attached to our window 12331 final AttachInfo attachInfo = mAttachInfo; 12332 if (attachInfo != null) { 12333 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12334 info.target = this; 12335 info.left = left; 12336 info.top = top; 12337 info.right = right; 12338 info.bottom = bottom; 12339 12340 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 12341 } 12342 } 12343 12344 /** 12345 * <p>Cause an invalidate to happen on the next animation time step, typically the 12346 * next display frame.</p> 12347 * 12348 * <p>This method can be invoked from outside of the UI thread 12349 * only when this View is attached to a window.</p> 12350 * 12351 * @see #invalidate() 12352 */ 12353 public void postInvalidateOnAnimation() { 12354 // We try only with the AttachInfo because there's no point in invalidating 12355 // if we are not attached to our window 12356 final AttachInfo attachInfo = mAttachInfo; 12357 if (attachInfo != null) { 12358 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 12359 } 12360 } 12361 12362 /** 12363 * <p>Cause an invalidate of the specified area to happen on the next animation 12364 * time step, typically the next display frame.</p> 12365 * 12366 * <p>This method can be invoked from outside of the UI thread 12367 * only when this View is attached to a window.</p> 12368 * 12369 * @param left The left coordinate of the rectangle to invalidate. 12370 * @param top The top coordinate of the rectangle to invalidate. 12371 * @param right The right coordinate of the rectangle to invalidate. 12372 * @param bottom The bottom coordinate of the rectangle to invalidate. 12373 * 12374 * @see #invalidate(int, int, int, int) 12375 * @see #invalidate(Rect) 12376 */ 12377 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 12378 // We try only with the AttachInfo because there's no point in invalidating 12379 // if we are not attached to our window 12380 final AttachInfo attachInfo = mAttachInfo; 12381 if (attachInfo != null) { 12382 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12383 info.target = this; 12384 info.left = left; 12385 info.top = top; 12386 info.right = right; 12387 info.bottom = bottom; 12388 12389 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 12390 } 12391 } 12392 12393 /** 12394 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 12395 * This event is sent at most once every 12396 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 12397 */ 12398 private void postSendViewScrolledAccessibilityEventCallback() { 12399 if (mSendViewScrolledAccessibilityEvent == null) { 12400 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 12401 } 12402 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 12403 mSendViewScrolledAccessibilityEvent.mIsPending = true; 12404 postDelayed(mSendViewScrolledAccessibilityEvent, 12405 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 12406 } 12407 } 12408 12409 /** 12410 * Called by a parent to request that a child update its values for mScrollX 12411 * and mScrollY if necessary. This will typically be done if the child is 12412 * animating a scroll using a {@link android.widget.Scroller Scroller} 12413 * object. 12414 */ 12415 public void computeScroll() { 12416 } 12417 12418 /** 12419 * <p>Indicate whether the horizontal edges are faded when the view is 12420 * scrolled horizontally.</p> 12421 * 12422 * @return true if the horizontal edges should are faded on scroll, false 12423 * otherwise 12424 * 12425 * @see #setHorizontalFadingEdgeEnabled(boolean) 12426 * 12427 * @attr ref android.R.styleable#View_requiresFadingEdge 12428 */ 12429 public boolean isHorizontalFadingEdgeEnabled() { 12430 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 12431 } 12432 12433 /** 12434 * <p>Define whether the horizontal edges should be faded when this view 12435 * is scrolled horizontally.</p> 12436 * 12437 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 12438 * be faded when the view is scrolled 12439 * horizontally 12440 * 12441 * @see #isHorizontalFadingEdgeEnabled() 12442 * 12443 * @attr ref android.R.styleable#View_requiresFadingEdge 12444 */ 12445 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 12446 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 12447 if (horizontalFadingEdgeEnabled) { 12448 initScrollCache(); 12449 } 12450 12451 mViewFlags ^= FADING_EDGE_HORIZONTAL; 12452 } 12453 } 12454 12455 /** 12456 * <p>Indicate whether the vertical edges are faded when the view is 12457 * scrolled horizontally.</p> 12458 * 12459 * @return true if the vertical edges should are faded on scroll, false 12460 * otherwise 12461 * 12462 * @see #setVerticalFadingEdgeEnabled(boolean) 12463 * 12464 * @attr ref android.R.styleable#View_requiresFadingEdge 12465 */ 12466 public boolean isVerticalFadingEdgeEnabled() { 12467 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 12468 } 12469 12470 /** 12471 * <p>Define whether the vertical edges should be faded when this view 12472 * is scrolled vertically.</p> 12473 * 12474 * @param verticalFadingEdgeEnabled true if the vertical edges should 12475 * be faded when the view is scrolled 12476 * vertically 12477 * 12478 * @see #isVerticalFadingEdgeEnabled() 12479 * 12480 * @attr ref android.R.styleable#View_requiresFadingEdge 12481 */ 12482 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 12483 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 12484 if (verticalFadingEdgeEnabled) { 12485 initScrollCache(); 12486 } 12487 12488 mViewFlags ^= FADING_EDGE_VERTICAL; 12489 } 12490 } 12491 12492 /** 12493 * Returns the strength, or intensity, of the top faded edge. The strength is 12494 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12495 * returns 0.0 or 1.0 but no value in between. 12496 * 12497 * Subclasses should override this method to provide a smoother fade transition 12498 * when scrolling occurs. 12499 * 12500 * @return the intensity of the top fade as a float between 0.0f and 1.0f 12501 */ 12502 protected float getTopFadingEdgeStrength() { 12503 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 12504 } 12505 12506 /** 12507 * Returns the strength, or intensity, of the bottom faded edge. The strength is 12508 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12509 * returns 0.0 or 1.0 but no value in between. 12510 * 12511 * Subclasses should override this method to provide a smoother fade transition 12512 * when scrolling occurs. 12513 * 12514 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 12515 */ 12516 protected float getBottomFadingEdgeStrength() { 12517 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 12518 computeVerticalScrollRange() ? 1.0f : 0.0f; 12519 } 12520 12521 /** 12522 * Returns the strength, or intensity, of the left faded edge. The strength is 12523 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12524 * returns 0.0 or 1.0 but no value in between. 12525 * 12526 * Subclasses should override this method to provide a smoother fade transition 12527 * when scrolling occurs. 12528 * 12529 * @return the intensity of the left fade as a float between 0.0f and 1.0f 12530 */ 12531 protected float getLeftFadingEdgeStrength() { 12532 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12533 } 12534 12535 /** 12536 * Returns the strength, or intensity, of the right faded edge. The strength is 12537 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12538 * returns 0.0 or 1.0 but no value in between. 12539 * 12540 * Subclasses should override this method to provide a smoother fade transition 12541 * when scrolling occurs. 12542 * 12543 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12544 */ 12545 protected float getRightFadingEdgeStrength() { 12546 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12547 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12548 } 12549 12550 /** 12551 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12552 * scrollbar is not drawn by default.</p> 12553 * 12554 * @return true if the horizontal scrollbar should be painted, false 12555 * otherwise 12556 * 12557 * @see #setHorizontalScrollBarEnabled(boolean) 12558 */ 12559 public boolean isHorizontalScrollBarEnabled() { 12560 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12561 } 12562 12563 /** 12564 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12565 * scrollbar is not drawn by default.</p> 12566 * 12567 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12568 * be painted 12569 * 12570 * @see #isHorizontalScrollBarEnabled() 12571 */ 12572 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12573 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12574 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12575 computeOpaqueFlags(); 12576 resolvePadding(); 12577 } 12578 } 12579 12580 /** 12581 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12582 * scrollbar is not drawn by default.</p> 12583 * 12584 * @return true if the vertical scrollbar should be painted, false 12585 * otherwise 12586 * 12587 * @see #setVerticalScrollBarEnabled(boolean) 12588 */ 12589 public boolean isVerticalScrollBarEnabled() { 12590 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12591 } 12592 12593 /** 12594 * <p>Define whether the vertical scrollbar should be drawn or not. The 12595 * scrollbar is not drawn by default.</p> 12596 * 12597 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12598 * be painted 12599 * 12600 * @see #isVerticalScrollBarEnabled() 12601 */ 12602 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12603 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12604 mViewFlags ^= SCROLLBARS_VERTICAL; 12605 computeOpaqueFlags(); 12606 resolvePadding(); 12607 } 12608 } 12609 12610 /** 12611 * @hide 12612 */ 12613 protected void recomputePadding() { 12614 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12615 } 12616 12617 /** 12618 * Define whether scrollbars will fade when the view is not scrolling. 12619 * 12620 * @param fadeScrollbars wheter to enable fading 12621 * 12622 * @attr ref android.R.styleable#View_fadeScrollbars 12623 */ 12624 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12625 initScrollCache(); 12626 final ScrollabilityCache scrollabilityCache = mScrollCache; 12627 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12628 if (fadeScrollbars) { 12629 scrollabilityCache.state = ScrollabilityCache.OFF; 12630 } else { 12631 scrollabilityCache.state = ScrollabilityCache.ON; 12632 } 12633 } 12634 12635 /** 12636 * 12637 * Returns true if scrollbars will fade when this view is not scrolling 12638 * 12639 * @return true if scrollbar fading is enabled 12640 * 12641 * @attr ref android.R.styleable#View_fadeScrollbars 12642 */ 12643 public boolean isScrollbarFadingEnabled() { 12644 return mScrollCache != null && mScrollCache.fadeScrollBars; 12645 } 12646 12647 /** 12648 * 12649 * Returns the delay before scrollbars fade. 12650 * 12651 * @return the delay before scrollbars fade 12652 * 12653 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12654 */ 12655 public int getScrollBarDefaultDelayBeforeFade() { 12656 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12657 mScrollCache.scrollBarDefaultDelayBeforeFade; 12658 } 12659 12660 /** 12661 * Define the delay before scrollbars fade. 12662 * 12663 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12664 * 12665 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12666 */ 12667 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12668 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12669 } 12670 12671 /** 12672 * 12673 * Returns the scrollbar fade duration. 12674 * 12675 * @return the scrollbar fade duration 12676 * 12677 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12678 */ 12679 public int getScrollBarFadeDuration() { 12680 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12681 mScrollCache.scrollBarFadeDuration; 12682 } 12683 12684 /** 12685 * Define the scrollbar fade duration. 12686 * 12687 * @param scrollBarFadeDuration - the scrollbar fade duration 12688 * 12689 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12690 */ 12691 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12692 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12693 } 12694 12695 /** 12696 * 12697 * Returns the scrollbar size. 12698 * 12699 * @return the scrollbar size 12700 * 12701 * @attr ref android.R.styleable#View_scrollbarSize 12702 */ 12703 public int getScrollBarSize() { 12704 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12705 mScrollCache.scrollBarSize; 12706 } 12707 12708 /** 12709 * Define the scrollbar size. 12710 * 12711 * @param scrollBarSize - the scrollbar size 12712 * 12713 * @attr ref android.R.styleable#View_scrollbarSize 12714 */ 12715 public void setScrollBarSize(int scrollBarSize) { 12716 getScrollCache().scrollBarSize = scrollBarSize; 12717 } 12718 12719 /** 12720 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12721 * inset. When inset, they add to the padding of the view. And the scrollbars 12722 * can be drawn inside the padding area or on the edge of the view. For example, 12723 * if a view has a background drawable and you want to draw the scrollbars 12724 * inside the padding specified by the drawable, you can use 12725 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12726 * appear at the edge of the view, ignoring the padding, then you can use 12727 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12728 * @param style the style of the scrollbars. Should be one of 12729 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12730 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12731 * @see #SCROLLBARS_INSIDE_OVERLAY 12732 * @see #SCROLLBARS_INSIDE_INSET 12733 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12734 * @see #SCROLLBARS_OUTSIDE_INSET 12735 * 12736 * @attr ref android.R.styleable#View_scrollbarStyle 12737 */ 12738 public void setScrollBarStyle(@ScrollBarStyle int style) { 12739 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12740 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12741 computeOpaqueFlags(); 12742 resolvePadding(); 12743 } 12744 } 12745 12746 /** 12747 * <p>Returns the current scrollbar style.</p> 12748 * @return the current scrollbar style 12749 * @see #SCROLLBARS_INSIDE_OVERLAY 12750 * @see #SCROLLBARS_INSIDE_INSET 12751 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12752 * @see #SCROLLBARS_OUTSIDE_INSET 12753 * 12754 * @attr ref android.R.styleable#View_scrollbarStyle 12755 */ 12756 @ViewDebug.ExportedProperty(mapping = { 12757 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12758 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12759 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12760 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12761 }) 12762 @ScrollBarStyle 12763 public int getScrollBarStyle() { 12764 return mViewFlags & SCROLLBARS_STYLE_MASK; 12765 } 12766 12767 /** 12768 * <p>Compute the horizontal range that the horizontal scrollbar 12769 * represents.</p> 12770 * 12771 * <p>The range is expressed in arbitrary units that must be the same as the 12772 * units used by {@link #computeHorizontalScrollExtent()} and 12773 * {@link #computeHorizontalScrollOffset()}.</p> 12774 * 12775 * <p>The default range is the drawing width of this view.</p> 12776 * 12777 * @return the total horizontal range represented by the horizontal 12778 * scrollbar 12779 * 12780 * @see #computeHorizontalScrollExtent() 12781 * @see #computeHorizontalScrollOffset() 12782 * @see android.widget.ScrollBarDrawable 12783 */ 12784 protected int computeHorizontalScrollRange() { 12785 return getWidth(); 12786 } 12787 12788 /** 12789 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12790 * within the horizontal range. This value is used to compute the position 12791 * of the thumb within the scrollbar's track.</p> 12792 * 12793 * <p>The range is expressed in arbitrary units that must be the same as the 12794 * units used by {@link #computeHorizontalScrollRange()} and 12795 * {@link #computeHorizontalScrollExtent()}.</p> 12796 * 12797 * <p>The default offset is the scroll offset of this view.</p> 12798 * 12799 * @return the horizontal offset of the scrollbar's thumb 12800 * 12801 * @see #computeHorizontalScrollRange() 12802 * @see #computeHorizontalScrollExtent() 12803 * @see android.widget.ScrollBarDrawable 12804 */ 12805 protected int computeHorizontalScrollOffset() { 12806 return mScrollX; 12807 } 12808 12809 /** 12810 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12811 * within the horizontal range. This value is used to compute the length 12812 * of the thumb within the scrollbar's track.</p> 12813 * 12814 * <p>The range is expressed in arbitrary units that must be the same as the 12815 * units used by {@link #computeHorizontalScrollRange()} and 12816 * {@link #computeHorizontalScrollOffset()}.</p> 12817 * 12818 * <p>The default extent is the drawing width of this view.</p> 12819 * 12820 * @return the horizontal extent of the scrollbar's thumb 12821 * 12822 * @see #computeHorizontalScrollRange() 12823 * @see #computeHorizontalScrollOffset() 12824 * @see android.widget.ScrollBarDrawable 12825 */ 12826 protected int computeHorizontalScrollExtent() { 12827 return getWidth(); 12828 } 12829 12830 /** 12831 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12832 * 12833 * <p>The range is expressed in arbitrary units that must be the same as the 12834 * units used by {@link #computeVerticalScrollExtent()} and 12835 * {@link #computeVerticalScrollOffset()}.</p> 12836 * 12837 * @return the total vertical range represented by the vertical scrollbar 12838 * 12839 * <p>The default range is the drawing height of this view.</p> 12840 * 12841 * @see #computeVerticalScrollExtent() 12842 * @see #computeVerticalScrollOffset() 12843 * @see android.widget.ScrollBarDrawable 12844 */ 12845 protected int computeVerticalScrollRange() { 12846 return getHeight(); 12847 } 12848 12849 /** 12850 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12851 * within the horizontal range. This value is used to compute the position 12852 * of the thumb within the scrollbar's track.</p> 12853 * 12854 * <p>The range is expressed in arbitrary units that must be the same as the 12855 * units used by {@link #computeVerticalScrollRange()} and 12856 * {@link #computeVerticalScrollExtent()}.</p> 12857 * 12858 * <p>The default offset is the scroll offset of this view.</p> 12859 * 12860 * @return the vertical offset of the scrollbar's thumb 12861 * 12862 * @see #computeVerticalScrollRange() 12863 * @see #computeVerticalScrollExtent() 12864 * @see android.widget.ScrollBarDrawable 12865 */ 12866 protected int computeVerticalScrollOffset() { 12867 return mScrollY; 12868 } 12869 12870 /** 12871 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12872 * within the vertical range. This value is used to compute the length 12873 * of the thumb within the scrollbar's track.</p> 12874 * 12875 * <p>The range is expressed in arbitrary units that must be the same as the 12876 * units used by {@link #computeVerticalScrollRange()} and 12877 * {@link #computeVerticalScrollOffset()}.</p> 12878 * 12879 * <p>The default extent is the drawing height of this view.</p> 12880 * 12881 * @return the vertical extent of the scrollbar's thumb 12882 * 12883 * @see #computeVerticalScrollRange() 12884 * @see #computeVerticalScrollOffset() 12885 * @see android.widget.ScrollBarDrawable 12886 */ 12887 protected int computeVerticalScrollExtent() { 12888 return getHeight(); 12889 } 12890 12891 /** 12892 * Check if this view can be scrolled horizontally in a certain direction. 12893 * 12894 * @param direction Negative to check scrolling left, positive to check scrolling right. 12895 * @return true if this view can be scrolled in the specified direction, false otherwise. 12896 */ 12897 public boolean canScrollHorizontally(int direction) { 12898 final int offset = computeHorizontalScrollOffset(); 12899 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12900 if (range == 0) return false; 12901 if (direction < 0) { 12902 return offset > 0; 12903 } else { 12904 return offset < range - 1; 12905 } 12906 } 12907 12908 /** 12909 * Check if this view can be scrolled vertically in a certain direction. 12910 * 12911 * @param direction Negative to check scrolling up, positive to check scrolling down. 12912 * @return true if this view can be scrolled in the specified direction, false otherwise. 12913 */ 12914 public boolean canScrollVertically(int direction) { 12915 final int offset = computeVerticalScrollOffset(); 12916 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12917 if (range == 0) return false; 12918 if (direction < 0) { 12919 return offset > 0; 12920 } else { 12921 return offset < range - 1; 12922 } 12923 } 12924 12925 /** 12926 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12927 * scrollbars are painted only if they have been awakened first.</p> 12928 * 12929 * @param canvas the canvas on which to draw the scrollbars 12930 * 12931 * @see #awakenScrollBars(int) 12932 */ 12933 protected final void onDrawScrollBars(Canvas canvas) { 12934 // scrollbars are drawn only when the animation is running 12935 final ScrollabilityCache cache = mScrollCache; 12936 if (cache != null) { 12937 12938 int state = cache.state; 12939 12940 if (state == ScrollabilityCache.OFF) { 12941 return; 12942 } 12943 12944 boolean invalidate = false; 12945 12946 if (state == ScrollabilityCache.FADING) { 12947 // We're fading -- get our fade interpolation 12948 if (cache.interpolatorValues == null) { 12949 cache.interpolatorValues = new float[1]; 12950 } 12951 12952 float[] values = cache.interpolatorValues; 12953 12954 // Stops the animation if we're done 12955 if (cache.scrollBarInterpolator.timeToValues(values) == 12956 Interpolator.Result.FREEZE_END) { 12957 cache.state = ScrollabilityCache.OFF; 12958 } else { 12959 cache.scrollBar.setAlpha(Math.round(values[0])); 12960 } 12961 12962 // This will make the scroll bars inval themselves after 12963 // drawing. We only want this when we're fading so that 12964 // we prevent excessive redraws 12965 invalidate = true; 12966 } else { 12967 // We're just on -- but we may have been fading before so 12968 // reset alpha 12969 cache.scrollBar.setAlpha(255); 12970 } 12971 12972 12973 final int viewFlags = mViewFlags; 12974 12975 final boolean drawHorizontalScrollBar = 12976 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12977 final boolean drawVerticalScrollBar = 12978 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12979 && !isVerticalScrollBarHidden(); 12980 12981 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12982 final int width = mRight - mLeft; 12983 final int height = mBottom - mTop; 12984 12985 final ScrollBarDrawable scrollBar = cache.scrollBar; 12986 12987 final int scrollX = mScrollX; 12988 final int scrollY = mScrollY; 12989 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12990 12991 int left; 12992 int top; 12993 int right; 12994 int bottom; 12995 12996 if (drawHorizontalScrollBar) { 12997 int size = scrollBar.getSize(false); 12998 if (size <= 0) { 12999 size = cache.scrollBarSize; 13000 } 13001 13002 scrollBar.setParameters(computeHorizontalScrollRange(), 13003 computeHorizontalScrollOffset(), 13004 computeHorizontalScrollExtent(), false); 13005 final int verticalScrollBarGap = drawVerticalScrollBar ? 13006 getVerticalScrollbarWidth() : 0; 13007 top = scrollY + height - size - (mUserPaddingBottom & inside); 13008 left = scrollX + (mPaddingLeft & inside); 13009 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 13010 bottom = top + size; 13011 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 13012 if (invalidate) { 13013 invalidate(left, top, right, bottom); 13014 } 13015 } 13016 13017 if (drawVerticalScrollBar) { 13018 int size = scrollBar.getSize(true); 13019 if (size <= 0) { 13020 size = cache.scrollBarSize; 13021 } 13022 13023 scrollBar.setParameters(computeVerticalScrollRange(), 13024 computeVerticalScrollOffset(), 13025 computeVerticalScrollExtent(), true); 13026 int verticalScrollbarPosition = mVerticalScrollbarPosition; 13027 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 13028 verticalScrollbarPosition = isLayoutRtl() ? 13029 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 13030 } 13031 switch (verticalScrollbarPosition) { 13032 default: 13033 case SCROLLBAR_POSITION_RIGHT: 13034 left = scrollX + width - size - (mUserPaddingRight & inside); 13035 break; 13036 case SCROLLBAR_POSITION_LEFT: 13037 left = scrollX + (mUserPaddingLeft & inside); 13038 break; 13039 } 13040 top = scrollY + (mPaddingTop & inside); 13041 right = left + size; 13042 bottom = scrollY + height - (mUserPaddingBottom & inside); 13043 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 13044 if (invalidate) { 13045 invalidate(left, top, right, bottom); 13046 } 13047 } 13048 } 13049 } 13050 } 13051 13052 /** 13053 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 13054 * FastScroller is visible. 13055 * @return whether to temporarily hide the vertical scrollbar 13056 * @hide 13057 */ 13058 protected boolean isVerticalScrollBarHidden() { 13059 return false; 13060 } 13061 13062 /** 13063 * <p>Draw the horizontal scrollbar if 13064 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 13065 * 13066 * @param canvas the canvas on which to draw the scrollbar 13067 * @param scrollBar the scrollbar's drawable 13068 * 13069 * @see #isHorizontalScrollBarEnabled() 13070 * @see #computeHorizontalScrollRange() 13071 * @see #computeHorizontalScrollExtent() 13072 * @see #computeHorizontalScrollOffset() 13073 * @see android.widget.ScrollBarDrawable 13074 * @hide 13075 */ 13076 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 13077 int l, int t, int r, int b) { 13078 scrollBar.setBounds(l, t, r, b); 13079 scrollBar.draw(canvas); 13080 } 13081 13082 /** 13083 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 13084 * returns true.</p> 13085 * 13086 * @param canvas the canvas on which to draw the scrollbar 13087 * @param scrollBar the scrollbar's drawable 13088 * 13089 * @see #isVerticalScrollBarEnabled() 13090 * @see #computeVerticalScrollRange() 13091 * @see #computeVerticalScrollExtent() 13092 * @see #computeVerticalScrollOffset() 13093 * @see android.widget.ScrollBarDrawable 13094 * @hide 13095 */ 13096 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 13097 int l, int t, int r, int b) { 13098 scrollBar.setBounds(l, t, r, b); 13099 scrollBar.draw(canvas); 13100 } 13101 13102 /** 13103 * Implement this to do your drawing. 13104 * 13105 * @param canvas the canvas on which the background will be drawn 13106 */ 13107 protected void onDraw(Canvas canvas) { 13108 } 13109 13110 /* 13111 * Caller is responsible for calling requestLayout if necessary. 13112 * (This allows addViewInLayout to not request a new layout.) 13113 */ 13114 void assignParent(ViewParent parent) { 13115 if (mParent == null) { 13116 mParent = parent; 13117 } else if (parent == null) { 13118 mParent = null; 13119 } else { 13120 throw new RuntimeException("view " + this + " being added, but" 13121 + " it already has a parent"); 13122 } 13123 } 13124 13125 /** 13126 * This is called when the view is attached to a window. At this point it 13127 * has a Surface and will start drawing. Note that this function is 13128 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 13129 * however it may be called any time before the first onDraw -- including 13130 * before or after {@link #onMeasure(int, int)}. 13131 * 13132 * @see #onDetachedFromWindow() 13133 */ 13134 protected void onAttachedToWindow() { 13135 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 13136 mParent.requestTransparentRegion(this); 13137 } 13138 13139 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 13140 initialAwakenScrollBars(); 13141 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 13142 } 13143 13144 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13145 13146 jumpDrawablesToCurrentState(); 13147 13148 resetSubtreeAccessibilityStateChanged(); 13149 13150 // rebuild, since Outline not maintained while View is detached 13151 rebuildOutline(); 13152 13153 if (isFocused()) { 13154 InputMethodManager imm = InputMethodManager.peekInstance(); 13155 imm.focusIn(this); 13156 } 13157 } 13158 13159 /** 13160 * Resolve all RTL related properties. 13161 * 13162 * @return true if resolution of RTL properties has been done 13163 * 13164 * @hide 13165 */ 13166 public boolean resolveRtlPropertiesIfNeeded() { 13167 if (!needRtlPropertiesResolution()) return false; 13168 13169 // Order is important here: LayoutDirection MUST be resolved first 13170 if (!isLayoutDirectionResolved()) { 13171 resolveLayoutDirection(); 13172 resolveLayoutParams(); 13173 } 13174 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 13175 if (!isTextDirectionResolved()) { 13176 resolveTextDirection(); 13177 } 13178 if (!isTextAlignmentResolved()) { 13179 resolveTextAlignment(); 13180 } 13181 // Should resolve Drawables before Padding because we need the layout direction of the 13182 // Drawable to correctly resolve Padding. 13183 if (!areDrawablesResolved()) { 13184 resolveDrawables(); 13185 } 13186 if (!isPaddingResolved()) { 13187 resolvePadding(); 13188 } 13189 onRtlPropertiesChanged(getLayoutDirection()); 13190 return true; 13191 } 13192 13193 /** 13194 * Reset resolution of all RTL related properties. 13195 * 13196 * @hide 13197 */ 13198 public void resetRtlProperties() { 13199 resetResolvedLayoutDirection(); 13200 resetResolvedTextDirection(); 13201 resetResolvedTextAlignment(); 13202 resetResolvedPadding(); 13203 resetResolvedDrawables(); 13204 } 13205 13206 /** 13207 * @see #onScreenStateChanged(int) 13208 */ 13209 void dispatchScreenStateChanged(int screenState) { 13210 onScreenStateChanged(screenState); 13211 } 13212 13213 /** 13214 * This method is called whenever the state of the screen this view is 13215 * attached to changes. A state change will usually occurs when the screen 13216 * turns on or off (whether it happens automatically or the user does it 13217 * manually.) 13218 * 13219 * @param screenState The new state of the screen. Can be either 13220 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 13221 */ 13222 public void onScreenStateChanged(int screenState) { 13223 } 13224 13225 /** 13226 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 13227 */ 13228 private boolean hasRtlSupport() { 13229 return mContext.getApplicationInfo().hasRtlSupport(); 13230 } 13231 13232 /** 13233 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 13234 * RTL not supported) 13235 */ 13236 private boolean isRtlCompatibilityMode() { 13237 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 13238 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 13239 } 13240 13241 /** 13242 * @return true if RTL properties need resolution. 13243 * 13244 */ 13245 private boolean needRtlPropertiesResolution() { 13246 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 13247 } 13248 13249 /** 13250 * Called when any RTL property (layout direction or text direction or text alignment) has 13251 * been changed. 13252 * 13253 * Subclasses need to override this method to take care of cached information that depends on the 13254 * resolved layout direction, or to inform child views that inherit their layout direction. 13255 * 13256 * The default implementation does nothing. 13257 * 13258 * @param layoutDirection the direction of the layout 13259 * 13260 * @see #LAYOUT_DIRECTION_LTR 13261 * @see #LAYOUT_DIRECTION_RTL 13262 */ 13263 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 13264 } 13265 13266 /** 13267 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 13268 * that the parent directionality can and will be resolved before its children. 13269 * 13270 * @return true if resolution has been done, false otherwise. 13271 * 13272 * @hide 13273 */ 13274 public boolean resolveLayoutDirection() { 13275 // Clear any previous layout direction resolution 13276 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13277 13278 if (hasRtlSupport()) { 13279 // Set resolved depending on layout direction 13280 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 13281 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 13282 case LAYOUT_DIRECTION_INHERIT: 13283 // We cannot resolve yet. LTR is by default and let the resolution happen again 13284 // later to get the correct resolved value 13285 if (!canResolveLayoutDirection()) return false; 13286 13287 // Parent has not yet resolved, LTR is still the default 13288 try { 13289 if (!mParent.isLayoutDirectionResolved()) return false; 13290 13291 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 13292 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13293 } 13294 } catch (AbstractMethodError e) { 13295 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13296 " does not fully implement ViewParent", e); 13297 } 13298 break; 13299 case LAYOUT_DIRECTION_RTL: 13300 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13301 break; 13302 case LAYOUT_DIRECTION_LOCALE: 13303 if((LAYOUT_DIRECTION_RTL == 13304 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 13305 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13306 } 13307 break; 13308 default: 13309 // Nothing to do, LTR by default 13310 } 13311 } 13312 13313 // Set to resolved 13314 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13315 return true; 13316 } 13317 13318 /** 13319 * Check if layout direction resolution can be done. 13320 * 13321 * @return true if layout direction resolution can be done otherwise return false. 13322 */ 13323 public boolean canResolveLayoutDirection() { 13324 switch (getRawLayoutDirection()) { 13325 case LAYOUT_DIRECTION_INHERIT: 13326 if (mParent != null) { 13327 try { 13328 return mParent.canResolveLayoutDirection(); 13329 } catch (AbstractMethodError e) { 13330 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13331 " does not fully implement ViewParent", e); 13332 } 13333 } 13334 return false; 13335 13336 default: 13337 return true; 13338 } 13339 } 13340 13341 /** 13342 * Reset the resolved layout direction. Layout direction will be resolved during a call to 13343 * {@link #onMeasure(int, int)}. 13344 * 13345 * @hide 13346 */ 13347 public void resetResolvedLayoutDirection() { 13348 // Reset the current resolved bits 13349 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13350 } 13351 13352 /** 13353 * @return true if the layout direction is inherited. 13354 * 13355 * @hide 13356 */ 13357 public boolean isLayoutDirectionInherited() { 13358 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 13359 } 13360 13361 /** 13362 * @return true if layout direction has been resolved. 13363 */ 13364 public boolean isLayoutDirectionResolved() { 13365 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13366 } 13367 13368 /** 13369 * Return if padding has been resolved 13370 * 13371 * @hide 13372 */ 13373 boolean isPaddingResolved() { 13374 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 13375 } 13376 13377 /** 13378 * Resolves padding depending on layout direction, if applicable, and 13379 * recomputes internal padding values to adjust for scroll bars. 13380 * 13381 * @hide 13382 */ 13383 public void resolvePadding() { 13384 final int resolvedLayoutDirection = getLayoutDirection(); 13385 13386 if (!isRtlCompatibilityMode()) { 13387 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 13388 // If start / end padding are defined, they will be resolved (hence overriding) to 13389 // left / right or right / left depending on the resolved layout direction. 13390 // If start / end padding are not defined, use the left / right ones. 13391 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 13392 Rect padding = sThreadLocal.get(); 13393 if (padding == null) { 13394 padding = new Rect(); 13395 sThreadLocal.set(padding); 13396 } 13397 mBackground.getPadding(padding); 13398 if (!mLeftPaddingDefined) { 13399 mUserPaddingLeftInitial = padding.left; 13400 } 13401 if (!mRightPaddingDefined) { 13402 mUserPaddingRightInitial = padding.right; 13403 } 13404 } 13405 switch (resolvedLayoutDirection) { 13406 case LAYOUT_DIRECTION_RTL: 13407 if (mUserPaddingStart != UNDEFINED_PADDING) { 13408 mUserPaddingRight = mUserPaddingStart; 13409 } else { 13410 mUserPaddingRight = mUserPaddingRightInitial; 13411 } 13412 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13413 mUserPaddingLeft = mUserPaddingEnd; 13414 } else { 13415 mUserPaddingLeft = mUserPaddingLeftInitial; 13416 } 13417 break; 13418 case LAYOUT_DIRECTION_LTR: 13419 default: 13420 if (mUserPaddingStart != UNDEFINED_PADDING) { 13421 mUserPaddingLeft = mUserPaddingStart; 13422 } else { 13423 mUserPaddingLeft = mUserPaddingLeftInitial; 13424 } 13425 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13426 mUserPaddingRight = mUserPaddingEnd; 13427 } else { 13428 mUserPaddingRight = mUserPaddingRightInitial; 13429 } 13430 } 13431 13432 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 13433 } 13434 13435 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 13436 onRtlPropertiesChanged(resolvedLayoutDirection); 13437 13438 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 13439 } 13440 13441 /** 13442 * Reset the resolved layout direction. 13443 * 13444 * @hide 13445 */ 13446 public void resetResolvedPadding() { 13447 resetResolvedPaddingInternal(); 13448 } 13449 13450 /** 13451 * Used when we only want to reset *this* view's padding and not trigger overrides 13452 * in ViewGroup that reset children too. 13453 */ 13454 void resetResolvedPaddingInternal() { 13455 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 13456 } 13457 13458 /** 13459 * This is called when the view is detached from a window. At this point it 13460 * no longer has a surface for drawing. 13461 * 13462 * @see #onAttachedToWindow() 13463 */ 13464 protected void onDetachedFromWindow() { 13465 } 13466 13467 /** 13468 * This is a framework-internal mirror of onDetachedFromWindow() that's called 13469 * after onDetachedFromWindow(). 13470 * 13471 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 13472 * The super method should be called at the end of the overriden method to ensure 13473 * subclasses are destroyed first 13474 * 13475 * @hide 13476 */ 13477 protected void onDetachedFromWindowInternal() { 13478 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 13479 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13480 13481 removeUnsetPressCallback(); 13482 removeLongPressCallback(); 13483 removePerformClickCallback(); 13484 removeSendViewScrolledAccessibilityEventCallback(); 13485 stopNestedScroll(); 13486 13487 // Anything that started animating right before detach should already 13488 // be in its final state when re-attached. 13489 jumpDrawablesToCurrentState(); 13490 13491 destroyDrawingCache(); 13492 13493 cleanupDraw(); 13494 mCurrentAnimation = null; 13495 } 13496 13497 private void cleanupDraw() { 13498 resetDisplayList(); 13499 if (mAttachInfo != null) { 13500 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 13501 } 13502 } 13503 13504 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 13505 } 13506 13507 /** 13508 * @return The number of times this view has been attached to a window 13509 */ 13510 protected int getWindowAttachCount() { 13511 return mWindowAttachCount; 13512 } 13513 13514 /** 13515 * Retrieve a unique token identifying the window this view is attached to. 13516 * @return Return the window's token for use in 13517 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13518 */ 13519 public IBinder getWindowToken() { 13520 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13521 } 13522 13523 /** 13524 * Retrieve the {@link WindowId} for the window this view is 13525 * currently attached to. 13526 */ 13527 public WindowId getWindowId() { 13528 if (mAttachInfo == null) { 13529 return null; 13530 } 13531 if (mAttachInfo.mWindowId == null) { 13532 try { 13533 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13534 mAttachInfo.mWindowToken); 13535 mAttachInfo.mWindowId = new WindowId( 13536 mAttachInfo.mIWindowId); 13537 } catch (RemoteException e) { 13538 } 13539 } 13540 return mAttachInfo.mWindowId; 13541 } 13542 13543 /** 13544 * Retrieve a unique token identifying the top-level "real" window of 13545 * the window that this view is attached to. That is, this is like 13546 * {@link #getWindowToken}, except if the window this view in is a panel 13547 * window (attached to another containing window), then the token of 13548 * the containing window is returned instead. 13549 * 13550 * @return Returns the associated window token, either 13551 * {@link #getWindowToken()} or the containing window's token. 13552 */ 13553 public IBinder getApplicationWindowToken() { 13554 AttachInfo ai = mAttachInfo; 13555 if (ai != null) { 13556 IBinder appWindowToken = ai.mPanelParentWindowToken; 13557 if (appWindowToken == null) { 13558 appWindowToken = ai.mWindowToken; 13559 } 13560 return appWindowToken; 13561 } 13562 return null; 13563 } 13564 13565 /** 13566 * Gets the logical display to which the view's window has been attached. 13567 * 13568 * @return The logical display, or null if the view is not currently attached to a window. 13569 */ 13570 public Display getDisplay() { 13571 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13572 } 13573 13574 /** 13575 * Retrieve private session object this view hierarchy is using to 13576 * communicate with the window manager. 13577 * @return the session object to communicate with the window manager 13578 */ 13579 /*package*/ IWindowSession getWindowSession() { 13580 return mAttachInfo != null ? mAttachInfo.mSession : null; 13581 } 13582 13583 /** 13584 * @param info the {@link android.view.View.AttachInfo} to associated with 13585 * this view 13586 */ 13587 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13588 //System.out.println("Attached! " + this); 13589 mAttachInfo = info; 13590 if (mOverlay != null) { 13591 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13592 } 13593 mWindowAttachCount++; 13594 // We will need to evaluate the drawable state at least once. 13595 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13596 if (mFloatingTreeObserver != null) { 13597 info.mTreeObserver.merge(mFloatingTreeObserver); 13598 mFloatingTreeObserver = null; 13599 } 13600 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13601 mAttachInfo.mScrollContainers.add(this); 13602 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13603 } 13604 performCollectViewAttributes(mAttachInfo, visibility); 13605 onAttachedToWindow(); 13606 13607 ListenerInfo li = mListenerInfo; 13608 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13609 li != null ? li.mOnAttachStateChangeListeners : null; 13610 if (listeners != null && listeners.size() > 0) { 13611 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13612 // perform the dispatching. The iterator is a safe guard against listeners that 13613 // could mutate the list by calling the various add/remove methods. This prevents 13614 // the array from being modified while we iterate it. 13615 for (OnAttachStateChangeListener listener : listeners) { 13616 listener.onViewAttachedToWindow(this); 13617 } 13618 } 13619 13620 int vis = info.mWindowVisibility; 13621 if (vis != GONE) { 13622 onWindowVisibilityChanged(vis); 13623 } 13624 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13625 // If nobody has evaluated the drawable state yet, then do it now. 13626 refreshDrawableState(); 13627 } 13628 needGlobalAttributesUpdate(false); 13629 } 13630 13631 void dispatchDetachedFromWindow() { 13632 AttachInfo info = mAttachInfo; 13633 if (info != null) { 13634 int vis = info.mWindowVisibility; 13635 if (vis != GONE) { 13636 onWindowVisibilityChanged(GONE); 13637 } 13638 } 13639 13640 onDetachedFromWindow(); 13641 onDetachedFromWindowInternal(); 13642 13643 ListenerInfo li = mListenerInfo; 13644 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13645 li != null ? li.mOnAttachStateChangeListeners : null; 13646 if (listeners != null && listeners.size() > 0) { 13647 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13648 // perform the dispatching. The iterator is a safe guard against listeners that 13649 // could mutate the list by calling the various add/remove methods. This prevents 13650 // the array from being modified while we iterate it. 13651 for (OnAttachStateChangeListener listener : listeners) { 13652 listener.onViewDetachedFromWindow(this); 13653 } 13654 } 13655 13656 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13657 mAttachInfo.mScrollContainers.remove(this); 13658 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13659 } 13660 13661 mAttachInfo = null; 13662 if (mOverlay != null) { 13663 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13664 } 13665 } 13666 13667 /** 13668 * Cancel any deferred high-level input events that were previously posted to the event queue. 13669 * 13670 * <p>Many views post high-level events such as click handlers to the event queue 13671 * to run deferred in order to preserve a desired user experience - clearing visible 13672 * pressed states before executing, etc. This method will abort any events of this nature 13673 * that are currently in flight.</p> 13674 * 13675 * <p>Custom views that generate their own high-level deferred input events should override 13676 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13677 * 13678 * <p>This will also cancel pending input events for any child views.</p> 13679 * 13680 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13681 * This will not impact newer events posted after this call that may occur as a result of 13682 * lower-level input events still waiting in the queue. If you are trying to prevent 13683 * double-submitted events for the duration of some sort of asynchronous transaction 13684 * you should also take other steps to protect against unexpected double inputs e.g. calling 13685 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13686 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13687 */ 13688 public final void cancelPendingInputEvents() { 13689 dispatchCancelPendingInputEvents(); 13690 } 13691 13692 /** 13693 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13694 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13695 */ 13696 void dispatchCancelPendingInputEvents() { 13697 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13698 onCancelPendingInputEvents(); 13699 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13700 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13701 " did not call through to super.onCancelPendingInputEvents()"); 13702 } 13703 } 13704 13705 /** 13706 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13707 * a parent view. 13708 * 13709 * <p>This method is responsible for removing any pending high-level input events that were 13710 * posted to the event queue to run later. Custom view classes that post their own deferred 13711 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13712 * {@link android.os.Handler} should override this method, call 13713 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13714 * </p> 13715 */ 13716 public void onCancelPendingInputEvents() { 13717 removePerformClickCallback(); 13718 cancelLongPress(); 13719 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13720 } 13721 13722 /** 13723 * Store this view hierarchy's frozen state into the given container. 13724 * 13725 * @param container The SparseArray in which to save the view's state. 13726 * 13727 * @see #restoreHierarchyState(android.util.SparseArray) 13728 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13729 * @see #onSaveInstanceState() 13730 */ 13731 public void saveHierarchyState(SparseArray<Parcelable> container) { 13732 dispatchSaveInstanceState(container); 13733 } 13734 13735 /** 13736 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13737 * this view and its children. May be overridden to modify how freezing happens to a 13738 * view's children; for example, some views may want to not store state for their children. 13739 * 13740 * @param container The SparseArray in which to save the view's state. 13741 * 13742 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13743 * @see #saveHierarchyState(android.util.SparseArray) 13744 * @see #onSaveInstanceState() 13745 */ 13746 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13747 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13748 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13749 Parcelable state = onSaveInstanceState(); 13750 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13751 throw new IllegalStateException( 13752 "Derived class did not call super.onSaveInstanceState()"); 13753 } 13754 if (state != null) { 13755 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13756 // + ": " + state); 13757 container.put(mID, state); 13758 } 13759 } 13760 } 13761 13762 /** 13763 * Hook allowing a view to generate a representation of its internal state 13764 * that can later be used to create a new instance with that same state. 13765 * This state should only contain information that is not persistent or can 13766 * not be reconstructed later. For example, you will never store your 13767 * current position on screen because that will be computed again when a 13768 * new instance of the view is placed in its view hierarchy. 13769 * <p> 13770 * Some examples of things you may store here: the current cursor position 13771 * in a text view (but usually not the text itself since that is stored in a 13772 * content provider or other persistent storage), the currently selected 13773 * item in a list view. 13774 * 13775 * @return Returns a Parcelable object containing the view's current dynamic 13776 * state, or null if there is nothing interesting to save. The 13777 * default implementation returns null. 13778 * @see #onRestoreInstanceState(android.os.Parcelable) 13779 * @see #saveHierarchyState(android.util.SparseArray) 13780 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13781 * @see #setSaveEnabled(boolean) 13782 */ 13783 protected Parcelable onSaveInstanceState() { 13784 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13785 return BaseSavedState.EMPTY_STATE; 13786 } 13787 13788 /** 13789 * Restore this view hierarchy's frozen state from the given container. 13790 * 13791 * @param container The SparseArray which holds previously frozen states. 13792 * 13793 * @see #saveHierarchyState(android.util.SparseArray) 13794 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13795 * @see #onRestoreInstanceState(android.os.Parcelable) 13796 */ 13797 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13798 dispatchRestoreInstanceState(container); 13799 } 13800 13801 /** 13802 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13803 * state for this view and its children. May be overridden to modify how restoring 13804 * happens to a view's children; for example, some views may want to not store state 13805 * for their children. 13806 * 13807 * @param container The SparseArray which holds previously saved state. 13808 * 13809 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13810 * @see #restoreHierarchyState(android.util.SparseArray) 13811 * @see #onRestoreInstanceState(android.os.Parcelable) 13812 */ 13813 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13814 if (mID != NO_ID) { 13815 Parcelable state = container.get(mID); 13816 if (state != null) { 13817 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13818 // + ": " + state); 13819 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13820 onRestoreInstanceState(state); 13821 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13822 throw new IllegalStateException( 13823 "Derived class did not call super.onRestoreInstanceState()"); 13824 } 13825 } 13826 } 13827 } 13828 13829 /** 13830 * Hook allowing a view to re-apply a representation of its internal state that had previously 13831 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13832 * null state. 13833 * 13834 * @param state The frozen state that had previously been returned by 13835 * {@link #onSaveInstanceState}. 13836 * 13837 * @see #onSaveInstanceState() 13838 * @see #restoreHierarchyState(android.util.SparseArray) 13839 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13840 */ 13841 protected void onRestoreInstanceState(Parcelable state) { 13842 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13843 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13844 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13845 + "received " + state.getClass().toString() + " instead. This usually happens " 13846 + "when two views of different type have the same id in the same hierarchy. " 13847 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13848 + "other views do not use the same id."); 13849 } 13850 } 13851 13852 /** 13853 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13854 * 13855 * @return the drawing start time in milliseconds 13856 */ 13857 public long getDrawingTime() { 13858 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13859 } 13860 13861 /** 13862 * <p>Enables or disables the duplication of the parent's state into this view. When 13863 * duplication is enabled, this view gets its drawable state from its parent rather 13864 * than from its own internal properties.</p> 13865 * 13866 * <p>Note: in the current implementation, setting this property to true after the 13867 * view was added to a ViewGroup might have no effect at all. This property should 13868 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13869 * 13870 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13871 * property is enabled, an exception will be thrown.</p> 13872 * 13873 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13874 * parent, these states should not be affected by this method.</p> 13875 * 13876 * @param enabled True to enable duplication of the parent's drawable state, false 13877 * to disable it. 13878 * 13879 * @see #getDrawableState() 13880 * @see #isDuplicateParentStateEnabled() 13881 */ 13882 public void setDuplicateParentStateEnabled(boolean enabled) { 13883 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13884 } 13885 13886 /** 13887 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13888 * 13889 * @return True if this view's drawable state is duplicated from the parent, 13890 * false otherwise 13891 * 13892 * @see #getDrawableState() 13893 * @see #setDuplicateParentStateEnabled(boolean) 13894 */ 13895 public boolean isDuplicateParentStateEnabled() { 13896 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13897 } 13898 13899 /** 13900 * <p>Specifies the type of layer backing this view. The layer can be 13901 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13902 * {@link #LAYER_TYPE_HARDWARE}.</p> 13903 * 13904 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13905 * instance that controls how the layer is composed on screen. The following 13906 * properties of the paint are taken into account when composing the layer:</p> 13907 * <ul> 13908 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13909 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13910 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13911 * </ul> 13912 * 13913 * <p>If this view has an alpha value set to < 1.0 by calling 13914 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13915 * by this view's alpha value.</p> 13916 * 13917 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13918 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13919 * for more information on when and how to use layers.</p> 13920 * 13921 * @param layerType The type of layer to use with this view, must be one of 13922 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13923 * {@link #LAYER_TYPE_HARDWARE} 13924 * @param paint The paint used to compose the layer. This argument is optional 13925 * and can be null. It is ignored when the layer type is 13926 * {@link #LAYER_TYPE_NONE} 13927 * 13928 * @see #getLayerType() 13929 * @see #LAYER_TYPE_NONE 13930 * @see #LAYER_TYPE_SOFTWARE 13931 * @see #LAYER_TYPE_HARDWARE 13932 * @see #setAlpha(float) 13933 * 13934 * @attr ref android.R.styleable#View_layerType 13935 */ 13936 public void setLayerType(int layerType, Paint paint) { 13937 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13938 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13939 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13940 } 13941 13942 boolean typeChanged = mRenderNode.setLayerType(layerType); 13943 13944 if (!typeChanged) { 13945 setLayerPaint(paint); 13946 return; 13947 } 13948 13949 // Destroy any previous software drawing cache if needed 13950 if (mLayerType == LAYER_TYPE_SOFTWARE) { 13951 destroyDrawingCache(); 13952 } 13953 13954 mLayerType = layerType; 13955 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 13956 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13957 mRenderNode.setLayerPaint(mLayerPaint); 13958 13959 // draw() behaves differently if we are on a layer, so we need to 13960 // invalidate() here 13961 invalidateParentCaches(); 13962 invalidate(true); 13963 } 13964 13965 /** 13966 * Updates the {@link Paint} object used with the current layer (used only if the current 13967 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13968 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13969 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13970 * ensure that the view gets redrawn immediately. 13971 * 13972 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13973 * instance that controls how the layer is composed on screen. The following 13974 * properties of the paint are taken into account when composing the layer:</p> 13975 * <ul> 13976 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13977 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13978 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13979 * </ul> 13980 * 13981 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13982 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13983 * 13984 * @param paint The paint used to compose the layer. This argument is optional 13985 * and can be null. It is ignored when the layer type is 13986 * {@link #LAYER_TYPE_NONE} 13987 * 13988 * @see #setLayerType(int, android.graphics.Paint) 13989 */ 13990 public void setLayerPaint(Paint paint) { 13991 int layerType = getLayerType(); 13992 if (layerType != LAYER_TYPE_NONE) { 13993 mLayerPaint = paint == null ? new Paint() : paint; 13994 if (layerType == LAYER_TYPE_HARDWARE) { 13995 if (mRenderNode.setLayerPaint(mLayerPaint)) { 13996 invalidateViewProperty(false, false); 13997 } 13998 } else { 13999 invalidate(); 14000 } 14001 } 14002 } 14003 14004 /** 14005 * Indicates whether this view has a static layer. A view with layer type 14006 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 14007 * dynamic. 14008 */ 14009 boolean hasStaticLayer() { 14010 return true; 14011 } 14012 14013 /** 14014 * Indicates what type of layer is currently associated with this view. By default 14015 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 14016 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 14017 * for more information on the different types of layers. 14018 * 14019 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 14020 * {@link #LAYER_TYPE_HARDWARE} 14021 * 14022 * @see #setLayerType(int, android.graphics.Paint) 14023 * @see #buildLayer() 14024 * @see #LAYER_TYPE_NONE 14025 * @see #LAYER_TYPE_SOFTWARE 14026 * @see #LAYER_TYPE_HARDWARE 14027 */ 14028 public int getLayerType() { 14029 return mLayerType; 14030 } 14031 14032 /** 14033 * Forces this view's layer to be created and this view to be rendered 14034 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 14035 * invoking this method will have no effect. 14036 * 14037 * This method can for instance be used to render a view into its layer before 14038 * starting an animation. If this view is complex, rendering into the layer 14039 * before starting the animation will avoid skipping frames. 14040 * 14041 * @throws IllegalStateException If this view is not attached to a window 14042 * 14043 * @see #setLayerType(int, android.graphics.Paint) 14044 */ 14045 public void buildLayer() { 14046 if (mLayerType == LAYER_TYPE_NONE) return; 14047 14048 final AttachInfo attachInfo = mAttachInfo; 14049 if (attachInfo == null) { 14050 throw new IllegalStateException("This view must be attached to a window first"); 14051 } 14052 14053 if (getWidth() == 0 || getHeight() == 0) { 14054 return; 14055 } 14056 14057 switch (mLayerType) { 14058 case LAYER_TYPE_HARDWARE: 14059 updateDisplayListIfDirty(); 14060 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 14061 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 14062 } 14063 break; 14064 case LAYER_TYPE_SOFTWARE: 14065 buildDrawingCache(true); 14066 break; 14067 } 14068 } 14069 14070 /** 14071 * If this View draws with a HardwareLayer, returns it. 14072 * Otherwise returns null 14073 * 14074 * TODO: Only TextureView uses this, can we eliminate it? 14075 */ 14076 HardwareLayer getHardwareLayer() { 14077 return null; 14078 } 14079 14080 /** 14081 * Destroys all hardware rendering resources. This method is invoked 14082 * when the system needs to reclaim resources. Upon execution of this 14083 * method, you should free any OpenGL resources created by the view. 14084 * 14085 * Note: you <strong>must</strong> call 14086 * <code>super.destroyHardwareResources()</code> when overriding 14087 * this method. 14088 * 14089 * @hide 14090 */ 14091 protected void destroyHardwareResources() { 14092 // Although the Layer will be destroyed by RenderNode, we want to release 14093 // the staging display list, which is also a signal to RenderNode that it's 14094 // safe to free its copy of the display list as it knows that we will 14095 // push an updated DisplayList if we try to draw again 14096 resetDisplayList(); 14097 } 14098 14099 /** 14100 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 14101 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 14102 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 14103 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 14104 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 14105 * null.</p> 14106 * 14107 * <p>Enabling the drawing cache is similar to 14108 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 14109 * acceleration is turned off. When hardware acceleration is turned on, enabling the 14110 * drawing cache has no effect on rendering because the system uses a different mechanism 14111 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 14112 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 14113 * for information on how to enable software and hardware layers.</p> 14114 * 14115 * <p>This API can be used to manually generate 14116 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 14117 * {@link #getDrawingCache()}.</p> 14118 * 14119 * @param enabled true to enable the drawing cache, false otherwise 14120 * 14121 * @see #isDrawingCacheEnabled() 14122 * @see #getDrawingCache() 14123 * @see #buildDrawingCache() 14124 * @see #setLayerType(int, android.graphics.Paint) 14125 */ 14126 public void setDrawingCacheEnabled(boolean enabled) { 14127 mCachingFailed = false; 14128 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 14129 } 14130 14131 /** 14132 * <p>Indicates whether the drawing cache is enabled for this view.</p> 14133 * 14134 * @return true if the drawing cache is enabled 14135 * 14136 * @see #setDrawingCacheEnabled(boolean) 14137 * @see #getDrawingCache() 14138 */ 14139 @ViewDebug.ExportedProperty(category = "drawing") 14140 public boolean isDrawingCacheEnabled() { 14141 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 14142 } 14143 14144 /** 14145 * Debugging utility which recursively outputs the dirty state of a view and its 14146 * descendants. 14147 * 14148 * @hide 14149 */ 14150 @SuppressWarnings({"UnusedDeclaration"}) 14151 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 14152 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 14153 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 14154 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 14155 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 14156 if (clear) { 14157 mPrivateFlags &= clearMask; 14158 } 14159 if (this instanceof ViewGroup) { 14160 ViewGroup parent = (ViewGroup) this; 14161 final int count = parent.getChildCount(); 14162 for (int i = 0; i < count; i++) { 14163 final View child = parent.getChildAt(i); 14164 child.outputDirtyFlags(indent + " ", clear, clearMask); 14165 } 14166 } 14167 } 14168 14169 /** 14170 * This method is used by ViewGroup to cause its children to restore or recreate their 14171 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 14172 * to recreate its own display list, which would happen if it went through the normal 14173 * draw/dispatchDraw mechanisms. 14174 * 14175 * @hide 14176 */ 14177 protected void dispatchGetDisplayList() {} 14178 14179 /** 14180 * A view that is not attached or hardware accelerated cannot create a display list. 14181 * This method checks these conditions and returns the appropriate result. 14182 * 14183 * @return true if view has the ability to create a display list, false otherwise. 14184 * 14185 * @hide 14186 */ 14187 public boolean canHaveDisplayList() { 14188 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 14189 } 14190 14191 private void updateDisplayListIfDirty() { 14192 final RenderNode renderNode = mRenderNode; 14193 if (!canHaveDisplayList()) { 14194 // can't populate RenderNode, don't try 14195 return; 14196 } 14197 14198 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 14199 || !renderNode.isValid() 14200 || (mRecreateDisplayList)) { 14201 // Don't need to recreate the display list, just need to tell our 14202 // children to restore/recreate theirs 14203 if (renderNode.isValid() 14204 && !mRecreateDisplayList) { 14205 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14206 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14207 dispatchGetDisplayList(); 14208 14209 return; // no work needed 14210 } 14211 14212 // If we got here, we're recreating it. Mark it as such to ensure that 14213 // we copy in child display lists into ours in drawChild() 14214 mRecreateDisplayList = true; 14215 14216 int width = mRight - mLeft; 14217 int height = mBottom - mTop; 14218 int layerType = getLayerType(); 14219 14220 final HardwareCanvas canvas = renderNode.start(width, height); 14221 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 14222 14223 try { 14224 final HardwareLayer layer = getHardwareLayer(); 14225 if (layer != null && layer.isValid()) { 14226 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 14227 } else if (layerType == LAYER_TYPE_SOFTWARE) { 14228 buildDrawingCache(true); 14229 Bitmap cache = getDrawingCache(true); 14230 if (cache != null) { 14231 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 14232 } 14233 } else { 14234 computeScroll(); 14235 14236 canvas.translate(-mScrollX, -mScrollY); 14237 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14238 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14239 14240 // Fast path for layouts with no backgrounds 14241 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14242 dispatchDraw(canvas); 14243 if (mOverlay != null && !mOverlay.isEmpty()) { 14244 mOverlay.getOverlayView().draw(canvas); 14245 } 14246 } else { 14247 draw(canvas); 14248 } 14249 } 14250 } finally { 14251 renderNode.end(canvas); 14252 setDisplayListProperties(renderNode); 14253 } 14254 } else { 14255 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14256 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14257 } 14258 } 14259 14260 /** 14261 * Returns a RenderNode with View draw content recorded, which can be 14262 * used to draw this view again without executing its draw method. 14263 * 14264 * @return A RenderNode ready to replay, or null if caching is not enabled. 14265 * 14266 * @hide 14267 */ 14268 public RenderNode getDisplayList() { 14269 updateDisplayListIfDirty(); 14270 return mRenderNode; 14271 } 14272 14273 private void resetDisplayList() { 14274 if (mRenderNode.isValid()) { 14275 mRenderNode.destroyDisplayListData(); 14276 } 14277 14278 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 14279 mBackgroundRenderNode.destroyDisplayListData(); 14280 } 14281 } 14282 14283 /** 14284 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 14285 * 14286 * @return A non-scaled bitmap representing this view or null if cache is disabled. 14287 * 14288 * @see #getDrawingCache(boolean) 14289 */ 14290 public Bitmap getDrawingCache() { 14291 return getDrawingCache(false); 14292 } 14293 14294 /** 14295 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 14296 * is null when caching is disabled. If caching is enabled and the cache is not ready, 14297 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 14298 * draw from the cache when the cache is enabled. To benefit from the cache, you must 14299 * request the drawing cache by calling this method and draw it on screen if the 14300 * returned bitmap is not null.</p> 14301 * 14302 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14303 * this method will create a bitmap of the same size as this view. Because this bitmap 14304 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14305 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14306 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14307 * size than the view. This implies that your application must be able to handle this 14308 * size.</p> 14309 * 14310 * @param autoScale Indicates whether the generated bitmap should be scaled based on 14311 * the current density of the screen when the application is in compatibility 14312 * mode. 14313 * 14314 * @return A bitmap representing this view or null if cache is disabled. 14315 * 14316 * @see #setDrawingCacheEnabled(boolean) 14317 * @see #isDrawingCacheEnabled() 14318 * @see #buildDrawingCache(boolean) 14319 * @see #destroyDrawingCache() 14320 */ 14321 public Bitmap getDrawingCache(boolean autoScale) { 14322 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 14323 return null; 14324 } 14325 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 14326 buildDrawingCache(autoScale); 14327 } 14328 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 14329 } 14330 14331 /** 14332 * <p>Frees the resources used by the drawing cache. If you call 14333 * {@link #buildDrawingCache()} manually without calling 14334 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14335 * should cleanup the cache with this method afterwards.</p> 14336 * 14337 * @see #setDrawingCacheEnabled(boolean) 14338 * @see #buildDrawingCache() 14339 * @see #getDrawingCache() 14340 */ 14341 public void destroyDrawingCache() { 14342 if (mDrawingCache != null) { 14343 mDrawingCache.recycle(); 14344 mDrawingCache = null; 14345 } 14346 if (mUnscaledDrawingCache != null) { 14347 mUnscaledDrawingCache.recycle(); 14348 mUnscaledDrawingCache = null; 14349 } 14350 } 14351 14352 /** 14353 * Setting a solid background color for the drawing cache's bitmaps will improve 14354 * performance and memory usage. Note, though that this should only be used if this 14355 * view will always be drawn on top of a solid color. 14356 * 14357 * @param color The background color to use for the drawing cache's bitmap 14358 * 14359 * @see #setDrawingCacheEnabled(boolean) 14360 * @see #buildDrawingCache() 14361 * @see #getDrawingCache() 14362 */ 14363 public void setDrawingCacheBackgroundColor(int color) { 14364 if (color != mDrawingCacheBackgroundColor) { 14365 mDrawingCacheBackgroundColor = color; 14366 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 14367 } 14368 } 14369 14370 /** 14371 * @see #setDrawingCacheBackgroundColor(int) 14372 * 14373 * @return The background color to used for the drawing cache's bitmap 14374 */ 14375 public int getDrawingCacheBackgroundColor() { 14376 return mDrawingCacheBackgroundColor; 14377 } 14378 14379 /** 14380 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 14381 * 14382 * @see #buildDrawingCache(boolean) 14383 */ 14384 public void buildDrawingCache() { 14385 buildDrawingCache(false); 14386 } 14387 14388 /** 14389 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 14390 * 14391 * <p>If you call {@link #buildDrawingCache()} manually without calling 14392 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14393 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 14394 * 14395 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14396 * this method will create a bitmap of the same size as this view. Because this bitmap 14397 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14398 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14399 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14400 * size than the view. This implies that your application must be able to handle this 14401 * size.</p> 14402 * 14403 * <p>You should avoid calling this method when hardware acceleration is enabled. If 14404 * you do not need the drawing cache bitmap, calling this method will increase memory 14405 * usage and cause the view to be rendered in software once, thus negatively impacting 14406 * performance.</p> 14407 * 14408 * @see #getDrawingCache() 14409 * @see #destroyDrawingCache() 14410 */ 14411 public void buildDrawingCache(boolean autoScale) { 14412 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 14413 mDrawingCache == null : mUnscaledDrawingCache == null)) { 14414 mCachingFailed = false; 14415 14416 int width = mRight - mLeft; 14417 int height = mBottom - mTop; 14418 14419 final AttachInfo attachInfo = mAttachInfo; 14420 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 14421 14422 if (autoScale && scalingRequired) { 14423 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 14424 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 14425 } 14426 14427 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 14428 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 14429 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 14430 14431 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 14432 final long drawingCacheSize = 14433 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 14434 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 14435 if (width > 0 && height > 0) { 14436 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 14437 + projectedBitmapSize + " bytes, only " 14438 + drawingCacheSize + " available"); 14439 } 14440 destroyDrawingCache(); 14441 mCachingFailed = true; 14442 return; 14443 } 14444 14445 boolean clear = true; 14446 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 14447 14448 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 14449 Bitmap.Config quality; 14450 if (!opaque) { 14451 // Never pick ARGB_4444 because it looks awful 14452 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 14453 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 14454 case DRAWING_CACHE_QUALITY_AUTO: 14455 case DRAWING_CACHE_QUALITY_LOW: 14456 case DRAWING_CACHE_QUALITY_HIGH: 14457 default: 14458 quality = Bitmap.Config.ARGB_8888; 14459 break; 14460 } 14461 } else { 14462 // Optimization for translucent windows 14463 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 14464 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 14465 } 14466 14467 // Try to cleanup memory 14468 if (bitmap != null) bitmap.recycle(); 14469 14470 try { 14471 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14472 width, height, quality); 14473 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14474 if (autoScale) { 14475 mDrawingCache = bitmap; 14476 } else { 14477 mUnscaledDrawingCache = bitmap; 14478 } 14479 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14480 } catch (OutOfMemoryError e) { 14481 // If there is not enough memory to create the bitmap cache, just 14482 // ignore the issue as bitmap caches are not required to draw the 14483 // view hierarchy 14484 if (autoScale) { 14485 mDrawingCache = null; 14486 } else { 14487 mUnscaledDrawingCache = null; 14488 } 14489 mCachingFailed = true; 14490 return; 14491 } 14492 14493 clear = drawingCacheBackgroundColor != 0; 14494 } 14495 14496 Canvas canvas; 14497 if (attachInfo != null) { 14498 canvas = attachInfo.mCanvas; 14499 if (canvas == null) { 14500 canvas = new Canvas(); 14501 } 14502 canvas.setBitmap(bitmap); 14503 // Temporarily clobber the cached Canvas in case one of our children 14504 // is also using a drawing cache. Without this, the children would 14505 // steal the canvas by attaching their own bitmap to it and bad, bad 14506 // thing would happen (invisible views, corrupted drawings, etc.) 14507 attachInfo.mCanvas = null; 14508 } else { 14509 // This case should hopefully never or seldom happen 14510 canvas = new Canvas(bitmap); 14511 } 14512 14513 if (clear) { 14514 bitmap.eraseColor(drawingCacheBackgroundColor); 14515 } 14516 14517 computeScroll(); 14518 final int restoreCount = canvas.save(); 14519 14520 if (autoScale && scalingRequired) { 14521 final float scale = attachInfo.mApplicationScale; 14522 canvas.scale(scale, scale); 14523 } 14524 14525 canvas.translate(-mScrollX, -mScrollY); 14526 14527 mPrivateFlags |= PFLAG_DRAWN; 14528 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14529 mLayerType != LAYER_TYPE_NONE) { 14530 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14531 } 14532 14533 // Fast path for layouts with no backgrounds 14534 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14535 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14536 dispatchDraw(canvas); 14537 if (mOverlay != null && !mOverlay.isEmpty()) { 14538 mOverlay.getOverlayView().draw(canvas); 14539 } 14540 } else { 14541 draw(canvas); 14542 } 14543 14544 canvas.restoreToCount(restoreCount); 14545 canvas.setBitmap(null); 14546 14547 if (attachInfo != null) { 14548 // Restore the cached Canvas for our siblings 14549 attachInfo.mCanvas = canvas; 14550 } 14551 } 14552 } 14553 14554 /** 14555 * Create a snapshot of the view into a bitmap. We should probably make 14556 * some form of this public, but should think about the API. 14557 */ 14558 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14559 int width = mRight - mLeft; 14560 int height = mBottom - mTop; 14561 14562 final AttachInfo attachInfo = mAttachInfo; 14563 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14564 width = (int) ((width * scale) + 0.5f); 14565 height = (int) ((height * scale) + 0.5f); 14566 14567 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14568 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14569 if (bitmap == null) { 14570 throw new OutOfMemoryError(); 14571 } 14572 14573 Resources resources = getResources(); 14574 if (resources != null) { 14575 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14576 } 14577 14578 Canvas canvas; 14579 if (attachInfo != null) { 14580 canvas = attachInfo.mCanvas; 14581 if (canvas == null) { 14582 canvas = new Canvas(); 14583 } 14584 canvas.setBitmap(bitmap); 14585 // Temporarily clobber the cached Canvas in case one of our children 14586 // is also using a drawing cache. Without this, the children would 14587 // steal the canvas by attaching their own bitmap to it and bad, bad 14588 // things would happen (invisible views, corrupted drawings, etc.) 14589 attachInfo.mCanvas = null; 14590 } else { 14591 // This case should hopefully never or seldom happen 14592 canvas = new Canvas(bitmap); 14593 } 14594 14595 if ((backgroundColor & 0xff000000) != 0) { 14596 bitmap.eraseColor(backgroundColor); 14597 } 14598 14599 computeScroll(); 14600 final int restoreCount = canvas.save(); 14601 canvas.scale(scale, scale); 14602 canvas.translate(-mScrollX, -mScrollY); 14603 14604 // Temporarily remove the dirty mask 14605 int flags = mPrivateFlags; 14606 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14607 14608 // Fast path for layouts with no backgrounds 14609 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14610 dispatchDraw(canvas); 14611 if (mOverlay != null && !mOverlay.isEmpty()) { 14612 mOverlay.getOverlayView().draw(canvas); 14613 } 14614 } else { 14615 draw(canvas); 14616 } 14617 14618 mPrivateFlags = flags; 14619 14620 canvas.restoreToCount(restoreCount); 14621 canvas.setBitmap(null); 14622 14623 if (attachInfo != null) { 14624 // Restore the cached Canvas for our siblings 14625 attachInfo.mCanvas = canvas; 14626 } 14627 14628 return bitmap; 14629 } 14630 14631 /** 14632 * Indicates whether this View is currently in edit mode. A View is usually 14633 * in edit mode when displayed within a developer tool. For instance, if 14634 * this View is being drawn by a visual user interface builder, this method 14635 * should return true. 14636 * 14637 * Subclasses should check the return value of this method to provide 14638 * different behaviors if their normal behavior might interfere with the 14639 * host environment. For instance: the class spawns a thread in its 14640 * constructor, the drawing code relies on device-specific features, etc. 14641 * 14642 * This method is usually checked in the drawing code of custom widgets. 14643 * 14644 * @return True if this View is in edit mode, false otherwise. 14645 */ 14646 public boolean isInEditMode() { 14647 return false; 14648 } 14649 14650 /** 14651 * If the View draws content inside its padding and enables fading edges, 14652 * it needs to support padding offsets. Padding offsets are added to the 14653 * fading edges to extend the length of the fade so that it covers pixels 14654 * drawn inside the padding. 14655 * 14656 * Subclasses of this class should override this method if they need 14657 * to draw content inside the padding. 14658 * 14659 * @return True if padding offset must be applied, false otherwise. 14660 * 14661 * @see #getLeftPaddingOffset() 14662 * @see #getRightPaddingOffset() 14663 * @see #getTopPaddingOffset() 14664 * @see #getBottomPaddingOffset() 14665 * 14666 * @since CURRENT 14667 */ 14668 protected boolean isPaddingOffsetRequired() { 14669 return false; 14670 } 14671 14672 /** 14673 * Amount by which to extend the left fading region. Called only when 14674 * {@link #isPaddingOffsetRequired()} returns true. 14675 * 14676 * @return The left padding offset in pixels. 14677 * 14678 * @see #isPaddingOffsetRequired() 14679 * 14680 * @since CURRENT 14681 */ 14682 protected int getLeftPaddingOffset() { 14683 return 0; 14684 } 14685 14686 /** 14687 * Amount by which to extend the right fading region. Called only when 14688 * {@link #isPaddingOffsetRequired()} returns true. 14689 * 14690 * @return The right padding offset in pixels. 14691 * 14692 * @see #isPaddingOffsetRequired() 14693 * 14694 * @since CURRENT 14695 */ 14696 protected int getRightPaddingOffset() { 14697 return 0; 14698 } 14699 14700 /** 14701 * Amount by which to extend the top fading region. Called only when 14702 * {@link #isPaddingOffsetRequired()} returns true. 14703 * 14704 * @return The top padding offset in pixels. 14705 * 14706 * @see #isPaddingOffsetRequired() 14707 * 14708 * @since CURRENT 14709 */ 14710 protected int getTopPaddingOffset() { 14711 return 0; 14712 } 14713 14714 /** 14715 * Amount by which to extend the bottom fading region. Called only when 14716 * {@link #isPaddingOffsetRequired()} returns true. 14717 * 14718 * @return The bottom padding offset in pixels. 14719 * 14720 * @see #isPaddingOffsetRequired() 14721 * 14722 * @since CURRENT 14723 */ 14724 protected int getBottomPaddingOffset() { 14725 return 0; 14726 } 14727 14728 /** 14729 * @hide 14730 * @param offsetRequired 14731 */ 14732 protected int getFadeTop(boolean offsetRequired) { 14733 int top = mPaddingTop; 14734 if (offsetRequired) top += getTopPaddingOffset(); 14735 return top; 14736 } 14737 14738 /** 14739 * @hide 14740 * @param offsetRequired 14741 */ 14742 protected int getFadeHeight(boolean offsetRequired) { 14743 int padding = mPaddingTop; 14744 if (offsetRequired) padding += getTopPaddingOffset(); 14745 return mBottom - mTop - mPaddingBottom - padding; 14746 } 14747 14748 /** 14749 * <p>Indicates whether this view is attached to a hardware accelerated 14750 * window or not.</p> 14751 * 14752 * <p>Even if this method returns true, it does not mean that every call 14753 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14754 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14755 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14756 * window is hardware accelerated, 14757 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14758 * return false, and this method will return true.</p> 14759 * 14760 * @return True if the view is attached to a window and the window is 14761 * hardware accelerated; false in any other case. 14762 */ 14763 @ViewDebug.ExportedProperty(category = "drawing") 14764 public boolean isHardwareAccelerated() { 14765 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14766 } 14767 14768 /** 14769 * Sets a rectangular area on this view to which the view will be clipped 14770 * when it is drawn. Setting the value to null will remove the clip bounds 14771 * and the view will draw normally, using its full bounds. 14772 * 14773 * @param clipBounds The rectangular area, in the local coordinates of 14774 * this view, to which future drawing operations will be clipped. 14775 */ 14776 public void setClipBounds(Rect clipBounds) { 14777 if (clipBounds == mClipBounds 14778 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 14779 return; 14780 } 14781 if (clipBounds != null) { 14782 if (mClipBounds == null) { 14783 mClipBounds = new Rect(clipBounds); 14784 } else { 14785 mClipBounds.set(clipBounds); 14786 } 14787 } else { 14788 mClipBounds = null; 14789 } 14790 mRenderNode.setClipBounds(mClipBounds); 14791 invalidateViewProperty(false, false); 14792 } 14793 14794 /** 14795 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14796 * 14797 * @return A copy of the current clip bounds if clip bounds are set, 14798 * otherwise null. 14799 */ 14800 public Rect getClipBounds() { 14801 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14802 } 14803 14804 /** 14805 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14806 * case of an active Animation being run on the view. 14807 */ 14808 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14809 Animation a, boolean scalingRequired) { 14810 Transformation invalidationTransform; 14811 final int flags = parent.mGroupFlags; 14812 final boolean initialized = a.isInitialized(); 14813 if (!initialized) { 14814 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14815 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14816 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14817 onAnimationStart(); 14818 } 14819 14820 final Transformation t = parent.getChildTransformation(); 14821 boolean more = a.getTransformation(drawingTime, t, 1f); 14822 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14823 if (parent.mInvalidationTransformation == null) { 14824 parent.mInvalidationTransformation = new Transformation(); 14825 } 14826 invalidationTransform = parent.mInvalidationTransformation; 14827 a.getTransformation(drawingTime, invalidationTransform, 1f); 14828 } else { 14829 invalidationTransform = t; 14830 } 14831 14832 if (more) { 14833 if (!a.willChangeBounds()) { 14834 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14835 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14836 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14837 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14838 // The child need to draw an animation, potentially offscreen, so 14839 // make sure we do not cancel invalidate requests 14840 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14841 parent.invalidate(mLeft, mTop, mRight, mBottom); 14842 } 14843 } else { 14844 if (parent.mInvalidateRegion == null) { 14845 parent.mInvalidateRegion = new RectF(); 14846 } 14847 final RectF region = parent.mInvalidateRegion; 14848 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14849 invalidationTransform); 14850 14851 // The child need to draw an animation, potentially offscreen, so 14852 // make sure we do not cancel invalidate requests 14853 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14854 14855 final int left = mLeft + (int) region.left; 14856 final int top = mTop + (int) region.top; 14857 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14858 top + (int) (region.height() + .5f)); 14859 } 14860 } 14861 return more; 14862 } 14863 14864 /** 14865 * This method is called by getDisplayList() when a display list is recorded for a View. 14866 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14867 */ 14868 void setDisplayListProperties(RenderNode renderNode) { 14869 if (renderNode != null) { 14870 if ((mPrivateFlags3 & PFLAG3_OUTLINE_INVALID) != 0) { 14871 rebuildOutline(); 14872 mPrivateFlags3 &= ~PFLAG3_OUTLINE_INVALID; 14873 } 14874 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14875 if (mParent instanceof ViewGroup) { 14876 renderNode.setClipToBounds( 14877 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14878 } 14879 float alpha = 1; 14880 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14881 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14882 ViewGroup parentVG = (ViewGroup) mParent; 14883 final Transformation t = parentVG.getChildTransformation(); 14884 if (parentVG.getChildStaticTransformation(this, t)) { 14885 final int transformType = t.getTransformationType(); 14886 if (transformType != Transformation.TYPE_IDENTITY) { 14887 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14888 alpha = t.getAlpha(); 14889 } 14890 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14891 renderNode.setStaticMatrix(t.getMatrix()); 14892 } 14893 } 14894 } 14895 } 14896 if (mTransformationInfo != null) { 14897 alpha *= getFinalAlpha(); 14898 if (alpha < 1) { 14899 final int multipliedAlpha = (int) (255 * alpha); 14900 if (onSetAlpha(multipliedAlpha)) { 14901 alpha = 1; 14902 } 14903 } 14904 renderNode.setAlpha(alpha); 14905 } else if (alpha < 1) { 14906 renderNode.setAlpha(alpha); 14907 } 14908 } 14909 } 14910 14911 /** 14912 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14913 * This draw() method is an implementation detail and is not intended to be overridden or 14914 * to be called from anywhere else other than ViewGroup.drawChild(). 14915 */ 14916 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14917 boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14918 boolean more = false; 14919 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14920 final int flags = parent.mGroupFlags; 14921 14922 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14923 parent.getChildTransformation().clear(); 14924 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14925 } 14926 14927 Transformation transformToApply = null; 14928 boolean concatMatrix = false; 14929 14930 boolean scalingRequired = false; 14931 boolean caching; 14932 int layerType = getLayerType(); 14933 14934 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14935 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14936 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14937 caching = true; 14938 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14939 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14940 } else { 14941 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14942 } 14943 14944 final Animation a = getAnimation(); 14945 if (a != null) { 14946 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14947 concatMatrix = a.willChangeTransformationMatrix(); 14948 if (concatMatrix) { 14949 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14950 } 14951 transformToApply = parent.getChildTransformation(); 14952 } else { 14953 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14954 // No longer animating: clear out old animation matrix 14955 mRenderNode.setAnimationMatrix(null); 14956 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14957 } 14958 if (!usingRenderNodeProperties && 14959 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14960 final Transformation t = parent.getChildTransformation(); 14961 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14962 if (hasTransform) { 14963 final int transformType = t.getTransformationType(); 14964 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14965 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14966 } 14967 } 14968 } 14969 14970 concatMatrix |= !childHasIdentityMatrix; 14971 14972 // Sets the flag as early as possible to allow draw() implementations 14973 // to call invalidate() successfully when doing animations 14974 mPrivateFlags |= PFLAG_DRAWN; 14975 14976 if (!concatMatrix && 14977 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14978 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14979 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14980 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14981 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14982 return more; 14983 } 14984 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14985 14986 if (hardwareAccelerated) { 14987 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14988 // retain the flag's value temporarily in the mRecreateDisplayList flag 14989 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14990 mPrivateFlags &= ~PFLAG_INVALIDATED; 14991 } 14992 14993 RenderNode renderNode = null; 14994 Bitmap cache = null; 14995 boolean hasDisplayList = false; 14996 if (caching) { 14997 if (!hardwareAccelerated) { 14998 if (layerType != LAYER_TYPE_NONE) { 14999 layerType = LAYER_TYPE_SOFTWARE; 15000 buildDrawingCache(true); 15001 } 15002 cache = getDrawingCache(true); 15003 } else { 15004 switch (layerType) { 15005 case LAYER_TYPE_SOFTWARE: 15006 if (usingRenderNodeProperties) { 15007 hasDisplayList = canHaveDisplayList(); 15008 } else { 15009 buildDrawingCache(true); 15010 cache = getDrawingCache(true); 15011 } 15012 break; 15013 case LAYER_TYPE_HARDWARE: 15014 if (usingRenderNodeProperties) { 15015 hasDisplayList = canHaveDisplayList(); 15016 } 15017 break; 15018 case LAYER_TYPE_NONE: 15019 // Delay getting the display list until animation-driven alpha values are 15020 // set up and possibly passed on to the view 15021 hasDisplayList = canHaveDisplayList(); 15022 break; 15023 } 15024 } 15025 } 15026 usingRenderNodeProperties &= hasDisplayList; 15027 if (usingRenderNodeProperties) { 15028 renderNode = getDisplayList(); 15029 if (!renderNode.isValid()) { 15030 // Uncommon, but possible. If a view is removed from the hierarchy during the call 15031 // to getDisplayList(), the display list will be marked invalid and we should not 15032 // try to use it again. 15033 renderNode = null; 15034 hasDisplayList = false; 15035 usingRenderNodeProperties = false; 15036 } 15037 } 15038 15039 int sx = 0; 15040 int sy = 0; 15041 if (!hasDisplayList) { 15042 computeScroll(); 15043 sx = mScrollX; 15044 sy = mScrollY; 15045 } 15046 15047 final boolean hasNoCache = cache == null || hasDisplayList; 15048 final boolean offsetForScroll = cache == null && !hasDisplayList && 15049 layerType != LAYER_TYPE_HARDWARE; 15050 15051 int restoreTo = -1; 15052 if (!usingRenderNodeProperties || transformToApply != null) { 15053 restoreTo = canvas.save(); 15054 } 15055 if (offsetForScroll) { 15056 canvas.translate(mLeft - sx, mTop - sy); 15057 } else { 15058 if (!usingRenderNodeProperties) { 15059 canvas.translate(mLeft, mTop); 15060 } 15061 if (scalingRequired) { 15062 if (usingRenderNodeProperties) { 15063 // TODO: Might not need this if we put everything inside the DL 15064 restoreTo = canvas.save(); 15065 } 15066 // mAttachInfo cannot be null, otherwise scalingRequired == false 15067 final float scale = 1.0f / mAttachInfo.mApplicationScale; 15068 canvas.scale(scale, scale); 15069 } 15070 } 15071 15072 float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha()); 15073 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 15074 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 15075 if (transformToApply != null || !childHasIdentityMatrix) { 15076 int transX = 0; 15077 int transY = 0; 15078 15079 if (offsetForScroll) { 15080 transX = -sx; 15081 transY = -sy; 15082 } 15083 15084 if (transformToApply != null) { 15085 if (concatMatrix) { 15086 if (usingRenderNodeProperties) { 15087 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 15088 } else { 15089 // Undo the scroll translation, apply the transformation matrix, 15090 // then redo the scroll translate to get the correct result. 15091 canvas.translate(-transX, -transY); 15092 canvas.concat(transformToApply.getMatrix()); 15093 canvas.translate(transX, transY); 15094 } 15095 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15096 } 15097 15098 float transformAlpha = transformToApply.getAlpha(); 15099 if (transformAlpha < 1) { 15100 alpha *= transformAlpha; 15101 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15102 } 15103 } 15104 15105 if (!childHasIdentityMatrix && !usingRenderNodeProperties) { 15106 canvas.translate(-transX, -transY); 15107 canvas.concat(getMatrix()); 15108 canvas.translate(transX, transY); 15109 } 15110 } 15111 15112 // Deal with alpha if it is or used to be <1 15113 if (alpha < 1 || 15114 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 15115 if (alpha < 1) { 15116 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 15117 } else { 15118 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 15119 } 15120 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15121 if (hasNoCache) { 15122 final int multipliedAlpha = (int) (255 * alpha); 15123 if (!onSetAlpha(multipliedAlpha)) { 15124 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 15125 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 15126 layerType != LAYER_TYPE_NONE) { 15127 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 15128 } 15129 if (usingRenderNodeProperties) { 15130 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 15131 } else if (layerType == LAYER_TYPE_NONE) { 15132 final int scrollX = hasDisplayList ? 0 : sx; 15133 final int scrollY = hasDisplayList ? 0 : sy; 15134 canvas.saveLayerAlpha(scrollX, scrollY, 15135 scrollX + (mRight - mLeft), scrollY + (mBottom - mTop), 15136 multipliedAlpha, layerFlags); 15137 } 15138 } else { 15139 // Alpha is handled by the child directly, clobber the layer's alpha 15140 mPrivateFlags |= PFLAG_ALPHA_SET; 15141 } 15142 } 15143 } 15144 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 15145 onSetAlpha(255); 15146 mPrivateFlags &= ~PFLAG_ALPHA_SET; 15147 } 15148 15149 if (!usingRenderNodeProperties) { 15150 // apply clips directly, since RenderNode won't do it for this draw 15151 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN 15152 && cache == null) { 15153 if (offsetForScroll) { 15154 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 15155 } else { 15156 if (!scalingRequired || cache == null) { 15157 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 15158 } else { 15159 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 15160 } 15161 } 15162 } 15163 15164 if (mClipBounds != null) { 15165 // clip bounds ignore scroll 15166 canvas.clipRect(mClipBounds); 15167 } 15168 } 15169 15170 15171 15172 if (!usingRenderNodeProperties && hasDisplayList) { 15173 renderNode = getDisplayList(); 15174 if (!renderNode.isValid()) { 15175 // Uncommon, but possible. If a view is removed from the hierarchy during the call 15176 // to getDisplayList(), the display list will be marked invalid and we should not 15177 // try to use it again. 15178 renderNode = null; 15179 hasDisplayList = false; 15180 } 15181 } 15182 15183 if (hasNoCache) { 15184 boolean layerRendered = false; 15185 if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) { 15186 final HardwareLayer layer = getHardwareLayer(); 15187 if (layer != null && layer.isValid()) { 15188 int restoreAlpha = mLayerPaint.getAlpha(); 15189 mLayerPaint.setAlpha((int) (alpha * 255)); 15190 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 15191 mLayerPaint.setAlpha(restoreAlpha); 15192 layerRendered = true; 15193 } else { 15194 final int scrollX = hasDisplayList ? 0 : sx; 15195 final int scrollY = hasDisplayList ? 0 : sy; 15196 canvas.saveLayer(scrollX, scrollY, 15197 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 15198 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 15199 } 15200 } 15201 15202 if (!layerRendered) { 15203 if (!hasDisplayList) { 15204 // Fast path for layouts with no backgrounds 15205 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15206 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15207 dispatchDraw(canvas); 15208 } else { 15209 draw(canvas); 15210 } 15211 } else { 15212 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15213 ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags); 15214 } 15215 } 15216 } else if (cache != null) { 15217 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15218 Paint cachePaint; 15219 int restoreAlpha = 0; 15220 15221 if (layerType == LAYER_TYPE_NONE) { 15222 cachePaint = parent.mCachePaint; 15223 if (cachePaint == null) { 15224 cachePaint = new Paint(); 15225 cachePaint.setDither(false); 15226 parent.mCachePaint = cachePaint; 15227 } 15228 } else { 15229 cachePaint = mLayerPaint; 15230 restoreAlpha = mLayerPaint.getAlpha(); 15231 } 15232 cachePaint.setAlpha((int) (alpha * 255)); 15233 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 15234 cachePaint.setAlpha(restoreAlpha); 15235 } 15236 15237 if (restoreTo >= 0) { 15238 canvas.restoreToCount(restoreTo); 15239 } 15240 15241 if (a != null && !more) { 15242 if (!hardwareAccelerated && !a.getFillAfter()) { 15243 onSetAlpha(255); 15244 } 15245 parent.finishAnimatingView(this, a); 15246 } 15247 15248 if (more && hardwareAccelerated) { 15249 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 15250 // alpha animations should cause the child to recreate its display list 15251 invalidate(true); 15252 } 15253 } 15254 15255 mRecreateDisplayList = false; 15256 15257 return more; 15258 } 15259 15260 /** 15261 * Manually render this view (and all of its children) to the given Canvas. 15262 * The view must have already done a full layout before this function is 15263 * called. When implementing a view, implement 15264 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 15265 * If you do need to override this method, call the superclass version. 15266 * 15267 * @param canvas The Canvas to which the View is rendered. 15268 */ 15269 public void draw(Canvas canvas) { 15270 final int privateFlags = mPrivateFlags; 15271 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 15272 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 15273 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 15274 15275 /* 15276 * Draw traversal performs several drawing steps which must be executed 15277 * in the appropriate order: 15278 * 15279 * 1. Draw the background 15280 * 2. If necessary, save the canvas' layers to prepare for fading 15281 * 3. Draw view's content 15282 * 4. Draw children 15283 * 5. If necessary, draw the fading edges and restore layers 15284 * 6. Draw decorations (scrollbars for instance) 15285 */ 15286 15287 // Step 1, draw the background, if needed 15288 int saveCount; 15289 15290 if (!dirtyOpaque) { 15291 drawBackground(canvas); 15292 } 15293 15294 // skip step 2 & 5 if possible (common case) 15295 final int viewFlags = mViewFlags; 15296 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 15297 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 15298 if (!verticalEdges && !horizontalEdges) { 15299 // Step 3, draw the content 15300 if (!dirtyOpaque) onDraw(canvas); 15301 15302 // Step 4, draw the children 15303 dispatchDraw(canvas); 15304 15305 // Step 6, draw decorations (scrollbars) 15306 onDrawScrollBars(canvas); 15307 15308 if (mOverlay != null && !mOverlay.isEmpty()) { 15309 mOverlay.getOverlayView().dispatchDraw(canvas); 15310 } 15311 15312 // we're done... 15313 return; 15314 } 15315 15316 /* 15317 * Here we do the full fledged routine... 15318 * (this is an uncommon case where speed matters less, 15319 * this is why we repeat some of the tests that have been 15320 * done above) 15321 */ 15322 15323 boolean drawTop = false; 15324 boolean drawBottom = false; 15325 boolean drawLeft = false; 15326 boolean drawRight = false; 15327 15328 float topFadeStrength = 0.0f; 15329 float bottomFadeStrength = 0.0f; 15330 float leftFadeStrength = 0.0f; 15331 float rightFadeStrength = 0.0f; 15332 15333 // Step 2, save the canvas' layers 15334 int paddingLeft = mPaddingLeft; 15335 15336 final boolean offsetRequired = isPaddingOffsetRequired(); 15337 if (offsetRequired) { 15338 paddingLeft += getLeftPaddingOffset(); 15339 } 15340 15341 int left = mScrollX + paddingLeft; 15342 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 15343 int top = mScrollY + getFadeTop(offsetRequired); 15344 int bottom = top + getFadeHeight(offsetRequired); 15345 15346 if (offsetRequired) { 15347 right += getRightPaddingOffset(); 15348 bottom += getBottomPaddingOffset(); 15349 } 15350 15351 final ScrollabilityCache scrollabilityCache = mScrollCache; 15352 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 15353 int length = (int) fadeHeight; 15354 15355 // clip the fade length if top and bottom fades overlap 15356 // overlapping fades produce odd-looking artifacts 15357 if (verticalEdges && (top + length > bottom - length)) { 15358 length = (bottom - top) / 2; 15359 } 15360 15361 // also clip horizontal fades if necessary 15362 if (horizontalEdges && (left + length > right - length)) { 15363 length = (right - left) / 2; 15364 } 15365 15366 if (verticalEdges) { 15367 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 15368 drawTop = topFadeStrength * fadeHeight > 1.0f; 15369 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 15370 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 15371 } 15372 15373 if (horizontalEdges) { 15374 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 15375 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 15376 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 15377 drawRight = rightFadeStrength * fadeHeight > 1.0f; 15378 } 15379 15380 saveCount = canvas.getSaveCount(); 15381 15382 int solidColor = getSolidColor(); 15383 if (solidColor == 0) { 15384 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 15385 15386 if (drawTop) { 15387 canvas.saveLayer(left, top, right, top + length, null, flags); 15388 } 15389 15390 if (drawBottom) { 15391 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 15392 } 15393 15394 if (drawLeft) { 15395 canvas.saveLayer(left, top, left + length, bottom, null, flags); 15396 } 15397 15398 if (drawRight) { 15399 canvas.saveLayer(right - length, top, right, bottom, null, flags); 15400 } 15401 } else { 15402 scrollabilityCache.setFadeColor(solidColor); 15403 } 15404 15405 // Step 3, draw the content 15406 if (!dirtyOpaque) onDraw(canvas); 15407 15408 // Step 4, draw the children 15409 dispatchDraw(canvas); 15410 15411 // Step 5, draw the fade effect and restore layers 15412 final Paint p = scrollabilityCache.paint; 15413 final Matrix matrix = scrollabilityCache.matrix; 15414 final Shader fade = scrollabilityCache.shader; 15415 15416 if (drawTop) { 15417 matrix.setScale(1, fadeHeight * topFadeStrength); 15418 matrix.postTranslate(left, top); 15419 fade.setLocalMatrix(matrix); 15420 p.setShader(fade); 15421 canvas.drawRect(left, top, right, top + length, p); 15422 } 15423 15424 if (drawBottom) { 15425 matrix.setScale(1, fadeHeight * bottomFadeStrength); 15426 matrix.postRotate(180); 15427 matrix.postTranslate(left, bottom); 15428 fade.setLocalMatrix(matrix); 15429 p.setShader(fade); 15430 canvas.drawRect(left, bottom - length, right, bottom, p); 15431 } 15432 15433 if (drawLeft) { 15434 matrix.setScale(1, fadeHeight * leftFadeStrength); 15435 matrix.postRotate(-90); 15436 matrix.postTranslate(left, top); 15437 fade.setLocalMatrix(matrix); 15438 p.setShader(fade); 15439 canvas.drawRect(left, top, left + length, bottom, p); 15440 } 15441 15442 if (drawRight) { 15443 matrix.setScale(1, fadeHeight * rightFadeStrength); 15444 matrix.postRotate(90); 15445 matrix.postTranslate(right, top); 15446 fade.setLocalMatrix(matrix); 15447 p.setShader(fade); 15448 canvas.drawRect(right - length, top, right, bottom, p); 15449 } 15450 15451 canvas.restoreToCount(saveCount); 15452 15453 // Step 6, draw decorations (scrollbars) 15454 onDrawScrollBars(canvas); 15455 15456 if (mOverlay != null && !mOverlay.isEmpty()) { 15457 mOverlay.getOverlayView().dispatchDraw(canvas); 15458 } 15459 } 15460 15461 /** 15462 * Draws the background onto the specified canvas. 15463 * 15464 * @param canvas Canvas on which to draw the background 15465 */ 15466 private void drawBackground(Canvas canvas) { 15467 final Drawable background = mBackground; 15468 if (background == null) { 15469 return; 15470 } 15471 15472 if (mBackgroundSizeChanged) { 15473 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 15474 mBackgroundSizeChanged = false; 15475 mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID; 15476 } 15477 15478 // Attempt to use a display list if requested. 15479 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15480 && mAttachInfo.mHardwareRenderer != null) { 15481 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 15482 15483 final RenderNode displayList = mBackgroundRenderNode; 15484 if (displayList != null && displayList.isValid()) { 15485 setBackgroundDisplayListProperties(displayList); 15486 ((HardwareCanvas) canvas).drawRenderNode(displayList); 15487 return; 15488 } 15489 } 15490 15491 final int scrollX = mScrollX; 15492 final int scrollY = mScrollY; 15493 if ((scrollX | scrollY) == 0) { 15494 background.draw(canvas); 15495 } else { 15496 canvas.translate(scrollX, scrollY); 15497 background.draw(canvas); 15498 canvas.translate(-scrollX, -scrollY); 15499 } 15500 } 15501 15502 /** 15503 * Set up background drawable display list properties. 15504 * 15505 * @param displayList Valid display list for the background drawable 15506 */ 15507 private void setBackgroundDisplayListProperties(RenderNode displayList) { 15508 displayList.setTranslationX(mScrollX); 15509 displayList.setTranslationY(mScrollY); 15510 } 15511 15512 /** 15513 * Creates a new display list or updates the existing display list for the 15514 * specified Drawable. 15515 * 15516 * @param drawable Drawable for which to create a display list 15517 * @param renderNode Existing RenderNode, or {@code null} 15518 * @return A valid display list for the specified drawable 15519 */ 15520 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 15521 if (renderNode == null) { 15522 renderNode = RenderNode.create(drawable.getClass().getName(), this); 15523 } 15524 15525 final Rect bounds = drawable.getBounds(); 15526 final int width = bounds.width(); 15527 final int height = bounds.height(); 15528 final HardwareCanvas canvas = renderNode.start(width, height); 15529 try { 15530 drawable.draw(canvas); 15531 } finally { 15532 renderNode.end(canvas); 15533 } 15534 15535 // Set up drawable properties that are view-independent. 15536 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15537 renderNode.setProjectBackwards(drawable.isProjected()); 15538 renderNode.setProjectionReceiver(true); 15539 renderNode.setClipToBounds(false); 15540 return renderNode; 15541 } 15542 15543 /** 15544 * Returns the overlay for this view, creating it if it does not yet exist. 15545 * Adding drawables to the overlay will cause them to be displayed whenever 15546 * the view itself is redrawn. Objects in the overlay should be actively 15547 * managed: remove them when they should not be displayed anymore. The 15548 * overlay will always have the same size as its host view. 15549 * 15550 * <p>Note: Overlays do not currently work correctly with {@link 15551 * SurfaceView} or {@link TextureView}; contents in overlays for these 15552 * types of views may not display correctly.</p> 15553 * 15554 * @return The ViewOverlay object for this view. 15555 * @see ViewOverlay 15556 */ 15557 public ViewOverlay getOverlay() { 15558 if (mOverlay == null) { 15559 mOverlay = new ViewOverlay(mContext, this); 15560 } 15561 return mOverlay; 15562 } 15563 15564 /** 15565 * Override this if your view is known to always be drawn on top of a solid color background, 15566 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15567 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15568 * should be set to 0xFF. 15569 * 15570 * @see #setVerticalFadingEdgeEnabled(boolean) 15571 * @see #setHorizontalFadingEdgeEnabled(boolean) 15572 * 15573 * @return The known solid color background for this view, or 0 if the color may vary 15574 */ 15575 @ViewDebug.ExportedProperty(category = "drawing") 15576 public int getSolidColor() { 15577 return 0; 15578 } 15579 15580 /** 15581 * Build a human readable string representation of the specified view flags. 15582 * 15583 * @param flags the view flags to convert to a string 15584 * @return a String representing the supplied flags 15585 */ 15586 private static String printFlags(int flags) { 15587 String output = ""; 15588 int numFlags = 0; 15589 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15590 output += "TAKES_FOCUS"; 15591 numFlags++; 15592 } 15593 15594 switch (flags & VISIBILITY_MASK) { 15595 case INVISIBLE: 15596 if (numFlags > 0) { 15597 output += " "; 15598 } 15599 output += "INVISIBLE"; 15600 // USELESS HERE numFlags++; 15601 break; 15602 case GONE: 15603 if (numFlags > 0) { 15604 output += " "; 15605 } 15606 output += "GONE"; 15607 // USELESS HERE numFlags++; 15608 break; 15609 default: 15610 break; 15611 } 15612 return output; 15613 } 15614 15615 /** 15616 * Build a human readable string representation of the specified private 15617 * view flags. 15618 * 15619 * @param privateFlags the private view flags to convert to a string 15620 * @return a String representing the supplied flags 15621 */ 15622 private static String printPrivateFlags(int privateFlags) { 15623 String output = ""; 15624 int numFlags = 0; 15625 15626 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15627 output += "WANTS_FOCUS"; 15628 numFlags++; 15629 } 15630 15631 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15632 if (numFlags > 0) { 15633 output += " "; 15634 } 15635 output += "FOCUSED"; 15636 numFlags++; 15637 } 15638 15639 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15640 if (numFlags > 0) { 15641 output += " "; 15642 } 15643 output += "SELECTED"; 15644 numFlags++; 15645 } 15646 15647 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15648 if (numFlags > 0) { 15649 output += " "; 15650 } 15651 output += "IS_ROOT_NAMESPACE"; 15652 numFlags++; 15653 } 15654 15655 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15656 if (numFlags > 0) { 15657 output += " "; 15658 } 15659 output += "HAS_BOUNDS"; 15660 numFlags++; 15661 } 15662 15663 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15664 if (numFlags > 0) { 15665 output += " "; 15666 } 15667 output += "DRAWN"; 15668 // USELESS HERE numFlags++; 15669 } 15670 return output; 15671 } 15672 15673 /** 15674 * <p>Indicates whether or not this view's layout will be requested during 15675 * the next hierarchy layout pass.</p> 15676 * 15677 * @return true if the layout will be forced during next layout pass 15678 */ 15679 public boolean isLayoutRequested() { 15680 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15681 } 15682 15683 /** 15684 * Return true if o is a ViewGroup that is laying out using optical bounds. 15685 * @hide 15686 */ 15687 public static boolean isLayoutModeOptical(Object o) { 15688 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15689 } 15690 15691 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15692 Insets parentInsets = mParent instanceof View ? 15693 ((View) mParent).getOpticalInsets() : Insets.NONE; 15694 Insets childInsets = getOpticalInsets(); 15695 return setFrame( 15696 left + parentInsets.left - childInsets.left, 15697 top + parentInsets.top - childInsets.top, 15698 right + parentInsets.left + childInsets.right, 15699 bottom + parentInsets.top + childInsets.bottom); 15700 } 15701 15702 /** 15703 * Assign a size and position to a view and all of its 15704 * descendants 15705 * 15706 * <p>This is the second phase of the layout mechanism. 15707 * (The first is measuring). In this phase, each parent calls 15708 * layout on all of its children to position them. 15709 * This is typically done using the child measurements 15710 * that were stored in the measure pass().</p> 15711 * 15712 * <p>Derived classes should not override this method. 15713 * Derived classes with children should override 15714 * onLayout. In that method, they should 15715 * call layout on each of their children.</p> 15716 * 15717 * @param l Left position, relative to parent 15718 * @param t Top position, relative to parent 15719 * @param r Right position, relative to parent 15720 * @param b Bottom position, relative to parent 15721 */ 15722 @SuppressWarnings({"unchecked"}) 15723 public void layout(int l, int t, int r, int b) { 15724 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15725 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15726 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15727 } 15728 15729 int oldL = mLeft; 15730 int oldT = mTop; 15731 int oldB = mBottom; 15732 int oldR = mRight; 15733 15734 boolean changed = isLayoutModeOptical(mParent) ? 15735 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15736 15737 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15738 onLayout(changed, l, t, r, b); 15739 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15740 15741 ListenerInfo li = mListenerInfo; 15742 if (li != null && li.mOnLayoutChangeListeners != null) { 15743 ArrayList<OnLayoutChangeListener> listenersCopy = 15744 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15745 int numListeners = listenersCopy.size(); 15746 for (int i = 0; i < numListeners; ++i) { 15747 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15748 } 15749 } 15750 } 15751 15752 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15753 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15754 } 15755 15756 /** 15757 * Called from layout when this view should 15758 * assign a size and position to each of its children. 15759 * 15760 * Derived classes with children should override 15761 * this method and call layout on each of 15762 * their children. 15763 * @param changed This is a new size or position for this view 15764 * @param left Left position, relative to parent 15765 * @param top Top position, relative to parent 15766 * @param right Right position, relative to parent 15767 * @param bottom Bottom position, relative to parent 15768 */ 15769 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15770 } 15771 15772 /** 15773 * Assign a size and position to this view. 15774 * 15775 * This is called from layout. 15776 * 15777 * @param left Left position, relative to parent 15778 * @param top Top position, relative to parent 15779 * @param right Right position, relative to parent 15780 * @param bottom Bottom position, relative to parent 15781 * @return true if the new size and position are different than the 15782 * previous ones 15783 * {@hide} 15784 */ 15785 protected boolean setFrame(int left, int top, int right, int bottom) { 15786 boolean changed = false; 15787 15788 if (DBG) { 15789 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15790 + right + "," + bottom + ")"); 15791 } 15792 15793 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15794 changed = true; 15795 15796 // Remember our drawn bit 15797 int drawn = mPrivateFlags & PFLAG_DRAWN; 15798 15799 int oldWidth = mRight - mLeft; 15800 int oldHeight = mBottom - mTop; 15801 int newWidth = right - left; 15802 int newHeight = bottom - top; 15803 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15804 15805 // Invalidate our old position 15806 invalidate(sizeChanged); 15807 15808 mLeft = left; 15809 mTop = top; 15810 mRight = right; 15811 mBottom = bottom; 15812 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15813 15814 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15815 15816 15817 if (sizeChanged) { 15818 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15819 } 15820 15821 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 15822 // If we are visible, force the DRAWN bit to on so that 15823 // this invalidate will go through (at least to our parent). 15824 // This is because someone may have invalidated this view 15825 // before this call to setFrame came in, thereby clearing 15826 // the DRAWN bit. 15827 mPrivateFlags |= PFLAG_DRAWN; 15828 invalidate(sizeChanged); 15829 // parent display list may need to be recreated based on a change in the bounds 15830 // of any child 15831 invalidateParentCaches(); 15832 } 15833 15834 // Reset drawn bit to original value (invalidate turns it off) 15835 mPrivateFlags |= drawn; 15836 15837 mBackgroundSizeChanged = true; 15838 15839 notifySubtreeAccessibilityStateChangedIfNeeded(); 15840 } 15841 return changed; 15842 } 15843 15844 /** 15845 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 15846 * @hide 15847 */ 15848 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 15849 setFrame(left, top, right, bottom); 15850 } 15851 15852 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15853 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15854 if (mOverlay != null) { 15855 mOverlay.getOverlayView().setRight(newWidth); 15856 mOverlay.getOverlayView().setBottom(newHeight); 15857 } 15858 mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID; 15859 } 15860 15861 /** 15862 * Finalize inflating a view from XML. This is called as the last phase 15863 * of inflation, after all child views have been added. 15864 * 15865 * <p>Even if the subclass overrides onFinishInflate, they should always be 15866 * sure to call the super method, so that we get called. 15867 */ 15868 protected void onFinishInflate() { 15869 } 15870 15871 /** 15872 * Returns the resources associated with this view. 15873 * 15874 * @return Resources object. 15875 */ 15876 public Resources getResources() { 15877 return mResources; 15878 } 15879 15880 /** 15881 * Invalidates the specified Drawable. 15882 * 15883 * @param drawable the drawable to invalidate 15884 */ 15885 @Override 15886 public void invalidateDrawable(@NonNull Drawable drawable) { 15887 if (verifyDrawable(drawable)) { 15888 final Rect dirty = drawable.getDirtyBounds(); 15889 final int scrollX = mScrollX; 15890 final int scrollY = mScrollY; 15891 15892 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15893 dirty.right + scrollX, dirty.bottom + scrollY); 15894 15895 mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID; 15896 } 15897 } 15898 15899 /** 15900 * Schedules an action on a drawable to occur at a specified time. 15901 * 15902 * @param who the recipient of the action 15903 * @param what the action to run on the drawable 15904 * @param when the time at which the action must occur. Uses the 15905 * {@link SystemClock#uptimeMillis} timebase. 15906 */ 15907 @Override 15908 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15909 if (verifyDrawable(who) && what != null) { 15910 final long delay = when - SystemClock.uptimeMillis(); 15911 if (mAttachInfo != null) { 15912 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15913 Choreographer.CALLBACK_ANIMATION, what, who, 15914 Choreographer.subtractFrameDelay(delay)); 15915 } else { 15916 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15917 } 15918 } 15919 } 15920 15921 /** 15922 * Cancels a scheduled action on a drawable. 15923 * 15924 * @param who the recipient of the action 15925 * @param what the action to cancel 15926 */ 15927 @Override 15928 public void unscheduleDrawable(Drawable who, Runnable what) { 15929 if (verifyDrawable(who) && what != null) { 15930 if (mAttachInfo != null) { 15931 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15932 Choreographer.CALLBACK_ANIMATION, what, who); 15933 } 15934 ViewRootImpl.getRunQueue().removeCallbacks(what); 15935 } 15936 } 15937 15938 /** 15939 * Unschedule any events associated with the given Drawable. This can be 15940 * used when selecting a new Drawable into a view, so that the previous 15941 * one is completely unscheduled. 15942 * 15943 * @param who The Drawable to unschedule. 15944 * 15945 * @see #drawableStateChanged 15946 */ 15947 public void unscheduleDrawable(Drawable who) { 15948 if (mAttachInfo != null && who != null) { 15949 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15950 Choreographer.CALLBACK_ANIMATION, null, who); 15951 } 15952 } 15953 15954 /** 15955 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15956 * that the View directionality can and will be resolved before its Drawables. 15957 * 15958 * Will call {@link View#onResolveDrawables} when resolution is done. 15959 * 15960 * @hide 15961 */ 15962 protected void resolveDrawables() { 15963 // Drawables resolution may need to happen before resolving the layout direction (which is 15964 // done only during the measure() call). 15965 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15966 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15967 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15968 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15969 // direction to be resolved as its resolved value will be the same as its raw value. 15970 if (!isLayoutDirectionResolved() && 15971 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15972 return; 15973 } 15974 15975 final int layoutDirection = isLayoutDirectionResolved() ? 15976 getLayoutDirection() : getRawLayoutDirection(); 15977 15978 if (mBackground != null) { 15979 mBackground.setLayoutDirection(layoutDirection); 15980 } 15981 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15982 onResolveDrawables(layoutDirection); 15983 } 15984 15985 boolean areDrawablesResolved() { 15986 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15987 } 15988 15989 /** 15990 * Called when layout direction has been resolved. 15991 * 15992 * The default implementation does nothing. 15993 * 15994 * @param layoutDirection The resolved layout direction. 15995 * 15996 * @see #LAYOUT_DIRECTION_LTR 15997 * @see #LAYOUT_DIRECTION_RTL 15998 * 15999 * @hide 16000 */ 16001 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 16002 } 16003 16004 /** 16005 * @hide 16006 */ 16007 protected void resetResolvedDrawables() { 16008 resetResolvedDrawablesInternal(); 16009 } 16010 16011 void resetResolvedDrawablesInternal() { 16012 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 16013 } 16014 16015 /** 16016 * If your view subclass is displaying its own Drawable objects, it should 16017 * override this function and return true for any Drawable it is 16018 * displaying. This allows animations for those drawables to be 16019 * scheduled. 16020 * 16021 * <p>Be sure to call through to the super class when overriding this 16022 * function. 16023 * 16024 * @param who The Drawable to verify. Return true if it is one you are 16025 * displaying, else return the result of calling through to the 16026 * super class. 16027 * 16028 * @return boolean If true than the Drawable is being displayed in the 16029 * view; else false and it is not allowed to animate. 16030 * 16031 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 16032 * @see #drawableStateChanged() 16033 */ 16034 protected boolean verifyDrawable(Drawable who) { 16035 return who == mBackground; 16036 } 16037 16038 /** 16039 * This function is called whenever the state of the view changes in such 16040 * a way that it impacts the state of drawables being shown. 16041 * <p> 16042 * If the View has a StateListAnimator, it will also be called to run necessary state 16043 * change animations. 16044 * <p> 16045 * Be sure to call through to the superclass when overriding this function. 16046 * 16047 * @see Drawable#setState(int[]) 16048 */ 16049 protected void drawableStateChanged() { 16050 final Drawable d = mBackground; 16051 if (d != null && d.isStateful()) { 16052 d.setState(getDrawableState()); 16053 } 16054 16055 if (mStateListAnimator != null) { 16056 mStateListAnimator.setState(getDrawableState()); 16057 } 16058 } 16059 16060 /** 16061 * This function is called whenever the view hotspot changes and needs to 16062 * be propagated to drawables managed by the view. 16063 * <p> 16064 * Be sure to call through to the superclass when overriding this function. 16065 * 16066 * @param x hotspot x coordinate 16067 * @param y hotspot y coordinate 16068 */ 16069 public void drawableHotspotChanged(float x, float y) { 16070 if (mBackground != null) { 16071 mBackground.setHotspot(x, y); 16072 } 16073 } 16074 16075 /** 16076 * Call this to force a view to update its drawable state. This will cause 16077 * drawableStateChanged to be called on this view. Views that are interested 16078 * in the new state should call getDrawableState. 16079 * 16080 * @see #drawableStateChanged 16081 * @see #getDrawableState 16082 */ 16083 public void refreshDrawableState() { 16084 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 16085 drawableStateChanged(); 16086 16087 ViewParent parent = mParent; 16088 if (parent != null) { 16089 parent.childDrawableStateChanged(this); 16090 } 16091 } 16092 16093 /** 16094 * Return an array of resource IDs of the drawable states representing the 16095 * current state of the view. 16096 * 16097 * @return The current drawable state 16098 * 16099 * @see Drawable#setState(int[]) 16100 * @see #drawableStateChanged() 16101 * @see #onCreateDrawableState(int) 16102 */ 16103 public final int[] getDrawableState() { 16104 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 16105 return mDrawableState; 16106 } else { 16107 mDrawableState = onCreateDrawableState(0); 16108 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 16109 return mDrawableState; 16110 } 16111 } 16112 16113 /** 16114 * Generate the new {@link android.graphics.drawable.Drawable} state for 16115 * this view. This is called by the view 16116 * system when the cached Drawable state is determined to be invalid. To 16117 * retrieve the current state, you should use {@link #getDrawableState}. 16118 * 16119 * @param extraSpace if non-zero, this is the number of extra entries you 16120 * would like in the returned array in which you can place your own 16121 * states. 16122 * 16123 * @return Returns an array holding the current {@link Drawable} state of 16124 * the view. 16125 * 16126 * @see #mergeDrawableStates(int[], int[]) 16127 */ 16128 protected int[] onCreateDrawableState(int extraSpace) { 16129 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 16130 mParent instanceof View) { 16131 return ((View) mParent).onCreateDrawableState(extraSpace); 16132 } 16133 16134 int[] drawableState; 16135 16136 int privateFlags = mPrivateFlags; 16137 16138 int viewStateIndex = 0; 16139 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 16140 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 16141 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 16142 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 16143 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 16144 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 16145 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 16146 HardwareRenderer.isAvailable()) { 16147 // This is set if HW acceleration is requested, even if the current 16148 // process doesn't allow it. This is just to allow app preview 16149 // windows to better match their app. 16150 viewStateIndex |= VIEW_STATE_ACCELERATED; 16151 } 16152 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 16153 16154 final int privateFlags2 = mPrivateFlags2; 16155 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 16156 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 16157 16158 drawableState = VIEW_STATE_SETS[viewStateIndex]; 16159 16160 //noinspection ConstantIfStatement 16161 if (false) { 16162 Log.i("View", "drawableStateIndex=" + viewStateIndex); 16163 Log.i("View", toString() 16164 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 16165 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 16166 + " fo=" + hasFocus() 16167 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 16168 + " wf=" + hasWindowFocus() 16169 + ": " + Arrays.toString(drawableState)); 16170 } 16171 16172 if (extraSpace == 0) { 16173 return drawableState; 16174 } 16175 16176 final int[] fullState; 16177 if (drawableState != null) { 16178 fullState = new int[drawableState.length + extraSpace]; 16179 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 16180 } else { 16181 fullState = new int[extraSpace]; 16182 } 16183 16184 return fullState; 16185 } 16186 16187 /** 16188 * Merge your own state values in <var>additionalState</var> into the base 16189 * state values <var>baseState</var> that were returned by 16190 * {@link #onCreateDrawableState(int)}. 16191 * 16192 * @param baseState The base state values returned by 16193 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 16194 * own additional state values. 16195 * 16196 * @param additionalState The additional state values you would like 16197 * added to <var>baseState</var>; this array is not modified. 16198 * 16199 * @return As a convenience, the <var>baseState</var> array you originally 16200 * passed into the function is returned. 16201 * 16202 * @see #onCreateDrawableState(int) 16203 */ 16204 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 16205 final int N = baseState.length; 16206 int i = N - 1; 16207 while (i >= 0 && baseState[i] == 0) { 16208 i--; 16209 } 16210 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 16211 return baseState; 16212 } 16213 16214 /** 16215 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 16216 * on all Drawable objects associated with this view. 16217 * <p> 16218 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 16219 * attached to this view. 16220 */ 16221 public void jumpDrawablesToCurrentState() { 16222 if (mBackground != null) { 16223 mBackground.jumpToCurrentState(); 16224 } 16225 if (mStateListAnimator != null) { 16226 mStateListAnimator.jumpToCurrentState(); 16227 } 16228 } 16229 16230 /** 16231 * Sets the background color for this view. 16232 * @param color the color of the background 16233 */ 16234 @RemotableViewMethod 16235 public void setBackgroundColor(int color) { 16236 if (mBackground instanceof ColorDrawable) { 16237 ((ColorDrawable) mBackground.mutate()).setColor(color); 16238 computeOpaqueFlags(); 16239 mBackgroundResource = 0; 16240 } else { 16241 setBackground(new ColorDrawable(color)); 16242 } 16243 } 16244 16245 /** 16246 * Set the background to a given resource. The resource should refer to 16247 * a Drawable object or 0 to remove the background. 16248 * @param resid The identifier of the resource. 16249 * 16250 * @attr ref android.R.styleable#View_background 16251 */ 16252 @RemotableViewMethod 16253 public void setBackgroundResource(int resid) { 16254 if (resid != 0 && resid == mBackgroundResource) { 16255 return; 16256 } 16257 16258 Drawable d = null; 16259 if (resid != 0) { 16260 d = mContext.getDrawable(resid); 16261 } 16262 setBackground(d); 16263 16264 mBackgroundResource = resid; 16265 } 16266 16267 /** 16268 * Set the background to a given Drawable, or remove the background. If the 16269 * background has padding, this View's padding is set to the background's 16270 * padding. However, when a background is removed, this View's padding isn't 16271 * touched. If setting the padding is desired, please use 16272 * {@link #setPadding(int, int, int, int)}. 16273 * 16274 * @param background The Drawable to use as the background, or null to remove the 16275 * background 16276 */ 16277 public void setBackground(Drawable background) { 16278 //noinspection deprecation 16279 setBackgroundDrawable(background); 16280 } 16281 16282 /** 16283 * @deprecated use {@link #setBackground(Drawable)} instead 16284 */ 16285 @Deprecated 16286 public void setBackgroundDrawable(Drawable background) { 16287 computeOpaqueFlags(); 16288 16289 if (background == mBackground) { 16290 return; 16291 } 16292 16293 boolean requestLayout = false; 16294 16295 mBackgroundResource = 0; 16296 16297 /* 16298 * Regardless of whether we're setting a new background or not, we want 16299 * to clear the previous drawable. 16300 */ 16301 if (mBackground != null) { 16302 mBackground.setCallback(null); 16303 unscheduleDrawable(mBackground); 16304 } 16305 16306 if (background != null) { 16307 Rect padding = sThreadLocal.get(); 16308 if (padding == null) { 16309 padding = new Rect(); 16310 sThreadLocal.set(padding); 16311 } 16312 resetResolvedDrawablesInternal(); 16313 background.setLayoutDirection(getLayoutDirection()); 16314 if (background.getPadding(padding)) { 16315 resetResolvedPaddingInternal(); 16316 switch (background.getLayoutDirection()) { 16317 case LAYOUT_DIRECTION_RTL: 16318 mUserPaddingLeftInitial = padding.right; 16319 mUserPaddingRightInitial = padding.left; 16320 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 16321 break; 16322 case LAYOUT_DIRECTION_LTR: 16323 default: 16324 mUserPaddingLeftInitial = padding.left; 16325 mUserPaddingRightInitial = padding.right; 16326 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 16327 } 16328 mLeftPaddingDefined = false; 16329 mRightPaddingDefined = false; 16330 } 16331 16332 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 16333 // if it has a different minimum size, we should layout again 16334 if (mBackground == null 16335 || mBackground.getMinimumHeight() != background.getMinimumHeight() 16336 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 16337 requestLayout = true; 16338 } 16339 16340 background.setCallback(this); 16341 if (background.isStateful()) { 16342 background.setState(getDrawableState()); 16343 } 16344 background.setVisible(getVisibility() == VISIBLE, false); 16345 mBackground = background; 16346 16347 applyBackgroundTint(); 16348 16349 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 16350 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 16351 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 16352 requestLayout = true; 16353 } 16354 } else { 16355 /* Remove the background */ 16356 mBackground = null; 16357 16358 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 16359 /* 16360 * This view ONLY drew the background before and we're removing 16361 * the background, so now it won't draw anything 16362 * (hence we SKIP_DRAW) 16363 */ 16364 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 16365 mPrivateFlags |= PFLAG_SKIP_DRAW; 16366 } 16367 16368 /* 16369 * When the background is set, we try to apply its padding to this 16370 * View. When the background is removed, we don't touch this View's 16371 * padding. This is noted in the Javadocs. Hence, we don't need to 16372 * requestLayout(), the invalidate() below is sufficient. 16373 */ 16374 16375 // The old background's minimum size could have affected this 16376 // View's layout, so let's requestLayout 16377 requestLayout = true; 16378 } 16379 16380 computeOpaqueFlags(); 16381 16382 if (requestLayout) { 16383 requestLayout(); 16384 } 16385 16386 mBackgroundSizeChanged = true; 16387 invalidate(true); 16388 } 16389 16390 /** 16391 * Gets the background drawable 16392 * 16393 * @return The drawable used as the background for this view, if any. 16394 * 16395 * @see #setBackground(Drawable) 16396 * 16397 * @attr ref android.R.styleable#View_background 16398 */ 16399 public Drawable getBackground() { 16400 return mBackground; 16401 } 16402 16403 /** 16404 * Applies a tint to the background drawable. Does not modify the current tint 16405 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 16406 * <p> 16407 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 16408 * mutate the drawable and apply the specified tint and tint mode using 16409 * {@link Drawable#setTintList(ColorStateList)}. 16410 * 16411 * @param tint the tint to apply, may be {@code null} to clear tint 16412 * 16413 * @attr ref android.R.styleable#View_backgroundTint 16414 * @see #getBackgroundTintList() 16415 * @see Drawable#setTintList(ColorStateList) 16416 */ 16417 public void setBackgroundTintList(@Nullable ColorStateList tint) { 16418 if (mBackgroundTint == null) { 16419 mBackgroundTint = new TintInfo(); 16420 } 16421 mBackgroundTint.mTintList = tint; 16422 mBackgroundTint.mHasTintList = true; 16423 16424 applyBackgroundTint(); 16425 } 16426 16427 /** 16428 * Return the tint applied to the background drawable, if specified. 16429 * 16430 * @return the tint applied to the background drawable 16431 * @attr ref android.R.styleable#View_backgroundTint 16432 * @see #setBackgroundTintList(ColorStateList) 16433 */ 16434 @Nullable 16435 public ColorStateList getBackgroundTintList() { 16436 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 16437 } 16438 16439 /** 16440 * Specifies the blending mode used to apply the tint specified by 16441 * {@link #setBackgroundTintList(ColorStateList)}} to the background 16442 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 16443 * 16444 * @param tintMode the blending mode used to apply the tint, may be 16445 * {@code null} to clear tint 16446 * @attr ref android.R.styleable#View_backgroundTintMode 16447 * @see #getBackgroundTintMode() 16448 * @see Drawable#setTintMode(PorterDuff.Mode) 16449 */ 16450 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 16451 if (mBackgroundTint == null) { 16452 mBackgroundTint = new TintInfo(); 16453 } 16454 mBackgroundTint.mTintMode = tintMode; 16455 mBackgroundTint.mHasTintMode = true; 16456 16457 applyBackgroundTint(); 16458 } 16459 16460 /** 16461 * Return the blending mode used to apply the tint to the background 16462 * drawable, if specified. 16463 * 16464 * @return the blending mode used to apply the tint to the background 16465 * drawable 16466 * @attr ref android.R.styleable#View_backgroundTintMode 16467 * @see #setBackgroundTintMode(PorterDuff.Mode) 16468 */ 16469 @Nullable 16470 public PorterDuff.Mode getBackgroundTintMode() { 16471 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 16472 } 16473 16474 private void applyBackgroundTint() { 16475 if (mBackground != null && mBackgroundTint != null) { 16476 final TintInfo tintInfo = mBackgroundTint; 16477 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 16478 mBackground = mBackground.mutate(); 16479 16480 if (tintInfo.mHasTintList) { 16481 mBackground.setTintList(tintInfo.mTintList); 16482 } 16483 16484 if (tintInfo.mHasTintMode) { 16485 mBackground.setTintMode(tintInfo.mTintMode); 16486 } 16487 16488 // The drawable (or one of its children) may not have been 16489 // stateful before applying the tint, so let's try again. 16490 if (mBackground.isStateful()) { 16491 mBackground.setState(getDrawableState()); 16492 } 16493 } 16494 } 16495 } 16496 16497 /** 16498 * Sets the padding. The view may add on the space required to display 16499 * the scrollbars, depending on the style and visibility of the scrollbars. 16500 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 16501 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 16502 * from the values set in this call. 16503 * 16504 * @attr ref android.R.styleable#View_padding 16505 * @attr ref android.R.styleable#View_paddingBottom 16506 * @attr ref android.R.styleable#View_paddingLeft 16507 * @attr ref android.R.styleable#View_paddingRight 16508 * @attr ref android.R.styleable#View_paddingTop 16509 * @param left the left padding in pixels 16510 * @param top the top padding in pixels 16511 * @param right the right padding in pixels 16512 * @param bottom the bottom padding in pixels 16513 */ 16514 public void setPadding(int left, int top, int right, int bottom) { 16515 resetResolvedPaddingInternal(); 16516 16517 mUserPaddingStart = UNDEFINED_PADDING; 16518 mUserPaddingEnd = UNDEFINED_PADDING; 16519 16520 mUserPaddingLeftInitial = left; 16521 mUserPaddingRightInitial = right; 16522 16523 mLeftPaddingDefined = true; 16524 mRightPaddingDefined = true; 16525 16526 internalSetPadding(left, top, right, bottom); 16527 } 16528 16529 /** 16530 * @hide 16531 */ 16532 protected void internalSetPadding(int left, int top, int right, int bottom) { 16533 mUserPaddingLeft = left; 16534 mUserPaddingRight = right; 16535 mUserPaddingBottom = bottom; 16536 16537 final int viewFlags = mViewFlags; 16538 boolean changed = false; 16539 16540 // Common case is there are no scroll bars. 16541 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 16542 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 16543 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 16544 ? 0 : getVerticalScrollbarWidth(); 16545 switch (mVerticalScrollbarPosition) { 16546 case SCROLLBAR_POSITION_DEFAULT: 16547 if (isLayoutRtl()) { 16548 left += offset; 16549 } else { 16550 right += offset; 16551 } 16552 break; 16553 case SCROLLBAR_POSITION_RIGHT: 16554 right += offset; 16555 break; 16556 case SCROLLBAR_POSITION_LEFT: 16557 left += offset; 16558 break; 16559 } 16560 } 16561 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16562 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16563 ? 0 : getHorizontalScrollbarHeight(); 16564 } 16565 } 16566 16567 if (mPaddingLeft != left) { 16568 changed = true; 16569 mPaddingLeft = left; 16570 } 16571 if (mPaddingTop != top) { 16572 changed = true; 16573 mPaddingTop = top; 16574 } 16575 if (mPaddingRight != right) { 16576 changed = true; 16577 mPaddingRight = right; 16578 } 16579 if (mPaddingBottom != bottom) { 16580 changed = true; 16581 mPaddingBottom = bottom; 16582 } 16583 16584 if (changed) { 16585 requestLayout(); 16586 } 16587 } 16588 16589 /** 16590 * Sets the relative padding. The view may add on the space required to display 16591 * the scrollbars, depending on the style and visibility of the scrollbars. 16592 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16593 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16594 * from the values set in this call. 16595 * 16596 * @attr ref android.R.styleable#View_padding 16597 * @attr ref android.R.styleable#View_paddingBottom 16598 * @attr ref android.R.styleable#View_paddingStart 16599 * @attr ref android.R.styleable#View_paddingEnd 16600 * @attr ref android.R.styleable#View_paddingTop 16601 * @param start the start padding in pixels 16602 * @param top the top padding in pixels 16603 * @param end the end padding in pixels 16604 * @param bottom the bottom padding in pixels 16605 */ 16606 public void setPaddingRelative(int start, int top, int end, int bottom) { 16607 resetResolvedPaddingInternal(); 16608 16609 mUserPaddingStart = start; 16610 mUserPaddingEnd = end; 16611 mLeftPaddingDefined = true; 16612 mRightPaddingDefined = true; 16613 16614 switch(getLayoutDirection()) { 16615 case LAYOUT_DIRECTION_RTL: 16616 mUserPaddingLeftInitial = end; 16617 mUserPaddingRightInitial = start; 16618 internalSetPadding(end, top, start, bottom); 16619 break; 16620 case LAYOUT_DIRECTION_LTR: 16621 default: 16622 mUserPaddingLeftInitial = start; 16623 mUserPaddingRightInitial = end; 16624 internalSetPadding(start, top, end, bottom); 16625 } 16626 } 16627 16628 /** 16629 * Returns the top padding of this view. 16630 * 16631 * @return the top padding in pixels 16632 */ 16633 public int getPaddingTop() { 16634 return mPaddingTop; 16635 } 16636 16637 /** 16638 * Returns the bottom padding of this view. If there are inset and enabled 16639 * scrollbars, this value may include the space required to display the 16640 * scrollbars as well. 16641 * 16642 * @return the bottom padding in pixels 16643 */ 16644 public int getPaddingBottom() { 16645 return mPaddingBottom; 16646 } 16647 16648 /** 16649 * Returns the left padding of this view. If there are inset and enabled 16650 * scrollbars, this value may include the space required to display the 16651 * scrollbars as well. 16652 * 16653 * @return the left padding in pixels 16654 */ 16655 public int getPaddingLeft() { 16656 if (!isPaddingResolved()) { 16657 resolvePadding(); 16658 } 16659 return mPaddingLeft; 16660 } 16661 16662 /** 16663 * Returns the start padding of this view depending on its resolved layout direction. 16664 * If there are inset and enabled scrollbars, this value may include the space 16665 * required to display the scrollbars as well. 16666 * 16667 * @return the start padding in pixels 16668 */ 16669 public int getPaddingStart() { 16670 if (!isPaddingResolved()) { 16671 resolvePadding(); 16672 } 16673 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16674 mPaddingRight : mPaddingLeft; 16675 } 16676 16677 /** 16678 * Returns the right padding of this view. If there are inset and enabled 16679 * scrollbars, this value may include the space required to display the 16680 * scrollbars as well. 16681 * 16682 * @return the right padding in pixels 16683 */ 16684 public int getPaddingRight() { 16685 if (!isPaddingResolved()) { 16686 resolvePadding(); 16687 } 16688 return mPaddingRight; 16689 } 16690 16691 /** 16692 * Returns the end padding of this view depending on its resolved layout direction. 16693 * If there are inset and enabled scrollbars, this value may include the space 16694 * required to display the scrollbars as well. 16695 * 16696 * @return the end padding in pixels 16697 */ 16698 public int getPaddingEnd() { 16699 if (!isPaddingResolved()) { 16700 resolvePadding(); 16701 } 16702 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16703 mPaddingLeft : mPaddingRight; 16704 } 16705 16706 /** 16707 * Return if the padding as been set thru relative values 16708 * {@link #setPaddingRelative(int, int, int, int)} or thru 16709 * @attr ref android.R.styleable#View_paddingStart or 16710 * @attr ref android.R.styleable#View_paddingEnd 16711 * 16712 * @return true if the padding is relative or false if it is not. 16713 */ 16714 public boolean isPaddingRelative() { 16715 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16716 } 16717 16718 Insets computeOpticalInsets() { 16719 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16720 } 16721 16722 /** 16723 * @hide 16724 */ 16725 public void resetPaddingToInitialValues() { 16726 if (isRtlCompatibilityMode()) { 16727 mPaddingLeft = mUserPaddingLeftInitial; 16728 mPaddingRight = mUserPaddingRightInitial; 16729 return; 16730 } 16731 if (isLayoutRtl()) { 16732 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16733 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16734 } else { 16735 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16736 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16737 } 16738 } 16739 16740 /** 16741 * @hide 16742 */ 16743 public Insets getOpticalInsets() { 16744 if (mLayoutInsets == null) { 16745 mLayoutInsets = computeOpticalInsets(); 16746 } 16747 return mLayoutInsets; 16748 } 16749 16750 /** 16751 * Set this view's optical insets. 16752 * 16753 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16754 * property. Views that compute their own optical insets should call it as part of measurement. 16755 * This method does not request layout. If you are setting optical insets outside of 16756 * measure/layout itself you will want to call requestLayout() yourself. 16757 * </p> 16758 * @hide 16759 */ 16760 public void setOpticalInsets(Insets insets) { 16761 mLayoutInsets = insets; 16762 } 16763 16764 /** 16765 * Changes the selection state of this view. A view can be selected or not. 16766 * Note that selection is not the same as focus. Views are typically 16767 * selected in the context of an AdapterView like ListView or GridView; 16768 * the selected view is the view that is highlighted. 16769 * 16770 * @param selected true if the view must be selected, false otherwise 16771 */ 16772 public void setSelected(boolean selected) { 16773 //noinspection DoubleNegation 16774 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16775 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16776 if (!selected) resetPressedState(); 16777 invalidate(true); 16778 refreshDrawableState(); 16779 dispatchSetSelected(selected); 16780 if (selected) { 16781 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 16782 } else { 16783 notifyViewAccessibilityStateChangedIfNeeded( 16784 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16785 } 16786 } 16787 } 16788 16789 /** 16790 * Dispatch setSelected to all of this View's children. 16791 * 16792 * @see #setSelected(boolean) 16793 * 16794 * @param selected The new selected state 16795 */ 16796 protected void dispatchSetSelected(boolean selected) { 16797 } 16798 16799 /** 16800 * Indicates the selection state of this view. 16801 * 16802 * @return true if the view is selected, false otherwise 16803 */ 16804 @ViewDebug.ExportedProperty 16805 public boolean isSelected() { 16806 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16807 } 16808 16809 /** 16810 * Changes the activated state of this view. A view can be activated or not. 16811 * Note that activation is not the same as selection. Selection is 16812 * a transient property, representing the view (hierarchy) the user is 16813 * currently interacting with. Activation is a longer-term state that the 16814 * user can move views in and out of. For example, in a list view with 16815 * single or multiple selection enabled, the views in the current selection 16816 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16817 * here.) The activated state is propagated down to children of the view it 16818 * is set on. 16819 * 16820 * @param activated true if the view must be activated, false otherwise 16821 */ 16822 public void setActivated(boolean activated) { 16823 //noinspection DoubleNegation 16824 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16825 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16826 invalidate(true); 16827 refreshDrawableState(); 16828 dispatchSetActivated(activated); 16829 } 16830 } 16831 16832 /** 16833 * Dispatch setActivated to all of this View's children. 16834 * 16835 * @see #setActivated(boolean) 16836 * 16837 * @param activated The new activated state 16838 */ 16839 protected void dispatchSetActivated(boolean activated) { 16840 } 16841 16842 /** 16843 * Indicates the activation state of this view. 16844 * 16845 * @return true if the view is activated, false otherwise 16846 */ 16847 @ViewDebug.ExportedProperty 16848 public boolean isActivated() { 16849 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16850 } 16851 16852 /** 16853 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16854 * observer can be used to get notifications when global events, like 16855 * layout, happen. 16856 * 16857 * The returned ViewTreeObserver observer is not guaranteed to remain 16858 * valid for the lifetime of this View. If the caller of this method keeps 16859 * a long-lived reference to ViewTreeObserver, it should always check for 16860 * the return value of {@link ViewTreeObserver#isAlive()}. 16861 * 16862 * @return The ViewTreeObserver for this view's hierarchy. 16863 */ 16864 public ViewTreeObserver getViewTreeObserver() { 16865 if (mAttachInfo != null) { 16866 return mAttachInfo.mTreeObserver; 16867 } 16868 if (mFloatingTreeObserver == null) { 16869 mFloatingTreeObserver = new ViewTreeObserver(); 16870 } 16871 return mFloatingTreeObserver; 16872 } 16873 16874 /** 16875 * <p>Finds the topmost view in the current view hierarchy.</p> 16876 * 16877 * @return the topmost view containing this view 16878 */ 16879 public View getRootView() { 16880 if (mAttachInfo != null) { 16881 final View v = mAttachInfo.mRootView; 16882 if (v != null) { 16883 return v; 16884 } 16885 } 16886 16887 View parent = this; 16888 16889 while (parent.mParent != null && parent.mParent instanceof View) { 16890 parent = (View) parent.mParent; 16891 } 16892 16893 return parent; 16894 } 16895 16896 /** 16897 * Transforms a motion event from view-local coordinates to on-screen 16898 * coordinates. 16899 * 16900 * @param ev the view-local motion event 16901 * @return false if the transformation could not be applied 16902 * @hide 16903 */ 16904 public boolean toGlobalMotionEvent(MotionEvent ev) { 16905 final AttachInfo info = mAttachInfo; 16906 if (info == null) { 16907 return false; 16908 } 16909 16910 final Matrix m = info.mTmpMatrix; 16911 m.set(Matrix.IDENTITY_MATRIX); 16912 transformMatrixToGlobal(m); 16913 ev.transform(m); 16914 return true; 16915 } 16916 16917 /** 16918 * Transforms a motion event from on-screen coordinates to view-local 16919 * coordinates. 16920 * 16921 * @param ev the on-screen motion event 16922 * @return false if the transformation could not be applied 16923 * @hide 16924 */ 16925 public boolean toLocalMotionEvent(MotionEvent ev) { 16926 final AttachInfo info = mAttachInfo; 16927 if (info == null) { 16928 return false; 16929 } 16930 16931 final Matrix m = info.mTmpMatrix; 16932 m.set(Matrix.IDENTITY_MATRIX); 16933 transformMatrixToLocal(m); 16934 ev.transform(m); 16935 return true; 16936 } 16937 16938 /** 16939 * Modifies the input matrix such that it maps view-local coordinates to 16940 * on-screen coordinates. 16941 * 16942 * @param m input matrix to modify 16943 * @hide 16944 */ 16945 public void transformMatrixToGlobal(Matrix m) { 16946 final ViewParent parent = mParent; 16947 if (parent instanceof View) { 16948 final View vp = (View) parent; 16949 vp.transformMatrixToGlobal(m); 16950 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 16951 } else if (parent instanceof ViewRootImpl) { 16952 final ViewRootImpl vr = (ViewRootImpl) parent; 16953 vr.transformMatrixToGlobal(m); 16954 m.preTranslate(0, -vr.mCurScrollY); 16955 } 16956 16957 m.preTranslate(mLeft, mTop); 16958 16959 if (!hasIdentityMatrix()) { 16960 m.preConcat(getMatrix()); 16961 } 16962 } 16963 16964 /** 16965 * Modifies the input matrix such that it maps on-screen coordinates to 16966 * view-local coordinates. 16967 * 16968 * @param m input matrix to modify 16969 * @hide 16970 */ 16971 public void transformMatrixToLocal(Matrix m) { 16972 final ViewParent parent = mParent; 16973 if (parent instanceof View) { 16974 final View vp = (View) parent; 16975 vp.transformMatrixToLocal(m); 16976 m.postTranslate(vp.mScrollX, vp.mScrollY); 16977 } else if (parent instanceof ViewRootImpl) { 16978 final ViewRootImpl vr = (ViewRootImpl) parent; 16979 vr.transformMatrixToLocal(m); 16980 m.postTranslate(0, vr.mCurScrollY); 16981 } 16982 16983 m.postTranslate(-mLeft, -mTop); 16984 16985 if (!hasIdentityMatrix()) { 16986 m.postConcat(getInverseMatrix()); 16987 } 16988 } 16989 16990 /** 16991 * @hide 16992 */ 16993 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 16994 @ViewDebug.IntToString(from = 0, to = "x"), 16995 @ViewDebug.IntToString(from = 1, to = "y") 16996 }) 16997 public int[] getLocationOnScreen() { 16998 int[] location = new int[2]; 16999 getLocationOnScreen(location); 17000 return location; 17001 } 17002 17003 /** 17004 * <p>Computes the coordinates of this view on the screen. The argument 17005 * must be an array of two integers. After the method returns, the array 17006 * contains the x and y location in that order.</p> 17007 * 17008 * @param location an array of two integers in which to hold the coordinates 17009 */ 17010 public void getLocationOnScreen(int[] location) { 17011 getLocationInWindow(location); 17012 17013 final AttachInfo info = mAttachInfo; 17014 if (info != null) { 17015 location[0] += info.mWindowLeft; 17016 location[1] += info.mWindowTop; 17017 } 17018 } 17019 17020 /** 17021 * <p>Computes the coordinates of this view in its window. The argument 17022 * must be an array of two integers. After the method returns, the array 17023 * contains the x and y location in that order.</p> 17024 * 17025 * @param location an array of two integers in which to hold the coordinates 17026 */ 17027 public void getLocationInWindow(int[] location) { 17028 if (location == null || location.length < 2) { 17029 throw new IllegalArgumentException("location must be an array of two integers"); 17030 } 17031 17032 if (mAttachInfo == null) { 17033 // When the view is not attached to a window, this method does not make sense 17034 location[0] = location[1] = 0; 17035 return; 17036 } 17037 17038 float[] position = mAttachInfo.mTmpTransformLocation; 17039 position[0] = position[1] = 0.0f; 17040 17041 if (!hasIdentityMatrix()) { 17042 getMatrix().mapPoints(position); 17043 } 17044 17045 position[0] += mLeft; 17046 position[1] += mTop; 17047 17048 ViewParent viewParent = mParent; 17049 while (viewParent instanceof View) { 17050 final View view = (View) viewParent; 17051 17052 position[0] -= view.mScrollX; 17053 position[1] -= view.mScrollY; 17054 17055 if (!view.hasIdentityMatrix()) { 17056 view.getMatrix().mapPoints(position); 17057 } 17058 17059 position[0] += view.mLeft; 17060 position[1] += view.mTop; 17061 17062 viewParent = view.mParent; 17063 } 17064 17065 if (viewParent instanceof ViewRootImpl) { 17066 // *cough* 17067 final ViewRootImpl vr = (ViewRootImpl) viewParent; 17068 position[1] -= vr.mCurScrollY; 17069 } 17070 17071 location[0] = (int) (position[0] + 0.5f); 17072 location[1] = (int) (position[1] + 0.5f); 17073 } 17074 17075 /** 17076 * {@hide} 17077 * @param id the id of the view to be found 17078 * @return the view of the specified id, null if cannot be found 17079 */ 17080 protected View findViewTraversal(int id) { 17081 if (id == mID) { 17082 return this; 17083 } 17084 return null; 17085 } 17086 17087 /** 17088 * {@hide} 17089 * @param tag the tag of the view to be found 17090 * @return the view of specified tag, null if cannot be found 17091 */ 17092 protected View findViewWithTagTraversal(Object tag) { 17093 if (tag != null && tag.equals(mTag)) { 17094 return this; 17095 } 17096 return null; 17097 } 17098 17099 /** 17100 * {@hide} 17101 * @param predicate The predicate to evaluate. 17102 * @param childToSkip If not null, ignores this child during the recursive traversal. 17103 * @return The first view that matches the predicate or null. 17104 */ 17105 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 17106 if (predicate.apply(this)) { 17107 return this; 17108 } 17109 return null; 17110 } 17111 17112 /** 17113 * Look for a child view with the given id. If this view has the given 17114 * id, return this view. 17115 * 17116 * @param id The id to search for. 17117 * @return The view that has the given id in the hierarchy or null 17118 */ 17119 public final View findViewById(int id) { 17120 if (id < 0) { 17121 return null; 17122 } 17123 return findViewTraversal(id); 17124 } 17125 17126 /** 17127 * Finds a view by its unuque and stable accessibility id. 17128 * 17129 * @param accessibilityId The searched accessibility id. 17130 * @return The found view. 17131 */ 17132 final View findViewByAccessibilityId(int accessibilityId) { 17133 if (accessibilityId < 0) { 17134 return null; 17135 } 17136 return findViewByAccessibilityIdTraversal(accessibilityId); 17137 } 17138 17139 /** 17140 * Performs the traversal to find a view by its unuque and stable accessibility id. 17141 * 17142 * <strong>Note:</strong>This method does not stop at the root namespace 17143 * boundary since the user can touch the screen at an arbitrary location 17144 * potentially crossing the root namespace bounday which will send an 17145 * accessibility event to accessibility services and they should be able 17146 * to obtain the event source. Also accessibility ids are guaranteed to be 17147 * unique in the window. 17148 * 17149 * @param accessibilityId The accessibility id. 17150 * @return The found view. 17151 * 17152 * @hide 17153 */ 17154 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 17155 if (getAccessibilityViewId() == accessibilityId) { 17156 return this; 17157 } 17158 return null; 17159 } 17160 17161 /** 17162 * Look for a child view with the given tag. If this view has the given 17163 * tag, return this view. 17164 * 17165 * @param tag The tag to search for, using "tag.equals(getTag())". 17166 * @return The View that has the given tag in the hierarchy or null 17167 */ 17168 public final View findViewWithTag(Object tag) { 17169 if (tag == null) { 17170 return null; 17171 } 17172 return findViewWithTagTraversal(tag); 17173 } 17174 17175 /** 17176 * {@hide} 17177 * Look for a child view that matches the specified predicate. 17178 * If this view matches the predicate, return this view. 17179 * 17180 * @param predicate The predicate to evaluate. 17181 * @return The first view that matches the predicate or null. 17182 */ 17183 public final View findViewByPredicate(Predicate<View> predicate) { 17184 return findViewByPredicateTraversal(predicate, null); 17185 } 17186 17187 /** 17188 * {@hide} 17189 * Look for a child view that matches the specified predicate, 17190 * starting with the specified view and its descendents and then 17191 * recusively searching the ancestors and siblings of that view 17192 * until this view is reached. 17193 * 17194 * This method is useful in cases where the predicate does not match 17195 * a single unique view (perhaps multiple views use the same id) 17196 * and we are trying to find the view that is "closest" in scope to the 17197 * starting view. 17198 * 17199 * @param start The view to start from. 17200 * @param predicate The predicate to evaluate. 17201 * @return The first view that matches the predicate or null. 17202 */ 17203 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 17204 View childToSkip = null; 17205 for (;;) { 17206 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 17207 if (view != null || start == this) { 17208 return view; 17209 } 17210 17211 ViewParent parent = start.getParent(); 17212 if (parent == null || !(parent instanceof View)) { 17213 return null; 17214 } 17215 17216 childToSkip = start; 17217 start = (View) parent; 17218 } 17219 } 17220 17221 /** 17222 * Sets the identifier for this view. The identifier does not have to be 17223 * unique in this view's hierarchy. The identifier should be a positive 17224 * number. 17225 * 17226 * @see #NO_ID 17227 * @see #getId() 17228 * @see #findViewById(int) 17229 * 17230 * @param id a number used to identify the view 17231 * 17232 * @attr ref android.R.styleable#View_id 17233 */ 17234 public void setId(int id) { 17235 mID = id; 17236 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 17237 mID = generateViewId(); 17238 } 17239 } 17240 17241 /** 17242 * {@hide} 17243 * 17244 * @param isRoot true if the view belongs to the root namespace, false 17245 * otherwise 17246 */ 17247 public void setIsRootNamespace(boolean isRoot) { 17248 if (isRoot) { 17249 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 17250 } else { 17251 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 17252 } 17253 } 17254 17255 /** 17256 * {@hide} 17257 * 17258 * @return true if the view belongs to the root namespace, false otherwise 17259 */ 17260 public boolean isRootNamespace() { 17261 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 17262 } 17263 17264 /** 17265 * Returns this view's identifier. 17266 * 17267 * @return a positive integer used to identify the view or {@link #NO_ID} 17268 * if the view has no ID 17269 * 17270 * @see #setId(int) 17271 * @see #findViewById(int) 17272 * @attr ref android.R.styleable#View_id 17273 */ 17274 @ViewDebug.CapturedViewProperty 17275 public int getId() { 17276 return mID; 17277 } 17278 17279 /** 17280 * Returns this view's tag. 17281 * 17282 * @return the Object stored in this view as a tag, or {@code null} if not 17283 * set 17284 * 17285 * @see #setTag(Object) 17286 * @see #getTag(int) 17287 */ 17288 @ViewDebug.ExportedProperty 17289 public Object getTag() { 17290 return mTag; 17291 } 17292 17293 /** 17294 * Sets the tag associated with this view. A tag can be used to mark 17295 * a view in its hierarchy and does not have to be unique within the 17296 * hierarchy. Tags can also be used to store data within a view without 17297 * resorting to another data structure. 17298 * 17299 * @param tag an Object to tag the view with 17300 * 17301 * @see #getTag() 17302 * @see #setTag(int, Object) 17303 */ 17304 public void setTag(final Object tag) { 17305 mTag = tag; 17306 } 17307 17308 /** 17309 * Returns the tag associated with this view and the specified key. 17310 * 17311 * @param key The key identifying the tag 17312 * 17313 * @return the Object stored in this view as a tag, or {@code null} if not 17314 * set 17315 * 17316 * @see #setTag(int, Object) 17317 * @see #getTag() 17318 */ 17319 public Object getTag(int key) { 17320 if (mKeyedTags != null) return mKeyedTags.get(key); 17321 return null; 17322 } 17323 17324 /** 17325 * Sets a tag associated with this view and a key. A tag can be used 17326 * to mark a view in its hierarchy and does not have to be unique within 17327 * the hierarchy. Tags can also be used to store data within a view 17328 * without resorting to another data structure. 17329 * 17330 * The specified key should be an id declared in the resources of the 17331 * application to ensure it is unique (see the <a 17332 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 17333 * Keys identified as belonging to 17334 * the Android framework or not associated with any package will cause 17335 * an {@link IllegalArgumentException} to be thrown. 17336 * 17337 * @param key The key identifying the tag 17338 * @param tag An Object to tag the view with 17339 * 17340 * @throws IllegalArgumentException If they specified key is not valid 17341 * 17342 * @see #setTag(Object) 17343 * @see #getTag(int) 17344 */ 17345 public void setTag(int key, final Object tag) { 17346 // If the package id is 0x00 or 0x01, it's either an undefined package 17347 // or a framework id 17348 if ((key >>> 24) < 2) { 17349 throw new IllegalArgumentException("The key must be an application-specific " 17350 + "resource id."); 17351 } 17352 17353 setKeyedTag(key, tag); 17354 } 17355 17356 /** 17357 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 17358 * framework id. 17359 * 17360 * @hide 17361 */ 17362 public void setTagInternal(int key, Object tag) { 17363 if ((key >>> 24) != 0x1) { 17364 throw new IllegalArgumentException("The key must be a framework-specific " 17365 + "resource id."); 17366 } 17367 17368 setKeyedTag(key, tag); 17369 } 17370 17371 private void setKeyedTag(int key, Object tag) { 17372 if (mKeyedTags == null) { 17373 mKeyedTags = new SparseArray<Object>(2); 17374 } 17375 17376 mKeyedTags.put(key, tag); 17377 } 17378 17379 /** 17380 * Prints information about this view in the log output, with the tag 17381 * {@link #VIEW_LOG_TAG}. 17382 * 17383 * @hide 17384 */ 17385 public void debug() { 17386 debug(0); 17387 } 17388 17389 /** 17390 * Prints information about this view in the log output, with the tag 17391 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 17392 * indentation defined by the <code>depth</code>. 17393 * 17394 * @param depth the indentation level 17395 * 17396 * @hide 17397 */ 17398 protected void debug(int depth) { 17399 String output = debugIndent(depth - 1); 17400 17401 output += "+ " + this; 17402 int id = getId(); 17403 if (id != -1) { 17404 output += " (id=" + id + ")"; 17405 } 17406 Object tag = getTag(); 17407 if (tag != null) { 17408 output += " (tag=" + tag + ")"; 17409 } 17410 Log.d(VIEW_LOG_TAG, output); 17411 17412 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 17413 output = debugIndent(depth) + " FOCUSED"; 17414 Log.d(VIEW_LOG_TAG, output); 17415 } 17416 17417 output = debugIndent(depth); 17418 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 17419 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 17420 + "} "; 17421 Log.d(VIEW_LOG_TAG, output); 17422 17423 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 17424 || mPaddingBottom != 0) { 17425 output = debugIndent(depth); 17426 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 17427 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 17428 Log.d(VIEW_LOG_TAG, output); 17429 } 17430 17431 output = debugIndent(depth); 17432 output += "mMeasureWidth=" + mMeasuredWidth + 17433 " mMeasureHeight=" + mMeasuredHeight; 17434 Log.d(VIEW_LOG_TAG, output); 17435 17436 output = debugIndent(depth); 17437 if (mLayoutParams == null) { 17438 output += "BAD! no layout params"; 17439 } else { 17440 output = mLayoutParams.debug(output); 17441 } 17442 Log.d(VIEW_LOG_TAG, output); 17443 17444 output = debugIndent(depth); 17445 output += "flags={"; 17446 output += View.printFlags(mViewFlags); 17447 output += "}"; 17448 Log.d(VIEW_LOG_TAG, output); 17449 17450 output = debugIndent(depth); 17451 output += "privateFlags={"; 17452 output += View.printPrivateFlags(mPrivateFlags); 17453 output += "}"; 17454 Log.d(VIEW_LOG_TAG, output); 17455 } 17456 17457 /** 17458 * Creates a string of whitespaces used for indentation. 17459 * 17460 * @param depth the indentation level 17461 * @return a String containing (depth * 2 + 3) * 2 white spaces 17462 * 17463 * @hide 17464 */ 17465 protected static String debugIndent(int depth) { 17466 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 17467 for (int i = 0; i < (depth * 2) + 3; i++) { 17468 spaces.append(' ').append(' '); 17469 } 17470 return spaces.toString(); 17471 } 17472 17473 /** 17474 * <p>Return the offset of the widget's text baseline from the widget's top 17475 * boundary. If this widget does not support baseline alignment, this 17476 * method returns -1. </p> 17477 * 17478 * @return the offset of the baseline within the widget's bounds or -1 17479 * if baseline alignment is not supported 17480 */ 17481 @ViewDebug.ExportedProperty(category = "layout") 17482 public int getBaseline() { 17483 return -1; 17484 } 17485 17486 /** 17487 * Returns whether the view hierarchy is currently undergoing a layout pass. This 17488 * information is useful to avoid situations such as calling {@link #requestLayout()} during 17489 * a layout pass. 17490 * 17491 * @return whether the view hierarchy is currently undergoing a layout pass 17492 */ 17493 public boolean isInLayout() { 17494 ViewRootImpl viewRoot = getViewRootImpl(); 17495 return (viewRoot != null && viewRoot.isInLayout()); 17496 } 17497 17498 /** 17499 * Call this when something has changed which has invalidated the 17500 * layout of this view. This will schedule a layout pass of the view 17501 * tree. This should not be called while the view hierarchy is currently in a layout 17502 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 17503 * end of the current layout pass (and then layout will run again) or after the current 17504 * frame is drawn and the next layout occurs. 17505 * 17506 * <p>Subclasses which override this method should call the superclass method to 17507 * handle possible request-during-layout errors correctly.</p> 17508 */ 17509 public void requestLayout() { 17510 if (mMeasureCache != null) mMeasureCache.clear(); 17511 17512 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 17513 // Only trigger request-during-layout logic if this is the view requesting it, 17514 // not the views in its parent hierarchy 17515 ViewRootImpl viewRoot = getViewRootImpl(); 17516 if (viewRoot != null && viewRoot.isInLayout()) { 17517 if (!viewRoot.requestLayoutDuringLayout(this)) { 17518 return; 17519 } 17520 } 17521 mAttachInfo.mViewRequestingLayout = this; 17522 } 17523 17524 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17525 mPrivateFlags |= PFLAG_INVALIDATED; 17526 17527 if (mParent != null && !mParent.isLayoutRequested()) { 17528 mParent.requestLayout(); 17529 } 17530 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 17531 mAttachInfo.mViewRequestingLayout = null; 17532 } 17533 } 17534 17535 /** 17536 * Forces this view to be laid out during the next layout pass. 17537 * This method does not call requestLayout() or forceLayout() 17538 * on the parent. 17539 */ 17540 public void forceLayout() { 17541 if (mMeasureCache != null) mMeasureCache.clear(); 17542 17543 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17544 mPrivateFlags |= PFLAG_INVALIDATED; 17545 } 17546 17547 /** 17548 * <p> 17549 * This is called to find out how big a view should be. The parent 17550 * supplies constraint information in the width and height parameters. 17551 * </p> 17552 * 17553 * <p> 17554 * The actual measurement work of a view is performed in 17555 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 17556 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 17557 * </p> 17558 * 17559 * 17560 * @param widthMeasureSpec Horizontal space requirements as imposed by the 17561 * parent 17562 * @param heightMeasureSpec Vertical space requirements as imposed by the 17563 * parent 17564 * 17565 * @see #onMeasure(int, int) 17566 */ 17567 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 17568 boolean optical = isLayoutModeOptical(this); 17569 if (optical != isLayoutModeOptical(mParent)) { 17570 Insets insets = getOpticalInsets(); 17571 int oWidth = insets.left + insets.right; 17572 int oHeight = insets.top + insets.bottom; 17573 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 17574 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 17575 } 17576 17577 // Suppress sign extension for the low bytes 17578 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 17579 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 17580 17581 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 17582 final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY && 17583 MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 17584 final boolean matchingSize = isExactly && 17585 getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) && 17586 getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 17587 if (forceLayout || !matchingSize && 17588 (widthMeasureSpec != mOldWidthMeasureSpec || 17589 heightMeasureSpec != mOldHeightMeasureSpec)) { 17590 17591 // first clears the measured dimension flag 17592 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 17593 17594 resolveRtlPropertiesIfNeeded(); 17595 17596 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 17597 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17598 // measure ourselves, this should set the measured dimension flag back 17599 onMeasure(widthMeasureSpec, heightMeasureSpec); 17600 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17601 } else { 17602 long value = mMeasureCache.valueAt(cacheIndex); 17603 // Casting a long to int drops the high 32 bits, no mask needed 17604 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17605 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17606 } 17607 17608 // flag not set, setMeasuredDimension() was not invoked, we raise 17609 // an exception to warn the developer 17610 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17611 throw new IllegalStateException("onMeasure() did not set the" 17612 + " measured dimension by calling" 17613 + " setMeasuredDimension()"); 17614 } 17615 17616 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17617 } 17618 17619 mOldWidthMeasureSpec = widthMeasureSpec; 17620 mOldHeightMeasureSpec = heightMeasureSpec; 17621 17622 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17623 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17624 } 17625 17626 /** 17627 * <p> 17628 * Measure the view and its content to determine the measured width and the 17629 * measured height. This method is invoked by {@link #measure(int, int)} and 17630 * should be overriden by subclasses to provide accurate and efficient 17631 * measurement of their contents. 17632 * </p> 17633 * 17634 * <p> 17635 * <strong>CONTRACT:</strong> When overriding this method, you 17636 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17637 * measured width and height of this view. Failure to do so will trigger an 17638 * <code>IllegalStateException</code>, thrown by 17639 * {@link #measure(int, int)}. Calling the superclass' 17640 * {@link #onMeasure(int, int)} is a valid use. 17641 * </p> 17642 * 17643 * <p> 17644 * The base class implementation of measure defaults to the background size, 17645 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17646 * override {@link #onMeasure(int, int)} to provide better measurements of 17647 * their content. 17648 * </p> 17649 * 17650 * <p> 17651 * If this method is overridden, it is the subclass's responsibility to make 17652 * sure the measured height and width are at least the view's minimum height 17653 * and width ({@link #getSuggestedMinimumHeight()} and 17654 * {@link #getSuggestedMinimumWidth()}). 17655 * </p> 17656 * 17657 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17658 * The requirements are encoded with 17659 * {@link android.view.View.MeasureSpec}. 17660 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17661 * The requirements are encoded with 17662 * {@link android.view.View.MeasureSpec}. 17663 * 17664 * @see #getMeasuredWidth() 17665 * @see #getMeasuredHeight() 17666 * @see #setMeasuredDimension(int, int) 17667 * @see #getSuggestedMinimumHeight() 17668 * @see #getSuggestedMinimumWidth() 17669 * @see android.view.View.MeasureSpec#getMode(int) 17670 * @see android.view.View.MeasureSpec#getSize(int) 17671 */ 17672 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17673 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17674 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17675 } 17676 17677 /** 17678 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17679 * measured width and measured height. Failing to do so will trigger an 17680 * exception at measurement time.</p> 17681 * 17682 * @param measuredWidth The measured width of this view. May be a complex 17683 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17684 * {@link #MEASURED_STATE_TOO_SMALL}. 17685 * @param measuredHeight The measured height of this view. May be a complex 17686 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17687 * {@link #MEASURED_STATE_TOO_SMALL}. 17688 */ 17689 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17690 boolean optical = isLayoutModeOptical(this); 17691 if (optical != isLayoutModeOptical(mParent)) { 17692 Insets insets = getOpticalInsets(); 17693 int opticalWidth = insets.left + insets.right; 17694 int opticalHeight = insets.top + insets.bottom; 17695 17696 measuredWidth += optical ? opticalWidth : -opticalWidth; 17697 measuredHeight += optical ? opticalHeight : -opticalHeight; 17698 } 17699 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17700 } 17701 17702 /** 17703 * Sets the measured dimension without extra processing for things like optical bounds. 17704 * Useful for reapplying consistent values that have already been cooked with adjustments 17705 * for optical bounds, etc. such as those from the measurement cache. 17706 * 17707 * @param measuredWidth The measured width of this view. May be a complex 17708 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17709 * {@link #MEASURED_STATE_TOO_SMALL}. 17710 * @param measuredHeight The measured height of this view. May be a complex 17711 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17712 * {@link #MEASURED_STATE_TOO_SMALL}. 17713 */ 17714 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17715 mMeasuredWidth = measuredWidth; 17716 mMeasuredHeight = measuredHeight; 17717 17718 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17719 } 17720 17721 /** 17722 * Merge two states as returned by {@link #getMeasuredState()}. 17723 * @param curState The current state as returned from a view or the result 17724 * of combining multiple views. 17725 * @param newState The new view state to combine. 17726 * @return Returns a new integer reflecting the combination of the two 17727 * states. 17728 */ 17729 public static int combineMeasuredStates(int curState, int newState) { 17730 return curState | newState; 17731 } 17732 17733 /** 17734 * Version of {@link #resolveSizeAndState(int, int, int)} 17735 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17736 */ 17737 public static int resolveSize(int size, int measureSpec) { 17738 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17739 } 17740 17741 /** 17742 * Utility to reconcile a desired size and state, with constraints imposed 17743 * by a MeasureSpec. Will take the desired size, unless a different size 17744 * is imposed by the constraints. The returned value is a compound integer, 17745 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17746 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17747 * size is smaller than the size the view wants to be. 17748 * 17749 * @param size How big the view wants to be 17750 * @param measureSpec Constraints imposed by the parent 17751 * @return Size information bit mask as defined by 17752 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17753 */ 17754 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17755 int result = size; 17756 int specMode = MeasureSpec.getMode(measureSpec); 17757 int specSize = MeasureSpec.getSize(measureSpec); 17758 switch (specMode) { 17759 case MeasureSpec.UNSPECIFIED: 17760 result = size; 17761 break; 17762 case MeasureSpec.AT_MOST: 17763 if (specSize < size) { 17764 result = specSize | MEASURED_STATE_TOO_SMALL; 17765 } else { 17766 result = size; 17767 } 17768 break; 17769 case MeasureSpec.EXACTLY: 17770 result = specSize; 17771 break; 17772 } 17773 return result | (childMeasuredState&MEASURED_STATE_MASK); 17774 } 17775 17776 /** 17777 * Utility to return a default size. Uses the supplied size if the 17778 * MeasureSpec imposed no constraints. Will get larger if allowed 17779 * by the MeasureSpec. 17780 * 17781 * @param size Default size for this view 17782 * @param measureSpec Constraints imposed by the parent 17783 * @return The size this view should be. 17784 */ 17785 public static int getDefaultSize(int size, int measureSpec) { 17786 int result = size; 17787 int specMode = MeasureSpec.getMode(measureSpec); 17788 int specSize = MeasureSpec.getSize(measureSpec); 17789 17790 switch (specMode) { 17791 case MeasureSpec.UNSPECIFIED: 17792 result = size; 17793 break; 17794 case MeasureSpec.AT_MOST: 17795 case MeasureSpec.EXACTLY: 17796 result = specSize; 17797 break; 17798 } 17799 return result; 17800 } 17801 17802 /** 17803 * Returns the suggested minimum height that the view should use. This 17804 * returns the maximum of the view's minimum height 17805 * and the background's minimum height 17806 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17807 * <p> 17808 * When being used in {@link #onMeasure(int, int)}, the caller should still 17809 * ensure the returned height is within the requirements of the parent. 17810 * 17811 * @return The suggested minimum height of the view. 17812 */ 17813 protected int getSuggestedMinimumHeight() { 17814 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17815 17816 } 17817 17818 /** 17819 * Returns the suggested minimum width that the view should use. This 17820 * returns the maximum of the view's minimum width) 17821 * and the background's minimum width 17822 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17823 * <p> 17824 * When being used in {@link #onMeasure(int, int)}, the caller should still 17825 * ensure the returned width is within the requirements of the parent. 17826 * 17827 * @return The suggested minimum width of the view. 17828 */ 17829 protected int getSuggestedMinimumWidth() { 17830 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17831 } 17832 17833 /** 17834 * Returns the minimum height of the view. 17835 * 17836 * @return the minimum height the view will try to be. 17837 * 17838 * @see #setMinimumHeight(int) 17839 * 17840 * @attr ref android.R.styleable#View_minHeight 17841 */ 17842 public int getMinimumHeight() { 17843 return mMinHeight; 17844 } 17845 17846 /** 17847 * Sets the minimum height of the view. It is not guaranteed the view will 17848 * be able to achieve this minimum height (for example, if its parent layout 17849 * constrains it with less available height). 17850 * 17851 * @param minHeight The minimum height the view will try to be. 17852 * 17853 * @see #getMinimumHeight() 17854 * 17855 * @attr ref android.R.styleable#View_minHeight 17856 */ 17857 public void setMinimumHeight(int minHeight) { 17858 mMinHeight = minHeight; 17859 requestLayout(); 17860 } 17861 17862 /** 17863 * Returns the minimum width of the view. 17864 * 17865 * @return the minimum width the view will try to be. 17866 * 17867 * @see #setMinimumWidth(int) 17868 * 17869 * @attr ref android.R.styleable#View_minWidth 17870 */ 17871 public int getMinimumWidth() { 17872 return mMinWidth; 17873 } 17874 17875 /** 17876 * Sets the minimum width of the view. It is not guaranteed the view will 17877 * be able to achieve this minimum width (for example, if its parent layout 17878 * constrains it with less available width). 17879 * 17880 * @param minWidth The minimum width the view will try to be. 17881 * 17882 * @see #getMinimumWidth() 17883 * 17884 * @attr ref android.R.styleable#View_minWidth 17885 */ 17886 public void setMinimumWidth(int minWidth) { 17887 mMinWidth = minWidth; 17888 requestLayout(); 17889 17890 } 17891 17892 /** 17893 * Get the animation currently associated with this view. 17894 * 17895 * @return The animation that is currently playing or 17896 * scheduled to play for this view. 17897 */ 17898 public Animation getAnimation() { 17899 return mCurrentAnimation; 17900 } 17901 17902 /** 17903 * Start the specified animation now. 17904 * 17905 * @param animation the animation to start now 17906 */ 17907 public void startAnimation(Animation animation) { 17908 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17909 setAnimation(animation); 17910 invalidateParentCaches(); 17911 invalidate(true); 17912 } 17913 17914 /** 17915 * Cancels any animations for this view. 17916 */ 17917 public void clearAnimation() { 17918 if (mCurrentAnimation != null) { 17919 mCurrentAnimation.detach(); 17920 } 17921 mCurrentAnimation = null; 17922 invalidateParentIfNeeded(); 17923 } 17924 17925 /** 17926 * Sets the next animation to play for this view. 17927 * If you want the animation to play immediately, use 17928 * {@link #startAnimation(android.view.animation.Animation)} instead. 17929 * This method provides allows fine-grained 17930 * control over the start time and invalidation, but you 17931 * must make sure that 1) the animation has a start time set, and 17932 * 2) the view's parent (which controls animations on its children) 17933 * will be invalidated when the animation is supposed to 17934 * start. 17935 * 17936 * @param animation The next animation, or null. 17937 */ 17938 public void setAnimation(Animation animation) { 17939 mCurrentAnimation = animation; 17940 17941 if (animation != null) { 17942 // If the screen is off assume the animation start time is now instead of 17943 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17944 // would cause the animation to start when the screen turns back on 17945 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17946 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17947 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17948 } 17949 animation.reset(); 17950 } 17951 } 17952 17953 /** 17954 * Invoked by a parent ViewGroup to notify the start of the animation 17955 * currently associated with this view. If you override this method, 17956 * always call super.onAnimationStart(); 17957 * 17958 * @see #setAnimation(android.view.animation.Animation) 17959 * @see #getAnimation() 17960 */ 17961 protected void onAnimationStart() { 17962 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17963 } 17964 17965 /** 17966 * Invoked by a parent ViewGroup to notify the end of the animation 17967 * currently associated with this view. If you override this method, 17968 * always call super.onAnimationEnd(); 17969 * 17970 * @see #setAnimation(android.view.animation.Animation) 17971 * @see #getAnimation() 17972 */ 17973 protected void onAnimationEnd() { 17974 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17975 } 17976 17977 /** 17978 * Invoked if there is a Transform that involves alpha. Subclass that can 17979 * draw themselves with the specified alpha should return true, and then 17980 * respect that alpha when their onDraw() is called. If this returns false 17981 * then the view may be redirected to draw into an offscreen buffer to 17982 * fulfill the request, which will look fine, but may be slower than if the 17983 * subclass handles it internally. The default implementation returns false. 17984 * 17985 * @param alpha The alpha (0..255) to apply to the view's drawing 17986 * @return true if the view can draw with the specified alpha. 17987 */ 17988 protected boolean onSetAlpha(int alpha) { 17989 return false; 17990 } 17991 17992 /** 17993 * This is used by the RootView to perform an optimization when 17994 * the view hierarchy contains one or several SurfaceView. 17995 * SurfaceView is always considered transparent, but its children are not, 17996 * therefore all View objects remove themselves from the global transparent 17997 * region (passed as a parameter to this function). 17998 * 17999 * @param region The transparent region for this ViewAncestor (window). 18000 * 18001 * @return Returns true if the effective visibility of the view at this 18002 * point is opaque, regardless of the transparent region; returns false 18003 * if it is possible for underlying windows to be seen behind the view. 18004 * 18005 * {@hide} 18006 */ 18007 public boolean gatherTransparentRegion(Region region) { 18008 final AttachInfo attachInfo = mAttachInfo; 18009 if (region != null && attachInfo != null) { 18010 final int pflags = mPrivateFlags; 18011 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 18012 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 18013 // remove it from the transparent region. 18014 final int[] location = attachInfo.mTransparentLocation; 18015 getLocationInWindow(location); 18016 region.op(location[0], location[1], location[0] + mRight - mLeft, 18017 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 18018 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null && 18019 mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 18020 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 18021 // exists, so we remove the background drawable's non-transparent 18022 // parts from this transparent region. 18023 applyDrawableToTransparentRegion(mBackground, region); 18024 } 18025 } 18026 return true; 18027 } 18028 18029 /** 18030 * Play a sound effect for this view. 18031 * 18032 * <p>The framework will play sound effects for some built in actions, such as 18033 * clicking, but you may wish to play these effects in your widget, 18034 * for instance, for internal navigation. 18035 * 18036 * <p>The sound effect will only be played if sound effects are enabled by the user, and 18037 * {@link #isSoundEffectsEnabled()} is true. 18038 * 18039 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 18040 */ 18041 public void playSoundEffect(int soundConstant) { 18042 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 18043 return; 18044 } 18045 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 18046 } 18047 18048 /** 18049 * BZZZTT!!1! 18050 * 18051 * <p>Provide haptic feedback to the user for this view. 18052 * 18053 * <p>The framework will provide haptic feedback for some built in actions, 18054 * such as long presses, but you may wish to provide feedback for your 18055 * own widget. 18056 * 18057 * <p>The feedback will only be performed if 18058 * {@link #isHapticFeedbackEnabled()} is true. 18059 * 18060 * @param feedbackConstant One of the constants defined in 18061 * {@link HapticFeedbackConstants} 18062 */ 18063 public boolean performHapticFeedback(int feedbackConstant) { 18064 return performHapticFeedback(feedbackConstant, 0); 18065 } 18066 18067 /** 18068 * BZZZTT!!1! 18069 * 18070 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 18071 * 18072 * @param feedbackConstant One of the constants defined in 18073 * {@link HapticFeedbackConstants} 18074 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 18075 */ 18076 public boolean performHapticFeedback(int feedbackConstant, int flags) { 18077 if (mAttachInfo == null) { 18078 return false; 18079 } 18080 //noinspection SimplifiableIfStatement 18081 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 18082 && !isHapticFeedbackEnabled()) { 18083 return false; 18084 } 18085 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 18086 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 18087 } 18088 18089 /** 18090 * Request that the visibility of the status bar or other screen/window 18091 * decorations be changed. 18092 * 18093 * <p>This method is used to put the over device UI into temporary modes 18094 * where the user's attention is focused more on the application content, 18095 * by dimming or hiding surrounding system affordances. This is typically 18096 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 18097 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 18098 * to be placed behind the action bar (and with these flags other system 18099 * affordances) so that smooth transitions between hiding and showing them 18100 * can be done. 18101 * 18102 * <p>Two representative examples of the use of system UI visibility is 18103 * implementing a content browsing application (like a magazine reader) 18104 * and a video playing application. 18105 * 18106 * <p>The first code shows a typical implementation of a View in a content 18107 * browsing application. In this implementation, the application goes 18108 * into a content-oriented mode by hiding the status bar and action bar, 18109 * and putting the navigation elements into lights out mode. The user can 18110 * then interact with content while in this mode. Such an application should 18111 * provide an easy way for the user to toggle out of the mode (such as to 18112 * check information in the status bar or access notifications). In the 18113 * implementation here, this is done simply by tapping on the content. 18114 * 18115 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 18116 * content} 18117 * 18118 * <p>This second code sample shows a typical implementation of a View 18119 * in a video playing application. In this situation, while the video is 18120 * playing the application would like to go into a complete full-screen mode, 18121 * to use as much of the display as possible for the video. When in this state 18122 * the user can not interact with the application; the system intercepts 18123 * touching on the screen to pop the UI out of full screen mode. See 18124 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 18125 * 18126 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 18127 * content} 18128 * 18129 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18130 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 18131 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 18132 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 18133 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 18134 */ 18135 public void setSystemUiVisibility(int visibility) { 18136 if (visibility != mSystemUiVisibility) { 18137 mSystemUiVisibility = visibility; 18138 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 18139 mParent.recomputeViewAttributes(this); 18140 } 18141 } 18142 } 18143 18144 /** 18145 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 18146 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18147 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 18148 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 18149 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 18150 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 18151 */ 18152 public int getSystemUiVisibility() { 18153 return mSystemUiVisibility; 18154 } 18155 18156 /** 18157 * Returns the current system UI visibility that is currently set for 18158 * the entire window. This is the combination of the 18159 * {@link #setSystemUiVisibility(int)} values supplied by all of the 18160 * views in the window. 18161 */ 18162 public int getWindowSystemUiVisibility() { 18163 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 18164 } 18165 18166 /** 18167 * Override to find out when the window's requested system UI visibility 18168 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 18169 * This is different from the callbacks received through 18170 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 18171 * in that this is only telling you about the local request of the window, 18172 * not the actual values applied by the system. 18173 */ 18174 public void onWindowSystemUiVisibilityChanged(int visible) { 18175 } 18176 18177 /** 18178 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 18179 * the view hierarchy. 18180 */ 18181 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 18182 onWindowSystemUiVisibilityChanged(visible); 18183 } 18184 18185 /** 18186 * Set a listener to receive callbacks when the visibility of the system bar changes. 18187 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 18188 */ 18189 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 18190 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 18191 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 18192 mParent.recomputeViewAttributes(this); 18193 } 18194 } 18195 18196 /** 18197 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 18198 * the view hierarchy. 18199 */ 18200 public void dispatchSystemUiVisibilityChanged(int visibility) { 18201 ListenerInfo li = mListenerInfo; 18202 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 18203 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 18204 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 18205 } 18206 } 18207 18208 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 18209 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 18210 if (val != mSystemUiVisibility) { 18211 setSystemUiVisibility(val); 18212 return true; 18213 } 18214 return false; 18215 } 18216 18217 /** @hide */ 18218 public void setDisabledSystemUiVisibility(int flags) { 18219 if (mAttachInfo != null) { 18220 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 18221 mAttachInfo.mDisabledSystemUiVisibility = flags; 18222 if (mParent != null) { 18223 mParent.recomputeViewAttributes(this); 18224 } 18225 } 18226 } 18227 } 18228 18229 /** 18230 * Creates an image that the system displays during the drag and drop 18231 * operation. This is called a "drag shadow". The default implementation 18232 * for a DragShadowBuilder based on a View returns an image that has exactly the same 18233 * appearance as the given View. The default also positions the center of the drag shadow 18234 * directly under the touch point. If no View is provided (the constructor with no parameters 18235 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 18236 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 18237 * default is an invisible drag shadow. 18238 * <p> 18239 * You are not required to use the View you provide to the constructor as the basis of the 18240 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 18241 * anything you want as the drag shadow. 18242 * </p> 18243 * <p> 18244 * You pass a DragShadowBuilder object to the system when you start the drag. The system 18245 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 18246 * size and position of the drag shadow. It uses this data to construct a 18247 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 18248 * so that your application can draw the shadow image in the Canvas. 18249 * </p> 18250 * 18251 * <div class="special reference"> 18252 * <h3>Developer Guides</h3> 18253 * <p>For a guide to implementing drag and drop features, read the 18254 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 18255 * </div> 18256 */ 18257 public static class DragShadowBuilder { 18258 private final WeakReference<View> mView; 18259 18260 /** 18261 * Constructs a shadow image builder based on a View. By default, the resulting drag 18262 * shadow will have the same appearance and dimensions as the View, with the touch point 18263 * over the center of the View. 18264 * @param view A View. Any View in scope can be used. 18265 */ 18266 public DragShadowBuilder(View view) { 18267 mView = new WeakReference<View>(view); 18268 } 18269 18270 /** 18271 * Construct a shadow builder object with no associated View. This 18272 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 18273 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 18274 * to supply the drag shadow's dimensions and appearance without 18275 * reference to any View object. If they are not overridden, then the result is an 18276 * invisible drag shadow. 18277 */ 18278 public DragShadowBuilder() { 18279 mView = new WeakReference<View>(null); 18280 } 18281 18282 /** 18283 * Returns the View object that had been passed to the 18284 * {@link #View.DragShadowBuilder(View)} 18285 * constructor. If that View parameter was {@code null} or if the 18286 * {@link #View.DragShadowBuilder()} 18287 * constructor was used to instantiate the builder object, this method will return 18288 * null. 18289 * 18290 * @return The View object associate with this builder object. 18291 */ 18292 @SuppressWarnings({"JavadocReference"}) 18293 final public View getView() { 18294 return mView.get(); 18295 } 18296 18297 /** 18298 * Provides the metrics for the shadow image. These include the dimensions of 18299 * the shadow image, and the point within that shadow that should 18300 * be centered under the touch location while dragging. 18301 * <p> 18302 * The default implementation sets the dimensions of the shadow to be the 18303 * same as the dimensions of the View itself and centers the shadow under 18304 * the touch point. 18305 * </p> 18306 * 18307 * @param shadowSize A {@link android.graphics.Point} containing the width and height 18308 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 18309 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 18310 * image. 18311 * 18312 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 18313 * shadow image that should be underneath the touch point during the drag and drop 18314 * operation. Your application must set {@link android.graphics.Point#x} to the 18315 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 18316 */ 18317 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 18318 final View view = mView.get(); 18319 if (view != null) { 18320 shadowSize.set(view.getWidth(), view.getHeight()); 18321 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 18322 } else { 18323 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 18324 } 18325 } 18326 18327 /** 18328 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 18329 * based on the dimensions it received from the 18330 * {@link #onProvideShadowMetrics(Point, Point)} callback. 18331 * 18332 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 18333 */ 18334 public void onDrawShadow(Canvas canvas) { 18335 final View view = mView.get(); 18336 if (view != null) { 18337 view.draw(canvas); 18338 } else { 18339 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 18340 } 18341 } 18342 } 18343 18344 /** 18345 * Starts a drag and drop operation. When your application calls this method, it passes a 18346 * {@link android.view.View.DragShadowBuilder} object to the system. The 18347 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 18348 * to get metrics for the drag shadow, and then calls the object's 18349 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 18350 * <p> 18351 * Once the system has the drag shadow, it begins the drag and drop operation by sending 18352 * drag events to all the View objects in your application that are currently visible. It does 18353 * this either by calling the View object's drag listener (an implementation of 18354 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 18355 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 18356 * Both are passed a {@link android.view.DragEvent} object that has a 18357 * {@link android.view.DragEvent#getAction()} value of 18358 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 18359 * </p> 18360 * <p> 18361 * Your application can invoke startDrag() on any attached View object. The View object does not 18362 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 18363 * be related to the View the user selected for dragging. 18364 * </p> 18365 * @param data A {@link android.content.ClipData} object pointing to the data to be 18366 * transferred by the drag and drop operation. 18367 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 18368 * drag shadow. 18369 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 18370 * drop operation. This Object is put into every DragEvent object sent by the system during the 18371 * current drag. 18372 * <p> 18373 * myLocalState is a lightweight mechanism for the sending information from the dragged View 18374 * to the target Views. For example, it can contain flags that differentiate between a 18375 * a copy operation and a move operation. 18376 * </p> 18377 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 18378 * so the parameter should be set to 0. 18379 * @return {@code true} if the method completes successfully, or 18380 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 18381 * do a drag, and so no drag operation is in progress. 18382 */ 18383 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 18384 Object myLocalState, int flags) { 18385 if (ViewDebug.DEBUG_DRAG) { 18386 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 18387 } 18388 boolean okay = false; 18389 18390 Point shadowSize = new Point(); 18391 Point shadowTouchPoint = new Point(); 18392 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 18393 18394 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 18395 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 18396 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 18397 } 18398 18399 if (ViewDebug.DEBUG_DRAG) { 18400 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 18401 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 18402 } 18403 Surface surface = new Surface(); 18404 try { 18405 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 18406 flags, shadowSize.x, shadowSize.y, surface); 18407 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 18408 + " surface=" + surface); 18409 if (token != null) { 18410 Canvas canvas = surface.lockCanvas(null); 18411 try { 18412 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 18413 shadowBuilder.onDrawShadow(canvas); 18414 } finally { 18415 surface.unlockCanvasAndPost(canvas); 18416 } 18417 18418 final ViewRootImpl root = getViewRootImpl(); 18419 18420 // Cache the local state object for delivery with DragEvents 18421 root.setLocalDragState(myLocalState); 18422 18423 // repurpose 'shadowSize' for the last touch point 18424 root.getLastTouchPoint(shadowSize); 18425 18426 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 18427 shadowSize.x, shadowSize.y, 18428 shadowTouchPoint.x, shadowTouchPoint.y, data); 18429 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 18430 18431 // Off and running! Release our local surface instance; the drag 18432 // shadow surface is now managed by the system process. 18433 surface.release(); 18434 } 18435 } catch (Exception e) { 18436 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 18437 surface.destroy(); 18438 } 18439 18440 return okay; 18441 } 18442 18443 /** 18444 * Handles drag events sent by the system following a call to 18445 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 18446 *<p> 18447 * When the system calls this method, it passes a 18448 * {@link android.view.DragEvent} object. A call to 18449 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 18450 * in DragEvent. The method uses these to determine what is happening in the drag and drop 18451 * operation. 18452 * @param event The {@link android.view.DragEvent} sent by the system. 18453 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 18454 * in DragEvent, indicating the type of drag event represented by this object. 18455 * @return {@code true} if the method was successful, otherwise {@code false}. 18456 * <p> 18457 * The method should return {@code true} in response to an action type of 18458 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 18459 * operation. 18460 * </p> 18461 * <p> 18462 * The method should also return {@code true} in response to an action type of 18463 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 18464 * {@code false} if it didn't. 18465 * </p> 18466 */ 18467 public boolean onDragEvent(DragEvent event) { 18468 return false; 18469 } 18470 18471 /** 18472 * Detects if this View is enabled and has a drag event listener. 18473 * If both are true, then it calls the drag event listener with the 18474 * {@link android.view.DragEvent} it received. If the drag event listener returns 18475 * {@code true}, then dispatchDragEvent() returns {@code true}. 18476 * <p> 18477 * For all other cases, the method calls the 18478 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 18479 * method and returns its result. 18480 * </p> 18481 * <p> 18482 * This ensures that a drag event is always consumed, even if the View does not have a drag 18483 * event listener. However, if the View has a listener and the listener returns true, then 18484 * onDragEvent() is not called. 18485 * </p> 18486 */ 18487 public boolean dispatchDragEvent(DragEvent event) { 18488 ListenerInfo li = mListenerInfo; 18489 //noinspection SimplifiableIfStatement 18490 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 18491 && li.mOnDragListener.onDrag(this, event)) { 18492 return true; 18493 } 18494 return onDragEvent(event); 18495 } 18496 18497 boolean canAcceptDrag() { 18498 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 18499 } 18500 18501 /** 18502 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 18503 * it is ever exposed at all. 18504 * @hide 18505 */ 18506 public void onCloseSystemDialogs(String reason) { 18507 } 18508 18509 /** 18510 * Given a Drawable whose bounds have been set to draw into this view, 18511 * update a Region being computed for 18512 * {@link #gatherTransparentRegion(android.graphics.Region)} so 18513 * that any non-transparent parts of the Drawable are removed from the 18514 * given transparent region. 18515 * 18516 * @param dr The Drawable whose transparency is to be applied to the region. 18517 * @param region A Region holding the current transparency information, 18518 * where any parts of the region that are set are considered to be 18519 * transparent. On return, this region will be modified to have the 18520 * transparency information reduced by the corresponding parts of the 18521 * Drawable that are not transparent. 18522 * {@hide} 18523 */ 18524 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 18525 if (DBG) { 18526 Log.i("View", "Getting transparent region for: " + this); 18527 } 18528 final Region r = dr.getTransparentRegion(); 18529 final Rect db = dr.getBounds(); 18530 final AttachInfo attachInfo = mAttachInfo; 18531 if (r != null && attachInfo != null) { 18532 final int w = getRight()-getLeft(); 18533 final int h = getBottom()-getTop(); 18534 if (db.left > 0) { 18535 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 18536 r.op(0, 0, db.left, h, Region.Op.UNION); 18537 } 18538 if (db.right < w) { 18539 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 18540 r.op(db.right, 0, w, h, Region.Op.UNION); 18541 } 18542 if (db.top > 0) { 18543 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 18544 r.op(0, 0, w, db.top, Region.Op.UNION); 18545 } 18546 if (db.bottom < h) { 18547 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 18548 r.op(0, db.bottom, w, h, Region.Op.UNION); 18549 } 18550 final int[] location = attachInfo.mTransparentLocation; 18551 getLocationInWindow(location); 18552 r.translate(location[0], location[1]); 18553 region.op(r, Region.Op.INTERSECT); 18554 } else { 18555 region.op(db, Region.Op.DIFFERENCE); 18556 } 18557 } 18558 18559 private void checkForLongClick(int delayOffset) { 18560 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 18561 mHasPerformedLongPress = false; 18562 18563 if (mPendingCheckForLongPress == null) { 18564 mPendingCheckForLongPress = new CheckForLongPress(); 18565 } 18566 mPendingCheckForLongPress.rememberWindowAttachCount(); 18567 postDelayed(mPendingCheckForLongPress, 18568 ViewConfiguration.getLongPressTimeout() - delayOffset); 18569 } 18570 } 18571 18572 /** 18573 * Inflate a view from an XML resource. This convenience method wraps the {@link 18574 * LayoutInflater} class, which provides a full range of options for view inflation. 18575 * 18576 * @param context The Context object for your activity or application. 18577 * @param resource The resource ID to inflate 18578 * @param root A view group that will be the parent. Used to properly inflate the 18579 * layout_* parameters. 18580 * @see LayoutInflater 18581 */ 18582 public static View inflate(Context context, int resource, ViewGroup root) { 18583 LayoutInflater factory = LayoutInflater.from(context); 18584 return factory.inflate(resource, root); 18585 } 18586 18587 /** 18588 * Scroll the view with standard behavior for scrolling beyond the normal 18589 * content boundaries. Views that call this method should override 18590 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 18591 * results of an over-scroll operation. 18592 * 18593 * Views can use this method to handle any touch or fling-based scrolling. 18594 * 18595 * @param deltaX Change in X in pixels 18596 * @param deltaY Change in Y in pixels 18597 * @param scrollX Current X scroll value in pixels before applying deltaX 18598 * @param scrollY Current Y scroll value in pixels before applying deltaY 18599 * @param scrollRangeX Maximum content scroll range along the X axis 18600 * @param scrollRangeY Maximum content scroll range along the Y axis 18601 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18602 * along the X axis. 18603 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18604 * along the Y axis. 18605 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18606 * @return true if scrolling was clamped to an over-scroll boundary along either 18607 * axis, false otherwise. 18608 */ 18609 @SuppressWarnings({"UnusedParameters"}) 18610 protected boolean overScrollBy(int deltaX, int deltaY, 18611 int scrollX, int scrollY, 18612 int scrollRangeX, int scrollRangeY, 18613 int maxOverScrollX, int maxOverScrollY, 18614 boolean isTouchEvent) { 18615 final int overScrollMode = mOverScrollMode; 18616 final boolean canScrollHorizontal = 18617 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18618 final boolean canScrollVertical = 18619 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18620 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18621 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18622 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18623 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18624 18625 int newScrollX = scrollX + deltaX; 18626 if (!overScrollHorizontal) { 18627 maxOverScrollX = 0; 18628 } 18629 18630 int newScrollY = scrollY + deltaY; 18631 if (!overScrollVertical) { 18632 maxOverScrollY = 0; 18633 } 18634 18635 // Clamp values if at the limits and record 18636 final int left = -maxOverScrollX; 18637 final int right = maxOverScrollX + scrollRangeX; 18638 final int top = -maxOverScrollY; 18639 final int bottom = maxOverScrollY + scrollRangeY; 18640 18641 boolean clampedX = false; 18642 if (newScrollX > right) { 18643 newScrollX = right; 18644 clampedX = true; 18645 } else if (newScrollX < left) { 18646 newScrollX = left; 18647 clampedX = true; 18648 } 18649 18650 boolean clampedY = false; 18651 if (newScrollY > bottom) { 18652 newScrollY = bottom; 18653 clampedY = true; 18654 } else if (newScrollY < top) { 18655 newScrollY = top; 18656 clampedY = true; 18657 } 18658 18659 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18660 18661 return clampedX || clampedY; 18662 } 18663 18664 /** 18665 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18666 * respond to the results of an over-scroll operation. 18667 * 18668 * @param scrollX New X scroll value in pixels 18669 * @param scrollY New Y scroll value in pixels 18670 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18671 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18672 */ 18673 protected void onOverScrolled(int scrollX, int scrollY, 18674 boolean clampedX, boolean clampedY) { 18675 // Intentionally empty. 18676 } 18677 18678 /** 18679 * Returns the over-scroll mode for this view. The result will be 18680 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18681 * (allow over-scrolling only if the view content is larger than the container), 18682 * or {@link #OVER_SCROLL_NEVER}. 18683 * 18684 * @return This view's over-scroll mode. 18685 */ 18686 public int getOverScrollMode() { 18687 return mOverScrollMode; 18688 } 18689 18690 /** 18691 * Set the over-scroll mode for this view. Valid over-scroll modes are 18692 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18693 * (allow over-scrolling only if the view content is larger than the container), 18694 * or {@link #OVER_SCROLL_NEVER}. 18695 * 18696 * Setting the over-scroll mode of a view will have an effect only if the 18697 * view is capable of scrolling. 18698 * 18699 * @param overScrollMode The new over-scroll mode for this view. 18700 */ 18701 public void setOverScrollMode(int overScrollMode) { 18702 if (overScrollMode != OVER_SCROLL_ALWAYS && 18703 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18704 overScrollMode != OVER_SCROLL_NEVER) { 18705 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18706 } 18707 mOverScrollMode = overScrollMode; 18708 } 18709 18710 /** 18711 * Enable or disable nested scrolling for this view. 18712 * 18713 * <p>If this property is set to true the view will be permitted to initiate nested 18714 * scrolling operations with a compatible parent view in the current hierarchy. If this 18715 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18716 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18717 * the nested scroll.</p> 18718 * 18719 * @param enabled true to enable nested scrolling, false to disable 18720 * 18721 * @see #isNestedScrollingEnabled() 18722 */ 18723 public void setNestedScrollingEnabled(boolean enabled) { 18724 if (enabled) { 18725 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18726 } else { 18727 stopNestedScroll(); 18728 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18729 } 18730 } 18731 18732 /** 18733 * Returns true if nested scrolling is enabled for this view. 18734 * 18735 * <p>If nested scrolling is enabled and this View class implementation supports it, 18736 * this view will act as a nested scrolling child view when applicable, forwarding data 18737 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18738 * parent.</p> 18739 * 18740 * @return true if nested scrolling is enabled 18741 * 18742 * @see #setNestedScrollingEnabled(boolean) 18743 */ 18744 public boolean isNestedScrollingEnabled() { 18745 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18746 PFLAG3_NESTED_SCROLLING_ENABLED; 18747 } 18748 18749 /** 18750 * Begin a nestable scroll operation along the given axes. 18751 * 18752 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18753 * 18754 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18755 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18756 * In the case of touch scrolling the nested scroll will be terminated automatically in 18757 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18758 * In the event of programmatic scrolling the caller must explicitly call 18759 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18760 * 18761 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18762 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18763 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18764 * 18765 * <p>At each incremental step of the scroll the caller should invoke 18766 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18767 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18768 * parent at least partially consumed the scroll and the caller should adjust the amount it 18769 * scrolls by.</p> 18770 * 18771 * <p>After applying the remainder of the scroll delta the caller should invoke 18772 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18773 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18774 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18775 * </p> 18776 * 18777 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18778 * {@link #SCROLL_AXIS_VERTICAL}. 18779 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18780 * the current gesture. 18781 * 18782 * @see #stopNestedScroll() 18783 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18784 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18785 */ 18786 public boolean startNestedScroll(int axes) { 18787 if (hasNestedScrollingParent()) { 18788 // Already in progress 18789 return true; 18790 } 18791 if (isNestedScrollingEnabled()) { 18792 ViewParent p = getParent(); 18793 View child = this; 18794 while (p != null) { 18795 try { 18796 if (p.onStartNestedScroll(child, this, axes)) { 18797 mNestedScrollingParent = p; 18798 p.onNestedScrollAccepted(child, this, axes); 18799 return true; 18800 } 18801 } catch (AbstractMethodError e) { 18802 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18803 "method onStartNestedScroll", e); 18804 // Allow the search upward to continue 18805 } 18806 if (p instanceof View) { 18807 child = (View) p; 18808 } 18809 p = p.getParent(); 18810 } 18811 } 18812 return false; 18813 } 18814 18815 /** 18816 * Stop a nested scroll in progress. 18817 * 18818 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18819 * 18820 * @see #startNestedScroll(int) 18821 */ 18822 public void stopNestedScroll() { 18823 if (mNestedScrollingParent != null) { 18824 mNestedScrollingParent.onStopNestedScroll(this); 18825 mNestedScrollingParent = null; 18826 } 18827 } 18828 18829 /** 18830 * Returns true if this view has a nested scrolling parent. 18831 * 18832 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18833 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18834 * 18835 * @return whether this view has a nested scrolling parent 18836 */ 18837 public boolean hasNestedScrollingParent() { 18838 return mNestedScrollingParent != null; 18839 } 18840 18841 /** 18842 * Dispatch one step of a nested scroll in progress. 18843 * 18844 * <p>Implementations of views that support nested scrolling should call this to report 18845 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18846 * is not currently in progress or nested scrolling is not 18847 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18848 * 18849 * <p>Compatible View implementations should also call 18850 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18851 * consuming a component of the scroll event themselves.</p> 18852 * 18853 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18854 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18855 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18856 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18857 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18858 * in local view coordinates of this view from before this operation 18859 * to after it completes. View implementations may use this to adjust 18860 * expected input coordinate tracking. 18861 * @return true if the event was dispatched, false if it could not be dispatched. 18862 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18863 */ 18864 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18865 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18866 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18867 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18868 int startX = 0; 18869 int startY = 0; 18870 if (offsetInWindow != null) { 18871 getLocationInWindow(offsetInWindow); 18872 startX = offsetInWindow[0]; 18873 startY = offsetInWindow[1]; 18874 } 18875 18876 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18877 dxUnconsumed, dyUnconsumed); 18878 18879 if (offsetInWindow != null) { 18880 getLocationInWindow(offsetInWindow); 18881 offsetInWindow[0] -= startX; 18882 offsetInWindow[1] -= startY; 18883 } 18884 return true; 18885 } else if (offsetInWindow != null) { 18886 // No motion, no dispatch. Keep offsetInWindow up to date. 18887 offsetInWindow[0] = 0; 18888 offsetInWindow[1] = 0; 18889 } 18890 } 18891 return false; 18892 } 18893 18894 /** 18895 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18896 * 18897 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18898 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18899 * scrolling operation to consume some or all of the scroll operation before the child view 18900 * consumes it.</p> 18901 * 18902 * @param dx Horizontal scroll distance in pixels 18903 * @param dy Vertical scroll distance in pixels 18904 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18905 * and consumed[1] the consumed dy. 18906 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18907 * in local view coordinates of this view from before this operation 18908 * to after it completes. View implementations may use this to adjust 18909 * expected input coordinate tracking. 18910 * @return true if the parent consumed some or all of the scroll delta 18911 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18912 */ 18913 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18914 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18915 if (dx != 0 || dy != 0) { 18916 int startX = 0; 18917 int startY = 0; 18918 if (offsetInWindow != null) { 18919 getLocationInWindow(offsetInWindow); 18920 startX = offsetInWindow[0]; 18921 startY = offsetInWindow[1]; 18922 } 18923 18924 if (consumed == null) { 18925 if (mTempNestedScrollConsumed == null) { 18926 mTempNestedScrollConsumed = new int[2]; 18927 } 18928 consumed = mTempNestedScrollConsumed; 18929 } 18930 consumed[0] = 0; 18931 consumed[1] = 0; 18932 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18933 18934 if (offsetInWindow != null) { 18935 getLocationInWindow(offsetInWindow); 18936 offsetInWindow[0] -= startX; 18937 offsetInWindow[1] -= startY; 18938 } 18939 return consumed[0] != 0 || consumed[1] != 0; 18940 } else if (offsetInWindow != null) { 18941 offsetInWindow[0] = 0; 18942 offsetInWindow[1] = 0; 18943 } 18944 } 18945 return false; 18946 } 18947 18948 /** 18949 * Dispatch a fling to a nested scrolling parent. 18950 * 18951 * <p>This method should be used to indicate that a nested scrolling child has detected 18952 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18953 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18954 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18955 * along a scrollable axis.</p> 18956 * 18957 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18958 * its own content, it can use this method to delegate the fling to its nested scrolling 18959 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18960 * 18961 * @param velocityX Horizontal fling velocity in pixels per second 18962 * @param velocityY Vertical fling velocity in pixels per second 18963 * @param consumed true if the child consumed the fling, false otherwise 18964 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18965 */ 18966 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18967 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18968 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18969 } 18970 return false; 18971 } 18972 18973 /** 18974 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 18975 * 18976 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 18977 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 18978 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 18979 * before the child view consumes it. If this method returns <code>true</code>, a nested 18980 * parent view consumed the fling and this view should not scroll as a result.</p> 18981 * 18982 * <p>For a better user experience, only one view in a nested scrolling chain should consume 18983 * the fling at a time. If a parent view consumed the fling this method will return false. 18984 * Custom view implementations should account for this in two ways:</p> 18985 * 18986 * <ul> 18987 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 18988 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 18989 * position regardless.</li> 18990 * <li>If a nested parent does consume the fling, this view should not scroll at all, 18991 * even to settle back to a valid idle position.</li> 18992 * </ul> 18993 * 18994 * <p>Views should also not offer fling velocities to nested parent views along an axis 18995 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 18996 * should not offer a horizontal fling velocity to its parents since scrolling along that 18997 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 18998 * 18999 * @param velocityX Horizontal fling velocity in pixels per second 19000 * @param velocityY Vertical fling velocity in pixels per second 19001 * @return true if a nested scrolling parent consumed the fling 19002 */ 19003 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 19004 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 19005 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 19006 } 19007 return false; 19008 } 19009 19010 /** 19011 * Gets a scale factor that determines the distance the view should scroll 19012 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 19013 * @return The vertical scroll scale factor. 19014 * @hide 19015 */ 19016 protected float getVerticalScrollFactor() { 19017 if (mVerticalScrollFactor == 0) { 19018 TypedValue outValue = new TypedValue(); 19019 if (!mContext.getTheme().resolveAttribute( 19020 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 19021 throw new IllegalStateException( 19022 "Expected theme to define listPreferredItemHeight."); 19023 } 19024 mVerticalScrollFactor = outValue.getDimension( 19025 mContext.getResources().getDisplayMetrics()); 19026 } 19027 return mVerticalScrollFactor; 19028 } 19029 19030 /** 19031 * Gets a scale factor that determines the distance the view should scroll 19032 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 19033 * @return The horizontal scroll scale factor. 19034 * @hide 19035 */ 19036 protected float getHorizontalScrollFactor() { 19037 // TODO: Should use something else. 19038 return getVerticalScrollFactor(); 19039 } 19040 19041 /** 19042 * Return the value specifying the text direction or policy that was set with 19043 * {@link #setTextDirection(int)}. 19044 * 19045 * @return the defined text direction. It can be one of: 19046 * 19047 * {@link #TEXT_DIRECTION_INHERIT}, 19048 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19049 * {@link #TEXT_DIRECTION_ANY_RTL}, 19050 * {@link #TEXT_DIRECTION_LTR}, 19051 * {@link #TEXT_DIRECTION_RTL}, 19052 * {@link #TEXT_DIRECTION_LOCALE} 19053 * 19054 * @attr ref android.R.styleable#View_textDirection 19055 * 19056 * @hide 19057 */ 19058 @ViewDebug.ExportedProperty(category = "text", mapping = { 19059 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 19060 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 19061 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 19062 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 19063 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 19064 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 19065 }) 19066 public int getRawTextDirection() { 19067 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 19068 } 19069 19070 /** 19071 * Set the text direction. 19072 * 19073 * @param textDirection the direction to set. Should be one of: 19074 * 19075 * {@link #TEXT_DIRECTION_INHERIT}, 19076 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19077 * {@link #TEXT_DIRECTION_ANY_RTL}, 19078 * {@link #TEXT_DIRECTION_LTR}, 19079 * {@link #TEXT_DIRECTION_RTL}, 19080 * {@link #TEXT_DIRECTION_LOCALE} 19081 * 19082 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 19083 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 19084 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 19085 * 19086 * @attr ref android.R.styleable#View_textDirection 19087 */ 19088 public void setTextDirection(int textDirection) { 19089 if (getRawTextDirection() != textDirection) { 19090 // Reset the current text direction and the resolved one 19091 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 19092 resetResolvedTextDirection(); 19093 // Set the new text direction 19094 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 19095 // Do resolution 19096 resolveTextDirection(); 19097 // Notify change 19098 onRtlPropertiesChanged(getLayoutDirection()); 19099 // Refresh 19100 requestLayout(); 19101 invalidate(true); 19102 } 19103 } 19104 19105 /** 19106 * Return the resolved text direction. 19107 * 19108 * @return the resolved text direction. Returns one of: 19109 * 19110 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19111 * {@link #TEXT_DIRECTION_ANY_RTL}, 19112 * {@link #TEXT_DIRECTION_LTR}, 19113 * {@link #TEXT_DIRECTION_RTL}, 19114 * {@link #TEXT_DIRECTION_LOCALE} 19115 * 19116 * @attr ref android.R.styleable#View_textDirection 19117 */ 19118 @ViewDebug.ExportedProperty(category = "text", mapping = { 19119 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 19120 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 19121 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 19122 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 19123 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 19124 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 19125 }) 19126 public int getTextDirection() { 19127 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 19128 } 19129 19130 /** 19131 * Resolve the text direction. 19132 * 19133 * @return true if resolution has been done, false otherwise. 19134 * 19135 * @hide 19136 */ 19137 public boolean resolveTextDirection() { 19138 // Reset any previous text direction resolution 19139 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 19140 19141 if (hasRtlSupport()) { 19142 // Set resolved text direction flag depending on text direction flag 19143 final int textDirection = getRawTextDirection(); 19144 switch(textDirection) { 19145 case TEXT_DIRECTION_INHERIT: 19146 if (!canResolveTextDirection()) { 19147 // We cannot do the resolution if there is no parent, so use the default one 19148 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19149 // Resolution will need to happen again later 19150 return false; 19151 } 19152 19153 // Parent has not yet resolved, so we still return the default 19154 try { 19155 if (!mParent.isTextDirectionResolved()) { 19156 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19157 // Resolution will need to happen again later 19158 return false; 19159 } 19160 } catch (AbstractMethodError e) { 19161 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19162 " does not fully implement ViewParent", e); 19163 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 19164 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19165 return true; 19166 } 19167 19168 // Set current resolved direction to the same value as the parent's one 19169 int parentResolvedDirection; 19170 try { 19171 parentResolvedDirection = mParent.getTextDirection(); 19172 } catch (AbstractMethodError e) { 19173 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19174 " does not fully implement ViewParent", e); 19175 parentResolvedDirection = TEXT_DIRECTION_LTR; 19176 } 19177 switch (parentResolvedDirection) { 19178 case TEXT_DIRECTION_FIRST_STRONG: 19179 case TEXT_DIRECTION_ANY_RTL: 19180 case TEXT_DIRECTION_LTR: 19181 case TEXT_DIRECTION_RTL: 19182 case TEXT_DIRECTION_LOCALE: 19183 mPrivateFlags2 |= 19184 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 19185 break; 19186 default: 19187 // Default resolved direction is "first strong" heuristic 19188 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19189 } 19190 break; 19191 case TEXT_DIRECTION_FIRST_STRONG: 19192 case TEXT_DIRECTION_ANY_RTL: 19193 case TEXT_DIRECTION_LTR: 19194 case TEXT_DIRECTION_RTL: 19195 case TEXT_DIRECTION_LOCALE: 19196 // Resolved direction is the same as text direction 19197 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 19198 break; 19199 default: 19200 // Default resolved direction is "first strong" heuristic 19201 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19202 } 19203 } else { 19204 // Default resolved direction is "first strong" heuristic 19205 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19206 } 19207 19208 // Set to resolved 19209 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 19210 return true; 19211 } 19212 19213 /** 19214 * Check if text direction resolution can be done. 19215 * 19216 * @return true if text direction resolution can be done otherwise return false. 19217 */ 19218 public boolean canResolveTextDirection() { 19219 switch (getRawTextDirection()) { 19220 case TEXT_DIRECTION_INHERIT: 19221 if (mParent != null) { 19222 try { 19223 return mParent.canResolveTextDirection(); 19224 } catch (AbstractMethodError e) { 19225 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19226 " does not fully implement ViewParent", e); 19227 } 19228 } 19229 return false; 19230 19231 default: 19232 return true; 19233 } 19234 } 19235 19236 /** 19237 * Reset resolved text direction. Text direction will be resolved during a call to 19238 * {@link #onMeasure(int, int)}. 19239 * 19240 * @hide 19241 */ 19242 public void resetResolvedTextDirection() { 19243 // Reset any previous text direction resolution 19244 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 19245 // Set to default value 19246 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19247 } 19248 19249 /** 19250 * @return true if text direction is inherited. 19251 * 19252 * @hide 19253 */ 19254 public boolean isTextDirectionInherited() { 19255 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 19256 } 19257 19258 /** 19259 * @return true if text direction is resolved. 19260 */ 19261 public boolean isTextDirectionResolved() { 19262 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 19263 } 19264 19265 /** 19266 * Return the value specifying the text alignment or policy that was set with 19267 * {@link #setTextAlignment(int)}. 19268 * 19269 * @return the defined text alignment. It can be one of: 19270 * 19271 * {@link #TEXT_ALIGNMENT_INHERIT}, 19272 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19273 * {@link #TEXT_ALIGNMENT_CENTER}, 19274 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19275 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19276 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19277 * {@link #TEXT_ALIGNMENT_VIEW_END} 19278 * 19279 * @attr ref android.R.styleable#View_textAlignment 19280 * 19281 * @hide 19282 */ 19283 @ViewDebug.ExportedProperty(category = "text", mapping = { 19284 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19285 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19286 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19287 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19288 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19289 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19290 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19291 }) 19292 @TextAlignment 19293 public int getRawTextAlignment() { 19294 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 19295 } 19296 19297 /** 19298 * Set the text alignment. 19299 * 19300 * @param textAlignment The text alignment to set. Should be one of 19301 * 19302 * {@link #TEXT_ALIGNMENT_INHERIT}, 19303 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19304 * {@link #TEXT_ALIGNMENT_CENTER}, 19305 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19306 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19307 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19308 * {@link #TEXT_ALIGNMENT_VIEW_END} 19309 * 19310 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 19311 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 19312 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 19313 * 19314 * @attr ref android.R.styleable#View_textAlignment 19315 */ 19316 public void setTextAlignment(@TextAlignment int textAlignment) { 19317 if (textAlignment != getRawTextAlignment()) { 19318 // Reset the current and resolved text alignment 19319 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 19320 resetResolvedTextAlignment(); 19321 // Set the new text alignment 19322 mPrivateFlags2 |= 19323 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 19324 // Do resolution 19325 resolveTextAlignment(); 19326 // Notify change 19327 onRtlPropertiesChanged(getLayoutDirection()); 19328 // Refresh 19329 requestLayout(); 19330 invalidate(true); 19331 } 19332 } 19333 19334 /** 19335 * Return the resolved text alignment. 19336 * 19337 * @return the resolved text alignment. Returns one of: 19338 * 19339 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19340 * {@link #TEXT_ALIGNMENT_CENTER}, 19341 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19342 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19343 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19344 * {@link #TEXT_ALIGNMENT_VIEW_END} 19345 * 19346 * @attr ref android.R.styleable#View_textAlignment 19347 */ 19348 @ViewDebug.ExportedProperty(category = "text", mapping = { 19349 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19350 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19351 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19352 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19353 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19354 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19355 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19356 }) 19357 @TextAlignment 19358 public int getTextAlignment() { 19359 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 19360 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 19361 } 19362 19363 /** 19364 * Resolve the text alignment. 19365 * 19366 * @return true if resolution has been done, false otherwise. 19367 * 19368 * @hide 19369 */ 19370 public boolean resolveTextAlignment() { 19371 // Reset any previous text alignment resolution 19372 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19373 19374 if (hasRtlSupport()) { 19375 // Set resolved text alignment flag depending on text alignment flag 19376 final int textAlignment = getRawTextAlignment(); 19377 switch (textAlignment) { 19378 case TEXT_ALIGNMENT_INHERIT: 19379 // Check if we can resolve the text alignment 19380 if (!canResolveTextAlignment()) { 19381 // We cannot do the resolution if there is no parent so use the default 19382 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19383 // Resolution will need to happen again later 19384 return false; 19385 } 19386 19387 // Parent has not yet resolved, so we still return the default 19388 try { 19389 if (!mParent.isTextAlignmentResolved()) { 19390 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19391 // Resolution will need to happen again later 19392 return false; 19393 } 19394 } catch (AbstractMethodError e) { 19395 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19396 " does not fully implement ViewParent", e); 19397 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 19398 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19399 return true; 19400 } 19401 19402 int parentResolvedTextAlignment; 19403 try { 19404 parentResolvedTextAlignment = mParent.getTextAlignment(); 19405 } catch (AbstractMethodError e) { 19406 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19407 " does not fully implement ViewParent", e); 19408 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 19409 } 19410 switch (parentResolvedTextAlignment) { 19411 case TEXT_ALIGNMENT_GRAVITY: 19412 case TEXT_ALIGNMENT_TEXT_START: 19413 case TEXT_ALIGNMENT_TEXT_END: 19414 case TEXT_ALIGNMENT_CENTER: 19415 case TEXT_ALIGNMENT_VIEW_START: 19416 case TEXT_ALIGNMENT_VIEW_END: 19417 // Resolved text alignment is the same as the parent resolved 19418 // text alignment 19419 mPrivateFlags2 |= 19420 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19421 break; 19422 default: 19423 // Use default resolved text alignment 19424 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19425 } 19426 break; 19427 case TEXT_ALIGNMENT_GRAVITY: 19428 case TEXT_ALIGNMENT_TEXT_START: 19429 case TEXT_ALIGNMENT_TEXT_END: 19430 case TEXT_ALIGNMENT_CENTER: 19431 case TEXT_ALIGNMENT_VIEW_START: 19432 case TEXT_ALIGNMENT_VIEW_END: 19433 // Resolved text alignment is the same as text alignment 19434 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19435 break; 19436 default: 19437 // Use default resolved text alignment 19438 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19439 } 19440 } else { 19441 // Use default resolved text alignment 19442 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19443 } 19444 19445 // Set the resolved 19446 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19447 return true; 19448 } 19449 19450 /** 19451 * Check if text alignment resolution can be done. 19452 * 19453 * @return true if text alignment resolution can be done otherwise return false. 19454 */ 19455 public boolean canResolveTextAlignment() { 19456 switch (getRawTextAlignment()) { 19457 case TEXT_DIRECTION_INHERIT: 19458 if (mParent != null) { 19459 try { 19460 return mParent.canResolveTextAlignment(); 19461 } catch (AbstractMethodError e) { 19462 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19463 " does not fully implement ViewParent", e); 19464 } 19465 } 19466 return false; 19467 19468 default: 19469 return true; 19470 } 19471 } 19472 19473 /** 19474 * Reset resolved text alignment. Text alignment will be resolved during a call to 19475 * {@link #onMeasure(int, int)}. 19476 * 19477 * @hide 19478 */ 19479 public void resetResolvedTextAlignment() { 19480 // Reset any previous text alignment resolution 19481 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19482 // Set to default 19483 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19484 } 19485 19486 /** 19487 * @return true if text alignment is inherited. 19488 * 19489 * @hide 19490 */ 19491 public boolean isTextAlignmentInherited() { 19492 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 19493 } 19494 19495 /** 19496 * @return true if text alignment is resolved. 19497 */ 19498 public boolean isTextAlignmentResolved() { 19499 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19500 } 19501 19502 /** 19503 * Generate a value suitable for use in {@link #setId(int)}. 19504 * This value will not collide with ID values generated at build time by aapt for R.id. 19505 * 19506 * @return a generated ID value 19507 */ 19508 public static int generateViewId() { 19509 for (;;) { 19510 final int result = sNextGeneratedId.get(); 19511 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 19512 int newValue = result + 1; 19513 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 19514 if (sNextGeneratedId.compareAndSet(result, newValue)) { 19515 return result; 19516 } 19517 } 19518 } 19519 19520 /** 19521 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 19522 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 19523 * a normal View or a ViewGroup with 19524 * {@link android.view.ViewGroup#isTransitionGroup()} true. 19525 * @hide 19526 */ 19527 public void captureTransitioningViews(List<View> transitioningViews) { 19528 if (getVisibility() == View.VISIBLE) { 19529 transitioningViews.add(this); 19530 } 19531 } 19532 19533 /** 19534 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 19535 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 19536 * @hide 19537 */ 19538 public void findNamedViews(Map<String, View> namedElements) { 19539 if (getVisibility() == VISIBLE || mGhostView != null) { 19540 String transitionName = getTransitionName(); 19541 if (transitionName != null) { 19542 namedElements.put(transitionName, this); 19543 } 19544 } 19545 } 19546 19547 // 19548 // Properties 19549 // 19550 /** 19551 * A Property wrapper around the <code>alpha</code> functionality handled by the 19552 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 19553 */ 19554 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 19555 @Override 19556 public void setValue(View object, float value) { 19557 object.setAlpha(value); 19558 } 19559 19560 @Override 19561 public Float get(View object) { 19562 return object.getAlpha(); 19563 } 19564 }; 19565 19566 /** 19567 * A Property wrapper around the <code>translationX</code> functionality handled by the 19568 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 19569 */ 19570 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 19571 @Override 19572 public void setValue(View object, float value) { 19573 object.setTranslationX(value); 19574 } 19575 19576 @Override 19577 public Float get(View object) { 19578 return object.getTranslationX(); 19579 } 19580 }; 19581 19582 /** 19583 * A Property wrapper around the <code>translationY</code> functionality handled by the 19584 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 19585 */ 19586 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 19587 @Override 19588 public void setValue(View object, float value) { 19589 object.setTranslationY(value); 19590 } 19591 19592 @Override 19593 public Float get(View object) { 19594 return object.getTranslationY(); 19595 } 19596 }; 19597 19598 /** 19599 * A Property wrapper around the <code>translationZ</code> functionality handled by the 19600 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 19601 */ 19602 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 19603 @Override 19604 public void setValue(View object, float value) { 19605 object.setTranslationZ(value); 19606 } 19607 19608 @Override 19609 public Float get(View object) { 19610 return object.getTranslationZ(); 19611 } 19612 }; 19613 19614 /** 19615 * A Property wrapper around the <code>x</code> functionality handled by the 19616 * {@link View#setX(float)} and {@link View#getX()} methods. 19617 */ 19618 public static final Property<View, Float> X = new FloatProperty<View>("x") { 19619 @Override 19620 public void setValue(View object, float value) { 19621 object.setX(value); 19622 } 19623 19624 @Override 19625 public Float get(View object) { 19626 return object.getX(); 19627 } 19628 }; 19629 19630 /** 19631 * A Property wrapper around the <code>y</code> functionality handled by the 19632 * {@link View#setY(float)} and {@link View#getY()} methods. 19633 */ 19634 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 19635 @Override 19636 public void setValue(View object, float value) { 19637 object.setY(value); 19638 } 19639 19640 @Override 19641 public Float get(View object) { 19642 return object.getY(); 19643 } 19644 }; 19645 19646 /** 19647 * A Property wrapper around the <code>z</code> functionality handled by the 19648 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19649 */ 19650 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19651 @Override 19652 public void setValue(View object, float value) { 19653 object.setZ(value); 19654 } 19655 19656 @Override 19657 public Float get(View object) { 19658 return object.getZ(); 19659 } 19660 }; 19661 19662 /** 19663 * A Property wrapper around the <code>rotation</code> functionality handled by the 19664 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19665 */ 19666 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19667 @Override 19668 public void setValue(View object, float value) { 19669 object.setRotation(value); 19670 } 19671 19672 @Override 19673 public Float get(View object) { 19674 return object.getRotation(); 19675 } 19676 }; 19677 19678 /** 19679 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19680 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19681 */ 19682 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19683 @Override 19684 public void setValue(View object, float value) { 19685 object.setRotationX(value); 19686 } 19687 19688 @Override 19689 public Float get(View object) { 19690 return object.getRotationX(); 19691 } 19692 }; 19693 19694 /** 19695 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19696 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19697 */ 19698 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19699 @Override 19700 public void setValue(View object, float value) { 19701 object.setRotationY(value); 19702 } 19703 19704 @Override 19705 public Float get(View object) { 19706 return object.getRotationY(); 19707 } 19708 }; 19709 19710 /** 19711 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19712 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19713 */ 19714 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19715 @Override 19716 public void setValue(View object, float value) { 19717 object.setScaleX(value); 19718 } 19719 19720 @Override 19721 public Float get(View object) { 19722 return object.getScaleX(); 19723 } 19724 }; 19725 19726 /** 19727 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19728 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19729 */ 19730 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19731 @Override 19732 public void setValue(View object, float value) { 19733 object.setScaleY(value); 19734 } 19735 19736 @Override 19737 public Float get(View object) { 19738 return object.getScaleY(); 19739 } 19740 }; 19741 19742 /** 19743 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19744 * Each MeasureSpec represents a requirement for either the width or the height. 19745 * A MeasureSpec is comprised of a size and a mode. There are three possible 19746 * modes: 19747 * <dl> 19748 * <dt>UNSPECIFIED</dt> 19749 * <dd> 19750 * The parent has not imposed any constraint on the child. It can be whatever size 19751 * it wants. 19752 * </dd> 19753 * 19754 * <dt>EXACTLY</dt> 19755 * <dd> 19756 * The parent has determined an exact size for the child. The child is going to be 19757 * given those bounds regardless of how big it wants to be. 19758 * </dd> 19759 * 19760 * <dt>AT_MOST</dt> 19761 * <dd> 19762 * The child can be as large as it wants up to the specified size. 19763 * </dd> 19764 * </dl> 19765 * 19766 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19767 * is provided to pack and unpack the <size, mode> tuple into the int. 19768 */ 19769 public static class MeasureSpec { 19770 private static final int MODE_SHIFT = 30; 19771 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19772 19773 /** 19774 * Measure specification mode: The parent has not imposed any constraint 19775 * on the child. It can be whatever size it wants. 19776 */ 19777 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19778 19779 /** 19780 * Measure specification mode: The parent has determined an exact size 19781 * for the child. The child is going to be given those bounds regardless 19782 * of how big it wants to be. 19783 */ 19784 public static final int EXACTLY = 1 << MODE_SHIFT; 19785 19786 /** 19787 * Measure specification mode: The child can be as large as it wants up 19788 * to the specified size. 19789 */ 19790 public static final int AT_MOST = 2 << MODE_SHIFT; 19791 19792 /** 19793 * Creates a measure specification based on the supplied size and mode. 19794 * 19795 * The mode must always be one of the following: 19796 * <ul> 19797 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19798 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19799 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19800 * </ul> 19801 * 19802 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19803 * implementation was such that the order of arguments did not matter 19804 * and overflow in either value could impact the resulting MeasureSpec. 19805 * {@link android.widget.RelativeLayout} was affected by this bug. 19806 * Apps targeting API levels greater than 17 will get the fixed, more strict 19807 * behavior.</p> 19808 * 19809 * @param size the size of the measure specification 19810 * @param mode the mode of the measure specification 19811 * @return the measure specification based on size and mode 19812 */ 19813 public static int makeMeasureSpec(int size, int mode) { 19814 if (sUseBrokenMakeMeasureSpec) { 19815 return size + mode; 19816 } else { 19817 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19818 } 19819 } 19820 19821 /** 19822 * Extracts the mode from the supplied measure specification. 19823 * 19824 * @param measureSpec the measure specification to extract the mode from 19825 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19826 * {@link android.view.View.MeasureSpec#AT_MOST} or 19827 * {@link android.view.View.MeasureSpec#EXACTLY} 19828 */ 19829 public static int getMode(int measureSpec) { 19830 return (measureSpec & MODE_MASK); 19831 } 19832 19833 /** 19834 * Extracts the size from the supplied measure specification. 19835 * 19836 * @param measureSpec the measure specification to extract the size from 19837 * @return the size in pixels defined in the supplied measure specification 19838 */ 19839 public static int getSize(int measureSpec) { 19840 return (measureSpec & ~MODE_MASK); 19841 } 19842 19843 static int adjust(int measureSpec, int delta) { 19844 final int mode = getMode(measureSpec); 19845 if (mode == UNSPECIFIED) { 19846 // No need to adjust size for UNSPECIFIED mode. 19847 return makeMeasureSpec(0, UNSPECIFIED); 19848 } 19849 int size = getSize(measureSpec) + delta; 19850 if (size < 0) { 19851 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19852 ") spec: " + toString(measureSpec) + " delta: " + delta); 19853 size = 0; 19854 } 19855 return makeMeasureSpec(size, mode); 19856 } 19857 19858 /** 19859 * Returns a String representation of the specified measure 19860 * specification. 19861 * 19862 * @param measureSpec the measure specification to convert to a String 19863 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19864 */ 19865 public static String toString(int measureSpec) { 19866 int mode = getMode(measureSpec); 19867 int size = getSize(measureSpec); 19868 19869 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19870 19871 if (mode == UNSPECIFIED) 19872 sb.append("UNSPECIFIED "); 19873 else if (mode == EXACTLY) 19874 sb.append("EXACTLY "); 19875 else if (mode == AT_MOST) 19876 sb.append("AT_MOST "); 19877 else 19878 sb.append(mode).append(" "); 19879 19880 sb.append(size); 19881 return sb.toString(); 19882 } 19883 } 19884 19885 private final class CheckForLongPress implements Runnable { 19886 private int mOriginalWindowAttachCount; 19887 19888 @Override 19889 public void run() { 19890 if (isPressed() && (mParent != null) 19891 && mOriginalWindowAttachCount == mWindowAttachCount) { 19892 if (performLongClick()) { 19893 mHasPerformedLongPress = true; 19894 } 19895 } 19896 } 19897 19898 public void rememberWindowAttachCount() { 19899 mOriginalWindowAttachCount = mWindowAttachCount; 19900 } 19901 } 19902 19903 private final class CheckForTap implements Runnable { 19904 public float x; 19905 public float y; 19906 19907 @Override 19908 public void run() { 19909 mPrivateFlags &= ~PFLAG_PREPRESSED; 19910 setPressed(true, x, y); 19911 checkForLongClick(ViewConfiguration.getTapTimeout()); 19912 } 19913 } 19914 19915 private final class PerformClick implements Runnable { 19916 @Override 19917 public void run() { 19918 performClick(); 19919 } 19920 } 19921 19922 /** @hide */ 19923 public void hackTurnOffWindowResizeAnim(boolean off) { 19924 mAttachInfo.mTurnOffWindowResizeAnim = off; 19925 } 19926 19927 /** 19928 * This method returns a ViewPropertyAnimator object, which can be used to animate 19929 * specific properties on this View. 19930 * 19931 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19932 */ 19933 public ViewPropertyAnimator animate() { 19934 if (mAnimator == null) { 19935 mAnimator = new ViewPropertyAnimator(this); 19936 } 19937 return mAnimator; 19938 } 19939 19940 /** 19941 * Sets the name of the View to be used to identify Views in Transitions. 19942 * Names should be unique in the View hierarchy. 19943 * 19944 * @param transitionName The name of the View to uniquely identify it for Transitions. 19945 */ 19946 public final void setTransitionName(String transitionName) { 19947 mTransitionName = transitionName; 19948 } 19949 19950 /** 19951 * Returns the name of the View to be used to identify Views in Transitions. 19952 * Names should be unique in the View hierarchy. 19953 * 19954 * <p>This returns null if the View has not been given a name.</p> 19955 * 19956 * @return The name used of the View to be used to identify Views in Transitions or null 19957 * if no name has been given. 19958 */ 19959 @ViewDebug.ExportedProperty 19960 public String getTransitionName() { 19961 return mTransitionName; 19962 } 19963 19964 /** 19965 * Interface definition for a callback to be invoked when a hardware key event is 19966 * dispatched to this view. The callback will be invoked before the key event is 19967 * given to the view. This is only useful for hardware keyboards; a software input 19968 * method has no obligation to trigger this listener. 19969 */ 19970 public interface OnKeyListener { 19971 /** 19972 * Called when a hardware key is dispatched to a view. This allows listeners to 19973 * get a chance to respond before the target view. 19974 * <p>Key presses in software keyboards will generally NOT trigger this method, 19975 * although some may elect to do so in some situations. Do not assume a 19976 * software input method has to be key-based; even if it is, it may use key presses 19977 * in a different way than you expect, so there is no way to reliably catch soft 19978 * input key presses. 19979 * 19980 * @param v The view the key has been dispatched to. 19981 * @param keyCode The code for the physical key that was pressed 19982 * @param event The KeyEvent object containing full information about 19983 * the event. 19984 * @return True if the listener has consumed the event, false otherwise. 19985 */ 19986 boolean onKey(View v, int keyCode, KeyEvent event); 19987 } 19988 19989 /** 19990 * Interface definition for a callback to be invoked when a touch event is 19991 * dispatched to this view. The callback will be invoked before the touch 19992 * event is given to the view. 19993 */ 19994 public interface OnTouchListener { 19995 /** 19996 * Called when a touch event is dispatched to a view. This allows listeners to 19997 * get a chance to respond before the target view. 19998 * 19999 * @param v The view the touch event has been dispatched to. 20000 * @param event The MotionEvent object containing full information about 20001 * the event. 20002 * @return True if the listener has consumed the event, false otherwise. 20003 */ 20004 boolean onTouch(View v, MotionEvent event); 20005 } 20006 20007 /** 20008 * Interface definition for a callback to be invoked when a hover event is 20009 * dispatched to this view. The callback will be invoked before the hover 20010 * event is given to the view. 20011 */ 20012 public interface OnHoverListener { 20013 /** 20014 * Called when a hover event is dispatched to a view. This allows listeners to 20015 * get a chance to respond before the target view. 20016 * 20017 * @param v The view the hover event has been dispatched to. 20018 * @param event The MotionEvent object containing full information about 20019 * the event. 20020 * @return True if the listener has consumed the event, false otherwise. 20021 */ 20022 boolean onHover(View v, MotionEvent event); 20023 } 20024 20025 /** 20026 * Interface definition for a callback to be invoked when a generic motion event is 20027 * dispatched to this view. The callback will be invoked before the generic motion 20028 * event is given to the view. 20029 */ 20030 public interface OnGenericMotionListener { 20031 /** 20032 * Called when a generic motion event is dispatched to a view. This allows listeners to 20033 * get a chance to respond before the target view. 20034 * 20035 * @param v The view the generic motion event has been dispatched to. 20036 * @param event The MotionEvent object containing full information about 20037 * the event. 20038 * @return True if the listener has consumed the event, false otherwise. 20039 */ 20040 boolean onGenericMotion(View v, MotionEvent event); 20041 } 20042 20043 /** 20044 * Interface definition for a callback to be invoked when a view has been clicked and held. 20045 */ 20046 public interface OnLongClickListener { 20047 /** 20048 * Called when a view has been clicked and held. 20049 * 20050 * @param v The view that was clicked and held. 20051 * 20052 * @return true if the callback consumed the long click, false otherwise. 20053 */ 20054 boolean onLongClick(View v); 20055 } 20056 20057 /** 20058 * Interface definition for a callback to be invoked when a drag is being dispatched 20059 * to this view. The callback will be invoked before the hosting view's own 20060 * onDrag(event) method. If the listener wants to fall back to the hosting view's 20061 * onDrag(event) behavior, it should return 'false' from this callback. 20062 * 20063 * <div class="special reference"> 20064 * <h3>Developer Guides</h3> 20065 * <p>For a guide to implementing drag and drop features, read the 20066 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 20067 * </div> 20068 */ 20069 public interface OnDragListener { 20070 /** 20071 * Called when a drag event is dispatched to a view. This allows listeners 20072 * to get a chance to override base View behavior. 20073 * 20074 * @param v The View that received the drag event. 20075 * @param event The {@link android.view.DragEvent} object for the drag event. 20076 * @return {@code true} if the drag event was handled successfully, or {@code false} 20077 * if the drag event was not handled. Note that {@code false} will trigger the View 20078 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 20079 */ 20080 boolean onDrag(View v, DragEvent event); 20081 } 20082 20083 /** 20084 * Interface definition for a callback to be invoked when the focus state of 20085 * a view changed. 20086 */ 20087 public interface OnFocusChangeListener { 20088 /** 20089 * Called when the focus state of a view has changed. 20090 * 20091 * @param v The view whose state has changed. 20092 * @param hasFocus The new focus state of v. 20093 */ 20094 void onFocusChange(View v, boolean hasFocus); 20095 } 20096 20097 /** 20098 * Interface definition for a callback to be invoked when a view is clicked. 20099 */ 20100 public interface OnClickListener { 20101 /** 20102 * Called when a view has been clicked. 20103 * 20104 * @param v The view that was clicked. 20105 */ 20106 void onClick(View v); 20107 } 20108 20109 /** 20110 * Interface definition for a callback to be invoked when the context menu 20111 * for this view is being built. 20112 */ 20113 public interface OnCreateContextMenuListener { 20114 /** 20115 * Called when the context menu for this view is being built. It is not 20116 * safe to hold onto the menu after this method returns. 20117 * 20118 * @param menu The context menu that is being built 20119 * @param v The view for which the context menu is being built 20120 * @param menuInfo Extra information about the item for which the 20121 * context menu should be shown. This information will vary 20122 * depending on the class of v. 20123 */ 20124 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 20125 } 20126 20127 /** 20128 * Interface definition for a callback to be invoked when the status bar changes 20129 * visibility. This reports <strong>global</strong> changes to the system UI 20130 * state, not what the application is requesting. 20131 * 20132 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 20133 */ 20134 public interface OnSystemUiVisibilityChangeListener { 20135 /** 20136 * Called when the status bar changes visibility because of a call to 20137 * {@link View#setSystemUiVisibility(int)}. 20138 * 20139 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20140 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 20141 * This tells you the <strong>global</strong> state of these UI visibility 20142 * flags, not what your app is currently applying. 20143 */ 20144 public void onSystemUiVisibilityChange(int visibility); 20145 } 20146 20147 /** 20148 * Interface definition for a callback to be invoked when this view is attached 20149 * or detached from its window. 20150 */ 20151 public interface OnAttachStateChangeListener { 20152 /** 20153 * Called when the view is attached to a window. 20154 * @param v The view that was attached 20155 */ 20156 public void onViewAttachedToWindow(View v); 20157 /** 20158 * Called when the view is detached from a window. 20159 * @param v The view that was detached 20160 */ 20161 public void onViewDetachedFromWindow(View v); 20162 } 20163 20164 /** 20165 * Listener for applying window insets on a view in a custom way. 20166 * 20167 * <p>Apps may choose to implement this interface if they want to apply custom policy 20168 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 20169 * is set, its 20170 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 20171 * method will be called instead of the View's own 20172 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 20173 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 20174 * the View's normal behavior as part of its own.</p> 20175 */ 20176 public interface OnApplyWindowInsetsListener { 20177 /** 20178 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 20179 * on a View, this listener method will be called instead of the view's own 20180 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 20181 * 20182 * @param v The view applying window insets 20183 * @param insets The insets to apply 20184 * @return The insets supplied, minus any insets that were consumed 20185 */ 20186 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 20187 } 20188 20189 private final class UnsetPressedState implements Runnable { 20190 @Override 20191 public void run() { 20192 setPressed(false); 20193 } 20194 } 20195 20196 /** 20197 * Base class for derived classes that want to save and restore their own 20198 * state in {@link android.view.View#onSaveInstanceState()}. 20199 */ 20200 public static class BaseSavedState extends AbsSavedState { 20201 /** 20202 * Constructor used when reading from a parcel. Reads the state of the superclass. 20203 * 20204 * @param source 20205 */ 20206 public BaseSavedState(Parcel source) { 20207 super(source); 20208 } 20209 20210 /** 20211 * Constructor called by derived classes when creating their SavedState objects 20212 * 20213 * @param superState The state of the superclass of this view 20214 */ 20215 public BaseSavedState(Parcelable superState) { 20216 super(superState); 20217 } 20218 20219 public static final Parcelable.Creator<BaseSavedState> CREATOR = 20220 new Parcelable.Creator<BaseSavedState>() { 20221 public BaseSavedState createFromParcel(Parcel in) { 20222 return new BaseSavedState(in); 20223 } 20224 20225 public BaseSavedState[] newArray(int size) { 20226 return new BaseSavedState[size]; 20227 } 20228 }; 20229 } 20230 20231 /** 20232 * A set of information given to a view when it is attached to its parent 20233 * window. 20234 */ 20235 final static class AttachInfo { 20236 interface Callbacks { 20237 void playSoundEffect(int effectId); 20238 boolean performHapticFeedback(int effectId, boolean always); 20239 } 20240 20241 /** 20242 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 20243 * to a Handler. This class contains the target (View) to invalidate and 20244 * the coordinates of the dirty rectangle. 20245 * 20246 * For performance purposes, this class also implements a pool of up to 20247 * POOL_LIMIT objects that get reused. This reduces memory allocations 20248 * whenever possible. 20249 */ 20250 static class InvalidateInfo { 20251 private static final int POOL_LIMIT = 10; 20252 20253 private static final SynchronizedPool<InvalidateInfo> sPool = 20254 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 20255 20256 View target; 20257 20258 int left; 20259 int top; 20260 int right; 20261 int bottom; 20262 20263 public static InvalidateInfo obtain() { 20264 InvalidateInfo instance = sPool.acquire(); 20265 return (instance != null) ? instance : new InvalidateInfo(); 20266 } 20267 20268 public void recycle() { 20269 target = null; 20270 sPool.release(this); 20271 } 20272 } 20273 20274 final IWindowSession mSession; 20275 20276 final IWindow mWindow; 20277 20278 final IBinder mWindowToken; 20279 20280 final Display mDisplay; 20281 20282 final Callbacks mRootCallbacks; 20283 20284 IWindowId mIWindowId; 20285 WindowId mWindowId; 20286 20287 /** 20288 * The top view of the hierarchy. 20289 */ 20290 View mRootView; 20291 20292 IBinder mPanelParentWindowToken; 20293 20294 boolean mHardwareAccelerated; 20295 boolean mHardwareAccelerationRequested; 20296 HardwareRenderer mHardwareRenderer; 20297 List<RenderNode> mPendingAnimatingRenderNodes; 20298 20299 /** 20300 * The state of the display to which the window is attached, as reported 20301 * by {@link Display#getState()}. Note that the display state constants 20302 * declared by {@link Display} do not exactly line up with the screen state 20303 * constants declared by {@link View} (there are more display states than 20304 * screen states). 20305 */ 20306 int mDisplayState = Display.STATE_UNKNOWN; 20307 20308 /** 20309 * Scale factor used by the compatibility mode 20310 */ 20311 float mApplicationScale; 20312 20313 /** 20314 * Indicates whether the application is in compatibility mode 20315 */ 20316 boolean mScalingRequired; 20317 20318 /** 20319 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 20320 */ 20321 boolean mTurnOffWindowResizeAnim; 20322 20323 /** 20324 * Left position of this view's window 20325 */ 20326 int mWindowLeft; 20327 20328 /** 20329 * Top position of this view's window 20330 */ 20331 int mWindowTop; 20332 20333 /** 20334 * Indicates whether views need to use 32-bit drawing caches 20335 */ 20336 boolean mUse32BitDrawingCache; 20337 20338 /** 20339 * For windows that are full-screen but using insets to layout inside 20340 * of the screen areas, these are the current insets to appear inside 20341 * the overscan area of the display. 20342 */ 20343 final Rect mOverscanInsets = new Rect(); 20344 20345 /** 20346 * For windows that are full-screen but using insets to layout inside 20347 * of the screen decorations, these are the current insets for the 20348 * content of the window. 20349 */ 20350 final Rect mContentInsets = new Rect(); 20351 20352 /** 20353 * For windows that are full-screen but using insets to layout inside 20354 * of the screen decorations, these are the current insets for the 20355 * actual visible parts of the window. 20356 */ 20357 final Rect mVisibleInsets = new Rect(); 20358 20359 /** 20360 * For windows that are full-screen but using insets to layout inside 20361 * of the screen decorations, these are the current insets for the 20362 * stable system windows. 20363 */ 20364 final Rect mStableInsets = new Rect(); 20365 20366 /** 20367 * The internal insets given by this window. This value is 20368 * supplied by the client (through 20369 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 20370 * be given to the window manager when changed to be used in laying 20371 * out windows behind it. 20372 */ 20373 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 20374 = new ViewTreeObserver.InternalInsetsInfo(); 20375 20376 /** 20377 * Set to true when mGivenInternalInsets is non-empty. 20378 */ 20379 boolean mHasNonEmptyGivenInternalInsets; 20380 20381 /** 20382 * All views in the window's hierarchy that serve as scroll containers, 20383 * used to determine if the window can be resized or must be panned 20384 * to adjust for a soft input area. 20385 */ 20386 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 20387 20388 final KeyEvent.DispatcherState mKeyDispatchState 20389 = new KeyEvent.DispatcherState(); 20390 20391 /** 20392 * Indicates whether the view's window currently has the focus. 20393 */ 20394 boolean mHasWindowFocus; 20395 20396 /** 20397 * The current visibility of the window. 20398 */ 20399 int mWindowVisibility; 20400 20401 /** 20402 * Indicates the time at which drawing started to occur. 20403 */ 20404 long mDrawingTime; 20405 20406 /** 20407 * Indicates whether or not ignoring the DIRTY_MASK flags. 20408 */ 20409 boolean mIgnoreDirtyState; 20410 20411 /** 20412 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 20413 * to avoid clearing that flag prematurely. 20414 */ 20415 boolean mSetIgnoreDirtyState = false; 20416 20417 /** 20418 * Indicates whether the view's window is currently in touch mode. 20419 */ 20420 boolean mInTouchMode; 20421 20422 /** 20423 * Indicates whether the view has requested unbuffered input dispatching for the current 20424 * event stream. 20425 */ 20426 boolean mUnbufferedDispatchRequested; 20427 20428 /** 20429 * Indicates that ViewAncestor should trigger a global layout change 20430 * the next time it performs a traversal 20431 */ 20432 boolean mRecomputeGlobalAttributes; 20433 20434 /** 20435 * Always report new attributes at next traversal. 20436 */ 20437 boolean mForceReportNewAttributes; 20438 20439 /** 20440 * Set during a traveral if any views want to keep the screen on. 20441 */ 20442 boolean mKeepScreenOn; 20443 20444 /** 20445 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 20446 */ 20447 int mSystemUiVisibility; 20448 20449 /** 20450 * Hack to force certain system UI visibility flags to be cleared. 20451 */ 20452 int mDisabledSystemUiVisibility; 20453 20454 /** 20455 * Last global system UI visibility reported by the window manager. 20456 */ 20457 int mGlobalSystemUiVisibility; 20458 20459 /** 20460 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 20461 * attached. 20462 */ 20463 boolean mHasSystemUiListeners; 20464 20465 /** 20466 * Set if the window has requested to extend into the overscan region 20467 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 20468 */ 20469 boolean mOverscanRequested; 20470 20471 /** 20472 * Set if the visibility of any views has changed. 20473 */ 20474 boolean mViewVisibilityChanged; 20475 20476 /** 20477 * Set to true if a view has been scrolled. 20478 */ 20479 boolean mViewScrollChanged; 20480 20481 /** 20482 * Set to true if high contrast mode enabled 20483 */ 20484 boolean mHighContrastText; 20485 20486 /** 20487 * Global to the view hierarchy used as a temporary for dealing with 20488 * x/y points in the transparent region computations. 20489 */ 20490 final int[] mTransparentLocation = new int[2]; 20491 20492 /** 20493 * Global to the view hierarchy used as a temporary for dealing with 20494 * x/y points in the ViewGroup.invalidateChild implementation. 20495 */ 20496 final int[] mInvalidateChildLocation = new int[2]; 20497 20498 /** 20499 * Global to the view hierarchy used as a temporary for dealng with 20500 * computing absolute on-screen location. 20501 */ 20502 final int[] mTmpLocation = new int[2]; 20503 20504 /** 20505 * Global to the view hierarchy used as a temporary for dealing with 20506 * x/y location when view is transformed. 20507 */ 20508 final float[] mTmpTransformLocation = new float[2]; 20509 20510 /** 20511 * The view tree observer used to dispatch global events like 20512 * layout, pre-draw, touch mode change, etc. 20513 */ 20514 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 20515 20516 /** 20517 * A Canvas used by the view hierarchy to perform bitmap caching. 20518 */ 20519 Canvas mCanvas; 20520 20521 /** 20522 * The view root impl. 20523 */ 20524 final ViewRootImpl mViewRootImpl; 20525 20526 /** 20527 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 20528 * handler can be used to pump events in the UI events queue. 20529 */ 20530 final Handler mHandler; 20531 20532 /** 20533 * Temporary for use in computing invalidate rectangles while 20534 * calling up the hierarchy. 20535 */ 20536 final Rect mTmpInvalRect = new Rect(); 20537 20538 /** 20539 * Temporary for use in computing hit areas with transformed views 20540 */ 20541 final RectF mTmpTransformRect = new RectF(); 20542 20543 /** 20544 * Temporary for use in computing hit areas with transformed views 20545 */ 20546 final RectF mTmpTransformRect1 = new RectF(); 20547 20548 /** 20549 * Temporary list of rectanges. 20550 */ 20551 final List<RectF> mTmpRectList = new ArrayList<>(); 20552 20553 /** 20554 * Temporary for use in transforming invalidation rect 20555 */ 20556 final Matrix mTmpMatrix = new Matrix(); 20557 20558 /** 20559 * Temporary for use in transforming invalidation rect 20560 */ 20561 final Transformation mTmpTransformation = new Transformation(); 20562 20563 /** 20564 * Temporary for use in querying outlines from OutlineProviders 20565 */ 20566 final Outline mTmpOutline = new Outline(); 20567 20568 /** 20569 * Temporary list for use in collecting focusable descendents of a view. 20570 */ 20571 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 20572 20573 /** 20574 * The id of the window for accessibility purposes. 20575 */ 20576 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 20577 20578 /** 20579 * Flags related to accessibility processing. 20580 * 20581 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 20582 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 20583 */ 20584 int mAccessibilityFetchFlags; 20585 20586 /** 20587 * The drawable for highlighting accessibility focus. 20588 */ 20589 Drawable mAccessibilityFocusDrawable; 20590 20591 /** 20592 * Show where the margins, bounds and layout bounds are for each view. 20593 */ 20594 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 20595 20596 /** 20597 * Point used to compute visible regions. 20598 */ 20599 final Point mPoint = new Point(); 20600 20601 /** 20602 * Used to track which View originated a requestLayout() call, used when 20603 * requestLayout() is called during layout. 20604 */ 20605 View mViewRequestingLayout; 20606 20607 /** 20608 * Creates a new set of attachment information with the specified 20609 * events handler and thread. 20610 * 20611 * @param handler the events handler the view must use 20612 */ 20613 AttachInfo(IWindowSession session, IWindow window, Display display, 20614 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 20615 mSession = session; 20616 mWindow = window; 20617 mWindowToken = window.asBinder(); 20618 mDisplay = display; 20619 mViewRootImpl = viewRootImpl; 20620 mHandler = handler; 20621 mRootCallbacks = effectPlayer; 20622 } 20623 } 20624 20625 /** 20626 * <p>ScrollabilityCache holds various fields used by a View when scrolling 20627 * is supported. This avoids keeping too many unused fields in most 20628 * instances of View.</p> 20629 */ 20630 private static class ScrollabilityCache implements Runnable { 20631 20632 /** 20633 * Scrollbars are not visible 20634 */ 20635 public static final int OFF = 0; 20636 20637 /** 20638 * Scrollbars are visible 20639 */ 20640 public static final int ON = 1; 20641 20642 /** 20643 * Scrollbars are fading away 20644 */ 20645 public static final int FADING = 2; 20646 20647 public boolean fadeScrollBars; 20648 20649 public int fadingEdgeLength; 20650 public int scrollBarDefaultDelayBeforeFade; 20651 public int scrollBarFadeDuration; 20652 20653 public int scrollBarSize; 20654 public ScrollBarDrawable scrollBar; 20655 public float[] interpolatorValues; 20656 public View host; 20657 20658 public final Paint paint; 20659 public final Matrix matrix; 20660 public Shader shader; 20661 20662 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 20663 20664 private static final float[] OPAQUE = { 255 }; 20665 private static final float[] TRANSPARENT = { 0.0f }; 20666 20667 /** 20668 * When fading should start. This time moves into the future every time 20669 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20670 */ 20671 public long fadeStartTime; 20672 20673 20674 /** 20675 * The current state of the scrollbars: ON, OFF, or FADING 20676 */ 20677 public int state = OFF; 20678 20679 private int mLastColor; 20680 20681 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20682 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20683 scrollBarSize = configuration.getScaledScrollBarSize(); 20684 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20685 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20686 20687 paint = new Paint(); 20688 matrix = new Matrix(); 20689 // use use a height of 1, and then wack the matrix each time we 20690 // actually use it. 20691 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20692 paint.setShader(shader); 20693 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20694 20695 this.host = host; 20696 } 20697 20698 public void setFadeColor(int color) { 20699 if (color != mLastColor) { 20700 mLastColor = color; 20701 20702 if (color != 0) { 20703 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20704 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20705 paint.setShader(shader); 20706 // Restore the default transfer mode (src_over) 20707 paint.setXfermode(null); 20708 } else { 20709 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20710 paint.setShader(shader); 20711 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20712 } 20713 } 20714 } 20715 20716 public void run() { 20717 long now = AnimationUtils.currentAnimationTimeMillis(); 20718 if (now >= fadeStartTime) { 20719 20720 // the animation fades the scrollbars out by changing 20721 // the opacity (alpha) from fully opaque to fully 20722 // transparent 20723 int nextFrame = (int) now; 20724 int framesCount = 0; 20725 20726 Interpolator interpolator = scrollBarInterpolator; 20727 20728 // Start opaque 20729 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20730 20731 // End transparent 20732 nextFrame += scrollBarFadeDuration; 20733 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20734 20735 state = FADING; 20736 20737 // Kick off the fade animation 20738 host.invalidate(true); 20739 } 20740 } 20741 } 20742 20743 /** 20744 * Resuable callback for sending 20745 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20746 */ 20747 private class SendViewScrolledAccessibilityEvent implements Runnable { 20748 public volatile boolean mIsPending; 20749 20750 public void run() { 20751 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20752 mIsPending = false; 20753 } 20754 } 20755 20756 /** 20757 * <p> 20758 * This class represents a delegate that can be registered in a {@link View} 20759 * to enhance accessibility support via composition rather via inheritance. 20760 * It is specifically targeted to widget developers that extend basic View 20761 * classes i.e. classes in package android.view, that would like their 20762 * applications to be backwards compatible. 20763 * </p> 20764 * <div class="special reference"> 20765 * <h3>Developer Guides</h3> 20766 * <p>For more information about making applications accessible, read the 20767 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20768 * developer guide.</p> 20769 * </div> 20770 * <p> 20771 * A scenario in which a developer would like to use an accessibility delegate 20772 * is overriding a method introduced in a later API version then the minimal API 20773 * version supported by the application. For example, the method 20774 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20775 * in API version 4 when the accessibility APIs were first introduced. If a 20776 * developer would like his application to run on API version 4 devices (assuming 20777 * all other APIs used by the application are version 4 or lower) and take advantage 20778 * of this method, instead of overriding the method which would break the application's 20779 * backwards compatibility, he can override the corresponding method in this 20780 * delegate and register the delegate in the target View if the API version of 20781 * the system is high enough i.e. the API version is same or higher to the API 20782 * version that introduced 20783 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20784 * </p> 20785 * <p> 20786 * Here is an example implementation: 20787 * </p> 20788 * <code><pre><p> 20789 * if (Build.VERSION.SDK_INT >= 14) { 20790 * // If the API version is equal of higher than the version in 20791 * // which onInitializeAccessibilityNodeInfo was introduced we 20792 * // register a delegate with a customized implementation. 20793 * View view = findViewById(R.id.view_id); 20794 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20795 * public void onInitializeAccessibilityNodeInfo(View host, 20796 * AccessibilityNodeInfo info) { 20797 * // Let the default implementation populate the info. 20798 * super.onInitializeAccessibilityNodeInfo(host, info); 20799 * // Set some other information. 20800 * info.setEnabled(host.isEnabled()); 20801 * } 20802 * }); 20803 * } 20804 * </code></pre></p> 20805 * <p> 20806 * This delegate contains methods that correspond to the accessibility methods 20807 * in View. If a delegate has been specified the implementation in View hands 20808 * off handling to the corresponding method in this delegate. The default 20809 * implementation the delegate methods behaves exactly as the corresponding 20810 * method in View for the case of no accessibility delegate been set. Hence, 20811 * to customize the behavior of a View method, clients can override only the 20812 * corresponding delegate method without altering the behavior of the rest 20813 * accessibility related methods of the host view. 20814 * </p> 20815 */ 20816 public static class AccessibilityDelegate { 20817 20818 /** 20819 * Sends an accessibility event of the given type. If accessibility is not 20820 * enabled this method has no effect. 20821 * <p> 20822 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20823 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20824 * been set. 20825 * </p> 20826 * 20827 * @param host The View hosting the delegate. 20828 * @param eventType The type of the event to send. 20829 * 20830 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20831 */ 20832 public void sendAccessibilityEvent(View host, int eventType) { 20833 host.sendAccessibilityEventInternal(eventType); 20834 } 20835 20836 /** 20837 * Performs the specified accessibility action on the view. For 20838 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20839 * <p> 20840 * The default implementation behaves as 20841 * {@link View#performAccessibilityAction(int, Bundle) 20842 * View#performAccessibilityAction(int, Bundle)} for the case of 20843 * no accessibility delegate been set. 20844 * </p> 20845 * 20846 * @param action The action to perform. 20847 * @return Whether the action was performed. 20848 * 20849 * @see View#performAccessibilityAction(int, Bundle) 20850 * View#performAccessibilityAction(int, Bundle) 20851 */ 20852 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20853 return host.performAccessibilityActionInternal(action, args); 20854 } 20855 20856 /** 20857 * Sends an accessibility event. This method behaves exactly as 20858 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20859 * empty {@link AccessibilityEvent} and does not perform a check whether 20860 * accessibility is enabled. 20861 * <p> 20862 * The default implementation behaves as 20863 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20864 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20865 * the case of no accessibility delegate been set. 20866 * </p> 20867 * 20868 * @param host The View hosting the delegate. 20869 * @param event The event to send. 20870 * 20871 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20872 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20873 */ 20874 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20875 host.sendAccessibilityEventUncheckedInternal(event); 20876 } 20877 20878 /** 20879 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20880 * to its children for adding their text content to the event. 20881 * <p> 20882 * The default implementation behaves as 20883 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20884 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20885 * the case of no accessibility delegate been set. 20886 * </p> 20887 * 20888 * @param host The View hosting the delegate. 20889 * @param event The event. 20890 * @return True if the event population was completed. 20891 * 20892 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20893 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20894 */ 20895 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20896 return host.dispatchPopulateAccessibilityEventInternal(event); 20897 } 20898 20899 /** 20900 * Gives a chance to the host View to populate the accessibility event with its 20901 * text content. 20902 * <p> 20903 * The default implementation behaves as 20904 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20905 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20906 * the case of no accessibility delegate been set. 20907 * </p> 20908 * 20909 * @param host The View hosting the delegate. 20910 * @param event The accessibility event which to populate. 20911 * 20912 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20913 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20914 */ 20915 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20916 host.onPopulateAccessibilityEventInternal(event); 20917 } 20918 20919 /** 20920 * Initializes an {@link AccessibilityEvent} with information about the 20921 * the host View which is the event source. 20922 * <p> 20923 * The default implementation behaves as 20924 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20925 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20926 * the case of no accessibility delegate been set. 20927 * </p> 20928 * 20929 * @param host The View hosting the delegate. 20930 * @param event The event to initialize. 20931 * 20932 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20933 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20934 */ 20935 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20936 host.onInitializeAccessibilityEventInternal(event); 20937 } 20938 20939 /** 20940 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20941 * <p> 20942 * The default implementation behaves as 20943 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20944 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20945 * the case of no accessibility delegate been set. 20946 * </p> 20947 * 20948 * @param host The View hosting the delegate. 20949 * @param info The instance to initialize. 20950 * 20951 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20952 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20953 */ 20954 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20955 host.onInitializeAccessibilityNodeInfoInternal(info); 20956 } 20957 20958 /** 20959 * Called when a child of the host View has requested sending an 20960 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20961 * to augment the event. 20962 * <p> 20963 * The default implementation behaves as 20964 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20965 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20966 * the case of no accessibility delegate been set. 20967 * </p> 20968 * 20969 * @param host The View hosting the delegate. 20970 * @param child The child which requests sending the event. 20971 * @param event The event to be sent. 20972 * @return True if the event should be sent 20973 * 20974 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20975 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20976 */ 20977 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20978 AccessibilityEvent event) { 20979 return host.onRequestSendAccessibilityEventInternal(child, event); 20980 } 20981 20982 /** 20983 * Gets the provider for managing a virtual view hierarchy rooted at this View 20984 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20985 * that explore the window content. 20986 * <p> 20987 * The default implementation behaves as 20988 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20989 * the case of no accessibility delegate been set. 20990 * </p> 20991 * 20992 * @return The provider. 20993 * 20994 * @see AccessibilityNodeProvider 20995 */ 20996 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20997 return null; 20998 } 20999 21000 /** 21001 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 21002 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 21003 * This method is responsible for obtaining an accessibility node info from a 21004 * pool of reusable instances and calling 21005 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 21006 * view to initialize the former. 21007 * <p> 21008 * <strong>Note:</strong> The client is responsible for recycling the obtained 21009 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 21010 * creation. 21011 * </p> 21012 * <p> 21013 * The default implementation behaves as 21014 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 21015 * the case of no accessibility delegate been set. 21016 * </p> 21017 * @return A populated {@link AccessibilityNodeInfo}. 21018 * 21019 * @see AccessibilityNodeInfo 21020 * 21021 * @hide 21022 */ 21023 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 21024 return host.createAccessibilityNodeInfoInternal(); 21025 } 21026 } 21027 21028 private class MatchIdPredicate implements Predicate<View> { 21029 public int mId; 21030 21031 @Override 21032 public boolean apply(View view) { 21033 return (view.mID == mId); 21034 } 21035 } 21036 21037 private class MatchLabelForPredicate implements Predicate<View> { 21038 private int mLabeledId; 21039 21040 @Override 21041 public boolean apply(View view) { 21042 return (view.mLabelForId == mLabeledId); 21043 } 21044 } 21045 21046 private class SendViewStateChangedAccessibilityEvent implements Runnable { 21047 private int mChangeTypes = 0; 21048 private boolean mPosted; 21049 private boolean mPostedWithDelay; 21050 private long mLastEventTimeMillis; 21051 21052 @Override 21053 public void run() { 21054 mPosted = false; 21055 mPostedWithDelay = false; 21056 mLastEventTimeMillis = SystemClock.uptimeMillis(); 21057 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 21058 final AccessibilityEvent event = AccessibilityEvent.obtain(); 21059 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 21060 event.setContentChangeTypes(mChangeTypes); 21061 sendAccessibilityEventUnchecked(event); 21062 } 21063 mChangeTypes = 0; 21064 } 21065 21066 public void runOrPost(int changeType) { 21067 mChangeTypes |= changeType; 21068 21069 // If this is a live region or the child of a live region, collect 21070 // all events from this frame and send them on the next frame. 21071 if (inLiveRegion()) { 21072 // If we're already posted with a delay, remove that. 21073 if (mPostedWithDelay) { 21074 removeCallbacks(this); 21075 mPostedWithDelay = false; 21076 } 21077 // Only post if we're not already posted. 21078 if (!mPosted) { 21079 post(this); 21080 mPosted = true; 21081 } 21082 return; 21083 } 21084 21085 if (mPosted) { 21086 return; 21087 } 21088 21089 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 21090 final long minEventIntevalMillis = 21091 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 21092 if (timeSinceLastMillis >= minEventIntevalMillis) { 21093 removeCallbacks(this); 21094 run(); 21095 } else { 21096 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 21097 mPostedWithDelay = true; 21098 } 21099 } 21100 } 21101 21102 private boolean inLiveRegion() { 21103 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 21104 return true; 21105 } 21106 21107 ViewParent parent = getParent(); 21108 while (parent instanceof View) { 21109 if (((View) parent).getAccessibilityLiveRegion() 21110 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 21111 return true; 21112 } 21113 parent = parent.getParent(); 21114 } 21115 21116 return false; 21117 } 21118 21119 /** 21120 * Dump all private flags in readable format, useful for documentation and 21121 * sanity checking. 21122 */ 21123 private static void dumpFlags() { 21124 final HashMap<String, String> found = Maps.newHashMap(); 21125 try { 21126 for (Field field : View.class.getDeclaredFields()) { 21127 final int modifiers = field.getModifiers(); 21128 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 21129 if (field.getType().equals(int.class)) { 21130 final int value = field.getInt(null); 21131 dumpFlag(found, field.getName(), value); 21132 } else if (field.getType().equals(int[].class)) { 21133 final int[] values = (int[]) field.get(null); 21134 for (int i = 0; i < values.length; i++) { 21135 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 21136 } 21137 } 21138 } 21139 } 21140 } catch (IllegalAccessException e) { 21141 throw new RuntimeException(e); 21142 } 21143 21144 final ArrayList<String> keys = Lists.newArrayList(); 21145 keys.addAll(found.keySet()); 21146 Collections.sort(keys); 21147 for (String key : keys) { 21148 Log.d(VIEW_LOG_TAG, found.get(key)); 21149 } 21150 } 21151 21152 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 21153 // Sort flags by prefix, then by bits, always keeping unique keys 21154 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 21155 final int prefix = name.indexOf('_'); 21156 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 21157 final String output = bits + " " + name; 21158 found.put(key, output); 21159 } 21160} 21161