View.java revision d5154ec2bc7e7c0bdfd14fc784912d390afe43cc
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.annotation.IntDef; 20import android.annotation.NonNull; 21import android.annotation.Nullable; 22import android.content.ClipData; 23import android.content.Context; 24import android.content.res.Configuration; 25import android.content.res.Resources; 26import android.content.res.TypedArray; 27import android.graphics.Bitmap; 28import android.graphics.Camera; 29import android.graphics.Canvas; 30import android.graphics.Insets; 31import android.graphics.Interpolator; 32import android.graphics.LinearGradient; 33import android.graphics.Matrix; 34import android.graphics.Paint; 35import android.graphics.Path; 36import android.graphics.PixelFormat; 37import android.graphics.Point; 38import android.graphics.PorterDuff; 39import android.graphics.PorterDuffXfermode; 40import android.graphics.Rect; 41import android.graphics.RectF; 42import android.graphics.Region; 43import android.graphics.Shader; 44import android.graphics.drawable.ColorDrawable; 45import android.graphics.drawable.Drawable; 46import android.hardware.display.DisplayManagerGlobal; 47import android.os.Bundle; 48import android.os.Handler; 49import android.os.IBinder; 50import android.os.Parcel; 51import android.os.Parcelable; 52import android.os.RemoteException; 53import android.os.SystemClock; 54import android.os.SystemProperties; 55import android.text.TextUtils; 56import android.util.AttributeSet; 57import android.util.FloatProperty; 58import android.util.LayoutDirection; 59import android.util.Log; 60import android.util.LongSparseLongArray; 61import android.util.Pools.SynchronizedPool; 62import android.util.Property; 63import android.util.SparseArray; 64import android.util.SuperNotCalledException; 65import android.util.TypedValue; 66import android.view.ContextMenu.ContextMenuInfo; 67import android.view.AccessibilityIterators.TextSegmentIterator; 68import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 69import android.view.AccessibilityIterators.WordTextSegmentIterator; 70import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 71import android.view.accessibility.AccessibilityEvent; 72import android.view.accessibility.AccessibilityEventSource; 73import android.view.accessibility.AccessibilityManager; 74import android.view.accessibility.AccessibilityNodeInfo; 75import android.view.accessibility.AccessibilityNodeProvider; 76import android.view.animation.Animation; 77import android.view.animation.AnimationUtils; 78import android.view.animation.Transformation; 79import android.view.inputmethod.EditorInfo; 80import android.view.inputmethod.InputConnection; 81import android.view.inputmethod.InputMethodManager; 82import android.widget.ScrollBarDrawable; 83 84import static android.os.Build.VERSION_CODES.*; 85import static java.lang.Math.max; 86 87import com.android.internal.R; 88import com.android.internal.util.Predicate; 89import com.android.internal.view.menu.MenuBuilder; 90 91import com.google.android.collect.Lists; 92import com.google.android.collect.Maps; 93 94import java.lang.annotation.Retention; 95import java.lang.annotation.RetentionPolicy; 96import java.lang.ref.WeakReference; 97import java.lang.reflect.Field; 98import java.lang.reflect.InvocationTargetException; 99import java.lang.reflect.Method; 100import java.lang.reflect.Modifier; 101import java.util.ArrayList; 102import java.util.Arrays; 103import java.util.Collections; 104import java.util.HashMap; 105import java.util.Locale; 106import java.util.concurrent.CopyOnWriteArrayList; 107import java.util.concurrent.atomic.AtomicInteger; 108 109/** 110 * <p> 111 * This class represents the basic building block for user interface components. A View 112 * occupies a rectangular area on the screen and is responsible for drawing and 113 * event handling. View is the base class for <em>widgets</em>, which are 114 * used to create interactive UI components (buttons, text fields, etc.). The 115 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 116 * are invisible containers that hold other Views (or other ViewGroups) and define 117 * their layout properties. 118 * </p> 119 * 120 * <div class="special reference"> 121 * <h3>Developer Guides</h3> 122 * <p>For information about using this class to develop your application's user interface, 123 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 124 * </div> 125 * 126 * <a name="Using"></a> 127 * <h3>Using Views</h3> 128 * <p> 129 * All of the views in a window are arranged in a single tree. You can add views 130 * either from code or by specifying a tree of views in one or more XML layout 131 * files. There are many specialized subclasses of views that act as controls or 132 * are capable of displaying text, images, or other content. 133 * </p> 134 * <p> 135 * Once you have created a tree of views, there are typically a few types of 136 * common operations you may wish to perform: 137 * <ul> 138 * <li><strong>Set properties:</strong> for example setting the text of a 139 * {@link android.widget.TextView}. The available properties and the methods 140 * that set them will vary among the different subclasses of views. Note that 141 * properties that are known at build time can be set in the XML layout 142 * files.</li> 143 * <li><strong>Set focus:</strong> The framework will handled moving focus in 144 * response to user input. To force focus to a specific view, call 145 * {@link #requestFocus}.</li> 146 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 147 * that will be notified when something interesting happens to the view. For 148 * example, all views will let you set a listener to be notified when the view 149 * gains or loses focus. You can register such a listener using 150 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 151 * Other view subclasses offer more specialized listeners. For example, a Button 152 * exposes a listener to notify clients when the button is clicked.</li> 153 * <li><strong>Set visibility:</strong> You can hide or show views using 154 * {@link #setVisibility(int)}.</li> 155 * </ul> 156 * </p> 157 * <p><em> 158 * Note: The Android framework is responsible for measuring, laying out and 159 * drawing views. You should not call methods that perform these actions on 160 * views yourself unless you are actually implementing a 161 * {@link android.view.ViewGroup}. 162 * </em></p> 163 * 164 * <a name="Lifecycle"></a> 165 * <h3>Implementing a Custom View</h3> 166 * 167 * <p> 168 * To implement a custom view, you will usually begin by providing overrides for 169 * some of the standard methods that the framework calls on all views. You do 170 * not need to override all of these methods. In fact, you can start by just 171 * overriding {@link #onDraw(android.graphics.Canvas)}. 172 * <table border="2" width="85%" align="center" cellpadding="5"> 173 * <thead> 174 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 175 * </thead> 176 * 177 * <tbody> 178 * <tr> 179 * <td rowspan="2">Creation</td> 180 * <td>Constructors</td> 181 * <td>There is a form of the constructor that are called when the view 182 * is created from code and a form that is called when the view is 183 * inflated from a layout file. The second form should parse and apply 184 * any attributes defined in the layout file. 185 * </td> 186 * </tr> 187 * <tr> 188 * <td><code>{@link #onFinishInflate()}</code></td> 189 * <td>Called after a view and all of its children has been inflated 190 * from XML.</td> 191 * </tr> 192 * 193 * <tr> 194 * <td rowspan="3">Layout</td> 195 * <td><code>{@link #onMeasure(int, int)}</code></td> 196 * <td>Called to determine the size requirements for this view and all 197 * of its children. 198 * </td> 199 * </tr> 200 * <tr> 201 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 202 * <td>Called when this view should assign a size and position to all 203 * of its children. 204 * </td> 205 * </tr> 206 * <tr> 207 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 208 * <td>Called when the size of this view has changed. 209 * </td> 210 * </tr> 211 * 212 * <tr> 213 * <td>Drawing</td> 214 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 215 * <td>Called when the view should render its content. 216 * </td> 217 * </tr> 218 * 219 * <tr> 220 * <td rowspan="4">Event processing</td> 221 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 222 * <td>Called when a new hardware key event occurs. 223 * </td> 224 * </tr> 225 * <tr> 226 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 227 * <td>Called when a hardware key up event occurs. 228 * </td> 229 * </tr> 230 * <tr> 231 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 232 * <td>Called when a trackball motion event occurs. 233 * </td> 234 * </tr> 235 * <tr> 236 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 237 * <td>Called when a touch screen motion event occurs. 238 * </td> 239 * </tr> 240 * 241 * <tr> 242 * <td rowspan="2">Focus</td> 243 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 244 * <td>Called when the view gains or loses focus. 245 * </td> 246 * </tr> 247 * 248 * <tr> 249 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 250 * <td>Called when the window containing the view gains or loses focus. 251 * </td> 252 * </tr> 253 * 254 * <tr> 255 * <td rowspan="3">Attaching</td> 256 * <td><code>{@link #onAttachedToWindow()}</code></td> 257 * <td>Called when the view is attached to a window. 258 * </td> 259 * </tr> 260 * 261 * <tr> 262 * <td><code>{@link #onDetachedFromWindow}</code></td> 263 * <td>Called when the view is detached from its window. 264 * </td> 265 * </tr> 266 * 267 * <tr> 268 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 269 * <td>Called when the visibility of the window containing the view 270 * has changed. 271 * </td> 272 * </tr> 273 * </tbody> 274 * 275 * </table> 276 * </p> 277 * 278 * <a name="IDs"></a> 279 * <h3>IDs</h3> 280 * Views may have an integer id associated with them. These ids are typically 281 * assigned in the layout XML files, and are used to find specific views within 282 * the view tree. A common pattern is to: 283 * <ul> 284 * <li>Define a Button in the layout file and assign it a unique ID. 285 * <pre> 286 * <Button 287 * android:id="@+id/my_button" 288 * android:layout_width="wrap_content" 289 * android:layout_height="wrap_content" 290 * android:text="@string/my_button_text"/> 291 * </pre></li> 292 * <li>From the onCreate method of an Activity, find the Button 293 * <pre class="prettyprint"> 294 * Button myButton = (Button) findViewById(R.id.my_button); 295 * </pre></li> 296 * </ul> 297 * <p> 298 * View IDs need not be unique throughout the tree, but it is good practice to 299 * ensure that they are at least unique within the part of the tree you are 300 * searching. 301 * </p> 302 * 303 * <a name="Position"></a> 304 * <h3>Position</h3> 305 * <p> 306 * The geometry of a view is that of a rectangle. A view has a location, 307 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 308 * two dimensions, expressed as a width and a height. The unit for location 309 * and dimensions is the pixel. 310 * </p> 311 * 312 * <p> 313 * It is possible to retrieve the location of a view by invoking the methods 314 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 315 * coordinate of the rectangle representing the view. The latter returns the 316 * top, or Y, coordinate of the rectangle representing the view. These methods 317 * both return the location of the view relative to its parent. For instance, 318 * when getLeft() returns 20, that means the view is located 20 pixels to the 319 * right of the left edge of its direct parent. 320 * </p> 321 * 322 * <p> 323 * In addition, several convenience methods are offered to avoid unnecessary 324 * computations, namely {@link #getRight()} and {@link #getBottom()}. 325 * These methods return the coordinates of the right and bottom edges of the 326 * rectangle representing the view. For instance, calling {@link #getRight()} 327 * is similar to the following computation: <code>getLeft() + getWidth()</code> 328 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 329 * </p> 330 * 331 * <a name="SizePaddingMargins"></a> 332 * <h3>Size, padding and margins</h3> 333 * <p> 334 * The size of a view is expressed with a width and a height. A view actually 335 * possess two pairs of width and height values. 336 * </p> 337 * 338 * <p> 339 * The first pair is known as <em>measured width</em> and 340 * <em>measured height</em>. These dimensions define how big a view wants to be 341 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 342 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 343 * and {@link #getMeasuredHeight()}. 344 * </p> 345 * 346 * <p> 347 * The second pair is simply known as <em>width</em> and <em>height</em>, or 348 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 349 * dimensions define the actual size of the view on screen, at drawing time and 350 * after layout. These values may, but do not have to, be different from the 351 * measured width and height. The width and height can be obtained by calling 352 * {@link #getWidth()} and {@link #getHeight()}. 353 * </p> 354 * 355 * <p> 356 * To measure its dimensions, a view takes into account its padding. The padding 357 * is expressed in pixels for the left, top, right and bottom parts of the view. 358 * Padding can be used to offset the content of the view by a specific amount of 359 * pixels. For instance, a left padding of 2 will push the view's content by 360 * 2 pixels to the right of the left edge. Padding can be set using the 361 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 362 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 363 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 364 * {@link #getPaddingEnd()}. 365 * </p> 366 * 367 * <p> 368 * Even though a view can define a padding, it does not provide any support for 369 * margins. However, view groups provide such a support. Refer to 370 * {@link android.view.ViewGroup} and 371 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 372 * </p> 373 * 374 * <a name="Layout"></a> 375 * <h3>Layout</h3> 376 * <p> 377 * Layout is a two pass process: a measure pass and a layout pass. The measuring 378 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 379 * of the view tree. Each view pushes dimension specifications down the tree 380 * during the recursion. At the end of the measure pass, every view has stored 381 * its measurements. The second pass happens in 382 * {@link #layout(int,int,int,int)} and is also top-down. During 383 * this pass each parent is responsible for positioning all of its children 384 * using the sizes computed in the measure pass. 385 * </p> 386 * 387 * <p> 388 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 389 * {@link #getMeasuredHeight()} values must be set, along with those for all of 390 * that view's descendants. A view's measured width and measured height values 391 * must respect the constraints imposed by the view's parents. This guarantees 392 * that at the end of the measure pass, all parents accept all of their 393 * children's measurements. A parent view may call measure() more than once on 394 * its children. For example, the parent may measure each child once with 395 * unspecified dimensions to find out how big they want to be, then call 396 * measure() on them again with actual numbers if the sum of all the children's 397 * unconstrained sizes is too big or too small. 398 * </p> 399 * 400 * <p> 401 * The measure pass uses two classes to communicate dimensions. The 402 * {@link MeasureSpec} class is used by views to tell their parents how they 403 * want to be measured and positioned. The base LayoutParams class just 404 * describes how big the view wants to be for both width and height. For each 405 * dimension, it can specify one of: 406 * <ul> 407 * <li> an exact number 408 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 409 * (minus padding) 410 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 411 * enclose its content (plus padding). 412 * </ul> 413 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 414 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 415 * an X and Y value. 416 * </p> 417 * 418 * <p> 419 * MeasureSpecs are used to push requirements down the tree from parent to 420 * child. A MeasureSpec can be in one of three modes: 421 * <ul> 422 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 423 * of a child view. For example, a LinearLayout may call measure() on its child 424 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 425 * tall the child view wants to be given a width of 240 pixels. 426 * <li>EXACTLY: This is used by the parent to impose an exact size on the 427 * child. The child must use this size, and guarantee that all of its 428 * descendants will fit within this size. 429 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 430 * child. The child must gurantee that it and all of its descendants will fit 431 * within this size. 432 * </ul> 433 * </p> 434 * 435 * <p> 436 * To intiate a layout, call {@link #requestLayout}. This method is typically 437 * called by a view on itself when it believes that is can no longer fit within 438 * its current bounds. 439 * </p> 440 * 441 * <a name="Drawing"></a> 442 * <h3>Drawing</h3> 443 * <p> 444 * Drawing is handled by walking the tree and rendering each view that 445 * intersects the invalid region. Because the tree is traversed in-order, 446 * this means that parents will draw before (i.e., behind) their children, with 447 * siblings drawn in the order they appear in the tree. 448 * If you set a background drawable for a View, then the View will draw it for you 449 * before calling back to its <code>onDraw()</code> method. 450 * </p> 451 * 452 * <p> 453 * Note that the framework will not draw views that are not in the invalid region. 454 * </p> 455 * 456 * <p> 457 * To force a view to draw, call {@link #invalidate()}. 458 * </p> 459 * 460 * <a name="EventHandlingThreading"></a> 461 * <h3>Event Handling and Threading</h3> 462 * <p> 463 * The basic cycle of a view is as follows: 464 * <ol> 465 * <li>An event comes in and is dispatched to the appropriate view. The view 466 * handles the event and notifies any listeners.</li> 467 * <li>If in the course of processing the event, the view's bounds may need 468 * to be changed, the view will call {@link #requestLayout()}.</li> 469 * <li>Similarly, if in the course of processing the event the view's appearance 470 * may need to be changed, the view will call {@link #invalidate()}.</li> 471 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 472 * the framework will take care of measuring, laying out, and drawing the tree 473 * as appropriate.</li> 474 * </ol> 475 * </p> 476 * 477 * <p><em>Note: The entire view tree is single threaded. You must always be on 478 * the UI thread when calling any method on any view.</em> 479 * If you are doing work on other threads and want to update the state of a view 480 * from that thread, you should use a {@link Handler}. 481 * </p> 482 * 483 * <a name="FocusHandling"></a> 484 * <h3>Focus Handling</h3> 485 * <p> 486 * The framework will handle routine focus movement in response to user input. 487 * This includes changing the focus as views are removed or hidden, or as new 488 * views become available. Views indicate their willingness to take focus 489 * through the {@link #isFocusable} method. To change whether a view can take 490 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 491 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 492 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 493 * </p> 494 * <p> 495 * Focus movement is based on an algorithm which finds the nearest neighbor in a 496 * given direction. In rare cases, the default algorithm may not match the 497 * intended behavior of the developer. In these situations, you can provide 498 * explicit overrides by using these XML attributes in the layout file: 499 * <pre> 500 * nextFocusDown 501 * nextFocusLeft 502 * nextFocusRight 503 * nextFocusUp 504 * </pre> 505 * </p> 506 * 507 * 508 * <p> 509 * To get a particular view to take focus, call {@link #requestFocus()}. 510 * </p> 511 * 512 * <a name="TouchMode"></a> 513 * <h3>Touch Mode</h3> 514 * <p> 515 * When a user is navigating a user interface via directional keys such as a D-pad, it is 516 * necessary to give focus to actionable items such as buttons so the user can see 517 * what will take input. If the device has touch capabilities, however, and the user 518 * begins interacting with the interface by touching it, it is no longer necessary to 519 * always highlight, or give focus to, a particular view. This motivates a mode 520 * for interaction named 'touch mode'. 521 * </p> 522 * <p> 523 * For a touch capable device, once the user touches the screen, the device 524 * will enter touch mode. From this point onward, only views for which 525 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 526 * Other views that are touchable, like buttons, will not take focus when touched; they will 527 * only fire the on click listeners. 528 * </p> 529 * <p> 530 * Any time a user hits a directional key, such as a D-pad direction, the view device will 531 * exit touch mode, and find a view to take focus, so that the user may resume interacting 532 * with the user interface without touching the screen again. 533 * </p> 534 * <p> 535 * The touch mode state is maintained across {@link android.app.Activity}s. Call 536 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 537 * </p> 538 * 539 * <a name="Scrolling"></a> 540 * <h3>Scrolling</h3> 541 * <p> 542 * The framework provides basic support for views that wish to internally 543 * scroll their content. This includes keeping track of the X and Y scroll 544 * offset as well as mechanisms for drawing scrollbars. See 545 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 546 * {@link #awakenScrollBars()} for more details. 547 * </p> 548 * 549 * <a name="Tags"></a> 550 * <h3>Tags</h3> 551 * <p> 552 * Unlike IDs, tags are not used to identify views. Tags are essentially an 553 * extra piece of information that can be associated with a view. They are most 554 * often used as a convenience to store data related to views in the views 555 * themselves rather than by putting them in a separate structure. 556 * </p> 557 * 558 * <a name="Properties"></a> 559 * <h3>Properties</h3> 560 * <p> 561 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 562 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 563 * available both in the {@link Property} form as well as in similarly-named setter/getter 564 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 565 * be used to set persistent state associated with these rendering-related properties on the view. 566 * The properties and methods can also be used in conjunction with 567 * {@link android.animation.Animator Animator}-based animations, described more in the 568 * <a href="#Animation">Animation</a> section. 569 * </p> 570 * 571 * <a name="Animation"></a> 572 * <h3>Animation</h3> 573 * <p> 574 * Starting with Android 3.0, the preferred way of animating views is to use the 575 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 576 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 577 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 578 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 579 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 580 * makes animating these View properties particularly easy and efficient. 581 * </p> 582 * <p> 583 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 584 * You can attach an {@link Animation} object to a view using 585 * {@link #setAnimation(Animation)} or 586 * {@link #startAnimation(Animation)}. The animation can alter the scale, 587 * rotation, translation and alpha of a view over time. If the animation is 588 * attached to a view that has children, the animation will affect the entire 589 * subtree rooted by that node. When an animation is started, the framework will 590 * take care of redrawing the appropriate views until the animation completes. 591 * </p> 592 * 593 * <a name="Security"></a> 594 * <h3>Security</h3> 595 * <p> 596 * Sometimes it is essential that an application be able to verify that an action 597 * is being performed with the full knowledge and consent of the user, such as 598 * granting a permission request, making a purchase or clicking on an advertisement. 599 * Unfortunately, a malicious application could try to spoof the user into 600 * performing these actions, unaware, by concealing the intended purpose of the view. 601 * As a remedy, the framework offers a touch filtering mechanism that can be used to 602 * improve the security of views that provide access to sensitive functionality. 603 * </p><p> 604 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 605 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 606 * will discard touches that are received whenever the view's window is obscured by 607 * another visible window. As a result, the view will not receive touches whenever a 608 * toast, dialog or other window appears above the view's window. 609 * </p><p> 610 * For more fine-grained control over security, consider overriding the 611 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 612 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 613 * </p> 614 * 615 * @attr ref android.R.styleable#View_alpha 616 * @attr ref android.R.styleable#View_background 617 * @attr ref android.R.styleable#View_clickable 618 * @attr ref android.R.styleable#View_contentDescription 619 * @attr ref android.R.styleable#View_drawingCacheQuality 620 * @attr ref android.R.styleable#View_duplicateParentState 621 * @attr ref android.R.styleable#View_id 622 * @attr ref android.R.styleable#View_requiresFadingEdge 623 * @attr ref android.R.styleable#View_fadeScrollbars 624 * @attr ref android.R.styleable#View_fadingEdgeLength 625 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 626 * @attr ref android.R.styleable#View_fitsSystemWindows 627 * @attr ref android.R.styleable#View_isScrollContainer 628 * @attr ref android.R.styleable#View_focusable 629 * @attr ref android.R.styleable#View_focusableInTouchMode 630 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 631 * @attr ref android.R.styleable#View_keepScreenOn 632 * @attr ref android.R.styleable#View_layerType 633 * @attr ref android.R.styleable#View_layoutDirection 634 * @attr ref android.R.styleable#View_longClickable 635 * @attr ref android.R.styleable#View_minHeight 636 * @attr ref android.R.styleable#View_minWidth 637 * @attr ref android.R.styleable#View_nextFocusDown 638 * @attr ref android.R.styleable#View_nextFocusLeft 639 * @attr ref android.R.styleable#View_nextFocusRight 640 * @attr ref android.R.styleable#View_nextFocusUp 641 * @attr ref android.R.styleable#View_onClick 642 * @attr ref android.R.styleable#View_padding 643 * @attr ref android.R.styleable#View_paddingBottom 644 * @attr ref android.R.styleable#View_paddingLeft 645 * @attr ref android.R.styleable#View_paddingRight 646 * @attr ref android.R.styleable#View_paddingTop 647 * @attr ref android.R.styleable#View_paddingStart 648 * @attr ref android.R.styleable#View_paddingEnd 649 * @attr ref android.R.styleable#View_saveEnabled 650 * @attr ref android.R.styleable#View_rotation 651 * @attr ref android.R.styleable#View_rotationX 652 * @attr ref android.R.styleable#View_rotationY 653 * @attr ref android.R.styleable#View_scaleX 654 * @attr ref android.R.styleable#View_scaleY 655 * @attr ref android.R.styleable#View_scrollX 656 * @attr ref android.R.styleable#View_scrollY 657 * @attr ref android.R.styleable#View_scrollbarSize 658 * @attr ref android.R.styleable#View_scrollbarStyle 659 * @attr ref android.R.styleable#View_scrollbars 660 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 661 * @attr ref android.R.styleable#View_scrollbarFadeDuration 662 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 663 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 664 * @attr ref android.R.styleable#View_scrollbarThumbVertical 665 * @attr ref android.R.styleable#View_scrollbarTrackVertical 666 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 667 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 668 * @attr ref android.R.styleable#View_sharedElementName 669 * @attr ref android.R.styleable#View_soundEffectsEnabled 670 * @attr ref android.R.styleable#View_tag 671 * @attr ref android.R.styleable#View_textAlignment 672 * @attr ref android.R.styleable#View_textDirection 673 * @attr ref android.R.styleable#View_transformPivotX 674 * @attr ref android.R.styleable#View_transformPivotY 675 * @attr ref android.R.styleable#View_translationX 676 * @attr ref android.R.styleable#View_translationY 677 * @attr ref android.R.styleable#View_translationZ 678 * @attr ref android.R.styleable#View_visibility 679 * 680 * @see android.view.ViewGroup 681 */ 682public class View implements Drawable.Callback, KeyEvent.Callback, 683 AccessibilityEventSource { 684 private static final boolean DBG = false; 685 686 /** 687 * The logging tag used by this class with android.util.Log. 688 */ 689 protected static final String VIEW_LOG_TAG = "View"; 690 691 /** 692 * When set to true, apps will draw debugging information about their layouts. 693 * 694 * @hide 695 */ 696 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 697 698 /** 699 * Used to mark a View that has no ID. 700 */ 701 public static final int NO_ID = -1; 702 703 /** 704 * Signals that compatibility booleans have been initialized according to 705 * target SDK versions. 706 */ 707 private static boolean sCompatibilityDone = false; 708 709 /** 710 * Use the old (broken) way of building MeasureSpecs. 711 */ 712 private static boolean sUseBrokenMakeMeasureSpec = false; 713 714 /** 715 * Ignore any optimizations using the measure cache. 716 */ 717 private static boolean sIgnoreMeasureCache = false; 718 719 /** 720 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 721 * calling setFlags. 722 */ 723 private static final int NOT_FOCUSABLE = 0x00000000; 724 725 /** 726 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 727 * setFlags. 728 */ 729 private static final int FOCUSABLE = 0x00000001; 730 731 /** 732 * Mask for use with setFlags indicating bits used for focus. 733 */ 734 private static final int FOCUSABLE_MASK = 0x00000001; 735 736 /** 737 * This view will adjust its padding to fit sytem windows (e.g. status bar) 738 */ 739 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 740 741 /** @hide */ 742 @IntDef({VISIBLE, INVISIBLE, GONE}) 743 @Retention(RetentionPolicy.SOURCE) 744 public @interface Visibility {} 745 746 /** 747 * This view is visible. 748 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 749 * android:visibility}. 750 */ 751 public static final int VISIBLE = 0x00000000; 752 753 /** 754 * This view is invisible, but it still takes up space for layout purposes. 755 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 756 * android:visibility}. 757 */ 758 public static final int INVISIBLE = 0x00000004; 759 760 /** 761 * This view is invisible, and it doesn't take any space for layout 762 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 763 * android:visibility}. 764 */ 765 public static final int GONE = 0x00000008; 766 767 /** 768 * Mask for use with setFlags indicating bits used for visibility. 769 * {@hide} 770 */ 771 static final int VISIBILITY_MASK = 0x0000000C; 772 773 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 774 775 /** 776 * This view is enabled. Interpretation varies by subclass. 777 * Use with ENABLED_MASK when calling setFlags. 778 * {@hide} 779 */ 780 static final int ENABLED = 0x00000000; 781 782 /** 783 * This view is disabled. Interpretation varies by subclass. 784 * Use with ENABLED_MASK when calling setFlags. 785 * {@hide} 786 */ 787 static final int DISABLED = 0x00000020; 788 789 /** 790 * Mask for use with setFlags indicating bits used for indicating whether 791 * this view is enabled 792 * {@hide} 793 */ 794 static final int ENABLED_MASK = 0x00000020; 795 796 /** 797 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 798 * called and further optimizations will be performed. It is okay to have 799 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 800 * {@hide} 801 */ 802 static final int WILL_NOT_DRAW = 0x00000080; 803 804 /** 805 * Mask for use with setFlags indicating bits used for indicating whether 806 * this view is will draw 807 * {@hide} 808 */ 809 static final int DRAW_MASK = 0x00000080; 810 811 /** 812 * <p>This view doesn't show scrollbars.</p> 813 * {@hide} 814 */ 815 static final int SCROLLBARS_NONE = 0x00000000; 816 817 /** 818 * <p>This view shows horizontal scrollbars.</p> 819 * {@hide} 820 */ 821 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 822 823 /** 824 * <p>This view shows vertical scrollbars.</p> 825 * {@hide} 826 */ 827 static final int SCROLLBARS_VERTICAL = 0x00000200; 828 829 /** 830 * <p>Mask for use with setFlags indicating bits used for indicating which 831 * scrollbars are enabled.</p> 832 * {@hide} 833 */ 834 static final int SCROLLBARS_MASK = 0x00000300; 835 836 /** 837 * Indicates that the view should filter touches when its window is obscured. 838 * Refer to the class comments for more information about this security feature. 839 * {@hide} 840 */ 841 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 842 843 /** 844 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 845 * that they are optional and should be skipped if the window has 846 * requested system UI flags that ignore those insets for layout. 847 */ 848 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 849 850 /** 851 * <p>This view doesn't show fading edges.</p> 852 * {@hide} 853 */ 854 static final int FADING_EDGE_NONE = 0x00000000; 855 856 /** 857 * <p>This view shows horizontal fading edges.</p> 858 * {@hide} 859 */ 860 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 861 862 /** 863 * <p>This view shows vertical fading edges.</p> 864 * {@hide} 865 */ 866 static final int FADING_EDGE_VERTICAL = 0x00002000; 867 868 /** 869 * <p>Mask for use with setFlags indicating bits used for indicating which 870 * fading edges are enabled.</p> 871 * {@hide} 872 */ 873 static final int FADING_EDGE_MASK = 0x00003000; 874 875 /** 876 * <p>Indicates this view can be clicked. When clickable, a View reacts 877 * to clicks by notifying the OnClickListener.<p> 878 * {@hide} 879 */ 880 static final int CLICKABLE = 0x00004000; 881 882 /** 883 * <p>Indicates this view is caching its drawing into a bitmap.</p> 884 * {@hide} 885 */ 886 static final int DRAWING_CACHE_ENABLED = 0x00008000; 887 888 /** 889 * <p>Indicates that no icicle should be saved for this view.<p> 890 * {@hide} 891 */ 892 static final int SAVE_DISABLED = 0x000010000; 893 894 /** 895 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 896 * property.</p> 897 * {@hide} 898 */ 899 static final int SAVE_DISABLED_MASK = 0x000010000; 900 901 /** 902 * <p>Indicates that no drawing cache should ever be created for this view.<p> 903 * {@hide} 904 */ 905 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 906 907 /** 908 * <p>Indicates this view can take / keep focus when int touch mode.</p> 909 * {@hide} 910 */ 911 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 912 913 /** @hide */ 914 @Retention(RetentionPolicy.SOURCE) 915 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 916 public @interface DrawingCacheQuality {} 917 918 /** 919 * <p>Enables low quality mode for the drawing cache.</p> 920 */ 921 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 922 923 /** 924 * <p>Enables high quality mode for the drawing cache.</p> 925 */ 926 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 927 928 /** 929 * <p>Enables automatic quality mode for the drawing cache.</p> 930 */ 931 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 932 933 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 934 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 935 }; 936 937 /** 938 * <p>Mask for use with setFlags indicating bits used for the cache 939 * quality property.</p> 940 * {@hide} 941 */ 942 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 943 944 /** 945 * <p> 946 * Indicates this view can be long clicked. When long clickable, a View 947 * reacts to long clicks by notifying the OnLongClickListener or showing a 948 * context menu. 949 * </p> 950 * {@hide} 951 */ 952 static final int LONG_CLICKABLE = 0x00200000; 953 954 /** 955 * <p>Indicates that this view gets its drawable states from its direct parent 956 * and ignores its original internal states.</p> 957 * 958 * @hide 959 */ 960 static final int DUPLICATE_PARENT_STATE = 0x00400000; 961 962 /** @hide */ 963 @IntDef({ 964 SCROLLBARS_INSIDE_OVERLAY, 965 SCROLLBARS_INSIDE_INSET, 966 SCROLLBARS_OUTSIDE_OVERLAY, 967 SCROLLBARS_OUTSIDE_INSET 968 }) 969 @Retention(RetentionPolicy.SOURCE) 970 public @interface ScrollBarStyle {} 971 972 /** 973 * The scrollbar style to display the scrollbars inside the content area, 974 * without increasing the padding. The scrollbars will be overlaid with 975 * translucency on the view's content. 976 */ 977 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 978 979 /** 980 * The scrollbar style to display the scrollbars inside the padded area, 981 * increasing the padding of the view. The scrollbars will not overlap the 982 * content area of the view. 983 */ 984 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 985 986 /** 987 * The scrollbar style to display the scrollbars at the edge of the view, 988 * without increasing the padding. The scrollbars will be overlaid with 989 * translucency. 990 */ 991 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 992 993 /** 994 * The scrollbar style to display the scrollbars at the edge of the view, 995 * increasing the padding of the view. The scrollbars will only overlap the 996 * background, if any. 997 */ 998 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 999 1000 /** 1001 * Mask to check if the scrollbar style is overlay or inset. 1002 * {@hide} 1003 */ 1004 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1005 1006 /** 1007 * Mask to check if the scrollbar style is inside or outside. 1008 * {@hide} 1009 */ 1010 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1011 1012 /** 1013 * Mask for scrollbar style. 1014 * {@hide} 1015 */ 1016 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1017 1018 /** 1019 * View flag indicating that the screen should remain on while the 1020 * window containing this view is visible to the user. This effectively 1021 * takes care of automatically setting the WindowManager's 1022 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1023 */ 1024 public static final int KEEP_SCREEN_ON = 0x04000000; 1025 1026 /** 1027 * View flag indicating whether this view should have sound effects enabled 1028 * for events such as clicking and touching. 1029 */ 1030 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1031 1032 /** 1033 * View flag indicating whether this view should have haptic feedback 1034 * enabled for events such as long presses. 1035 */ 1036 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1037 1038 /** 1039 * <p>Indicates that the view hierarchy should stop saving state when 1040 * it reaches this view. If state saving is initiated immediately at 1041 * the view, it will be allowed. 1042 * {@hide} 1043 */ 1044 static final int PARENT_SAVE_DISABLED = 0x20000000; 1045 1046 /** 1047 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1048 * {@hide} 1049 */ 1050 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1051 1052 /** @hide */ 1053 @IntDef(flag = true, 1054 value = { 1055 FOCUSABLES_ALL, 1056 FOCUSABLES_TOUCH_MODE 1057 }) 1058 @Retention(RetentionPolicy.SOURCE) 1059 public @interface FocusableMode {} 1060 1061 /** 1062 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1063 * should add all focusable Views regardless if they are focusable in touch mode. 1064 */ 1065 public static final int FOCUSABLES_ALL = 0x00000000; 1066 1067 /** 1068 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1069 * should add only Views focusable in touch mode. 1070 */ 1071 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1072 1073 /** @hide */ 1074 @IntDef({ 1075 FOCUS_BACKWARD, 1076 FOCUS_FORWARD, 1077 FOCUS_LEFT, 1078 FOCUS_UP, 1079 FOCUS_RIGHT, 1080 FOCUS_DOWN 1081 }) 1082 @Retention(RetentionPolicy.SOURCE) 1083 public @interface FocusDirection {} 1084 1085 /** @hide */ 1086 @IntDef({ 1087 FOCUS_LEFT, 1088 FOCUS_UP, 1089 FOCUS_RIGHT, 1090 FOCUS_DOWN 1091 }) 1092 @Retention(RetentionPolicy.SOURCE) 1093 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1094 1095 /** 1096 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1097 * item. 1098 */ 1099 public static final int FOCUS_BACKWARD = 0x00000001; 1100 1101 /** 1102 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1103 * item. 1104 */ 1105 public static final int FOCUS_FORWARD = 0x00000002; 1106 1107 /** 1108 * Use with {@link #focusSearch(int)}. Move focus to the left. 1109 */ 1110 public static final int FOCUS_LEFT = 0x00000011; 1111 1112 /** 1113 * Use with {@link #focusSearch(int)}. Move focus up. 1114 */ 1115 public static final int FOCUS_UP = 0x00000021; 1116 1117 /** 1118 * Use with {@link #focusSearch(int)}. Move focus to the right. 1119 */ 1120 public static final int FOCUS_RIGHT = 0x00000042; 1121 1122 /** 1123 * Use with {@link #focusSearch(int)}. Move focus down. 1124 */ 1125 public static final int FOCUS_DOWN = 0x00000082; 1126 1127 /** 1128 * Bits of {@link #getMeasuredWidthAndState()} and 1129 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1130 */ 1131 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1132 1133 /** 1134 * Bits of {@link #getMeasuredWidthAndState()} and 1135 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1136 */ 1137 public static final int MEASURED_STATE_MASK = 0xff000000; 1138 1139 /** 1140 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1141 * for functions that combine both width and height into a single int, 1142 * such as {@link #getMeasuredState()} and the childState argument of 1143 * {@link #resolveSizeAndState(int, int, int)}. 1144 */ 1145 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1146 1147 /** 1148 * Bit of {@link #getMeasuredWidthAndState()} and 1149 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1150 * is smaller that the space the view would like to have. 1151 */ 1152 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1153 1154 /** 1155 * Base View state sets 1156 */ 1157 // Singles 1158 /** 1159 * Indicates the view has no states set. States are used with 1160 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1161 * view depending on its state. 1162 * 1163 * @see android.graphics.drawable.Drawable 1164 * @see #getDrawableState() 1165 */ 1166 protected static final int[] EMPTY_STATE_SET; 1167 /** 1168 * Indicates the view is enabled. States are used with 1169 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1170 * view depending on its state. 1171 * 1172 * @see android.graphics.drawable.Drawable 1173 * @see #getDrawableState() 1174 */ 1175 protected static final int[] ENABLED_STATE_SET; 1176 /** 1177 * Indicates the view is focused. States are used with 1178 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1179 * view depending on its state. 1180 * 1181 * @see android.graphics.drawable.Drawable 1182 * @see #getDrawableState() 1183 */ 1184 protected static final int[] FOCUSED_STATE_SET; 1185 /** 1186 * Indicates the view is selected. States are used with 1187 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1188 * view depending on its state. 1189 * 1190 * @see android.graphics.drawable.Drawable 1191 * @see #getDrawableState() 1192 */ 1193 protected static final int[] SELECTED_STATE_SET; 1194 /** 1195 * Indicates the view is pressed. States are used with 1196 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1197 * view depending on its state. 1198 * 1199 * @see android.graphics.drawable.Drawable 1200 * @see #getDrawableState() 1201 */ 1202 protected static final int[] PRESSED_STATE_SET; 1203 /** 1204 * Indicates the view's window has focus. States are used with 1205 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1206 * view depending on its state. 1207 * 1208 * @see android.graphics.drawable.Drawable 1209 * @see #getDrawableState() 1210 */ 1211 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1212 // Doubles 1213 /** 1214 * Indicates the view is enabled and has the focus. 1215 * 1216 * @see #ENABLED_STATE_SET 1217 * @see #FOCUSED_STATE_SET 1218 */ 1219 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1220 /** 1221 * Indicates the view is enabled and selected. 1222 * 1223 * @see #ENABLED_STATE_SET 1224 * @see #SELECTED_STATE_SET 1225 */ 1226 protected static final int[] ENABLED_SELECTED_STATE_SET; 1227 /** 1228 * Indicates the view is enabled and that its window has focus. 1229 * 1230 * @see #ENABLED_STATE_SET 1231 * @see #WINDOW_FOCUSED_STATE_SET 1232 */ 1233 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1234 /** 1235 * Indicates the view is focused and selected. 1236 * 1237 * @see #FOCUSED_STATE_SET 1238 * @see #SELECTED_STATE_SET 1239 */ 1240 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1241 /** 1242 * Indicates the view has the focus and that its window has the focus. 1243 * 1244 * @see #FOCUSED_STATE_SET 1245 * @see #WINDOW_FOCUSED_STATE_SET 1246 */ 1247 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1248 /** 1249 * Indicates the view is selected and that its window has the focus. 1250 * 1251 * @see #SELECTED_STATE_SET 1252 * @see #WINDOW_FOCUSED_STATE_SET 1253 */ 1254 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1255 // Triples 1256 /** 1257 * Indicates the view is enabled, focused and selected. 1258 * 1259 * @see #ENABLED_STATE_SET 1260 * @see #FOCUSED_STATE_SET 1261 * @see #SELECTED_STATE_SET 1262 */ 1263 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1264 /** 1265 * Indicates the view is enabled, focused and its window has the focus. 1266 * 1267 * @see #ENABLED_STATE_SET 1268 * @see #FOCUSED_STATE_SET 1269 * @see #WINDOW_FOCUSED_STATE_SET 1270 */ 1271 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1272 /** 1273 * Indicates the view is enabled, selected and its window has the focus. 1274 * 1275 * @see #ENABLED_STATE_SET 1276 * @see #SELECTED_STATE_SET 1277 * @see #WINDOW_FOCUSED_STATE_SET 1278 */ 1279 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1280 /** 1281 * Indicates the view is focused, selected and its window has the focus. 1282 * 1283 * @see #FOCUSED_STATE_SET 1284 * @see #SELECTED_STATE_SET 1285 * @see #WINDOW_FOCUSED_STATE_SET 1286 */ 1287 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1288 /** 1289 * Indicates the view is enabled, focused, selected and its window 1290 * has the focus. 1291 * 1292 * @see #ENABLED_STATE_SET 1293 * @see #FOCUSED_STATE_SET 1294 * @see #SELECTED_STATE_SET 1295 * @see #WINDOW_FOCUSED_STATE_SET 1296 */ 1297 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1298 /** 1299 * Indicates the view is pressed and its window has the focus. 1300 * 1301 * @see #PRESSED_STATE_SET 1302 * @see #WINDOW_FOCUSED_STATE_SET 1303 */ 1304 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1305 /** 1306 * Indicates the view is pressed and selected. 1307 * 1308 * @see #PRESSED_STATE_SET 1309 * @see #SELECTED_STATE_SET 1310 */ 1311 protected static final int[] PRESSED_SELECTED_STATE_SET; 1312 /** 1313 * Indicates the view is pressed, selected and its window has the focus. 1314 * 1315 * @see #PRESSED_STATE_SET 1316 * @see #SELECTED_STATE_SET 1317 * @see #WINDOW_FOCUSED_STATE_SET 1318 */ 1319 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1320 /** 1321 * Indicates the view is pressed and focused. 1322 * 1323 * @see #PRESSED_STATE_SET 1324 * @see #FOCUSED_STATE_SET 1325 */ 1326 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1327 /** 1328 * Indicates the view is pressed, focused and its window has the focus. 1329 * 1330 * @see #PRESSED_STATE_SET 1331 * @see #FOCUSED_STATE_SET 1332 * @see #WINDOW_FOCUSED_STATE_SET 1333 */ 1334 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1335 /** 1336 * Indicates the view is pressed, focused and selected. 1337 * 1338 * @see #PRESSED_STATE_SET 1339 * @see #SELECTED_STATE_SET 1340 * @see #FOCUSED_STATE_SET 1341 */ 1342 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1343 /** 1344 * Indicates the view is pressed, focused, selected and its window has the focus. 1345 * 1346 * @see #PRESSED_STATE_SET 1347 * @see #FOCUSED_STATE_SET 1348 * @see #SELECTED_STATE_SET 1349 * @see #WINDOW_FOCUSED_STATE_SET 1350 */ 1351 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1352 /** 1353 * Indicates the view is pressed and enabled. 1354 * 1355 * @see #PRESSED_STATE_SET 1356 * @see #ENABLED_STATE_SET 1357 */ 1358 protected static final int[] PRESSED_ENABLED_STATE_SET; 1359 /** 1360 * Indicates the view is pressed, enabled and its window has the focus. 1361 * 1362 * @see #PRESSED_STATE_SET 1363 * @see #ENABLED_STATE_SET 1364 * @see #WINDOW_FOCUSED_STATE_SET 1365 */ 1366 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1367 /** 1368 * Indicates the view is pressed, enabled and selected. 1369 * 1370 * @see #PRESSED_STATE_SET 1371 * @see #ENABLED_STATE_SET 1372 * @see #SELECTED_STATE_SET 1373 */ 1374 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1375 /** 1376 * Indicates the view is pressed, enabled, selected and its window has the 1377 * focus. 1378 * 1379 * @see #PRESSED_STATE_SET 1380 * @see #ENABLED_STATE_SET 1381 * @see #SELECTED_STATE_SET 1382 * @see #WINDOW_FOCUSED_STATE_SET 1383 */ 1384 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1385 /** 1386 * Indicates the view is pressed, enabled and focused. 1387 * 1388 * @see #PRESSED_STATE_SET 1389 * @see #ENABLED_STATE_SET 1390 * @see #FOCUSED_STATE_SET 1391 */ 1392 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1393 /** 1394 * Indicates the view is pressed, enabled, focused and its window has the 1395 * focus. 1396 * 1397 * @see #PRESSED_STATE_SET 1398 * @see #ENABLED_STATE_SET 1399 * @see #FOCUSED_STATE_SET 1400 * @see #WINDOW_FOCUSED_STATE_SET 1401 */ 1402 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1403 /** 1404 * Indicates the view is pressed, enabled, focused and selected. 1405 * 1406 * @see #PRESSED_STATE_SET 1407 * @see #ENABLED_STATE_SET 1408 * @see #SELECTED_STATE_SET 1409 * @see #FOCUSED_STATE_SET 1410 */ 1411 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1412 /** 1413 * Indicates the view is pressed, enabled, focused, selected and its window 1414 * has the focus. 1415 * 1416 * @see #PRESSED_STATE_SET 1417 * @see #ENABLED_STATE_SET 1418 * @see #SELECTED_STATE_SET 1419 * @see #FOCUSED_STATE_SET 1420 * @see #WINDOW_FOCUSED_STATE_SET 1421 */ 1422 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1423 1424 /** 1425 * The order here is very important to {@link #getDrawableState()} 1426 */ 1427 private static final int[][] VIEW_STATE_SETS; 1428 1429 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1430 static final int VIEW_STATE_SELECTED = 1 << 1; 1431 static final int VIEW_STATE_FOCUSED = 1 << 2; 1432 static final int VIEW_STATE_ENABLED = 1 << 3; 1433 static final int VIEW_STATE_PRESSED = 1 << 4; 1434 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1435 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1436 static final int VIEW_STATE_HOVERED = 1 << 7; 1437 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1438 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1439 1440 static final int[] VIEW_STATE_IDS = new int[] { 1441 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1442 R.attr.state_selected, VIEW_STATE_SELECTED, 1443 R.attr.state_focused, VIEW_STATE_FOCUSED, 1444 R.attr.state_enabled, VIEW_STATE_ENABLED, 1445 R.attr.state_pressed, VIEW_STATE_PRESSED, 1446 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1447 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1448 R.attr.state_hovered, VIEW_STATE_HOVERED, 1449 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1450 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1451 }; 1452 1453 static { 1454 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1455 throw new IllegalStateException( 1456 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1457 } 1458 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1459 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1460 int viewState = R.styleable.ViewDrawableStates[i]; 1461 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1462 if (VIEW_STATE_IDS[j] == viewState) { 1463 orderedIds[i * 2] = viewState; 1464 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1465 } 1466 } 1467 } 1468 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1469 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1470 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1471 int numBits = Integer.bitCount(i); 1472 int[] set = new int[numBits]; 1473 int pos = 0; 1474 for (int j = 0; j < orderedIds.length; j += 2) { 1475 if ((i & orderedIds[j+1]) != 0) { 1476 set[pos++] = orderedIds[j]; 1477 } 1478 } 1479 VIEW_STATE_SETS[i] = set; 1480 } 1481 1482 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1483 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1484 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1485 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1486 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1487 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1488 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1489 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1490 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1491 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1492 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1493 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1494 | VIEW_STATE_FOCUSED]; 1495 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1496 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1497 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1498 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1499 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1500 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1501 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1502 | VIEW_STATE_ENABLED]; 1503 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1504 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1505 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1506 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1507 | VIEW_STATE_ENABLED]; 1508 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1509 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1510 | VIEW_STATE_ENABLED]; 1511 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1512 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1513 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1514 1515 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1516 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1517 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1518 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1519 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1520 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1521 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1522 | VIEW_STATE_PRESSED]; 1523 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1524 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1525 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1526 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1527 | VIEW_STATE_PRESSED]; 1528 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1529 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1530 | VIEW_STATE_PRESSED]; 1531 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1532 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1533 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1534 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1535 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1536 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1537 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1538 | VIEW_STATE_PRESSED]; 1539 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1540 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1541 | VIEW_STATE_PRESSED]; 1542 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1543 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1544 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1545 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1546 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1547 | VIEW_STATE_PRESSED]; 1548 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1549 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1550 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1551 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1552 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1553 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1554 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1555 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1556 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1557 | VIEW_STATE_PRESSED]; 1558 } 1559 1560 /** 1561 * Accessibility event types that are dispatched for text population. 1562 */ 1563 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1564 AccessibilityEvent.TYPE_VIEW_CLICKED 1565 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1566 | AccessibilityEvent.TYPE_VIEW_SELECTED 1567 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1568 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1569 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1570 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1571 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1572 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1573 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1574 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1575 1576 /** 1577 * Temporary Rect currently for use in setBackground(). This will probably 1578 * be extended in the future to hold our own class with more than just 1579 * a Rect. :) 1580 */ 1581 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1582 1583 /** 1584 * Map used to store views' tags. 1585 */ 1586 private SparseArray<Object> mKeyedTags; 1587 1588 /** 1589 * The next available accessibility id. 1590 */ 1591 private static int sNextAccessibilityViewId; 1592 1593 /** 1594 * The animation currently associated with this view. 1595 * @hide 1596 */ 1597 protected Animation mCurrentAnimation = null; 1598 1599 /** 1600 * Width as measured during measure pass. 1601 * {@hide} 1602 */ 1603 @ViewDebug.ExportedProperty(category = "measurement") 1604 int mMeasuredWidth; 1605 1606 /** 1607 * Height as measured during measure pass. 1608 * {@hide} 1609 */ 1610 @ViewDebug.ExportedProperty(category = "measurement") 1611 int mMeasuredHeight; 1612 1613 /** 1614 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1615 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1616 * its display list. This flag, used only when hw accelerated, allows us to clear the 1617 * flag while retaining this information until it's needed (at getDisplayList() time and 1618 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1619 * 1620 * {@hide} 1621 */ 1622 boolean mRecreateDisplayList = false; 1623 1624 /** 1625 * The view's identifier. 1626 * {@hide} 1627 * 1628 * @see #setId(int) 1629 * @see #getId() 1630 */ 1631 @ViewDebug.ExportedProperty(resolveId = true) 1632 int mID = NO_ID; 1633 1634 /** 1635 * The stable ID of this view for accessibility purposes. 1636 */ 1637 int mAccessibilityViewId = NO_ID; 1638 1639 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1640 1641 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1642 1643 /** 1644 * The view's tag. 1645 * {@hide} 1646 * 1647 * @see #setTag(Object) 1648 * @see #getTag() 1649 */ 1650 protected Object mTag = null; 1651 1652 // for mPrivateFlags: 1653 /** {@hide} */ 1654 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1655 /** {@hide} */ 1656 static final int PFLAG_FOCUSED = 0x00000002; 1657 /** {@hide} */ 1658 static final int PFLAG_SELECTED = 0x00000004; 1659 /** {@hide} */ 1660 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1661 /** {@hide} */ 1662 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1663 /** {@hide} */ 1664 static final int PFLAG_DRAWN = 0x00000020; 1665 /** 1666 * When this flag is set, this view is running an animation on behalf of its 1667 * children and should therefore not cancel invalidate requests, even if they 1668 * lie outside of this view's bounds. 1669 * 1670 * {@hide} 1671 */ 1672 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1673 /** {@hide} */ 1674 static final int PFLAG_SKIP_DRAW = 0x00000080; 1675 /** {@hide} */ 1676 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1677 /** {@hide} */ 1678 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1679 /** {@hide} */ 1680 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1681 /** {@hide} */ 1682 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1683 /** {@hide} */ 1684 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1685 /** {@hide} */ 1686 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1687 1688 private static final int PFLAG_PRESSED = 0x00004000; 1689 1690 /** {@hide} */ 1691 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1692 /** 1693 * Flag used to indicate that this view should be drawn once more (and only once 1694 * more) after its animation has completed. 1695 * {@hide} 1696 */ 1697 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1698 1699 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1700 1701 /** 1702 * Indicates that the View returned true when onSetAlpha() was called and that 1703 * the alpha must be restored. 1704 * {@hide} 1705 */ 1706 static final int PFLAG_ALPHA_SET = 0x00040000; 1707 1708 /** 1709 * Set by {@link #setScrollContainer(boolean)}. 1710 */ 1711 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1712 1713 /** 1714 * Set by {@link #setScrollContainer(boolean)}. 1715 */ 1716 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1717 1718 /** 1719 * View flag indicating whether this view was invalidated (fully or partially.) 1720 * 1721 * @hide 1722 */ 1723 static final int PFLAG_DIRTY = 0x00200000; 1724 1725 /** 1726 * View flag indicating whether this view was invalidated by an opaque 1727 * invalidate request. 1728 * 1729 * @hide 1730 */ 1731 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1732 1733 /** 1734 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1735 * 1736 * @hide 1737 */ 1738 static final int PFLAG_DIRTY_MASK = 0x00600000; 1739 1740 /** 1741 * Indicates whether the background is opaque. 1742 * 1743 * @hide 1744 */ 1745 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1746 1747 /** 1748 * Indicates whether the scrollbars are opaque. 1749 * 1750 * @hide 1751 */ 1752 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1753 1754 /** 1755 * Indicates whether the view is opaque. 1756 * 1757 * @hide 1758 */ 1759 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1760 1761 /** 1762 * Indicates a prepressed state; 1763 * the short time between ACTION_DOWN and recognizing 1764 * a 'real' press. Prepressed is used to recognize quick taps 1765 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1766 * 1767 * @hide 1768 */ 1769 private static final int PFLAG_PREPRESSED = 0x02000000; 1770 1771 /** 1772 * Indicates whether the view is temporarily detached. 1773 * 1774 * @hide 1775 */ 1776 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1777 1778 /** 1779 * Indicates that we should awaken scroll bars once attached 1780 * 1781 * @hide 1782 */ 1783 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1784 1785 /** 1786 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1787 * @hide 1788 */ 1789 private static final int PFLAG_HOVERED = 0x10000000; 1790 1791 /** 1792 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1793 * for transform operations 1794 * 1795 * @hide 1796 */ 1797 private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000; 1798 1799 /** {@hide} */ 1800 static final int PFLAG_ACTIVATED = 0x40000000; 1801 1802 /** 1803 * Indicates that this view was specifically invalidated, not just dirtied because some 1804 * child view was invalidated. The flag is used to determine when we need to recreate 1805 * a view's display list (as opposed to just returning a reference to its existing 1806 * display list). 1807 * 1808 * @hide 1809 */ 1810 static final int PFLAG_INVALIDATED = 0x80000000; 1811 1812 /** 1813 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1814 * 1815 * |-------|-------|-------|-------| 1816 * 1 PFLAG2_DRAG_CAN_ACCEPT 1817 * 1 PFLAG2_DRAG_HOVERED 1818 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1819 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1820 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1821 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1822 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1823 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1824 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1825 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1826 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1827 * 111 PFLAG2_TEXT_DIRECTION_MASK 1828 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1829 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1830 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1831 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1832 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1833 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1834 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1835 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1836 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1837 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1838 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1839 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1840 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1841 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1842 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1843 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1844 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1845 * 1 PFLAG2_VIEW_QUICK_REJECTED 1846 * 1 PFLAG2_PADDING_RESOLVED 1847 * 1 PFLAG2_DRAWABLE_RESOLVED 1848 * 1 PFLAG2_HAS_TRANSIENT_STATE 1849 * |-------|-------|-------|-------| 1850 */ 1851 1852 /** 1853 * Indicates that this view has reported that it can accept the current drag's content. 1854 * Cleared when the drag operation concludes. 1855 * @hide 1856 */ 1857 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1858 1859 /** 1860 * Indicates that this view is currently directly under the drag location in a 1861 * drag-and-drop operation involving content that it can accept. Cleared when 1862 * the drag exits the view, or when the drag operation concludes. 1863 * @hide 1864 */ 1865 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1866 1867 /** @hide */ 1868 @IntDef({ 1869 LAYOUT_DIRECTION_LTR, 1870 LAYOUT_DIRECTION_RTL, 1871 LAYOUT_DIRECTION_INHERIT, 1872 LAYOUT_DIRECTION_LOCALE 1873 }) 1874 @Retention(RetentionPolicy.SOURCE) 1875 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1876 public @interface LayoutDir {} 1877 1878 /** @hide */ 1879 @IntDef({ 1880 LAYOUT_DIRECTION_LTR, 1881 LAYOUT_DIRECTION_RTL 1882 }) 1883 @Retention(RetentionPolicy.SOURCE) 1884 public @interface ResolvedLayoutDir {} 1885 1886 /** 1887 * Horizontal layout direction of this view is from Left to Right. 1888 * Use with {@link #setLayoutDirection}. 1889 */ 1890 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1891 1892 /** 1893 * Horizontal layout direction of this view is from Right to Left. 1894 * Use with {@link #setLayoutDirection}. 1895 */ 1896 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1897 1898 /** 1899 * Horizontal layout direction of this view is inherited from its parent. 1900 * Use with {@link #setLayoutDirection}. 1901 */ 1902 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1903 1904 /** 1905 * Horizontal layout direction of this view is from deduced from the default language 1906 * script for the locale. Use with {@link #setLayoutDirection}. 1907 */ 1908 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1909 1910 /** 1911 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1912 * @hide 1913 */ 1914 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1915 1916 /** 1917 * Mask for use with private flags indicating bits used for horizontal layout direction. 1918 * @hide 1919 */ 1920 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1921 1922 /** 1923 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1924 * right-to-left direction. 1925 * @hide 1926 */ 1927 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1928 1929 /** 1930 * Indicates whether the view horizontal layout direction has been resolved. 1931 * @hide 1932 */ 1933 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1934 1935 /** 1936 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1937 * @hide 1938 */ 1939 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1940 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1941 1942 /* 1943 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1944 * flag value. 1945 * @hide 1946 */ 1947 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1948 LAYOUT_DIRECTION_LTR, 1949 LAYOUT_DIRECTION_RTL, 1950 LAYOUT_DIRECTION_INHERIT, 1951 LAYOUT_DIRECTION_LOCALE 1952 }; 1953 1954 /** 1955 * Default horizontal layout direction. 1956 */ 1957 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1958 1959 /** 1960 * Default horizontal layout direction. 1961 * @hide 1962 */ 1963 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1964 1965 /** 1966 * Text direction is inherited thru {@link ViewGroup} 1967 */ 1968 public static final int TEXT_DIRECTION_INHERIT = 0; 1969 1970 /** 1971 * Text direction is using "first strong algorithm". The first strong directional character 1972 * determines the paragraph direction. If there is no strong directional character, the 1973 * paragraph direction is the view's resolved layout direction. 1974 */ 1975 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1976 1977 /** 1978 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1979 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1980 * If there are neither, the paragraph direction is the view's resolved layout direction. 1981 */ 1982 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1983 1984 /** 1985 * Text direction is forced to LTR. 1986 */ 1987 public static final int TEXT_DIRECTION_LTR = 3; 1988 1989 /** 1990 * Text direction is forced to RTL. 1991 */ 1992 public static final int TEXT_DIRECTION_RTL = 4; 1993 1994 /** 1995 * Text direction is coming from the system Locale. 1996 */ 1997 public static final int TEXT_DIRECTION_LOCALE = 5; 1998 1999 /** 2000 * Default text direction is inherited 2001 */ 2002 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2003 2004 /** 2005 * Default resolved text direction 2006 * @hide 2007 */ 2008 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2009 2010 /** 2011 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2012 * @hide 2013 */ 2014 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2015 2016 /** 2017 * Mask for use with private flags indicating bits used for text direction. 2018 * @hide 2019 */ 2020 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2021 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2022 2023 /** 2024 * Array of text direction flags for mapping attribute "textDirection" to correct 2025 * flag value. 2026 * @hide 2027 */ 2028 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2029 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2030 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2031 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2032 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2033 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2034 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2035 }; 2036 2037 /** 2038 * Indicates whether the view text direction has been resolved. 2039 * @hide 2040 */ 2041 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2042 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2043 2044 /** 2045 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2046 * @hide 2047 */ 2048 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2049 2050 /** 2051 * Mask for use with private flags indicating bits used for resolved text direction. 2052 * @hide 2053 */ 2054 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2055 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2056 2057 /** 2058 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2059 * @hide 2060 */ 2061 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2062 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2063 2064 /** @hide */ 2065 @IntDef({ 2066 TEXT_ALIGNMENT_INHERIT, 2067 TEXT_ALIGNMENT_GRAVITY, 2068 TEXT_ALIGNMENT_CENTER, 2069 TEXT_ALIGNMENT_TEXT_START, 2070 TEXT_ALIGNMENT_TEXT_END, 2071 TEXT_ALIGNMENT_VIEW_START, 2072 TEXT_ALIGNMENT_VIEW_END 2073 }) 2074 @Retention(RetentionPolicy.SOURCE) 2075 public @interface TextAlignment {} 2076 2077 /** 2078 * Default text alignment. The text alignment of this View is inherited from its parent. 2079 * Use with {@link #setTextAlignment(int)} 2080 */ 2081 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2082 2083 /** 2084 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2085 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2086 * 2087 * Use with {@link #setTextAlignment(int)} 2088 */ 2089 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2090 2091 /** 2092 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2093 * 2094 * Use with {@link #setTextAlignment(int)} 2095 */ 2096 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2097 2098 /** 2099 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2100 * 2101 * Use with {@link #setTextAlignment(int)} 2102 */ 2103 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2104 2105 /** 2106 * Center the paragraph, e.g. ALIGN_CENTER. 2107 * 2108 * Use with {@link #setTextAlignment(int)} 2109 */ 2110 public static final int TEXT_ALIGNMENT_CENTER = 4; 2111 2112 /** 2113 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2114 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2115 * 2116 * Use with {@link #setTextAlignment(int)} 2117 */ 2118 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2119 2120 /** 2121 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2122 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2123 * 2124 * Use with {@link #setTextAlignment(int)} 2125 */ 2126 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2127 2128 /** 2129 * Default text alignment is inherited 2130 */ 2131 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2132 2133 /** 2134 * Default resolved text alignment 2135 * @hide 2136 */ 2137 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2138 2139 /** 2140 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2141 * @hide 2142 */ 2143 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2144 2145 /** 2146 * Mask for use with private flags indicating bits used for text alignment. 2147 * @hide 2148 */ 2149 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2150 2151 /** 2152 * Array of text direction flags for mapping attribute "textAlignment" to correct 2153 * flag value. 2154 * @hide 2155 */ 2156 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2157 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2158 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2159 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2160 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2161 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2162 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2163 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2164 }; 2165 2166 /** 2167 * Indicates whether the view text alignment has been resolved. 2168 * @hide 2169 */ 2170 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2171 2172 /** 2173 * Bit shift to get the resolved text alignment. 2174 * @hide 2175 */ 2176 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2177 2178 /** 2179 * Mask for use with private flags indicating bits used for text alignment. 2180 * @hide 2181 */ 2182 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2183 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2184 2185 /** 2186 * Indicates whether if the view text alignment has been resolved to gravity 2187 */ 2188 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2189 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2190 2191 // Accessiblity constants for mPrivateFlags2 2192 2193 /** 2194 * Shift for the bits in {@link #mPrivateFlags2} related to the 2195 * "importantForAccessibility" attribute. 2196 */ 2197 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2198 2199 /** 2200 * Automatically determine whether a view is important for accessibility. 2201 */ 2202 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2203 2204 /** 2205 * The view is important for accessibility. 2206 */ 2207 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2208 2209 /** 2210 * The view is not important for accessibility. 2211 */ 2212 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2213 2214 /** 2215 * The view is not important for accessibility, nor are any of its 2216 * descendant views. 2217 */ 2218 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2219 2220 /** 2221 * The default whether the view is important for accessibility. 2222 */ 2223 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2224 2225 /** 2226 * Mask for obtainig the bits which specify how to determine 2227 * whether a view is important for accessibility. 2228 */ 2229 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2230 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2231 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2232 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2233 2234 /** 2235 * Shift for the bits in {@link #mPrivateFlags2} related to the 2236 * "accessibilityLiveRegion" attribute. 2237 */ 2238 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2239 2240 /** 2241 * Live region mode specifying that accessibility services should not 2242 * automatically announce changes to this view. This is the default live 2243 * region mode for most views. 2244 * <p> 2245 * Use with {@link #setAccessibilityLiveRegion(int)}. 2246 */ 2247 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2248 2249 /** 2250 * Live region mode specifying that accessibility services should announce 2251 * changes to this view. 2252 * <p> 2253 * Use with {@link #setAccessibilityLiveRegion(int)}. 2254 */ 2255 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2256 2257 /** 2258 * Live region mode specifying that accessibility services should interrupt 2259 * ongoing speech to immediately announce changes to this view. 2260 * <p> 2261 * Use with {@link #setAccessibilityLiveRegion(int)}. 2262 */ 2263 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2264 2265 /** 2266 * The default whether the view is important for accessibility. 2267 */ 2268 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2269 2270 /** 2271 * Mask for obtaining the bits which specify a view's accessibility live 2272 * region mode. 2273 */ 2274 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2275 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2276 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2277 2278 /** 2279 * Flag indicating whether a view has accessibility focus. 2280 */ 2281 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2282 2283 /** 2284 * Flag whether the accessibility state of the subtree rooted at this view changed. 2285 */ 2286 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2287 2288 /** 2289 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2290 * is used to check whether later changes to the view's transform should invalidate the 2291 * view to force the quickReject test to run again. 2292 */ 2293 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2294 2295 /** 2296 * Flag indicating that start/end padding has been resolved into left/right padding 2297 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2298 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2299 * during measurement. In some special cases this is required such as when an adapter-based 2300 * view measures prospective children without attaching them to a window. 2301 */ 2302 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2303 2304 /** 2305 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2306 */ 2307 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2308 2309 /** 2310 * Indicates that the view is tracking some sort of transient state 2311 * that the app should not need to be aware of, but that the framework 2312 * should take special care to preserve. 2313 */ 2314 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2315 2316 /** 2317 * Group of bits indicating that RTL properties resolution is done. 2318 */ 2319 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2320 PFLAG2_TEXT_DIRECTION_RESOLVED | 2321 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2322 PFLAG2_PADDING_RESOLVED | 2323 PFLAG2_DRAWABLE_RESOLVED; 2324 2325 // There are a couple of flags left in mPrivateFlags2 2326 2327 /* End of masks for mPrivateFlags2 */ 2328 2329 /** 2330 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2331 * 2332 * |-------|-------|-------|-------| 2333 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2334 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2335 * 1 PFLAG3_IS_LAID_OUT 2336 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2337 * 1 PFLAG3_CALLED_SUPER 2338 * 1 PFLAG3_PROJECT_BACKGROUND 2339 * |-------|-------|-------|-------| 2340 */ 2341 2342 /** 2343 * Flag indicating that view has a transform animation set on it. This is used to track whether 2344 * an animation is cleared between successive frames, in order to tell the associated 2345 * DisplayList to clear its animation matrix. 2346 */ 2347 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2348 2349 /** 2350 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2351 * animation is cleared between successive frames, in order to tell the associated 2352 * DisplayList to restore its alpha value. 2353 */ 2354 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2355 2356 /** 2357 * Flag indicating that the view has been through at least one layout since it 2358 * was last attached to a window. 2359 */ 2360 static final int PFLAG3_IS_LAID_OUT = 0x4; 2361 2362 /** 2363 * Flag indicating that a call to measure() was skipped and should be done 2364 * instead when layout() is invoked. 2365 */ 2366 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2367 2368 /** 2369 * Flag indicating that an overridden method correctly called down to 2370 * the superclass implementation as required by the API spec. 2371 */ 2372 static final int PFLAG3_CALLED_SUPER = 0x10; 2373 2374 /** 2375 * Flag indicating that the background of this view will be drawn into a 2376 * display list and projected onto the closest parent projection surface. 2377 */ 2378 static final int PFLAG3_PROJECT_BACKGROUND = 0x20; 2379 2380 /* End of masks for mPrivateFlags3 */ 2381 2382 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2383 2384 /** 2385 * Always allow a user to over-scroll this view, provided it is a 2386 * view that can scroll. 2387 * 2388 * @see #getOverScrollMode() 2389 * @see #setOverScrollMode(int) 2390 */ 2391 public static final int OVER_SCROLL_ALWAYS = 0; 2392 2393 /** 2394 * Allow a user to over-scroll this view only if the content is large 2395 * enough to meaningfully scroll, provided it is a view that can scroll. 2396 * 2397 * @see #getOverScrollMode() 2398 * @see #setOverScrollMode(int) 2399 */ 2400 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2401 2402 /** 2403 * Never allow a user to over-scroll this view. 2404 * 2405 * @see #getOverScrollMode() 2406 * @see #setOverScrollMode(int) 2407 */ 2408 public static final int OVER_SCROLL_NEVER = 2; 2409 2410 /** 2411 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2412 * requested the system UI (status bar) to be visible (the default). 2413 * 2414 * @see #setSystemUiVisibility(int) 2415 */ 2416 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2417 2418 /** 2419 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2420 * system UI to enter an unobtrusive "low profile" mode. 2421 * 2422 * <p>This is for use in games, book readers, video players, or any other 2423 * "immersive" application where the usual system chrome is deemed too distracting. 2424 * 2425 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2426 * 2427 * @see #setSystemUiVisibility(int) 2428 */ 2429 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2430 2431 /** 2432 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2433 * system navigation be temporarily hidden. 2434 * 2435 * <p>This is an even less obtrusive state than that called for by 2436 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2437 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2438 * those to disappear. This is useful (in conjunction with the 2439 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2440 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2441 * window flags) for displaying content using every last pixel on the display. 2442 * 2443 * <p>There is a limitation: because navigation controls are so important, the least user 2444 * interaction will cause them to reappear immediately. When this happens, both 2445 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2446 * so that both elements reappear at the same time. 2447 * 2448 * @see #setSystemUiVisibility(int) 2449 */ 2450 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2451 2452 /** 2453 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2454 * into the normal fullscreen mode so that its content can take over the screen 2455 * while still allowing the user to interact with the application. 2456 * 2457 * <p>This has the same visual effect as 2458 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2459 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2460 * meaning that non-critical screen decorations (such as the status bar) will be 2461 * hidden while the user is in the View's window, focusing the experience on 2462 * that content. Unlike the window flag, if you are using ActionBar in 2463 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2464 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2465 * hide the action bar. 2466 * 2467 * <p>This approach to going fullscreen is best used over the window flag when 2468 * it is a transient state -- that is, the application does this at certain 2469 * points in its user interaction where it wants to allow the user to focus 2470 * on content, but not as a continuous state. For situations where the application 2471 * would like to simply stay full screen the entire time (such as a game that 2472 * wants to take over the screen), the 2473 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2474 * is usually a better approach. The state set here will be removed by the system 2475 * in various situations (such as the user moving to another application) like 2476 * the other system UI states. 2477 * 2478 * <p>When using this flag, the application should provide some easy facility 2479 * for the user to go out of it. A common example would be in an e-book 2480 * reader, where tapping on the screen brings back whatever screen and UI 2481 * decorations that had been hidden while the user was immersed in reading 2482 * the book. 2483 * 2484 * @see #setSystemUiVisibility(int) 2485 */ 2486 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2487 2488 /** 2489 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2490 * flags, we would like a stable view of the content insets given to 2491 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2492 * will always represent the worst case that the application can expect 2493 * as a continuous state. In the stock Android UI this is the space for 2494 * the system bar, nav bar, and status bar, but not more transient elements 2495 * such as an input method. 2496 * 2497 * The stable layout your UI sees is based on the system UI modes you can 2498 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2499 * then you will get a stable layout for changes of the 2500 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2501 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2502 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2503 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2504 * with a stable layout. (Note that you should avoid using 2505 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2506 * 2507 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2508 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2509 * then a hidden status bar will be considered a "stable" state for purposes 2510 * here. This allows your UI to continually hide the status bar, while still 2511 * using the system UI flags to hide the action bar while still retaining 2512 * a stable layout. Note that changing the window fullscreen flag will never 2513 * provide a stable layout for a clean transition. 2514 * 2515 * <p>If you are using ActionBar in 2516 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2517 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2518 * insets it adds to those given to the application. 2519 */ 2520 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2521 2522 /** 2523 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2524 * to be layed out as if it has requested 2525 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2526 * allows it to avoid artifacts when switching in and out of that mode, at 2527 * the expense that some of its user interface may be covered by screen 2528 * decorations when they are shown. You can perform layout of your inner 2529 * UI elements to account for the navigation system UI through the 2530 * {@link #fitSystemWindows(Rect)} method. 2531 */ 2532 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2533 2534 /** 2535 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2536 * to be layed out as if it has requested 2537 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2538 * allows it to avoid artifacts when switching in and out of that mode, at 2539 * the expense that some of its user interface may be covered by screen 2540 * decorations when they are shown. You can perform layout of your inner 2541 * UI elements to account for non-fullscreen system UI through the 2542 * {@link #fitSystemWindows(Rect)} method. 2543 */ 2544 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2545 2546 /** 2547 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2548 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2549 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2550 * user interaction. 2551 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2552 * has an effect when used in combination with that flag.</p> 2553 */ 2554 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2555 2556 /** 2557 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2558 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2559 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2560 * experience while also hiding the system bars. If this flag is not set, 2561 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2562 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2563 * if the user swipes from the top of the screen. 2564 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2565 * system gestures, such as swiping from the top of the screen. These transient system bars 2566 * will overlay app’s content, may have some degree of transparency, and will automatically 2567 * hide after a short timeout. 2568 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2569 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2570 * with one or both of those flags.</p> 2571 */ 2572 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2573 2574 /** 2575 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2576 */ 2577 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2578 2579 /** 2580 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2581 */ 2582 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2583 2584 /** 2585 * @hide 2586 * 2587 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2588 * out of the public fields to keep the undefined bits out of the developer's way. 2589 * 2590 * Flag to make the status bar not expandable. Unless you also 2591 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2592 */ 2593 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2594 2595 /** 2596 * @hide 2597 * 2598 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2599 * out of the public fields to keep the undefined bits out of the developer's way. 2600 * 2601 * Flag to hide notification icons and scrolling ticker text. 2602 */ 2603 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2604 2605 /** 2606 * @hide 2607 * 2608 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2609 * out of the public fields to keep the undefined bits out of the developer's way. 2610 * 2611 * Flag to disable incoming notification alerts. This will not block 2612 * icons, but it will block sound, vibrating and other visual or aural notifications. 2613 */ 2614 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2615 2616 /** 2617 * @hide 2618 * 2619 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2620 * out of the public fields to keep the undefined bits out of the developer's way. 2621 * 2622 * Flag to hide only the scrolling ticker. Note that 2623 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2624 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2625 */ 2626 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2627 2628 /** 2629 * @hide 2630 * 2631 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2632 * out of the public fields to keep the undefined bits out of the developer's way. 2633 * 2634 * Flag to hide the center system info area. 2635 */ 2636 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2637 2638 /** 2639 * @hide 2640 * 2641 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2642 * out of the public fields to keep the undefined bits out of the developer's way. 2643 * 2644 * Flag to hide only the home button. Don't use this 2645 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2646 */ 2647 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2648 2649 /** 2650 * @hide 2651 * 2652 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2653 * out of the public fields to keep the undefined bits out of the developer's way. 2654 * 2655 * Flag to hide only the back button. Don't use this 2656 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2657 */ 2658 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2659 2660 /** 2661 * @hide 2662 * 2663 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2664 * out of the public fields to keep the undefined bits out of the developer's way. 2665 * 2666 * Flag to hide only the clock. You might use this if your activity has 2667 * its own clock making the status bar's clock redundant. 2668 */ 2669 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2670 2671 /** 2672 * @hide 2673 * 2674 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2675 * out of the public fields to keep the undefined bits out of the developer's way. 2676 * 2677 * Flag to hide only the recent apps button. Don't use this 2678 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2679 */ 2680 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2681 2682 /** 2683 * @hide 2684 * 2685 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2686 * out of the public fields to keep the undefined bits out of the developer's way. 2687 * 2688 * Flag to disable the global search gesture. Don't use this 2689 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2690 */ 2691 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2692 2693 /** 2694 * @hide 2695 * 2696 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2697 * out of the public fields to keep the undefined bits out of the developer's way. 2698 * 2699 * Flag to specify that the status bar is displayed in transient mode. 2700 */ 2701 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2702 2703 /** 2704 * @hide 2705 * 2706 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2707 * out of the public fields to keep the undefined bits out of the developer's way. 2708 * 2709 * Flag to specify that the navigation bar is displayed in transient mode. 2710 */ 2711 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2712 2713 /** 2714 * @hide 2715 * 2716 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2717 * out of the public fields to keep the undefined bits out of the developer's way. 2718 * 2719 * Flag to specify that the hidden status bar would like to be shown. 2720 */ 2721 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2722 2723 /** 2724 * @hide 2725 * 2726 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2727 * out of the public fields to keep the undefined bits out of the developer's way. 2728 * 2729 * Flag to specify that the hidden navigation bar would like to be shown. 2730 */ 2731 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2732 2733 /** 2734 * @hide 2735 * 2736 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2737 * out of the public fields to keep the undefined bits out of the developer's way. 2738 * 2739 * Flag to specify that the status bar is displayed in translucent mode. 2740 */ 2741 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2742 2743 /** 2744 * @hide 2745 * 2746 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2747 * out of the public fields to keep the undefined bits out of the developer's way. 2748 * 2749 * Flag to specify that the navigation bar is displayed in translucent mode. 2750 */ 2751 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2752 2753 /** 2754 * @hide 2755 */ 2756 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2757 2758 /** 2759 * These are the system UI flags that can be cleared by events outside 2760 * of an application. Currently this is just the ability to tap on the 2761 * screen while hiding the navigation bar to have it return. 2762 * @hide 2763 */ 2764 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2765 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2766 | SYSTEM_UI_FLAG_FULLSCREEN; 2767 2768 /** 2769 * Flags that can impact the layout in relation to system UI. 2770 */ 2771 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2772 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2773 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2774 2775 /** @hide */ 2776 @IntDef(flag = true, 2777 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2778 @Retention(RetentionPolicy.SOURCE) 2779 public @interface FindViewFlags {} 2780 2781 /** 2782 * Find views that render the specified text. 2783 * 2784 * @see #findViewsWithText(ArrayList, CharSequence, int) 2785 */ 2786 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2787 2788 /** 2789 * Find find views that contain the specified content description. 2790 * 2791 * @see #findViewsWithText(ArrayList, CharSequence, int) 2792 */ 2793 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2794 2795 /** 2796 * Find views that contain {@link AccessibilityNodeProvider}. Such 2797 * a View is a root of virtual view hierarchy and may contain the searched 2798 * text. If this flag is set Views with providers are automatically 2799 * added and it is a responsibility of the client to call the APIs of 2800 * the provider to determine whether the virtual tree rooted at this View 2801 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2802 * representing the virtual views with this text. 2803 * 2804 * @see #findViewsWithText(ArrayList, CharSequence, int) 2805 * 2806 * @hide 2807 */ 2808 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2809 2810 /** 2811 * The undefined cursor position. 2812 * 2813 * @hide 2814 */ 2815 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2816 2817 /** 2818 * Indicates that the screen has changed state and is now off. 2819 * 2820 * @see #onScreenStateChanged(int) 2821 */ 2822 public static final int SCREEN_STATE_OFF = 0x0; 2823 2824 /** 2825 * Indicates that the screen has changed state and is now on. 2826 * 2827 * @see #onScreenStateChanged(int) 2828 */ 2829 public static final int SCREEN_STATE_ON = 0x1; 2830 2831 /** 2832 * Controls the over-scroll mode for this view. 2833 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2834 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2835 * and {@link #OVER_SCROLL_NEVER}. 2836 */ 2837 private int mOverScrollMode; 2838 2839 /** 2840 * The parent this view is attached to. 2841 * {@hide} 2842 * 2843 * @see #getParent() 2844 */ 2845 protected ViewParent mParent; 2846 2847 /** 2848 * {@hide} 2849 */ 2850 AttachInfo mAttachInfo; 2851 2852 /** 2853 * {@hide} 2854 */ 2855 @ViewDebug.ExportedProperty(flagMapping = { 2856 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2857 name = "FORCE_LAYOUT"), 2858 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2859 name = "LAYOUT_REQUIRED"), 2860 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2861 name = "DRAWING_CACHE_INVALID", outputIf = false), 2862 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2863 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2864 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2865 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2866 }) 2867 int mPrivateFlags; 2868 int mPrivateFlags2; 2869 int mPrivateFlags3; 2870 2871 /** 2872 * This view's request for the visibility of the status bar. 2873 * @hide 2874 */ 2875 @ViewDebug.ExportedProperty(flagMapping = { 2876 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2877 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2878 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2879 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2880 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2881 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2882 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2883 equals = SYSTEM_UI_FLAG_VISIBLE, 2884 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2885 }) 2886 int mSystemUiVisibility; 2887 2888 /** 2889 * Reference count for transient state. 2890 * @see #setHasTransientState(boolean) 2891 */ 2892 int mTransientStateCount = 0; 2893 2894 /** 2895 * Count of how many windows this view has been attached to. 2896 */ 2897 int mWindowAttachCount; 2898 2899 /** 2900 * The layout parameters associated with this view and used by the parent 2901 * {@link android.view.ViewGroup} to determine how this view should be 2902 * laid out. 2903 * {@hide} 2904 */ 2905 protected ViewGroup.LayoutParams mLayoutParams; 2906 2907 /** 2908 * The view flags hold various views states. 2909 * {@hide} 2910 */ 2911 @ViewDebug.ExportedProperty 2912 int mViewFlags; 2913 2914 static class TransformationInfo { 2915 /** 2916 * The transform matrix for the View. This transform is calculated internally 2917 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2918 * is used by default. Do *not* use this variable directly; instead call 2919 * getMatrix(), which will automatically recalculate the matrix if necessary 2920 * to get the correct matrix based on the latest rotation and scale properties. 2921 */ 2922 private final Matrix mMatrix = new Matrix(); 2923 2924 /** 2925 * The transform matrix for the View. This transform is calculated internally 2926 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2927 * is used by default. Do *not* use this variable directly; instead call 2928 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2929 * to get the correct matrix based on the latest rotation and scale properties. 2930 */ 2931 private Matrix mInverseMatrix; 2932 2933 /** 2934 * An internal variable that tracks whether we need to recalculate the 2935 * transform matrix, based on whether the rotation or scaleX/Y properties 2936 * have changed since the matrix was last calculated. 2937 */ 2938 boolean mMatrixDirty = false; 2939 2940 /** 2941 * An internal variable that tracks whether we need to recalculate the 2942 * transform matrix, based on whether the rotation or scaleX/Y properties 2943 * have changed since the matrix was last calculated. 2944 */ 2945 private boolean mInverseMatrixDirty = true; 2946 2947 /** 2948 * A variable that tracks whether we need to recalculate the 2949 * transform matrix, based on whether the rotation or scaleX/Y properties 2950 * have changed since the matrix was last calculated. This variable 2951 * is only valid after a call to updateMatrix() or to a function that 2952 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2953 */ 2954 private boolean mMatrixIsIdentity = true; 2955 2956 /** 2957 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2958 */ 2959 private Camera mCamera = null; 2960 2961 /** 2962 * This matrix is used when computing the matrix for 3D rotations. 2963 */ 2964 private Matrix matrix3D = null; 2965 2966 /** 2967 * These prev values are used to recalculate a centered pivot point when necessary. The 2968 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2969 * set), so thes values are only used then as well. 2970 */ 2971 private int mPrevWidth = -1; 2972 private int mPrevHeight = -1; 2973 2974 /** 2975 * The degrees rotation around the vertical axis through the pivot point. 2976 */ 2977 @ViewDebug.ExportedProperty 2978 float mRotationY = 0f; 2979 2980 /** 2981 * The degrees rotation around the horizontal axis through the pivot point. 2982 */ 2983 @ViewDebug.ExportedProperty 2984 float mRotationX = 0f; 2985 2986 /** 2987 * The degrees rotation around the pivot point. 2988 */ 2989 @ViewDebug.ExportedProperty 2990 float mRotation = 0f; 2991 2992 /** 2993 * The amount of translation of the object away from its left property (post-layout). 2994 */ 2995 @ViewDebug.ExportedProperty 2996 float mTranslationX = 0f; 2997 2998 /** 2999 * The amount of translation of the object away from its top property (post-layout). 3000 */ 3001 @ViewDebug.ExportedProperty 3002 float mTranslationY = 0f; 3003 3004 @ViewDebug.ExportedProperty 3005 float mTranslationZ = 0f; 3006 3007 /** 3008 * The amount of scale in the x direction around the pivot point. A 3009 * value of 1 means no scaling is applied. 3010 */ 3011 @ViewDebug.ExportedProperty 3012 float mScaleX = 1f; 3013 3014 /** 3015 * The amount of scale in the y direction around the pivot point. A 3016 * value of 1 means no scaling is applied. 3017 */ 3018 @ViewDebug.ExportedProperty 3019 float mScaleY = 1f; 3020 3021 /** 3022 * The x location of the point around which the view is rotated and scaled. 3023 */ 3024 @ViewDebug.ExportedProperty 3025 float mPivotX = 0f; 3026 3027 /** 3028 * The y location of the point around which the view is rotated and scaled. 3029 */ 3030 @ViewDebug.ExportedProperty 3031 float mPivotY = 0f; 3032 3033 /** 3034 * The opacity of the View. This is a value from 0 to 1, where 0 means 3035 * completely transparent and 1 means completely opaque. 3036 */ 3037 @ViewDebug.ExportedProperty 3038 float mAlpha = 1f; 3039 3040 /** 3041 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3042 * property only used by transitions, which is composited with the other alpha 3043 * values to calculate the final visual alpha value. 3044 */ 3045 float mTransitionAlpha = 1f; 3046 } 3047 3048 TransformationInfo mTransformationInfo; 3049 3050 /** 3051 * Current clip bounds. to which all drawing of this view are constrained. 3052 */ 3053 private Rect mClipBounds = null; 3054 3055 private boolean mLastIsOpaque; 3056 3057 /** 3058 * Convenience value to check for float values that are close enough to zero to be considered 3059 * zero. 3060 */ 3061 private static final float NONZERO_EPSILON = .001f; 3062 3063 /** 3064 * The distance in pixels from the left edge of this view's parent 3065 * to the left edge of this view. 3066 * {@hide} 3067 */ 3068 @ViewDebug.ExportedProperty(category = "layout") 3069 protected int mLeft; 3070 /** 3071 * The distance in pixels from the left edge of this view's parent 3072 * to the right edge of this view. 3073 * {@hide} 3074 */ 3075 @ViewDebug.ExportedProperty(category = "layout") 3076 protected int mRight; 3077 /** 3078 * The distance in pixels from the top edge of this view's parent 3079 * to the top edge of this view. 3080 * {@hide} 3081 */ 3082 @ViewDebug.ExportedProperty(category = "layout") 3083 protected int mTop; 3084 /** 3085 * The distance in pixels from the top edge of this view's parent 3086 * to the bottom edge of this view. 3087 * {@hide} 3088 */ 3089 @ViewDebug.ExportedProperty(category = "layout") 3090 protected int mBottom; 3091 3092 /** 3093 * The offset, in pixels, by which the content of this view is scrolled 3094 * horizontally. 3095 * {@hide} 3096 */ 3097 @ViewDebug.ExportedProperty(category = "scrolling") 3098 protected int mScrollX; 3099 /** 3100 * The offset, in pixels, by which the content of this view is scrolled 3101 * vertically. 3102 * {@hide} 3103 */ 3104 @ViewDebug.ExportedProperty(category = "scrolling") 3105 protected int mScrollY; 3106 3107 /** 3108 * The left padding in pixels, that is the distance in pixels between the 3109 * left edge of this view and the left edge of its content. 3110 * {@hide} 3111 */ 3112 @ViewDebug.ExportedProperty(category = "padding") 3113 protected int mPaddingLeft = 0; 3114 /** 3115 * The right padding in pixels, that is the distance in pixels between the 3116 * right edge of this view and the right edge of its content. 3117 * {@hide} 3118 */ 3119 @ViewDebug.ExportedProperty(category = "padding") 3120 protected int mPaddingRight = 0; 3121 /** 3122 * The top padding in pixels, that is the distance in pixels between the 3123 * top edge of this view and the top edge of its content. 3124 * {@hide} 3125 */ 3126 @ViewDebug.ExportedProperty(category = "padding") 3127 protected int mPaddingTop; 3128 /** 3129 * The bottom padding in pixels, that is the distance in pixels between the 3130 * bottom edge of this view and the bottom edge of its content. 3131 * {@hide} 3132 */ 3133 @ViewDebug.ExportedProperty(category = "padding") 3134 protected int mPaddingBottom; 3135 3136 /** 3137 * The layout insets in pixels, that is the distance in pixels between the 3138 * visible edges of this view its bounds. 3139 */ 3140 private Insets mLayoutInsets; 3141 3142 /** 3143 * Briefly describes the view and is primarily used for accessibility support. 3144 */ 3145 private CharSequence mContentDescription; 3146 3147 /** 3148 * Specifies the id of a view for which this view serves as a label for 3149 * accessibility purposes. 3150 */ 3151 private int mLabelForId = View.NO_ID; 3152 3153 /** 3154 * Predicate for matching labeled view id with its label for 3155 * accessibility purposes. 3156 */ 3157 private MatchLabelForPredicate mMatchLabelForPredicate; 3158 3159 /** 3160 * Predicate for matching a view by its id. 3161 */ 3162 private MatchIdPredicate mMatchIdPredicate; 3163 3164 /** 3165 * Cache the paddingRight set by the user to append to the scrollbar's size. 3166 * 3167 * @hide 3168 */ 3169 @ViewDebug.ExportedProperty(category = "padding") 3170 protected int mUserPaddingRight; 3171 3172 /** 3173 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3174 * 3175 * @hide 3176 */ 3177 @ViewDebug.ExportedProperty(category = "padding") 3178 protected int mUserPaddingBottom; 3179 3180 /** 3181 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3182 * 3183 * @hide 3184 */ 3185 @ViewDebug.ExportedProperty(category = "padding") 3186 protected int mUserPaddingLeft; 3187 3188 /** 3189 * Cache the paddingStart set by the user to append to the scrollbar's size. 3190 * 3191 */ 3192 @ViewDebug.ExportedProperty(category = "padding") 3193 int mUserPaddingStart; 3194 3195 /** 3196 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3197 * 3198 */ 3199 @ViewDebug.ExportedProperty(category = "padding") 3200 int mUserPaddingEnd; 3201 3202 /** 3203 * Cache initial left padding. 3204 * 3205 * @hide 3206 */ 3207 int mUserPaddingLeftInitial; 3208 3209 /** 3210 * Cache initial right padding. 3211 * 3212 * @hide 3213 */ 3214 int mUserPaddingRightInitial; 3215 3216 /** 3217 * Default undefined padding 3218 */ 3219 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3220 3221 /** 3222 * Cache if a left padding has been defined 3223 */ 3224 private boolean mLeftPaddingDefined = false; 3225 3226 /** 3227 * Cache if a right padding has been defined 3228 */ 3229 private boolean mRightPaddingDefined = false; 3230 3231 /** 3232 * @hide 3233 */ 3234 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3235 /** 3236 * @hide 3237 */ 3238 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3239 3240 private LongSparseLongArray mMeasureCache; 3241 3242 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3243 private Drawable mBackground; 3244 3245 /** 3246 * Display list used for backgrounds. 3247 * <p> 3248 * When non-null and valid, this is expected to contain an up-to-date copy 3249 * of the background drawable. It is cleared on temporary detach and reset 3250 * on cleanup. 3251 */ 3252 private DisplayList mBackgroundDisplayList; 3253 3254 private int mBackgroundResource; 3255 private boolean mBackgroundSizeChanged; 3256 3257 static class ListenerInfo { 3258 /** 3259 * Listener used to dispatch focus change events. 3260 * This field should be made private, so it is hidden from the SDK. 3261 * {@hide} 3262 */ 3263 protected OnFocusChangeListener mOnFocusChangeListener; 3264 3265 /** 3266 * Listeners for layout change events. 3267 */ 3268 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3269 3270 /** 3271 * Listeners for attach events. 3272 */ 3273 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3274 3275 /** 3276 * Listener used to dispatch click events. 3277 * This field should be made private, so it is hidden from the SDK. 3278 * {@hide} 3279 */ 3280 public OnClickListener mOnClickListener; 3281 3282 /** 3283 * Listener used to dispatch long click events. 3284 * This field should be made private, so it is hidden from the SDK. 3285 * {@hide} 3286 */ 3287 protected OnLongClickListener mOnLongClickListener; 3288 3289 /** 3290 * Listener used to build the context menu. 3291 * This field should be made private, so it is hidden from the SDK. 3292 * {@hide} 3293 */ 3294 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3295 3296 private OnKeyListener mOnKeyListener; 3297 3298 private OnTouchListener mOnTouchListener; 3299 3300 private OnHoverListener mOnHoverListener; 3301 3302 private OnGenericMotionListener mOnGenericMotionListener; 3303 3304 private OnDragListener mOnDragListener; 3305 3306 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3307 } 3308 3309 ListenerInfo mListenerInfo; 3310 3311 /** 3312 * The application environment this view lives in. 3313 * This field should be made private, so it is hidden from the SDK. 3314 * {@hide} 3315 */ 3316 protected Context mContext; 3317 3318 private final Resources mResources; 3319 3320 private ScrollabilityCache mScrollCache; 3321 3322 private int[] mDrawableState = null; 3323 3324 /** 3325 * Stores the outline of the view, passed down to the DisplayList level for shadow shape. 3326 */ 3327 private Path mOutline; 3328 3329 /** 3330 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3331 * the user may specify which view to go to next. 3332 */ 3333 private int mNextFocusLeftId = View.NO_ID; 3334 3335 /** 3336 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3337 * the user may specify which view to go to next. 3338 */ 3339 private int mNextFocusRightId = View.NO_ID; 3340 3341 /** 3342 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3343 * the user may specify which view to go to next. 3344 */ 3345 private int mNextFocusUpId = View.NO_ID; 3346 3347 /** 3348 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3349 * the user may specify which view to go to next. 3350 */ 3351 private int mNextFocusDownId = View.NO_ID; 3352 3353 /** 3354 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3355 * the user may specify which view to go to next. 3356 */ 3357 int mNextFocusForwardId = View.NO_ID; 3358 3359 private CheckForLongPress mPendingCheckForLongPress; 3360 private CheckForTap mPendingCheckForTap = null; 3361 private PerformClick mPerformClick; 3362 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3363 3364 private UnsetPressedState mUnsetPressedState; 3365 3366 /** 3367 * Whether the long press's action has been invoked. The tap's action is invoked on the 3368 * up event while a long press is invoked as soon as the long press duration is reached, so 3369 * a long press could be performed before the tap is checked, in which case the tap's action 3370 * should not be invoked. 3371 */ 3372 private boolean mHasPerformedLongPress; 3373 3374 /** 3375 * The minimum height of the view. We'll try our best to have the height 3376 * of this view to at least this amount. 3377 */ 3378 @ViewDebug.ExportedProperty(category = "measurement") 3379 private int mMinHeight; 3380 3381 /** 3382 * The minimum width of the view. We'll try our best to have the width 3383 * of this view to at least this amount. 3384 */ 3385 @ViewDebug.ExportedProperty(category = "measurement") 3386 private int mMinWidth; 3387 3388 /** 3389 * The delegate to handle touch events that are physically in this view 3390 * but should be handled by another view. 3391 */ 3392 private TouchDelegate mTouchDelegate = null; 3393 3394 /** 3395 * Solid color to use as a background when creating the drawing cache. Enables 3396 * the cache to use 16 bit bitmaps instead of 32 bit. 3397 */ 3398 private int mDrawingCacheBackgroundColor = 0; 3399 3400 /** 3401 * Special tree observer used when mAttachInfo is null. 3402 */ 3403 private ViewTreeObserver mFloatingTreeObserver; 3404 3405 /** 3406 * Cache the touch slop from the context that created the view. 3407 */ 3408 private int mTouchSlop; 3409 3410 /** 3411 * Object that handles automatic animation of view properties. 3412 */ 3413 private ViewPropertyAnimator mAnimator = null; 3414 3415 /** 3416 * Flag indicating that a drag can cross window boundaries. When 3417 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3418 * with this flag set, all visible applications will be able to participate 3419 * in the drag operation and receive the dragged content. 3420 * 3421 * @hide 3422 */ 3423 public static final int DRAG_FLAG_GLOBAL = 1; 3424 3425 /** 3426 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3427 */ 3428 private float mVerticalScrollFactor; 3429 3430 /** 3431 * Position of the vertical scroll bar. 3432 */ 3433 private int mVerticalScrollbarPosition; 3434 3435 /** 3436 * Position the scroll bar at the default position as determined by the system. 3437 */ 3438 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3439 3440 /** 3441 * Position the scroll bar along the left edge. 3442 */ 3443 public static final int SCROLLBAR_POSITION_LEFT = 1; 3444 3445 /** 3446 * Position the scroll bar along the right edge. 3447 */ 3448 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3449 3450 /** 3451 * Indicates that the view does not have a layer. 3452 * 3453 * @see #getLayerType() 3454 * @see #setLayerType(int, android.graphics.Paint) 3455 * @see #LAYER_TYPE_SOFTWARE 3456 * @see #LAYER_TYPE_HARDWARE 3457 */ 3458 public static final int LAYER_TYPE_NONE = 0; 3459 3460 /** 3461 * <p>Indicates that the view has a software layer. A software layer is backed 3462 * by a bitmap and causes the view to be rendered using Android's software 3463 * rendering pipeline, even if hardware acceleration is enabled.</p> 3464 * 3465 * <p>Software layers have various usages:</p> 3466 * <p>When the application is not using hardware acceleration, a software layer 3467 * is useful to apply a specific color filter and/or blending mode and/or 3468 * translucency to a view and all its children.</p> 3469 * <p>When the application is using hardware acceleration, a software layer 3470 * is useful to render drawing primitives not supported by the hardware 3471 * accelerated pipeline. It can also be used to cache a complex view tree 3472 * into a texture and reduce the complexity of drawing operations. For instance, 3473 * when animating a complex view tree with a translation, a software layer can 3474 * be used to render the view tree only once.</p> 3475 * <p>Software layers should be avoided when the affected view tree updates 3476 * often. Every update will require to re-render the software layer, which can 3477 * potentially be slow (particularly when hardware acceleration is turned on 3478 * since the layer will have to be uploaded into a hardware texture after every 3479 * update.)</p> 3480 * 3481 * @see #getLayerType() 3482 * @see #setLayerType(int, android.graphics.Paint) 3483 * @see #LAYER_TYPE_NONE 3484 * @see #LAYER_TYPE_HARDWARE 3485 */ 3486 public static final int LAYER_TYPE_SOFTWARE = 1; 3487 3488 /** 3489 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3490 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3491 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3492 * rendering pipeline, but only if hardware acceleration is turned on for the 3493 * view hierarchy. When hardware acceleration is turned off, hardware layers 3494 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3495 * 3496 * <p>A hardware layer is useful to apply a specific color filter and/or 3497 * blending mode and/or translucency to a view and all its children.</p> 3498 * <p>A hardware layer can be used to cache a complex view tree into a 3499 * texture and reduce the complexity of drawing operations. For instance, 3500 * when animating a complex view tree with a translation, a hardware layer can 3501 * be used to render the view tree only once.</p> 3502 * <p>A hardware layer can also be used to increase the rendering quality when 3503 * rotation transformations are applied on a view. It can also be used to 3504 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3505 * 3506 * @see #getLayerType() 3507 * @see #setLayerType(int, android.graphics.Paint) 3508 * @see #LAYER_TYPE_NONE 3509 * @see #LAYER_TYPE_SOFTWARE 3510 */ 3511 public static final int LAYER_TYPE_HARDWARE = 2; 3512 3513 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3514 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3515 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3516 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3517 }) 3518 int mLayerType = LAYER_TYPE_NONE; 3519 Paint mLayerPaint; 3520 Rect mLocalDirtyRect; 3521 private HardwareLayer mHardwareLayer; 3522 3523 /** 3524 * Set to true when drawing cache is enabled and cannot be created. 3525 * 3526 * @hide 3527 */ 3528 public boolean mCachingFailed; 3529 private Bitmap mDrawingCache; 3530 private Bitmap mUnscaledDrawingCache; 3531 3532 /** 3533 * Display list used for the View content. 3534 * <p> 3535 * When non-null and valid, this is expected to contain an up-to-date copy 3536 * of the View content. It is cleared on temporary detach and reset on 3537 * cleanup. 3538 */ 3539 DisplayList mDisplayList; 3540 3541 /** 3542 * Set to true when the view is sending hover accessibility events because it 3543 * is the innermost hovered view. 3544 */ 3545 private boolean mSendingHoverAccessibilityEvents; 3546 3547 /** 3548 * Delegate for injecting accessibility functionality. 3549 */ 3550 AccessibilityDelegate mAccessibilityDelegate; 3551 3552 /** 3553 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3554 * and add/remove objects to/from the overlay directly through the Overlay methods. 3555 */ 3556 ViewOverlay mOverlay; 3557 3558 /** 3559 * Consistency verifier for debugging purposes. 3560 * @hide 3561 */ 3562 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3563 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3564 new InputEventConsistencyVerifier(this, 0) : null; 3565 3566 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3567 3568 /** 3569 * Simple constructor to use when creating a view from code. 3570 * 3571 * @param context The Context the view is running in, through which it can 3572 * access the current theme, resources, etc. 3573 */ 3574 public View(Context context) { 3575 mContext = context; 3576 mResources = context != null ? context.getResources() : null; 3577 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3578 // Set some flags defaults 3579 mPrivateFlags2 = 3580 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3581 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3582 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3583 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3584 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3585 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3586 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3587 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3588 mUserPaddingStart = UNDEFINED_PADDING; 3589 mUserPaddingEnd = UNDEFINED_PADDING; 3590 3591 if (!sCompatibilityDone && context != null) { 3592 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3593 3594 // Older apps may need this compatibility hack for measurement. 3595 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3596 3597 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3598 // of whether a layout was requested on that View. 3599 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3600 3601 sCompatibilityDone = true; 3602 } 3603 } 3604 3605 /** 3606 * Constructor that is called when inflating a view from XML. This is called 3607 * when a view is being constructed from an XML file, supplying attributes 3608 * that were specified in the XML file. This version uses a default style of 3609 * 0, so the only attribute values applied are those in the Context's Theme 3610 * and the given AttributeSet. 3611 * 3612 * <p> 3613 * The method onFinishInflate() will be called after all children have been 3614 * added. 3615 * 3616 * @param context The Context the view is running in, through which it can 3617 * access the current theme, resources, etc. 3618 * @param attrs The attributes of the XML tag that is inflating the view. 3619 * @see #View(Context, AttributeSet, int) 3620 */ 3621 public View(Context context, AttributeSet attrs) { 3622 this(context, attrs, 0); 3623 } 3624 3625 /** 3626 * Perform inflation from XML and apply a class-specific base style from a 3627 * theme attribute. This constructor of View allows subclasses to use their 3628 * own base style when they are inflating. For example, a Button class's 3629 * constructor would call this version of the super class constructor and 3630 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3631 * allows the theme's button style to modify all of the base view attributes 3632 * (in particular its background) as well as the Button class's attributes. 3633 * 3634 * @param context The Context the view is running in, through which it can 3635 * access the current theme, resources, etc. 3636 * @param attrs The attributes of the XML tag that is inflating the view. 3637 * @param defStyleAttr An attribute in the current theme that contains a 3638 * reference to a style resource that supplies default values for 3639 * the view. Can be 0 to not look for defaults. 3640 * @see #View(Context, AttributeSet) 3641 */ 3642 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3643 this(context, attrs, defStyleAttr, 0); 3644 } 3645 3646 /** 3647 * Perform inflation from XML and apply a class-specific base style from a 3648 * theme attribute or style resource. This constructor of View allows 3649 * subclasses to use their own base style when they are inflating. 3650 * <p> 3651 * When determining the final value of a particular attribute, there are 3652 * four inputs that come into play: 3653 * <ol> 3654 * <li>Any attribute values in the given AttributeSet. 3655 * <li>The style resource specified in the AttributeSet (named "style"). 3656 * <li>The default style specified by <var>defStyleAttr</var>. 3657 * <li>The default style specified by <var>defStyleRes</var>. 3658 * <li>The base values in this theme. 3659 * </ol> 3660 * <p> 3661 * Each of these inputs is considered in-order, with the first listed taking 3662 * precedence over the following ones. In other words, if in the 3663 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3664 * , then the button's text will <em>always</em> be black, regardless of 3665 * what is specified in any of the styles. 3666 * 3667 * @param context The Context the view is running in, through which it can 3668 * access the current theme, resources, etc. 3669 * @param attrs The attributes of the XML tag that is inflating the view. 3670 * @param defStyleAttr An attribute in the current theme that contains a 3671 * reference to a style resource that supplies default values for 3672 * the view. Can be 0 to not look for defaults. 3673 * @param defStyleRes A resource identifier of a style resource that 3674 * supplies default values for the view, used only if 3675 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3676 * to not look for defaults. 3677 * @see #View(Context, AttributeSet, int) 3678 */ 3679 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3680 this(context); 3681 3682 final TypedArray a = context.obtainStyledAttributes( 3683 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3684 3685 Drawable background = null; 3686 3687 int leftPadding = -1; 3688 int topPadding = -1; 3689 int rightPadding = -1; 3690 int bottomPadding = -1; 3691 int startPadding = UNDEFINED_PADDING; 3692 int endPadding = UNDEFINED_PADDING; 3693 3694 int padding = -1; 3695 3696 int viewFlagValues = 0; 3697 int viewFlagMasks = 0; 3698 3699 boolean setScrollContainer = false; 3700 3701 int x = 0; 3702 int y = 0; 3703 3704 float tx = 0; 3705 float ty = 0; 3706 float tz = 0; 3707 float rotation = 0; 3708 float rotationX = 0; 3709 float rotationY = 0; 3710 float sx = 1f; 3711 float sy = 1f; 3712 boolean transformSet = false; 3713 3714 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3715 int overScrollMode = mOverScrollMode; 3716 boolean initializeScrollbars = false; 3717 3718 boolean startPaddingDefined = false; 3719 boolean endPaddingDefined = false; 3720 boolean leftPaddingDefined = false; 3721 boolean rightPaddingDefined = false; 3722 3723 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3724 3725 final int N = a.getIndexCount(); 3726 for (int i = 0; i < N; i++) { 3727 int attr = a.getIndex(i); 3728 switch (attr) { 3729 case com.android.internal.R.styleable.View_background: 3730 background = a.getDrawable(attr); 3731 break; 3732 case com.android.internal.R.styleable.View_padding: 3733 padding = a.getDimensionPixelSize(attr, -1); 3734 mUserPaddingLeftInitial = padding; 3735 mUserPaddingRightInitial = padding; 3736 leftPaddingDefined = true; 3737 rightPaddingDefined = true; 3738 break; 3739 case com.android.internal.R.styleable.View_paddingLeft: 3740 leftPadding = a.getDimensionPixelSize(attr, -1); 3741 mUserPaddingLeftInitial = leftPadding; 3742 leftPaddingDefined = true; 3743 break; 3744 case com.android.internal.R.styleable.View_paddingTop: 3745 topPadding = a.getDimensionPixelSize(attr, -1); 3746 break; 3747 case com.android.internal.R.styleable.View_paddingRight: 3748 rightPadding = a.getDimensionPixelSize(attr, -1); 3749 mUserPaddingRightInitial = rightPadding; 3750 rightPaddingDefined = true; 3751 break; 3752 case com.android.internal.R.styleable.View_paddingBottom: 3753 bottomPadding = a.getDimensionPixelSize(attr, -1); 3754 break; 3755 case com.android.internal.R.styleable.View_paddingStart: 3756 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3757 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3758 break; 3759 case com.android.internal.R.styleable.View_paddingEnd: 3760 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3761 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3762 break; 3763 case com.android.internal.R.styleable.View_scrollX: 3764 x = a.getDimensionPixelOffset(attr, 0); 3765 break; 3766 case com.android.internal.R.styleable.View_scrollY: 3767 y = a.getDimensionPixelOffset(attr, 0); 3768 break; 3769 case com.android.internal.R.styleable.View_alpha: 3770 setAlpha(a.getFloat(attr, 1f)); 3771 break; 3772 case com.android.internal.R.styleable.View_transformPivotX: 3773 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3774 break; 3775 case com.android.internal.R.styleable.View_transformPivotY: 3776 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3777 break; 3778 case com.android.internal.R.styleable.View_translationX: 3779 tx = a.getDimensionPixelOffset(attr, 0); 3780 transformSet = true; 3781 break; 3782 case com.android.internal.R.styleable.View_translationY: 3783 ty = a.getDimensionPixelOffset(attr, 0); 3784 transformSet = true; 3785 break; 3786 case com.android.internal.R.styleable.View_translationZ: 3787 tz = a.getDimensionPixelOffset(attr, 0); 3788 transformSet = true; 3789 break; 3790 case com.android.internal.R.styleable.View_rotation: 3791 rotation = a.getFloat(attr, 0); 3792 transformSet = true; 3793 break; 3794 case com.android.internal.R.styleable.View_rotationX: 3795 rotationX = a.getFloat(attr, 0); 3796 transformSet = true; 3797 break; 3798 case com.android.internal.R.styleable.View_rotationY: 3799 rotationY = a.getFloat(attr, 0); 3800 transformSet = true; 3801 break; 3802 case com.android.internal.R.styleable.View_scaleX: 3803 sx = a.getFloat(attr, 1f); 3804 transformSet = true; 3805 break; 3806 case com.android.internal.R.styleable.View_scaleY: 3807 sy = a.getFloat(attr, 1f); 3808 transformSet = true; 3809 break; 3810 case com.android.internal.R.styleable.View_id: 3811 mID = a.getResourceId(attr, NO_ID); 3812 break; 3813 case com.android.internal.R.styleable.View_tag: 3814 mTag = a.getText(attr); 3815 break; 3816 case com.android.internal.R.styleable.View_fitsSystemWindows: 3817 if (a.getBoolean(attr, false)) { 3818 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3819 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3820 } 3821 break; 3822 case com.android.internal.R.styleable.View_focusable: 3823 if (a.getBoolean(attr, false)) { 3824 viewFlagValues |= FOCUSABLE; 3825 viewFlagMasks |= FOCUSABLE_MASK; 3826 } 3827 break; 3828 case com.android.internal.R.styleable.View_focusableInTouchMode: 3829 if (a.getBoolean(attr, false)) { 3830 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3831 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3832 } 3833 break; 3834 case com.android.internal.R.styleable.View_clickable: 3835 if (a.getBoolean(attr, false)) { 3836 viewFlagValues |= CLICKABLE; 3837 viewFlagMasks |= CLICKABLE; 3838 } 3839 break; 3840 case com.android.internal.R.styleable.View_longClickable: 3841 if (a.getBoolean(attr, false)) { 3842 viewFlagValues |= LONG_CLICKABLE; 3843 viewFlagMasks |= LONG_CLICKABLE; 3844 } 3845 break; 3846 case com.android.internal.R.styleable.View_saveEnabled: 3847 if (!a.getBoolean(attr, true)) { 3848 viewFlagValues |= SAVE_DISABLED; 3849 viewFlagMasks |= SAVE_DISABLED_MASK; 3850 } 3851 break; 3852 case com.android.internal.R.styleable.View_duplicateParentState: 3853 if (a.getBoolean(attr, false)) { 3854 viewFlagValues |= DUPLICATE_PARENT_STATE; 3855 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3856 } 3857 break; 3858 case com.android.internal.R.styleable.View_visibility: 3859 final int visibility = a.getInt(attr, 0); 3860 if (visibility != 0) { 3861 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3862 viewFlagMasks |= VISIBILITY_MASK; 3863 } 3864 break; 3865 case com.android.internal.R.styleable.View_layoutDirection: 3866 // Clear any layout direction flags (included resolved bits) already set 3867 mPrivateFlags2 &= 3868 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3869 // Set the layout direction flags depending on the value of the attribute 3870 final int layoutDirection = a.getInt(attr, -1); 3871 final int value = (layoutDirection != -1) ? 3872 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3873 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3874 break; 3875 case com.android.internal.R.styleable.View_drawingCacheQuality: 3876 final int cacheQuality = a.getInt(attr, 0); 3877 if (cacheQuality != 0) { 3878 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3879 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3880 } 3881 break; 3882 case com.android.internal.R.styleable.View_contentDescription: 3883 setContentDescription(a.getString(attr)); 3884 break; 3885 case com.android.internal.R.styleable.View_labelFor: 3886 setLabelFor(a.getResourceId(attr, NO_ID)); 3887 break; 3888 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3889 if (!a.getBoolean(attr, true)) { 3890 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3891 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3892 } 3893 break; 3894 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3895 if (!a.getBoolean(attr, true)) { 3896 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3897 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3898 } 3899 break; 3900 case R.styleable.View_scrollbars: 3901 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3902 if (scrollbars != SCROLLBARS_NONE) { 3903 viewFlagValues |= scrollbars; 3904 viewFlagMasks |= SCROLLBARS_MASK; 3905 initializeScrollbars = true; 3906 } 3907 break; 3908 //noinspection deprecation 3909 case R.styleable.View_fadingEdge: 3910 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3911 // Ignore the attribute starting with ICS 3912 break; 3913 } 3914 // With builds < ICS, fall through and apply fading edges 3915 case R.styleable.View_requiresFadingEdge: 3916 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3917 if (fadingEdge != FADING_EDGE_NONE) { 3918 viewFlagValues |= fadingEdge; 3919 viewFlagMasks |= FADING_EDGE_MASK; 3920 initializeFadingEdge(a); 3921 } 3922 break; 3923 case R.styleable.View_scrollbarStyle: 3924 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3925 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3926 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3927 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3928 } 3929 break; 3930 case R.styleable.View_isScrollContainer: 3931 setScrollContainer = true; 3932 if (a.getBoolean(attr, false)) { 3933 setScrollContainer(true); 3934 } 3935 break; 3936 case com.android.internal.R.styleable.View_keepScreenOn: 3937 if (a.getBoolean(attr, false)) { 3938 viewFlagValues |= KEEP_SCREEN_ON; 3939 viewFlagMasks |= KEEP_SCREEN_ON; 3940 } 3941 break; 3942 case R.styleable.View_filterTouchesWhenObscured: 3943 if (a.getBoolean(attr, false)) { 3944 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3945 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3946 } 3947 break; 3948 case R.styleable.View_nextFocusLeft: 3949 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3950 break; 3951 case R.styleable.View_nextFocusRight: 3952 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3953 break; 3954 case R.styleable.View_nextFocusUp: 3955 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3956 break; 3957 case R.styleable.View_nextFocusDown: 3958 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3959 break; 3960 case R.styleable.View_nextFocusForward: 3961 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3962 break; 3963 case R.styleable.View_minWidth: 3964 mMinWidth = a.getDimensionPixelSize(attr, 0); 3965 break; 3966 case R.styleable.View_minHeight: 3967 mMinHeight = a.getDimensionPixelSize(attr, 0); 3968 break; 3969 case R.styleable.View_onClick: 3970 if (context.isRestricted()) { 3971 throw new IllegalStateException("The android:onClick attribute cannot " 3972 + "be used within a restricted context"); 3973 } 3974 3975 final String handlerName = a.getString(attr); 3976 if (handlerName != null) { 3977 setOnClickListener(new OnClickListener() { 3978 private Method mHandler; 3979 3980 public void onClick(View v) { 3981 if (mHandler == null) { 3982 try { 3983 mHandler = getContext().getClass().getMethod(handlerName, 3984 View.class); 3985 } catch (NoSuchMethodException e) { 3986 int id = getId(); 3987 String idText = id == NO_ID ? "" : " with id '" 3988 + getContext().getResources().getResourceEntryName( 3989 id) + "'"; 3990 throw new IllegalStateException("Could not find a method " + 3991 handlerName + "(View) in the activity " 3992 + getContext().getClass() + " for onClick handler" 3993 + " on view " + View.this.getClass() + idText, e); 3994 } 3995 } 3996 3997 try { 3998 mHandler.invoke(getContext(), View.this); 3999 } catch (IllegalAccessException e) { 4000 throw new IllegalStateException("Could not execute non " 4001 + "public method of the activity", e); 4002 } catch (InvocationTargetException e) { 4003 throw new IllegalStateException("Could not execute " 4004 + "method of the activity", e); 4005 } 4006 } 4007 }); 4008 } 4009 break; 4010 case R.styleable.View_overScrollMode: 4011 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4012 break; 4013 case R.styleable.View_verticalScrollbarPosition: 4014 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4015 break; 4016 case R.styleable.View_layerType: 4017 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4018 break; 4019 case R.styleable.View_textDirection: 4020 // Clear any text direction flag already set 4021 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4022 // Set the text direction flags depending on the value of the attribute 4023 final int textDirection = a.getInt(attr, -1); 4024 if (textDirection != -1) { 4025 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4026 } 4027 break; 4028 case R.styleable.View_textAlignment: 4029 // Clear any text alignment flag already set 4030 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4031 // Set the text alignment flag depending on the value of the attribute 4032 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4033 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4034 break; 4035 case R.styleable.View_importantForAccessibility: 4036 setImportantForAccessibility(a.getInt(attr, 4037 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4038 break; 4039 case R.styleable.View_accessibilityLiveRegion: 4040 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4041 break; 4042 case R.styleable.View_sharedElementName: 4043 setSharedElementName(a.getString(attr)); 4044 break; 4045 } 4046 } 4047 4048 setOverScrollMode(overScrollMode); 4049 4050 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4051 // the resolved layout direction). Those cached values will be used later during padding 4052 // resolution. 4053 mUserPaddingStart = startPadding; 4054 mUserPaddingEnd = endPadding; 4055 4056 if (background != null) { 4057 setBackground(background); 4058 } 4059 4060 // setBackground above will record that padding is currently provided by the background. 4061 // If we have padding specified via xml, record that here instead and use it. 4062 mLeftPaddingDefined = leftPaddingDefined; 4063 mRightPaddingDefined = rightPaddingDefined; 4064 4065 if (padding >= 0) { 4066 leftPadding = padding; 4067 topPadding = padding; 4068 rightPadding = padding; 4069 bottomPadding = padding; 4070 mUserPaddingLeftInitial = padding; 4071 mUserPaddingRightInitial = padding; 4072 } 4073 4074 if (isRtlCompatibilityMode()) { 4075 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4076 // left / right padding are used if defined (meaning here nothing to do). If they are not 4077 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4078 // start / end and resolve them as left / right (layout direction is not taken into account). 4079 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4080 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4081 // defined. 4082 if (!mLeftPaddingDefined && startPaddingDefined) { 4083 leftPadding = startPadding; 4084 } 4085 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4086 if (!mRightPaddingDefined && endPaddingDefined) { 4087 rightPadding = endPadding; 4088 } 4089 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4090 } else { 4091 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4092 // values defined. Otherwise, left /right values are used. 4093 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4094 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4095 // defined. 4096 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4097 4098 if (mLeftPaddingDefined && !hasRelativePadding) { 4099 mUserPaddingLeftInitial = leftPadding; 4100 } 4101 if (mRightPaddingDefined && !hasRelativePadding) { 4102 mUserPaddingRightInitial = rightPadding; 4103 } 4104 } 4105 4106 internalSetPadding( 4107 mUserPaddingLeftInitial, 4108 topPadding >= 0 ? topPadding : mPaddingTop, 4109 mUserPaddingRightInitial, 4110 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4111 4112 if (viewFlagMasks != 0) { 4113 setFlags(viewFlagValues, viewFlagMasks); 4114 } 4115 4116 if (initializeScrollbars) { 4117 initializeScrollbars(a); 4118 } 4119 4120 a.recycle(); 4121 4122 // Needs to be called after mViewFlags is set 4123 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4124 recomputePadding(); 4125 } 4126 4127 if (x != 0 || y != 0) { 4128 scrollTo(x, y); 4129 } 4130 4131 if (transformSet) { 4132 setTranslationX(tx); 4133 setTranslationY(ty); 4134 setTranslationZ(tz); 4135 setRotation(rotation); 4136 setRotationX(rotationX); 4137 setRotationY(rotationY); 4138 setScaleX(sx); 4139 setScaleY(sy); 4140 } 4141 4142 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4143 setScrollContainer(true); 4144 } 4145 4146 computeOpaqueFlags(); 4147 } 4148 4149 /** 4150 * Non-public constructor for use in testing 4151 */ 4152 View() { 4153 mResources = null; 4154 } 4155 4156 public String toString() { 4157 StringBuilder out = new StringBuilder(128); 4158 out.append(getClass().getName()); 4159 out.append('{'); 4160 out.append(Integer.toHexString(System.identityHashCode(this))); 4161 out.append(' '); 4162 switch (mViewFlags&VISIBILITY_MASK) { 4163 case VISIBLE: out.append('V'); break; 4164 case INVISIBLE: out.append('I'); break; 4165 case GONE: out.append('G'); break; 4166 default: out.append('.'); break; 4167 } 4168 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4169 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4170 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4171 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4172 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4173 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4174 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4175 out.append(' '); 4176 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4177 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4178 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4179 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4180 out.append('p'); 4181 } else { 4182 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4183 } 4184 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4185 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4186 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4187 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4188 out.append(' '); 4189 out.append(mLeft); 4190 out.append(','); 4191 out.append(mTop); 4192 out.append('-'); 4193 out.append(mRight); 4194 out.append(','); 4195 out.append(mBottom); 4196 final int id = getId(); 4197 if (id != NO_ID) { 4198 out.append(" #"); 4199 out.append(Integer.toHexString(id)); 4200 final Resources r = mResources; 4201 if (id != 0 && r != null) { 4202 try { 4203 String pkgname; 4204 switch (id&0xff000000) { 4205 case 0x7f000000: 4206 pkgname="app"; 4207 break; 4208 case 0x01000000: 4209 pkgname="android"; 4210 break; 4211 default: 4212 pkgname = r.getResourcePackageName(id); 4213 break; 4214 } 4215 String typename = r.getResourceTypeName(id); 4216 String entryname = r.getResourceEntryName(id); 4217 out.append(" "); 4218 out.append(pkgname); 4219 out.append(":"); 4220 out.append(typename); 4221 out.append("/"); 4222 out.append(entryname); 4223 } catch (Resources.NotFoundException e) { 4224 } 4225 } 4226 } 4227 out.append("}"); 4228 return out.toString(); 4229 } 4230 4231 /** 4232 * <p> 4233 * Initializes the fading edges from a given set of styled attributes. This 4234 * method should be called by subclasses that need fading edges and when an 4235 * instance of these subclasses is created programmatically rather than 4236 * being inflated from XML. This method is automatically called when the XML 4237 * is inflated. 4238 * </p> 4239 * 4240 * @param a the styled attributes set to initialize the fading edges from 4241 */ 4242 protected void initializeFadingEdge(TypedArray a) { 4243 initScrollCache(); 4244 4245 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4246 R.styleable.View_fadingEdgeLength, 4247 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4248 } 4249 4250 /** 4251 * Returns the size of the vertical faded edges used to indicate that more 4252 * content in this view is visible. 4253 * 4254 * @return The size in pixels of the vertical faded edge or 0 if vertical 4255 * faded edges are not enabled for this view. 4256 * @attr ref android.R.styleable#View_fadingEdgeLength 4257 */ 4258 public int getVerticalFadingEdgeLength() { 4259 if (isVerticalFadingEdgeEnabled()) { 4260 ScrollabilityCache cache = mScrollCache; 4261 if (cache != null) { 4262 return cache.fadingEdgeLength; 4263 } 4264 } 4265 return 0; 4266 } 4267 4268 /** 4269 * Set the size of the faded edge used to indicate that more content in this 4270 * view is available. Will not change whether the fading edge is enabled; use 4271 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4272 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4273 * for the vertical or horizontal fading edges. 4274 * 4275 * @param length The size in pixels of the faded edge used to indicate that more 4276 * content in this view is visible. 4277 */ 4278 public void setFadingEdgeLength(int length) { 4279 initScrollCache(); 4280 mScrollCache.fadingEdgeLength = length; 4281 } 4282 4283 /** 4284 * Returns the size of the horizontal faded edges used to indicate that more 4285 * content in this view is visible. 4286 * 4287 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4288 * faded edges are not enabled for this view. 4289 * @attr ref android.R.styleable#View_fadingEdgeLength 4290 */ 4291 public int getHorizontalFadingEdgeLength() { 4292 if (isHorizontalFadingEdgeEnabled()) { 4293 ScrollabilityCache cache = mScrollCache; 4294 if (cache != null) { 4295 return cache.fadingEdgeLength; 4296 } 4297 } 4298 return 0; 4299 } 4300 4301 /** 4302 * Returns the width of the vertical scrollbar. 4303 * 4304 * @return The width in pixels of the vertical scrollbar or 0 if there 4305 * is no vertical scrollbar. 4306 */ 4307 public int getVerticalScrollbarWidth() { 4308 ScrollabilityCache cache = mScrollCache; 4309 if (cache != null) { 4310 ScrollBarDrawable scrollBar = cache.scrollBar; 4311 if (scrollBar != null) { 4312 int size = scrollBar.getSize(true); 4313 if (size <= 0) { 4314 size = cache.scrollBarSize; 4315 } 4316 return size; 4317 } 4318 return 0; 4319 } 4320 return 0; 4321 } 4322 4323 /** 4324 * Returns the height of the horizontal scrollbar. 4325 * 4326 * @return The height in pixels of the horizontal scrollbar or 0 if 4327 * there is no horizontal scrollbar. 4328 */ 4329 protected int getHorizontalScrollbarHeight() { 4330 ScrollabilityCache cache = mScrollCache; 4331 if (cache != null) { 4332 ScrollBarDrawable scrollBar = cache.scrollBar; 4333 if (scrollBar != null) { 4334 int size = scrollBar.getSize(false); 4335 if (size <= 0) { 4336 size = cache.scrollBarSize; 4337 } 4338 return size; 4339 } 4340 return 0; 4341 } 4342 return 0; 4343 } 4344 4345 /** 4346 * <p> 4347 * Initializes the scrollbars from a given set of styled attributes. This 4348 * method should be called by subclasses that need scrollbars and when an 4349 * instance of these subclasses is created programmatically rather than 4350 * being inflated from XML. This method is automatically called when the XML 4351 * is inflated. 4352 * </p> 4353 * 4354 * @param a the styled attributes set to initialize the scrollbars from 4355 */ 4356 protected void initializeScrollbars(TypedArray a) { 4357 initScrollCache(); 4358 4359 final ScrollabilityCache scrollabilityCache = mScrollCache; 4360 4361 if (scrollabilityCache.scrollBar == null) { 4362 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4363 } 4364 4365 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4366 4367 if (!fadeScrollbars) { 4368 scrollabilityCache.state = ScrollabilityCache.ON; 4369 } 4370 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4371 4372 4373 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4374 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4375 .getScrollBarFadeDuration()); 4376 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4377 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4378 ViewConfiguration.getScrollDefaultDelay()); 4379 4380 4381 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4382 com.android.internal.R.styleable.View_scrollbarSize, 4383 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4384 4385 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4386 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4387 4388 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4389 if (thumb != null) { 4390 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4391 } 4392 4393 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4394 false); 4395 if (alwaysDraw) { 4396 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4397 } 4398 4399 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4400 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4401 4402 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4403 if (thumb != null) { 4404 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4405 } 4406 4407 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4408 false); 4409 if (alwaysDraw) { 4410 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4411 } 4412 4413 // Apply layout direction to the new Drawables if needed 4414 final int layoutDirection = getLayoutDirection(); 4415 if (track != null) { 4416 track.setLayoutDirection(layoutDirection); 4417 } 4418 if (thumb != null) { 4419 thumb.setLayoutDirection(layoutDirection); 4420 } 4421 4422 // Re-apply user/background padding so that scrollbar(s) get added 4423 resolvePadding(); 4424 } 4425 4426 /** 4427 * <p> 4428 * Initalizes the scrollability cache if necessary. 4429 * </p> 4430 */ 4431 private void initScrollCache() { 4432 if (mScrollCache == null) { 4433 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4434 } 4435 } 4436 4437 private ScrollabilityCache getScrollCache() { 4438 initScrollCache(); 4439 return mScrollCache; 4440 } 4441 4442 /** 4443 * Set the position of the vertical scroll bar. Should be one of 4444 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4445 * {@link #SCROLLBAR_POSITION_RIGHT}. 4446 * 4447 * @param position Where the vertical scroll bar should be positioned. 4448 */ 4449 public void setVerticalScrollbarPosition(int position) { 4450 if (mVerticalScrollbarPosition != position) { 4451 mVerticalScrollbarPosition = position; 4452 computeOpaqueFlags(); 4453 resolvePadding(); 4454 } 4455 } 4456 4457 /** 4458 * @return The position where the vertical scroll bar will show, if applicable. 4459 * @see #setVerticalScrollbarPosition(int) 4460 */ 4461 public int getVerticalScrollbarPosition() { 4462 return mVerticalScrollbarPosition; 4463 } 4464 4465 ListenerInfo getListenerInfo() { 4466 if (mListenerInfo != null) { 4467 return mListenerInfo; 4468 } 4469 mListenerInfo = new ListenerInfo(); 4470 return mListenerInfo; 4471 } 4472 4473 /** 4474 * Register a callback to be invoked when focus of this view changed. 4475 * 4476 * @param l The callback that will run. 4477 */ 4478 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4479 getListenerInfo().mOnFocusChangeListener = l; 4480 } 4481 4482 /** 4483 * Add a listener that will be called when the bounds of the view change due to 4484 * layout processing. 4485 * 4486 * @param listener The listener that will be called when layout bounds change. 4487 */ 4488 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4489 ListenerInfo li = getListenerInfo(); 4490 if (li.mOnLayoutChangeListeners == null) { 4491 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4492 } 4493 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4494 li.mOnLayoutChangeListeners.add(listener); 4495 } 4496 } 4497 4498 /** 4499 * Remove a listener for layout changes. 4500 * 4501 * @param listener The listener for layout bounds change. 4502 */ 4503 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4504 ListenerInfo li = mListenerInfo; 4505 if (li == null || li.mOnLayoutChangeListeners == null) { 4506 return; 4507 } 4508 li.mOnLayoutChangeListeners.remove(listener); 4509 } 4510 4511 /** 4512 * Add a listener for attach state changes. 4513 * 4514 * This listener will be called whenever this view is attached or detached 4515 * from a window. Remove the listener using 4516 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4517 * 4518 * @param listener Listener to attach 4519 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4520 */ 4521 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4522 ListenerInfo li = getListenerInfo(); 4523 if (li.mOnAttachStateChangeListeners == null) { 4524 li.mOnAttachStateChangeListeners 4525 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4526 } 4527 li.mOnAttachStateChangeListeners.add(listener); 4528 } 4529 4530 /** 4531 * Remove a listener for attach state changes. The listener will receive no further 4532 * notification of window attach/detach events. 4533 * 4534 * @param listener Listener to remove 4535 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4536 */ 4537 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4538 ListenerInfo li = mListenerInfo; 4539 if (li == null || li.mOnAttachStateChangeListeners == null) { 4540 return; 4541 } 4542 li.mOnAttachStateChangeListeners.remove(listener); 4543 } 4544 4545 /** 4546 * Returns the focus-change callback registered for this view. 4547 * 4548 * @return The callback, or null if one is not registered. 4549 */ 4550 public OnFocusChangeListener getOnFocusChangeListener() { 4551 ListenerInfo li = mListenerInfo; 4552 return li != null ? li.mOnFocusChangeListener : null; 4553 } 4554 4555 /** 4556 * Register a callback to be invoked when this view is clicked. If this view is not 4557 * clickable, it becomes clickable. 4558 * 4559 * @param l The callback that will run 4560 * 4561 * @see #setClickable(boolean) 4562 */ 4563 public void setOnClickListener(OnClickListener l) { 4564 if (!isClickable()) { 4565 setClickable(true); 4566 } 4567 getListenerInfo().mOnClickListener = l; 4568 } 4569 4570 /** 4571 * Return whether this view has an attached OnClickListener. Returns 4572 * true if there is a listener, false if there is none. 4573 */ 4574 public boolean hasOnClickListeners() { 4575 ListenerInfo li = mListenerInfo; 4576 return (li != null && li.mOnClickListener != null); 4577 } 4578 4579 /** 4580 * Register a callback to be invoked when this view is clicked and held. If this view is not 4581 * long clickable, it becomes long clickable. 4582 * 4583 * @param l The callback that will run 4584 * 4585 * @see #setLongClickable(boolean) 4586 */ 4587 public void setOnLongClickListener(OnLongClickListener l) { 4588 if (!isLongClickable()) { 4589 setLongClickable(true); 4590 } 4591 getListenerInfo().mOnLongClickListener = l; 4592 } 4593 4594 /** 4595 * Register a callback to be invoked when the context menu for this view is 4596 * being built. If this view is not long clickable, it becomes long clickable. 4597 * 4598 * @param l The callback that will run 4599 * 4600 */ 4601 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4602 if (!isLongClickable()) { 4603 setLongClickable(true); 4604 } 4605 getListenerInfo().mOnCreateContextMenuListener = l; 4606 } 4607 4608 /** 4609 * Call this view's OnClickListener, if it is defined. Performs all normal 4610 * actions associated with clicking: reporting accessibility event, playing 4611 * a sound, etc. 4612 * 4613 * @return True there was an assigned OnClickListener that was called, false 4614 * otherwise is returned. 4615 */ 4616 public boolean performClick() { 4617 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4618 4619 ListenerInfo li = mListenerInfo; 4620 if (li != null && li.mOnClickListener != null) { 4621 playSoundEffect(SoundEffectConstants.CLICK); 4622 li.mOnClickListener.onClick(this); 4623 return true; 4624 } 4625 4626 return false; 4627 } 4628 4629 /** 4630 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4631 * this only calls the listener, and does not do any associated clicking 4632 * actions like reporting an accessibility event. 4633 * 4634 * @return True there was an assigned OnClickListener that was called, false 4635 * otherwise is returned. 4636 */ 4637 public boolean callOnClick() { 4638 ListenerInfo li = mListenerInfo; 4639 if (li != null && li.mOnClickListener != null) { 4640 li.mOnClickListener.onClick(this); 4641 return true; 4642 } 4643 return false; 4644 } 4645 4646 /** 4647 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4648 * OnLongClickListener did not consume the event. 4649 * 4650 * @return True if one of the above receivers consumed the event, false otherwise. 4651 */ 4652 public boolean performLongClick() { 4653 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4654 4655 boolean handled = false; 4656 ListenerInfo li = mListenerInfo; 4657 if (li != null && li.mOnLongClickListener != null) { 4658 handled = li.mOnLongClickListener.onLongClick(View.this); 4659 } 4660 if (!handled) { 4661 handled = showContextMenu(); 4662 } 4663 if (handled) { 4664 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4665 } 4666 return handled; 4667 } 4668 4669 /** 4670 * Performs button-related actions during a touch down event. 4671 * 4672 * @param event The event. 4673 * @return True if the down was consumed. 4674 * 4675 * @hide 4676 */ 4677 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4678 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4679 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4680 return true; 4681 } 4682 } 4683 return false; 4684 } 4685 4686 /** 4687 * Bring up the context menu for this view. 4688 * 4689 * @return Whether a context menu was displayed. 4690 */ 4691 public boolean showContextMenu() { 4692 return getParent().showContextMenuForChild(this); 4693 } 4694 4695 /** 4696 * Bring up the context menu for this view, referring to the item under the specified point. 4697 * 4698 * @param x The referenced x coordinate. 4699 * @param y The referenced y coordinate. 4700 * @param metaState The keyboard modifiers that were pressed. 4701 * @return Whether a context menu was displayed. 4702 * 4703 * @hide 4704 */ 4705 public boolean showContextMenu(float x, float y, int metaState) { 4706 return showContextMenu(); 4707 } 4708 4709 /** 4710 * Start an action mode. 4711 * 4712 * @param callback Callback that will control the lifecycle of the action mode 4713 * @return The new action mode if it is started, null otherwise 4714 * 4715 * @see ActionMode 4716 */ 4717 public ActionMode startActionMode(ActionMode.Callback callback) { 4718 ViewParent parent = getParent(); 4719 if (parent == null) return null; 4720 return parent.startActionModeForChild(this, callback); 4721 } 4722 4723 /** 4724 * Register a callback to be invoked when a hardware key is pressed in this view. 4725 * Key presses in software input methods will generally not trigger the methods of 4726 * this listener. 4727 * @param l the key listener to attach to this view 4728 */ 4729 public void setOnKeyListener(OnKeyListener l) { 4730 getListenerInfo().mOnKeyListener = l; 4731 } 4732 4733 /** 4734 * Register a callback to be invoked when a touch event is sent to this view. 4735 * @param l the touch listener to attach to this view 4736 */ 4737 public void setOnTouchListener(OnTouchListener l) { 4738 getListenerInfo().mOnTouchListener = l; 4739 } 4740 4741 /** 4742 * Register a callback to be invoked when a generic motion event is sent to this view. 4743 * @param l the generic motion listener to attach to this view 4744 */ 4745 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4746 getListenerInfo().mOnGenericMotionListener = l; 4747 } 4748 4749 /** 4750 * Register a callback to be invoked when a hover event is sent to this view. 4751 * @param l the hover listener to attach to this view 4752 */ 4753 public void setOnHoverListener(OnHoverListener l) { 4754 getListenerInfo().mOnHoverListener = l; 4755 } 4756 4757 /** 4758 * Register a drag event listener callback object for this View. The parameter is 4759 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4760 * View, the system calls the 4761 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4762 * @param l An implementation of {@link android.view.View.OnDragListener}. 4763 */ 4764 public void setOnDragListener(OnDragListener l) { 4765 getListenerInfo().mOnDragListener = l; 4766 } 4767 4768 /** 4769 * Give this view focus. This will cause 4770 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4771 * 4772 * Note: this does not check whether this {@link View} should get focus, it just 4773 * gives it focus no matter what. It should only be called internally by framework 4774 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4775 * 4776 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4777 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4778 * focus moved when requestFocus() is called. It may not always 4779 * apply, in which case use the default View.FOCUS_DOWN. 4780 * @param previouslyFocusedRect The rectangle of the view that had focus 4781 * prior in this View's coordinate system. 4782 */ 4783 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4784 if (DBG) { 4785 System.out.println(this + " requestFocus()"); 4786 } 4787 4788 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4789 mPrivateFlags |= PFLAG_FOCUSED; 4790 4791 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4792 4793 if (mParent != null) { 4794 mParent.requestChildFocus(this, this); 4795 } 4796 4797 if (mAttachInfo != null) { 4798 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4799 } 4800 4801 manageFocusHotspot(true, oldFocus); 4802 onFocusChanged(true, direction, previouslyFocusedRect); 4803 refreshDrawableState(); 4804 } 4805 } 4806 4807 /** 4808 * Forwards focus information to the background drawable, if necessary. When 4809 * the view is gaining focus, <code>v</code> is the previous focus holder. 4810 * When the view is losing focus, <code>v</code> is the next focus holder. 4811 * 4812 * @param focused whether this view is focused 4813 * @param v previous or the next focus holder, or null if none 4814 */ 4815 private void manageFocusHotspot(boolean focused, View v) { 4816 if (mBackground != null && mBackground.supportsHotspots()) { 4817 final Rect r = new Rect(); 4818 if (v != null) { 4819 v.getBoundsOnScreen(r); 4820 final int[] location = new int[2]; 4821 getLocationOnScreen(location); 4822 r.offset(-location[0], -location[1]); 4823 } else { 4824 r.set(mLeft, mTop, mRight, mBottom); 4825 } 4826 4827 final float x = r.exactCenterX(); 4828 final float y = r.exactCenterY(); 4829 mBackground.setHotspot(Drawable.HOTSPOT_FOCUS, x, y); 4830 4831 if (!focused) { 4832 mBackground.removeHotspot(Drawable.HOTSPOT_FOCUS); 4833 } 4834 } 4835 } 4836 4837 /** 4838 * Request that a rectangle of this view be visible on the screen, 4839 * scrolling if necessary just enough. 4840 * 4841 * <p>A View should call this if it maintains some notion of which part 4842 * of its content is interesting. For example, a text editing view 4843 * should call this when its cursor moves. 4844 * 4845 * @param rectangle The rectangle. 4846 * @return Whether any parent scrolled. 4847 */ 4848 public boolean requestRectangleOnScreen(Rect rectangle) { 4849 return requestRectangleOnScreen(rectangle, false); 4850 } 4851 4852 /** 4853 * Request that a rectangle of this view be visible on the screen, 4854 * scrolling if necessary just enough. 4855 * 4856 * <p>A View should call this if it maintains some notion of which part 4857 * of its content is interesting. For example, a text editing view 4858 * should call this when its cursor moves. 4859 * 4860 * <p>When <code>immediate</code> is set to true, scrolling will not be 4861 * animated. 4862 * 4863 * @param rectangle The rectangle. 4864 * @param immediate True to forbid animated scrolling, false otherwise 4865 * @return Whether any parent scrolled. 4866 */ 4867 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4868 if (mParent == null) { 4869 return false; 4870 } 4871 4872 View child = this; 4873 4874 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4875 position.set(rectangle); 4876 4877 ViewParent parent = mParent; 4878 boolean scrolled = false; 4879 while (parent != null) { 4880 rectangle.set((int) position.left, (int) position.top, 4881 (int) position.right, (int) position.bottom); 4882 4883 scrolled |= parent.requestChildRectangleOnScreen(child, 4884 rectangle, immediate); 4885 4886 if (!child.hasIdentityMatrix()) { 4887 child.getMatrix().mapRect(position); 4888 } 4889 4890 position.offset(child.mLeft, child.mTop); 4891 4892 if (!(parent instanceof View)) { 4893 break; 4894 } 4895 4896 View parentView = (View) parent; 4897 4898 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4899 4900 child = parentView; 4901 parent = child.getParent(); 4902 } 4903 4904 return scrolled; 4905 } 4906 4907 /** 4908 * Called when this view wants to give up focus. If focus is cleared 4909 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4910 * <p> 4911 * <strong>Note:</strong> When a View clears focus the framework is trying 4912 * to give focus to the first focusable View from the top. Hence, if this 4913 * View is the first from the top that can take focus, then all callbacks 4914 * related to clearing focus will be invoked after wich the framework will 4915 * give focus to this view. 4916 * </p> 4917 */ 4918 public void clearFocus() { 4919 if (DBG) { 4920 System.out.println(this + " clearFocus()"); 4921 } 4922 4923 clearFocusInternal(null, true, true); 4924 } 4925 4926 /** 4927 * Clears focus from the view, optionally propagating the change up through 4928 * the parent hierarchy and requesting that the root view place new focus. 4929 * 4930 * @param propagate whether to propagate the change up through the parent 4931 * hierarchy 4932 * @param refocus when propagate is true, specifies whether to request the 4933 * root view place new focus 4934 */ 4935 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4936 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4937 mPrivateFlags &= ~PFLAG_FOCUSED; 4938 4939 if (hasFocus()) { 4940 manageFocusHotspot(false, focused); 4941 } 4942 4943 if (propagate && mParent != null) { 4944 mParent.clearChildFocus(this); 4945 } 4946 4947 onFocusChanged(false, 0, null); 4948 4949 refreshDrawableState(); 4950 4951 if (propagate && (!refocus || !rootViewRequestFocus())) { 4952 notifyGlobalFocusCleared(this); 4953 } 4954 } 4955 } 4956 4957 void notifyGlobalFocusCleared(View oldFocus) { 4958 if (oldFocus != null && mAttachInfo != null) { 4959 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4960 } 4961 } 4962 4963 boolean rootViewRequestFocus() { 4964 final View root = getRootView(); 4965 return root != null && root.requestFocus(); 4966 } 4967 4968 /** 4969 * Called internally by the view system when a new view is getting focus. 4970 * This is what clears the old focus. 4971 * <p> 4972 * <b>NOTE:</b> The parent view's focused child must be updated manually 4973 * after calling this method. Otherwise, the view hierarchy may be left in 4974 * an inconstent state. 4975 */ 4976 void unFocus(View focused) { 4977 if (DBG) { 4978 System.out.println(this + " unFocus()"); 4979 } 4980 4981 clearFocusInternal(focused, false, false); 4982 } 4983 4984 /** 4985 * Returns true if this view has focus iteself, or is the ancestor of the 4986 * view that has focus. 4987 * 4988 * @return True if this view has or contains focus, false otherwise. 4989 */ 4990 @ViewDebug.ExportedProperty(category = "focus") 4991 public boolean hasFocus() { 4992 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4993 } 4994 4995 /** 4996 * Returns true if this view is focusable or if it contains a reachable View 4997 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4998 * is a View whose parents do not block descendants focus. 4999 * 5000 * Only {@link #VISIBLE} views are considered focusable. 5001 * 5002 * @return True if the view is focusable or if the view contains a focusable 5003 * View, false otherwise. 5004 * 5005 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5006 */ 5007 public boolean hasFocusable() { 5008 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5009 } 5010 5011 /** 5012 * Called by the view system when the focus state of this view changes. 5013 * When the focus change event is caused by directional navigation, direction 5014 * and previouslyFocusedRect provide insight into where the focus is coming from. 5015 * When overriding, be sure to call up through to the super class so that 5016 * the standard focus handling will occur. 5017 * 5018 * @param gainFocus True if the View has focus; false otherwise. 5019 * @param direction The direction focus has moved when requestFocus() 5020 * is called to give this view focus. Values are 5021 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5022 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5023 * It may not always apply, in which case use the default. 5024 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5025 * system, of the previously focused view. If applicable, this will be 5026 * passed in as finer grained information about where the focus is coming 5027 * from (in addition to direction). Will be <code>null</code> otherwise. 5028 */ 5029 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5030 @Nullable Rect previouslyFocusedRect) { 5031 if (gainFocus) { 5032 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5033 } else { 5034 notifyViewAccessibilityStateChangedIfNeeded( 5035 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5036 } 5037 5038 InputMethodManager imm = InputMethodManager.peekInstance(); 5039 if (!gainFocus) { 5040 if (isPressed()) { 5041 setPressed(false); 5042 } 5043 if (imm != null && mAttachInfo != null 5044 && mAttachInfo.mHasWindowFocus) { 5045 imm.focusOut(this); 5046 } 5047 onFocusLost(); 5048 } else if (imm != null && mAttachInfo != null 5049 && mAttachInfo.mHasWindowFocus) { 5050 imm.focusIn(this); 5051 } 5052 5053 invalidate(true); 5054 ListenerInfo li = mListenerInfo; 5055 if (li != null && li.mOnFocusChangeListener != null) { 5056 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5057 } 5058 5059 if (mAttachInfo != null) { 5060 mAttachInfo.mKeyDispatchState.reset(this); 5061 } 5062 } 5063 5064 /** 5065 * Sends an accessibility event of the given type. If accessibility is 5066 * not enabled this method has no effect. The default implementation calls 5067 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5068 * to populate information about the event source (this View), then calls 5069 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5070 * populate the text content of the event source including its descendants, 5071 * and last calls 5072 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5073 * on its parent to resuest sending of the event to interested parties. 5074 * <p> 5075 * If an {@link AccessibilityDelegate} has been specified via calling 5076 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5077 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5078 * responsible for handling this call. 5079 * </p> 5080 * 5081 * @param eventType The type of the event to send, as defined by several types from 5082 * {@link android.view.accessibility.AccessibilityEvent}, such as 5083 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5084 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5085 * 5086 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5087 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5088 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5089 * @see AccessibilityDelegate 5090 */ 5091 public void sendAccessibilityEvent(int eventType) { 5092 // Excluded views do not send accessibility events. 5093 if (!includeForAccessibility()) { 5094 return; 5095 } 5096 if (mAccessibilityDelegate != null) { 5097 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5098 } else { 5099 sendAccessibilityEventInternal(eventType); 5100 } 5101 } 5102 5103 /** 5104 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5105 * {@link AccessibilityEvent} to make an announcement which is related to some 5106 * sort of a context change for which none of the events representing UI transitions 5107 * is a good fit. For example, announcing a new page in a book. If accessibility 5108 * is not enabled this method does nothing. 5109 * 5110 * @param text The announcement text. 5111 */ 5112 public void announceForAccessibility(CharSequence text) { 5113 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null 5114 && isImportantForAccessibility()) { 5115 AccessibilityEvent event = AccessibilityEvent.obtain( 5116 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5117 onInitializeAccessibilityEvent(event); 5118 event.getText().add(text); 5119 event.setContentDescription(null); 5120 mParent.requestSendAccessibilityEvent(this, event); 5121 } 5122 } 5123 5124 /** 5125 * @see #sendAccessibilityEvent(int) 5126 * 5127 * Note: Called from the default {@link AccessibilityDelegate}. 5128 */ 5129 void sendAccessibilityEventInternal(int eventType) { 5130 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5131 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5132 } 5133 } 5134 5135 /** 5136 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5137 * takes as an argument an empty {@link AccessibilityEvent} and does not 5138 * perform a check whether accessibility is enabled. 5139 * <p> 5140 * If an {@link AccessibilityDelegate} has been specified via calling 5141 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5142 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5143 * is responsible for handling this call. 5144 * </p> 5145 * 5146 * @param event The event to send. 5147 * 5148 * @see #sendAccessibilityEvent(int) 5149 */ 5150 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5151 if (mAccessibilityDelegate != null) { 5152 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5153 } else { 5154 sendAccessibilityEventUncheckedInternal(event); 5155 } 5156 } 5157 5158 /** 5159 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5160 * 5161 * Note: Called from the default {@link AccessibilityDelegate}. 5162 */ 5163 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5164 if (!isShown() || !isImportantForAccessibility()) { 5165 return; 5166 } 5167 onInitializeAccessibilityEvent(event); 5168 // Only a subset of accessibility events populates text content. 5169 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5170 dispatchPopulateAccessibilityEvent(event); 5171 } 5172 // In the beginning we called #isShown(), so we know that getParent() is not null. 5173 getParent().requestSendAccessibilityEvent(this, event); 5174 } 5175 5176 /** 5177 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5178 * to its children for adding their text content to the event. Note that the 5179 * event text is populated in a separate dispatch path since we add to the 5180 * event not only the text of the source but also the text of all its descendants. 5181 * A typical implementation will call 5182 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5183 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5184 * on each child. Override this method if custom population of the event text 5185 * content is required. 5186 * <p> 5187 * If an {@link AccessibilityDelegate} has been specified via calling 5188 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5189 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5190 * is responsible for handling this call. 5191 * </p> 5192 * <p> 5193 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5194 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5195 * </p> 5196 * 5197 * @param event The event. 5198 * 5199 * @return True if the event population was completed. 5200 */ 5201 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5202 if (mAccessibilityDelegate != null) { 5203 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5204 } else { 5205 return dispatchPopulateAccessibilityEventInternal(event); 5206 } 5207 } 5208 5209 /** 5210 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5211 * 5212 * Note: Called from the default {@link AccessibilityDelegate}. 5213 */ 5214 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5215 onPopulateAccessibilityEvent(event); 5216 return false; 5217 } 5218 5219 /** 5220 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5221 * giving a chance to this View to populate the accessibility event with its 5222 * text content. While this method is free to modify event 5223 * attributes other than text content, doing so should normally be performed in 5224 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5225 * <p> 5226 * Example: Adding formatted date string to an accessibility event in addition 5227 * to the text added by the super implementation: 5228 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5229 * super.onPopulateAccessibilityEvent(event); 5230 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5231 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5232 * mCurrentDate.getTimeInMillis(), flags); 5233 * event.getText().add(selectedDateUtterance); 5234 * }</pre> 5235 * <p> 5236 * If an {@link AccessibilityDelegate} has been specified via calling 5237 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5238 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5239 * is responsible for handling this call. 5240 * </p> 5241 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5242 * information to the event, in case the default implementation has basic information to add. 5243 * </p> 5244 * 5245 * @param event The accessibility event which to populate. 5246 * 5247 * @see #sendAccessibilityEvent(int) 5248 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5249 */ 5250 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5251 if (mAccessibilityDelegate != null) { 5252 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5253 } else { 5254 onPopulateAccessibilityEventInternal(event); 5255 } 5256 } 5257 5258 /** 5259 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5260 * 5261 * Note: Called from the default {@link AccessibilityDelegate}. 5262 */ 5263 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5264 } 5265 5266 /** 5267 * Initializes an {@link AccessibilityEvent} with information about 5268 * this View which is the event source. In other words, the source of 5269 * an accessibility event is the view whose state change triggered firing 5270 * the event. 5271 * <p> 5272 * Example: Setting the password property of an event in addition 5273 * to properties set by the super implementation: 5274 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5275 * super.onInitializeAccessibilityEvent(event); 5276 * event.setPassword(true); 5277 * }</pre> 5278 * <p> 5279 * If an {@link AccessibilityDelegate} has been specified via calling 5280 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5281 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5282 * is responsible for handling this call. 5283 * </p> 5284 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5285 * information to the event, in case the default implementation has basic information to add. 5286 * </p> 5287 * @param event The event to initialize. 5288 * 5289 * @see #sendAccessibilityEvent(int) 5290 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5291 */ 5292 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5293 if (mAccessibilityDelegate != null) { 5294 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5295 } else { 5296 onInitializeAccessibilityEventInternal(event); 5297 } 5298 } 5299 5300 /** 5301 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5302 * 5303 * Note: Called from the default {@link AccessibilityDelegate}. 5304 */ 5305 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5306 event.setSource(this); 5307 event.setClassName(View.class.getName()); 5308 event.setPackageName(getContext().getPackageName()); 5309 event.setEnabled(isEnabled()); 5310 event.setContentDescription(mContentDescription); 5311 5312 switch (event.getEventType()) { 5313 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5314 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5315 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5316 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5317 event.setItemCount(focusablesTempList.size()); 5318 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5319 if (mAttachInfo != null) { 5320 focusablesTempList.clear(); 5321 } 5322 } break; 5323 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5324 CharSequence text = getIterableTextForAccessibility(); 5325 if (text != null && text.length() > 0) { 5326 event.setFromIndex(getAccessibilitySelectionStart()); 5327 event.setToIndex(getAccessibilitySelectionEnd()); 5328 event.setItemCount(text.length()); 5329 } 5330 } break; 5331 } 5332 } 5333 5334 /** 5335 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5336 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5337 * This method is responsible for obtaining an accessibility node info from a 5338 * pool of reusable instances and calling 5339 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5340 * initialize the former. 5341 * <p> 5342 * Note: The client is responsible for recycling the obtained instance by calling 5343 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5344 * </p> 5345 * 5346 * @return A populated {@link AccessibilityNodeInfo}. 5347 * 5348 * @see AccessibilityNodeInfo 5349 */ 5350 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5351 if (mAccessibilityDelegate != null) { 5352 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5353 } else { 5354 return createAccessibilityNodeInfoInternal(); 5355 } 5356 } 5357 5358 /** 5359 * @see #createAccessibilityNodeInfo() 5360 */ 5361 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5362 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5363 if (provider != null) { 5364 return provider.createAccessibilityNodeInfo(View.NO_ID); 5365 } else { 5366 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5367 onInitializeAccessibilityNodeInfo(info); 5368 return info; 5369 } 5370 } 5371 5372 /** 5373 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5374 * The base implementation sets: 5375 * <ul> 5376 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5377 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5378 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5379 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5380 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5381 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5382 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5383 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5384 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5385 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5386 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5387 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5388 * </ul> 5389 * <p> 5390 * Subclasses should override this method, call the super implementation, 5391 * and set additional attributes. 5392 * </p> 5393 * <p> 5394 * If an {@link AccessibilityDelegate} has been specified via calling 5395 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5396 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5397 * is responsible for handling this call. 5398 * </p> 5399 * 5400 * @param info The instance to initialize. 5401 */ 5402 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5403 if (mAccessibilityDelegate != null) { 5404 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5405 } else { 5406 onInitializeAccessibilityNodeInfoInternal(info); 5407 } 5408 } 5409 5410 /** 5411 * Gets the location of this view in screen coordintates. 5412 * 5413 * @param outRect The output location 5414 */ 5415 void getBoundsOnScreen(Rect outRect) { 5416 if (mAttachInfo == null) { 5417 return; 5418 } 5419 5420 RectF position = mAttachInfo.mTmpTransformRect; 5421 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5422 5423 if (!hasIdentityMatrix()) { 5424 getMatrix().mapRect(position); 5425 } 5426 5427 position.offset(mLeft, mTop); 5428 5429 ViewParent parent = mParent; 5430 while (parent instanceof View) { 5431 View parentView = (View) parent; 5432 5433 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5434 5435 if (!parentView.hasIdentityMatrix()) { 5436 parentView.getMatrix().mapRect(position); 5437 } 5438 5439 position.offset(parentView.mLeft, parentView.mTop); 5440 5441 parent = parentView.mParent; 5442 } 5443 5444 if (parent instanceof ViewRootImpl) { 5445 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5446 position.offset(0, -viewRootImpl.mCurScrollY); 5447 } 5448 5449 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5450 5451 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5452 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5453 } 5454 5455 /** 5456 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5457 * 5458 * Note: Called from the default {@link AccessibilityDelegate}. 5459 */ 5460 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5461 Rect bounds = mAttachInfo.mTmpInvalRect; 5462 5463 getDrawingRect(bounds); 5464 info.setBoundsInParent(bounds); 5465 5466 getBoundsOnScreen(bounds); 5467 info.setBoundsInScreen(bounds); 5468 5469 ViewParent parent = getParentForAccessibility(); 5470 if (parent instanceof View) { 5471 info.setParent((View) parent); 5472 } 5473 5474 if (mID != View.NO_ID) { 5475 View rootView = getRootView(); 5476 if (rootView == null) { 5477 rootView = this; 5478 } 5479 View label = rootView.findLabelForView(this, mID); 5480 if (label != null) { 5481 info.setLabeledBy(label); 5482 } 5483 5484 if ((mAttachInfo.mAccessibilityFetchFlags 5485 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5486 && Resources.resourceHasPackage(mID)) { 5487 try { 5488 String viewId = getResources().getResourceName(mID); 5489 info.setViewIdResourceName(viewId); 5490 } catch (Resources.NotFoundException nfe) { 5491 /* ignore */ 5492 } 5493 } 5494 } 5495 5496 if (mLabelForId != View.NO_ID) { 5497 View rootView = getRootView(); 5498 if (rootView == null) { 5499 rootView = this; 5500 } 5501 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5502 if (labeled != null) { 5503 info.setLabelFor(labeled); 5504 } 5505 } 5506 5507 info.setVisibleToUser(isVisibleToUser()); 5508 5509 info.setPackageName(mContext.getPackageName()); 5510 info.setClassName(View.class.getName()); 5511 info.setContentDescription(getContentDescription()); 5512 5513 info.setEnabled(isEnabled()); 5514 info.setClickable(isClickable()); 5515 info.setFocusable(isFocusable()); 5516 info.setFocused(isFocused()); 5517 info.setAccessibilityFocused(isAccessibilityFocused()); 5518 info.setSelected(isSelected()); 5519 info.setLongClickable(isLongClickable()); 5520 info.setLiveRegion(getAccessibilityLiveRegion()); 5521 5522 // TODO: These make sense only if we are in an AdapterView but all 5523 // views can be selected. Maybe from accessibility perspective 5524 // we should report as selectable view in an AdapterView. 5525 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5526 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5527 5528 if (isFocusable()) { 5529 if (isFocused()) { 5530 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5531 } else { 5532 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5533 } 5534 } 5535 5536 if (!isAccessibilityFocused()) { 5537 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5538 } else { 5539 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5540 } 5541 5542 if (isClickable() && isEnabled()) { 5543 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5544 } 5545 5546 if (isLongClickable() && isEnabled()) { 5547 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5548 } 5549 5550 CharSequence text = getIterableTextForAccessibility(); 5551 if (text != null && text.length() > 0) { 5552 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5553 5554 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5555 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5556 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5557 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5558 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5559 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5560 } 5561 } 5562 5563 private View findLabelForView(View view, int labeledId) { 5564 if (mMatchLabelForPredicate == null) { 5565 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5566 } 5567 mMatchLabelForPredicate.mLabeledId = labeledId; 5568 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5569 } 5570 5571 /** 5572 * Computes whether this view is visible to the user. Such a view is 5573 * attached, visible, all its predecessors are visible, it is not clipped 5574 * entirely by its predecessors, and has an alpha greater than zero. 5575 * 5576 * @return Whether the view is visible on the screen. 5577 * 5578 * @hide 5579 */ 5580 protected boolean isVisibleToUser() { 5581 return isVisibleToUser(null); 5582 } 5583 5584 /** 5585 * Computes whether the given portion of this view is visible to the user. 5586 * Such a view is attached, visible, all its predecessors are visible, 5587 * has an alpha greater than zero, and the specified portion is not 5588 * clipped entirely by its predecessors. 5589 * 5590 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5591 * <code>null</code>, and the entire view will be tested in this case. 5592 * When <code>true</code> is returned by the function, the actual visible 5593 * region will be stored in this parameter; that is, if boundInView is fully 5594 * contained within the view, no modification will be made, otherwise regions 5595 * outside of the visible area of the view will be clipped. 5596 * 5597 * @return Whether the specified portion of the view is visible on the screen. 5598 * 5599 * @hide 5600 */ 5601 protected boolean isVisibleToUser(Rect boundInView) { 5602 if (mAttachInfo != null) { 5603 // Attached to invisible window means this view is not visible. 5604 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5605 return false; 5606 } 5607 // An invisible predecessor or one with alpha zero means 5608 // that this view is not visible to the user. 5609 Object current = this; 5610 while (current instanceof View) { 5611 View view = (View) current; 5612 // We have attach info so this view is attached and there is no 5613 // need to check whether we reach to ViewRootImpl on the way up. 5614 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5615 view.getVisibility() != VISIBLE) { 5616 return false; 5617 } 5618 current = view.mParent; 5619 } 5620 // Check if the view is entirely covered by its predecessors. 5621 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5622 Point offset = mAttachInfo.mPoint; 5623 if (!getGlobalVisibleRect(visibleRect, offset)) { 5624 return false; 5625 } 5626 // Check if the visible portion intersects the rectangle of interest. 5627 if (boundInView != null) { 5628 visibleRect.offset(-offset.x, -offset.y); 5629 return boundInView.intersect(visibleRect); 5630 } 5631 return true; 5632 } 5633 return false; 5634 } 5635 5636 /** 5637 * Returns the delegate for implementing accessibility support via 5638 * composition. For more details see {@link AccessibilityDelegate}. 5639 * 5640 * @return The delegate, or null if none set. 5641 * 5642 * @hide 5643 */ 5644 public AccessibilityDelegate getAccessibilityDelegate() { 5645 return mAccessibilityDelegate; 5646 } 5647 5648 /** 5649 * Sets a delegate for implementing accessibility support via composition as 5650 * opposed to inheritance. The delegate's primary use is for implementing 5651 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5652 * 5653 * @param delegate The delegate instance. 5654 * 5655 * @see AccessibilityDelegate 5656 */ 5657 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5658 mAccessibilityDelegate = delegate; 5659 } 5660 5661 /** 5662 * Gets the provider for managing a virtual view hierarchy rooted at this View 5663 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5664 * that explore the window content. 5665 * <p> 5666 * If this method returns an instance, this instance is responsible for managing 5667 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5668 * View including the one representing the View itself. Similarly the returned 5669 * instance is responsible for performing accessibility actions on any virtual 5670 * view or the root view itself. 5671 * </p> 5672 * <p> 5673 * If an {@link AccessibilityDelegate} has been specified via calling 5674 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5675 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5676 * is responsible for handling this call. 5677 * </p> 5678 * 5679 * @return The provider. 5680 * 5681 * @see AccessibilityNodeProvider 5682 */ 5683 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5684 if (mAccessibilityDelegate != null) { 5685 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5686 } else { 5687 return null; 5688 } 5689 } 5690 5691 /** 5692 * Gets the unique identifier of this view on the screen for accessibility purposes. 5693 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5694 * 5695 * @return The view accessibility id. 5696 * 5697 * @hide 5698 */ 5699 public int getAccessibilityViewId() { 5700 if (mAccessibilityViewId == NO_ID) { 5701 mAccessibilityViewId = sNextAccessibilityViewId++; 5702 } 5703 return mAccessibilityViewId; 5704 } 5705 5706 /** 5707 * Gets the unique identifier of the window in which this View reseides. 5708 * 5709 * @return The window accessibility id. 5710 * 5711 * @hide 5712 */ 5713 public int getAccessibilityWindowId() { 5714 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 5715 } 5716 5717 /** 5718 * Gets the {@link View} description. It briefly describes the view and is 5719 * primarily used for accessibility support. Set this property to enable 5720 * better accessibility support for your application. This is especially 5721 * true for views that do not have textual representation (For example, 5722 * ImageButton). 5723 * 5724 * @return The content description. 5725 * 5726 * @attr ref android.R.styleable#View_contentDescription 5727 */ 5728 @ViewDebug.ExportedProperty(category = "accessibility") 5729 public CharSequence getContentDescription() { 5730 return mContentDescription; 5731 } 5732 5733 /** 5734 * Sets the {@link View} description. It briefly describes the view and is 5735 * primarily used for accessibility support. Set this property to enable 5736 * better accessibility support for your application. This is especially 5737 * true for views that do not have textual representation (For example, 5738 * ImageButton). 5739 * 5740 * @param contentDescription The content description. 5741 * 5742 * @attr ref android.R.styleable#View_contentDescription 5743 */ 5744 @RemotableViewMethod 5745 public void setContentDescription(CharSequence contentDescription) { 5746 if (mContentDescription == null) { 5747 if (contentDescription == null) { 5748 return; 5749 } 5750 } else if (mContentDescription.equals(contentDescription)) { 5751 return; 5752 } 5753 mContentDescription = contentDescription; 5754 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5755 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5756 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5757 notifySubtreeAccessibilityStateChangedIfNeeded(); 5758 } else { 5759 notifyViewAccessibilityStateChangedIfNeeded( 5760 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5761 } 5762 } 5763 5764 /** 5765 * Gets the id of a view for which this view serves as a label for 5766 * accessibility purposes. 5767 * 5768 * @return The labeled view id. 5769 */ 5770 @ViewDebug.ExportedProperty(category = "accessibility") 5771 public int getLabelFor() { 5772 return mLabelForId; 5773 } 5774 5775 /** 5776 * Sets the id of a view for which this view serves as a label for 5777 * accessibility purposes. 5778 * 5779 * @param id The labeled view id. 5780 */ 5781 @RemotableViewMethod 5782 public void setLabelFor(int id) { 5783 mLabelForId = id; 5784 if (mLabelForId != View.NO_ID 5785 && mID == View.NO_ID) { 5786 mID = generateViewId(); 5787 } 5788 } 5789 5790 /** 5791 * Invoked whenever this view loses focus, either by losing window focus or by losing 5792 * focus within its window. This method can be used to clear any state tied to the 5793 * focus. For instance, if a button is held pressed with the trackball and the window 5794 * loses focus, this method can be used to cancel the press. 5795 * 5796 * Subclasses of View overriding this method should always call super.onFocusLost(). 5797 * 5798 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5799 * @see #onWindowFocusChanged(boolean) 5800 * 5801 * @hide pending API council approval 5802 */ 5803 protected void onFocusLost() { 5804 resetPressedState(); 5805 } 5806 5807 private void resetPressedState() { 5808 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5809 return; 5810 } 5811 5812 if (isPressed()) { 5813 setPressed(false); 5814 5815 if (!mHasPerformedLongPress) { 5816 removeLongPressCallback(); 5817 } 5818 } 5819 } 5820 5821 /** 5822 * Returns true if this view has focus 5823 * 5824 * @return True if this view has focus, false otherwise. 5825 */ 5826 @ViewDebug.ExportedProperty(category = "focus") 5827 public boolean isFocused() { 5828 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5829 } 5830 5831 /** 5832 * Find the view in the hierarchy rooted at this view that currently has 5833 * focus. 5834 * 5835 * @return The view that currently has focus, or null if no focused view can 5836 * be found. 5837 */ 5838 public View findFocus() { 5839 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5840 } 5841 5842 /** 5843 * Indicates whether this view is one of the set of scrollable containers in 5844 * its window. 5845 * 5846 * @return whether this view is one of the set of scrollable containers in 5847 * its window 5848 * 5849 * @attr ref android.R.styleable#View_isScrollContainer 5850 */ 5851 public boolean isScrollContainer() { 5852 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5853 } 5854 5855 /** 5856 * Change whether this view is one of the set of scrollable containers in 5857 * its window. This will be used to determine whether the window can 5858 * resize or must pan when a soft input area is open -- scrollable 5859 * containers allow the window to use resize mode since the container 5860 * will appropriately shrink. 5861 * 5862 * @attr ref android.R.styleable#View_isScrollContainer 5863 */ 5864 public void setScrollContainer(boolean isScrollContainer) { 5865 if (isScrollContainer) { 5866 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5867 mAttachInfo.mScrollContainers.add(this); 5868 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5869 } 5870 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5871 } else { 5872 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5873 mAttachInfo.mScrollContainers.remove(this); 5874 } 5875 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5876 } 5877 } 5878 5879 /** 5880 * Returns the quality of the drawing cache. 5881 * 5882 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5883 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5884 * 5885 * @see #setDrawingCacheQuality(int) 5886 * @see #setDrawingCacheEnabled(boolean) 5887 * @see #isDrawingCacheEnabled() 5888 * 5889 * @attr ref android.R.styleable#View_drawingCacheQuality 5890 */ 5891 @DrawingCacheQuality 5892 public int getDrawingCacheQuality() { 5893 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5894 } 5895 5896 /** 5897 * Set the drawing cache quality of this view. This value is used only when the 5898 * drawing cache is enabled 5899 * 5900 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5901 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5902 * 5903 * @see #getDrawingCacheQuality() 5904 * @see #setDrawingCacheEnabled(boolean) 5905 * @see #isDrawingCacheEnabled() 5906 * 5907 * @attr ref android.R.styleable#View_drawingCacheQuality 5908 */ 5909 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5910 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5911 } 5912 5913 /** 5914 * Returns whether the screen should remain on, corresponding to the current 5915 * value of {@link #KEEP_SCREEN_ON}. 5916 * 5917 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5918 * 5919 * @see #setKeepScreenOn(boolean) 5920 * 5921 * @attr ref android.R.styleable#View_keepScreenOn 5922 */ 5923 public boolean getKeepScreenOn() { 5924 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5925 } 5926 5927 /** 5928 * Controls whether the screen should remain on, modifying the 5929 * value of {@link #KEEP_SCREEN_ON}. 5930 * 5931 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5932 * 5933 * @see #getKeepScreenOn() 5934 * 5935 * @attr ref android.R.styleable#View_keepScreenOn 5936 */ 5937 public void setKeepScreenOn(boolean keepScreenOn) { 5938 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5939 } 5940 5941 /** 5942 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5943 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5944 * 5945 * @attr ref android.R.styleable#View_nextFocusLeft 5946 */ 5947 public int getNextFocusLeftId() { 5948 return mNextFocusLeftId; 5949 } 5950 5951 /** 5952 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5953 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5954 * decide automatically. 5955 * 5956 * @attr ref android.R.styleable#View_nextFocusLeft 5957 */ 5958 public void setNextFocusLeftId(int nextFocusLeftId) { 5959 mNextFocusLeftId = nextFocusLeftId; 5960 } 5961 5962 /** 5963 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5964 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5965 * 5966 * @attr ref android.R.styleable#View_nextFocusRight 5967 */ 5968 public int getNextFocusRightId() { 5969 return mNextFocusRightId; 5970 } 5971 5972 /** 5973 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5974 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5975 * decide automatically. 5976 * 5977 * @attr ref android.R.styleable#View_nextFocusRight 5978 */ 5979 public void setNextFocusRightId(int nextFocusRightId) { 5980 mNextFocusRightId = nextFocusRightId; 5981 } 5982 5983 /** 5984 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5985 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5986 * 5987 * @attr ref android.R.styleable#View_nextFocusUp 5988 */ 5989 public int getNextFocusUpId() { 5990 return mNextFocusUpId; 5991 } 5992 5993 /** 5994 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5995 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5996 * decide automatically. 5997 * 5998 * @attr ref android.R.styleable#View_nextFocusUp 5999 */ 6000 public void setNextFocusUpId(int nextFocusUpId) { 6001 mNextFocusUpId = nextFocusUpId; 6002 } 6003 6004 /** 6005 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6006 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6007 * 6008 * @attr ref android.R.styleable#View_nextFocusDown 6009 */ 6010 public int getNextFocusDownId() { 6011 return mNextFocusDownId; 6012 } 6013 6014 /** 6015 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6016 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6017 * decide automatically. 6018 * 6019 * @attr ref android.R.styleable#View_nextFocusDown 6020 */ 6021 public void setNextFocusDownId(int nextFocusDownId) { 6022 mNextFocusDownId = nextFocusDownId; 6023 } 6024 6025 /** 6026 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6027 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6028 * 6029 * @attr ref android.R.styleable#View_nextFocusForward 6030 */ 6031 public int getNextFocusForwardId() { 6032 return mNextFocusForwardId; 6033 } 6034 6035 /** 6036 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6037 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6038 * decide automatically. 6039 * 6040 * @attr ref android.R.styleable#View_nextFocusForward 6041 */ 6042 public void setNextFocusForwardId(int nextFocusForwardId) { 6043 mNextFocusForwardId = nextFocusForwardId; 6044 } 6045 6046 /** 6047 * Returns the visibility of this view and all of its ancestors 6048 * 6049 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6050 */ 6051 public boolean isShown() { 6052 View current = this; 6053 //noinspection ConstantConditions 6054 do { 6055 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6056 return false; 6057 } 6058 ViewParent parent = current.mParent; 6059 if (parent == null) { 6060 return false; // We are not attached to the view root 6061 } 6062 if (!(parent instanceof View)) { 6063 return true; 6064 } 6065 current = (View) parent; 6066 } while (current != null); 6067 6068 return false; 6069 } 6070 6071 /** 6072 * Called by the view hierarchy when the content insets for a window have 6073 * changed, to allow it to adjust its content to fit within those windows. 6074 * The content insets tell you the space that the status bar, input method, 6075 * and other system windows infringe on the application's window. 6076 * 6077 * <p>You do not normally need to deal with this function, since the default 6078 * window decoration given to applications takes care of applying it to the 6079 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6080 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6081 * and your content can be placed under those system elements. You can then 6082 * use this method within your view hierarchy if you have parts of your UI 6083 * which you would like to ensure are not being covered. 6084 * 6085 * <p>The default implementation of this method simply applies the content 6086 * insets to the view's padding, consuming that content (modifying the 6087 * insets to be 0), and returning true. This behavior is off by default, but can 6088 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6089 * 6090 * <p>This function's traversal down the hierarchy is depth-first. The same content 6091 * insets object is propagated down the hierarchy, so any changes made to it will 6092 * be seen by all following views (including potentially ones above in 6093 * the hierarchy since this is a depth-first traversal). The first view 6094 * that returns true will abort the entire traversal. 6095 * 6096 * <p>The default implementation works well for a situation where it is 6097 * used with a container that covers the entire window, allowing it to 6098 * apply the appropriate insets to its content on all edges. If you need 6099 * a more complicated layout (such as two different views fitting system 6100 * windows, one on the top of the window, and one on the bottom), 6101 * you can override the method and handle the insets however you would like. 6102 * Note that the insets provided by the framework are always relative to the 6103 * far edges of the window, not accounting for the location of the called view 6104 * within that window. (In fact when this method is called you do not yet know 6105 * where the layout will place the view, as it is done before layout happens.) 6106 * 6107 * <p>Note: unlike many View methods, there is no dispatch phase to this 6108 * call. If you are overriding it in a ViewGroup and want to allow the 6109 * call to continue to your children, you must be sure to call the super 6110 * implementation. 6111 * 6112 * <p>Here is a sample layout that makes use of fitting system windows 6113 * to have controls for a video view placed inside of the window decorations 6114 * that it hides and shows. This can be used with code like the second 6115 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6116 * 6117 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6118 * 6119 * @param insets Current content insets of the window. Prior to 6120 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6121 * the insets or else you and Android will be unhappy. 6122 * 6123 * @return {@code true} if this view applied the insets and it should not 6124 * continue propagating further down the hierarchy, {@code false} otherwise. 6125 * @see #getFitsSystemWindows() 6126 * @see #setFitsSystemWindows(boolean) 6127 * @see #setSystemUiVisibility(int) 6128 */ 6129 protected boolean fitSystemWindows(Rect insets) { 6130 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6131 mUserPaddingStart = UNDEFINED_PADDING; 6132 mUserPaddingEnd = UNDEFINED_PADDING; 6133 Rect localInsets = sThreadLocal.get(); 6134 if (localInsets == null) { 6135 localInsets = new Rect(); 6136 sThreadLocal.set(localInsets); 6137 } 6138 boolean res = computeFitSystemWindows(insets, localInsets); 6139 mUserPaddingLeftInitial = localInsets.left; 6140 mUserPaddingRightInitial = localInsets.right; 6141 internalSetPadding(localInsets.left, localInsets.top, 6142 localInsets.right, localInsets.bottom); 6143 return res; 6144 } 6145 return false; 6146 } 6147 6148 /** 6149 * @hide Compute the insets that should be consumed by this view and the ones 6150 * that should propagate to those under it. 6151 */ 6152 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6153 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6154 || mAttachInfo == null 6155 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6156 && !mAttachInfo.mOverscanRequested)) { 6157 outLocalInsets.set(inoutInsets); 6158 inoutInsets.set(0, 0, 0, 0); 6159 return true; 6160 } else { 6161 // The application wants to take care of fitting system window for 6162 // the content... however we still need to take care of any overscan here. 6163 final Rect overscan = mAttachInfo.mOverscanInsets; 6164 outLocalInsets.set(overscan); 6165 inoutInsets.left -= overscan.left; 6166 inoutInsets.top -= overscan.top; 6167 inoutInsets.right -= overscan.right; 6168 inoutInsets.bottom -= overscan.bottom; 6169 return false; 6170 } 6171 } 6172 6173 /** 6174 * Sets whether or not this view should account for system screen decorations 6175 * such as the status bar and inset its content; that is, controlling whether 6176 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6177 * executed. See that method for more details. 6178 * 6179 * <p>Note that if you are providing your own implementation of 6180 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6181 * flag to true -- your implementation will be overriding the default 6182 * implementation that checks this flag. 6183 * 6184 * @param fitSystemWindows If true, then the default implementation of 6185 * {@link #fitSystemWindows(Rect)} will be executed. 6186 * 6187 * @attr ref android.R.styleable#View_fitsSystemWindows 6188 * @see #getFitsSystemWindows() 6189 * @see #fitSystemWindows(Rect) 6190 * @see #setSystemUiVisibility(int) 6191 */ 6192 public void setFitsSystemWindows(boolean fitSystemWindows) { 6193 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6194 } 6195 6196 /** 6197 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6198 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6199 * will be executed. 6200 * 6201 * @return {@code true} if the default implementation of 6202 * {@link #fitSystemWindows(Rect)} will be executed. 6203 * 6204 * @attr ref android.R.styleable#View_fitsSystemWindows 6205 * @see #setFitsSystemWindows(boolean) 6206 * @see #fitSystemWindows(Rect) 6207 * @see #setSystemUiVisibility(int) 6208 */ 6209 public boolean getFitsSystemWindows() { 6210 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6211 } 6212 6213 /** @hide */ 6214 public boolean fitsSystemWindows() { 6215 return getFitsSystemWindows(); 6216 } 6217 6218 /** 6219 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6220 */ 6221 public void requestFitSystemWindows() { 6222 if (mParent != null) { 6223 mParent.requestFitSystemWindows(); 6224 } 6225 } 6226 6227 /** 6228 * For use by PhoneWindow to make its own system window fitting optional. 6229 * @hide 6230 */ 6231 public void makeOptionalFitsSystemWindows() { 6232 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6233 } 6234 6235 /** 6236 * Returns the visibility status for this view. 6237 * 6238 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6239 * @attr ref android.R.styleable#View_visibility 6240 */ 6241 @ViewDebug.ExportedProperty(mapping = { 6242 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6243 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6244 @ViewDebug.IntToString(from = GONE, to = "GONE") 6245 }) 6246 @Visibility 6247 public int getVisibility() { 6248 return mViewFlags & VISIBILITY_MASK; 6249 } 6250 6251 /** 6252 * Set the enabled state of this view. 6253 * 6254 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6255 * @attr ref android.R.styleable#View_visibility 6256 */ 6257 @RemotableViewMethod 6258 public void setVisibility(@Visibility int visibility) { 6259 setFlags(visibility, VISIBILITY_MASK); 6260 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6261 } 6262 6263 /** 6264 * Returns the enabled status for this view. The interpretation of the 6265 * enabled state varies by subclass. 6266 * 6267 * @return True if this view is enabled, false otherwise. 6268 */ 6269 @ViewDebug.ExportedProperty 6270 public boolean isEnabled() { 6271 return (mViewFlags & ENABLED_MASK) == ENABLED; 6272 } 6273 6274 /** 6275 * Set the enabled state of this view. The interpretation of the enabled 6276 * state varies by subclass. 6277 * 6278 * @param enabled True if this view is enabled, false otherwise. 6279 */ 6280 @RemotableViewMethod 6281 public void setEnabled(boolean enabled) { 6282 if (enabled == isEnabled()) return; 6283 6284 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6285 6286 /* 6287 * The View most likely has to change its appearance, so refresh 6288 * the drawable state. 6289 */ 6290 refreshDrawableState(); 6291 6292 // Invalidate too, since the default behavior for views is to be 6293 // be drawn at 50% alpha rather than to change the drawable. 6294 invalidate(true); 6295 6296 if (!enabled) { 6297 cancelPendingInputEvents(); 6298 } 6299 } 6300 6301 /** 6302 * Set whether this view can receive the focus. 6303 * 6304 * Setting this to false will also ensure that this view is not focusable 6305 * in touch mode. 6306 * 6307 * @param focusable If true, this view can receive the focus. 6308 * 6309 * @see #setFocusableInTouchMode(boolean) 6310 * @attr ref android.R.styleable#View_focusable 6311 */ 6312 public void setFocusable(boolean focusable) { 6313 if (!focusable) { 6314 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6315 } 6316 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6317 } 6318 6319 /** 6320 * Set whether this view can receive focus while in touch mode. 6321 * 6322 * Setting this to true will also ensure that this view is focusable. 6323 * 6324 * @param focusableInTouchMode If true, this view can receive the focus while 6325 * in touch mode. 6326 * 6327 * @see #setFocusable(boolean) 6328 * @attr ref android.R.styleable#View_focusableInTouchMode 6329 */ 6330 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6331 // Focusable in touch mode should always be set before the focusable flag 6332 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6333 // which, in touch mode, will not successfully request focus on this view 6334 // because the focusable in touch mode flag is not set 6335 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6336 if (focusableInTouchMode) { 6337 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6338 } 6339 } 6340 6341 /** 6342 * Set whether this view should have sound effects enabled for events such as 6343 * clicking and touching. 6344 * 6345 * <p>You may wish to disable sound effects for a view if you already play sounds, 6346 * for instance, a dial key that plays dtmf tones. 6347 * 6348 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6349 * @see #isSoundEffectsEnabled() 6350 * @see #playSoundEffect(int) 6351 * @attr ref android.R.styleable#View_soundEffectsEnabled 6352 */ 6353 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6354 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6355 } 6356 6357 /** 6358 * @return whether this view should have sound effects enabled for events such as 6359 * clicking and touching. 6360 * 6361 * @see #setSoundEffectsEnabled(boolean) 6362 * @see #playSoundEffect(int) 6363 * @attr ref android.R.styleable#View_soundEffectsEnabled 6364 */ 6365 @ViewDebug.ExportedProperty 6366 public boolean isSoundEffectsEnabled() { 6367 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6368 } 6369 6370 /** 6371 * Set whether this view should have haptic feedback for events such as 6372 * long presses. 6373 * 6374 * <p>You may wish to disable haptic feedback if your view already controls 6375 * its own haptic feedback. 6376 * 6377 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6378 * @see #isHapticFeedbackEnabled() 6379 * @see #performHapticFeedback(int) 6380 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6381 */ 6382 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6383 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6384 } 6385 6386 /** 6387 * @return whether this view should have haptic feedback enabled for events 6388 * long presses. 6389 * 6390 * @see #setHapticFeedbackEnabled(boolean) 6391 * @see #performHapticFeedback(int) 6392 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6393 */ 6394 @ViewDebug.ExportedProperty 6395 public boolean isHapticFeedbackEnabled() { 6396 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6397 } 6398 6399 /** 6400 * Returns the layout direction for this view. 6401 * 6402 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6403 * {@link #LAYOUT_DIRECTION_RTL}, 6404 * {@link #LAYOUT_DIRECTION_INHERIT} or 6405 * {@link #LAYOUT_DIRECTION_LOCALE}. 6406 * 6407 * @attr ref android.R.styleable#View_layoutDirection 6408 * 6409 * @hide 6410 */ 6411 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6412 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6413 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6414 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6415 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6416 }) 6417 @LayoutDir 6418 public int getRawLayoutDirection() { 6419 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6420 } 6421 6422 /** 6423 * Set the layout direction for this view. This will propagate a reset of layout direction 6424 * resolution to the view's children and resolve layout direction for this view. 6425 * 6426 * @param layoutDirection the layout direction to set. Should be one of: 6427 * 6428 * {@link #LAYOUT_DIRECTION_LTR}, 6429 * {@link #LAYOUT_DIRECTION_RTL}, 6430 * {@link #LAYOUT_DIRECTION_INHERIT}, 6431 * {@link #LAYOUT_DIRECTION_LOCALE}. 6432 * 6433 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6434 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6435 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6436 * 6437 * @attr ref android.R.styleable#View_layoutDirection 6438 */ 6439 @RemotableViewMethod 6440 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6441 if (getRawLayoutDirection() != layoutDirection) { 6442 // Reset the current layout direction and the resolved one 6443 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6444 resetRtlProperties(); 6445 // Set the new layout direction (filtered) 6446 mPrivateFlags2 |= 6447 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6448 // We need to resolve all RTL properties as they all depend on layout direction 6449 resolveRtlPropertiesIfNeeded(); 6450 requestLayout(); 6451 invalidate(true); 6452 } 6453 } 6454 6455 /** 6456 * Returns the resolved layout direction for this view. 6457 * 6458 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6459 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6460 * 6461 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6462 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6463 * 6464 * @attr ref android.R.styleable#View_layoutDirection 6465 */ 6466 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6467 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6468 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6469 }) 6470 @ResolvedLayoutDir 6471 public int getLayoutDirection() { 6472 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6473 if (targetSdkVersion < JELLY_BEAN_MR1) { 6474 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6475 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6476 } 6477 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6478 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6479 } 6480 6481 /** 6482 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6483 * layout attribute and/or the inherited value from the parent 6484 * 6485 * @return true if the layout is right-to-left. 6486 * 6487 * @hide 6488 */ 6489 @ViewDebug.ExportedProperty(category = "layout") 6490 public boolean isLayoutRtl() { 6491 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6492 } 6493 6494 /** 6495 * Indicates whether the view is currently tracking transient state that the 6496 * app should not need to concern itself with saving and restoring, but that 6497 * the framework should take special note to preserve when possible. 6498 * 6499 * <p>A view with transient state cannot be trivially rebound from an external 6500 * data source, such as an adapter binding item views in a list. This may be 6501 * because the view is performing an animation, tracking user selection 6502 * of content, or similar.</p> 6503 * 6504 * @return true if the view has transient state 6505 */ 6506 @ViewDebug.ExportedProperty(category = "layout") 6507 public boolean hasTransientState() { 6508 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6509 } 6510 6511 /** 6512 * Set whether this view is currently tracking transient state that the 6513 * framework should attempt to preserve when possible. This flag is reference counted, 6514 * so every call to setHasTransientState(true) should be paired with a later call 6515 * to setHasTransientState(false). 6516 * 6517 * <p>A view with transient state cannot be trivially rebound from an external 6518 * data source, such as an adapter binding item views in a list. This may be 6519 * because the view is performing an animation, tracking user selection 6520 * of content, or similar.</p> 6521 * 6522 * @param hasTransientState true if this view has transient state 6523 */ 6524 public void setHasTransientState(boolean hasTransientState) { 6525 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6526 mTransientStateCount - 1; 6527 if (mTransientStateCount < 0) { 6528 mTransientStateCount = 0; 6529 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6530 "unmatched pair of setHasTransientState calls"); 6531 } else if ((hasTransientState && mTransientStateCount == 1) || 6532 (!hasTransientState && mTransientStateCount == 0)) { 6533 // update flag if we've just incremented up from 0 or decremented down to 0 6534 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6535 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6536 if (mParent != null) { 6537 try { 6538 mParent.childHasTransientStateChanged(this, hasTransientState); 6539 } catch (AbstractMethodError e) { 6540 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6541 " does not fully implement ViewParent", e); 6542 } 6543 } 6544 } 6545 } 6546 6547 /** 6548 * Returns true if this view is currently attached to a window. 6549 */ 6550 public boolean isAttachedToWindow() { 6551 return mAttachInfo != null; 6552 } 6553 6554 /** 6555 * Returns true if this view has been through at least one layout since it 6556 * was last attached to or detached from a window. 6557 */ 6558 public boolean isLaidOut() { 6559 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6560 } 6561 6562 /** 6563 * If this view doesn't do any drawing on its own, set this flag to 6564 * allow further optimizations. By default, this flag is not set on 6565 * View, but could be set on some View subclasses such as ViewGroup. 6566 * 6567 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6568 * you should clear this flag. 6569 * 6570 * @param willNotDraw whether or not this View draw on its own 6571 */ 6572 public void setWillNotDraw(boolean willNotDraw) { 6573 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6574 } 6575 6576 /** 6577 * Returns whether or not this View draws on its own. 6578 * 6579 * @return true if this view has nothing to draw, false otherwise 6580 */ 6581 @ViewDebug.ExportedProperty(category = "drawing") 6582 public boolean willNotDraw() { 6583 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6584 } 6585 6586 /** 6587 * When a View's drawing cache is enabled, drawing is redirected to an 6588 * offscreen bitmap. Some views, like an ImageView, must be able to 6589 * bypass this mechanism if they already draw a single bitmap, to avoid 6590 * unnecessary usage of the memory. 6591 * 6592 * @param willNotCacheDrawing true if this view does not cache its 6593 * drawing, false otherwise 6594 */ 6595 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6596 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6597 } 6598 6599 /** 6600 * Returns whether or not this View can cache its drawing or not. 6601 * 6602 * @return true if this view does not cache its drawing, false otherwise 6603 */ 6604 @ViewDebug.ExportedProperty(category = "drawing") 6605 public boolean willNotCacheDrawing() { 6606 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6607 } 6608 6609 /** 6610 * Indicates whether this view reacts to click events or not. 6611 * 6612 * @return true if the view is clickable, false otherwise 6613 * 6614 * @see #setClickable(boolean) 6615 * @attr ref android.R.styleable#View_clickable 6616 */ 6617 @ViewDebug.ExportedProperty 6618 public boolean isClickable() { 6619 return (mViewFlags & CLICKABLE) == CLICKABLE; 6620 } 6621 6622 /** 6623 * Enables or disables click events for this view. When a view 6624 * is clickable it will change its state to "pressed" on every click. 6625 * Subclasses should set the view clickable to visually react to 6626 * user's clicks. 6627 * 6628 * @param clickable true to make the view clickable, false otherwise 6629 * 6630 * @see #isClickable() 6631 * @attr ref android.R.styleable#View_clickable 6632 */ 6633 public void setClickable(boolean clickable) { 6634 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6635 } 6636 6637 /** 6638 * Indicates whether this view reacts to long click events or not. 6639 * 6640 * @return true if the view is long clickable, false otherwise 6641 * 6642 * @see #setLongClickable(boolean) 6643 * @attr ref android.R.styleable#View_longClickable 6644 */ 6645 public boolean isLongClickable() { 6646 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6647 } 6648 6649 /** 6650 * Enables or disables long click events for this view. When a view is long 6651 * clickable it reacts to the user holding down the button for a longer 6652 * duration than a tap. This event can either launch the listener or a 6653 * context menu. 6654 * 6655 * @param longClickable true to make the view long clickable, false otherwise 6656 * @see #isLongClickable() 6657 * @attr ref android.R.styleable#View_longClickable 6658 */ 6659 public void setLongClickable(boolean longClickable) { 6660 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6661 } 6662 6663 /** 6664 * Sets the pressed state for this view. 6665 * 6666 * @see #isClickable() 6667 * @see #setClickable(boolean) 6668 * 6669 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6670 * the View's internal state from a previously set "pressed" state. 6671 */ 6672 public void setPressed(boolean pressed) { 6673 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6674 6675 if (pressed) { 6676 mPrivateFlags |= PFLAG_PRESSED; 6677 } else { 6678 mPrivateFlags &= ~PFLAG_PRESSED; 6679 } 6680 6681 if (needsRefresh) { 6682 refreshDrawableState(); 6683 } 6684 dispatchSetPressed(pressed); 6685 } 6686 6687 /** 6688 * Dispatch setPressed to all of this View's children. 6689 * 6690 * @see #setPressed(boolean) 6691 * 6692 * @param pressed The new pressed state 6693 */ 6694 protected void dispatchSetPressed(boolean pressed) { 6695 } 6696 6697 /** 6698 * Indicates whether the view is currently in pressed state. Unless 6699 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6700 * the pressed state. 6701 * 6702 * @see #setPressed(boolean) 6703 * @see #isClickable() 6704 * @see #setClickable(boolean) 6705 * 6706 * @return true if the view is currently pressed, false otherwise 6707 */ 6708 public boolean isPressed() { 6709 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6710 } 6711 6712 /** 6713 * Indicates whether this view will save its state (that is, 6714 * whether its {@link #onSaveInstanceState} method will be called). 6715 * 6716 * @return Returns true if the view state saving is enabled, else false. 6717 * 6718 * @see #setSaveEnabled(boolean) 6719 * @attr ref android.R.styleable#View_saveEnabled 6720 */ 6721 public boolean isSaveEnabled() { 6722 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6723 } 6724 6725 /** 6726 * Controls whether the saving of this view's state is 6727 * enabled (that is, whether its {@link #onSaveInstanceState} method 6728 * will be called). Note that even if freezing is enabled, the 6729 * view still must have an id assigned to it (via {@link #setId(int)}) 6730 * for its state to be saved. This flag can only disable the 6731 * saving of this view; any child views may still have their state saved. 6732 * 6733 * @param enabled Set to false to <em>disable</em> state saving, or true 6734 * (the default) to allow it. 6735 * 6736 * @see #isSaveEnabled() 6737 * @see #setId(int) 6738 * @see #onSaveInstanceState() 6739 * @attr ref android.R.styleable#View_saveEnabled 6740 */ 6741 public void setSaveEnabled(boolean enabled) { 6742 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6743 } 6744 6745 /** 6746 * Gets whether the framework should discard touches when the view's 6747 * window is obscured by another visible window. 6748 * Refer to the {@link View} security documentation for more details. 6749 * 6750 * @return True if touch filtering is enabled. 6751 * 6752 * @see #setFilterTouchesWhenObscured(boolean) 6753 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6754 */ 6755 @ViewDebug.ExportedProperty 6756 public boolean getFilterTouchesWhenObscured() { 6757 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6758 } 6759 6760 /** 6761 * Sets whether the framework should discard touches when the view's 6762 * window is obscured by another visible window. 6763 * Refer to the {@link View} security documentation for more details. 6764 * 6765 * @param enabled True if touch filtering should be enabled. 6766 * 6767 * @see #getFilterTouchesWhenObscured 6768 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6769 */ 6770 public void setFilterTouchesWhenObscured(boolean enabled) { 6771 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 6772 FILTER_TOUCHES_WHEN_OBSCURED); 6773 } 6774 6775 /** 6776 * Indicates whether the entire hierarchy under this view will save its 6777 * state when a state saving traversal occurs from its parent. The default 6778 * is true; if false, these views will not be saved unless 6779 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6780 * 6781 * @return Returns true if the view state saving from parent is enabled, else false. 6782 * 6783 * @see #setSaveFromParentEnabled(boolean) 6784 */ 6785 public boolean isSaveFromParentEnabled() { 6786 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6787 } 6788 6789 /** 6790 * Controls whether the entire hierarchy under this view will save its 6791 * state when a state saving traversal occurs from its parent. The default 6792 * is true; if false, these views will not be saved unless 6793 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6794 * 6795 * @param enabled Set to false to <em>disable</em> state saving, or true 6796 * (the default) to allow it. 6797 * 6798 * @see #isSaveFromParentEnabled() 6799 * @see #setId(int) 6800 * @see #onSaveInstanceState() 6801 */ 6802 public void setSaveFromParentEnabled(boolean enabled) { 6803 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6804 } 6805 6806 6807 /** 6808 * Returns whether this View is able to take focus. 6809 * 6810 * @return True if this view can take focus, or false otherwise. 6811 * @attr ref android.R.styleable#View_focusable 6812 */ 6813 @ViewDebug.ExportedProperty(category = "focus") 6814 public final boolean isFocusable() { 6815 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6816 } 6817 6818 /** 6819 * When a view is focusable, it may not want to take focus when in touch mode. 6820 * For example, a button would like focus when the user is navigating via a D-pad 6821 * so that the user can click on it, but once the user starts touching the screen, 6822 * the button shouldn't take focus 6823 * @return Whether the view is focusable in touch mode. 6824 * @attr ref android.R.styleable#View_focusableInTouchMode 6825 */ 6826 @ViewDebug.ExportedProperty 6827 public final boolean isFocusableInTouchMode() { 6828 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6829 } 6830 6831 /** 6832 * Find the nearest view in the specified direction that can take focus. 6833 * This does not actually give focus to that view. 6834 * 6835 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6836 * 6837 * @return The nearest focusable in the specified direction, or null if none 6838 * can be found. 6839 */ 6840 public View focusSearch(@FocusRealDirection int direction) { 6841 if (mParent != null) { 6842 return mParent.focusSearch(this, direction); 6843 } else { 6844 return null; 6845 } 6846 } 6847 6848 /** 6849 * This method is the last chance for the focused view and its ancestors to 6850 * respond to an arrow key. This is called when the focused view did not 6851 * consume the key internally, nor could the view system find a new view in 6852 * the requested direction to give focus to. 6853 * 6854 * @param focused The currently focused view. 6855 * @param direction The direction focus wants to move. One of FOCUS_UP, 6856 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6857 * @return True if the this view consumed this unhandled move. 6858 */ 6859 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 6860 return false; 6861 } 6862 6863 /** 6864 * If a user manually specified the next view id for a particular direction, 6865 * use the root to look up the view. 6866 * @param root The root view of the hierarchy containing this view. 6867 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6868 * or FOCUS_BACKWARD. 6869 * @return The user specified next view, or null if there is none. 6870 */ 6871 View findUserSetNextFocus(View root, @FocusDirection int direction) { 6872 switch (direction) { 6873 case FOCUS_LEFT: 6874 if (mNextFocusLeftId == View.NO_ID) return null; 6875 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6876 case FOCUS_RIGHT: 6877 if (mNextFocusRightId == View.NO_ID) return null; 6878 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6879 case FOCUS_UP: 6880 if (mNextFocusUpId == View.NO_ID) return null; 6881 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6882 case FOCUS_DOWN: 6883 if (mNextFocusDownId == View.NO_ID) return null; 6884 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6885 case FOCUS_FORWARD: 6886 if (mNextFocusForwardId == View.NO_ID) return null; 6887 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6888 case FOCUS_BACKWARD: { 6889 if (mID == View.NO_ID) return null; 6890 final int id = mID; 6891 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6892 @Override 6893 public boolean apply(View t) { 6894 return t.mNextFocusForwardId == id; 6895 } 6896 }); 6897 } 6898 } 6899 return null; 6900 } 6901 6902 private View findViewInsideOutShouldExist(View root, int id) { 6903 if (mMatchIdPredicate == null) { 6904 mMatchIdPredicate = new MatchIdPredicate(); 6905 } 6906 mMatchIdPredicate.mId = id; 6907 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6908 if (result == null) { 6909 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6910 } 6911 return result; 6912 } 6913 6914 /** 6915 * Find and return all focusable views that are descendants of this view, 6916 * possibly including this view if it is focusable itself. 6917 * 6918 * @param direction The direction of the focus 6919 * @return A list of focusable views 6920 */ 6921 public ArrayList<View> getFocusables(@FocusDirection int direction) { 6922 ArrayList<View> result = new ArrayList<View>(24); 6923 addFocusables(result, direction); 6924 return result; 6925 } 6926 6927 /** 6928 * Add any focusable views that are descendants of this view (possibly 6929 * including this view if it is focusable itself) to views. If we are in touch mode, 6930 * only add views that are also focusable in touch mode. 6931 * 6932 * @param views Focusable views found so far 6933 * @param direction The direction of the focus 6934 */ 6935 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 6936 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6937 } 6938 6939 /** 6940 * Adds any focusable views that are descendants of this view (possibly 6941 * including this view if it is focusable itself) to views. This method 6942 * adds all focusable views regardless if we are in touch mode or 6943 * only views focusable in touch mode if we are in touch mode or 6944 * only views that can take accessibility focus if accessibility is enabeld 6945 * depending on the focusable mode paramater. 6946 * 6947 * @param views Focusable views found so far or null if all we are interested is 6948 * the number of focusables. 6949 * @param direction The direction of the focus. 6950 * @param focusableMode The type of focusables to be added. 6951 * 6952 * @see #FOCUSABLES_ALL 6953 * @see #FOCUSABLES_TOUCH_MODE 6954 */ 6955 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 6956 @FocusableMode int focusableMode) { 6957 if (views == null) { 6958 return; 6959 } 6960 if (!isFocusable()) { 6961 return; 6962 } 6963 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6964 && isInTouchMode() && !isFocusableInTouchMode()) { 6965 return; 6966 } 6967 views.add(this); 6968 } 6969 6970 /** 6971 * Finds the Views that contain given text. The containment is case insensitive. 6972 * The search is performed by either the text that the View renders or the content 6973 * description that describes the view for accessibility purposes and the view does 6974 * not render or both. Clients can specify how the search is to be performed via 6975 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 6976 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 6977 * 6978 * @param outViews The output list of matching Views. 6979 * @param searched The text to match against. 6980 * 6981 * @see #FIND_VIEWS_WITH_TEXT 6982 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 6983 * @see #setContentDescription(CharSequence) 6984 */ 6985 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 6986 @FindViewFlags int flags) { 6987 if (getAccessibilityNodeProvider() != null) { 6988 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 6989 outViews.add(this); 6990 } 6991 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 6992 && (searched != null && searched.length() > 0) 6993 && (mContentDescription != null && mContentDescription.length() > 0)) { 6994 String searchedLowerCase = searched.toString().toLowerCase(); 6995 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 6996 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 6997 outViews.add(this); 6998 } 6999 } 7000 } 7001 7002 /** 7003 * Find and return all touchable views that are descendants of this view, 7004 * possibly including this view if it is touchable itself. 7005 * 7006 * @return A list of touchable views 7007 */ 7008 public ArrayList<View> getTouchables() { 7009 ArrayList<View> result = new ArrayList<View>(); 7010 addTouchables(result); 7011 return result; 7012 } 7013 7014 /** 7015 * Add any touchable views that are descendants of this view (possibly 7016 * including this view if it is touchable itself) to views. 7017 * 7018 * @param views Touchable views found so far 7019 */ 7020 public void addTouchables(ArrayList<View> views) { 7021 final int viewFlags = mViewFlags; 7022 7023 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7024 && (viewFlags & ENABLED_MASK) == ENABLED) { 7025 views.add(this); 7026 } 7027 } 7028 7029 /** 7030 * Returns whether this View is accessibility focused. 7031 * 7032 * @return True if this View is accessibility focused. 7033 */ 7034 public boolean isAccessibilityFocused() { 7035 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7036 } 7037 7038 /** 7039 * Call this to try to give accessibility focus to this view. 7040 * 7041 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7042 * returns false or the view is no visible or the view already has accessibility 7043 * focus. 7044 * 7045 * See also {@link #focusSearch(int)}, which is what you call to say that you 7046 * have focus, and you want your parent to look for the next one. 7047 * 7048 * @return Whether this view actually took accessibility focus. 7049 * 7050 * @hide 7051 */ 7052 public boolean requestAccessibilityFocus() { 7053 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7054 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7055 return false; 7056 } 7057 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7058 return false; 7059 } 7060 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7061 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7062 ViewRootImpl viewRootImpl = getViewRootImpl(); 7063 if (viewRootImpl != null) { 7064 viewRootImpl.setAccessibilityFocus(this, null); 7065 } 7066 invalidate(); 7067 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7068 return true; 7069 } 7070 return false; 7071 } 7072 7073 /** 7074 * Call this to try to clear accessibility focus of this view. 7075 * 7076 * See also {@link #focusSearch(int)}, which is what you call to say that you 7077 * have focus, and you want your parent to look for the next one. 7078 * 7079 * @hide 7080 */ 7081 public void clearAccessibilityFocus() { 7082 clearAccessibilityFocusNoCallbacks(); 7083 // Clear the global reference of accessibility focus if this 7084 // view or any of its descendants had accessibility focus. 7085 ViewRootImpl viewRootImpl = getViewRootImpl(); 7086 if (viewRootImpl != null) { 7087 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7088 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7089 viewRootImpl.setAccessibilityFocus(null, null); 7090 } 7091 } 7092 } 7093 7094 private void sendAccessibilityHoverEvent(int eventType) { 7095 // Since we are not delivering to a client accessibility events from not 7096 // important views (unless the clinet request that) we need to fire the 7097 // event from the deepest view exposed to the client. As a consequence if 7098 // the user crosses a not exposed view the client will see enter and exit 7099 // of the exposed predecessor followed by and enter and exit of that same 7100 // predecessor when entering and exiting the not exposed descendant. This 7101 // is fine since the client has a clear idea which view is hovered at the 7102 // price of a couple more events being sent. This is a simple and 7103 // working solution. 7104 View source = this; 7105 while (true) { 7106 if (source.includeForAccessibility()) { 7107 source.sendAccessibilityEvent(eventType); 7108 return; 7109 } 7110 ViewParent parent = source.getParent(); 7111 if (parent instanceof View) { 7112 source = (View) parent; 7113 } else { 7114 return; 7115 } 7116 } 7117 } 7118 7119 /** 7120 * Clears accessibility focus without calling any callback methods 7121 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7122 * is used for clearing accessibility focus when giving this focus to 7123 * another view. 7124 */ 7125 void clearAccessibilityFocusNoCallbacks() { 7126 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7127 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7128 invalidate(); 7129 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7130 } 7131 } 7132 7133 /** 7134 * Call this to try to give focus to a specific view or to one of its 7135 * descendants. 7136 * 7137 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7138 * false), or if it is focusable and it is not focusable in touch mode 7139 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7140 * 7141 * See also {@link #focusSearch(int)}, which is what you call to say that you 7142 * have focus, and you want your parent to look for the next one. 7143 * 7144 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7145 * {@link #FOCUS_DOWN} and <code>null</code>. 7146 * 7147 * @return Whether this view or one of its descendants actually took focus. 7148 */ 7149 public final boolean requestFocus() { 7150 return requestFocus(View.FOCUS_DOWN); 7151 } 7152 7153 /** 7154 * Call this to try to give focus to a specific view or to one of its 7155 * descendants and give it a hint about what direction focus is heading. 7156 * 7157 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7158 * false), or if it is focusable and it is not focusable in touch mode 7159 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7160 * 7161 * See also {@link #focusSearch(int)}, which is what you call to say that you 7162 * have focus, and you want your parent to look for the next one. 7163 * 7164 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7165 * <code>null</code> set for the previously focused rectangle. 7166 * 7167 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7168 * @return Whether this view or one of its descendants actually took focus. 7169 */ 7170 public final boolean requestFocus(int direction) { 7171 return requestFocus(direction, null); 7172 } 7173 7174 /** 7175 * Call this to try to give focus to a specific view or to one of its descendants 7176 * and give it hints about the direction and a specific rectangle that the focus 7177 * is coming from. The rectangle can help give larger views a finer grained hint 7178 * about where focus is coming from, and therefore, where to show selection, or 7179 * forward focus change internally. 7180 * 7181 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7182 * false), or if it is focusable and it is not focusable in touch mode 7183 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7184 * 7185 * A View will not take focus if it is not visible. 7186 * 7187 * A View will not take focus if one of its parents has 7188 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7189 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7190 * 7191 * See also {@link #focusSearch(int)}, which is what you call to say that you 7192 * have focus, and you want your parent to look for the next one. 7193 * 7194 * You may wish to override this method if your custom {@link View} has an internal 7195 * {@link View} that it wishes to forward the request to. 7196 * 7197 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7198 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7199 * to give a finer grained hint about where focus is coming from. May be null 7200 * if there is no hint. 7201 * @return Whether this view or one of its descendants actually took focus. 7202 */ 7203 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7204 return requestFocusNoSearch(direction, previouslyFocusedRect); 7205 } 7206 7207 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7208 // need to be focusable 7209 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7210 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7211 return false; 7212 } 7213 7214 // need to be focusable in touch mode if in touch mode 7215 if (isInTouchMode() && 7216 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7217 return false; 7218 } 7219 7220 // need to not have any parents blocking us 7221 if (hasAncestorThatBlocksDescendantFocus()) { 7222 return false; 7223 } 7224 7225 handleFocusGainInternal(direction, previouslyFocusedRect); 7226 return true; 7227 } 7228 7229 /** 7230 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7231 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7232 * touch mode to request focus when they are touched. 7233 * 7234 * @return Whether this view or one of its descendants actually took focus. 7235 * 7236 * @see #isInTouchMode() 7237 * 7238 */ 7239 public final boolean requestFocusFromTouch() { 7240 // Leave touch mode if we need to 7241 if (isInTouchMode()) { 7242 ViewRootImpl viewRoot = getViewRootImpl(); 7243 if (viewRoot != null) { 7244 viewRoot.ensureTouchMode(false); 7245 } 7246 } 7247 return requestFocus(View.FOCUS_DOWN); 7248 } 7249 7250 /** 7251 * @return Whether any ancestor of this view blocks descendant focus. 7252 */ 7253 private boolean hasAncestorThatBlocksDescendantFocus() { 7254 ViewParent ancestor = mParent; 7255 while (ancestor instanceof ViewGroup) { 7256 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7257 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7258 return true; 7259 } else { 7260 ancestor = vgAncestor.getParent(); 7261 } 7262 } 7263 return false; 7264 } 7265 7266 /** 7267 * Gets the mode for determining whether this View is important for accessibility 7268 * which is if it fires accessibility events and if it is reported to 7269 * accessibility services that query the screen. 7270 * 7271 * @return The mode for determining whether a View is important for accessibility. 7272 * 7273 * @attr ref android.R.styleable#View_importantForAccessibility 7274 * 7275 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7276 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7277 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7278 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7279 */ 7280 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7281 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7282 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7283 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7284 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7285 to = "noHideDescendants") 7286 }) 7287 public int getImportantForAccessibility() { 7288 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7289 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7290 } 7291 7292 /** 7293 * Sets the live region mode for this view. This indicates to accessibility 7294 * services whether they should automatically notify the user about changes 7295 * to the view's content description or text, or to the content descriptions 7296 * or text of the view's children (where applicable). 7297 * <p> 7298 * For example, in a login screen with a TextView that displays an "incorrect 7299 * password" notification, that view should be marked as a live region with 7300 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7301 * <p> 7302 * To disable change notifications for this view, use 7303 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7304 * mode for most views. 7305 * <p> 7306 * To indicate that the user should be notified of changes, use 7307 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7308 * <p> 7309 * If the view's changes should interrupt ongoing speech and notify the user 7310 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7311 * 7312 * @param mode The live region mode for this view, one of: 7313 * <ul> 7314 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7315 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7316 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7317 * </ul> 7318 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7319 */ 7320 public void setAccessibilityLiveRegion(int mode) { 7321 if (mode != getAccessibilityLiveRegion()) { 7322 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7323 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7324 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7325 notifyViewAccessibilityStateChangedIfNeeded( 7326 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7327 } 7328 } 7329 7330 /** 7331 * Gets the live region mode for this View. 7332 * 7333 * @return The live region mode for the view. 7334 * 7335 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7336 * 7337 * @see #setAccessibilityLiveRegion(int) 7338 */ 7339 public int getAccessibilityLiveRegion() { 7340 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7341 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7342 } 7343 7344 /** 7345 * Sets how to determine whether this view is important for accessibility 7346 * which is if it fires accessibility events and if it is reported to 7347 * accessibility services that query the screen. 7348 * 7349 * @param mode How to determine whether this view is important for accessibility. 7350 * 7351 * @attr ref android.R.styleable#View_importantForAccessibility 7352 * 7353 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7354 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7355 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7356 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7357 */ 7358 public void setImportantForAccessibility(int mode) { 7359 final int oldMode = getImportantForAccessibility(); 7360 if (mode != oldMode) { 7361 // If we're moving between AUTO and another state, we might not need 7362 // to send a subtree changed notification. We'll store the computed 7363 // importance, since we'll need to check it later to make sure. 7364 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7365 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7366 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7367 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7368 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7369 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7370 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7371 notifySubtreeAccessibilityStateChangedIfNeeded(); 7372 } else { 7373 notifyViewAccessibilityStateChangedIfNeeded( 7374 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7375 } 7376 } 7377 } 7378 7379 /** 7380 * Computes whether this view should be exposed for accessibility. In 7381 * general, views that are interactive or provide information are exposed 7382 * while views that serve only as containers are hidden. 7383 * <p> 7384 * If an ancestor of this view has importance 7385 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7386 * returns <code>false</code>. 7387 * <p> 7388 * Otherwise, the value is computed according to the view's 7389 * {@link #getImportantForAccessibility()} value: 7390 * <ol> 7391 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7392 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7393 * </code> 7394 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7395 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7396 * view satisfies any of the following: 7397 * <ul> 7398 * <li>Is actionable, e.g. {@link #isClickable()}, 7399 * {@link #isLongClickable()}, or {@link #isFocusable()} 7400 * <li>Has an {@link AccessibilityDelegate} 7401 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7402 * {@link OnKeyListener}, etc. 7403 * <li>Is an accessibility live region, e.g. 7404 * {@link #getAccessibilityLiveRegion()} is not 7405 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7406 * </ul> 7407 * </ol> 7408 * 7409 * @return Whether the view is exposed for accessibility. 7410 * @see #setImportantForAccessibility(int) 7411 * @see #getImportantForAccessibility() 7412 */ 7413 public boolean isImportantForAccessibility() { 7414 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7415 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7416 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7417 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7418 return false; 7419 } 7420 7421 // Check parent mode to ensure we're not hidden. 7422 ViewParent parent = mParent; 7423 while (parent instanceof View) { 7424 if (((View) parent).getImportantForAccessibility() 7425 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7426 return false; 7427 } 7428 parent = parent.getParent(); 7429 } 7430 7431 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7432 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7433 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7434 } 7435 7436 /** 7437 * Gets the parent for accessibility purposes. Note that the parent for 7438 * accessibility is not necessary the immediate parent. It is the first 7439 * predecessor that is important for accessibility. 7440 * 7441 * @return The parent for accessibility purposes. 7442 */ 7443 public ViewParent getParentForAccessibility() { 7444 if (mParent instanceof View) { 7445 View parentView = (View) mParent; 7446 if (parentView.includeForAccessibility()) { 7447 return mParent; 7448 } else { 7449 return mParent.getParentForAccessibility(); 7450 } 7451 } 7452 return null; 7453 } 7454 7455 /** 7456 * Adds the children of a given View for accessibility. Since some Views are 7457 * not important for accessibility the children for accessibility are not 7458 * necessarily direct children of the view, rather they are the first level of 7459 * descendants important for accessibility. 7460 * 7461 * @param children The list of children for accessibility. 7462 */ 7463 public void addChildrenForAccessibility(ArrayList<View> children) { 7464 7465 } 7466 7467 /** 7468 * Whether to regard this view for accessibility. A view is regarded for 7469 * accessibility if it is important for accessibility or the querying 7470 * accessibility service has explicitly requested that view not 7471 * important for accessibility are regarded. 7472 * 7473 * @return Whether to regard the view for accessibility. 7474 * 7475 * @hide 7476 */ 7477 public boolean includeForAccessibility() { 7478 if (mAttachInfo != null) { 7479 return (mAttachInfo.mAccessibilityFetchFlags 7480 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7481 || isImportantForAccessibility(); 7482 } 7483 return false; 7484 } 7485 7486 /** 7487 * Returns whether the View is considered actionable from 7488 * accessibility perspective. Such view are important for 7489 * accessibility. 7490 * 7491 * @return True if the view is actionable for accessibility. 7492 * 7493 * @hide 7494 */ 7495 public boolean isActionableForAccessibility() { 7496 return (isClickable() || isLongClickable() || isFocusable()); 7497 } 7498 7499 /** 7500 * Returns whether the View has registered callbacks which makes it 7501 * important for accessibility. 7502 * 7503 * @return True if the view is actionable for accessibility. 7504 */ 7505 private boolean hasListenersForAccessibility() { 7506 ListenerInfo info = getListenerInfo(); 7507 return mTouchDelegate != null || info.mOnKeyListener != null 7508 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7509 || info.mOnHoverListener != null || info.mOnDragListener != null; 7510 } 7511 7512 /** 7513 * Notifies that the accessibility state of this view changed. The change 7514 * is local to this view and does not represent structural changes such 7515 * as children and parent. For example, the view became focusable. The 7516 * notification is at at most once every 7517 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7518 * to avoid unnecessary load to the system. Also once a view has a pending 7519 * notification this method is a NOP until the notification has been sent. 7520 * 7521 * @hide 7522 */ 7523 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7524 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7525 return; 7526 } 7527 if (mSendViewStateChangedAccessibilityEvent == null) { 7528 mSendViewStateChangedAccessibilityEvent = 7529 new SendViewStateChangedAccessibilityEvent(); 7530 } 7531 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7532 } 7533 7534 /** 7535 * Notifies that the accessibility state of this view changed. The change 7536 * is *not* local to this view and does represent structural changes such 7537 * as children and parent. For example, the view size changed. The 7538 * notification is at at most once every 7539 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7540 * to avoid unnecessary load to the system. Also once a view has a pending 7541 * notifucation this method is a NOP until the notification has been sent. 7542 * 7543 * @hide 7544 */ 7545 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7546 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7547 return; 7548 } 7549 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7550 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7551 if (mParent != null) { 7552 try { 7553 mParent.notifySubtreeAccessibilityStateChanged( 7554 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7555 } catch (AbstractMethodError e) { 7556 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7557 " does not fully implement ViewParent", e); 7558 } 7559 } 7560 } 7561 } 7562 7563 /** 7564 * Reset the flag indicating the accessibility state of the subtree rooted 7565 * at this view changed. 7566 */ 7567 void resetSubtreeAccessibilityStateChanged() { 7568 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7569 } 7570 7571 /** 7572 * Performs the specified accessibility action on the view. For 7573 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7574 * <p> 7575 * If an {@link AccessibilityDelegate} has been specified via calling 7576 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7577 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7578 * is responsible for handling this call. 7579 * </p> 7580 * 7581 * @param action The action to perform. 7582 * @param arguments Optional action arguments. 7583 * @return Whether the action was performed. 7584 */ 7585 public boolean performAccessibilityAction(int action, Bundle arguments) { 7586 if (mAccessibilityDelegate != null) { 7587 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7588 } else { 7589 return performAccessibilityActionInternal(action, arguments); 7590 } 7591 } 7592 7593 /** 7594 * @see #performAccessibilityAction(int, Bundle) 7595 * 7596 * Note: Called from the default {@link AccessibilityDelegate}. 7597 */ 7598 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7599 switch (action) { 7600 case AccessibilityNodeInfo.ACTION_CLICK: { 7601 if (isClickable()) { 7602 performClick(); 7603 return true; 7604 } 7605 } break; 7606 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7607 if (isLongClickable()) { 7608 performLongClick(); 7609 return true; 7610 } 7611 } break; 7612 case AccessibilityNodeInfo.ACTION_FOCUS: { 7613 if (!hasFocus()) { 7614 // Get out of touch mode since accessibility 7615 // wants to move focus around. 7616 getViewRootImpl().ensureTouchMode(false); 7617 return requestFocus(); 7618 } 7619 } break; 7620 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7621 if (hasFocus()) { 7622 clearFocus(); 7623 return !isFocused(); 7624 } 7625 } break; 7626 case AccessibilityNodeInfo.ACTION_SELECT: { 7627 if (!isSelected()) { 7628 setSelected(true); 7629 return isSelected(); 7630 } 7631 } break; 7632 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7633 if (isSelected()) { 7634 setSelected(false); 7635 return !isSelected(); 7636 } 7637 } break; 7638 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7639 if (!isAccessibilityFocused()) { 7640 return requestAccessibilityFocus(); 7641 } 7642 } break; 7643 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7644 if (isAccessibilityFocused()) { 7645 clearAccessibilityFocus(); 7646 return true; 7647 } 7648 } break; 7649 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7650 if (arguments != null) { 7651 final int granularity = arguments.getInt( 7652 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7653 final boolean extendSelection = arguments.getBoolean( 7654 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7655 return traverseAtGranularity(granularity, true, extendSelection); 7656 } 7657 } break; 7658 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7659 if (arguments != null) { 7660 final int granularity = arguments.getInt( 7661 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7662 final boolean extendSelection = arguments.getBoolean( 7663 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7664 return traverseAtGranularity(granularity, false, extendSelection); 7665 } 7666 } break; 7667 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7668 CharSequence text = getIterableTextForAccessibility(); 7669 if (text == null) { 7670 return false; 7671 } 7672 final int start = (arguments != null) ? arguments.getInt( 7673 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7674 final int end = (arguments != null) ? arguments.getInt( 7675 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7676 // Only cursor position can be specified (selection length == 0) 7677 if ((getAccessibilitySelectionStart() != start 7678 || getAccessibilitySelectionEnd() != end) 7679 && (start == end)) { 7680 setAccessibilitySelection(start, end); 7681 notifyViewAccessibilityStateChangedIfNeeded( 7682 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7683 return true; 7684 } 7685 } break; 7686 } 7687 return false; 7688 } 7689 7690 private boolean traverseAtGranularity(int granularity, boolean forward, 7691 boolean extendSelection) { 7692 CharSequence text = getIterableTextForAccessibility(); 7693 if (text == null || text.length() == 0) { 7694 return false; 7695 } 7696 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7697 if (iterator == null) { 7698 return false; 7699 } 7700 int current = getAccessibilitySelectionEnd(); 7701 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7702 current = forward ? 0 : text.length(); 7703 } 7704 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7705 if (range == null) { 7706 return false; 7707 } 7708 final int segmentStart = range[0]; 7709 final int segmentEnd = range[1]; 7710 int selectionStart; 7711 int selectionEnd; 7712 if (extendSelection && isAccessibilitySelectionExtendable()) { 7713 selectionStart = getAccessibilitySelectionStart(); 7714 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7715 selectionStart = forward ? segmentStart : segmentEnd; 7716 } 7717 selectionEnd = forward ? segmentEnd : segmentStart; 7718 } else { 7719 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7720 } 7721 setAccessibilitySelection(selectionStart, selectionEnd); 7722 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7723 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7724 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7725 return true; 7726 } 7727 7728 /** 7729 * Gets the text reported for accessibility purposes. 7730 * 7731 * @return The accessibility text. 7732 * 7733 * @hide 7734 */ 7735 public CharSequence getIterableTextForAccessibility() { 7736 return getContentDescription(); 7737 } 7738 7739 /** 7740 * Gets whether accessibility selection can be extended. 7741 * 7742 * @return If selection is extensible. 7743 * 7744 * @hide 7745 */ 7746 public boolean isAccessibilitySelectionExtendable() { 7747 return false; 7748 } 7749 7750 /** 7751 * @hide 7752 */ 7753 public int getAccessibilitySelectionStart() { 7754 return mAccessibilityCursorPosition; 7755 } 7756 7757 /** 7758 * @hide 7759 */ 7760 public int getAccessibilitySelectionEnd() { 7761 return getAccessibilitySelectionStart(); 7762 } 7763 7764 /** 7765 * @hide 7766 */ 7767 public void setAccessibilitySelection(int start, int end) { 7768 if (start == end && end == mAccessibilityCursorPosition) { 7769 return; 7770 } 7771 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7772 mAccessibilityCursorPosition = start; 7773 } else { 7774 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7775 } 7776 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7777 } 7778 7779 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7780 int fromIndex, int toIndex) { 7781 if (mParent == null) { 7782 return; 7783 } 7784 AccessibilityEvent event = AccessibilityEvent.obtain( 7785 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7786 onInitializeAccessibilityEvent(event); 7787 onPopulateAccessibilityEvent(event); 7788 event.setFromIndex(fromIndex); 7789 event.setToIndex(toIndex); 7790 event.setAction(action); 7791 event.setMovementGranularity(granularity); 7792 mParent.requestSendAccessibilityEvent(this, event); 7793 } 7794 7795 /** 7796 * @hide 7797 */ 7798 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7799 switch (granularity) { 7800 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7801 CharSequence text = getIterableTextForAccessibility(); 7802 if (text != null && text.length() > 0) { 7803 CharacterTextSegmentIterator iterator = 7804 CharacterTextSegmentIterator.getInstance( 7805 mContext.getResources().getConfiguration().locale); 7806 iterator.initialize(text.toString()); 7807 return iterator; 7808 } 7809 } break; 7810 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7811 CharSequence text = getIterableTextForAccessibility(); 7812 if (text != null && text.length() > 0) { 7813 WordTextSegmentIterator iterator = 7814 WordTextSegmentIterator.getInstance( 7815 mContext.getResources().getConfiguration().locale); 7816 iterator.initialize(text.toString()); 7817 return iterator; 7818 } 7819 } break; 7820 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7821 CharSequence text = getIterableTextForAccessibility(); 7822 if (text != null && text.length() > 0) { 7823 ParagraphTextSegmentIterator iterator = 7824 ParagraphTextSegmentIterator.getInstance(); 7825 iterator.initialize(text.toString()); 7826 return iterator; 7827 } 7828 } break; 7829 } 7830 return null; 7831 } 7832 7833 /** 7834 * @hide 7835 */ 7836 public void dispatchStartTemporaryDetach() { 7837 clearDisplayList(); 7838 7839 onStartTemporaryDetach(); 7840 } 7841 7842 /** 7843 * This is called when a container is going to temporarily detach a child, with 7844 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7845 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7846 * {@link #onDetachedFromWindow()} when the container is done. 7847 */ 7848 public void onStartTemporaryDetach() { 7849 removeUnsetPressCallback(); 7850 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7851 } 7852 7853 /** 7854 * @hide 7855 */ 7856 public void dispatchFinishTemporaryDetach() { 7857 onFinishTemporaryDetach(); 7858 } 7859 7860 /** 7861 * Called after {@link #onStartTemporaryDetach} when the container is done 7862 * changing the view. 7863 */ 7864 public void onFinishTemporaryDetach() { 7865 } 7866 7867 /** 7868 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7869 * for this view's window. Returns null if the view is not currently attached 7870 * to the window. Normally you will not need to use this directly, but 7871 * just use the standard high-level event callbacks like 7872 * {@link #onKeyDown(int, KeyEvent)}. 7873 */ 7874 public KeyEvent.DispatcherState getKeyDispatcherState() { 7875 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7876 } 7877 7878 /** 7879 * Dispatch a key event before it is processed by any input method 7880 * associated with the view hierarchy. This can be used to intercept 7881 * key events in special situations before the IME consumes them; a 7882 * typical example would be handling the BACK key to update the application's 7883 * UI instead of allowing the IME to see it and close itself. 7884 * 7885 * @param event The key event to be dispatched. 7886 * @return True if the event was handled, false otherwise. 7887 */ 7888 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7889 return onKeyPreIme(event.getKeyCode(), event); 7890 } 7891 7892 /** 7893 * Dispatch a key event to the next view on the focus path. This path runs 7894 * from the top of the view tree down to the currently focused view. If this 7895 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7896 * the next node down the focus path. This method also fires any key 7897 * listeners. 7898 * 7899 * @param event The key event to be dispatched. 7900 * @return True if the event was handled, false otherwise. 7901 */ 7902 public boolean dispatchKeyEvent(KeyEvent event) { 7903 if (mInputEventConsistencyVerifier != null) { 7904 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7905 } 7906 7907 // Give any attached key listener a first crack at the event. 7908 //noinspection SimplifiableIfStatement 7909 ListenerInfo li = mListenerInfo; 7910 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7911 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7912 return true; 7913 } 7914 7915 if (event.dispatch(this, mAttachInfo != null 7916 ? mAttachInfo.mKeyDispatchState : null, this)) { 7917 return true; 7918 } 7919 7920 if (mInputEventConsistencyVerifier != null) { 7921 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7922 } 7923 return false; 7924 } 7925 7926 /** 7927 * Dispatches a key shortcut event. 7928 * 7929 * @param event The key event to be dispatched. 7930 * @return True if the event was handled by the view, false otherwise. 7931 */ 7932 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 7933 return onKeyShortcut(event.getKeyCode(), event); 7934 } 7935 7936 /** 7937 * Pass the touch screen motion event down to the target view, or this 7938 * view if it is the target. 7939 * 7940 * @param event The motion event to be dispatched. 7941 * @return True if the event was handled by the view, false otherwise. 7942 */ 7943 public boolean dispatchTouchEvent(MotionEvent event) { 7944 if (mInputEventConsistencyVerifier != null) { 7945 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 7946 } 7947 7948 if (onFilterTouchEventForSecurity(event)) { 7949 //noinspection SimplifiableIfStatement 7950 ListenerInfo li = mListenerInfo; 7951 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7952 && li.mOnTouchListener.onTouch(this, event)) { 7953 return true; 7954 } 7955 7956 if (onTouchEvent(event)) { 7957 return true; 7958 } 7959 } 7960 7961 if (mInputEventConsistencyVerifier != null) { 7962 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7963 } 7964 return false; 7965 } 7966 7967 /** 7968 * Filter the touch event to apply security policies. 7969 * 7970 * @param event The motion event to be filtered. 7971 * @return True if the event should be dispatched, false if the event should be dropped. 7972 * 7973 * @see #getFilterTouchesWhenObscured 7974 */ 7975 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 7976 //noinspection RedundantIfStatement 7977 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 7978 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 7979 // Window is obscured, drop this touch. 7980 return false; 7981 } 7982 return true; 7983 } 7984 7985 /** 7986 * Pass a trackball motion event down to the focused view. 7987 * 7988 * @param event The motion event to be dispatched. 7989 * @return True if the event was handled by the view, false otherwise. 7990 */ 7991 public boolean dispatchTrackballEvent(MotionEvent event) { 7992 if (mInputEventConsistencyVerifier != null) { 7993 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 7994 } 7995 7996 return onTrackballEvent(event); 7997 } 7998 7999 /** 8000 * Dispatch a generic motion event. 8001 * <p> 8002 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8003 * are delivered to the view under the pointer. All other generic motion events are 8004 * delivered to the focused view. Hover events are handled specially and are delivered 8005 * to {@link #onHoverEvent(MotionEvent)}. 8006 * </p> 8007 * 8008 * @param event The motion event to be dispatched. 8009 * @return True if the event was handled by the view, false otherwise. 8010 */ 8011 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8012 if (mInputEventConsistencyVerifier != null) { 8013 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8014 } 8015 8016 final int source = event.getSource(); 8017 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8018 final int action = event.getAction(); 8019 if (action == MotionEvent.ACTION_HOVER_ENTER 8020 || action == MotionEvent.ACTION_HOVER_MOVE 8021 || action == MotionEvent.ACTION_HOVER_EXIT) { 8022 if (dispatchHoverEvent(event)) { 8023 return true; 8024 } 8025 } else if (dispatchGenericPointerEvent(event)) { 8026 return true; 8027 } 8028 } else if (dispatchGenericFocusedEvent(event)) { 8029 return true; 8030 } 8031 8032 if (dispatchGenericMotionEventInternal(event)) { 8033 return true; 8034 } 8035 8036 if (mInputEventConsistencyVerifier != null) { 8037 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8038 } 8039 return false; 8040 } 8041 8042 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8043 //noinspection SimplifiableIfStatement 8044 ListenerInfo li = mListenerInfo; 8045 if (li != null && li.mOnGenericMotionListener != null 8046 && (mViewFlags & ENABLED_MASK) == ENABLED 8047 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8048 return true; 8049 } 8050 8051 if (onGenericMotionEvent(event)) { 8052 return true; 8053 } 8054 8055 if (mInputEventConsistencyVerifier != null) { 8056 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8057 } 8058 return false; 8059 } 8060 8061 /** 8062 * Dispatch a hover event. 8063 * <p> 8064 * Do not call this method directly. 8065 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8066 * </p> 8067 * 8068 * @param event The motion event to be dispatched. 8069 * @return True if the event was handled by the view, false otherwise. 8070 */ 8071 protected boolean dispatchHoverEvent(MotionEvent event) { 8072 ListenerInfo li = mListenerInfo; 8073 //noinspection SimplifiableIfStatement 8074 if (li != null && li.mOnHoverListener != null 8075 && (mViewFlags & ENABLED_MASK) == ENABLED 8076 && li.mOnHoverListener.onHover(this, event)) { 8077 return true; 8078 } 8079 8080 return onHoverEvent(event); 8081 } 8082 8083 /** 8084 * Returns true if the view has a child to which it has recently sent 8085 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8086 * it does not have a hovered child, then it must be the innermost hovered view. 8087 * @hide 8088 */ 8089 protected boolean hasHoveredChild() { 8090 return false; 8091 } 8092 8093 /** 8094 * Dispatch a generic motion event to the view under the first pointer. 8095 * <p> 8096 * Do not call this method directly. 8097 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8098 * </p> 8099 * 8100 * @param event The motion event to be dispatched. 8101 * @return True if the event was handled by the view, false otherwise. 8102 */ 8103 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8104 return false; 8105 } 8106 8107 /** 8108 * Dispatch a generic motion event to the currently focused view. 8109 * <p> 8110 * Do not call this method directly. 8111 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8112 * </p> 8113 * 8114 * @param event The motion event to be dispatched. 8115 * @return True if the event was handled by the view, false otherwise. 8116 */ 8117 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8118 return false; 8119 } 8120 8121 /** 8122 * Dispatch a pointer event. 8123 * <p> 8124 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8125 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8126 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8127 * and should not be expected to handle other pointing device features. 8128 * </p> 8129 * 8130 * @param event The motion event to be dispatched. 8131 * @return True if the event was handled by the view, false otherwise. 8132 * @hide 8133 */ 8134 public final boolean dispatchPointerEvent(MotionEvent event) { 8135 if (event.isTouchEvent()) { 8136 return dispatchTouchEvent(event); 8137 } else { 8138 return dispatchGenericMotionEvent(event); 8139 } 8140 } 8141 8142 /** 8143 * Called when the window containing this view gains or loses window focus. 8144 * ViewGroups should override to route to their children. 8145 * 8146 * @param hasFocus True if the window containing this view now has focus, 8147 * false otherwise. 8148 */ 8149 public void dispatchWindowFocusChanged(boolean hasFocus) { 8150 onWindowFocusChanged(hasFocus); 8151 } 8152 8153 /** 8154 * Called when the window containing this view gains or loses focus. Note 8155 * that this is separate from view focus: to receive key events, both 8156 * your view and its window must have focus. If a window is displayed 8157 * on top of yours that takes input focus, then your own window will lose 8158 * focus but the view focus will remain unchanged. 8159 * 8160 * @param hasWindowFocus True if the window containing this view now has 8161 * focus, false otherwise. 8162 */ 8163 public void onWindowFocusChanged(boolean hasWindowFocus) { 8164 InputMethodManager imm = InputMethodManager.peekInstance(); 8165 if (!hasWindowFocus) { 8166 if (isPressed()) { 8167 setPressed(false); 8168 } 8169 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8170 imm.focusOut(this); 8171 } 8172 removeLongPressCallback(); 8173 removeTapCallback(); 8174 onFocusLost(); 8175 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8176 imm.focusIn(this); 8177 } 8178 refreshDrawableState(); 8179 } 8180 8181 /** 8182 * Returns true if this view is in a window that currently has window focus. 8183 * Note that this is not the same as the view itself having focus. 8184 * 8185 * @return True if this view is in a window that currently has window focus. 8186 */ 8187 public boolean hasWindowFocus() { 8188 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8189 } 8190 8191 /** 8192 * Dispatch a view visibility change down the view hierarchy. 8193 * ViewGroups should override to route to their children. 8194 * @param changedView The view whose visibility changed. Could be 'this' or 8195 * an ancestor view. 8196 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8197 * {@link #INVISIBLE} or {@link #GONE}. 8198 */ 8199 protected void dispatchVisibilityChanged(@NonNull View changedView, 8200 @Visibility int visibility) { 8201 onVisibilityChanged(changedView, visibility); 8202 } 8203 8204 /** 8205 * Called when the visibility of the view or an ancestor of the view is changed. 8206 * @param changedView The view whose visibility changed. Could be 'this' or 8207 * an ancestor view. 8208 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8209 * {@link #INVISIBLE} or {@link #GONE}. 8210 */ 8211 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8212 if (visibility == VISIBLE) { 8213 if (mAttachInfo != null) { 8214 initialAwakenScrollBars(); 8215 } else { 8216 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8217 } 8218 } 8219 } 8220 8221 /** 8222 * Dispatch a hint about whether this view is displayed. For instance, when 8223 * a View moves out of the screen, it might receives a display hint indicating 8224 * the view is not displayed. Applications should not <em>rely</em> on this hint 8225 * as there is no guarantee that they will receive one. 8226 * 8227 * @param hint A hint about whether or not this view is displayed: 8228 * {@link #VISIBLE} or {@link #INVISIBLE}. 8229 */ 8230 public void dispatchDisplayHint(@Visibility int hint) { 8231 onDisplayHint(hint); 8232 } 8233 8234 /** 8235 * Gives this view a hint about whether is displayed or not. For instance, when 8236 * a View moves out of the screen, it might receives a display hint indicating 8237 * the view is not displayed. Applications should not <em>rely</em> on this hint 8238 * as there is no guarantee that they will receive one. 8239 * 8240 * @param hint A hint about whether or not this view is displayed: 8241 * {@link #VISIBLE} or {@link #INVISIBLE}. 8242 */ 8243 protected void onDisplayHint(@Visibility int hint) { 8244 } 8245 8246 /** 8247 * Dispatch a window visibility change down the view hierarchy. 8248 * ViewGroups should override to route to their children. 8249 * 8250 * @param visibility The new visibility of the window. 8251 * 8252 * @see #onWindowVisibilityChanged(int) 8253 */ 8254 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8255 onWindowVisibilityChanged(visibility); 8256 } 8257 8258 /** 8259 * Called when the window containing has change its visibility 8260 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8261 * that this tells you whether or not your window is being made visible 8262 * to the window manager; this does <em>not</em> tell you whether or not 8263 * your window is obscured by other windows on the screen, even if it 8264 * is itself visible. 8265 * 8266 * @param visibility The new visibility of the window. 8267 */ 8268 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8269 if (visibility == VISIBLE) { 8270 initialAwakenScrollBars(); 8271 } 8272 } 8273 8274 /** 8275 * Returns the current visibility of the window this view is attached to 8276 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8277 * 8278 * @return Returns the current visibility of the view's window. 8279 */ 8280 @Visibility 8281 public int getWindowVisibility() { 8282 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8283 } 8284 8285 /** 8286 * Retrieve the overall visible display size in which the window this view is 8287 * attached to has been positioned in. This takes into account screen 8288 * decorations above the window, for both cases where the window itself 8289 * is being position inside of them or the window is being placed under 8290 * then and covered insets are used for the window to position its content 8291 * inside. In effect, this tells you the available area where content can 8292 * be placed and remain visible to users. 8293 * 8294 * <p>This function requires an IPC back to the window manager to retrieve 8295 * the requested information, so should not be used in performance critical 8296 * code like drawing. 8297 * 8298 * @param outRect Filled in with the visible display frame. If the view 8299 * is not attached to a window, this is simply the raw display size. 8300 */ 8301 public void getWindowVisibleDisplayFrame(Rect outRect) { 8302 if (mAttachInfo != null) { 8303 try { 8304 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8305 } catch (RemoteException e) { 8306 return; 8307 } 8308 // XXX This is really broken, and probably all needs to be done 8309 // in the window manager, and we need to know more about whether 8310 // we want the area behind or in front of the IME. 8311 final Rect insets = mAttachInfo.mVisibleInsets; 8312 outRect.left += insets.left; 8313 outRect.top += insets.top; 8314 outRect.right -= insets.right; 8315 outRect.bottom -= insets.bottom; 8316 return; 8317 } 8318 // The view is not attached to a display so we don't have a context. 8319 // Make a best guess about the display size. 8320 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8321 d.getRectSize(outRect); 8322 } 8323 8324 /** 8325 * Dispatch a notification about a resource configuration change down 8326 * the view hierarchy. 8327 * ViewGroups should override to route to their children. 8328 * 8329 * @param newConfig The new resource configuration. 8330 * 8331 * @see #onConfigurationChanged(android.content.res.Configuration) 8332 */ 8333 public void dispatchConfigurationChanged(Configuration newConfig) { 8334 onConfigurationChanged(newConfig); 8335 } 8336 8337 /** 8338 * Called when the current configuration of the resources being used 8339 * by the application have changed. You can use this to decide when 8340 * to reload resources that can changed based on orientation and other 8341 * configuration characterstics. You only need to use this if you are 8342 * not relying on the normal {@link android.app.Activity} mechanism of 8343 * recreating the activity instance upon a configuration change. 8344 * 8345 * @param newConfig The new resource configuration. 8346 */ 8347 protected void onConfigurationChanged(Configuration newConfig) { 8348 } 8349 8350 /** 8351 * Private function to aggregate all per-view attributes in to the view 8352 * root. 8353 */ 8354 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8355 performCollectViewAttributes(attachInfo, visibility); 8356 } 8357 8358 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8359 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8360 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8361 attachInfo.mKeepScreenOn = true; 8362 } 8363 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8364 ListenerInfo li = mListenerInfo; 8365 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8366 attachInfo.mHasSystemUiListeners = true; 8367 } 8368 } 8369 } 8370 8371 void needGlobalAttributesUpdate(boolean force) { 8372 final AttachInfo ai = mAttachInfo; 8373 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8374 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8375 || ai.mHasSystemUiListeners) { 8376 ai.mRecomputeGlobalAttributes = true; 8377 } 8378 } 8379 } 8380 8381 /** 8382 * Returns whether the device is currently in touch mode. Touch mode is entered 8383 * once the user begins interacting with the device by touch, and affects various 8384 * things like whether focus is always visible to the user. 8385 * 8386 * @return Whether the device is in touch mode. 8387 */ 8388 @ViewDebug.ExportedProperty 8389 public boolean isInTouchMode() { 8390 if (mAttachInfo != null) { 8391 return mAttachInfo.mInTouchMode; 8392 } else { 8393 return ViewRootImpl.isInTouchMode(); 8394 } 8395 } 8396 8397 /** 8398 * Returns the context the view is running in, through which it can 8399 * access the current theme, resources, etc. 8400 * 8401 * @return The view's Context. 8402 */ 8403 @ViewDebug.CapturedViewProperty 8404 public final Context getContext() { 8405 return mContext; 8406 } 8407 8408 /** 8409 * Handle a key event before it is processed by any input method 8410 * associated with the view hierarchy. This can be used to intercept 8411 * key events in special situations before the IME consumes them; a 8412 * typical example would be handling the BACK key to update the application's 8413 * UI instead of allowing the IME to see it and close itself. 8414 * 8415 * @param keyCode The value in event.getKeyCode(). 8416 * @param event Description of the key event. 8417 * @return If you handled the event, return true. If you want to allow the 8418 * event to be handled by the next receiver, return false. 8419 */ 8420 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8421 return false; 8422 } 8423 8424 /** 8425 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8426 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8427 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8428 * is released, if the view is enabled and clickable. 8429 * 8430 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8431 * although some may elect to do so in some situations. Do not rely on this to 8432 * catch software key presses. 8433 * 8434 * @param keyCode A key code that represents the button pressed, from 8435 * {@link android.view.KeyEvent}. 8436 * @param event The KeyEvent object that defines the button action. 8437 */ 8438 public boolean onKeyDown(int keyCode, KeyEvent event) { 8439 boolean result = false; 8440 8441 if (KeyEvent.isConfirmKey(keyCode)) { 8442 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8443 return true; 8444 } 8445 // Long clickable items don't necessarily have to be clickable 8446 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8447 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8448 (event.getRepeatCount() == 0)) { 8449 setPressed(true); 8450 checkForLongClick(0); 8451 return true; 8452 } 8453 } 8454 return result; 8455 } 8456 8457 /** 8458 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8459 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8460 * the event). 8461 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8462 * although some may elect to do so in some situations. Do not rely on this to 8463 * catch software key presses. 8464 */ 8465 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8466 return false; 8467 } 8468 8469 /** 8470 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8471 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8472 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8473 * {@link KeyEvent#KEYCODE_ENTER} is released. 8474 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8475 * although some may elect to do so in some situations. Do not rely on this to 8476 * catch software key presses. 8477 * 8478 * @param keyCode A key code that represents the button pressed, from 8479 * {@link android.view.KeyEvent}. 8480 * @param event The KeyEvent object that defines the button action. 8481 */ 8482 public boolean onKeyUp(int keyCode, KeyEvent event) { 8483 if (KeyEvent.isConfirmKey(keyCode)) { 8484 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8485 return true; 8486 } 8487 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8488 setPressed(false); 8489 8490 if (!mHasPerformedLongPress) { 8491 // This is a tap, so remove the longpress check 8492 removeLongPressCallback(); 8493 return performClick(); 8494 } 8495 } 8496 } 8497 return false; 8498 } 8499 8500 /** 8501 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8502 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8503 * the event). 8504 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8505 * although some may elect to do so in some situations. Do not rely on this to 8506 * catch software key presses. 8507 * 8508 * @param keyCode A key code that represents the button pressed, from 8509 * {@link android.view.KeyEvent}. 8510 * @param repeatCount The number of times the action was made. 8511 * @param event The KeyEvent object that defines the button action. 8512 */ 8513 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8514 return false; 8515 } 8516 8517 /** 8518 * Called on the focused view when a key shortcut event is not handled. 8519 * Override this method to implement local key shortcuts for the View. 8520 * Key shortcuts can also be implemented by setting the 8521 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8522 * 8523 * @param keyCode The value in event.getKeyCode(). 8524 * @param event Description of the key event. 8525 * @return If you handled the event, return true. If you want to allow the 8526 * event to be handled by the next receiver, return false. 8527 */ 8528 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8529 return false; 8530 } 8531 8532 /** 8533 * Check whether the called view is a text editor, in which case it 8534 * would make sense to automatically display a soft input window for 8535 * it. Subclasses should override this if they implement 8536 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8537 * a call on that method would return a non-null InputConnection, and 8538 * they are really a first-class editor that the user would normally 8539 * start typing on when the go into a window containing your view. 8540 * 8541 * <p>The default implementation always returns false. This does 8542 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8543 * will not be called or the user can not otherwise perform edits on your 8544 * view; it is just a hint to the system that this is not the primary 8545 * purpose of this view. 8546 * 8547 * @return Returns true if this view is a text editor, else false. 8548 */ 8549 public boolean onCheckIsTextEditor() { 8550 return false; 8551 } 8552 8553 /** 8554 * Create a new InputConnection for an InputMethod to interact 8555 * with the view. The default implementation returns null, since it doesn't 8556 * support input methods. You can override this to implement such support. 8557 * This is only needed for views that take focus and text input. 8558 * 8559 * <p>When implementing this, you probably also want to implement 8560 * {@link #onCheckIsTextEditor()} to indicate you will return a 8561 * non-null InputConnection. 8562 * 8563 * @param outAttrs Fill in with attribute information about the connection. 8564 */ 8565 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8566 return null; 8567 } 8568 8569 /** 8570 * Called by the {@link android.view.inputmethod.InputMethodManager} 8571 * when a view who is not the current 8572 * input connection target is trying to make a call on the manager. The 8573 * default implementation returns false; you can override this to return 8574 * true for certain views if you are performing InputConnection proxying 8575 * to them. 8576 * @param view The View that is making the InputMethodManager call. 8577 * @return Return true to allow the call, false to reject. 8578 */ 8579 public boolean checkInputConnectionProxy(View view) { 8580 return false; 8581 } 8582 8583 /** 8584 * Show the context menu for this view. It is not safe to hold on to the 8585 * menu after returning from this method. 8586 * 8587 * You should normally not overload this method. Overload 8588 * {@link #onCreateContextMenu(ContextMenu)} or define an 8589 * {@link OnCreateContextMenuListener} to add items to the context menu. 8590 * 8591 * @param menu The context menu to populate 8592 */ 8593 public void createContextMenu(ContextMenu menu) { 8594 ContextMenuInfo menuInfo = getContextMenuInfo(); 8595 8596 // Sets the current menu info so all items added to menu will have 8597 // my extra info set. 8598 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8599 8600 onCreateContextMenu(menu); 8601 ListenerInfo li = mListenerInfo; 8602 if (li != null && li.mOnCreateContextMenuListener != null) { 8603 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8604 } 8605 8606 // Clear the extra information so subsequent items that aren't mine don't 8607 // have my extra info. 8608 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8609 8610 if (mParent != null) { 8611 mParent.createContextMenu(menu); 8612 } 8613 } 8614 8615 /** 8616 * Views should implement this if they have extra information to associate 8617 * with the context menu. The return result is supplied as a parameter to 8618 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8619 * callback. 8620 * 8621 * @return Extra information about the item for which the context menu 8622 * should be shown. This information will vary across different 8623 * subclasses of View. 8624 */ 8625 protected ContextMenuInfo getContextMenuInfo() { 8626 return null; 8627 } 8628 8629 /** 8630 * Views should implement this if the view itself is going to add items to 8631 * the context menu. 8632 * 8633 * @param menu the context menu to populate 8634 */ 8635 protected void onCreateContextMenu(ContextMenu menu) { 8636 } 8637 8638 /** 8639 * Implement this method to handle trackball motion events. The 8640 * <em>relative</em> movement of the trackball since the last event 8641 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8642 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8643 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8644 * they will often be fractional values, representing the more fine-grained 8645 * movement information available from a trackball). 8646 * 8647 * @param event The motion event. 8648 * @return True if the event was handled, false otherwise. 8649 */ 8650 public boolean onTrackballEvent(MotionEvent event) { 8651 return false; 8652 } 8653 8654 /** 8655 * Implement this method to handle generic motion events. 8656 * <p> 8657 * Generic motion events describe joystick movements, mouse hovers, track pad 8658 * touches, scroll wheel movements and other input events. The 8659 * {@link MotionEvent#getSource() source} of the motion event specifies 8660 * the class of input that was received. Implementations of this method 8661 * must examine the bits in the source before processing the event. 8662 * The following code example shows how this is done. 8663 * </p><p> 8664 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8665 * are delivered to the view under the pointer. All other generic motion events are 8666 * delivered to the focused view. 8667 * </p> 8668 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8669 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8670 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8671 * // process the joystick movement... 8672 * return true; 8673 * } 8674 * } 8675 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8676 * switch (event.getAction()) { 8677 * case MotionEvent.ACTION_HOVER_MOVE: 8678 * // process the mouse hover movement... 8679 * return true; 8680 * case MotionEvent.ACTION_SCROLL: 8681 * // process the scroll wheel movement... 8682 * return true; 8683 * } 8684 * } 8685 * return super.onGenericMotionEvent(event); 8686 * }</pre> 8687 * 8688 * @param event The generic motion event being processed. 8689 * @return True if the event was handled, false otherwise. 8690 */ 8691 public boolean onGenericMotionEvent(MotionEvent event) { 8692 return false; 8693 } 8694 8695 /** 8696 * Implement this method to handle hover events. 8697 * <p> 8698 * This method is called whenever a pointer is hovering into, over, or out of the 8699 * bounds of a view and the view is not currently being touched. 8700 * Hover events are represented as pointer events with action 8701 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8702 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8703 * </p> 8704 * <ul> 8705 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8706 * when the pointer enters the bounds of the view.</li> 8707 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8708 * when the pointer has already entered the bounds of the view and has moved.</li> 8709 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8710 * when the pointer has exited the bounds of the view or when the pointer is 8711 * about to go down due to a button click, tap, or similar user action that 8712 * causes the view to be touched.</li> 8713 * </ul> 8714 * <p> 8715 * The view should implement this method to return true to indicate that it is 8716 * handling the hover event, such as by changing its drawable state. 8717 * </p><p> 8718 * The default implementation calls {@link #setHovered} to update the hovered state 8719 * of the view when a hover enter or hover exit event is received, if the view 8720 * is enabled and is clickable. The default implementation also sends hover 8721 * accessibility events. 8722 * </p> 8723 * 8724 * @param event The motion event that describes the hover. 8725 * @return True if the view handled the hover event. 8726 * 8727 * @see #isHovered 8728 * @see #setHovered 8729 * @see #onHoverChanged 8730 */ 8731 public boolean onHoverEvent(MotionEvent event) { 8732 // The root view may receive hover (or touch) events that are outside the bounds of 8733 // the window. This code ensures that we only send accessibility events for 8734 // hovers that are actually within the bounds of the root view. 8735 final int action = event.getActionMasked(); 8736 if (!mSendingHoverAccessibilityEvents) { 8737 if ((action == MotionEvent.ACTION_HOVER_ENTER 8738 || action == MotionEvent.ACTION_HOVER_MOVE) 8739 && !hasHoveredChild() 8740 && pointInView(event.getX(), event.getY())) { 8741 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8742 mSendingHoverAccessibilityEvents = true; 8743 } 8744 } else { 8745 if (action == MotionEvent.ACTION_HOVER_EXIT 8746 || (action == MotionEvent.ACTION_MOVE 8747 && !pointInView(event.getX(), event.getY()))) { 8748 mSendingHoverAccessibilityEvents = false; 8749 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8750 // If the window does not have input focus we take away accessibility 8751 // focus as soon as the user stop hovering over the view. 8752 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 8753 getViewRootImpl().setAccessibilityFocus(null, null); 8754 } 8755 } 8756 } 8757 8758 if (isHoverable()) { 8759 switch (action) { 8760 case MotionEvent.ACTION_HOVER_ENTER: 8761 setHovered(true); 8762 break; 8763 case MotionEvent.ACTION_HOVER_EXIT: 8764 setHovered(false); 8765 break; 8766 } 8767 8768 // Dispatch the event to onGenericMotionEvent before returning true. 8769 // This is to provide compatibility with existing applications that 8770 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8771 // break because of the new default handling for hoverable views 8772 // in onHoverEvent. 8773 // Note that onGenericMotionEvent will be called by default when 8774 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8775 dispatchGenericMotionEventInternal(event); 8776 // The event was already handled by calling setHovered(), so always 8777 // return true. 8778 return true; 8779 } 8780 8781 return false; 8782 } 8783 8784 /** 8785 * Returns true if the view should handle {@link #onHoverEvent} 8786 * by calling {@link #setHovered} to change its hovered state. 8787 * 8788 * @return True if the view is hoverable. 8789 */ 8790 private boolean isHoverable() { 8791 final int viewFlags = mViewFlags; 8792 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8793 return false; 8794 } 8795 8796 return (viewFlags & CLICKABLE) == CLICKABLE 8797 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8798 } 8799 8800 /** 8801 * Returns true if the view is currently hovered. 8802 * 8803 * @return True if the view is currently hovered. 8804 * 8805 * @see #setHovered 8806 * @see #onHoverChanged 8807 */ 8808 @ViewDebug.ExportedProperty 8809 public boolean isHovered() { 8810 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8811 } 8812 8813 /** 8814 * Sets whether the view is currently hovered. 8815 * <p> 8816 * Calling this method also changes the drawable state of the view. This 8817 * enables the view to react to hover by using different drawable resources 8818 * to change its appearance. 8819 * </p><p> 8820 * The {@link #onHoverChanged} method is called when the hovered state changes. 8821 * </p> 8822 * 8823 * @param hovered True if the view is hovered. 8824 * 8825 * @see #isHovered 8826 * @see #onHoverChanged 8827 */ 8828 public void setHovered(boolean hovered) { 8829 if (hovered) { 8830 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8831 mPrivateFlags |= PFLAG_HOVERED; 8832 refreshDrawableState(); 8833 onHoverChanged(true); 8834 } 8835 } else { 8836 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8837 mPrivateFlags &= ~PFLAG_HOVERED; 8838 refreshDrawableState(); 8839 onHoverChanged(false); 8840 } 8841 } 8842 } 8843 8844 /** 8845 * Implement this method to handle hover state changes. 8846 * <p> 8847 * This method is called whenever the hover state changes as a result of a 8848 * call to {@link #setHovered}. 8849 * </p> 8850 * 8851 * @param hovered The current hover state, as returned by {@link #isHovered}. 8852 * 8853 * @see #isHovered 8854 * @see #setHovered 8855 */ 8856 public void onHoverChanged(boolean hovered) { 8857 } 8858 8859 /** 8860 * Implement this method to handle touch screen motion events. 8861 * <p> 8862 * If this method is used to detect click actions, it is recommended that 8863 * the actions be performed by implementing and calling 8864 * {@link #performClick()}. This will ensure consistent system behavior, 8865 * including: 8866 * <ul> 8867 * <li>obeying click sound preferences 8868 * <li>dispatching OnClickListener calls 8869 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 8870 * accessibility features are enabled 8871 * </ul> 8872 * 8873 * @param event The motion event. 8874 * @return True if the event was handled, false otherwise. 8875 */ 8876 public boolean onTouchEvent(MotionEvent event) { 8877 final int viewFlags = mViewFlags; 8878 8879 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8880 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8881 setPressed(false); 8882 } 8883 // A disabled view that is clickable still consumes the touch 8884 // events, it just doesn't respond to them. 8885 return (((viewFlags & CLICKABLE) == CLICKABLE || 8886 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8887 } 8888 8889 if (mTouchDelegate != null) { 8890 if (mTouchDelegate.onTouchEvent(event)) { 8891 return true; 8892 } 8893 } 8894 8895 if (((viewFlags & CLICKABLE) == CLICKABLE || 8896 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8897 switch (event.getAction()) { 8898 case MotionEvent.ACTION_UP: 8899 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8900 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8901 // take focus if we don't have it already and we should in 8902 // touch mode. 8903 boolean focusTaken = false; 8904 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8905 focusTaken = requestFocus(); 8906 } 8907 8908 if (prepressed) { 8909 // The button is being released before we actually 8910 // showed it as pressed. Make it show the pressed 8911 // state now (before scheduling the click) to ensure 8912 // the user sees it. 8913 setPressed(true); 8914 } 8915 8916 if (!mHasPerformedLongPress) { 8917 // This is a tap, so remove the longpress check 8918 removeLongPressCallback(); 8919 8920 // Only perform take click actions if we were in the pressed state 8921 if (!focusTaken) { 8922 // Use a Runnable and post this rather than calling 8923 // performClick directly. This lets other visual state 8924 // of the view update before click actions start. 8925 if (mPerformClick == null) { 8926 mPerformClick = new PerformClick(); 8927 } 8928 if (!post(mPerformClick)) { 8929 performClick(); 8930 } 8931 } 8932 } 8933 8934 if (mUnsetPressedState == null) { 8935 mUnsetPressedState = new UnsetPressedState(); 8936 } 8937 8938 if (prepressed) { 8939 postDelayed(mUnsetPressedState, 8940 ViewConfiguration.getPressedStateDuration()); 8941 } else if (!post(mUnsetPressedState)) { 8942 // If the post failed, unpress right now 8943 mUnsetPressedState.run(); 8944 } 8945 removeTapCallback(); 8946 } 8947 break; 8948 8949 case MotionEvent.ACTION_DOWN: 8950 mHasPerformedLongPress = false; 8951 8952 if (performButtonActionOnTouchDown(event)) { 8953 break; 8954 } 8955 8956 // Walk up the hierarchy to determine if we're inside a scrolling container. 8957 boolean isInScrollingContainer = isInScrollingContainer(); 8958 8959 // For views inside a scrolling container, delay the pressed feedback for 8960 // a short period in case this is a scroll. 8961 if (isInScrollingContainer) { 8962 mPrivateFlags |= PFLAG_PREPRESSED; 8963 if (mPendingCheckForTap == null) { 8964 mPendingCheckForTap = new CheckForTap(); 8965 } 8966 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 8967 } else { 8968 // Not inside a scrolling container, so show the feedback right away 8969 setPressed(true); 8970 checkForLongClick(0); 8971 } 8972 break; 8973 8974 case MotionEvent.ACTION_CANCEL: 8975 setPressed(false); 8976 removeTapCallback(); 8977 removeLongPressCallback(); 8978 break; 8979 8980 case MotionEvent.ACTION_MOVE: 8981 final int x = (int) event.getX(); 8982 final int y = (int) event.getY(); 8983 8984 // Be lenient about moving outside of buttons 8985 if (!pointInView(x, y, mTouchSlop)) { 8986 // Outside button 8987 removeTapCallback(); 8988 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 8989 // Remove any future long press/tap checks 8990 removeLongPressCallback(); 8991 8992 setPressed(false); 8993 } 8994 } 8995 break; 8996 } 8997 8998 if (mBackground != null && mBackground.supportsHotspots()) { 8999 manageTouchHotspot(event); 9000 } 9001 9002 return true; 9003 } 9004 9005 return false; 9006 } 9007 9008 private void manageTouchHotspot(MotionEvent event) { 9009 switch (event.getAction()) { 9010 case MotionEvent.ACTION_DOWN: 9011 case MotionEvent.ACTION_POINTER_DOWN: { 9012 final int index = event.getActionIndex(); 9013 setPointerHotspot(event, index); 9014 } break; 9015 case MotionEvent.ACTION_MOVE: { 9016 final int count = event.getPointerCount(); 9017 for (int index = 0; index < count; index++) { 9018 setPointerHotspot(event, index); 9019 } 9020 } break; 9021 case MotionEvent.ACTION_POINTER_UP: { 9022 final int actionIndex = event.getActionIndex(); 9023 final int pointerId = event.getPointerId(actionIndex); 9024 mBackground.removeHotspot(pointerId); 9025 } break; 9026 case MotionEvent.ACTION_UP: 9027 case MotionEvent.ACTION_CANCEL: 9028 mBackground.clearHotspots(); 9029 break; 9030 } 9031 } 9032 9033 private void setPointerHotspot(MotionEvent event, int index) { 9034 final int id = event.getPointerId(index); 9035 final float x = event.getX(index); 9036 final float y = event.getY(index); 9037 mBackground.setHotspot(id, x, y); 9038 } 9039 9040 /** 9041 * @hide 9042 */ 9043 public boolean isInScrollingContainer() { 9044 ViewParent p = getParent(); 9045 while (p != null && p instanceof ViewGroup) { 9046 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9047 return true; 9048 } 9049 p = p.getParent(); 9050 } 9051 return false; 9052 } 9053 9054 /** 9055 * Remove the longpress detection timer. 9056 */ 9057 private void removeLongPressCallback() { 9058 if (mPendingCheckForLongPress != null) { 9059 removeCallbacks(mPendingCheckForLongPress); 9060 } 9061 } 9062 9063 /** 9064 * Remove the pending click action 9065 */ 9066 private void removePerformClickCallback() { 9067 if (mPerformClick != null) { 9068 removeCallbacks(mPerformClick); 9069 } 9070 } 9071 9072 /** 9073 * Remove the prepress detection timer. 9074 */ 9075 private void removeUnsetPressCallback() { 9076 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9077 setPressed(false); 9078 removeCallbacks(mUnsetPressedState); 9079 } 9080 } 9081 9082 /** 9083 * Remove the tap detection timer. 9084 */ 9085 private void removeTapCallback() { 9086 if (mPendingCheckForTap != null) { 9087 mPrivateFlags &= ~PFLAG_PREPRESSED; 9088 removeCallbacks(mPendingCheckForTap); 9089 } 9090 } 9091 9092 /** 9093 * Cancels a pending long press. Your subclass can use this if you 9094 * want the context menu to come up if the user presses and holds 9095 * at the same place, but you don't want it to come up if they press 9096 * and then move around enough to cause scrolling. 9097 */ 9098 public void cancelLongPress() { 9099 removeLongPressCallback(); 9100 9101 /* 9102 * The prepressed state handled by the tap callback is a display 9103 * construct, but the tap callback will post a long press callback 9104 * less its own timeout. Remove it here. 9105 */ 9106 removeTapCallback(); 9107 } 9108 9109 /** 9110 * Remove the pending callback for sending a 9111 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9112 */ 9113 private void removeSendViewScrolledAccessibilityEventCallback() { 9114 if (mSendViewScrolledAccessibilityEvent != null) { 9115 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9116 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9117 } 9118 } 9119 9120 /** 9121 * Sets the TouchDelegate for this View. 9122 */ 9123 public void setTouchDelegate(TouchDelegate delegate) { 9124 mTouchDelegate = delegate; 9125 } 9126 9127 /** 9128 * Gets the TouchDelegate for this View. 9129 */ 9130 public TouchDelegate getTouchDelegate() { 9131 return mTouchDelegate; 9132 } 9133 9134 /** 9135 * Set flags controlling behavior of this view. 9136 * 9137 * @param flags Constant indicating the value which should be set 9138 * @param mask Constant indicating the bit range that should be changed 9139 */ 9140 void setFlags(int flags, int mask) { 9141 final boolean accessibilityEnabled = 9142 AccessibilityManager.getInstance(mContext).isEnabled(); 9143 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9144 9145 int old = mViewFlags; 9146 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9147 9148 int changed = mViewFlags ^ old; 9149 if (changed == 0) { 9150 return; 9151 } 9152 int privateFlags = mPrivateFlags; 9153 9154 /* Check if the FOCUSABLE bit has changed */ 9155 if (((changed & FOCUSABLE_MASK) != 0) && 9156 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9157 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9158 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9159 /* Give up focus if we are no longer focusable */ 9160 clearFocus(); 9161 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9162 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9163 /* 9164 * Tell the view system that we are now available to take focus 9165 * if no one else already has it. 9166 */ 9167 if (mParent != null) mParent.focusableViewAvailable(this); 9168 } 9169 } 9170 9171 final int newVisibility = flags & VISIBILITY_MASK; 9172 if (newVisibility == VISIBLE) { 9173 if ((changed & VISIBILITY_MASK) != 0) { 9174 /* 9175 * If this view is becoming visible, invalidate it in case it changed while 9176 * it was not visible. Marking it drawn ensures that the invalidation will 9177 * go through. 9178 */ 9179 mPrivateFlags |= PFLAG_DRAWN; 9180 invalidate(true); 9181 9182 needGlobalAttributesUpdate(true); 9183 9184 // a view becoming visible is worth notifying the parent 9185 // about in case nothing has focus. even if this specific view 9186 // isn't focusable, it may contain something that is, so let 9187 // the root view try to give this focus if nothing else does. 9188 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9189 mParent.focusableViewAvailable(this); 9190 } 9191 } 9192 } 9193 9194 /* Check if the GONE bit has changed */ 9195 if ((changed & GONE) != 0) { 9196 needGlobalAttributesUpdate(false); 9197 requestLayout(); 9198 9199 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9200 if (hasFocus()) clearFocus(); 9201 clearAccessibilityFocus(); 9202 destroyDrawingCache(); 9203 if (mParent instanceof View) { 9204 // GONE views noop invalidation, so invalidate the parent 9205 ((View) mParent).invalidate(true); 9206 } 9207 // Mark the view drawn to ensure that it gets invalidated properly the next 9208 // time it is visible and gets invalidated 9209 mPrivateFlags |= PFLAG_DRAWN; 9210 } 9211 if (mAttachInfo != null) { 9212 mAttachInfo.mViewVisibilityChanged = true; 9213 } 9214 } 9215 9216 /* Check if the VISIBLE bit has changed */ 9217 if ((changed & INVISIBLE) != 0) { 9218 needGlobalAttributesUpdate(false); 9219 /* 9220 * If this view is becoming invisible, set the DRAWN flag so that 9221 * the next invalidate() will not be skipped. 9222 */ 9223 mPrivateFlags |= PFLAG_DRAWN; 9224 9225 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9226 // root view becoming invisible shouldn't clear focus and accessibility focus 9227 if (getRootView() != this) { 9228 if (hasFocus()) clearFocus(); 9229 clearAccessibilityFocus(); 9230 } 9231 } 9232 if (mAttachInfo != null) { 9233 mAttachInfo.mViewVisibilityChanged = true; 9234 } 9235 } 9236 9237 if ((changed & VISIBILITY_MASK) != 0) { 9238 // If the view is invisible, cleanup its display list to free up resources 9239 if (newVisibility != VISIBLE) { 9240 cleanupDraw(); 9241 } 9242 9243 if (mParent instanceof ViewGroup) { 9244 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9245 (changed & VISIBILITY_MASK), newVisibility); 9246 ((View) mParent).invalidate(true); 9247 } else if (mParent != null) { 9248 mParent.invalidateChild(this, null); 9249 } 9250 dispatchVisibilityChanged(this, newVisibility); 9251 } 9252 9253 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9254 destroyDrawingCache(); 9255 } 9256 9257 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9258 destroyDrawingCache(); 9259 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9260 invalidateParentCaches(); 9261 } 9262 9263 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9264 destroyDrawingCache(); 9265 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9266 } 9267 9268 if ((changed & DRAW_MASK) != 0) { 9269 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9270 if (mBackground != null) { 9271 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9272 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9273 } else { 9274 mPrivateFlags |= PFLAG_SKIP_DRAW; 9275 } 9276 } else { 9277 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9278 } 9279 requestLayout(); 9280 invalidate(true); 9281 } 9282 9283 if ((changed & KEEP_SCREEN_ON) != 0) { 9284 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9285 mParent.recomputeViewAttributes(this); 9286 } 9287 } 9288 9289 if (accessibilityEnabled) { 9290 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9291 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9292 if (oldIncludeForAccessibility != includeForAccessibility()) { 9293 notifySubtreeAccessibilityStateChangedIfNeeded(); 9294 } else { 9295 notifyViewAccessibilityStateChangedIfNeeded( 9296 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9297 } 9298 } else if ((changed & ENABLED_MASK) != 0) { 9299 notifyViewAccessibilityStateChangedIfNeeded( 9300 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9301 } 9302 } 9303 } 9304 9305 /** 9306 * Change the view's z order in the tree, so it's on top of other sibling 9307 * views. This ordering change may affect layout, if the parent container 9308 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9309 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9310 * method should be followed by calls to {@link #requestLayout()} and 9311 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9312 * with the new child ordering. 9313 * 9314 * @see ViewGroup#bringChildToFront(View) 9315 */ 9316 public void bringToFront() { 9317 if (mParent != null) { 9318 mParent.bringChildToFront(this); 9319 } 9320 } 9321 9322 /** 9323 * This is called in response to an internal scroll in this view (i.e., the 9324 * view scrolled its own contents). This is typically as a result of 9325 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9326 * called. 9327 * 9328 * @param l Current horizontal scroll origin. 9329 * @param t Current vertical scroll origin. 9330 * @param oldl Previous horizontal scroll origin. 9331 * @param oldt Previous vertical scroll origin. 9332 */ 9333 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9334 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9335 postSendViewScrolledAccessibilityEventCallback(); 9336 } 9337 9338 mBackgroundSizeChanged = true; 9339 9340 final AttachInfo ai = mAttachInfo; 9341 if (ai != null) { 9342 ai.mViewScrollChanged = true; 9343 } 9344 } 9345 9346 /** 9347 * Interface definition for a callback to be invoked when the layout bounds of a view 9348 * changes due to layout processing. 9349 */ 9350 public interface OnLayoutChangeListener { 9351 /** 9352 * Called when the layout bounds of a view changes due to layout processing. 9353 * 9354 * @param v The view whose bounds have changed. 9355 * @param left The new value of the view's left property. 9356 * @param top The new value of the view's top property. 9357 * @param right The new value of the view's right property. 9358 * @param bottom The new value of the view's bottom property. 9359 * @param oldLeft The previous value of the view's left property. 9360 * @param oldTop The previous value of the view's top property. 9361 * @param oldRight The previous value of the view's right property. 9362 * @param oldBottom The previous value of the view's bottom property. 9363 */ 9364 void onLayoutChange(View v, int left, int top, int right, int bottom, 9365 int oldLeft, int oldTop, int oldRight, int oldBottom); 9366 } 9367 9368 /** 9369 * This is called during layout when the size of this view has changed. If 9370 * you were just added to the view hierarchy, you're called with the old 9371 * values of 0. 9372 * 9373 * @param w Current width of this view. 9374 * @param h Current height of this view. 9375 * @param oldw Old width of this view. 9376 * @param oldh Old height of this view. 9377 */ 9378 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9379 } 9380 9381 /** 9382 * Called by draw to draw the child views. This may be overridden 9383 * by derived classes to gain control just before its children are drawn 9384 * (but after its own view has been drawn). 9385 * @param canvas the canvas on which to draw the view 9386 */ 9387 protected void dispatchDraw(Canvas canvas) { 9388 9389 } 9390 9391 /** 9392 * Gets the parent of this view. Note that the parent is a 9393 * ViewParent and not necessarily a View. 9394 * 9395 * @return Parent of this view. 9396 */ 9397 public final ViewParent getParent() { 9398 return mParent; 9399 } 9400 9401 /** 9402 * Set the horizontal scrolled position of your view. This will cause a call to 9403 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9404 * invalidated. 9405 * @param value the x position to scroll to 9406 */ 9407 public void setScrollX(int value) { 9408 scrollTo(value, mScrollY); 9409 } 9410 9411 /** 9412 * Set the vertical scrolled position of your view. This will cause a call to 9413 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9414 * invalidated. 9415 * @param value the y position to scroll to 9416 */ 9417 public void setScrollY(int value) { 9418 scrollTo(mScrollX, value); 9419 } 9420 9421 /** 9422 * Return the scrolled left position of this view. This is the left edge of 9423 * the displayed part of your view. You do not need to draw any pixels 9424 * farther left, since those are outside of the frame of your view on 9425 * screen. 9426 * 9427 * @return The left edge of the displayed part of your view, in pixels. 9428 */ 9429 public final int getScrollX() { 9430 return mScrollX; 9431 } 9432 9433 /** 9434 * Return the scrolled top position of this view. This is the top edge of 9435 * the displayed part of your view. You do not need to draw any pixels above 9436 * it, since those are outside of the frame of your view on screen. 9437 * 9438 * @return The top edge of the displayed part of your view, in pixels. 9439 */ 9440 public final int getScrollY() { 9441 return mScrollY; 9442 } 9443 9444 /** 9445 * Return the width of the your view. 9446 * 9447 * @return The width of your view, in pixels. 9448 */ 9449 @ViewDebug.ExportedProperty(category = "layout") 9450 public final int getWidth() { 9451 return mRight - mLeft; 9452 } 9453 9454 /** 9455 * Return the height of your view. 9456 * 9457 * @return The height of your view, in pixels. 9458 */ 9459 @ViewDebug.ExportedProperty(category = "layout") 9460 public final int getHeight() { 9461 return mBottom - mTop; 9462 } 9463 9464 /** 9465 * Return the visible drawing bounds of your view. Fills in the output 9466 * rectangle with the values from getScrollX(), getScrollY(), 9467 * getWidth(), and getHeight(). These bounds do not account for any 9468 * transformation properties currently set on the view, such as 9469 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9470 * 9471 * @param outRect The (scrolled) drawing bounds of the view. 9472 */ 9473 public void getDrawingRect(Rect outRect) { 9474 outRect.left = mScrollX; 9475 outRect.top = mScrollY; 9476 outRect.right = mScrollX + (mRight - mLeft); 9477 outRect.bottom = mScrollY + (mBottom - mTop); 9478 } 9479 9480 /** 9481 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9482 * raw width component (that is the result is masked by 9483 * {@link #MEASURED_SIZE_MASK}). 9484 * 9485 * @return The raw measured width of this view. 9486 */ 9487 public final int getMeasuredWidth() { 9488 return mMeasuredWidth & MEASURED_SIZE_MASK; 9489 } 9490 9491 /** 9492 * Return the full width measurement information for this view as computed 9493 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9494 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9495 * This should be used during measurement and layout calculations only. Use 9496 * {@link #getWidth()} to see how wide a view is after layout. 9497 * 9498 * @return The measured width of this view as a bit mask. 9499 */ 9500 public final int getMeasuredWidthAndState() { 9501 return mMeasuredWidth; 9502 } 9503 9504 /** 9505 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9506 * raw width component (that is the result is masked by 9507 * {@link #MEASURED_SIZE_MASK}). 9508 * 9509 * @return The raw measured height of this view. 9510 */ 9511 public final int getMeasuredHeight() { 9512 return mMeasuredHeight & MEASURED_SIZE_MASK; 9513 } 9514 9515 /** 9516 * Return the full height measurement information for this view as computed 9517 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9518 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9519 * This should be used during measurement and layout calculations only. Use 9520 * {@link #getHeight()} to see how wide a view is after layout. 9521 * 9522 * @return The measured width of this view as a bit mask. 9523 */ 9524 public final int getMeasuredHeightAndState() { 9525 return mMeasuredHeight; 9526 } 9527 9528 /** 9529 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9530 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9531 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9532 * and the height component is at the shifted bits 9533 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9534 */ 9535 public final int getMeasuredState() { 9536 return (mMeasuredWidth&MEASURED_STATE_MASK) 9537 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9538 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9539 } 9540 9541 /** 9542 * The transform matrix of this view, which is calculated based on the current 9543 * roation, scale, and pivot properties. 9544 * 9545 * @see #getRotation() 9546 * @see #getScaleX() 9547 * @see #getScaleY() 9548 * @see #getPivotX() 9549 * @see #getPivotY() 9550 * @return The current transform matrix for the view 9551 */ 9552 public Matrix getMatrix() { 9553 if (mTransformationInfo != null) { 9554 updateMatrix(); 9555 return mTransformationInfo.mMatrix; 9556 } 9557 return Matrix.IDENTITY_MATRIX; 9558 } 9559 9560 /** 9561 * Utility function to determine if the value is far enough away from zero to be 9562 * considered non-zero. 9563 * @param value A floating point value to check for zero-ness 9564 * @return whether the passed-in value is far enough away from zero to be considered non-zero 9565 */ 9566 private static boolean nonzero(float value) { 9567 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 9568 } 9569 9570 /** 9571 * Returns true if the transform matrix is the identity matrix. 9572 * Recomputes the matrix if necessary. 9573 * 9574 * @return True if the transform matrix is the identity matrix, false otherwise. 9575 */ 9576 final boolean hasIdentityMatrix() { 9577 if (mTransformationInfo != null) { 9578 updateMatrix(); 9579 return mTransformationInfo.mMatrixIsIdentity; 9580 } 9581 return true; 9582 } 9583 9584 void ensureTransformationInfo() { 9585 if (mTransformationInfo == null) { 9586 mTransformationInfo = new TransformationInfo(); 9587 } 9588 } 9589 9590 /** 9591 * Recomputes the transform matrix if necessary. 9592 */ 9593 private void updateMatrix() { 9594 final TransformationInfo info = mTransformationInfo; 9595 if (info == null) { 9596 return; 9597 } 9598 if (info.mMatrixDirty) { 9599 // transform-related properties have changed since the last time someone 9600 // asked for the matrix; recalculate it with the current values 9601 9602 // Figure out if we need to update the pivot point 9603 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9604 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 9605 info.mPrevWidth = mRight - mLeft; 9606 info.mPrevHeight = mBottom - mTop; 9607 info.mPivotX = info.mPrevWidth / 2f; 9608 info.mPivotY = info.mPrevHeight / 2f; 9609 } 9610 } 9611 info.mMatrix.reset(); 9612 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 9613 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 9614 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 9615 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9616 } else { 9617 if (info.mCamera == null) { 9618 info.mCamera = new Camera(); 9619 info.matrix3D = new Matrix(); 9620 } 9621 info.mCamera.save(); 9622 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9623 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 9624 info.mCamera.getMatrix(info.matrix3D); 9625 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 9626 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 9627 info.mPivotY + info.mTranslationY); 9628 info.mMatrix.postConcat(info.matrix3D); 9629 info.mCamera.restore(); 9630 } 9631 info.mMatrixDirty = false; 9632 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 9633 info.mInverseMatrixDirty = true; 9634 } 9635 } 9636 9637 /** 9638 * Utility method to retrieve the inverse of the current mMatrix property. 9639 * We cache the matrix to avoid recalculating it when transform properties 9640 * have not changed. 9641 * 9642 * @return The inverse of the current matrix of this view. 9643 */ 9644 final Matrix getInverseMatrix() { 9645 final TransformationInfo info = mTransformationInfo; 9646 if (info != null) { 9647 updateMatrix(); 9648 if (info.mInverseMatrixDirty) { 9649 if (info.mInverseMatrix == null) { 9650 info.mInverseMatrix = new Matrix(); 9651 } 9652 info.mMatrix.invert(info.mInverseMatrix); 9653 info.mInverseMatrixDirty = false; 9654 } 9655 return info.mInverseMatrix; 9656 } 9657 return Matrix.IDENTITY_MATRIX; 9658 } 9659 9660 /** 9661 * Gets the distance along the Z axis from the camera to this view. 9662 * 9663 * @see #setCameraDistance(float) 9664 * 9665 * @return The distance along the Z axis. 9666 */ 9667 public float getCameraDistance() { 9668 ensureTransformationInfo(); 9669 final float dpi = mResources.getDisplayMetrics().densityDpi; 9670 final TransformationInfo info = mTransformationInfo; 9671 if (info.mCamera == null) { 9672 info.mCamera = new Camera(); 9673 info.matrix3D = new Matrix(); 9674 } 9675 return -(info.mCamera.getLocationZ() * dpi); 9676 } 9677 9678 /** 9679 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9680 * views are drawn) from the camera to this view. The camera's distance 9681 * affects 3D transformations, for instance rotations around the X and Y 9682 * axis. If the rotationX or rotationY properties are changed and this view is 9683 * large (more than half the size of the screen), it is recommended to always 9684 * use a camera distance that's greater than the height (X axis rotation) or 9685 * the width (Y axis rotation) of this view.</p> 9686 * 9687 * <p>The distance of the camera from the view plane can have an affect on the 9688 * perspective distortion of the view when it is rotated around the x or y axis. 9689 * For example, a large distance will result in a large viewing angle, and there 9690 * will not be much perspective distortion of the view as it rotates. A short 9691 * distance may cause much more perspective distortion upon rotation, and can 9692 * also result in some drawing artifacts if the rotated view ends up partially 9693 * behind the camera (which is why the recommendation is to use a distance at 9694 * least as far as the size of the view, if the view is to be rotated.)</p> 9695 * 9696 * <p>The distance is expressed in "depth pixels." The default distance depends 9697 * on the screen density. For instance, on a medium density display, the 9698 * default distance is 1280. On a high density display, the default distance 9699 * is 1920.</p> 9700 * 9701 * <p>If you want to specify a distance that leads to visually consistent 9702 * results across various densities, use the following formula:</p> 9703 * <pre> 9704 * float scale = context.getResources().getDisplayMetrics().density; 9705 * view.setCameraDistance(distance * scale); 9706 * </pre> 9707 * 9708 * <p>The density scale factor of a high density display is 1.5, 9709 * and 1920 = 1280 * 1.5.</p> 9710 * 9711 * @param distance The distance in "depth pixels", if negative the opposite 9712 * value is used 9713 * 9714 * @see #setRotationX(float) 9715 * @see #setRotationY(float) 9716 */ 9717 public void setCameraDistance(float distance) { 9718 invalidateViewProperty(true, false); 9719 9720 ensureTransformationInfo(); 9721 final float dpi = mResources.getDisplayMetrics().densityDpi; 9722 final TransformationInfo info = mTransformationInfo; 9723 if (info.mCamera == null) { 9724 info.mCamera = new Camera(); 9725 info.matrix3D = new Matrix(); 9726 } 9727 9728 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 9729 info.mMatrixDirty = true; 9730 9731 invalidateViewProperty(false, false); 9732 if (mDisplayList != null) { 9733 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 9734 } 9735 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9736 // View was rejected last time it was drawn by its parent; this may have changed 9737 invalidateParentIfNeeded(); 9738 } 9739 } 9740 9741 /** 9742 * The degrees that the view is rotated around the pivot point. 9743 * 9744 * @see #setRotation(float) 9745 * @see #getPivotX() 9746 * @see #getPivotY() 9747 * 9748 * @return The degrees of rotation. 9749 */ 9750 @ViewDebug.ExportedProperty(category = "drawing") 9751 public float getRotation() { 9752 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 9753 } 9754 9755 /** 9756 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9757 * result in clockwise rotation. 9758 * 9759 * @param rotation The degrees of rotation. 9760 * 9761 * @see #getRotation() 9762 * @see #getPivotX() 9763 * @see #getPivotY() 9764 * @see #setRotationX(float) 9765 * @see #setRotationY(float) 9766 * 9767 * @attr ref android.R.styleable#View_rotation 9768 */ 9769 public void setRotation(float rotation) { 9770 ensureTransformationInfo(); 9771 final TransformationInfo info = mTransformationInfo; 9772 if (info.mRotation != rotation) { 9773 // Double-invalidation is necessary to capture view's old and new areas 9774 invalidateViewProperty(true, false); 9775 info.mRotation = rotation; 9776 info.mMatrixDirty = true; 9777 invalidateViewProperty(false, true); 9778 if (mDisplayList != null) { 9779 mDisplayList.setRotation(rotation); 9780 } 9781 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9782 // View was rejected last time it was drawn by its parent; this may have changed 9783 invalidateParentIfNeeded(); 9784 } 9785 } 9786 } 9787 9788 /** 9789 * The degrees that the view is rotated around the vertical axis through the pivot point. 9790 * 9791 * @see #getPivotX() 9792 * @see #getPivotY() 9793 * @see #setRotationY(float) 9794 * 9795 * @return The degrees of Y rotation. 9796 */ 9797 @ViewDebug.ExportedProperty(category = "drawing") 9798 public float getRotationY() { 9799 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 9800 } 9801 9802 /** 9803 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9804 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9805 * down the y axis. 9806 * 9807 * When rotating large views, it is recommended to adjust the camera distance 9808 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9809 * 9810 * @param rotationY The degrees of Y rotation. 9811 * 9812 * @see #getRotationY() 9813 * @see #getPivotX() 9814 * @see #getPivotY() 9815 * @see #setRotation(float) 9816 * @see #setRotationX(float) 9817 * @see #setCameraDistance(float) 9818 * 9819 * @attr ref android.R.styleable#View_rotationY 9820 */ 9821 public void setRotationY(float rotationY) { 9822 ensureTransformationInfo(); 9823 final TransformationInfo info = mTransformationInfo; 9824 if (info.mRotationY != rotationY) { 9825 invalidateViewProperty(true, false); 9826 info.mRotationY = rotationY; 9827 info.mMatrixDirty = true; 9828 invalidateViewProperty(false, true); 9829 if (mDisplayList != null) { 9830 mDisplayList.setRotationY(rotationY); 9831 } 9832 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9833 // View was rejected last time it was drawn by its parent; this may have changed 9834 invalidateParentIfNeeded(); 9835 } 9836 } 9837 } 9838 9839 /** 9840 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9841 * 9842 * @see #getPivotX() 9843 * @see #getPivotY() 9844 * @see #setRotationX(float) 9845 * 9846 * @return The degrees of X rotation. 9847 */ 9848 @ViewDebug.ExportedProperty(category = "drawing") 9849 public float getRotationX() { 9850 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 9851 } 9852 9853 /** 9854 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9855 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9856 * x axis. 9857 * 9858 * When rotating large views, it is recommended to adjust the camera distance 9859 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9860 * 9861 * @param rotationX The degrees of X rotation. 9862 * 9863 * @see #getRotationX() 9864 * @see #getPivotX() 9865 * @see #getPivotY() 9866 * @see #setRotation(float) 9867 * @see #setRotationY(float) 9868 * @see #setCameraDistance(float) 9869 * 9870 * @attr ref android.R.styleable#View_rotationX 9871 */ 9872 public void setRotationX(float rotationX) { 9873 ensureTransformationInfo(); 9874 final TransformationInfo info = mTransformationInfo; 9875 if (info.mRotationX != rotationX) { 9876 invalidateViewProperty(true, false); 9877 info.mRotationX = rotationX; 9878 info.mMatrixDirty = true; 9879 invalidateViewProperty(false, true); 9880 if (mDisplayList != null) { 9881 mDisplayList.setRotationX(rotationX); 9882 } 9883 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9884 // View was rejected last time it was drawn by its parent; this may have changed 9885 invalidateParentIfNeeded(); 9886 } 9887 } 9888 } 9889 9890 /** 9891 * The amount that the view is scaled in x around the pivot point, as a proportion of 9892 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9893 * 9894 * <p>By default, this is 1.0f. 9895 * 9896 * @see #getPivotX() 9897 * @see #getPivotY() 9898 * @return The scaling factor. 9899 */ 9900 @ViewDebug.ExportedProperty(category = "drawing") 9901 public float getScaleX() { 9902 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 9903 } 9904 9905 /** 9906 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9907 * the view's unscaled width. A value of 1 means that no scaling is applied. 9908 * 9909 * @param scaleX The scaling factor. 9910 * @see #getPivotX() 9911 * @see #getPivotY() 9912 * 9913 * @attr ref android.R.styleable#View_scaleX 9914 */ 9915 public void setScaleX(float scaleX) { 9916 ensureTransformationInfo(); 9917 final TransformationInfo info = mTransformationInfo; 9918 if (info.mScaleX != scaleX) { 9919 invalidateViewProperty(true, false); 9920 info.mScaleX = scaleX; 9921 info.mMatrixDirty = true; 9922 invalidateViewProperty(false, true); 9923 if (mDisplayList != null) { 9924 mDisplayList.setScaleX(scaleX); 9925 } 9926 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9927 // View was rejected last time it was drawn by its parent; this may have changed 9928 invalidateParentIfNeeded(); 9929 } 9930 } 9931 } 9932 9933 /** 9934 * The amount that the view is scaled in y around the pivot point, as a proportion of 9935 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9936 * 9937 * <p>By default, this is 1.0f. 9938 * 9939 * @see #getPivotX() 9940 * @see #getPivotY() 9941 * @return The scaling factor. 9942 */ 9943 @ViewDebug.ExportedProperty(category = "drawing") 9944 public float getScaleY() { 9945 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 9946 } 9947 9948 /** 9949 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9950 * the view's unscaled width. A value of 1 means that no scaling is applied. 9951 * 9952 * @param scaleY The scaling factor. 9953 * @see #getPivotX() 9954 * @see #getPivotY() 9955 * 9956 * @attr ref android.R.styleable#View_scaleY 9957 */ 9958 public void setScaleY(float scaleY) { 9959 ensureTransformationInfo(); 9960 final TransformationInfo info = mTransformationInfo; 9961 if (info.mScaleY != scaleY) { 9962 invalidateViewProperty(true, false); 9963 info.mScaleY = scaleY; 9964 info.mMatrixDirty = true; 9965 invalidateViewProperty(false, true); 9966 if (mDisplayList != null) { 9967 mDisplayList.setScaleY(scaleY); 9968 } 9969 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9970 // View was rejected last time it was drawn by its parent; this may have changed 9971 invalidateParentIfNeeded(); 9972 } 9973 } 9974 } 9975 9976 /** 9977 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9978 * and {@link #setScaleX(float) scaled}. 9979 * 9980 * @see #getRotation() 9981 * @see #getScaleX() 9982 * @see #getScaleY() 9983 * @see #getPivotY() 9984 * @return The x location of the pivot point. 9985 * 9986 * @attr ref android.R.styleable#View_transformPivotX 9987 */ 9988 @ViewDebug.ExportedProperty(category = "drawing") 9989 public float getPivotX() { 9990 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 9991 } 9992 9993 /** 9994 * Sets the x location of the point around which the view is 9995 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9996 * By default, the pivot point is centered on the object. 9997 * Setting this property disables this behavior and causes the view to use only the 9998 * explicitly set pivotX and pivotY values. 9999 * 10000 * @param pivotX The x location of the pivot point. 10001 * @see #getRotation() 10002 * @see #getScaleX() 10003 * @see #getScaleY() 10004 * @see #getPivotY() 10005 * 10006 * @attr ref android.R.styleable#View_transformPivotX 10007 */ 10008 public void setPivotX(float pivotX) { 10009 ensureTransformationInfo(); 10010 final TransformationInfo info = mTransformationInfo; 10011 boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 10012 PFLAG_PIVOT_EXPLICITLY_SET; 10013 if (info.mPivotX != pivotX || !pivotSet) { 10014 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 10015 invalidateViewProperty(true, false); 10016 info.mPivotX = pivotX; 10017 info.mMatrixDirty = true; 10018 invalidateViewProperty(false, true); 10019 if (mDisplayList != null) { 10020 mDisplayList.setPivotX(pivotX); 10021 } 10022 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10023 // View was rejected last time it was drawn by its parent; this may have changed 10024 invalidateParentIfNeeded(); 10025 } 10026 } 10027 } 10028 10029 /** 10030 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10031 * and {@link #setScaleY(float) scaled}. 10032 * 10033 * @see #getRotation() 10034 * @see #getScaleX() 10035 * @see #getScaleY() 10036 * @see #getPivotY() 10037 * @return The y location of the pivot point. 10038 * 10039 * @attr ref android.R.styleable#View_transformPivotY 10040 */ 10041 @ViewDebug.ExportedProperty(category = "drawing") 10042 public float getPivotY() { 10043 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 10044 } 10045 10046 /** 10047 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10048 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10049 * Setting this property disables this behavior and causes the view to use only the 10050 * explicitly set pivotX and pivotY values. 10051 * 10052 * @param pivotY The y location of the pivot point. 10053 * @see #getRotation() 10054 * @see #getScaleX() 10055 * @see #getScaleY() 10056 * @see #getPivotY() 10057 * 10058 * @attr ref android.R.styleable#View_transformPivotY 10059 */ 10060 public void setPivotY(float pivotY) { 10061 ensureTransformationInfo(); 10062 final TransformationInfo info = mTransformationInfo; 10063 boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 10064 PFLAG_PIVOT_EXPLICITLY_SET; 10065 if (info.mPivotY != pivotY || !pivotSet) { 10066 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 10067 invalidateViewProperty(true, false); 10068 info.mPivotY = pivotY; 10069 info.mMatrixDirty = true; 10070 invalidateViewProperty(false, true); 10071 if (mDisplayList != null) { 10072 mDisplayList.setPivotY(pivotY); 10073 } 10074 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10075 // View was rejected last time it was drawn by its parent; this may have changed 10076 invalidateParentIfNeeded(); 10077 } 10078 } 10079 } 10080 10081 /** 10082 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10083 * completely transparent and 1 means the view is completely opaque. 10084 * 10085 * <p>By default this is 1.0f. 10086 * @return The opacity of the view. 10087 */ 10088 @ViewDebug.ExportedProperty(category = "drawing") 10089 public float getAlpha() { 10090 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10091 } 10092 10093 /** 10094 * Returns whether this View has content which overlaps. 10095 * 10096 * <p>This function, intended to be overridden by specific View types, is an optimization when 10097 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10098 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10099 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10100 * directly. An example of overlapping rendering is a TextView with a background image, such as 10101 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10102 * ImageView with only the foreground image. The default implementation returns true; subclasses 10103 * should override if they have cases which can be optimized.</p> 10104 * 10105 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10106 * necessitates that a View return true if it uses the methods internally without passing the 10107 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10108 * 10109 * @return true if the content in this view might overlap, false otherwise. 10110 */ 10111 public boolean hasOverlappingRendering() { 10112 return true; 10113 } 10114 10115 /** 10116 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10117 * completely transparent and 1 means the view is completely opaque.</p> 10118 * 10119 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10120 * performance implications, especially for large views. It is best to use the alpha property 10121 * sparingly and transiently, as in the case of fading animations.</p> 10122 * 10123 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10124 * strongly recommended for performance reasons to either override 10125 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10126 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10127 * 10128 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10129 * responsible for applying the opacity itself.</p> 10130 * 10131 * <p>Note that if the view is backed by a 10132 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10133 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10134 * 1.0 will supercede the alpha of the layer paint.</p> 10135 * 10136 * @param alpha The opacity of the view. 10137 * 10138 * @see #hasOverlappingRendering() 10139 * @see #setLayerType(int, android.graphics.Paint) 10140 * 10141 * @attr ref android.R.styleable#View_alpha 10142 */ 10143 public void setAlpha(float alpha) { 10144 ensureTransformationInfo(); 10145 if (mTransformationInfo.mAlpha != alpha) { 10146 mTransformationInfo.mAlpha = alpha; 10147 if (onSetAlpha((int) (alpha * 255))) { 10148 mPrivateFlags |= PFLAG_ALPHA_SET; 10149 // subclass is handling alpha - don't optimize rendering cache invalidation 10150 invalidateParentCaches(); 10151 invalidate(true); 10152 } else { 10153 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10154 invalidateViewProperty(true, false); 10155 if (mDisplayList != null) { 10156 mDisplayList.setAlpha(getFinalAlpha()); 10157 } 10158 } 10159 } 10160 } 10161 10162 /** 10163 * Faster version of setAlpha() which performs the same steps except there are 10164 * no calls to invalidate(). The caller of this function should perform proper invalidation 10165 * on the parent and this object. The return value indicates whether the subclass handles 10166 * alpha (the return value for onSetAlpha()). 10167 * 10168 * @param alpha The new value for the alpha property 10169 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10170 * the new value for the alpha property is different from the old value 10171 */ 10172 boolean setAlphaNoInvalidation(float alpha) { 10173 ensureTransformationInfo(); 10174 if (mTransformationInfo.mAlpha != alpha) { 10175 mTransformationInfo.mAlpha = alpha; 10176 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10177 if (subclassHandlesAlpha) { 10178 mPrivateFlags |= PFLAG_ALPHA_SET; 10179 return true; 10180 } else { 10181 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10182 if (mDisplayList != null) { 10183 mDisplayList.setAlpha(getFinalAlpha()); 10184 } 10185 } 10186 } 10187 return false; 10188 } 10189 10190 /** 10191 * This property is hidden and intended only for use by the Fade transition, which 10192 * animates it to produce a visual translucency that does not side-effect (or get 10193 * affected by) the real alpha property. This value is composited with the other 10194 * alpha value (and the AlphaAnimation value, when that is present) to produce 10195 * a final visual translucency result, which is what is passed into the DisplayList. 10196 * 10197 * @hide 10198 */ 10199 public void setTransitionAlpha(float alpha) { 10200 ensureTransformationInfo(); 10201 if (mTransformationInfo.mTransitionAlpha != alpha) { 10202 mTransformationInfo.mTransitionAlpha = alpha; 10203 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10204 invalidateViewProperty(true, false); 10205 if (mDisplayList != null) { 10206 mDisplayList.setAlpha(getFinalAlpha()); 10207 } 10208 } 10209 } 10210 10211 /** 10212 * Calculates the visual alpha of this view, which is a combination of the actual 10213 * alpha value and the transitionAlpha value (if set). 10214 */ 10215 private float getFinalAlpha() { 10216 if (mTransformationInfo != null) { 10217 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10218 } 10219 return 1; 10220 } 10221 10222 /** 10223 * This property is hidden and intended only for use by the Fade transition, which 10224 * animates it to produce a visual translucency that does not side-effect (or get 10225 * affected by) the real alpha property. This value is composited with the other 10226 * alpha value (and the AlphaAnimation value, when that is present) to produce 10227 * a final visual translucency result, which is what is passed into the DisplayList. 10228 * 10229 * @hide 10230 */ 10231 public float getTransitionAlpha() { 10232 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10233 } 10234 10235 /** 10236 * Top position of this view relative to its parent. 10237 * 10238 * @return The top of this view, in pixels. 10239 */ 10240 @ViewDebug.CapturedViewProperty 10241 public final int getTop() { 10242 return mTop; 10243 } 10244 10245 /** 10246 * Sets the top position of this view relative to its parent. This method is meant to be called 10247 * by the layout system and should not generally be called otherwise, because the property 10248 * may be changed at any time by the layout. 10249 * 10250 * @param top The top of this view, in pixels. 10251 */ 10252 public final void setTop(int top) { 10253 if (top != mTop) { 10254 updateMatrix(); 10255 final boolean matrixIsIdentity = mTransformationInfo == null 10256 || mTransformationInfo.mMatrixIsIdentity; 10257 if (matrixIsIdentity) { 10258 if (mAttachInfo != null) { 10259 int minTop; 10260 int yLoc; 10261 if (top < mTop) { 10262 minTop = top; 10263 yLoc = top - mTop; 10264 } else { 10265 minTop = mTop; 10266 yLoc = 0; 10267 } 10268 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10269 } 10270 } else { 10271 // Double-invalidation is necessary to capture view's old and new areas 10272 invalidate(true); 10273 } 10274 10275 int width = mRight - mLeft; 10276 int oldHeight = mBottom - mTop; 10277 10278 mTop = top; 10279 if (mDisplayList != null) { 10280 mDisplayList.setTop(mTop); 10281 } 10282 10283 sizeChange(width, mBottom - mTop, width, oldHeight); 10284 10285 if (!matrixIsIdentity) { 10286 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10287 // A change in dimension means an auto-centered pivot point changes, too 10288 mTransformationInfo.mMatrixDirty = true; 10289 } 10290 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10291 invalidate(true); 10292 } 10293 mBackgroundSizeChanged = true; 10294 invalidateParentIfNeeded(); 10295 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10296 // View was rejected last time it was drawn by its parent; this may have changed 10297 invalidateParentIfNeeded(); 10298 } 10299 } 10300 } 10301 10302 /** 10303 * Bottom position of this view relative to its parent. 10304 * 10305 * @return The bottom of this view, in pixels. 10306 */ 10307 @ViewDebug.CapturedViewProperty 10308 public final int getBottom() { 10309 return mBottom; 10310 } 10311 10312 /** 10313 * True if this view has changed since the last time being drawn. 10314 * 10315 * @return The dirty state of this view. 10316 */ 10317 public boolean isDirty() { 10318 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10319 } 10320 10321 /** 10322 * Sets the bottom position of this view relative to its parent. This method is meant to be 10323 * called by the layout system and should not generally be called otherwise, because the 10324 * property may be changed at any time by the layout. 10325 * 10326 * @param bottom The bottom of this view, in pixels. 10327 */ 10328 public final void setBottom(int bottom) { 10329 if (bottom != mBottom) { 10330 updateMatrix(); 10331 final boolean matrixIsIdentity = mTransformationInfo == null 10332 || mTransformationInfo.mMatrixIsIdentity; 10333 if (matrixIsIdentity) { 10334 if (mAttachInfo != null) { 10335 int maxBottom; 10336 if (bottom < mBottom) { 10337 maxBottom = mBottom; 10338 } else { 10339 maxBottom = bottom; 10340 } 10341 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10342 } 10343 } else { 10344 // Double-invalidation is necessary to capture view's old and new areas 10345 invalidate(true); 10346 } 10347 10348 int width = mRight - mLeft; 10349 int oldHeight = mBottom - mTop; 10350 10351 mBottom = bottom; 10352 if (mDisplayList != null) { 10353 mDisplayList.setBottom(mBottom); 10354 } 10355 10356 sizeChange(width, mBottom - mTop, width, oldHeight); 10357 10358 if (!matrixIsIdentity) { 10359 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10360 // A change in dimension means an auto-centered pivot point changes, too 10361 mTransformationInfo.mMatrixDirty = true; 10362 } 10363 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10364 invalidate(true); 10365 } 10366 mBackgroundSizeChanged = true; 10367 invalidateParentIfNeeded(); 10368 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10369 // View was rejected last time it was drawn by its parent; this may have changed 10370 invalidateParentIfNeeded(); 10371 } 10372 } 10373 } 10374 10375 /** 10376 * Left position of this view relative to its parent. 10377 * 10378 * @return The left edge of this view, in pixels. 10379 */ 10380 @ViewDebug.CapturedViewProperty 10381 public final int getLeft() { 10382 return mLeft; 10383 } 10384 10385 /** 10386 * Sets the left position of this view relative to its parent. This method is meant to be called 10387 * by the layout system and should not generally be called otherwise, because the property 10388 * may be changed at any time by the layout. 10389 * 10390 * @param left The bottom of this view, in pixels. 10391 */ 10392 public final void setLeft(int left) { 10393 if (left != mLeft) { 10394 updateMatrix(); 10395 final boolean matrixIsIdentity = mTransformationInfo == null 10396 || mTransformationInfo.mMatrixIsIdentity; 10397 if (matrixIsIdentity) { 10398 if (mAttachInfo != null) { 10399 int minLeft; 10400 int xLoc; 10401 if (left < mLeft) { 10402 minLeft = left; 10403 xLoc = left - mLeft; 10404 } else { 10405 minLeft = mLeft; 10406 xLoc = 0; 10407 } 10408 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10409 } 10410 } else { 10411 // Double-invalidation is necessary to capture view's old and new areas 10412 invalidate(true); 10413 } 10414 10415 int oldWidth = mRight - mLeft; 10416 int height = mBottom - mTop; 10417 10418 mLeft = left; 10419 if (mDisplayList != null) { 10420 mDisplayList.setLeft(left); 10421 } 10422 10423 sizeChange(mRight - mLeft, height, oldWidth, height); 10424 10425 if (!matrixIsIdentity) { 10426 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10427 // A change in dimension means an auto-centered pivot point changes, too 10428 mTransformationInfo.mMatrixDirty = true; 10429 } 10430 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10431 invalidate(true); 10432 } 10433 mBackgroundSizeChanged = true; 10434 invalidateParentIfNeeded(); 10435 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10436 // View was rejected last time it was drawn by its parent; this may have changed 10437 invalidateParentIfNeeded(); 10438 } 10439 } 10440 } 10441 10442 /** 10443 * Right position of this view relative to its parent. 10444 * 10445 * @return The right edge of this view, in pixels. 10446 */ 10447 @ViewDebug.CapturedViewProperty 10448 public final int getRight() { 10449 return mRight; 10450 } 10451 10452 /** 10453 * Sets the right position of this view relative to its parent. This method is meant to be called 10454 * by the layout system and should not generally be called otherwise, because the property 10455 * may be changed at any time by the layout. 10456 * 10457 * @param right The bottom of this view, in pixels. 10458 */ 10459 public final void setRight(int right) { 10460 if (right != mRight) { 10461 updateMatrix(); 10462 final boolean matrixIsIdentity = mTransformationInfo == null 10463 || mTransformationInfo.mMatrixIsIdentity; 10464 if (matrixIsIdentity) { 10465 if (mAttachInfo != null) { 10466 int maxRight; 10467 if (right < mRight) { 10468 maxRight = mRight; 10469 } else { 10470 maxRight = right; 10471 } 10472 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10473 } 10474 } else { 10475 // Double-invalidation is necessary to capture view's old and new areas 10476 invalidate(true); 10477 } 10478 10479 int oldWidth = mRight - mLeft; 10480 int height = mBottom - mTop; 10481 10482 mRight = right; 10483 if (mDisplayList != null) { 10484 mDisplayList.setRight(mRight); 10485 } 10486 10487 sizeChange(mRight - mLeft, height, oldWidth, height); 10488 10489 if (!matrixIsIdentity) { 10490 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10491 // A change in dimension means an auto-centered pivot point changes, too 10492 mTransformationInfo.mMatrixDirty = true; 10493 } 10494 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10495 invalidate(true); 10496 } 10497 mBackgroundSizeChanged = true; 10498 invalidateParentIfNeeded(); 10499 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10500 // View was rejected last time it was drawn by its parent; this may have changed 10501 invalidateParentIfNeeded(); 10502 } 10503 } 10504 } 10505 10506 /** 10507 * The visual x position of this view, in pixels. This is equivalent to the 10508 * {@link #setTranslationX(float) translationX} property plus the current 10509 * {@link #getLeft() left} property. 10510 * 10511 * @return The visual x position of this view, in pixels. 10512 */ 10513 @ViewDebug.ExportedProperty(category = "drawing") 10514 public float getX() { 10515 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 10516 } 10517 10518 /** 10519 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10520 * {@link #setTranslationX(float) translationX} property to be the difference between 10521 * the x value passed in and the current {@link #getLeft() left} property. 10522 * 10523 * @param x The visual x position of this view, in pixels. 10524 */ 10525 public void setX(float x) { 10526 setTranslationX(x - mLeft); 10527 } 10528 10529 /** 10530 * The visual y position of this view, in pixels. This is equivalent to the 10531 * {@link #setTranslationY(float) translationY} property plus the current 10532 * {@link #getTop() top} property. 10533 * 10534 * @return The visual y position of this view, in pixels. 10535 */ 10536 @ViewDebug.ExportedProperty(category = "drawing") 10537 public float getY() { 10538 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 10539 } 10540 10541 /** 10542 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10543 * {@link #setTranslationY(float) translationY} property to be the difference between 10544 * the y value passed in and the current {@link #getTop() top} property. 10545 * 10546 * @param y The visual y position of this view, in pixels. 10547 */ 10548 public void setY(float y) { 10549 setTranslationY(y - mTop); 10550 } 10551 10552 10553 /** 10554 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10555 * This position is post-layout, in addition to wherever the object's 10556 * layout placed it. 10557 * 10558 * @return The horizontal position of this view relative to its left position, in pixels. 10559 */ 10560 @ViewDebug.ExportedProperty(category = "drawing") 10561 public float getTranslationX() { 10562 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 10563 } 10564 10565 /** 10566 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10567 * This effectively positions the object post-layout, in addition to wherever the object's 10568 * layout placed it. 10569 * 10570 * @param translationX The horizontal position of this view relative to its left position, 10571 * in pixels. 10572 * 10573 * @attr ref android.R.styleable#View_translationX 10574 */ 10575 public void setTranslationX(float translationX) { 10576 ensureTransformationInfo(); 10577 final TransformationInfo info = mTransformationInfo; 10578 if (info.mTranslationX != translationX) { 10579 // Double-invalidation is necessary to capture view's old and new areas 10580 invalidateViewProperty(true, false); 10581 info.mTranslationX = translationX; 10582 info.mMatrixDirty = true; 10583 invalidateViewProperty(false, true); 10584 if (mDisplayList != null) { 10585 mDisplayList.setTranslationX(translationX); 10586 } 10587 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10588 // View was rejected last time it was drawn by its parent; this may have changed 10589 invalidateParentIfNeeded(); 10590 } 10591 } 10592 } 10593 10594 /** 10595 * The vertical location of this view relative to its {@link #getTop() top} position. 10596 * This position is post-layout, in addition to wherever the object's 10597 * layout placed it. 10598 * 10599 * @return The vertical position of this view relative to its top position, 10600 * in pixels. 10601 */ 10602 @ViewDebug.ExportedProperty(category = "drawing") 10603 public float getTranslationY() { 10604 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 10605 } 10606 10607 /** 10608 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10609 * This effectively positions the object post-layout, in addition to wherever the object's 10610 * layout placed it. 10611 * 10612 * @param translationY The vertical position of this view relative to its top position, 10613 * in pixels. 10614 * 10615 * @attr ref android.R.styleable#View_translationY 10616 */ 10617 public void setTranslationY(float translationY) { 10618 ensureTransformationInfo(); 10619 final TransformationInfo info = mTransformationInfo; 10620 if (info.mTranslationY != translationY) { 10621 invalidateViewProperty(true, false); 10622 info.mTranslationY = translationY; 10623 info.mMatrixDirty = true; 10624 invalidateViewProperty(false, true); 10625 if (mDisplayList != null) { 10626 mDisplayList.setTranslationY(translationY); 10627 } 10628 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10629 // View was rejected last time it was drawn by its parent; this may have changed 10630 invalidateParentIfNeeded(); 10631 } 10632 } 10633 } 10634 10635 /** 10636 * The depth location of this view relative to its parent. 10637 * 10638 * @return The depth of this view relative to its parent. 10639 */ 10640 @ViewDebug.ExportedProperty(category = "drawing") 10641 public float getTranslationZ() { 10642 return mTransformationInfo != null ? mTransformationInfo.mTranslationZ : 0; 10643 } 10644 10645 /** 10646 * Sets the depth location of this view relative to its parent. 10647 * 10648 * @attr ref android.R.styleable#View_translationZ 10649 */ 10650 public void setTranslationZ(float translationZ) { 10651 ensureTransformationInfo(); 10652 final TransformationInfo info = mTransformationInfo; 10653 if (info.mTranslationZ != translationZ) { 10654 invalidateViewProperty(true, false); 10655 info.mTranslationZ = translationZ; 10656 info.mMatrixDirty = true; 10657 invalidateViewProperty(false, true); 10658 if (mDisplayList != null) { 10659 mDisplayList.setTranslationZ(translationZ); 10660 } 10661 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10662 // View was rejected last time it was drawn by its parent; this may have changed 10663 invalidateParentIfNeeded(); 10664 } 10665 } 10666 } 10667 10668 /** 10669 * @hide 10670 */ 10671 public final void getOutline(Path outline) { 10672 if (mOutline == null) { 10673 outline.reset(); 10674 } else { 10675 outline.set(mOutline); 10676 } 10677 } 10678 10679 /** 10680 * @hide 10681 */ 10682 public void setOutline(Path path) { 10683 // always copy the path since caller may reuse 10684 if (mOutline == null) { 10685 mOutline = new Path(path); 10686 } else { 10687 mOutline.set(path); 10688 } 10689 10690 if (mDisplayList != null) { 10691 mDisplayList.setOutline(path); 10692 } 10693 } 10694 10695 /** 10696 * Hit rectangle in parent's coordinates 10697 * 10698 * @param outRect The hit rectangle of the view. 10699 */ 10700 public void getHitRect(Rect outRect) { 10701 updateMatrix(); 10702 final TransformationInfo info = mTransformationInfo; 10703 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 10704 outRect.set(mLeft, mTop, mRight, mBottom); 10705 } else { 10706 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10707 tmpRect.set(0, 0, getWidth(), getHeight()); 10708 info.mMatrix.mapRect(tmpRect); 10709 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10710 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10711 } 10712 } 10713 10714 /** 10715 * Determines whether the given point, in local coordinates is inside the view. 10716 */ 10717 /*package*/ final boolean pointInView(float localX, float localY) { 10718 return localX >= 0 && localX < (mRight - mLeft) 10719 && localY >= 0 && localY < (mBottom - mTop); 10720 } 10721 10722 /** 10723 * Utility method to determine whether the given point, in local coordinates, 10724 * is inside the view, where the area of the view is expanded by the slop factor. 10725 * This method is called while processing touch-move events to determine if the event 10726 * is still within the view. 10727 * 10728 * @hide 10729 */ 10730 public boolean pointInView(float localX, float localY, float slop) { 10731 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10732 localY < ((mBottom - mTop) + slop); 10733 } 10734 10735 /** 10736 * When a view has focus and the user navigates away from it, the next view is searched for 10737 * starting from the rectangle filled in by this method. 10738 * 10739 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10740 * of the view. However, if your view maintains some idea of internal selection, 10741 * such as a cursor, or a selected row or column, you should override this method and 10742 * fill in a more specific rectangle. 10743 * 10744 * @param r The rectangle to fill in, in this view's coordinates. 10745 */ 10746 public void getFocusedRect(Rect r) { 10747 getDrawingRect(r); 10748 } 10749 10750 /** 10751 * If some part of this view is not clipped by any of its parents, then 10752 * return that area in r in global (root) coordinates. To convert r to local 10753 * coordinates (without taking possible View rotations into account), offset 10754 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10755 * If the view is completely clipped or translated out, return false. 10756 * 10757 * @param r If true is returned, r holds the global coordinates of the 10758 * visible portion of this view. 10759 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10760 * between this view and its root. globalOffet may be null. 10761 * @return true if r is non-empty (i.e. part of the view is visible at the 10762 * root level. 10763 */ 10764 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10765 int width = mRight - mLeft; 10766 int height = mBottom - mTop; 10767 if (width > 0 && height > 0) { 10768 r.set(0, 0, width, height); 10769 if (globalOffset != null) { 10770 globalOffset.set(-mScrollX, -mScrollY); 10771 } 10772 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10773 } 10774 return false; 10775 } 10776 10777 public final boolean getGlobalVisibleRect(Rect r) { 10778 return getGlobalVisibleRect(r, null); 10779 } 10780 10781 public final boolean getLocalVisibleRect(Rect r) { 10782 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10783 if (getGlobalVisibleRect(r, offset)) { 10784 r.offset(-offset.x, -offset.y); // make r local 10785 return true; 10786 } 10787 return false; 10788 } 10789 10790 /** 10791 * Offset this view's vertical location by the specified number of pixels. 10792 * 10793 * @param offset the number of pixels to offset the view by 10794 */ 10795 public void offsetTopAndBottom(int offset) { 10796 if (offset != 0) { 10797 updateMatrix(); 10798 final boolean matrixIsIdentity = mTransformationInfo == null 10799 || mTransformationInfo.mMatrixIsIdentity; 10800 if (matrixIsIdentity) { 10801 if (mDisplayList != null) { 10802 invalidateViewProperty(false, false); 10803 } else { 10804 final ViewParent p = mParent; 10805 if (p != null && mAttachInfo != null) { 10806 final Rect r = mAttachInfo.mTmpInvalRect; 10807 int minTop; 10808 int maxBottom; 10809 int yLoc; 10810 if (offset < 0) { 10811 minTop = mTop + offset; 10812 maxBottom = mBottom; 10813 yLoc = offset; 10814 } else { 10815 minTop = mTop; 10816 maxBottom = mBottom + offset; 10817 yLoc = 0; 10818 } 10819 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10820 p.invalidateChild(this, r); 10821 } 10822 } 10823 } else { 10824 invalidateViewProperty(false, false); 10825 } 10826 10827 mTop += offset; 10828 mBottom += offset; 10829 if (mDisplayList != null) { 10830 mDisplayList.offsetTopAndBottom(offset); 10831 invalidateViewProperty(false, false); 10832 } else { 10833 if (!matrixIsIdentity) { 10834 invalidateViewProperty(false, true); 10835 } 10836 invalidateParentIfNeeded(); 10837 } 10838 } 10839 } 10840 10841 /** 10842 * Offset this view's horizontal location by the specified amount of pixels. 10843 * 10844 * @param offset the number of pixels to offset the view by 10845 */ 10846 public void offsetLeftAndRight(int offset) { 10847 if (offset != 0) { 10848 updateMatrix(); 10849 final boolean matrixIsIdentity = mTransformationInfo == null 10850 || mTransformationInfo.mMatrixIsIdentity; 10851 if (matrixIsIdentity) { 10852 if (mDisplayList != null) { 10853 invalidateViewProperty(false, false); 10854 } else { 10855 final ViewParent p = mParent; 10856 if (p != null && mAttachInfo != null) { 10857 final Rect r = mAttachInfo.mTmpInvalRect; 10858 int minLeft; 10859 int maxRight; 10860 if (offset < 0) { 10861 minLeft = mLeft + offset; 10862 maxRight = mRight; 10863 } else { 10864 minLeft = mLeft; 10865 maxRight = mRight + offset; 10866 } 10867 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10868 p.invalidateChild(this, r); 10869 } 10870 } 10871 } else { 10872 invalidateViewProperty(false, false); 10873 } 10874 10875 mLeft += offset; 10876 mRight += offset; 10877 if (mDisplayList != null) { 10878 mDisplayList.offsetLeftAndRight(offset); 10879 invalidateViewProperty(false, false); 10880 } else { 10881 if (!matrixIsIdentity) { 10882 invalidateViewProperty(false, true); 10883 } 10884 invalidateParentIfNeeded(); 10885 } 10886 } 10887 } 10888 10889 /** 10890 * Get the LayoutParams associated with this view. All views should have 10891 * layout parameters. These supply parameters to the <i>parent</i> of this 10892 * view specifying how it should be arranged. There are many subclasses of 10893 * ViewGroup.LayoutParams, and these correspond to the different subclasses 10894 * of ViewGroup that are responsible for arranging their children. 10895 * 10896 * This method may return null if this View is not attached to a parent 10897 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 10898 * was not invoked successfully. When a View is attached to a parent 10899 * ViewGroup, this method must not return null. 10900 * 10901 * @return The LayoutParams associated with this view, or null if no 10902 * parameters have been set yet 10903 */ 10904 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 10905 public ViewGroup.LayoutParams getLayoutParams() { 10906 return mLayoutParams; 10907 } 10908 10909 /** 10910 * Set the layout parameters associated with this view. These supply 10911 * parameters to the <i>parent</i> of this view specifying how it should be 10912 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 10913 * correspond to the different subclasses of ViewGroup that are responsible 10914 * for arranging their children. 10915 * 10916 * @param params The layout parameters for this view, cannot be null 10917 */ 10918 public void setLayoutParams(ViewGroup.LayoutParams params) { 10919 if (params == null) { 10920 throw new NullPointerException("Layout parameters cannot be null"); 10921 } 10922 mLayoutParams = params; 10923 resolveLayoutParams(); 10924 if (mParent instanceof ViewGroup) { 10925 ((ViewGroup) mParent).onSetLayoutParams(this, params); 10926 } 10927 requestLayout(); 10928 } 10929 10930 /** 10931 * Resolve the layout parameters depending on the resolved layout direction 10932 * 10933 * @hide 10934 */ 10935 public void resolveLayoutParams() { 10936 if (mLayoutParams != null) { 10937 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 10938 } 10939 } 10940 10941 /** 10942 * Set the scrolled position of your view. This will cause a call to 10943 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10944 * invalidated. 10945 * @param x the x position to scroll to 10946 * @param y the y position to scroll to 10947 */ 10948 public void scrollTo(int x, int y) { 10949 if (mScrollX != x || mScrollY != y) { 10950 int oldX = mScrollX; 10951 int oldY = mScrollY; 10952 mScrollX = x; 10953 mScrollY = y; 10954 invalidateParentCaches(); 10955 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 10956 if (!awakenScrollBars()) { 10957 postInvalidateOnAnimation(); 10958 } 10959 } 10960 } 10961 10962 /** 10963 * Move the scrolled position of your view. This will cause a call to 10964 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10965 * invalidated. 10966 * @param x the amount of pixels to scroll by horizontally 10967 * @param y the amount of pixels to scroll by vertically 10968 */ 10969 public void scrollBy(int x, int y) { 10970 scrollTo(mScrollX + x, mScrollY + y); 10971 } 10972 10973 /** 10974 * <p>Trigger the scrollbars to draw. When invoked this method starts an 10975 * animation to fade the scrollbars out after a default delay. If a subclass 10976 * provides animated scrolling, the start delay should equal the duration 10977 * of the scrolling animation.</p> 10978 * 10979 * <p>The animation starts only if at least one of the scrollbars is 10980 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 10981 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10982 * this method returns true, and false otherwise. If the animation is 10983 * started, this method calls {@link #invalidate()}; in that case the 10984 * caller should not call {@link #invalidate()}.</p> 10985 * 10986 * <p>This method should be invoked every time a subclass directly updates 10987 * the scroll parameters.</p> 10988 * 10989 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 10990 * and {@link #scrollTo(int, int)}.</p> 10991 * 10992 * @return true if the animation is played, false otherwise 10993 * 10994 * @see #awakenScrollBars(int) 10995 * @see #scrollBy(int, int) 10996 * @see #scrollTo(int, int) 10997 * @see #isHorizontalScrollBarEnabled() 10998 * @see #isVerticalScrollBarEnabled() 10999 * @see #setHorizontalScrollBarEnabled(boolean) 11000 * @see #setVerticalScrollBarEnabled(boolean) 11001 */ 11002 protected boolean awakenScrollBars() { 11003 return mScrollCache != null && 11004 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11005 } 11006 11007 /** 11008 * Trigger the scrollbars to draw. 11009 * This method differs from awakenScrollBars() only in its default duration. 11010 * initialAwakenScrollBars() will show the scroll bars for longer than 11011 * usual to give the user more of a chance to notice them. 11012 * 11013 * @return true if the animation is played, false otherwise. 11014 */ 11015 private boolean initialAwakenScrollBars() { 11016 return mScrollCache != null && 11017 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11018 } 11019 11020 /** 11021 * <p> 11022 * Trigger the scrollbars to draw. When invoked this method starts an 11023 * animation to fade the scrollbars out after a fixed delay. If a subclass 11024 * provides animated scrolling, the start delay should equal the duration of 11025 * the scrolling animation. 11026 * </p> 11027 * 11028 * <p> 11029 * The animation starts only if at least one of the scrollbars is enabled, 11030 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11031 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11032 * this method returns true, and false otherwise. If the animation is 11033 * started, this method calls {@link #invalidate()}; in that case the caller 11034 * should not call {@link #invalidate()}. 11035 * </p> 11036 * 11037 * <p> 11038 * This method should be invoked everytime a subclass directly updates the 11039 * scroll parameters. 11040 * </p> 11041 * 11042 * @param startDelay the delay, in milliseconds, after which the animation 11043 * should start; when the delay is 0, the animation starts 11044 * immediately 11045 * @return true if the animation is played, false otherwise 11046 * 11047 * @see #scrollBy(int, int) 11048 * @see #scrollTo(int, int) 11049 * @see #isHorizontalScrollBarEnabled() 11050 * @see #isVerticalScrollBarEnabled() 11051 * @see #setHorizontalScrollBarEnabled(boolean) 11052 * @see #setVerticalScrollBarEnabled(boolean) 11053 */ 11054 protected boolean awakenScrollBars(int startDelay) { 11055 return awakenScrollBars(startDelay, true); 11056 } 11057 11058 /** 11059 * <p> 11060 * Trigger the scrollbars to draw. When invoked this method starts an 11061 * animation to fade the scrollbars out after a fixed delay. If a subclass 11062 * provides animated scrolling, the start delay should equal the duration of 11063 * the scrolling animation. 11064 * </p> 11065 * 11066 * <p> 11067 * The animation starts only if at least one of the scrollbars is enabled, 11068 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11069 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11070 * this method returns true, and false otherwise. If the animation is 11071 * started, this method calls {@link #invalidate()} if the invalidate parameter 11072 * is set to true; in that case the caller 11073 * should not call {@link #invalidate()}. 11074 * </p> 11075 * 11076 * <p> 11077 * This method should be invoked everytime a subclass directly updates the 11078 * scroll parameters. 11079 * </p> 11080 * 11081 * @param startDelay the delay, in milliseconds, after which the animation 11082 * should start; when the delay is 0, the animation starts 11083 * immediately 11084 * 11085 * @param invalidate Wheter this method should call invalidate 11086 * 11087 * @return true if the animation is played, false otherwise 11088 * 11089 * @see #scrollBy(int, int) 11090 * @see #scrollTo(int, int) 11091 * @see #isHorizontalScrollBarEnabled() 11092 * @see #isVerticalScrollBarEnabled() 11093 * @see #setHorizontalScrollBarEnabled(boolean) 11094 * @see #setVerticalScrollBarEnabled(boolean) 11095 */ 11096 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11097 final ScrollabilityCache scrollCache = mScrollCache; 11098 11099 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11100 return false; 11101 } 11102 11103 if (scrollCache.scrollBar == null) { 11104 scrollCache.scrollBar = new ScrollBarDrawable(); 11105 } 11106 11107 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11108 11109 if (invalidate) { 11110 // Invalidate to show the scrollbars 11111 postInvalidateOnAnimation(); 11112 } 11113 11114 if (scrollCache.state == ScrollabilityCache.OFF) { 11115 // FIXME: this is copied from WindowManagerService. 11116 // We should get this value from the system when it 11117 // is possible to do so. 11118 final int KEY_REPEAT_FIRST_DELAY = 750; 11119 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11120 } 11121 11122 // Tell mScrollCache when we should start fading. This may 11123 // extend the fade start time if one was already scheduled 11124 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11125 scrollCache.fadeStartTime = fadeStartTime; 11126 scrollCache.state = ScrollabilityCache.ON; 11127 11128 // Schedule our fader to run, unscheduling any old ones first 11129 if (mAttachInfo != null) { 11130 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11131 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11132 } 11133 11134 return true; 11135 } 11136 11137 return false; 11138 } 11139 11140 /** 11141 * Do not invalidate views which are not visible and which are not running an animation. They 11142 * will not get drawn and they should not set dirty flags as if they will be drawn 11143 */ 11144 private boolean skipInvalidate() { 11145 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11146 (!(mParent instanceof ViewGroup) || 11147 !((ViewGroup) mParent).isViewTransitioning(this)); 11148 } 11149 /** 11150 * Mark the area defined by dirty as needing to be drawn. If the view is 11151 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 11152 * in the future. This must be called from a UI thread. To call from a non-UI 11153 * thread, call {@link #postInvalidate()}. 11154 * 11155 * WARNING: This method is destructive to dirty. 11156 * @param dirty the rectangle representing the bounds of the dirty region 11157 */ 11158 public void invalidate(Rect dirty) { 11159 if (skipInvalidate()) { 11160 return; 11161 } 11162 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 11163 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 11164 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 11165 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11166 mPrivateFlags |= PFLAG_INVALIDATED; 11167 mPrivateFlags |= PFLAG_DIRTY; 11168 final ViewParent p = mParent; 11169 final AttachInfo ai = mAttachInfo; 11170 if (p != null && ai != null) { 11171 final int scrollX = mScrollX; 11172 final int scrollY = mScrollY; 11173 final Rect r = ai.mTmpInvalRect; 11174 r.set(dirty.left - scrollX, dirty.top - scrollY, 11175 dirty.right - scrollX, dirty.bottom - scrollY); 11176 mParent.invalidateChild(this, r); 11177 } 11178 } 11179 } 11180 11181 /** 11182 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 11183 * The coordinates of the dirty rect are relative to the view. 11184 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 11185 * will be called at some point in the future. This must be called from 11186 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 11187 * @param l the left position of the dirty region 11188 * @param t the top position of the dirty region 11189 * @param r the right position of the dirty region 11190 * @param b the bottom position of the dirty region 11191 */ 11192 public void invalidate(int l, int t, int r, int b) { 11193 if (skipInvalidate()) { 11194 return; 11195 } 11196 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 11197 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 11198 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 11199 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11200 mPrivateFlags |= PFLAG_INVALIDATED; 11201 mPrivateFlags |= PFLAG_DIRTY; 11202 final ViewParent p = mParent; 11203 final AttachInfo ai = mAttachInfo; 11204 if (p != null && ai != null && l < r && t < b) { 11205 final int scrollX = mScrollX; 11206 final int scrollY = mScrollY; 11207 final Rect tmpr = ai.mTmpInvalRect; 11208 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 11209 p.invalidateChild(this, tmpr); 11210 } 11211 } 11212 } 11213 11214 /** 11215 * Invalidate the whole view. If the view is visible, 11216 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11217 * the future. This must be called from a UI thread. To call from a non-UI thread, 11218 * call {@link #postInvalidate()}. 11219 */ 11220 public void invalidate() { 11221 invalidate(true); 11222 } 11223 11224 /** 11225 * This is where the invalidate() work actually happens. A full invalidate() 11226 * causes the drawing cache to be invalidated, but this function can be called with 11227 * invalidateCache set to false to skip that invalidation step for cases that do not 11228 * need it (for example, a component that remains at the same dimensions with the same 11229 * content). 11230 * 11231 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 11232 * well. This is usually true for a full invalidate, but may be set to false if the 11233 * View's contents or dimensions have not changed. 11234 */ 11235 void invalidate(boolean invalidateCache) { 11236 if (skipInvalidate()) { 11237 return; 11238 } 11239 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 11240 (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) || 11241 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) { 11242 mLastIsOpaque = isOpaque(); 11243 mPrivateFlags &= ~PFLAG_DRAWN; 11244 mPrivateFlags |= PFLAG_DIRTY; 11245 if (invalidateCache) { 11246 mPrivateFlags |= PFLAG_INVALIDATED; 11247 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11248 } 11249 final AttachInfo ai = mAttachInfo; 11250 final ViewParent p = mParent; 11251 11252 if (p != null && ai != null) { 11253 final Rect r = ai.mTmpInvalRect; 11254 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11255 // Don't call invalidate -- we don't want to internally scroll 11256 // our own bounds 11257 p.invalidateChild(this, r); 11258 } 11259 } 11260 } 11261 11262 /** 11263 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11264 * set any flags or handle all of the cases handled by the default invalidation methods. 11265 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11266 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11267 * walk up the hierarchy, transforming the dirty rect as necessary. 11268 * 11269 * The method also handles normal invalidation logic if display list properties are not 11270 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11271 * backup approach, to handle these cases used in the various property-setting methods. 11272 * 11273 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11274 * are not being used in this view 11275 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11276 * list properties are not being used in this view 11277 */ 11278 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11279 if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) { 11280 if (invalidateParent) { 11281 invalidateParentCaches(); 11282 } 11283 if (forceRedraw) { 11284 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11285 } 11286 invalidate(false); 11287 } else { 11288 final AttachInfo ai = mAttachInfo; 11289 final ViewParent p = mParent; 11290 if (p != null && ai != null) { 11291 final Rect r = ai.mTmpInvalRect; 11292 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11293 if (mParent instanceof ViewGroup) { 11294 ((ViewGroup) mParent).invalidateChildFast(this, r); 11295 } else { 11296 mParent.invalidateChild(this, r); 11297 } 11298 } 11299 } 11300 } 11301 11302 /** 11303 * Utility method to transform a given Rect by the current matrix of this view. 11304 */ 11305 void transformRect(final Rect rect) { 11306 if (!getMatrix().isIdentity()) { 11307 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11308 boundingRect.set(rect); 11309 getMatrix().mapRect(boundingRect); 11310 rect.set((int) Math.floor(boundingRect.left), 11311 (int) Math.floor(boundingRect.top), 11312 (int) Math.ceil(boundingRect.right), 11313 (int) Math.ceil(boundingRect.bottom)); 11314 } 11315 } 11316 11317 /** 11318 * Used to indicate that the parent of this view should clear its caches. This functionality 11319 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11320 * which is necessary when various parent-managed properties of the view change, such as 11321 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11322 * clears the parent caches and does not causes an invalidate event. 11323 * 11324 * @hide 11325 */ 11326 protected void invalidateParentCaches() { 11327 if (mParent instanceof View) { 11328 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11329 } 11330 } 11331 11332 /** 11333 * Used to indicate that the parent of this view should be invalidated. This functionality 11334 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11335 * which is necessary when various parent-managed properties of the view change, such as 11336 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11337 * an invalidation event to the parent. 11338 * 11339 * @hide 11340 */ 11341 protected void invalidateParentIfNeeded() { 11342 if (isHardwareAccelerated() && mParent instanceof View) { 11343 ((View) mParent).invalidate(true); 11344 } 11345 } 11346 11347 /** 11348 * Indicates whether this View is opaque. An opaque View guarantees that it will 11349 * draw all the pixels overlapping its bounds using a fully opaque color. 11350 * 11351 * Subclasses of View should override this method whenever possible to indicate 11352 * whether an instance is opaque. Opaque Views are treated in a special way by 11353 * the View hierarchy, possibly allowing it to perform optimizations during 11354 * invalidate/draw passes. 11355 * 11356 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11357 */ 11358 @ViewDebug.ExportedProperty(category = "drawing") 11359 public boolean isOpaque() { 11360 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11361 getFinalAlpha() >= 1.0f; 11362 } 11363 11364 /** 11365 * @hide 11366 */ 11367 protected void computeOpaqueFlags() { 11368 // Opaque if: 11369 // - Has a background 11370 // - Background is opaque 11371 // - Doesn't have scrollbars or scrollbars overlay 11372 11373 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11374 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11375 } else { 11376 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11377 } 11378 11379 final int flags = mViewFlags; 11380 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11381 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11382 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11383 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11384 } else { 11385 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11386 } 11387 } 11388 11389 /** 11390 * @hide 11391 */ 11392 protected boolean hasOpaqueScrollbars() { 11393 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11394 } 11395 11396 /** 11397 * @return A handler associated with the thread running the View. This 11398 * handler can be used to pump events in the UI events queue. 11399 */ 11400 public Handler getHandler() { 11401 final AttachInfo attachInfo = mAttachInfo; 11402 if (attachInfo != null) { 11403 return attachInfo.mHandler; 11404 } 11405 return null; 11406 } 11407 11408 /** 11409 * Gets the view root associated with the View. 11410 * @return The view root, or null if none. 11411 * @hide 11412 */ 11413 public ViewRootImpl getViewRootImpl() { 11414 if (mAttachInfo != null) { 11415 return mAttachInfo.mViewRootImpl; 11416 } 11417 return null; 11418 } 11419 11420 /** 11421 * @hide 11422 */ 11423 public HardwareRenderer getHardwareRenderer() { 11424 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11425 } 11426 11427 /** 11428 * <p>Causes the Runnable to be added to the message queue. 11429 * The runnable will be run on the user interface thread.</p> 11430 * 11431 * @param action The Runnable that will be executed. 11432 * 11433 * @return Returns true if the Runnable was successfully placed in to the 11434 * message queue. Returns false on failure, usually because the 11435 * looper processing the message queue is exiting. 11436 * 11437 * @see #postDelayed 11438 * @see #removeCallbacks 11439 */ 11440 public boolean post(Runnable action) { 11441 final AttachInfo attachInfo = mAttachInfo; 11442 if (attachInfo != null) { 11443 return attachInfo.mHandler.post(action); 11444 } 11445 // Assume that post will succeed later 11446 ViewRootImpl.getRunQueue().post(action); 11447 return true; 11448 } 11449 11450 /** 11451 * <p>Causes the Runnable to be added to the message queue, to be run 11452 * after the specified amount of time elapses. 11453 * The runnable will be run on the user interface thread.</p> 11454 * 11455 * @param action The Runnable that will be executed. 11456 * @param delayMillis The delay (in milliseconds) until the Runnable 11457 * will be executed. 11458 * 11459 * @return true if the Runnable was successfully placed in to the 11460 * message queue. Returns false on failure, usually because the 11461 * looper processing the message queue is exiting. Note that a 11462 * result of true does not mean the Runnable will be processed -- 11463 * if the looper is quit before the delivery time of the message 11464 * occurs then the message will be dropped. 11465 * 11466 * @see #post 11467 * @see #removeCallbacks 11468 */ 11469 public boolean postDelayed(Runnable action, long delayMillis) { 11470 final AttachInfo attachInfo = mAttachInfo; 11471 if (attachInfo != null) { 11472 return attachInfo.mHandler.postDelayed(action, delayMillis); 11473 } 11474 // Assume that post will succeed later 11475 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11476 return true; 11477 } 11478 11479 /** 11480 * <p>Causes the Runnable to execute on the next animation time step. 11481 * The runnable will be run on the user interface thread.</p> 11482 * 11483 * @param action The Runnable that will be executed. 11484 * 11485 * @see #postOnAnimationDelayed 11486 * @see #removeCallbacks 11487 */ 11488 public void postOnAnimation(Runnable action) { 11489 final AttachInfo attachInfo = mAttachInfo; 11490 if (attachInfo != null) { 11491 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11492 Choreographer.CALLBACK_ANIMATION, action, null); 11493 } else { 11494 // Assume that post will succeed later 11495 ViewRootImpl.getRunQueue().post(action); 11496 } 11497 } 11498 11499 /** 11500 * <p>Causes the Runnable to execute on the next animation time step, 11501 * after the specified amount of time elapses. 11502 * The runnable will be run on the user interface thread.</p> 11503 * 11504 * @param action The Runnable that will be executed. 11505 * @param delayMillis The delay (in milliseconds) until the Runnable 11506 * will be executed. 11507 * 11508 * @see #postOnAnimation 11509 * @see #removeCallbacks 11510 */ 11511 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11512 final AttachInfo attachInfo = mAttachInfo; 11513 if (attachInfo != null) { 11514 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11515 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11516 } else { 11517 // Assume that post will succeed later 11518 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11519 } 11520 } 11521 11522 /** 11523 * <p>Removes the specified Runnable from the message queue.</p> 11524 * 11525 * @param action The Runnable to remove from the message handling queue 11526 * 11527 * @return true if this view could ask the Handler to remove the Runnable, 11528 * false otherwise. When the returned value is true, the Runnable 11529 * may or may not have been actually removed from the message queue 11530 * (for instance, if the Runnable was not in the queue already.) 11531 * 11532 * @see #post 11533 * @see #postDelayed 11534 * @see #postOnAnimation 11535 * @see #postOnAnimationDelayed 11536 */ 11537 public boolean removeCallbacks(Runnable action) { 11538 if (action != null) { 11539 final AttachInfo attachInfo = mAttachInfo; 11540 if (attachInfo != null) { 11541 attachInfo.mHandler.removeCallbacks(action); 11542 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11543 Choreographer.CALLBACK_ANIMATION, action, null); 11544 } 11545 // Assume that post will succeed later 11546 ViewRootImpl.getRunQueue().removeCallbacks(action); 11547 } 11548 return true; 11549 } 11550 11551 /** 11552 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11553 * Use this to invalidate the View from a non-UI thread.</p> 11554 * 11555 * <p>This method can be invoked from outside of the UI thread 11556 * only when this View is attached to a window.</p> 11557 * 11558 * @see #invalidate() 11559 * @see #postInvalidateDelayed(long) 11560 */ 11561 public void postInvalidate() { 11562 postInvalidateDelayed(0); 11563 } 11564 11565 /** 11566 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11567 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11568 * 11569 * <p>This method can be invoked from outside of the UI thread 11570 * only when this View is attached to a window.</p> 11571 * 11572 * @param left The left coordinate of the rectangle to invalidate. 11573 * @param top The top coordinate of the rectangle to invalidate. 11574 * @param right The right coordinate of the rectangle to invalidate. 11575 * @param bottom The bottom coordinate of the rectangle to invalidate. 11576 * 11577 * @see #invalidate(int, int, int, int) 11578 * @see #invalidate(Rect) 11579 * @see #postInvalidateDelayed(long, int, int, int, int) 11580 */ 11581 public void postInvalidate(int left, int top, int right, int bottom) { 11582 postInvalidateDelayed(0, left, top, right, bottom); 11583 } 11584 11585 /** 11586 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11587 * loop. Waits for the specified amount of time.</p> 11588 * 11589 * <p>This method can be invoked from outside of the UI thread 11590 * only when this View is attached to a window.</p> 11591 * 11592 * @param delayMilliseconds the duration in milliseconds to delay the 11593 * invalidation by 11594 * 11595 * @see #invalidate() 11596 * @see #postInvalidate() 11597 */ 11598 public void postInvalidateDelayed(long delayMilliseconds) { 11599 // We try only with the AttachInfo because there's no point in invalidating 11600 // if we are not attached to our window 11601 final AttachInfo attachInfo = mAttachInfo; 11602 if (attachInfo != null) { 11603 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11604 } 11605 } 11606 11607 /** 11608 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11609 * through the event loop. Waits for the specified amount of time.</p> 11610 * 11611 * <p>This method can be invoked from outside of the UI thread 11612 * only when this View is attached to a window.</p> 11613 * 11614 * @param delayMilliseconds the duration in milliseconds to delay the 11615 * invalidation by 11616 * @param left The left coordinate of the rectangle to invalidate. 11617 * @param top The top coordinate of the rectangle to invalidate. 11618 * @param right The right coordinate of the rectangle to invalidate. 11619 * @param bottom The bottom coordinate of the rectangle to invalidate. 11620 * 11621 * @see #invalidate(int, int, int, int) 11622 * @see #invalidate(Rect) 11623 * @see #postInvalidate(int, int, int, int) 11624 */ 11625 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11626 int right, int bottom) { 11627 11628 // We try only with the AttachInfo because there's no point in invalidating 11629 // if we are not attached to our window 11630 final AttachInfo attachInfo = mAttachInfo; 11631 if (attachInfo != null) { 11632 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11633 info.target = this; 11634 info.left = left; 11635 info.top = top; 11636 info.right = right; 11637 info.bottom = bottom; 11638 11639 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11640 } 11641 } 11642 11643 /** 11644 * <p>Cause an invalidate to happen on the next animation time step, typically the 11645 * next display frame.</p> 11646 * 11647 * <p>This method can be invoked from outside of the UI thread 11648 * only when this View is attached to a window.</p> 11649 * 11650 * @see #invalidate() 11651 */ 11652 public void postInvalidateOnAnimation() { 11653 // We try only with the AttachInfo because there's no point in invalidating 11654 // if we are not attached to our window 11655 final AttachInfo attachInfo = mAttachInfo; 11656 if (attachInfo != null) { 11657 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11658 } 11659 } 11660 11661 /** 11662 * <p>Cause an invalidate of the specified area to happen on the next animation 11663 * time step, typically the next display frame.</p> 11664 * 11665 * <p>This method can be invoked from outside of the UI thread 11666 * only when this View is attached to a window.</p> 11667 * 11668 * @param left The left coordinate of the rectangle to invalidate. 11669 * @param top The top coordinate of the rectangle to invalidate. 11670 * @param right The right coordinate of the rectangle to invalidate. 11671 * @param bottom The bottom coordinate of the rectangle to invalidate. 11672 * 11673 * @see #invalidate(int, int, int, int) 11674 * @see #invalidate(Rect) 11675 */ 11676 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11677 // We try only with the AttachInfo because there's no point in invalidating 11678 // if we are not attached to our window 11679 final AttachInfo attachInfo = mAttachInfo; 11680 if (attachInfo != null) { 11681 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11682 info.target = this; 11683 info.left = left; 11684 info.top = top; 11685 info.right = right; 11686 info.bottom = bottom; 11687 11688 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11689 } 11690 } 11691 11692 /** 11693 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11694 * This event is sent at most once every 11695 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11696 */ 11697 private void postSendViewScrolledAccessibilityEventCallback() { 11698 if (mSendViewScrolledAccessibilityEvent == null) { 11699 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11700 } 11701 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11702 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11703 postDelayed(mSendViewScrolledAccessibilityEvent, 11704 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11705 } 11706 } 11707 11708 /** 11709 * Called by a parent to request that a child update its values for mScrollX 11710 * and mScrollY if necessary. This will typically be done if the child is 11711 * animating a scroll using a {@link android.widget.Scroller Scroller} 11712 * object. 11713 */ 11714 public void computeScroll() { 11715 } 11716 11717 /** 11718 * <p>Indicate whether the horizontal edges are faded when the view is 11719 * scrolled horizontally.</p> 11720 * 11721 * @return true if the horizontal edges should are faded on scroll, false 11722 * otherwise 11723 * 11724 * @see #setHorizontalFadingEdgeEnabled(boolean) 11725 * 11726 * @attr ref android.R.styleable#View_requiresFadingEdge 11727 */ 11728 public boolean isHorizontalFadingEdgeEnabled() { 11729 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11730 } 11731 11732 /** 11733 * <p>Define whether the horizontal edges should be faded when this view 11734 * is scrolled horizontally.</p> 11735 * 11736 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11737 * be faded when the view is scrolled 11738 * horizontally 11739 * 11740 * @see #isHorizontalFadingEdgeEnabled() 11741 * 11742 * @attr ref android.R.styleable#View_requiresFadingEdge 11743 */ 11744 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11745 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11746 if (horizontalFadingEdgeEnabled) { 11747 initScrollCache(); 11748 } 11749 11750 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11751 } 11752 } 11753 11754 /** 11755 * <p>Indicate whether the vertical edges are faded when the view is 11756 * scrolled horizontally.</p> 11757 * 11758 * @return true if the vertical edges should are faded on scroll, false 11759 * otherwise 11760 * 11761 * @see #setVerticalFadingEdgeEnabled(boolean) 11762 * 11763 * @attr ref android.R.styleable#View_requiresFadingEdge 11764 */ 11765 public boolean isVerticalFadingEdgeEnabled() { 11766 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11767 } 11768 11769 /** 11770 * <p>Define whether the vertical edges should be faded when this view 11771 * is scrolled vertically.</p> 11772 * 11773 * @param verticalFadingEdgeEnabled true if the vertical edges should 11774 * be faded when the view is scrolled 11775 * vertically 11776 * 11777 * @see #isVerticalFadingEdgeEnabled() 11778 * 11779 * @attr ref android.R.styleable#View_requiresFadingEdge 11780 */ 11781 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11782 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11783 if (verticalFadingEdgeEnabled) { 11784 initScrollCache(); 11785 } 11786 11787 mViewFlags ^= FADING_EDGE_VERTICAL; 11788 } 11789 } 11790 11791 /** 11792 * Returns the strength, or intensity, of the top faded edge. The strength is 11793 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11794 * returns 0.0 or 1.0 but no value in between. 11795 * 11796 * Subclasses should override this method to provide a smoother fade transition 11797 * when scrolling occurs. 11798 * 11799 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11800 */ 11801 protected float getTopFadingEdgeStrength() { 11802 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11803 } 11804 11805 /** 11806 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11807 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11808 * returns 0.0 or 1.0 but no value in between. 11809 * 11810 * Subclasses should override this method to provide a smoother fade transition 11811 * when scrolling occurs. 11812 * 11813 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11814 */ 11815 protected float getBottomFadingEdgeStrength() { 11816 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11817 computeVerticalScrollRange() ? 1.0f : 0.0f; 11818 } 11819 11820 /** 11821 * Returns the strength, or intensity, of the left faded edge. The strength is 11822 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11823 * returns 0.0 or 1.0 but no value in between. 11824 * 11825 * Subclasses should override this method to provide a smoother fade transition 11826 * when scrolling occurs. 11827 * 11828 * @return the intensity of the left fade as a float between 0.0f and 1.0f 11829 */ 11830 protected float getLeftFadingEdgeStrength() { 11831 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 11832 } 11833 11834 /** 11835 * Returns the strength, or intensity, of the right faded edge. The strength is 11836 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11837 * returns 0.0 or 1.0 but no value in between. 11838 * 11839 * Subclasses should override this method to provide a smoother fade transition 11840 * when scrolling occurs. 11841 * 11842 * @return the intensity of the right fade as a float between 0.0f and 1.0f 11843 */ 11844 protected float getRightFadingEdgeStrength() { 11845 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 11846 computeHorizontalScrollRange() ? 1.0f : 0.0f; 11847 } 11848 11849 /** 11850 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 11851 * scrollbar is not drawn by default.</p> 11852 * 11853 * @return true if the horizontal scrollbar should be painted, false 11854 * otherwise 11855 * 11856 * @see #setHorizontalScrollBarEnabled(boolean) 11857 */ 11858 public boolean isHorizontalScrollBarEnabled() { 11859 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11860 } 11861 11862 /** 11863 * <p>Define whether the horizontal scrollbar should be drawn or not. The 11864 * scrollbar is not drawn by default.</p> 11865 * 11866 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 11867 * be painted 11868 * 11869 * @see #isHorizontalScrollBarEnabled() 11870 */ 11871 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 11872 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 11873 mViewFlags ^= SCROLLBARS_HORIZONTAL; 11874 computeOpaqueFlags(); 11875 resolvePadding(); 11876 } 11877 } 11878 11879 /** 11880 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 11881 * scrollbar is not drawn by default.</p> 11882 * 11883 * @return true if the vertical scrollbar should be painted, false 11884 * otherwise 11885 * 11886 * @see #setVerticalScrollBarEnabled(boolean) 11887 */ 11888 public boolean isVerticalScrollBarEnabled() { 11889 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 11890 } 11891 11892 /** 11893 * <p>Define whether the vertical scrollbar should be drawn or not. The 11894 * scrollbar is not drawn by default.</p> 11895 * 11896 * @param verticalScrollBarEnabled true if the vertical scrollbar should 11897 * be painted 11898 * 11899 * @see #isVerticalScrollBarEnabled() 11900 */ 11901 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 11902 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 11903 mViewFlags ^= SCROLLBARS_VERTICAL; 11904 computeOpaqueFlags(); 11905 resolvePadding(); 11906 } 11907 } 11908 11909 /** 11910 * @hide 11911 */ 11912 protected void recomputePadding() { 11913 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 11914 } 11915 11916 /** 11917 * Define whether scrollbars will fade when the view is not scrolling. 11918 * 11919 * @param fadeScrollbars wheter to enable fading 11920 * 11921 * @attr ref android.R.styleable#View_fadeScrollbars 11922 */ 11923 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 11924 initScrollCache(); 11925 final ScrollabilityCache scrollabilityCache = mScrollCache; 11926 scrollabilityCache.fadeScrollBars = fadeScrollbars; 11927 if (fadeScrollbars) { 11928 scrollabilityCache.state = ScrollabilityCache.OFF; 11929 } else { 11930 scrollabilityCache.state = ScrollabilityCache.ON; 11931 } 11932 } 11933 11934 /** 11935 * 11936 * Returns true if scrollbars will fade when this view is not scrolling 11937 * 11938 * @return true if scrollbar fading is enabled 11939 * 11940 * @attr ref android.R.styleable#View_fadeScrollbars 11941 */ 11942 public boolean isScrollbarFadingEnabled() { 11943 return mScrollCache != null && mScrollCache.fadeScrollBars; 11944 } 11945 11946 /** 11947 * 11948 * Returns the delay before scrollbars fade. 11949 * 11950 * @return the delay before scrollbars fade 11951 * 11952 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11953 */ 11954 public int getScrollBarDefaultDelayBeforeFade() { 11955 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 11956 mScrollCache.scrollBarDefaultDelayBeforeFade; 11957 } 11958 11959 /** 11960 * Define the delay before scrollbars fade. 11961 * 11962 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 11963 * 11964 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11965 */ 11966 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 11967 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 11968 } 11969 11970 /** 11971 * 11972 * Returns the scrollbar fade duration. 11973 * 11974 * @return the scrollbar fade duration 11975 * 11976 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11977 */ 11978 public int getScrollBarFadeDuration() { 11979 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 11980 mScrollCache.scrollBarFadeDuration; 11981 } 11982 11983 /** 11984 * Define the scrollbar fade duration. 11985 * 11986 * @param scrollBarFadeDuration - the scrollbar fade duration 11987 * 11988 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11989 */ 11990 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 11991 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 11992 } 11993 11994 /** 11995 * 11996 * Returns the scrollbar size. 11997 * 11998 * @return the scrollbar size 11999 * 12000 * @attr ref android.R.styleable#View_scrollbarSize 12001 */ 12002 public int getScrollBarSize() { 12003 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12004 mScrollCache.scrollBarSize; 12005 } 12006 12007 /** 12008 * Define the scrollbar size. 12009 * 12010 * @param scrollBarSize - the scrollbar size 12011 * 12012 * @attr ref android.R.styleable#View_scrollbarSize 12013 */ 12014 public void setScrollBarSize(int scrollBarSize) { 12015 getScrollCache().scrollBarSize = scrollBarSize; 12016 } 12017 12018 /** 12019 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12020 * inset. When inset, they add to the padding of the view. And the scrollbars 12021 * can be drawn inside the padding area or on the edge of the view. For example, 12022 * if a view has a background drawable and you want to draw the scrollbars 12023 * inside the padding specified by the drawable, you can use 12024 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12025 * appear at the edge of the view, ignoring the padding, then you can use 12026 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12027 * @param style the style of the scrollbars. Should be one of 12028 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12029 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12030 * @see #SCROLLBARS_INSIDE_OVERLAY 12031 * @see #SCROLLBARS_INSIDE_INSET 12032 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12033 * @see #SCROLLBARS_OUTSIDE_INSET 12034 * 12035 * @attr ref android.R.styleable#View_scrollbarStyle 12036 */ 12037 public void setScrollBarStyle(@ScrollBarStyle int style) { 12038 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12039 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12040 computeOpaqueFlags(); 12041 resolvePadding(); 12042 } 12043 } 12044 12045 /** 12046 * <p>Returns the current scrollbar style.</p> 12047 * @return the current scrollbar style 12048 * @see #SCROLLBARS_INSIDE_OVERLAY 12049 * @see #SCROLLBARS_INSIDE_INSET 12050 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12051 * @see #SCROLLBARS_OUTSIDE_INSET 12052 * 12053 * @attr ref android.R.styleable#View_scrollbarStyle 12054 */ 12055 @ViewDebug.ExportedProperty(mapping = { 12056 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12057 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12058 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12059 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12060 }) 12061 @ScrollBarStyle 12062 public int getScrollBarStyle() { 12063 return mViewFlags & SCROLLBARS_STYLE_MASK; 12064 } 12065 12066 /** 12067 * <p>Compute the horizontal range that the horizontal scrollbar 12068 * represents.</p> 12069 * 12070 * <p>The range is expressed in arbitrary units that must be the same as the 12071 * units used by {@link #computeHorizontalScrollExtent()} and 12072 * {@link #computeHorizontalScrollOffset()}.</p> 12073 * 12074 * <p>The default range is the drawing width of this view.</p> 12075 * 12076 * @return the total horizontal range represented by the horizontal 12077 * scrollbar 12078 * 12079 * @see #computeHorizontalScrollExtent() 12080 * @see #computeHorizontalScrollOffset() 12081 * @see android.widget.ScrollBarDrawable 12082 */ 12083 protected int computeHorizontalScrollRange() { 12084 return getWidth(); 12085 } 12086 12087 /** 12088 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12089 * within the horizontal range. This value is used to compute the position 12090 * of the thumb within the scrollbar's track.</p> 12091 * 12092 * <p>The range is expressed in arbitrary units that must be the same as the 12093 * units used by {@link #computeHorizontalScrollRange()} and 12094 * {@link #computeHorizontalScrollExtent()}.</p> 12095 * 12096 * <p>The default offset is the scroll offset of this view.</p> 12097 * 12098 * @return the horizontal offset of the scrollbar's thumb 12099 * 12100 * @see #computeHorizontalScrollRange() 12101 * @see #computeHorizontalScrollExtent() 12102 * @see android.widget.ScrollBarDrawable 12103 */ 12104 protected int computeHorizontalScrollOffset() { 12105 return mScrollX; 12106 } 12107 12108 /** 12109 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12110 * within the horizontal range. This value is used to compute the length 12111 * of the thumb within the scrollbar's track.</p> 12112 * 12113 * <p>The range is expressed in arbitrary units that must be the same as the 12114 * units used by {@link #computeHorizontalScrollRange()} and 12115 * {@link #computeHorizontalScrollOffset()}.</p> 12116 * 12117 * <p>The default extent is the drawing width of this view.</p> 12118 * 12119 * @return the horizontal extent of the scrollbar's thumb 12120 * 12121 * @see #computeHorizontalScrollRange() 12122 * @see #computeHorizontalScrollOffset() 12123 * @see android.widget.ScrollBarDrawable 12124 */ 12125 protected int computeHorizontalScrollExtent() { 12126 return getWidth(); 12127 } 12128 12129 /** 12130 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12131 * 12132 * <p>The range is expressed in arbitrary units that must be the same as the 12133 * units used by {@link #computeVerticalScrollExtent()} and 12134 * {@link #computeVerticalScrollOffset()}.</p> 12135 * 12136 * @return the total vertical range represented by the vertical scrollbar 12137 * 12138 * <p>The default range is the drawing height of this view.</p> 12139 * 12140 * @see #computeVerticalScrollExtent() 12141 * @see #computeVerticalScrollOffset() 12142 * @see android.widget.ScrollBarDrawable 12143 */ 12144 protected int computeVerticalScrollRange() { 12145 return getHeight(); 12146 } 12147 12148 /** 12149 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12150 * within the horizontal range. This value is used to compute the position 12151 * of the thumb within the scrollbar's track.</p> 12152 * 12153 * <p>The range is expressed in arbitrary units that must be the same as the 12154 * units used by {@link #computeVerticalScrollRange()} and 12155 * {@link #computeVerticalScrollExtent()}.</p> 12156 * 12157 * <p>The default offset is the scroll offset of this view.</p> 12158 * 12159 * @return the vertical offset of the scrollbar's thumb 12160 * 12161 * @see #computeVerticalScrollRange() 12162 * @see #computeVerticalScrollExtent() 12163 * @see android.widget.ScrollBarDrawable 12164 */ 12165 protected int computeVerticalScrollOffset() { 12166 return mScrollY; 12167 } 12168 12169 /** 12170 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 12171 * within the vertical range. This value is used to compute the length 12172 * of the thumb within the scrollbar's track.</p> 12173 * 12174 * <p>The range is expressed in arbitrary units that must be the same as the 12175 * units used by {@link #computeVerticalScrollRange()} and 12176 * {@link #computeVerticalScrollOffset()}.</p> 12177 * 12178 * <p>The default extent is the drawing height of this view.</p> 12179 * 12180 * @return the vertical extent of the scrollbar's thumb 12181 * 12182 * @see #computeVerticalScrollRange() 12183 * @see #computeVerticalScrollOffset() 12184 * @see android.widget.ScrollBarDrawable 12185 */ 12186 protected int computeVerticalScrollExtent() { 12187 return getHeight(); 12188 } 12189 12190 /** 12191 * Check if this view can be scrolled horizontally in a certain direction. 12192 * 12193 * @param direction Negative to check scrolling left, positive to check scrolling right. 12194 * @return true if this view can be scrolled in the specified direction, false otherwise. 12195 */ 12196 public boolean canScrollHorizontally(int direction) { 12197 final int offset = computeHorizontalScrollOffset(); 12198 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12199 if (range == 0) return false; 12200 if (direction < 0) { 12201 return offset > 0; 12202 } else { 12203 return offset < range - 1; 12204 } 12205 } 12206 12207 /** 12208 * Check if this view can be scrolled vertically in a certain direction. 12209 * 12210 * @param direction Negative to check scrolling up, positive to check scrolling down. 12211 * @return true if this view can be scrolled in the specified direction, false otherwise. 12212 */ 12213 public boolean canScrollVertically(int direction) { 12214 final int offset = computeVerticalScrollOffset(); 12215 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12216 if (range == 0) return false; 12217 if (direction < 0) { 12218 return offset > 0; 12219 } else { 12220 return offset < range - 1; 12221 } 12222 } 12223 12224 /** 12225 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12226 * scrollbars are painted only if they have been awakened first.</p> 12227 * 12228 * @param canvas the canvas on which to draw the scrollbars 12229 * 12230 * @see #awakenScrollBars(int) 12231 */ 12232 protected final void onDrawScrollBars(Canvas canvas) { 12233 // scrollbars are drawn only when the animation is running 12234 final ScrollabilityCache cache = mScrollCache; 12235 if (cache != null) { 12236 12237 int state = cache.state; 12238 12239 if (state == ScrollabilityCache.OFF) { 12240 return; 12241 } 12242 12243 boolean invalidate = false; 12244 12245 if (state == ScrollabilityCache.FADING) { 12246 // We're fading -- get our fade interpolation 12247 if (cache.interpolatorValues == null) { 12248 cache.interpolatorValues = new float[1]; 12249 } 12250 12251 float[] values = cache.interpolatorValues; 12252 12253 // Stops the animation if we're done 12254 if (cache.scrollBarInterpolator.timeToValues(values) == 12255 Interpolator.Result.FREEZE_END) { 12256 cache.state = ScrollabilityCache.OFF; 12257 } else { 12258 cache.scrollBar.setAlpha(Math.round(values[0])); 12259 } 12260 12261 // This will make the scroll bars inval themselves after 12262 // drawing. We only want this when we're fading so that 12263 // we prevent excessive redraws 12264 invalidate = true; 12265 } else { 12266 // We're just on -- but we may have been fading before so 12267 // reset alpha 12268 cache.scrollBar.setAlpha(255); 12269 } 12270 12271 12272 final int viewFlags = mViewFlags; 12273 12274 final boolean drawHorizontalScrollBar = 12275 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12276 final boolean drawVerticalScrollBar = 12277 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12278 && !isVerticalScrollBarHidden(); 12279 12280 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12281 final int width = mRight - mLeft; 12282 final int height = mBottom - mTop; 12283 12284 final ScrollBarDrawable scrollBar = cache.scrollBar; 12285 12286 final int scrollX = mScrollX; 12287 final int scrollY = mScrollY; 12288 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12289 12290 int left; 12291 int top; 12292 int right; 12293 int bottom; 12294 12295 if (drawHorizontalScrollBar) { 12296 int size = scrollBar.getSize(false); 12297 if (size <= 0) { 12298 size = cache.scrollBarSize; 12299 } 12300 12301 scrollBar.setParameters(computeHorizontalScrollRange(), 12302 computeHorizontalScrollOffset(), 12303 computeHorizontalScrollExtent(), false); 12304 final int verticalScrollBarGap = drawVerticalScrollBar ? 12305 getVerticalScrollbarWidth() : 0; 12306 top = scrollY + height - size - (mUserPaddingBottom & inside); 12307 left = scrollX + (mPaddingLeft & inside); 12308 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12309 bottom = top + size; 12310 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12311 if (invalidate) { 12312 invalidate(left, top, right, bottom); 12313 } 12314 } 12315 12316 if (drawVerticalScrollBar) { 12317 int size = scrollBar.getSize(true); 12318 if (size <= 0) { 12319 size = cache.scrollBarSize; 12320 } 12321 12322 scrollBar.setParameters(computeVerticalScrollRange(), 12323 computeVerticalScrollOffset(), 12324 computeVerticalScrollExtent(), true); 12325 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12326 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12327 verticalScrollbarPosition = isLayoutRtl() ? 12328 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12329 } 12330 switch (verticalScrollbarPosition) { 12331 default: 12332 case SCROLLBAR_POSITION_RIGHT: 12333 left = scrollX + width - size - (mUserPaddingRight & inside); 12334 break; 12335 case SCROLLBAR_POSITION_LEFT: 12336 left = scrollX + (mUserPaddingLeft & inside); 12337 break; 12338 } 12339 top = scrollY + (mPaddingTop & inside); 12340 right = left + size; 12341 bottom = scrollY + height - (mUserPaddingBottom & inside); 12342 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12343 if (invalidate) { 12344 invalidate(left, top, right, bottom); 12345 } 12346 } 12347 } 12348 } 12349 } 12350 12351 /** 12352 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12353 * FastScroller is visible. 12354 * @return whether to temporarily hide the vertical scrollbar 12355 * @hide 12356 */ 12357 protected boolean isVerticalScrollBarHidden() { 12358 return false; 12359 } 12360 12361 /** 12362 * <p>Draw the horizontal scrollbar if 12363 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12364 * 12365 * @param canvas the canvas on which to draw the scrollbar 12366 * @param scrollBar the scrollbar's drawable 12367 * 12368 * @see #isHorizontalScrollBarEnabled() 12369 * @see #computeHorizontalScrollRange() 12370 * @see #computeHorizontalScrollExtent() 12371 * @see #computeHorizontalScrollOffset() 12372 * @see android.widget.ScrollBarDrawable 12373 * @hide 12374 */ 12375 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12376 int l, int t, int r, int b) { 12377 scrollBar.setBounds(l, t, r, b); 12378 scrollBar.draw(canvas); 12379 } 12380 12381 /** 12382 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12383 * returns true.</p> 12384 * 12385 * @param canvas the canvas on which to draw the scrollbar 12386 * @param scrollBar the scrollbar's drawable 12387 * 12388 * @see #isVerticalScrollBarEnabled() 12389 * @see #computeVerticalScrollRange() 12390 * @see #computeVerticalScrollExtent() 12391 * @see #computeVerticalScrollOffset() 12392 * @see android.widget.ScrollBarDrawable 12393 * @hide 12394 */ 12395 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12396 int l, int t, int r, int b) { 12397 scrollBar.setBounds(l, t, r, b); 12398 scrollBar.draw(canvas); 12399 } 12400 12401 /** 12402 * Implement this to do your drawing. 12403 * 12404 * @param canvas the canvas on which the background will be drawn 12405 */ 12406 protected void onDraw(Canvas canvas) { 12407 } 12408 12409 /* 12410 * Caller is responsible for calling requestLayout if necessary. 12411 * (This allows addViewInLayout to not request a new layout.) 12412 */ 12413 void assignParent(ViewParent parent) { 12414 if (mParent == null) { 12415 mParent = parent; 12416 } else if (parent == null) { 12417 mParent = null; 12418 } else { 12419 throw new RuntimeException("view " + this + " being added, but" 12420 + " it already has a parent"); 12421 } 12422 } 12423 12424 /** 12425 * This is called when the view is attached to a window. At this point it 12426 * has a Surface and will start drawing. Note that this function is 12427 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12428 * however it may be called any time before the first onDraw -- including 12429 * before or after {@link #onMeasure(int, int)}. 12430 * 12431 * @see #onDetachedFromWindow() 12432 */ 12433 protected void onAttachedToWindow() { 12434 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12435 mParent.requestTransparentRegion(this); 12436 } 12437 12438 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12439 initialAwakenScrollBars(); 12440 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12441 } 12442 12443 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12444 12445 jumpDrawablesToCurrentState(); 12446 12447 resetSubtreeAccessibilityStateChanged(); 12448 12449 if (isFocused()) { 12450 InputMethodManager imm = InputMethodManager.peekInstance(); 12451 imm.focusIn(this); 12452 } 12453 12454 if (mDisplayList != null) { 12455 mDisplayList.clearDirty(); 12456 } 12457 } 12458 12459 /** 12460 * Resolve all RTL related properties. 12461 * 12462 * @return true if resolution of RTL properties has been done 12463 * 12464 * @hide 12465 */ 12466 public boolean resolveRtlPropertiesIfNeeded() { 12467 if (!needRtlPropertiesResolution()) return false; 12468 12469 // Order is important here: LayoutDirection MUST be resolved first 12470 if (!isLayoutDirectionResolved()) { 12471 resolveLayoutDirection(); 12472 resolveLayoutParams(); 12473 } 12474 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12475 if (!isTextDirectionResolved()) { 12476 resolveTextDirection(); 12477 } 12478 if (!isTextAlignmentResolved()) { 12479 resolveTextAlignment(); 12480 } 12481 // Should resolve Drawables before Padding because we need the layout direction of the 12482 // Drawable to correctly resolve Padding. 12483 if (!isDrawablesResolved()) { 12484 resolveDrawables(); 12485 } 12486 if (!isPaddingResolved()) { 12487 resolvePadding(); 12488 } 12489 onRtlPropertiesChanged(getLayoutDirection()); 12490 return true; 12491 } 12492 12493 /** 12494 * Reset resolution of all RTL related properties. 12495 * 12496 * @hide 12497 */ 12498 public void resetRtlProperties() { 12499 resetResolvedLayoutDirection(); 12500 resetResolvedTextDirection(); 12501 resetResolvedTextAlignment(); 12502 resetResolvedPadding(); 12503 resetResolvedDrawables(); 12504 } 12505 12506 /** 12507 * @see #onScreenStateChanged(int) 12508 */ 12509 void dispatchScreenStateChanged(int screenState) { 12510 onScreenStateChanged(screenState); 12511 } 12512 12513 /** 12514 * This method is called whenever the state of the screen this view is 12515 * attached to changes. A state change will usually occurs when the screen 12516 * turns on or off (whether it happens automatically or the user does it 12517 * manually.) 12518 * 12519 * @param screenState The new state of the screen. Can be either 12520 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12521 */ 12522 public void onScreenStateChanged(int screenState) { 12523 } 12524 12525 /** 12526 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12527 */ 12528 private boolean hasRtlSupport() { 12529 return mContext.getApplicationInfo().hasRtlSupport(); 12530 } 12531 12532 /** 12533 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12534 * RTL not supported) 12535 */ 12536 private boolean isRtlCompatibilityMode() { 12537 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12538 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12539 } 12540 12541 /** 12542 * @return true if RTL properties need resolution. 12543 * 12544 */ 12545 private boolean needRtlPropertiesResolution() { 12546 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12547 } 12548 12549 /** 12550 * Called when any RTL property (layout direction or text direction or text alignment) has 12551 * been changed. 12552 * 12553 * Subclasses need to override this method to take care of cached information that depends on the 12554 * resolved layout direction, or to inform child views that inherit their layout direction. 12555 * 12556 * The default implementation does nothing. 12557 * 12558 * @param layoutDirection the direction of the layout 12559 * 12560 * @see #LAYOUT_DIRECTION_LTR 12561 * @see #LAYOUT_DIRECTION_RTL 12562 */ 12563 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12564 } 12565 12566 /** 12567 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12568 * that the parent directionality can and will be resolved before its children. 12569 * 12570 * @return true if resolution has been done, false otherwise. 12571 * 12572 * @hide 12573 */ 12574 public boolean resolveLayoutDirection() { 12575 // Clear any previous layout direction resolution 12576 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12577 12578 if (hasRtlSupport()) { 12579 // Set resolved depending on layout direction 12580 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12581 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12582 case LAYOUT_DIRECTION_INHERIT: 12583 // We cannot resolve yet. LTR is by default and let the resolution happen again 12584 // later to get the correct resolved value 12585 if (!canResolveLayoutDirection()) return false; 12586 12587 // Parent has not yet resolved, LTR is still the default 12588 try { 12589 if (!mParent.isLayoutDirectionResolved()) return false; 12590 12591 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12592 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12593 } 12594 } catch (AbstractMethodError e) { 12595 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12596 " does not fully implement ViewParent", e); 12597 } 12598 break; 12599 case LAYOUT_DIRECTION_RTL: 12600 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12601 break; 12602 case LAYOUT_DIRECTION_LOCALE: 12603 if((LAYOUT_DIRECTION_RTL == 12604 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12605 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12606 } 12607 break; 12608 default: 12609 // Nothing to do, LTR by default 12610 } 12611 } 12612 12613 // Set to resolved 12614 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12615 return true; 12616 } 12617 12618 /** 12619 * Check if layout direction resolution can be done. 12620 * 12621 * @return true if layout direction resolution can be done otherwise return false. 12622 */ 12623 public boolean canResolveLayoutDirection() { 12624 switch (getRawLayoutDirection()) { 12625 case LAYOUT_DIRECTION_INHERIT: 12626 if (mParent != null) { 12627 try { 12628 return mParent.canResolveLayoutDirection(); 12629 } catch (AbstractMethodError e) { 12630 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12631 " does not fully implement ViewParent", e); 12632 } 12633 } 12634 return false; 12635 12636 default: 12637 return true; 12638 } 12639 } 12640 12641 /** 12642 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12643 * {@link #onMeasure(int, int)}. 12644 * 12645 * @hide 12646 */ 12647 public void resetResolvedLayoutDirection() { 12648 // Reset the current resolved bits 12649 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12650 } 12651 12652 /** 12653 * @return true if the layout direction is inherited. 12654 * 12655 * @hide 12656 */ 12657 public boolean isLayoutDirectionInherited() { 12658 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12659 } 12660 12661 /** 12662 * @return true if layout direction has been resolved. 12663 */ 12664 public boolean isLayoutDirectionResolved() { 12665 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12666 } 12667 12668 /** 12669 * Return if padding has been resolved 12670 * 12671 * @hide 12672 */ 12673 boolean isPaddingResolved() { 12674 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12675 } 12676 12677 /** 12678 * Resolves padding depending on layout direction, if applicable, and 12679 * recomputes internal padding values to adjust for scroll bars. 12680 * 12681 * @hide 12682 */ 12683 public void resolvePadding() { 12684 final int resolvedLayoutDirection = getLayoutDirection(); 12685 12686 if (!isRtlCompatibilityMode()) { 12687 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12688 // If start / end padding are defined, they will be resolved (hence overriding) to 12689 // left / right or right / left depending on the resolved layout direction. 12690 // If start / end padding are not defined, use the left / right ones. 12691 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12692 Rect padding = sThreadLocal.get(); 12693 if (padding == null) { 12694 padding = new Rect(); 12695 sThreadLocal.set(padding); 12696 } 12697 mBackground.getPadding(padding); 12698 if (!mLeftPaddingDefined) { 12699 mUserPaddingLeftInitial = padding.left; 12700 } 12701 if (!mRightPaddingDefined) { 12702 mUserPaddingRightInitial = padding.right; 12703 } 12704 } 12705 switch (resolvedLayoutDirection) { 12706 case LAYOUT_DIRECTION_RTL: 12707 if (mUserPaddingStart != UNDEFINED_PADDING) { 12708 mUserPaddingRight = mUserPaddingStart; 12709 } else { 12710 mUserPaddingRight = mUserPaddingRightInitial; 12711 } 12712 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12713 mUserPaddingLeft = mUserPaddingEnd; 12714 } else { 12715 mUserPaddingLeft = mUserPaddingLeftInitial; 12716 } 12717 break; 12718 case LAYOUT_DIRECTION_LTR: 12719 default: 12720 if (mUserPaddingStart != UNDEFINED_PADDING) { 12721 mUserPaddingLeft = mUserPaddingStart; 12722 } else { 12723 mUserPaddingLeft = mUserPaddingLeftInitial; 12724 } 12725 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12726 mUserPaddingRight = mUserPaddingEnd; 12727 } else { 12728 mUserPaddingRight = mUserPaddingRightInitial; 12729 } 12730 } 12731 12732 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12733 } 12734 12735 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12736 onRtlPropertiesChanged(resolvedLayoutDirection); 12737 12738 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12739 } 12740 12741 /** 12742 * Reset the resolved layout direction. 12743 * 12744 * @hide 12745 */ 12746 public void resetResolvedPadding() { 12747 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12748 } 12749 12750 /** 12751 * This is called when the view is detached from a window. At this point it 12752 * no longer has a surface for drawing. 12753 * 12754 * @see #onAttachedToWindow() 12755 */ 12756 protected void onDetachedFromWindow() { 12757 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12758 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12759 12760 removeUnsetPressCallback(); 12761 removeLongPressCallback(); 12762 removePerformClickCallback(); 12763 removeSendViewScrolledAccessibilityEventCallback(); 12764 12765 destroyDrawingCache(); 12766 destroyLayer(false); 12767 12768 cleanupDraw(); 12769 12770 mCurrentAnimation = null; 12771 } 12772 12773 private void cleanupDraw() { 12774 if (mAttachInfo != null) { 12775 if (mDisplayList != null) { 12776 mDisplayList.markDirty(); 12777 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList); 12778 } 12779 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12780 } else { 12781 // Should never happen 12782 resetDisplayList(); 12783 } 12784 } 12785 12786 /** 12787 * This method ensures the hardware renderer is in a valid state 12788 * before executing the specified action. 12789 * 12790 * This method will attempt to set a valid state even if the window 12791 * the renderer is attached to was destroyed. 12792 * 12793 * This method is not guaranteed to work. If the hardware renderer 12794 * does not exist or cannot be put in a valid state, this method 12795 * will not executed the specified action. 12796 * 12797 * The specified action is executed synchronously. 12798 * 12799 * @param action The action to execute after the renderer is in a valid state 12800 * 12801 * @return True if the specified Runnable was executed, false otherwise 12802 * 12803 * @hide 12804 */ 12805 public boolean executeHardwareAction(Runnable action) { 12806 //noinspection SimplifiableIfStatement 12807 if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) { 12808 return mAttachInfo.mHardwareRenderer.safelyRun(action); 12809 } 12810 return false; 12811 } 12812 12813 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12814 } 12815 12816 /** 12817 * @return The number of times this view has been attached to a window 12818 */ 12819 protected int getWindowAttachCount() { 12820 return mWindowAttachCount; 12821 } 12822 12823 /** 12824 * Retrieve a unique token identifying the window this view is attached to. 12825 * @return Return the window's token for use in 12826 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 12827 */ 12828 public IBinder getWindowToken() { 12829 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 12830 } 12831 12832 /** 12833 * Retrieve the {@link WindowId} for the window this view is 12834 * currently attached to. 12835 */ 12836 public WindowId getWindowId() { 12837 if (mAttachInfo == null) { 12838 return null; 12839 } 12840 if (mAttachInfo.mWindowId == null) { 12841 try { 12842 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 12843 mAttachInfo.mWindowToken); 12844 mAttachInfo.mWindowId = new WindowId( 12845 mAttachInfo.mIWindowId); 12846 } catch (RemoteException e) { 12847 } 12848 } 12849 return mAttachInfo.mWindowId; 12850 } 12851 12852 /** 12853 * Retrieve a unique token identifying the top-level "real" window of 12854 * the window that this view is attached to. That is, this is like 12855 * {@link #getWindowToken}, except if the window this view in is a panel 12856 * window (attached to another containing window), then the token of 12857 * the containing window is returned instead. 12858 * 12859 * @return Returns the associated window token, either 12860 * {@link #getWindowToken()} or the containing window's token. 12861 */ 12862 public IBinder getApplicationWindowToken() { 12863 AttachInfo ai = mAttachInfo; 12864 if (ai != null) { 12865 IBinder appWindowToken = ai.mPanelParentWindowToken; 12866 if (appWindowToken == null) { 12867 appWindowToken = ai.mWindowToken; 12868 } 12869 return appWindowToken; 12870 } 12871 return null; 12872 } 12873 12874 /** 12875 * Gets the logical display to which the view's window has been attached. 12876 * 12877 * @return The logical display, or null if the view is not currently attached to a window. 12878 */ 12879 public Display getDisplay() { 12880 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 12881 } 12882 12883 /** 12884 * Retrieve private session object this view hierarchy is using to 12885 * communicate with the window manager. 12886 * @return the session object to communicate with the window manager 12887 */ 12888 /*package*/ IWindowSession getWindowSession() { 12889 return mAttachInfo != null ? mAttachInfo.mSession : null; 12890 } 12891 12892 /** 12893 * @param info the {@link android.view.View.AttachInfo} to associated with 12894 * this view 12895 */ 12896 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 12897 //System.out.println("Attached! " + this); 12898 mAttachInfo = info; 12899 if (mOverlay != null) { 12900 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 12901 } 12902 mWindowAttachCount++; 12903 // We will need to evaluate the drawable state at least once. 12904 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 12905 if (mFloatingTreeObserver != null) { 12906 info.mTreeObserver.merge(mFloatingTreeObserver); 12907 mFloatingTreeObserver = null; 12908 } 12909 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 12910 mAttachInfo.mScrollContainers.add(this); 12911 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 12912 } 12913 performCollectViewAttributes(mAttachInfo, visibility); 12914 onAttachedToWindow(); 12915 12916 ListenerInfo li = mListenerInfo; 12917 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12918 li != null ? li.mOnAttachStateChangeListeners : null; 12919 if (listeners != null && listeners.size() > 0) { 12920 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12921 // perform the dispatching. The iterator is a safe guard against listeners that 12922 // could mutate the list by calling the various add/remove methods. This prevents 12923 // the array from being modified while we iterate it. 12924 for (OnAttachStateChangeListener listener : listeners) { 12925 listener.onViewAttachedToWindow(this); 12926 } 12927 } 12928 12929 int vis = info.mWindowVisibility; 12930 if (vis != GONE) { 12931 onWindowVisibilityChanged(vis); 12932 } 12933 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 12934 // If nobody has evaluated the drawable state yet, then do it now. 12935 refreshDrawableState(); 12936 } 12937 needGlobalAttributesUpdate(false); 12938 } 12939 12940 void dispatchDetachedFromWindow() { 12941 AttachInfo info = mAttachInfo; 12942 if (info != null) { 12943 int vis = info.mWindowVisibility; 12944 if (vis != GONE) { 12945 onWindowVisibilityChanged(GONE); 12946 } 12947 } 12948 12949 onDetachedFromWindow(); 12950 12951 ListenerInfo li = mListenerInfo; 12952 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12953 li != null ? li.mOnAttachStateChangeListeners : null; 12954 if (listeners != null && listeners.size() > 0) { 12955 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12956 // perform the dispatching. The iterator is a safe guard against listeners that 12957 // could mutate the list by calling the various add/remove methods. This prevents 12958 // the array from being modified while we iterate it. 12959 for (OnAttachStateChangeListener listener : listeners) { 12960 listener.onViewDetachedFromWindow(this); 12961 } 12962 } 12963 12964 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 12965 mAttachInfo.mScrollContainers.remove(this); 12966 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 12967 } 12968 12969 mAttachInfo = null; 12970 if (mOverlay != null) { 12971 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 12972 } 12973 } 12974 12975 /** 12976 * Cancel any deferred high-level input events that were previously posted to the event queue. 12977 * 12978 * <p>Many views post high-level events such as click handlers to the event queue 12979 * to run deferred in order to preserve a desired user experience - clearing visible 12980 * pressed states before executing, etc. This method will abort any events of this nature 12981 * that are currently in flight.</p> 12982 * 12983 * <p>Custom views that generate their own high-level deferred input events should override 12984 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 12985 * 12986 * <p>This will also cancel pending input events for any child views.</p> 12987 * 12988 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 12989 * This will not impact newer events posted after this call that may occur as a result of 12990 * lower-level input events still waiting in the queue. If you are trying to prevent 12991 * double-submitted events for the duration of some sort of asynchronous transaction 12992 * you should also take other steps to protect against unexpected double inputs e.g. calling 12993 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 12994 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 12995 */ 12996 public final void cancelPendingInputEvents() { 12997 dispatchCancelPendingInputEvents(); 12998 } 12999 13000 /** 13001 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13002 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13003 */ 13004 void dispatchCancelPendingInputEvents() { 13005 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13006 onCancelPendingInputEvents(); 13007 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13008 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13009 " did not call through to super.onCancelPendingInputEvents()"); 13010 } 13011 } 13012 13013 /** 13014 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13015 * a parent view. 13016 * 13017 * <p>This method is responsible for removing any pending high-level input events that were 13018 * posted to the event queue to run later. Custom view classes that post their own deferred 13019 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13020 * {@link android.os.Handler} should override this method, call 13021 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13022 * </p> 13023 */ 13024 public void onCancelPendingInputEvents() { 13025 removePerformClickCallback(); 13026 cancelLongPress(); 13027 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13028 } 13029 13030 /** 13031 * Store this view hierarchy's frozen state into the given container. 13032 * 13033 * @param container The SparseArray in which to save the view's state. 13034 * 13035 * @see #restoreHierarchyState(android.util.SparseArray) 13036 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13037 * @see #onSaveInstanceState() 13038 */ 13039 public void saveHierarchyState(SparseArray<Parcelable> container) { 13040 dispatchSaveInstanceState(container); 13041 } 13042 13043 /** 13044 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13045 * this view and its children. May be overridden to modify how freezing happens to a 13046 * view's children; for example, some views may want to not store state for their children. 13047 * 13048 * @param container The SparseArray in which to save the view's state. 13049 * 13050 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13051 * @see #saveHierarchyState(android.util.SparseArray) 13052 * @see #onSaveInstanceState() 13053 */ 13054 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13055 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13056 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13057 Parcelable state = onSaveInstanceState(); 13058 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13059 throw new IllegalStateException( 13060 "Derived class did not call super.onSaveInstanceState()"); 13061 } 13062 if (state != null) { 13063 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13064 // + ": " + state); 13065 container.put(mID, state); 13066 } 13067 } 13068 } 13069 13070 /** 13071 * Hook allowing a view to generate a representation of its internal state 13072 * that can later be used to create a new instance with that same state. 13073 * This state should only contain information that is not persistent or can 13074 * not be reconstructed later. For example, you will never store your 13075 * current position on screen because that will be computed again when a 13076 * new instance of the view is placed in its view hierarchy. 13077 * <p> 13078 * Some examples of things you may store here: the current cursor position 13079 * in a text view (but usually not the text itself since that is stored in a 13080 * content provider or other persistent storage), the currently selected 13081 * item in a list view. 13082 * 13083 * @return Returns a Parcelable object containing the view's current dynamic 13084 * state, or null if there is nothing interesting to save. The 13085 * default implementation returns null. 13086 * @see #onRestoreInstanceState(android.os.Parcelable) 13087 * @see #saveHierarchyState(android.util.SparseArray) 13088 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13089 * @see #setSaveEnabled(boolean) 13090 */ 13091 protected Parcelable onSaveInstanceState() { 13092 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13093 return BaseSavedState.EMPTY_STATE; 13094 } 13095 13096 /** 13097 * Restore this view hierarchy's frozen state from the given container. 13098 * 13099 * @param container The SparseArray which holds previously frozen states. 13100 * 13101 * @see #saveHierarchyState(android.util.SparseArray) 13102 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13103 * @see #onRestoreInstanceState(android.os.Parcelable) 13104 */ 13105 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13106 dispatchRestoreInstanceState(container); 13107 } 13108 13109 /** 13110 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13111 * state for this view and its children. May be overridden to modify how restoring 13112 * happens to a view's children; for example, some views may want to not store state 13113 * for their children. 13114 * 13115 * @param container The SparseArray which holds previously saved state. 13116 * 13117 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13118 * @see #restoreHierarchyState(android.util.SparseArray) 13119 * @see #onRestoreInstanceState(android.os.Parcelable) 13120 */ 13121 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13122 if (mID != NO_ID) { 13123 Parcelable state = container.get(mID); 13124 if (state != null) { 13125 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13126 // + ": " + state); 13127 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13128 onRestoreInstanceState(state); 13129 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13130 throw new IllegalStateException( 13131 "Derived class did not call super.onRestoreInstanceState()"); 13132 } 13133 } 13134 } 13135 } 13136 13137 /** 13138 * Hook allowing a view to re-apply a representation of its internal state that had previously 13139 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13140 * null state. 13141 * 13142 * @param state The frozen state that had previously been returned by 13143 * {@link #onSaveInstanceState}. 13144 * 13145 * @see #onSaveInstanceState() 13146 * @see #restoreHierarchyState(android.util.SparseArray) 13147 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13148 */ 13149 protected void onRestoreInstanceState(Parcelable state) { 13150 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13151 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13152 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13153 + "received " + state.getClass().toString() + " instead. This usually happens " 13154 + "when two views of different type have the same id in the same hierarchy. " 13155 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13156 + "other views do not use the same id."); 13157 } 13158 } 13159 13160 /** 13161 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13162 * 13163 * @return the drawing start time in milliseconds 13164 */ 13165 public long getDrawingTime() { 13166 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13167 } 13168 13169 /** 13170 * <p>Enables or disables the duplication of the parent's state into this view. When 13171 * duplication is enabled, this view gets its drawable state from its parent rather 13172 * than from its own internal properties.</p> 13173 * 13174 * <p>Note: in the current implementation, setting this property to true after the 13175 * view was added to a ViewGroup might have no effect at all. This property should 13176 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13177 * 13178 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13179 * property is enabled, an exception will be thrown.</p> 13180 * 13181 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13182 * parent, these states should not be affected by this method.</p> 13183 * 13184 * @param enabled True to enable duplication of the parent's drawable state, false 13185 * to disable it. 13186 * 13187 * @see #getDrawableState() 13188 * @see #isDuplicateParentStateEnabled() 13189 */ 13190 public void setDuplicateParentStateEnabled(boolean enabled) { 13191 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13192 } 13193 13194 /** 13195 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13196 * 13197 * @return True if this view's drawable state is duplicated from the parent, 13198 * false otherwise 13199 * 13200 * @see #getDrawableState() 13201 * @see #setDuplicateParentStateEnabled(boolean) 13202 */ 13203 public boolean isDuplicateParentStateEnabled() { 13204 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13205 } 13206 13207 /** 13208 * <p>Specifies the type of layer backing this view. The layer can be 13209 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13210 * {@link #LAYER_TYPE_HARDWARE}.</p> 13211 * 13212 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13213 * instance that controls how the layer is composed on screen. The following 13214 * properties of the paint are taken into account when composing the layer:</p> 13215 * <ul> 13216 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13217 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13218 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13219 * </ul> 13220 * 13221 * <p>If this view has an alpha value set to < 1.0 by calling 13222 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13223 * by this view's alpha value.</p> 13224 * 13225 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13226 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13227 * for more information on when and how to use layers.</p> 13228 * 13229 * @param layerType The type of layer to use with this view, must be one of 13230 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13231 * {@link #LAYER_TYPE_HARDWARE} 13232 * @param paint The paint used to compose the layer. This argument is optional 13233 * and can be null. It is ignored when the layer type is 13234 * {@link #LAYER_TYPE_NONE} 13235 * 13236 * @see #getLayerType() 13237 * @see #LAYER_TYPE_NONE 13238 * @see #LAYER_TYPE_SOFTWARE 13239 * @see #LAYER_TYPE_HARDWARE 13240 * @see #setAlpha(float) 13241 * 13242 * @attr ref android.R.styleable#View_layerType 13243 */ 13244 public void setLayerType(int layerType, Paint paint) { 13245 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13246 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13247 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13248 } 13249 13250 if (layerType == mLayerType) { 13251 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 13252 mLayerPaint = paint == null ? new Paint() : paint; 13253 invalidateParentCaches(); 13254 invalidate(true); 13255 } 13256 return; 13257 } 13258 13259 // Destroy any previous software drawing cache if needed 13260 switch (mLayerType) { 13261 case LAYER_TYPE_HARDWARE: 13262 destroyLayer(false); 13263 // fall through - non-accelerated views may use software layer mechanism instead 13264 case LAYER_TYPE_SOFTWARE: 13265 destroyDrawingCache(); 13266 break; 13267 default: 13268 break; 13269 } 13270 13271 mLayerType = layerType; 13272 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 13273 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13274 mLocalDirtyRect = layerDisabled ? null : new Rect(); 13275 13276 invalidateParentCaches(); 13277 invalidate(true); 13278 } 13279 13280 /** 13281 * Updates the {@link Paint} object used with the current layer (used only if the current 13282 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13283 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13284 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13285 * ensure that the view gets redrawn immediately. 13286 * 13287 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13288 * instance that controls how the layer is composed on screen. The following 13289 * properties of the paint are taken into account when composing the layer:</p> 13290 * <ul> 13291 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13292 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13293 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13294 * </ul> 13295 * 13296 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13297 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13298 * 13299 * @param paint The paint used to compose the layer. This argument is optional 13300 * and can be null. It is ignored when the layer type is 13301 * {@link #LAYER_TYPE_NONE} 13302 * 13303 * @see #setLayerType(int, android.graphics.Paint) 13304 */ 13305 public void setLayerPaint(Paint paint) { 13306 int layerType = getLayerType(); 13307 if (layerType != LAYER_TYPE_NONE) { 13308 mLayerPaint = paint == null ? new Paint() : paint; 13309 if (layerType == LAYER_TYPE_HARDWARE) { 13310 HardwareLayer layer = getHardwareLayer(); 13311 if (layer != null) { 13312 layer.setLayerPaint(paint); 13313 } 13314 invalidateViewProperty(false, false); 13315 } else { 13316 invalidate(); 13317 } 13318 } 13319 } 13320 13321 /** 13322 * Indicates whether this view has a static layer. A view with layer type 13323 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13324 * dynamic. 13325 */ 13326 boolean hasStaticLayer() { 13327 return true; 13328 } 13329 13330 /** 13331 * Indicates what type of layer is currently associated with this view. By default 13332 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13333 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13334 * for more information on the different types of layers. 13335 * 13336 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13337 * {@link #LAYER_TYPE_HARDWARE} 13338 * 13339 * @see #setLayerType(int, android.graphics.Paint) 13340 * @see #buildLayer() 13341 * @see #LAYER_TYPE_NONE 13342 * @see #LAYER_TYPE_SOFTWARE 13343 * @see #LAYER_TYPE_HARDWARE 13344 */ 13345 public int getLayerType() { 13346 return mLayerType; 13347 } 13348 13349 /** 13350 * Forces this view's layer to be created and this view to be rendered 13351 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13352 * invoking this method will have no effect. 13353 * 13354 * This method can for instance be used to render a view into its layer before 13355 * starting an animation. If this view is complex, rendering into the layer 13356 * before starting the animation will avoid skipping frames. 13357 * 13358 * @throws IllegalStateException If this view is not attached to a window 13359 * 13360 * @see #setLayerType(int, android.graphics.Paint) 13361 */ 13362 public void buildLayer() { 13363 if (mLayerType == LAYER_TYPE_NONE) return; 13364 13365 final AttachInfo attachInfo = mAttachInfo; 13366 if (attachInfo == null) { 13367 throw new IllegalStateException("This view must be attached to a window first"); 13368 } 13369 13370 switch (mLayerType) { 13371 case LAYER_TYPE_HARDWARE: 13372 if (attachInfo.mHardwareRenderer != null && 13373 attachInfo.mHardwareRenderer.isEnabled() && 13374 attachInfo.mHardwareRenderer.validate()) { 13375 getHardwareLayer(); 13376 // TODO: We need a better way to handle this case 13377 // If views have registered pre-draw listeners they need 13378 // to be notified before we build the layer. Those listeners 13379 // may however rely on other events to happen first so we 13380 // cannot just invoke them here until they don't cancel the 13381 // current frame 13382 if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) { 13383 attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates(); 13384 } 13385 } 13386 break; 13387 case LAYER_TYPE_SOFTWARE: 13388 buildDrawingCache(true); 13389 break; 13390 } 13391 } 13392 13393 /** 13394 * <p>Returns a hardware layer that can be used to draw this view again 13395 * without executing its draw method.</p> 13396 * 13397 * @return A HardwareLayer ready to render, or null if an error occurred. 13398 */ 13399 HardwareLayer getHardwareLayer() { 13400 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 13401 !mAttachInfo.mHardwareRenderer.isEnabled()) { 13402 return null; 13403 } 13404 13405 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 13406 13407 final int width = mRight - mLeft; 13408 final int height = mBottom - mTop; 13409 13410 if (width == 0 || height == 0) { 13411 return null; 13412 } 13413 13414 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 13415 if (mHardwareLayer == null) { 13416 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 13417 width, height, isOpaque()); 13418 mLocalDirtyRect.set(0, 0, width, height); 13419 } else { 13420 if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 13421 if (mHardwareLayer.resize(width, height)) { 13422 mLocalDirtyRect.set(0, 0, width, height); 13423 } 13424 } 13425 13426 // This should not be necessary but applications that change 13427 // the parameters of their background drawable without calling 13428 // this.setBackground(Drawable) can leave the view in a bad state 13429 // (for instance isOpaque() returns true, but the background is 13430 // not opaque.) 13431 computeOpaqueFlags(); 13432 13433 final boolean opaque = isOpaque(); 13434 if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) { 13435 mHardwareLayer.setOpaque(opaque); 13436 mLocalDirtyRect.set(0, 0, width, height); 13437 } 13438 } 13439 13440 // The layer is not valid if the underlying GPU resources cannot be allocated 13441 if (!mHardwareLayer.isValid()) { 13442 return null; 13443 } 13444 13445 mHardwareLayer.setLayerPaint(mLayerPaint); 13446 mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 13447 ViewRootImpl viewRoot = getViewRootImpl(); 13448 if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer); 13449 13450 mLocalDirtyRect.setEmpty(); 13451 } 13452 13453 return mHardwareLayer; 13454 } 13455 13456 /** 13457 * Destroys this View's hardware layer if possible. 13458 * 13459 * @return True if the layer was destroyed, false otherwise. 13460 * 13461 * @see #setLayerType(int, android.graphics.Paint) 13462 * @see #LAYER_TYPE_HARDWARE 13463 */ 13464 boolean destroyLayer(boolean valid) { 13465 if (mHardwareLayer != null) { 13466 AttachInfo info = mAttachInfo; 13467 if (info != null && info.mHardwareRenderer != null && 13468 info.mHardwareRenderer.isEnabled() && 13469 (valid || info.mHardwareRenderer.validate())) { 13470 13471 info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer); 13472 mHardwareLayer.destroy(); 13473 mHardwareLayer = null; 13474 13475 invalidate(true); 13476 invalidateParentCaches(); 13477 } 13478 return true; 13479 } 13480 return false; 13481 } 13482 13483 /** 13484 * Destroys all hardware rendering resources. This method is invoked 13485 * when the system needs to reclaim resources. Upon execution of this 13486 * method, you should free any OpenGL resources created by the view. 13487 * 13488 * Note: you <strong>must</strong> call 13489 * <code>super.destroyHardwareResources()</code> when overriding 13490 * this method. 13491 * 13492 * @hide 13493 */ 13494 protected void destroyHardwareResources() { 13495 resetDisplayList(); 13496 destroyLayer(true); 13497 } 13498 13499 /** 13500 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13501 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13502 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13503 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13504 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13505 * null.</p> 13506 * 13507 * <p>Enabling the drawing cache is similar to 13508 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13509 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13510 * drawing cache has no effect on rendering because the system uses a different mechanism 13511 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13512 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13513 * for information on how to enable software and hardware layers.</p> 13514 * 13515 * <p>This API can be used to manually generate 13516 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13517 * {@link #getDrawingCache()}.</p> 13518 * 13519 * @param enabled true to enable the drawing cache, false otherwise 13520 * 13521 * @see #isDrawingCacheEnabled() 13522 * @see #getDrawingCache() 13523 * @see #buildDrawingCache() 13524 * @see #setLayerType(int, android.graphics.Paint) 13525 */ 13526 public void setDrawingCacheEnabled(boolean enabled) { 13527 mCachingFailed = false; 13528 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13529 } 13530 13531 /** 13532 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13533 * 13534 * @return true if the drawing cache is enabled 13535 * 13536 * @see #setDrawingCacheEnabled(boolean) 13537 * @see #getDrawingCache() 13538 */ 13539 @ViewDebug.ExportedProperty(category = "drawing") 13540 public boolean isDrawingCacheEnabled() { 13541 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13542 } 13543 13544 /** 13545 * Debugging utility which recursively outputs the dirty state of a view and its 13546 * descendants. 13547 * 13548 * @hide 13549 */ 13550 @SuppressWarnings({"UnusedDeclaration"}) 13551 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13552 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13553 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13554 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13555 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13556 if (clear) { 13557 mPrivateFlags &= clearMask; 13558 } 13559 if (this instanceof ViewGroup) { 13560 ViewGroup parent = (ViewGroup) this; 13561 final int count = parent.getChildCount(); 13562 for (int i = 0; i < count; i++) { 13563 final View child = parent.getChildAt(i); 13564 child.outputDirtyFlags(indent + " ", clear, clearMask); 13565 } 13566 } 13567 } 13568 13569 /** 13570 * This method is used by ViewGroup to cause its children to restore or recreate their 13571 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13572 * to recreate its own display list, which would happen if it went through the normal 13573 * draw/dispatchDraw mechanisms. 13574 * 13575 * @hide 13576 */ 13577 protected void dispatchGetDisplayList() {} 13578 13579 /** 13580 * A view that is not attached or hardware accelerated cannot create a display list. 13581 * This method checks these conditions and returns the appropriate result. 13582 * 13583 * @return true if view has the ability to create a display list, false otherwise. 13584 * 13585 * @hide 13586 */ 13587 public boolean canHaveDisplayList() { 13588 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13589 } 13590 13591 /** 13592 * Returns a DisplayList. If the incoming displayList is null, one will be created. 13593 * Otherwise, the same display list will be returned (after having been rendered into 13594 * along the way, depending on the invalidation state of the view). 13595 * 13596 * @param displayList The previous version of this displayList, could be null. 13597 * @param isLayer Whether the requester of the display list is a layer. If so, 13598 * the view will avoid creating a layer inside the resulting display list. 13599 * @return A new or reused DisplayList object. 13600 */ 13601 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 13602 if (!canHaveDisplayList()) { 13603 return null; 13604 } 13605 13606 if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || 13607 displayList == null || !displayList.isValid() || 13608 (!isLayer && mRecreateDisplayList))) { 13609 // Don't need to recreate the display list, just need to tell our 13610 // children to restore/recreate theirs 13611 if (displayList != null && displayList.isValid() && 13612 !isLayer && !mRecreateDisplayList) { 13613 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13614 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13615 dispatchGetDisplayList(); 13616 13617 return displayList; 13618 } 13619 13620 if (!isLayer) { 13621 // If we got here, we're recreating it. Mark it as such to ensure that 13622 // we copy in child display lists into ours in drawChild() 13623 mRecreateDisplayList = true; 13624 } 13625 if (displayList == null) { 13626 displayList = DisplayList.create(getClass().getName()); 13627 // If we're creating a new display list, make sure our parent gets invalidated 13628 // since they will need to recreate their display list to account for this 13629 // new child display list. 13630 invalidateParentCaches(); 13631 } 13632 13633 boolean caching = false; 13634 int width = mRight - mLeft; 13635 int height = mBottom - mTop; 13636 int layerType = getLayerType(); 13637 13638 final HardwareCanvas canvas = displayList.start(width, height); 13639 13640 try { 13641 if (!isLayer && layerType != LAYER_TYPE_NONE) { 13642 if (layerType == LAYER_TYPE_HARDWARE) { 13643 final HardwareLayer layer = getHardwareLayer(); 13644 if (layer != null && layer.isValid()) { 13645 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13646 } else { 13647 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 13648 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 13649 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13650 } 13651 caching = true; 13652 } else { 13653 buildDrawingCache(true); 13654 Bitmap cache = getDrawingCache(true); 13655 if (cache != null) { 13656 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13657 caching = true; 13658 } 13659 } 13660 } else { 13661 13662 computeScroll(); 13663 13664 canvas.translate(-mScrollX, -mScrollY); 13665 if (!isLayer) { 13666 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13667 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13668 } 13669 13670 // Fast path for layouts with no backgrounds 13671 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13672 dispatchDraw(canvas); 13673 if (mOverlay != null && !mOverlay.isEmpty()) { 13674 mOverlay.getOverlayView().draw(canvas); 13675 } 13676 } else { 13677 draw(canvas); 13678 } 13679 } 13680 } finally { 13681 displayList.end(); 13682 displayList.setCaching(caching); 13683 if (isLayer) { 13684 displayList.setLeftTopRightBottom(0, 0, width, height); 13685 } else { 13686 setDisplayListProperties(displayList); 13687 } 13688 } 13689 } else if (!isLayer) { 13690 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13691 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13692 } 13693 13694 return displayList; 13695 } 13696 13697 /** 13698 * Get the DisplayList for the HardwareLayer 13699 * 13700 * @param layer The HardwareLayer whose DisplayList we want 13701 * @return A DisplayList fopr the specified HardwareLayer 13702 */ 13703 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 13704 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 13705 layer.setDisplayList(displayList); 13706 return displayList; 13707 } 13708 13709 13710 /** 13711 * <p>Returns a display list that can be used to draw this view again 13712 * without executing its draw method.</p> 13713 * 13714 * @return A DisplayList ready to replay, or null if caching is not enabled. 13715 * 13716 * @hide 13717 */ 13718 public DisplayList getDisplayList() { 13719 mDisplayList = getDisplayList(mDisplayList, false); 13720 return mDisplayList; 13721 } 13722 13723 private void clearDisplayList() { 13724 if (mDisplayList != null) { 13725 mDisplayList.clear(); 13726 } 13727 13728 if (mBackgroundDisplayList != null) { 13729 mBackgroundDisplayList.clear(); 13730 } 13731 } 13732 13733 private void resetDisplayList() { 13734 if (mDisplayList != null) { 13735 mDisplayList.reset(); 13736 } 13737 13738 if (mBackgroundDisplayList != null) { 13739 mBackgroundDisplayList.reset(); 13740 } 13741 } 13742 13743 /** 13744 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13745 * 13746 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13747 * 13748 * @see #getDrawingCache(boolean) 13749 */ 13750 public Bitmap getDrawingCache() { 13751 return getDrawingCache(false); 13752 } 13753 13754 /** 13755 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13756 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13757 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13758 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13759 * request the drawing cache by calling this method and draw it on screen if the 13760 * returned bitmap is not null.</p> 13761 * 13762 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13763 * this method will create a bitmap of the same size as this view. Because this bitmap 13764 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13765 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13766 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13767 * size than the view. This implies that your application must be able to handle this 13768 * size.</p> 13769 * 13770 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13771 * the current density of the screen when the application is in compatibility 13772 * mode. 13773 * 13774 * @return A bitmap representing this view or null if cache is disabled. 13775 * 13776 * @see #setDrawingCacheEnabled(boolean) 13777 * @see #isDrawingCacheEnabled() 13778 * @see #buildDrawingCache(boolean) 13779 * @see #destroyDrawingCache() 13780 */ 13781 public Bitmap getDrawingCache(boolean autoScale) { 13782 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13783 return null; 13784 } 13785 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13786 buildDrawingCache(autoScale); 13787 } 13788 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13789 } 13790 13791 /** 13792 * <p>Frees the resources used by the drawing cache. If you call 13793 * {@link #buildDrawingCache()} manually without calling 13794 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13795 * should cleanup the cache with this method afterwards.</p> 13796 * 13797 * @see #setDrawingCacheEnabled(boolean) 13798 * @see #buildDrawingCache() 13799 * @see #getDrawingCache() 13800 */ 13801 public void destroyDrawingCache() { 13802 if (mDrawingCache != null) { 13803 mDrawingCache.recycle(); 13804 mDrawingCache = null; 13805 } 13806 if (mUnscaledDrawingCache != null) { 13807 mUnscaledDrawingCache.recycle(); 13808 mUnscaledDrawingCache = null; 13809 } 13810 } 13811 13812 /** 13813 * Setting a solid background color for the drawing cache's bitmaps will improve 13814 * performance and memory usage. Note, though that this should only be used if this 13815 * view will always be drawn on top of a solid color. 13816 * 13817 * @param color The background color to use for the drawing cache's bitmap 13818 * 13819 * @see #setDrawingCacheEnabled(boolean) 13820 * @see #buildDrawingCache() 13821 * @see #getDrawingCache() 13822 */ 13823 public void setDrawingCacheBackgroundColor(int color) { 13824 if (color != mDrawingCacheBackgroundColor) { 13825 mDrawingCacheBackgroundColor = color; 13826 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13827 } 13828 } 13829 13830 /** 13831 * @see #setDrawingCacheBackgroundColor(int) 13832 * 13833 * @return The background color to used for the drawing cache's bitmap 13834 */ 13835 public int getDrawingCacheBackgroundColor() { 13836 return mDrawingCacheBackgroundColor; 13837 } 13838 13839 /** 13840 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13841 * 13842 * @see #buildDrawingCache(boolean) 13843 */ 13844 public void buildDrawingCache() { 13845 buildDrawingCache(false); 13846 } 13847 13848 /** 13849 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13850 * 13851 * <p>If you call {@link #buildDrawingCache()} manually without calling 13852 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13853 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13854 * 13855 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13856 * this method will create a bitmap of the same size as this view. Because this bitmap 13857 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13858 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13859 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13860 * size than the view. This implies that your application must be able to handle this 13861 * size.</p> 13862 * 13863 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13864 * you do not need the drawing cache bitmap, calling this method will increase memory 13865 * usage and cause the view to be rendered in software once, thus negatively impacting 13866 * performance.</p> 13867 * 13868 * @see #getDrawingCache() 13869 * @see #destroyDrawingCache() 13870 */ 13871 public void buildDrawingCache(boolean autoScale) { 13872 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13873 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13874 mCachingFailed = false; 13875 13876 int width = mRight - mLeft; 13877 int height = mBottom - mTop; 13878 13879 final AttachInfo attachInfo = mAttachInfo; 13880 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13881 13882 if (autoScale && scalingRequired) { 13883 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13884 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13885 } 13886 13887 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13888 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13889 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13890 13891 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13892 final long drawingCacheSize = 13893 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13894 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13895 if (width > 0 && height > 0) { 13896 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13897 + projectedBitmapSize + " bytes, only " 13898 + drawingCacheSize + " available"); 13899 } 13900 destroyDrawingCache(); 13901 mCachingFailed = true; 13902 return; 13903 } 13904 13905 boolean clear = true; 13906 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13907 13908 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13909 Bitmap.Config quality; 13910 if (!opaque) { 13911 // Never pick ARGB_4444 because it looks awful 13912 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13913 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13914 case DRAWING_CACHE_QUALITY_AUTO: 13915 case DRAWING_CACHE_QUALITY_LOW: 13916 case DRAWING_CACHE_QUALITY_HIGH: 13917 default: 13918 quality = Bitmap.Config.ARGB_8888; 13919 break; 13920 } 13921 } else { 13922 // Optimization for translucent windows 13923 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13924 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13925 } 13926 13927 // Try to cleanup memory 13928 if (bitmap != null) bitmap.recycle(); 13929 13930 try { 13931 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13932 width, height, quality); 13933 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 13934 if (autoScale) { 13935 mDrawingCache = bitmap; 13936 } else { 13937 mUnscaledDrawingCache = bitmap; 13938 } 13939 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 13940 } catch (OutOfMemoryError e) { 13941 // If there is not enough memory to create the bitmap cache, just 13942 // ignore the issue as bitmap caches are not required to draw the 13943 // view hierarchy 13944 if (autoScale) { 13945 mDrawingCache = null; 13946 } else { 13947 mUnscaledDrawingCache = null; 13948 } 13949 mCachingFailed = true; 13950 return; 13951 } 13952 13953 clear = drawingCacheBackgroundColor != 0; 13954 } 13955 13956 Canvas canvas; 13957 if (attachInfo != null) { 13958 canvas = attachInfo.mCanvas; 13959 if (canvas == null) { 13960 canvas = new Canvas(); 13961 } 13962 canvas.setBitmap(bitmap); 13963 // Temporarily clobber the cached Canvas in case one of our children 13964 // is also using a drawing cache. Without this, the children would 13965 // steal the canvas by attaching their own bitmap to it and bad, bad 13966 // thing would happen (invisible views, corrupted drawings, etc.) 13967 attachInfo.mCanvas = null; 13968 } else { 13969 // This case should hopefully never or seldom happen 13970 canvas = new Canvas(bitmap); 13971 } 13972 13973 if (clear) { 13974 bitmap.eraseColor(drawingCacheBackgroundColor); 13975 } 13976 13977 computeScroll(); 13978 final int restoreCount = canvas.save(); 13979 13980 if (autoScale && scalingRequired) { 13981 final float scale = attachInfo.mApplicationScale; 13982 canvas.scale(scale, scale); 13983 } 13984 13985 canvas.translate(-mScrollX, -mScrollY); 13986 13987 mPrivateFlags |= PFLAG_DRAWN; 13988 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 13989 mLayerType != LAYER_TYPE_NONE) { 13990 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 13991 } 13992 13993 // Fast path for layouts with no backgrounds 13994 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13995 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13996 dispatchDraw(canvas); 13997 if (mOverlay != null && !mOverlay.isEmpty()) { 13998 mOverlay.getOverlayView().draw(canvas); 13999 } 14000 } else { 14001 draw(canvas); 14002 } 14003 14004 canvas.restoreToCount(restoreCount); 14005 canvas.setBitmap(null); 14006 14007 if (attachInfo != null) { 14008 // Restore the cached Canvas for our siblings 14009 attachInfo.mCanvas = canvas; 14010 } 14011 } 14012 } 14013 14014 /** 14015 * Create a snapshot of the view into a bitmap. We should probably make 14016 * some form of this public, but should think about the API. 14017 */ 14018 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14019 int width = mRight - mLeft; 14020 int height = mBottom - mTop; 14021 14022 final AttachInfo attachInfo = mAttachInfo; 14023 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14024 width = (int) ((width * scale) + 0.5f); 14025 height = (int) ((height * scale) + 0.5f); 14026 14027 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14028 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14029 if (bitmap == null) { 14030 throw new OutOfMemoryError(); 14031 } 14032 14033 Resources resources = getResources(); 14034 if (resources != null) { 14035 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14036 } 14037 14038 Canvas canvas; 14039 if (attachInfo != null) { 14040 canvas = attachInfo.mCanvas; 14041 if (canvas == null) { 14042 canvas = new Canvas(); 14043 } 14044 canvas.setBitmap(bitmap); 14045 // Temporarily clobber the cached Canvas in case one of our children 14046 // is also using a drawing cache. Without this, the children would 14047 // steal the canvas by attaching their own bitmap to it and bad, bad 14048 // things would happen (invisible views, corrupted drawings, etc.) 14049 attachInfo.mCanvas = null; 14050 } else { 14051 // This case should hopefully never or seldom happen 14052 canvas = new Canvas(bitmap); 14053 } 14054 14055 if ((backgroundColor & 0xff000000) != 0) { 14056 bitmap.eraseColor(backgroundColor); 14057 } 14058 14059 computeScroll(); 14060 final int restoreCount = canvas.save(); 14061 canvas.scale(scale, scale); 14062 canvas.translate(-mScrollX, -mScrollY); 14063 14064 // Temporarily remove the dirty mask 14065 int flags = mPrivateFlags; 14066 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14067 14068 // Fast path for layouts with no backgrounds 14069 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14070 dispatchDraw(canvas); 14071 if (mOverlay != null && !mOverlay.isEmpty()) { 14072 mOverlay.getOverlayView().draw(canvas); 14073 } 14074 } else { 14075 draw(canvas); 14076 } 14077 14078 mPrivateFlags = flags; 14079 14080 canvas.restoreToCount(restoreCount); 14081 canvas.setBitmap(null); 14082 14083 if (attachInfo != null) { 14084 // Restore the cached Canvas for our siblings 14085 attachInfo.mCanvas = canvas; 14086 } 14087 14088 return bitmap; 14089 } 14090 14091 /** 14092 * Indicates whether this View is currently in edit mode. A View is usually 14093 * in edit mode when displayed within a developer tool. For instance, if 14094 * this View is being drawn by a visual user interface builder, this method 14095 * should return true. 14096 * 14097 * Subclasses should check the return value of this method to provide 14098 * different behaviors if their normal behavior might interfere with the 14099 * host environment. For instance: the class spawns a thread in its 14100 * constructor, the drawing code relies on device-specific features, etc. 14101 * 14102 * This method is usually checked in the drawing code of custom widgets. 14103 * 14104 * @return True if this View is in edit mode, false otherwise. 14105 */ 14106 public boolean isInEditMode() { 14107 return false; 14108 } 14109 14110 /** 14111 * If the View draws content inside its padding and enables fading edges, 14112 * it needs to support padding offsets. Padding offsets are added to the 14113 * fading edges to extend the length of the fade so that it covers pixels 14114 * drawn inside the padding. 14115 * 14116 * Subclasses of this class should override this method if they need 14117 * to draw content inside the padding. 14118 * 14119 * @return True if padding offset must be applied, false otherwise. 14120 * 14121 * @see #getLeftPaddingOffset() 14122 * @see #getRightPaddingOffset() 14123 * @see #getTopPaddingOffset() 14124 * @see #getBottomPaddingOffset() 14125 * 14126 * @since CURRENT 14127 */ 14128 protected boolean isPaddingOffsetRequired() { 14129 return false; 14130 } 14131 14132 /** 14133 * Amount by which to extend the left fading region. Called only when 14134 * {@link #isPaddingOffsetRequired()} returns true. 14135 * 14136 * @return The left padding offset in pixels. 14137 * 14138 * @see #isPaddingOffsetRequired() 14139 * 14140 * @since CURRENT 14141 */ 14142 protected int getLeftPaddingOffset() { 14143 return 0; 14144 } 14145 14146 /** 14147 * Amount by which to extend the right fading region. Called only when 14148 * {@link #isPaddingOffsetRequired()} returns true. 14149 * 14150 * @return The right padding offset in pixels. 14151 * 14152 * @see #isPaddingOffsetRequired() 14153 * 14154 * @since CURRENT 14155 */ 14156 protected int getRightPaddingOffset() { 14157 return 0; 14158 } 14159 14160 /** 14161 * Amount by which to extend the top fading region. Called only when 14162 * {@link #isPaddingOffsetRequired()} returns true. 14163 * 14164 * @return The top padding offset in pixels. 14165 * 14166 * @see #isPaddingOffsetRequired() 14167 * 14168 * @since CURRENT 14169 */ 14170 protected int getTopPaddingOffset() { 14171 return 0; 14172 } 14173 14174 /** 14175 * Amount by which to extend the bottom fading region. Called only when 14176 * {@link #isPaddingOffsetRequired()} returns true. 14177 * 14178 * @return The bottom padding offset in pixels. 14179 * 14180 * @see #isPaddingOffsetRequired() 14181 * 14182 * @since CURRENT 14183 */ 14184 protected int getBottomPaddingOffset() { 14185 return 0; 14186 } 14187 14188 /** 14189 * @hide 14190 * @param offsetRequired 14191 */ 14192 protected int getFadeTop(boolean offsetRequired) { 14193 int top = mPaddingTop; 14194 if (offsetRequired) top += getTopPaddingOffset(); 14195 return top; 14196 } 14197 14198 /** 14199 * @hide 14200 * @param offsetRequired 14201 */ 14202 protected int getFadeHeight(boolean offsetRequired) { 14203 int padding = mPaddingTop; 14204 if (offsetRequired) padding += getTopPaddingOffset(); 14205 return mBottom - mTop - mPaddingBottom - padding; 14206 } 14207 14208 /** 14209 * <p>Indicates whether this view is attached to a hardware accelerated 14210 * window or not.</p> 14211 * 14212 * <p>Even if this method returns true, it does not mean that every call 14213 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14214 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14215 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14216 * window is hardware accelerated, 14217 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14218 * return false, and this method will return true.</p> 14219 * 14220 * @return True if the view is attached to a window and the window is 14221 * hardware accelerated; false in any other case. 14222 */ 14223 public boolean isHardwareAccelerated() { 14224 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14225 } 14226 14227 /** 14228 * Sets a rectangular area on this view to which the view will be clipped 14229 * when it is drawn. Setting the value to null will remove the clip bounds 14230 * and the view will draw normally, using its full bounds. 14231 * 14232 * @param clipBounds The rectangular area, in the local coordinates of 14233 * this view, to which future drawing operations will be clipped. 14234 */ 14235 public void setClipBounds(Rect clipBounds) { 14236 if (clipBounds != null) { 14237 if (clipBounds.equals(mClipBounds)) { 14238 return; 14239 } 14240 if (mClipBounds == null) { 14241 invalidate(); 14242 mClipBounds = new Rect(clipBounds); 14243 } else { 14244 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14245 Math.min(mClipBounds.top, clipBounds.top), 14246 Math.max(mClipBounds.right, clipBounds.right), 14247 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14248 mClipBounds.set(clipBounds); 14249 } 14250 } else { 14251 if (mClipBounds != null) { 14252 invalidate(); 14253 mClipBounds = null; 14254 } 14255 } 14256 } 14257 14258 /** 14259 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14260 * 14261 * @return A copy of the current clip bounds if clip bounds are set, 14262 * otherwise null. 14263 */ 14264 public Rect getClipBounds() { 14265 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14266 } 14267 14268 /** 14269 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14270 * case of an active Animation being run on the view. 14271 */ 14272 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14273 Animation a, boolean scalingRequired) { 14274 Transformation invalidationTransform; 14275 final int flags = parent.mGroupFlags; 14276 final boolean initialized = a.isInitialized(); 14277 if (!initialized) { 14278 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14279 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14280 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14281 onAnimationStart(); 14282 } 14283 14284 final Transformation t = parent.getChildTransformation(); 14285 boolean more = a.getTransformation(drawingTime, t, 1f); 14286 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14287 if (parent.mInvalidationTransformation == null) { 14288 parent.mInvalidationTransformation = new Transformation(); 14289 } 14290 invalidationTransform = parent.mInvalidationTransformation; 14291 a.getTransformation(drawingTime, invalidationTransform, 1f); 14292 } else { 14293 invalidationTransform = t; 14294 } 14295 14296 if (more) { 14297 if (!a.willChangeBounds()) { 14298 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14299 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14300 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14301 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14302 // The child need to draw an animation, potentially offscreen, so 14303 // make sure we do not cancel invalidate requests 14304 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14305 parent.invalidate(mLeft, mTop, mRight, mBottom); 14306 } 14307 } else { 14308 if (parent.mInvalidateRegion == null) { 14309 parent.mInvalidateRegion = new RectF(); 14310 } 14311 final RectF region = parent.mInvalidateRegion; 14312 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14313 invalidationTransform); 14314 14315 // The child need to draw an animation, potentially offscreen, so 14316 // make sure we do not cancel invalidate requests 14317 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14318 14319 final int left = mLeft + (int) region.left; 14320 final int top = mTop + (int) region.top; 14321 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14322 top + (int) (region.height() + .5f)); 14323 } 14324 } 14325 return more; 14326 } 14327 14328 /** 14329 * This method is called by getDisplayList() when a display list is created or re-rendered. 14330 * It sets or resets the current value of all properties on that display list (resetting is 14331 * necessary when a display list is being re-created, because we need to make sure that 14332 * previously-set transform values 14333 */ 14334 void setDisplayListProperties(DisplayList displayList) { 14335 if (displayList != null) { 14336 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 14337 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 14338 if (mParent instanceof ViewGroup) { 14339 displayList.setClipToBounds( 14340 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14341 } 14342 if (this instanceof ViewGroup) { 14343 displayList.setIsolatedZVolume( 14344 (((ViewGroup) this).mGroupFlags & ViewGroup.FLAG_ISOLATED_Z_VOLUME) != 0); 14345 } 14346 displayList.setOutline(mOutline); 14347 float alpha = 1; 14348 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14349 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14350 ViewGroup parentVG = (ViewGroup) mParent; 14351 final Transformation t = parentVG.getChildTransformation(); 14352 if (parentVG.getChildStaticTransformation(this, t)) { 14353 final int transformType = t.getTransformationType(); 14354 if (transformType != Transformation.TYPE_IDENTITY) { 14355 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14356 alpha = t.getAlpha(); 14357 } 14358 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14359 displayList.setMatrix(t.getMatrix()); 14360 } 14361 } 14362 } 14363 } 14364 if (mTransformationInfo != null) { 14365 alpha *= getFinalAlpha(); 14366 if (alpha < 1) { 14367 final int multipliedAlpha = (int) (255 * alpha); 14368 if (onSetAlpha(multipliedAlpha)) { 14369 alpha = 1; 14370 } 14371 } 14372 displayList.setTransformationInfo(alpha, 14373 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 14374 mTransformationInfo.mTranslationZ, 14375 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 14376 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 14377 mTransformationInfo.mScaleY); 14378 if (mTransformationInfo.mCamera == null) { 14379 mTransformationInfo.mCamera = new Camera(); 14380 mTransformationInfo.matrix3D = new Matrix(); 14381 } 14382 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 14383 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) { 14384 displayList.setPivotX(getPivotX()); 14385 displayList.setPivotY(getPivotY()); 14386 } 14387 } else if (alpha < 1) { 14388 displayList.setAlpha(alpha); 14389 } 14390 } 14391 } 14392 14393 /** 14394 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14395 * This draw() method is an implementation detail and is not intended to be overridden or 14396 * to be called from anywhere else other than ViewGroup.drawChild(). 14397 */ 14398 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14399 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14400 boolean more = false; 14401 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14402 final int flags = parent.mGroupFlags; 14403 14404 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14405 parent.getChildTransformation().clear(); 14406 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14407 } 14408 14409 Transformation transformToApply = null; 14410 boolean concatMatrix = false; 14411 14412 boolean scalingRequired = false; 14413 boolean caching; 14414 int layerType = getLayerType(); 14415 14416 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14417 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14418 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14419 caching = true; 14420 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14421 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14422 } else { 14423 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14424 } 14425 14426 final Animation a = getAnimation(); 14427 if (a != null) { 14428 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14429 concatMatrix = a.willChangeTransformationMatrix(); 14430 if (concatMatrix) { 14431 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14432 } 14433 transformToApply = parent.getChildTransformation(); 14434 } else { 14435 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == 14436 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) { 14437 // No longer animating: clear out old animation matrix 14438 mDisplayList.setAnimationMatrix(null); 14439 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14440 } 14441 if (!useDisplayListProperties && 14442 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14443 final Transformation t = parent.getChildTransformation(); 14444 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14445 if (hasTransform) { 14446 final int transformType = t.getTransformationType(); 14447 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14448 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14449 } 14450 } 14451 } 14452 14453 concatMatrix |= !childHasIdentityMatrix; 14454 14455 // Sets the flag as early as possible to allow draw() implementations 14456 // to call invalidate() successfully when doing animations 14457 mPrivateFlags |= PFLAG_DRAWN; 14458 14459 if (!concatMatrix && 14460 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14461 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14462 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14463 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14464 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14465 return more; 14466 } 14467 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14468 14469 if (hardwareAccelerated) { 14470 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14471 // retain the flag's value temporarily in the mRecreateDisplayList flag 14472 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14473 mPrivateFlags &= ~PFLAG_INVALIDATED; 14474 } 14475 14476 DisplayList displayList = null; 14477 Bitmap cache = null; 14478 boolean hasDisplayList = false; 14479 if (caching) { 14480 if (!hardwareAccelerated) { 14481 if (layerType != LAYER_TYPE_NONE) { 14482 layerType = LAYER_TYPE_SOFTWARE; 14483 buildDrawingCache(true); 14484 } 14485 cache = getDrawingCache(true); 14486 } else { 14487 switch (layerType) { 14488 case LAYER_TYPE_SOFTWARE: 14489 if (useDisplayListProperties) { 14490 hasDisplayList = canHaveDisplayList(); 14491 } else { 14492 buildDrawingCache(true); 14493 cache = getDrawingCache(true); 14494 } 14495 break; 14496 case LAYER_TYPE_HARDWARE: 14497 if (useDisplayListProperties) { 14498 hasDisplayList = canHaveDisplayList(); 14499 } 14500 break; 14501 case LAYER_TYPE_NONE: 14502 // Delay getting the display list until animation-driven alpha values are 14503 // set up and possibly passed on to the view 14504 hasDisplayList = canHaveDisplayList(); 14505 break; 14506 } 14507 } 14508 } 14509 useDisplayListProperties &= hasDisplayList; 14510 if (useDisplayListProperties) { 14511 displayList = getDisplayList(); 14512 if (!displayList.isValid()) { 14513 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14514 // to getDisplayList(), the display list will be marked invalid and we should not 14515 // try to use it again. 14516 displayList = null; 14517 hasDisplayList = false; 14518 useDisplayListProperties = false; 14519 } 14520 } 14521 14522 int sx = 0; 14523 int sy = 0; 14524 if (!hasDisplayList) { 14525 computeScroll(); 14526 sx = mScrollX; 14527 sy = mScrollY; 14528 } 14529 14530 final boolean hasNoCache = cache == null || hasDisplayList; 14531 final boolean offsetForScroll = cache == null && !hasDisplayList && 14532 layerType != LAYER_TYPE_HARDWARE; 14533 14534 int restoreTo = -1; 14535 if (!useDisplayListProperties || transformToApply != null) { 14536 restoreTo = canvas.save(); 14537 } 14538 if (offsetForScroll) { 14539 canvas.translate(mLeft - sx, mTop - sy); 14540 } else { 14541 if (!useDisplayListProperties) { 14542 canvas.translate(mLeft, mTop); 14543 } 14544 if (scalingRequired) { 14545 if (useDisplayListProperties) { 14546 // TODO: Might not need this if we put everything inside the DL 14547 restoreTo = canvas.save(); 14548 } 14549 // mAttachInfo cannot be null, otherwise scalingRequired == false 14550 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14551 canvas.scale(scale, scale); 14552 } 14553 } 14554 14555 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14556 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14557 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14558 if (transformToApply != null || !childHasIdentityMatrix) { 14559 int transX = 0; 14560 int transY = 0; 14561 14562 if (offsetForScroll) { 14563 transX = -sx; 14564 transY = -sy; 14565 } 14566 14567 if (transformToApply != null) { 14568 if (concatMatrix) { 14569 if (useDisplayListProperties) { 14570 displayList.setAnimationMatrix(transformToApply.getMatrix()); 14571 } else { 14572 // Undo the scroll translation, apply the transformation matrix, 14573 // then redo the scroll translate to get the correct result. 14574 canvas.translate(-transX, -transY); 14575 canvas.concat(transformToApply.getMatrix()); 14576 canvas.translate(transX, transY); 14577 } 14578 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14579 } 14580 14581 float transformAlpha = transformToApply.getAlpha(); 14582 if (transformAlpha < 1) { 14583 alpha *= transformAlpha; 14584 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14585 } 14586 } 14587 14588 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14589 canvas.translate(-transX, -transY); 14590 canvas.concat(getMatrix()); 14591 canvas.translate(transX, transY); 14592 } 14593 } 14594 14595 // Deal with alpha if it is or used to be <1 14596 if (alpha < 1 || 14597 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14598 if (alpha < 1) { 14599 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14600 } else { 14601 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14602 } 14603 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14604 if (hasNoCache) { 14605 final int multipliedAlpha = (int) (255 * alpha); 14606 if (!onSetAlpha(multipliedAlpha)) { 14607 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14608 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14609 layerType != LAYER_TYPE_NONE) { 14610 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14611 } 14612 if (useDisplayListProperties) { 14613 displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14614 } else if (layerType == LAYER_TYPE_NONE) { 14615 final int scrollX = hasDisplayList ? 0 : sx; 14616 final int scrollY = hasDisplayList ? 0 : sy; 14617 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14618 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14619 } 14620 } else { 14621 // Alpha is handled by the child directly, clobber the layer's alpha 14622 mPrivateFlags |= PFLAG_ALPHA_SET; 14623 } 14624 } 14625 } 14626 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14627 onSetAlpha(255); 14628 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14629 } 14630 14631 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14632 !useDisplayListProperties && cache == null) { 14633 if (offsetForScroll) { 14634 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14635 } else { 14636 if (!scalingRequired || cache == null) { 14637 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14638 } else { 14639 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14640 } 14641 } 14642 } 14643 14644 if (!useDisplayListProperties && hasDisplayList) { 14645 displayList = getDisplayList(); 14646 if (!displayList.isValid()) { 14647 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14648 // to getDisplayList(), the display list will be marked invalid and we should not 14649 // try to use it again. 14650 displayList = null; 14651 hasDisplayList = false; 14652 } 14653 } 14654 14655 if (hasNoCache) { 14656 boolean layerRendered = false; 14657 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14658 final HardwareLayer layer = getHardwareLayer(); 14659 if (layer != null && layer.isValid()) { 14660 mLayerPaint.setAlpha((int) (alpha * 255)); 14661 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14662 layerRendered = true; 14663 } else { 14664 final int scrollX = hasDisplayList ? 0 : sx; 14665 final int scrollY = hasDisplayList ? 0 : sy; 14666 canvas.saveLayer(scrollX, scrollY, 14667 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14668 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14669 } 14670 } 14671 14672 if (!layerRendered) { 14673 if (!hasDisplayList) { 14674 // Fast path for layouts with no backgrounds 14675 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14676 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14677 dispatchDraw(canvas); 14678 } else { 14679 draw(canvas); 14680 } 14681 } else { 14682 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14683 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14684 } 14685 } 14686 } else if (cache != null) { 14687 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14688 Paint cachePaint; 14689 14690 if (layerType == LAYER_TYPE_NONE) { 14691 cachePaint = parent.mCachePaint; 14692 if (cachePaint == null) { 14693 cachePaint = new Paint(); 14694 cachePaint.setDither(false); 14695 parent.mCachePaint = cachePaint; 14696 } 14697 if (alpha < 1) { 14698 cachePaint.setAlpha((int) (alpha * 255)); 14699 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14700 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14701 cachePaint.setAlpha(255); 14702 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14703 } 14704 } else { 14705 cachePaint = mLayerPaint; 14706 cachePaint.setAlpha((int) (alpha * 255)); 14707 } 14708 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14709 } 14710 14711 if (restoreTo >= 0) { 14712 canvas.restoreToCount(restoreTo); 14713 } 14714 14715 if (a != null && !more) { 14716 if (!hardwareAccelerated && !a.getFillAfter()) { 14717 onSetAlpha(255); 14718 } 14719 parent.finishAnimatingView(this, a); 14720 } 14721 14722 if (more && hardwareAccelerated) { 14723 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14724 // alpha animations should cause the child to recreate its display list 14725 invalidate(true); 14726 } 14727 } 14728 14729 mRecreateDisplayList = false; 14730 14731 return more; 14732 } 14733 14734 /** 14735 * Manually render this view (and all of its children) to the given Canvas. 14736 * The view must have already done a full layout before this function is 14737 * called. When implementing a view, implement 14738 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14739 * If you do need to override this method, call the superclass version. 14740 * 14741 * @param canvas The Canvas to which the View is rendered. 14742 */ 14743 public void draw(Canvas canvas) { 14744 if (mClipBounds != null) { 14745 canvas.clipRect(mClipBounds); 14746 } 14747 final int privateFlags = mPrivateFlags; 14748 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14749 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14750 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14751 14752 /* 14753 * Draw traversal performs several drawing steps which must be executed 14754 * in the appropriate order: 14755 * 14756 * 1. Draw the background 14757 * 2. If necessary, save the canvas' layers to prepare for fading 14758 * 3. Draw view's content 14759 * 4. Draw children 14760 * 5. If necessary, draw the fading edges and restore layers 14761 * 6. Draw decorations (scrollbars for instance) 14762 */ 14763 14764 // Step 1, draw the background, if needed 14765 int saveCount; 14766 14767 if (!dirtyOpaque) { 14768 drawBackground(canvas); 14769 } 14770 14771 // skip step 2 & 5 if possible (common case) 14772 final int viewFlags = mViewFlags; 14773 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14774 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14775 if (!verticalEdges && !horizontalEdges) { 14776 // Step 3, draw the content 14777 if (!dirtyOpaque) onDraw(canvas); 14778 14779 // Step 4, draw the children 14780 dispatchDraw(canvas); 14781 14782 // Step 6, draw decorations (scrollbars) 14783 onDrawScrollBars(canvas); 14784 14785 if (mOverlay != null && !mOverlay.isEmpty()) { 14786 mOverlay.getOverlayView().dispatchDraw(canvas); 14787 } 14788 14789 // we're done... 14790 return; 14791 } 14792 14793 /* 14794 * Here we do the full fledged routine... 14795 * (this is an uncommon case where speed matters less, 14796 * this is why we repeat some of the tests that have been 14797 * done above) 14798 */ 14799 14800 boolean drawTop = false; 14801 boolean drawBottom = false; 14802 boolean drawLeft = false; 14803 boolean drawRight = false; 14804 14805 float topFadeStrength = 0.0f; 14806 float bottomFadeStrength = 0.0f; 14807 float leftFadeStrength = 0.0f; 14808 float rightFadeStrength = 0.0f; 14809 14810 // Step 2, save the canvas' layers 14811 int paddingLeft = mPaddingLeft; 14812 14813 final boolean offsetRequired = isPaddingOffsetRequired(); 14814 if (offsetRequired) { 14815 paddingLeft += getLeftPaddingOffset(); 14816 } 14817 14818 int left = mScrollX + paddingLeft; 14819 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14820 int top = mScrollY + getFadeTop(offsetRequired); 14821 int bottom = top + getFadeHeight(offsetRequired); 14822 14823 if (offsetRequired) { 14824 right += getRightPaddingOffset(); 14825 bottom += getBottomPaddingOffset(); 14826 } 14827 14828 final ScrollabilityCache scrollabilityCache = mScrollCache; 14829 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14830 int length = (int) fadeHeight; 14831 14832 // clip the fade length if top and bottom fades overlap 14833 // overlapping fades produce odd-looking artifacts 14834 if (verticalEdges && (top + length > bottom - length)) { 14835 length = (bottom - top) / 2; 14836 } 14837 14838 // also clip horizontal fades if necessary 14839 if (horizontalEdges && (left + length > right - length)) { 14840 length = (right - left) / 2; 14841 } 14842 14843 if (verticalEdges) { 14844 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14845 drawTop = topFadeStrength * fadeHeight > 1.0f; 14846 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14847 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14848 } 14849 14850 if (horizontalEdges) { 14851 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14852 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14853 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14854 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14855 } 14856 14857 saveCount = canvas.getSaveCount(); 14858 14859 int solidColor = getSolidColor(); 14860 if (solidColor == 0) { 14861 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14862 14863 if (drawTop) { 14864 canvas.saveLayer(left, top, right, top + length, null, flags); 14865 } 14866 14867 if (drawBottom) { 14868 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14869 } 14870 14871 if (drawLeft) { 14872 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14873 } 14874 14875 if (drawRight) { 14876 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14877 } 14878 } else { 14879 scrollabilityCache.setFadeColor(solidColor); 14880 } 14881 14882 // Step 3, draw the content 14883 if (!dirtyOpaque) onDraw(canvas); 14884 14885 // Step 4, draw the children 14886 dispatchDraw(canvas); 14887 14888 // Step 5, draw the fade effect and restore layers 14889 final Paint p = scrollabilityCache.paint; 14890 final Matrix matrix = scrollabilityCache.matrix; 14891 final Shader fade = scrollabilityCache.shader; 14892 14893 if (drawTop) { 14894 matrix.setScale(1, fadeHeight * topFadeStrength); 14895 matrix.postTranslate(left, top); 14896 fade.setLocalMatrix(matrix); 14897 canvas.drawRect(left, top, right, top + length, p); 14898 } 14899 14900 if (drawBottom) { 14901 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14902 matrix.postRotate(180); 14903 matrix.postTranslate(left, bottom); 14904 fade.setLocalMatrix(matrix); 14905 canvas.drawRect(left, bottom - length, right, bottom, p); 14906 } 14907 14908 if (drawLeft) { 14909 matrix.setScale(1, fadeHeight * leftFadeStrength); 14910 matrix.postRotate(-90); 14911 matrix.postTranslate(left, top); 14912 fade.setLocalMatrix(matrix); 14913 canvas.drawRect(left, top, left + length, bottom, p); 14914 } 14915 14916 if (drawRight) { 14917 matrix.setScale(1, fadeHeight * rightFadeStrength); 14918 matrix.postRotate(90); 14919 matrix.postTranslate(right, top); 14920 fade.setLocalMatrix(matrix); 14921 canvas.drawRect(right - length, top, right, bottom, p); 14922 } 14923 14924 canvas.restoreToCount(saveCount); 14925 14926 // Step 6, draw decorations (scrollbars) 14927 onDrawScrollBars(canvas); 14928 14929 if (mOverlay != null && !mOverlay.isEmpty()) { 14930 mOverlay.getOverlayView().dispatchDraw(canvas); 14931 } 14932 } 14933 14934 /** 14935 * Draws the background onto the specified canvas. 14936 * 14937 * @param canvas Canvas on which to draw the background 14938 */ 14939 private void drawBackground(Canvas canvas) { 14940 final Drawable background = mBackground; 14941 if (background == null) { 14942 return; 14943 } 14944 14945 if (mBackgroundSizeChanged) { 14946 // We should see the background invalidate itself, but just to be 14947 // careful we're going to clear the display list and force redraw. 14948 if (mBackgroundDisplayList != null) { 14949 mBackgroundDisplayList.clear(); 14950 } 14951 14952 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14953 mBackgroundSizeChanged = false; 14954 } 14955 14956 14957 // Attempt to use a display list if requested. 14958 if (canvas != null && canvas.isHardwareAccelerated()) { 14959 mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList); 14960 14961 final DisplayList displayList = mBackgroundDisplayList; 14962 if (displayList != null && displayList.isValid()) { 14963 setBackgroundDisplayListProperties(displayList); 14964 ((HardwareCanvas) canvas).drawDisplayList(displayList); 14965 return; 14966 } 14967 } 14968 14969 final int scrollX = mScrollX; 14970 final int scrollY = mScrollY; 14971 if ((scrollX | scrollY) == 0) { 14972 background.draw(canvas); 14973 } else { 14974 canvas.translate(scrollX, scrollY); 14975 background.draw(canvas); 14976 canvas.translate(-scrollX, -scrollY); 14977 } 14978 } 14979 14980 /** 14981 * Set up background drawable display list properties. 14982 * 14983 * @param displayList Valid display list for the background drawable 14984 */ 14985 private void setBackgroundDisplayListProperties(DisplayList displayList) { 14986 displayList.setTranslationX(mScrollX); 14987 displayList.setTranslationY(mScrollY); 14988 } 14989 14990 /** 14991 * Creates a new display list or updates the existing display list for the 14992 * specified Drawable. 14993 * 14994 * @param drawable Drawable for which to create a display list 14995 * @param displayList Existing display list, or {@code null} 14996 * @return A valid display list for the specified drawable 14997 */ 14998 private static DisplayList getDrawableDisplayList(Drawable drawable, DisplayList displayList) { 14999 if (displayList != null && displayList.isValid()) { 15000 return displayList; 15001 } 15002 15003 if (displayList == null) { 15004 displayList = DisplayList.create(drawable.getClass().getName()); 15005 } 15006 15007 final Rect bounds = drawable.getBounds(); 15008 final int width = bounds.width(); 15009 final int height = bounds.height(); 15010 final HardwareCanvas canvas = displayList.start(width, height); 15011 drawable.draw(canvas); 15012 displayList.end(); 15013 15014 // Set up drawable properties that are view-independent. 15015 displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15016 displayList.setProjectBackwards(drawable.isProjected()); 15017 displayList.setClipToBounds(false); 15018 return displayList; 15019 } 15020 15021 /** 15022 * Returns the overlay for this view, creating it if it does not yet exist. 15023 * Adding drawables to the overlay will cause them to be displayed whenever 15024 * the view itself is redrawn. Objects in the overlay should be actively 15025 * managed: remove them when they should not be displayed anymore. The 15026 * overlay will always have the same size as its host view. 15027 * 15028 * <p>Note: Overlays do not currently work correctly with {@link 15029 * SurfaceView} or {@link TextureView}; contents in overlays for these 15030 * types of views may not display correctly.</p> 15031 * 15032 * @return The ViewOverlay object for this view. 15033 * @see ViewOverlay 15034 */ 15035 public ViewOverlay getOverlay() { 15036 if (mOverlay == null) { 15037 mOverlay = new ViewOverlay(mContext, this); 15038 } 15039 return mOverlay; 15040 } 15041 15042 /** 15043 * Override this if your view is known to always be drawn on top of a solid color background, 15044 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15045 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15046 * should be set to 0xFF. 15047 * 15048 * @see #setVerticalFadingEdgeEnabled(boolean) 15049 * @see #setHorizontalFadingEdgeEnabled(boolean) 15050 * 15051 * @return The known solid color background for this view, or 0 if the color may vary 15052 */ 15053 @ViewDebug.ExportedProperty(category = "drawing") 15054 public int getSolidColor() { 15055 return 0; 15056 } 15057 15058 /** 15059 * Build a human readable string representation of the specified view flags. 15060 * 15061 * @param flags the view flags to convert to a string 15062 * @return a String representing the supplied flags 15063 */ 15064 private static String printFlags(int flags) { 15065 String output = ""; 15066 int numFlags = 0; 15067 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15068 output += "TAKES_FOCUS"; 15069 numFlags++; 15070 } 15071 15072 switch (flags & VISIBILITY_MASK) { 15073 case INVISIBLE: 15074 if (numFlags > 0) { 15075 output += " "; 15076 } 15077 output += "INVISIBLE"; 15078 // USELESS HERE numFlags++; 15079 break; 15080 case GONE: 15081 if (numFlags > 0) { 15082 output += " "; 15083 } 15084 output += "GONE"; 15085 // USELESS HERE numFlags++; 15086 break; 15087 default: 15088 break; 15089 } 15090 return output; 15091 } 15092 15093 /** 15094 * Build a human readable string representation of the specified private 15095 * view flags. 15096 * 15097 * @param privateFlags the private view flags to convert to a string 15098 * @return a String representing the supplied flags 15099 */ 15100 private static String printPrivateFlags(int privateFlags) { 15101 String output = ""; 15102 int numFlags = 0; 15103 15104 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15105 output += "WANTS_FOCUS"; 15106 numFlags++; 15107 } 15108 15109 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15110 if (numFlags > 0) { 15111 output += " "; 15112 } 15113 output += "FOCUSED"; 15114 numFlags++; 15115 } 15116 15117 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15118 if (numFlags > 0) { 15119 output += " "; 15120 } 15121 output += "SELECTED"; 15122 numFlags++; 15123 } 15124 15125 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15126 if (numFlags > 0) { 15127 output += " "; 15128 } 15129 output += "IS_ROOT_NAMESPACE"; 15130 numFlags++; 15131 } 15132 15133 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15134 if (numFlags > 0) { 15135 output += " "; 15136 } 15137 output += "HAS_BOUNDS"; 15138 numFlags++; 15139 } 15140 15141 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15142 if (numFlags > 0) { 15143 output += " "; 15144 } 15145 output += "DRAWN"; 15146 // USELESS HERE numFlags++; 15147 } 15148 return output; 15149 } 15150 15151 /** 15152 * <p>Indicates whether or not this view's layout will be requested during 15153 * the next hierarchy layout pass.</p> 15154 * 15155 * @return true if the layout will be forced during next layout pass 15156 */ 15157 public boolean isLayoutRequested() { 15158 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15159 } 15160 15161 /** 15162 * Return true if o is a ViewGroup that is laying out using optical bounds. 15163 * @hide 15164 */ 15165 public static boolean isLayoutModeOptical(Object o) { 15166 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15167 } 15168 15169 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15170 Insets parentInsets = mParent instanceof View ? 15171 ((View) mParent).getOpticalInsets() : Insets.NONE; 15172 Insets childInsets = getOpticalInsets(); 15173 return setFrame( 15174 left + parentInsets.left - childInsets.left, 15175 top + parentInsets.top - childInsets.top, 15176 right + parentInsets.left + childInsets.right, 15177 bottom + parentInsets.top + childInsets.bottom); 15178 } 15179 15180 /** 15181 * Assign a size and position to a view and all of its 15182 * descendants 15183 * 15184 * <p>This is the second phase of the layout mechanism. 15185 * (The first is measuring). In this phase, each parent calls 15186 * layout on all of its children to position them. 15187 * This is typically done using the child measurements 15188 * that were stored in the measure pass().</p> 15189 * 15190 * <p>Derived classes should not override this method. 15191 * Derived classes with children should override 15192 * onLayout. In that method, they should 15193 * call layout on each of their children.</p> 15194 * 15195 * @param l Left position, relative to parent 15196 * @param t Top position, relative to parent 15197 * @param r Right position, relative to parent 15198 * @param b Bottom position, relative to parent 15199 */ 15200 @SuppressWarnings({"unchecked"}) 15201 public void layout(int l, int t, int r, int b) { 15202 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15203 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15204 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15205 } 15206 15207 int oldL = mLeft; 15208 int oldT = mTop; 15209 int oldB = mBottom; 15210 int oldR = mRight; 15211 15212 boolean changed = isLayoutModeOptical(mParent) ? 15213 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15214 15215 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15216 onLayout(changed, l, t, r, b); 15217 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15218 15219 ListenerInfo li = mListenerInfo; 15220 if (li != null && li.mOnLayoutChangeListeners != null) { 15221 ArrayList<OnLayoutChangeListener> listenersCopy = 15222 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15223 int numListeners = listenersCopy.size(); 15224 for (int i = 0; i < numListeners; ++i) { 15225 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15226 } 15227 } 15228 } 15229 15230 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15231 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15232 } 15233 15234 /** 15235 * Called from layout when this view should 15236 * assign a size and position to each of its children. 15237 * 15238 * Derived classes with children should override 15239 * this method and call layout on each of 15240 * their children. 15241 * @param changed This is a new size or position for this view 15242 * @param left Left position, relative to parent 15243 * @param top Top position, relative to parent 15244 * @param right Right position, relative to parent 15245 * @param bottom Bottom position, relative to parent 15246 */ 15247 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15248 } 15249 15250 /** 15251 * Assign a size and position to this view. 15252 * 15253 * This is called from layout. 15254 * 15255 * @param left Left position, relative to parent 15256 * @param top Top position, relative to parent 15257 * @param right Right position, relative to parent 15258 * @param bottom Bottom position, relative to parent 15259 * @return true if the new size and position are different than the 15260 * previous ones 15261 * {@hide} 15262 */ 15263 protected boolean setFrame(int left, int top, int right, int bottom) { 15264 boolean changed = false; 15265 15266 if (DBG) { 15267 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15268 + right + "," + bottom + ")"); 15269 } 15270 15271 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15272 changed = true; 15273 15274 // Remember our drawn bit 15275 int drawn = mPrivateFlags & PFLAG_DRAWN; 15276 15277 int oldWidth = mRight - mLeft; 15278 int oldHeight = mBottom - mTop; 15279 int newWidth = right - left; 15280 int newHeight = bottom - top; 15281 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15282 15283 // Invalidate our old position 15284 invalidate(sizeChanged); 15285 15286 mLeft = left; 15287 mTop = top; 15288 mRight = right; 15289 mBottom = bottom; 15290 if (mDisplayList != null) { 15291 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15292 } 15293 15294 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15295 15296 15297 if (sizeChanged) { 15298 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 15299 // A change in dimension means an auto-centered pivot point changes, too 15300 if (mTransformationInfo != null) { 15301 mTransformationInfo.mMatrixDirty = true; 15302 } 15303 } 15304 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15305 } 15306 15307 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15308 // If we are visible, force the DRAWN bit to on so that 15309 // this invalidate will go through (at least to our parent). 15310 // This is because someone may have invalidated this view 15311 // before this call to setFrame came in, thereby clearing 15312 // the DRAWN bit. 15313 mPrivateFlags |= PFLAG_DRAWN; 15314 invalidate(sizeChanged); 15315 // parent display list may need to be recreated based on a change in the bounds 15316 // of any child 15317 invalidateParentCaches(); 15318 } 15319 15320 // Reset drawn bit to original value (invalidate turns it off) 15321 mPrivateFlags |= drawn; 15322 15323 mBackgroundSizeChanged = true; 15324 15325 notifySubtreeAccessibilityStateChangedIfNeeded(); 15326 } 15327 return changed; 15328 } 15329 15330 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15331 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15332 if (mOverlay != null) { 15333 mOverlay.getOverlayView().setRight(newWidth); 15334 mOverlay.getOverlayView().setBottom(newHeight); 15335 } 15336 } 15337 15338 /** 15339 * Finalize inflating a view from XML. This is called as the last phase 15340 * of inflation, after all child views have been added. 15341 * 15342 * <p>Even if the subclass overrides onFinishInflate, they should always be 15343 * sure to call the super method, so that we get called. 15344 */ 15345 protected void onFinishInflate() { 15346 } 15347 15348 /** 15349 * Returns the resources associated with this view. 15350 * 15351 * @return Resources object. 15352 */ 15353 public Resources getResources() { 15354 return mResources; 15355 } 15356 15357 /** 15358 * Invalidates the specified Drawable. 15359 * 15360 * @param drawable the drawable to invalidate 15361 */ 15362 @Override 15363 public void invalidateDrawable(Drawable drawable) { 15364 if (verifyDrawable(drawable)) { 15365 if (drawable == mBackground && mBackgroundDisplayList != null) { 15366 // We'll need to redraw the display list. 15367 mBackgroundDisplayList.clear(); 15368 } 15369 15370 final Rect dirty = drawable.getDirtyBounds(); 15371 final int scrollX = mScrollX; 15372 final int scrollY = mScrollY; 15373 15374 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15375 dirty.right + scrollX, dirty.bottom + scrollY); 15376 } 15377 } 15378 15379 /** 15380 * Schedules an action on a drawable to occur at a specified time. 15381 * 15382 * @param who the recipient of the action 15383 * @param what the action to run on the drawable 15384 * @param when the time at which the action must occur. Uses the 15385 * {@link SystemClock#uptimeMillis} timebase. 15386 */ 15387 @Override 15388 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15389 if (verifyDrawable(who) && what != null) { 15390 final long delay = when - SystemClock.uptimeMillis(); 15391 if (mAttachInfo != null) { 15392 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15393 Choreographer.CALLBACK_ANIMATION, what, who, 15394 Choreographer.subtractFrameDelay(delay)); 15395 } else { 15396 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15397 } 15398 } 15399 } 15400 15401 /** 15402 * Cancels a scheduled action on a drawable. 15403 * 15404 * @param who the recipient of the action 15405 * @param what the action to cancel 15406 */ 15407 @Override 15408 public void unscheduleDrawable(Drawable who, Runnable what) { 15409 if (verifyDrawable(who) && what != null) { 15410 if (mAttachInfo != null) { 15411 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15412 Choreographer.CALLBACK_ANIMATION, what, who); 15413 } 15414 ViewRootImpl.getRunQueue().removeCallbacks(what); 15415 } 15416 } 15417 15418 /** 15419 * Unschedule any events associated with the given Drawable. This can be 15420 * used when selecting a new Drawable into a view, so that the previous 15421 * one is completely unscheduled. 15422 * 15423 * @param who The Drawable to unschedule. 15424 * 15425 * @see #drawableStateChanged 15426 */ 15427 public void unscheduleDrawable(Drawable who) { 15428 if (mAttachInfo != null && who != null) { 15429 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15430 Choreographer.CALLBACK_ANIMATION, null, who); 15431 } 15432 } 15433 15434 /** 15435 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15436 * that the View directionality can and will be resolved before its Drawables. 15437 * 15438 * Will call {@link View#onResolveDrawables} when resolution is done. 15439 * 15440 * @hide 15441 */ 15442 protected void resolveDrawables() { 15443 // Drawables resolution may need to happen before resolving the layout direction (which is 15444 // done only during the measure() call). 15445 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15446 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15447 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15448 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15449 // direction to be resolved as its resolved value will be the same as its raw value. 15450 if (!isLayoutDirectionResolved() && 15451 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15452 return; 15453 } 15454 15455 final int layoutDirection = isLayoutDirectionResolved() ? 15456 getLayoutDirection() : getRawLayoutDirection(); 15457 15458 if (mBackground != null) { 15459 mBackground.setLayoutDirection(layoutDirection); 15460 } 15461 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15462 onResolveDrawables(layoutDirection); 15463 } 15464 15465 /** 15466 * Called when layout direction has been resolved. 15467 * 15468 * The default implementation does nothing. 15469 * 15470 * @param layoutDirection The resolved layout direction. 15471 * 15472 * @see #LAYOUT_DIRECTION_LTR 15473 * @see #LAYOUT_DIRECTION_RTL 15474 * 15475 * @hide 15476 */ 15477 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15478 } 15479 15480 /** 15481 * @hide 15482 */ 15483 protected void resetResolvedDrawables() { 15484 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15485 } 15486 15487 private boolean isDrawablesResolved() { 15488 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15489 } 15490 15491 /** 15492 * If your view subclass is displaying its own Drawable objects, it should 15493 * override this function and return true for any Drawable it is 15494 * displaying. This allows animations for those drawables to be 15495 * scheduled. 15496 * 15497 * <p>Be sure to call through to the super class when overriding this 15498 * function. 15499 * 15500 * @param who The Drawable to verify. Return true if it is one you are 15501 * displaying, else return the result of calling through to the 15502 * super class. 15503 * 15504 * @return boolean If true than the Drawable is being displayed in the 15505 * view; else false and it is not allowed to animate. 15506 * 15507 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15508 * @see #drawableStateChanged() 15509 */ 15510 protected boolean verifyDrawable(Drawable who) { 15511 return who == mBackground; 15512 } 15513 15514 /** 15515 * This function is called whenever the state of the view changes in such 15516 * a way that it impacts the state of drawables being shown. 15517 * 15518 * <p>Be sure to call through to the superclass when overriding this 15519 * function. 15520 * 15521 * @see Drawable#setState(int[]) 15522 */ 15523 protected void drawableStateChanged() { 15524 final Drawable d = mBackground; 15525 if (d != null && d.isStateful()) { 15526 d.setState(getDrawableState()); 15527 } 15528 } 15529 15530 /** 15531 * Call this to force a view to update its drawable state. This will cause 15532 * drawableStateChanged to be called on this view. Views that are interested 15533 * in the new state should call getDrawableState. 15534 * 15535 * @see #drawableStateChanged 15536 * @see #getDrawableState 15537 */ 15538 public void refreshDrawableState() { 15539 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15540 drawableStateChanged(); 15541 15542 ViewParent parent = mParent; 15543 if (parent != null) { 15544 parent.childDrawableStateChanged(this); 15545 } 15546 } 15547 15548 /** 15549 * Return an array of resource IDs of the drawable states representing the 15550 * current state of the view. 15551 * 15552 * @return The current drawable state 15553 * 15554 * @see Drawable#setState(int[]) 15555 * @see #drawableStateChanged() 15556 * @see #onCreateDrawableState(int) 15557 */ 15558 public final int[] getDrawableState() { 15559 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15560 return mDrawableState; 15561 } else { 15562 mDrawableState = onCreateDrawableState(0); 15563 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15564 return mDrawableState; 15565 } 15566 } 15567 15568 /** 15569 * Generate the new {@link android.graphics.drawable.Drawable} state for 15570 * this view. This is called by the view 15571 * system when the cached Drawable state is determined to be invalid. To 15572 * retrieve the current state, you should use {@link #getDrawableState}. 15573 * 15574 * @param extraSpace if non-zero, this is the number of extra entries you 15575 * would like in the returned array in which you can place your own 15576 * states. 15577 * 15578 * @return Returns an array holding the current {@link Drawable} state of 15579 * the view. 15580 * 15581 * @see #mergeDrawableStates(int[], int[]) 15582 */ 15583 protected int[] onCreateDrawableState(int extraSpace) { 15584 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15585 mParent instanceof View) { 15586 return ((View) mParent).onCreateDrawableState(extraSpace); 15587 } 15588 15589 int[] drawableState; 15590 15591 int privateFlags = mPrivateFlags; 15592 15593 int viewStateIndex = 0; 15594 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15595 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15596 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15597 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15598 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15599 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15600 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15601 HardwareRenderer.isAvailable()) { 15602 // This is set if HW acceleration is requested, even if the current 15603 // process doesn't allow it. This is just to allow app preview 15604 // windows to better match their app. 15605 viewStateIndex |= VIEW_STATE_ACCELERATED; 15606 } 15607 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15608 15609 final int privateFlags2 = mPrivateFlags2; 15610 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15611 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15612 15613 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15614 15615 //noinspection ConstantIfStatement 15616 if (false) { 15617 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15618 Log.i("View", toString() 15619 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15620 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15621 + " fo=" + hasFocus() 15622 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15623 + " wf=" + hasWindowFocus() 15624 + ": " + Arrays.toString(drawableState)); 15625 } 15626 15627 if (extraSpace == 0) { 15628 return drawableState; 15629 } 15630 15631 final int[] fullState; 15632 if (drawableState != null) { 15633 fullState = new int[drawableState.length + extraSpace]; 15634 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15635 } else { 15636 fullState = new int[extraSpace]; 15637 } 15638 15639 return fullState; 15640 } 15641 15642 /** 15643 * Merge your own state values in <var>additionalState</var> into the base 15644 * state values <var>baseState</var> that were returned by 15645 * {@link #onCreateDrawableState(int)}. 15646 * 15647 * @param baseState The base state values returned by 15648 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15649 * own additional state values. 15650 * 15651 * @param additionalState The additional state values you would like 15652 * added to <var>baseState</var>; this array is not modified. 15653 * 15654 * @return As a convenience, the <var>baseState</var> array you originally 15655 * passed into the function is returned. 15656 * 15657 * @see #onCreateDrawableState(int) 15658 */ 15659 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15660 final int N = baseState.length; 15661 int i = N - 1; 15662 while (i >= 0 && baseState[i] == 0) { 15663 i--; 15664 } 15665 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15666 return baseState; 15667 } 15668 15669 /** 15670 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15671 * on all Drawable objects associated with this view. 15672 */ 15673 public void jumpDrawablesToCurrentState() { 15674 if (mBackground != null) { 15675 mBackground.jumpToCurrentState(); 15676 } 15677 } 15678 15679 /** 15680 * Sets the background color for this view. 15681 * @param color the color of the background 15682 */ 15683 @RemotableViewMethod 15684 public void setBackgroundColor(int color) { 15685 if (mBackground instanceof ColorDrawable) { 15686 ((ColorDrawable) mBackground.mutate()).setColor(color); 15687 computeOpaqueFlags(); 15688 mBackgroundResource = 0; 15689 } else { 15690 setBackground(new ColorDrawable(color)); 15691 } 15692 } 15693 15694 /** 15695 * Set the background to a given resource. The resource should refer to 15696 * a Drawable object or 0 to remove the background. 15697 * @param resid The identifier of the resource. 15698 * 15699 * @attr ref android.R.styleable#View_background 15700 */ 15701 @RemotableViewMethod 15702 public void setBackgroundResource(int resid) { 15703 if (resid != 0 && resid == mBackgroundResource) { 15704 return; 15705 } 15706 15707 Drawable d= null; 15708 if (resid != 0) { 15709 d = mContext.getDrawable(resid); 15710 } 15711 setBackground(d); 15712 15713 mBackgroundResource = resid; 15714 } 15715 15716 /** 15717 * Set the background to a given Drawable, or remove the background. If the 15718 * background has padding, this View's padding is set to the background's 15719 * padding. However, when a background is removed, this View's padding isn't 15720 * touched. If setting the padding is desired, please use 15721 * {@link #setPadding(int, int, int, int)}. 15722 * 15723 * @param background The Drawable to use as the background, or null to remove the 15724 * background 15725 */ 15726 public void setBackground(Drawable background) { 15727 //noinspection deprecation 15728 setBackgroundDrawable(background); 15729 } 15730 15731 /** 15732 * @deprecated use {@link #setBackground(Drawable)} instead 15733 */ 15734 @Deprecated 15735 public void setBackgroundDrawable(Drawable background) { 15736 computeOpaqueFlags(); 15737 15738 if (background == mBackground) { 15739 return; 15740 } 15741 15742 boolean requestLayout = false; 15743 15744 mBackgroundResource = 0; 15745 15746 /* 15747 * Regardless of whether we're setting a new background or not, we want 15748 * to clear the previous drawable. 15749 */ 15750 if (mBackground != null) { 15751 mBackground.setCallback(null); 15752 unscheduleDrawable(mBackground); 15753 } 15754 15755 if (background != null) { 15756 Rect padding = sThreadLocal.get(); 15757 if (padding == null) { 15758 padding = new Rect(); 15759 sThreadLocal.set(padding); 15760 } 15761 resetResolvedDrawables(); 15762 background.setLayoutDirection(getLayoutDirection()); 15763 if (background.getPadding(padding)) { 15764 resetResolvedPadding(); 15765 switch (background.getLayoutDirection()) { 15766 case LAYOUT_DIRECTION_RTL: 15767 mUserPaddingLeftInitial = padding.right; 15768 mUserPaddingRightInitial = padding.left; 15769 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15770 break; 15771 case LAYOUT_DIRECTION_LTR: 15772 default: 15773 mUserPaddingLeftInitial = padding.left; 15774 mUserPaddingRightInitial = padding.right; 15775 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15776 } 15777 mLeftPaddingDefined = false; 15778 mRightPaddingDefined = false; 15779 } 15780 15781 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15782 // if it has a different minimum size, we should layout again 15783 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 15784 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15785 requestLayout = true; 15786 } 15787 15788 background.setCallback(this); 15789 if (background.isStateful()) { 15790 background.setState(getDrawableState()); 15791 } 15792 background.setVisible(getVisibility() == VISIBLE, false); 15793 mBackground = background; 15794 15795 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15796 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15797 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15798 requestLayout = true; 15799 } 15800 } else { 15801 /* Remove the background */ 15802 mBackground = null; 15803 15804 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15805 /* 15806 * This view ONLY drew the background before and we're removing 15807 * the background, so now it won't draw anything 15808 * (hence we SKIP_DRAW) 15809 */ 15810 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15811 mPrivateFlags |= PFLAG_SKIP_DRAW; 15812 } 15813 15814 /* 15815 * When the background is set, we try to apply its padding to this 15816 * View. When the background is removed, we don't touch this View's 15817 * padding. This is noted in the Javadocs. Hence, we don't need to 15818 * requestLayout(), the invalidate() below is sufficient. 15819 */ 15820 15821 // The old background's minimum size could have affected this 15822 // View's layout, so let's requestLayout 15823 requestLayout = true; 15824 } 15825 15826 computeOpaqueFlags(); 15827 15828 if (requestLayout) { 15829 requestLayout(); 15830 } 15831 15832 mBackgroundSizeChanged = true; 15833 invalidate(true); 15834 } 15835 15836 /** 15837 * Gets the background drawable 15838 * 15839 * @return The drawable used as the background for this view, if any. 15840 * 15841 * @see #setBackground(Drawable) 15842 * 15843 * @attr ref android.R.styleable#View_background 15844 */ 15845 public Drawable getBackground() { 15846 return mBackground; 15847 } 15848 15849 /** 15850 * Sets the padding. The view may add on the space required to display 15851 * the scrollbars, depending on the style and visibility of the scrollbars. 15852 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15853 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15854 * from the values set in this call. 15855 * 15856 * @attr ref android.R.styleable#View_padding 15857 * @attr ref android.R.styleable#View_paddingBottom 15858 * @attr ref android.R.styleable#View_paddingLeft 15859 * @attr ref android.R.styleable#View_paddingRight 15860 * @attr ref android.R.styleable#View_paddingTop 15861 * @param left the left padding in pixels 15862 * @param top the top padding in pixels 15863 * @param right the right padding in pixels 15864 * @param bottom the bottom padding in pixels 15865 */ 15866 public void setPadding(int left, int top, int right, int bottom) { 15867 resetResolvedPadding(); 15868 15869 mUserPaddingStart = UNDEFINED_PADDING; 15870 mUserPaddingEnd = UNDEFINED_PADDING; 15871 15872 mUserPaddingLeftInitial = left; 15873 mUserPaddingRightInitial = right; 15874 15875 mLeftPaddingDefined = true; 15876 mRightPaddingDefined = true; 15877 15878 internalSetPadding(left, top, right, bottom); 15879 } 15880 15881 /** 15882 * @hide 15883 */ 15884 protected void internalSetPadding(int left, int top, int right, int bottom) { 15885 mUserPaddingLeft = left; 15886 mUserPaddingRight = right; 15887 mUserPaddingBottom = bottom; 15888 15889 final int viewFlags = mViewFlags; 15890 boolean changed = false; 15891 15892 // Common case is there are no scroll bars. 15893 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15894 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15895 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15896 ? 0 : getVerticalScrollbarWidth(); 15897 switch (mVerticalScrollbarPosition) { 15898 case SCROLLBAR_POSITION_DEFAULT: 15899 if (isLayoutRtl()) { 15900 left += offset; 15901 } else { 15902 right += offset; 15903 } 15904 break; 15905 case SCROLLBAR_POSITION_RIGHT: 15906 right += offset; 15907 break; 15908 case SCROLLBAR_POSITION_LEFT: 15909 left += offset; 15910 break; 15911 } 15912 } 15913 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 15914 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 15915 ? 0 : getHorizontalScrollbarHeight(); 15916 } 15917 } 15918 15919 if (mPaddingLeft != left) { 15920 changed = true; 15921 mPaddingLeft = left; 15922 } 15923 if (mPaddingTop != top) { 15924 changed = true; 15925 mPaddingTop = top; 15926 } 15927 if (mPaddingRight != right) { 15928 changed = true; 15929 mPaddingRight = right; 15930 } 15931 if (mPaddingBottom != bottom) { 15932 changed = true; 15933 mPaddingBottom = bottom; 15934 } 15935 15936 if (changed) { 15937 requestLayout(); 15938 } 15939 } 15940 15941 /** 15942 * Sets the relative padding. The view may add on the space required to display 15943 * the scrollbars, depending on the style and visibility of the scrollbars. 15944 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 15945 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 15946 * from the values set in this call. 15947 * 15948 * @attr ref android.R.styleable#View_padding 15949 * @attr ref android.R.styleable#View_paddingBottom 15950 * @attr ref android.R.styleable#View_paddingStart 15951 * @attr ref android.R.styleable#View_paddingEnd 15952 * @attr ref android.R.styleable#View_paddingTop 15953 * @param start the start padding in pixels 15954 * @param top the top padding in pixels 15955 * @param end the end padding in pixels 15956 * @param bottom the bottom padding in pixels 15957 */ 15958 public void setPaddingRelative(int start, int top, int end, int bottom) { 15959 resetResolvedPadding(); 15960 15961 mUserPaddingStart = start; 15962 mUserPaddingEnd = end; 15963 mLeftPaddingDefined = true; 15964 mRightPaddingDefined = true; 15965 15966 switch(getLayoutDirection()) { 15967 case LAYOUT_DIRECTION_RTL: 15968 mUserPaddingLeftInitial = end; 15969 mUserPaddingRightInitial = start; 15970 internalSetPadding(end, top, start, bottom); 15971 break; 15972 case LAYOUT_DIRECTION_LTR: 15973 default: 15974 mUserPaddingLeftInitial = start; 15975 mUserPaddingRightInitial = end; 15976 internalSetPadding(start, top, end, bottom); 15977 } 15978 } 15979 15980 /** 15981 * Returns the top padding of this view. 15982 * 15983 * @return the top padding in pixels 15984 */ 15985 public int getPaddingTop() { 15986 return mPaddingTop; 15987 } 15988 15989 /** 15990 * Returns the bottom padding of this view. If there are inset and enabled 15991 * scrollbars, this value may include the space required to display the 15992 * scrollbars as well. 15993 * 15994 * @return the bottom padding in pixels 15995 */ 15996 public int getPaddingBottom() { 15997 return mPaddingBottom; 15998 } 15999 16000 /** 16001 * Returns the left padding of this view. If there are inset and enabled 16002 * scrollbars, this value may include the space required to display the 16003 * scrollbars as well. 16004 * 16005 * @return the left padding in pixels 16006 */ 16007 public int getPaddingLeft() { 16008 if (!isPaddingResolved()) { 16009 resolvePadding(); 16010 } 16011 return mPaddingLeft; 16012 } 16013 16014 /** 16015 * Returns the start padding of this view depending on its resolved layout direction. 16016 * If there are inset and enabled scrollbars, this value may include the space 16017 * required to display the scrollbars as well. 16018 * 16019 * @return the start padding in pixels 16020 */ 16021 public int getPaddingStart() { 16022 if (!isPaddingResolved()) { 16023 resolvePadding(); 16024 } 16025 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16026 mPaddingRight : mPaddingLeft; 16027 } 16028 16029 /** 16030 * Returns the right padding of this view. If there are inset and enabled 16031 * scrollbars, this value may include the space required to display the 16032 * scrollbars as well. 16033 * 16034 * @return the right padding in pixels 16035 */ 16036 public int getPaddingRight() { 16037 if (!isPaddingResolved()) { 16038 resolvePadding(); 16039 } 16040 return mPaddingRight; 16041 } 16042 16043 /** 16044 * Returns the end padding of this view depending on its resolved layout direction. 16045 * If there are inset and enabled scrollbars, this value may include the space 16046 * required to display the scrollbars as well. 16047 * 16048 * @return the end padding in pixels 16049 */ 16050 public int getPaddingEnd() { 16051 if (!isPaddingResolved()) { 16052 resolvePadding(); 16053 } 16054 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16055 mPaddingLeft : mPaddingRight; 16056 } 16057 16058 /** 16059 * Return if the padding as been set thru relative values 16060 * {@link #setPaddingRelative(int, int, int, int)} or thru 16061 * @attr ref android.R.styleable#View_paddingStart or 16062 * @attr ref android.R.styleable#View_paddingEnd 16063 * 16064 * @return true if the padding is relative or false if it is not. 16065 */ 16066 public boolean isPaddingRelative() { 16067 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16068 } 16069 16070 Insets computeOpticalInsets() { 16071 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16072 } 16073 16074 /** 16075 * @hide 16076 */ 16077 public void resetPaddingToInitialValues() { 16078 if (isRtlCompatibilityMode()) { 16079 mPaddingLeft = mUserPaddingLeftInitial; 16080 mPaddingRight = mUserPaddingRightInitial; 16081 return; 16082 } 16083 if (isLayoutRtl()) { 16084 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16085 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16086 } else { 16087 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16088 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16089 } 16090 } 16091 16092 /** 16093 * @hide 16094 */ 16095 public Insets getOpticalInsets() { 16096 if (mLayoutInsets == null) { 16097 mLayoutInsets = computeOpticalInsets(); 16098 } 16099 return mLayoutInsets; 16100 } 16101 16102 /** 16103 * Changes the selection state of this view. A view can be selected or not. 16104 * Note that selection is not the same as focus. Views are typically 16105 * selected in the context of an AdapterView like ListView or GridView; 16106 * the selected view is the view that is highlighted. 16107 * 16108 * @param selected true if the view must be selected, false otherwise 16109 */ 16110 public void setSelected(boolean selected) { 16111 //noinspection DoubleNegation 16112 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16113 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16114 if (!selected) resetPressedState(); 16115 invalidate(true); 16116 refreshDrawableState(); 16117 dispatchSetSelected(selected); 16118 notifyViewAccessibilityStateChangedIfNeeded( 16119 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16120 } 16121 } 16122 16123 /** 16124 * Dispatch setSelected to all of this View's children. 16125 * 16126 * @see #setSelected(boolean) 16127 * 16128 * @param selected The new selected state 16129 */ 16130 protected void dispatchSetSelected(boolean selected) { 16131 } 16132 16133 /** 16134 * Indicates the selection state of this view. 16135 * 16136 * @return true if the view is selected, false otherwise 16137 */ 16138 @ViewDebug.ExportedProperty 16139 public boolean isSelected() { 16140 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16141 } 16142 16143 /** 16144 * Changes the activated state of this view. A view can be activated or not. 16145 * Note that activation is not the same as selection. Selection is 16146 * a transient property, representing the view (hierarchy) the user is 16147 * currently interacting with. Activation is a longer-term state that the 16148 * user can move views in and out of. For example, in a list view with 16149 * single or multiple selection enabled, the views in the current selection 16150 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16151 * here.) The activated state is propagated down to children of the view it 16152 * is set on. 16153 * 16154 * @param activated true if the view must be activated, false otherwise 16155 */ 16156 public void setActivated(boolean activated) { 16157 //noinspection DoubleNegation 16158 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16159 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16160 invalidate(true); 16161 refreshDrawableState(); 16162 dispatchSetActivated(activated); 16163 } 16164 } 16165 16166 /** 16167 * Dispatch setActivated to all of this View's children. 16168 * 16169 * @see #setActivated(boolean) 16170 * 16171 * @param activated The new activated state 16172 */ 16173 protected void dispatchSetActivated(boolean activated) { 16174 } 16175 16176 /** 16177 * Indicates the activation state of this view. 16178 * 16179 * @return true if the view is activated, false otherwise 16180 */ 16181 @ViewDebug.ExportedProperty 16182 public boolean isActivated() { 16183 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16184 } 16185 16186 /** 16187 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16188 * observer can be used to get notifications when global events, like 16189 * layout, happen. 16190 * 16191 * The returned ViewTreeObserver observer is not guaranteed to remain 16192 * valid for the lifetime of this View. If the caller of this method keeps 16193 * a long-lived reference to ViewTreeObserver, it should always check for 16194 * the return value of {@link ViewTreeObserver#isAlive()}. 16195 * 16196 * @return The ViewTreeObserver for this view's hierarchy. 16197 */ 16198 public ViewTreeObserver getViewTreeObserver() { 16199 if (mAttachInfo != null) { 16200 return mAttachInfo.mTreeObserver; 16201 } 16202 if (mFloatingTreeObserver == null) { 16203 mFloatingTreeObserver = new ViewTreeObserver(); 16204 } 16205 return mFloatingTreeObserver; 16206 } 16207 16208 /** 16209 * <p>Finds the topmost view in the current view hierarchy.</p> 16210 * 16211 * @return the topmost view containing this view 16212 */ 16213 public View getRootView() { 16214 if (mAttachInfo != null) { 16215 final View v = mAttachInfo.mRootView; 16216 if (v != null) { 16217 return v; 16218 } 16219 } 16220 16221 View parent = this; 16222 16223 while (parent.mParent != null && parent.mParent instanceof View) { 16224 parent = (View) parent.mParent; 16225 } 16226 16227 return parent; 16228 } 16229 16230 /** 16231 * Transforms a motion event from view-local coordinates to on-screen 16232 * coordinates. 16233 * 16234 * @param ev the view-local motion event 16235 * @return false if the transformation could not be applied 16236 * @hide 16237 */ 16238 public boolean toGlobalMotionEvent(MotionEvent ev) { 16239 final AttachInfo info = mAttachInfo; 16240 if (info == null) { 16241 return false; 16242 } 16243 16244 final Matrix m = info.mTmpMatrix; 16245 m.set(Matrix.IDENTITY_MATRIX); 16246 transformMatrixToGlobal(m); 16247 ev.transform(m); 16248 return true; 16249 } 16250 16251 /** 16252 * Transforms a motion event from on-screen coordinates to view-local 16253 * coordinates. 16254 * 16255 * @param ev the on-screen motion event 16256 * @return false if the transformation could not be applied 16257 * @hide 16258 */ 16259 public boolean toLocalMotionEvent(MotionEvent ev) { 16260 final AttachInfo info = mAttachInfo; 16261 if (info == null) { 16262 return false; 16263 } 16264 16265 final Matrix m = info.mTmpMatrix; 16266 m.set(Matrix.IDENTITY_MATRIX); 16267 transformMatrixToLocal(m); 16268 ev.transform(m); 16269 return true; 16270 } 16271 16272 /** 16273 * Modifies the input matrix such that it maps view-local coordinates to 16274 * on-screen coordinates. 16275 * 16276 * @param m input matrix to modify 16277 */ 16278 void transformMatrixToGlobal(Matrix m) { 16279 final ViewParent parent = mParent; 16280 if (parent instanceof View) { 16281 final View vp = (View) parent; 16282 vp.transformMatrixToGlobal(m); 16283 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16284 } else if (parent instanceof ViewRootImpl) { 16285 final ViewRootImpl vr = (ViewRootImpl) parent; 16286 vr.transformMatrixToGlobal(m); 16287 m.postTranslate(0, -vr.mCurScrollY); 16288 } 16289 16290 m.postTranslate(mLeft, mTop); 16291 16292 if (!hasIdentityMatrix()) { 16293 m.postConcat(getMatrix()); 16294 } 16295 } 16296 16297 /** 16298 * Modifies the input matrix such that it maps on-screen coordinates to 16299 * view-local coordinates. 16300 * 16301 * @param m input matrix to modify 16302 */ 16303 void transformMatrixToLocal(Matrix m) { 16304 final ViewParent parent = mParent; 16305 if (parent instanceof View) { 16306 final View vp = (View) parent; 16307 vp.transformMatrixToLocal(m); 16308 m.preTranslate(vp.mScrollX, vp.mScrollY); 16309 } else if (parent instanceof ViewRootImpl) { 16310 final ViewRootImpl vr = (ViewRootImpl) parent; 16311 vr.transformMatrixToLocal(m); 16312 m.preTranslate(0, vr.mCurScrollY); 16313 } 16314 16315 m.preTranslate(-mLeft, -mTop); 16316 16317 if (!hasIdentityMatrix()) { 16318 m.preConcat(getInverseMatrix()); 16319 } 16320 } 16321 16322 /** 16323 * <p>Computes the coordinates of this view on the screen. The argument 16324 * must be an array of two integers. After the method returns, the array 16325 * contains the x and y location in that order.</p> 16326 * 16327 * @param location an array of two integers in which to hold the coordinates 16328 */ 16329 public void getLocationOnScreen(int[] location) { 16330 getLocationInWindow(location); 16331 16332 final AttachInfo info = mAttachInfo; 16333 if (info != null) { 16334 location[0] += info.mWindowLeft; 16335 location[1] += info.mWindowTop; 16336 } 16337 } 16338 16339 /** 16340 * <p>Computes the coordinates of this view in its window. The argument 16341 * must be an array of two integers. After the method returns, the array 16342 * contains the x and y location in that order.</p> 16343 * 16344 * @param location an array of two integers in which to hold the coordinates 16345 */ 16346 public void getLocationInWindow(int[] location) { 16347 if (location == null || location.length < 2) { 16348 throw new IllegalArgumentException("location must be an array of two integers"); 16349 } 16350 16351 if (mAttachInfo == null) { 16352 // When the view is not attached to a window, this method does not make sense 16353 location[0] = location[1] = 0; 16354 return; 16355 } 16356 16357 float[] position = mAttachInfo.mTmpTransformLocation; 16358 position[0] = position[1] = 0.0f; 16359 16360 if (!hasIdentityMatrix()) { 16361 getMatrix().mapPoints(position); 16362 } 16363 16364 position[0] += mLeft; 16365 position[1] += mTop; 16366 16367 ViewParent viewParent = mParent; 16368 while (viewParent instanceof View) { 16369 final View view = (View) viewParent; 16370 16371 position[0] -= view.mScrollX; 16372 position[1] -= view.mScrollY; 16373 16374 if (!view.hasIdentityMatrix()) { 16375 view.getMatrix().mapPoints(position); 16376 } 16377 16378 position[0] += view.mLeft; 16379 position[1] += view.mTop; 16380 16381 viewParent = view.mParent; 16382 } 16383 16384 if (viewParent instanceof ViewRootImpl) { 16385 // *cough* 16386 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16387 position[1] -= vr.mCurScrollY; 16388 } 16389 16390 location[0] = (int) (position[0] + 0.5f); 16391 location[1] = (int) (position[1] + 0.5f); 16392 } 16393 16394 /** 16395 * {@hide} 16396 * @param id the id of the view to be found 16397 * @return the view of the specified id, null if cannot be found 16398 */ 16399 protected View findViewTraversal(int id) { 16400 if (id == mID) { 16401 return this; 16402 } 16403 return null; 16404 } 16405 16406 /** 16407 * {@hide} 16408 * @param tag the tag of the view to be found 16409 * @return the view of specified tag, null if cannot be found 16410 */ 16411 protected View findViewWithTagTraversal(Object tag) { 16412 if (tag != null && tag.equals(mTag)) { 16413 return this; 16414 } 16415 return null; 16416 } 16417 16418 /** 16419 * {@hide} 16420 * @param predicate The predicate to evaluate. 16421 * @param childToSkip If not null, ignores this child during the recursive traversal. 16422 * @return The first view that matches the predicate or null. 16423 */ 16424 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16425 if (predicate.apply(this)) { 16426 return this; 16427 } 16428 return null; 16429 } 16430 16431 /** 16432 * Look for a child view with the given id. If this view has the given 16433 * id, return this view. 16434 * 16435 * @param id The id to search for. 16436 * @return The view that has the given id in the hierarchy or null 16437 */ 16438 public final View findViewById(int id) { 16439 if (id < 0) { 16440 return null; 16441 } 16442 return findViewTraversal(id); 16443 } 16444 16445 /** 16446 * Finds a view by its unuque and stable accessibility id. 16447 * 16448 * @param accessibilityId The searched accessibility id. 16449 * @return The found view. 16450 */ 16451 final View findViewByAccessibilityId(int accessibilityId) { 16452 if (accessibilityId < 0) { 16453 return null; 16454 } 16455 return findViewByAccessibilityIdTraversal(accessibilityId); 16456 } 16457 16458 /** 16459 * Performs the traversal to find a view by its unuque and stable accessibility id. 16460 * 16461 * <strong>Note:</strong>This method does not stop at the root namespace 16462 * boundary since the user can touch the screen at an arbitrary location 16463 * potentially crossing the root namespace bounday which will send an 16464 * accessibility event to accessibility services and they should be able 16465 * to obtain the event source. Also accessibility ids are guaranteed to be 16466 * unique in the window. 16467 * 16468 * @param accessibilityId The accessibility id. 16469 * @return The found view. 16470 * 16471 * @hide 16472 */ 16473 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16474 if (getAccessibilityViewId() == accessibilityId) { 16475 return this; 16476 } 16477 return null; 16478 } 16479 16480 /** 16481 * Look for a child view with the given tag. If this view has the given 16482 * tag, return this view. 16483 * 16484 * @param tag The tag to search for, using "tag.equals(getTag())". 16485 * @return The View that has the given tag in the hierarchy or null 16486 */ 16487 public final View findViewWithTag(Object tag) { 16488 if (tag == null) { 16489 return null; 16490 } 16491 return findViewWithTagTraversal(tag); 16492 } 16493 16494 /** 16495 * {@hide} 16496 * Look for a child view that matches the specified predicate. 16497 * If this view matches the predicate, return this view. 16498 * 16499 * @param predicate The predicate to evaluate. 16500 * @return The first view that matches the predicate or null. 16501 */ 16502 public final View findViewByPredicate(Predicate<View> predicate) { 16503 return findViewByPredicateTraversal(predicate, null); 16504 } 16505 16506 /** 16507 * {@hide} 16508 * Look for a child view that matches the specified predicate, 16509 * starting with the specified view and its descendents and then 16510 * recusively searching the ancestors and siblings of that view 16511 * until this view is reached. 16512 * 16513 * This method is useful in cases where the predicate does not match 16514 * a single unique view (perhaps multiple views use the same id) 16515 * and we are trying to find the view that is "closest" in scope to the 16516 * starting view. 16517 * 16518 * @param start The view to start from. 16519 * @param predicate The predicate to evaluate. 16520 * @return The first view that matches the predicate or null. 16521 */ 16522 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16523 View childToSkip = null; 16524 for (;;) { 16525 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16526 if (view != null || start == this) { 16527 return view; 16528 } 16529 16530 ViewParent parent = start.getParent(); 16531 if (parent == null || !(parent instanceof View)) { 16532 return null; 16533 } 16534 16535 childToSkip = start; 16536 start = (View) parent; 16537 } 16538 } 16539 16540 /** 16541 * Sets the identifier for this view. The identifier does not have to be 16542 * unique in this view's hierarchy. The identifier should be a positive 16543 * number. 16544 * 16545 * @see #NO_ID 16546 * @see #getId() 16547 * @see #findViewById(int) 16548 * 16549 * @param id a number used to identify the view 16550 * 16551 * @attr ref android.R.styleable#View_id 16552 */ 16553 public void setId(int id) { 16554 mID = id; 16555 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16556 mID = generateViewId(); 16557 } 16558 } 16559 16560 /** 16561 * {@hide} 16562 * 16563 * @param isRoot true if the view belongs to the root namespace, false 16564 * otherwise 16565 */ 16566 public void setIsRootNamespace(boolean isRoot) { 16567 if (isRoot) { 16568 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16569 } else { 16570 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16571 } 16572 } 16573 16574 /** 16575 * {@hide} 16576 * 16577 * @return true if the view belongs to the root namespace, false otherwise 16578 */ 16579 public boolean isRootNamespace() { 16580 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16581 } 16582 16583 /** 16584 * Returns this view's identifier. 16585 * 16586 * @return a positive integer used to identify the view or {@link #NO_ID} 16587 * if the view has no ID 16588 * 16589 * @see #setId(int) 16590 * @see #findViewById(int) 16591 * @attr ref android.R.styleable#View_id 16592 */ 16593 @ViewDebug.CapturedViewProperty 16594 public int getId() { 16595 return mID; 16596 } 16597 16598 /** 16599 * Returns this view's tag. 16600 * 16601 * @return the Object stored in this view as a tag, or {@code null} if not 16602 * set 16603 * 16604 * @see #setTag(Object) 16605 * @see #getTag(int) 16606 */ 16607 @ViewDebug.ExportedProperty 16608 public Object getTag() { 16609 return mTag; 16610 } 16611 16612 /** 16613 * Sets the tag associated with this view. A tag can be used to mark 16614 * a view in its hierarchy and does not have to be unique within the 16615 * hierarchy. Tags can also be used to store data within a view without 16616 * resorting to another data structure. 16617 * 16618 * @param tag an Object to tag the view with 16619 * 16620 * @see #getTag() 16621 * @see #setTag(int, Object) 16622 */ 16623 public void setTag(final Object tag) { 16624 mTag = tag; 16625 } 16626 16627 /** 16628 * Returns the tag associated with this view and the specified key. 16629 * 16630 * @param key The key identifying the tag 16631 * 16632 * @return the Object stored in this view as a tag, or {@code null} if not 16633 * set 16634 * 16635 * @see #setTag(int, Object) 16636 * @see #getTag() 16637 */ 16638 public Object getTag(int key) { 16639 if (mKeyedTags != null) return mKeyedTags.get(key); 16640 return null; 16641 } 16642 16643 /** 16644 * Sets a tag associated with this view and a key. A tag can be used 16645 * to mark a view in its hierarchy and does not have to be unique within 16646 * the hierarchy. Tags can also be used to store data within a view 16647 * without resorting to another data structure. 16648 * 16649 * The specified key should be an id declared in the resources of the 16650 * application to ensure it is unique (see the <a 16651 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16652 * Keys identified as belonging to 16653 * the Android framework or not associated with any package will cause 16654 * an {@link IllegalArgumentException} to be thrown. 16655 * 16656 * @param key The key identifying the tag 16657 * @param tag An Object to tag the view with 16658 * 16659 * @throws IllegalArgumentException If they specified key is not valid 16660 * 16661 * @see #setTag(Object) 16662 * @see #getTag(int) 16663 */ 16664 public void setTag(int key, final Object tag) { 16665 // If the package id is 0x00 or 0x01, it's either an undefined package 16666 // or a framework id 16667 if ((key >>> 24) < 2) { 16668 throw new IllegalArgumentException("The key must be an application-specific " 16669 + "resource id."); 16670 } 16671 16672 setKeyedTag(key, tag); 16673 } 16674 16675 /** 16676 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16677 * framework id. 16678 * 16679 * @hide 16680 */ 16681 public void setTagInternal(int key, Object tag) { 16682 if ((key >>> 24) != 0x1) { 16683 throw new IllegalArgumentException("The key must be a framework-specific " 16684 + "resource id."); 16685 } 16686 16687 setKeyedTag(key, tag); 16688 } 16689 16690 private void setKeyedTag(int key, Object tag) { 16691 if (mKeyedTags == null) { 16692 mKeyedTags = new SparseArray<Object>(2); 16693 } 16694 16695 mKeyedTags.put(key, tag); 16696 } 16697 16698 /** 16699 * Prints information about this view in the log output, with the tag 16700 * {@link #VIEW_LOG_TAG}. 16701 * 16702 * @hide 16703 */ 16704 public void debug() { 16705 debug(0); 16706 } 16707 16708 /** 16709 * Prints information about this view in the log output, with the tag 16710 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16711 * indentation defined by the <code>depth</code>. 16712 * 16713 * @param depth the indentation level 16714 * 16715 * @hide 16716 */ 16717 protected void debug(int depth) { 16718 String output = debugIndent(depth - 1); 16719 16720 output += "+ " + this; 16721 int id = getId(); 16722 if (id != -1) { 16723 output += " (id=" + id + ")"; 16724 } 16725 Object tag = getTag(); 16726 if (tag != null) { 16727 output += " (tag=" + tag + ")"; 16728 } 16729 Log.d(VIEW_LOG_TAG, output); 16730 16731 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16732 output = debugIndent(depth) + " FOCUSED"; 16733 Log.d(VIEW_LOG_TAG, output); 16734 } 16735 16736 output = debugIndent(depth); 16737 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16738 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16739 + "} "; 16740 Log.d(VIEW_LOG_TAG, output); 16741 16742 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16743 || mPaddingBottom != 0) { 16744 output = debugIndent(depth); 16745 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16746 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16747 Log.d(VIEW_LOG_TAG, output); 16748 } 16749 16750 output = debugIndent(depth); 16751 output += "mMeasureWidth=" + mMeasuredWidth + 16752 " mMeasureHeight=" + mMeasuredHeight; 16753 Log.d(VIEW_LOG_TAG, output); 16754 16755 output = debugIndent(depth); 16756 if (mLayoutParams == null) { 16757 output += "BAD! no layout params"; 16758 } else { 16759 output = mLayoutParams.debug(output); 16760 } 16761 Log.d(VIEW_LOG_TAG, output); 16762 16763 output = debugIndent(depth); 16764 output += "flags={"; 16765 output += View.printFlags(mViewFlags); 16766 output += "}"; 16767 Log.d(VIEW_LOG_TAG, output); 16768 16769 output = debugIndent(depth); 16770 output += "privateFlags={"; 16771 output += View.printPrivateFlags(mPrivateFlags); 16772 output += "}"; 16773 Log.d(VIEW_LOG_TAG, output); 16774 } 16775 16776 /** 16777 * Creates a string of whitespaces used for indentation. 16778 * 16779 * @param depth the indentation level 16780 * @return a String containing (depth * 2 + 3) * 2 white spaces 16781 * 16782 * @hide 16783 */ 16784 protected static String debugIndent(int depth) { 16785 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16786 for (int i = 0; i < (depth * 2) + 3; i++) { 16787 spaces.append(' ').append(' '); 16788 } 16789 return spaces.toString(); 16790 } 16791 16792 /** 16793 * <p>Return the offset of the widget's text baseline from the widget's top 16794 * boundary. If this widget does not support baseline alignment, this 16795 * method returns -1. </p> 16796 * 16797 * @return the offset of the baseline within the widget's bounds or -1 16798 * if baseline alignment is not supported 16799 */ 16800 @ViewDebug.ExportedProperty(category = "layout") 16801 public int getBaseline() { 16802 return -1; 16803 } 16804 16805 /** 16806 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16807 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16808 * a layout pass. 16809 * 16810 * @return whether the view hierarchy is currently undergoing a layout pass 16811 */ 16812 public boolean isInLayout() { 16813 ViewRootImpl viewRoot = getViewRootImpl(); 16814 return (viewRoot != null && viewRoot.isInLayout()); 16815 } 16816 16817 /** 16818 * Call this when something has changed which has invalidated the 16819 * layout of this view. This will schedule a layout pass of the view 16820 * tree. This should not be called while the view hierarchy is currently in a layout 16821 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16822 * end of the current layout pass (and then layout will run again) or after the current 16823 * frame is drawn and the next layout occurs. 16824 * 16825 * <p>Subclasses which override this method should call the superclass method to 16826 * handle possible request-during-layout errors correctly.</p> 16827 */ 16828 public void requestLayout() { 16829 if (mMeasureCache != null) mMeasureCache.clear(); 16830 16831 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16832 // Only trigger request-during-layout logic if this is the view requesting it, 16833 // not the views in its parent hierarchy 16834 ViewRootImpl viewRoot = getViewRootImpl(); 16835 if (viewRoot != null && viewRoot.isInLayout()) { 16836 if (!viewRoot.requestLayoutDuringLayout(this)) { 16837 return; 16838 } 16839 } 16840 mAttachInfo.mViewRequestingLayout = this; 16841 } 16842 16843 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16844 mPrivateFlags |= PFLAG_INVALIDATED; 16845 16846 if (mParent != null && !mParent.isLayoutRequested()) { 16847 mParent.requestLayout(); 16848 } 16849 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16850 mAttachInfo.mViewRequestingLayout = null; 16851 } 16852 } 16853 16854 /** 16855 * Forces this view to be laid out during the next layout pass. 16856 * This method does not call requestLayout() or forceLayout() 16857 * on the parent. 16858 */ 16859 public void forceLayout() { 16860 if (mMeasureCache != null) mMeasureCache.clear(); 16861 16862 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16863 mPrivateFlags |= PFLAG_INVALIDATED; 16864 } 16865 16866 /** 16867 * <p> 16868 * This is called to find out how big a view should be. The parent 16869 * supplies constraint information in the width and height parameters. 16870 * </p> 16871 * 16872 * <p> 16873 * The actual measurement work of a view is performed in 16874 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16875 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16876 * </p> 16877 * 16878 * 16879 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16880 * parent 16881 * @param heightMeasureSpec Vertical space requirements as imposed by the 16882 * parent 16883 * 16884 * @see #onMeasure(int, int) 16885 */ 16886 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16887 boolean optical = isLayoutModeOptical(this); 16888 if (optical != isLayoutModeOptical(mParent)) { 16889 Insets insets = getOpticalInsets(); 16890 int oWidth = insets.left + insets.right; 16891 int oHeight = insets.top + insets.bottom; 16892 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 16893 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 16894 } 16895 16896 // Suppress sign extension for the low bytes 16897 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 16898 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 16899 16900 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 16901 widthMeasureSpec != mOldWidthMeasureSpec || 16902 heightMeasureSpec != mOldHeightMeasureSpec) { 16903 16904 // first clears the measured dimension flag 16905 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 16906 16907 resolveRtlPropertiesIfNeeded(); 16908 16909 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 16910 mMeasureCache.indexOfKey(key); 16911 if (cacheIndex < 0 || sIgnoreMeasureCache) { 16912 // measure ourselves, this should set the measured dimension flag back 16913 onMeasure(widthMeasureSpec, heightMeasureSpec); 16914 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16915 } else { 16916 long value = mMeasureCache.valueAt(cacheIndex); 16917 // Casting a long to int drops the high 32 bits, no mask needed 16918 setMeasuredDimension((int) (value >> 32), (int) value); 16919 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16920 } 16921 16922 // flag not set, setMeasuredDimension() was not invoked, we raise 16923 // an exception to warn the developer 16924 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 16925 throw new IllegalStateException("onMeasure() did not set the" 16926 + " measured dimension by calling" 16927 + " setMeasuredDimension()"); 16928 } 16929 16930 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 16931 } 16932 16933 mOldWidthMeasureSpec = widthMeasureSpec; 16934 mOldHeightMeasureSpec = heightMeasureSpec; 16935 16936 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 16937 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 16938 } 16939 16940 /** 16941 * <p> 16942 * Measure the view and its content to determine the measured width and the 16943 * measured height. This method is invoked by {@link #measure(int, int)} and 16944 * should be overriden by subclasses to provide accurate and efficient 16945 * measurement of their contents. 16946 * </p> 16947 * 16948 * <p> 16949 * <strong>CONTRACT:</strong> When overriding this method, you 16950 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 16951 * measured width and height of this view. Failure to do so will trigger an 16952 * <code>IllegalStateException</code>, thrown by 16953 * {@link #measure(int, int)}. Calling the superclass' 16954 * {@link #onMeasure(int, int)} is a valid use. 16955 * </p> 16956 * 16957 * <p> 16958 * The base class implementation of measure defaults to the background size, 16959 * unless a larger size is allowed by the MeasureSpec. Subclasses should 16960 * override {@link #onMeasure(int, int)} to provide better measurements of 16961 * their content. 16962 * </p> 16963 * 16964 * <p> 16965 * If this method is overridden, it is the subclass's responsibility to make 16966 * sure the measured height and width are at least the view's minimum height 16967 * and width ({@link #getSuggestedMinimumHeight()} and 16968 * {@link #getSuggestedMinimumWidth()}). 16969 * </p> 16970 * 16971 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 16972 * The requirements are encoded with 16973 * {@link android.view.View.MeasureSpec}. 16974 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 16975 * The requirements are encoded with 16976 * {@link android.view.View.MeasureSpec}. 16977 * 16978 * @see #getMeasuredWidth() 16979 * @see #getMeasuredHeight() 16980 * @see #setMeasuredDimension(int, int) 16981 * @see #getSuggestedMinimumHeight() 16982 * @see #getSuggestedMinimumWidth() 16983 * @see android.view.View.MeasureSpec#getMode(int) 16984 * @see android.view.View.MeasureSpec#getSize(int) 16985 */ 16986 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 16987 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 16988 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 16989 } 16990 16991 /** 16992 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 16993 * measured width and measured height. Failing to do so will trigger an 16994 * exception at measurement time.</p> 16995 * 16996 * @param measuredWidth The measured width of this view. May be a complex 16997 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16998 * {@link #MEASURED_STATE_TOO_SMALL}. 16999 * @param measuredHeight The measured height of this view. May be a complex 17000 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17001 * {@link #MEASURED_STATE_TOO_SMALL}. 17002 */ 17003 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17004 boolean optical = isLayoutModeOptical(this); 17005 if (optical != isLayoutModeOptical(mParent)) { 17006 Insets insets = getOpticalInsets(); 17007 int opticalWidth = insets.left + insets.right; 17008 int opticalHeight = insets.top + insets.bottom; 17009 17010 measuredWidth += optical ? opticalWidth : -opticalWidth; 17011 measuredHeight += optical ? opticalHeight : -opticalHeight; 17012 } 17013 mMeasuredWidth = measuredWidth; 17014 mMeasuredHeight = measuredHeight; 17015 17016 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17017 } 17018 17019 /** 17020 * Merge two states as returned by {@link #getMeasuredState()}. 17021 * @param curState The current state as returned from a view or the result 17022 * of combining multiple views. 17023 * @param newState The new view state to combine. 17024 * @return Returns a new integer reflecting the combination of the two 17025 * states. 17026 */ 17027 public static int combineMeasuredStates(int curState, int newState) { 17028 return curState | newState; 17029 } 17030 17031 /** 17032 * Version of {@link #resolveSizeAndState(int, int, int)} 17033 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17034 */ 17035 public static int resolveSize(int size, int measureSpec) { 17036 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17037 } 17038 17039 /** 17040 * Utility to reconcile a desired size and state, with constraints imposed 17041 * by a MeasureSpec. Will take the desired size, unless a different size 17042 * is imposed by the constraints. The returned value is a compound integer, 17043 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17044 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17045 * size is smaller than the size the view wants to be. 17046 * 17047 * @param size How big the view wants to be 17048 * @param measureSpec Constraints imposed by the parent 17049 * @return Size information bit mask as defined by 17050 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17051 */ 17052 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17053 int result = size; 17054 int specMode = MeasureSpec.getMode(measureSpec); 17055 int specSize = MeasureSpec.getSize(measureSpec); 17056 switch (specMode) { 17057 case MeasureSpec.UNSPECIFIED: 17058 result = size; 17059 break; 17060 case MeasureSpec.AT_MOST: 17061 if (specSize < size) { 17062 result = specSize | MEASURED_STATE_TOO_SMALL; 17063 } else { 17064 result = size; 17065 } 17066 break; 17067 case MeasureSpec.EXACTLY: 17068 result = specSize; 17069 break; 17070 } 17071 return result | (childMeasuredState&MEASURED_STATE_MASK); 17072 } 17073 17074 /** 17075 * Utility to return a default size. Uses the supplied size if the 17076 * MeasureSpec imposed no constraints. Will get larger if allowed 17077 * by the MeasureSpec. 17078 * 17079 * @param size Default size for this view 17080 * @param measureSpec Constraints imposed by the parent 17081 * @return The size this view should be. 17082 */ 17083 public static int getDefaultSize(int size, int measureSpec) { 17084 int result = size; 17085 int specMode = MeasureSpec.getMode(measureSpec); 17086 int specSize = MeasureSpec.getSize(measureSpec); 17087 17088 switch (specMode) { 17089 case MeasureSpec.UNSPECIFIED: 17090 result = size; 17091 break; 17092 case MeasureSpec.AT_MOST: 17093 case MeasureSpec.EXACTLY: 17094 result = specSize; 17095 break; 17096 } 17097 return result; 17098 } 17099 17100 /** 17101 * Returns the suggested minimum height that the view should use. This 17102 * returns the maximum of the view's minimum height 17103 * and the background's minimum height 17104 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17105 * <p> 17106 * When being used in {@link #onMeasure(int, int)}, the caller should still 17107 * ensure the returned height is within the requirements of the parent. 17108 * 17109 * @return The suggested minimum height of the view. 17110 */ 17111 protected int getSuggestedMinimumHeight() { 17112 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17113 17114 } 17115 17116 /** 17117 * Returns the suggested minimum width that the view should use. This 17118 * returns the maximum of the view's minimum width) 17119 * and the background's minimum width 17120 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17121 * <p> 17122 * When being used in {@link #onMeasure(int, int)}, the caller should still 17123 * ensure the returned width is within the requirements of the parent. 17124 * 17125 * @return The suggested minimum width of the view. 17126 */ 17127 protected int getSuggestedMinimumWidth() { 17128 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17129 } 17130 17131 /** 17132 * Returns the minimum height of the view. 17133 * 17134 * @return the minimum height the view will try to be. 17135 * 17136 * @see #setMinimumHeight(int) 17137 * 17138 * @attr ref android.R.styleable#View_minHeight 17139 */ 17140 public int getMinimumHeight() { 17141 return mMinHeight; 17142 } 17143 17144 /** 17145 * Sets the minimum height of the view. It is not guaranteed the view will 17146 * be able to achieve this minimum height (for example, if its parent layout 17147 * constrains it with less available height). 17148 * 17149 * @param minHeight The minimum height the view will try to be. 17150 * 17151 * @see #getMinimumHeight() 17152 * 17153 * @attr ref android.R.styleable#View_minHeight 17154 */ 17155 public void setMinimumHeight(int minHeight) { 17156 mMinHeight = minHeight; 17157 requestLayout(); 17158 } 17159 17160 /** 17161 * Returns the minimum width of the view. 17162 * 17163 * @return the minimum width the view will try to be. 17164 * 17165 * @see #setMinimumWidth(int) 17166 * 17167 * @attr ref android.R.styleable#View_minWidth 17168 */ 17169 public int getMinimumWidth() { 17170 return mMinWidth; 17171 } 17172 17173 /** 17174 * Sets the minimum width of the view. It is not guaranteed the view will 17175 * be able to achieve this minimum width (for example, if its parent layout 17176 * constrains it with less available width). 17177 * 17178 * @param minWidth The minimum width the view will try to be. 17179 * 17180 * @see #getMinimumWidth() 17181 * 17182 * @attr ref android.R.styleable#View_minWidth 17183 */ 17184 public void setMinimumWidth(int minWidth) { 17185 mMinWidth = minWidth; 17186 requestLayout(); 17187 17188 } 17189 17190 /** 17191 * Get the animation currently associated with this view. 17192 * 17193 * @return The animation that is currently playing or 17194 * scheduled to play for this view. 17195 */ 17196 public Animation getAnimation() { 17197 return mCurrentAnimation; 17198 } 17199 17200 /** 17201 * Start the specified animation now. 17202 * 17203 * @param animation the animation to start now 17204 */ 17205 public void startAnimation(Animation animation) { 17206 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17207 setAnimation(animation); 17208 invalidateParentCaches(); 17209 invalidate(true); 17210 } 17211 17212 /** 17213 * Cancels any animations for this view. 17214 */ 17215 public void clearAnimation() { 17216 if (mCurrentAnimation != null) { 17217 mCurrentAnimation.detach(); 17218 } 17219 mCurrentAnimation = null; 17220 invalidateParentIfNeeded(); 17221 } 17222 17223 /** 17224 * Sets the next animation to play for this view. 17225 * If you want the animation to play immediately, use 17226 * {@link #startAnimation(android.view.animation.Animation)} instead. 17227 * This method provides allows fine-grained 17228 * control over the start time and invalidation, but you 17229 * must make sure that 1) the animation has a start time set, and 17230 * 2) the view's parent (which controls animations on its children) 17231 * will be invalidated when the animation is supposed to 17232 * start. 17233 * 17234 * @param animation The next animation, or null. 17235 */ 17236 public void setAnimation(Animation animation) { 17237 mCurrentAnimation = animation; 17238 17239 if (animation != null) { 17240 // If the screen is off assume the animation start time is now instead of 17241 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17242 // would cause the animation to start when the screen turns back on 17243 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 17244 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17245 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17246 } 17247 animation.reset(); 17248 } 17249 } 17250 17251 /** 17252 * Invoked by a parent ViewGroup to notify the start of the animation 17253 * currently associated with this view. If you override this method, 17254 * always call super.onAnimationStart(); 17255 * 17256 * @see #setAnimation(android.view.animation.Animation) 17257 * @see #getAnimation() 17258 */ 17259 protected void onAnimationStart() { 17260 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17261 } 17262 17263 /** 17264 * Invoked by a parent ViewGroup to notify the end of the animation 17265 * currently associated with this view. If you override this method, 17266 * always call super.onAnimationEnd(); 17267 * 17268 * @see #setAnimation(android.view.animation.Animation) 17269 * @see #getAnimation() 17270 */ 17271 protected void onAnimationEnd() { 17272 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17273 } 17274 17275 /** 17276 * Invoked if there is a Transform that involves alpha. Subclass that can 17277 * draw themselves with the specified alpha should return true, and then 17278 * respect that alpha when their onDraw() is called. If this returns false 17279 * then the view may be redirected to draw into an offscreen buffer to 17280 * fulfill the request, which will look fine, but may be slower than if the 17281 * subclass handles it internally. The default implementation returns false. 17282 * 17283 * @param alpha The alpha (0..255) to apply to the view's drawing 17284 * @return true if the view can draw with the specified alpha. 17285 */ 17286 protected boolean onSetAlpha(int alpha) { 17287 return false; 17288 } 17289 17290 /** 17291 * This is used by the RootView to perform an optimization when 17292 * the view hierarchy contains one or several SurfaceView. 17293 * SurfaceView is always considered transparent, but its children are not, 17294 * therefore all View objects remove themselves from the global transparent 17295 * region (passed as a parameter to this function). 17296 * 17297 * @param region The transparent region for this ViewAncestor (window). 17298 * 17299 * @return Returns true if the effective visibility of the view at this 17300 * point is opaque, regardless of the transparent region; returns false 17301 * if it is possible for underlying windows to be seen behind the view. 17302 * 17303 * {@hide} 17304 */ 17305 public boolean gatherTransparentRegion(Region region) { 17306 final AttachInfo attachInfo = mAttachInfo; 17307 if (region != null && attachInfo != null) { 17308 final int pflags = mPrivateFlags; 17309 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17310 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17311 // remove it from the transparent region. 17312 final int[] location = attachInfo.mTransparentLocation; 17313 getLocationInWindow(location); 17314 region.op(location[0], location[1], location[0] + mRight - mLeft, 17315 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17316 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 17317 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17318 // exists, so we remove the background drawable's non-transparent 17319 // parts from this transparent region. 17320 applyDrawableToTransparentRegion(mBackground, region); 17321 } 17322 } 17323 return true; 17324 } 17325 17326 /** 17327 * Play a sound effect for this view. 17328 * 17329 * <p>The framework will play sound effects for some built in actions, such as 17330 * clicking, but you may wish to play these effects in your widget, 17331 * for instance, for internal navigation. 17332 * 17333 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17334 * {@link #isSoundEffectsEnabled()} is true. 17335 * 17336 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17337 */ 17338 public void playSoundEffect(int soundConstant) { 17339 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17340 return; 17341 } 17342 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17343 } 17344 17345 /** 17346 * BZZZTT!!1! 17347 * 17348 * <p>Provide haptic feedback to the user for this view. 17349 * 17350 * <p>The framework will provide haptic feedback for some built in actions, 17351 * such as long presses, but you may wish to provide feedback for your 17352 * own widget. 17353 * 17354 * <p>The feedback will only be performed if 17355 * {@link #isHapticFeedbackEnabled()} is true. 17356 * 17357 * @param feedbackConstant One of the constants defined in 17358 * {@link HapticFeedbackConstants} 17359 */ 17360 public boolean performHapticFeedback(int feedbackConstant) { 17361 return performHapticFeedback(feedbackConstant, 0); 17362 } 17363 17364 /** 17365 * BZZZTT!!1! 17366 * 17367 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17368 * 17369 * @param feedbackConstant One of the constants defined in 17370 * {@link HapticFeedbackConstants} 17371 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17372 */ 17373 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17374 if (mAttachInfo == null) { 17375 return false; 17376 } 17377 //noinspection SimplifiableIfStatement 17378 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17379 && !isHapticFeedbackEnabled()) { 17380 return false; 17381 } 17382 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17383 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17384 } 17385 17386 /** 17387 * Request that the visibility of the status bar or other screen/window 17388 * decorations be changed. 17389 * 17390 * <p>This method is used to put the over device UI into temporary modes 17391 * where the user's attention is focused more on the application content, 17392 * by dimming or hiding surrounding system affordances. This is typically 17393 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17394 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17395 * to be placed behind the action bar (and with these flags other system 17396 * affordances) so that smooth transitions between hiding and showing them 17397 * can be done. 17398 * 17399 * <p>Two representative examples of the use of system UI visibility is 17400 * implementing a content browsing application (like a magazine reader) 17401 * and a video playing application. 17402 * 17403 * <p>The first code shows a typical implementation of a View in a content 17404 * browsing application. In this implementation, the application goes 17405 * into a content-oriented mode by hiding the status bar and action bar, 17406 * and putting the navigation elements into lights out mode. The user can 17407 * then interact with content while in this mode. Such an application should 17408 * provide an easy way for the user to toggle out of the mode (such as to 17409 * check information in the status bar or access notifications). In the 17410 * implementation here, this is done simply by tapping on the content. 17411 * 17412 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17413 * content} 17414 * 17415 * <p>This second code sample shows a typical implementation of a View 17416 * in a video playing application. In this situation, while the video is 17417 * playing the application would like to go into a complete full-screen mode, 17418 * to use as much of the display as possible for the video. When in this state 17419 * the user can not interact with the application; the system intercepts 17420 * touching on the screen to pop the UI out of full screen mode. See 17421 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17422 * 17423 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17424 * content} 17425 * 17426 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17427 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17428 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17429 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17430 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17431 */ 17432 public void setSystemUiVisibility(int visibility) { 17433 if (visibility != mSystemUiVisibility) { 17434 mSystemUiVisibility = visibility; 17435 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17436 mParent.recomputeViewAttributes(this); 17437 } 17438 } 17439 } 17440 17441 /** 17442 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17443 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17444 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17445 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17446 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17447 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17448 */ 17449 public int getSystemUiVisibility() { 17450 return mSystemUiVisibility; 17451 } 17452 17453 /** 17454 * Returns the current system UI visibility that is currently set for 17455 * the entire window. This is the combination of the 17456 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17457 * views in the window. 17458 */ 17459 public int getWindowSystemUiVisibility() { 17460 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17461 } 17462 17463 /** 17464 * Override to find out when the window's requested system UI visibility 17465 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17466 * This is different from the callbacks received through 17467 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17468 * in that this is only telling you about the local request of the window, 17469 * not the actual values applied by the system. 17470 */ 17471 public void onWindowSystemUiVisibilityChanged(int visible) { 17472 } 17473 17474 /** 17475 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17476 * the view hierarchy. 17477 */ 17478 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17479 onWindowSystemUiVisibilityChanged(visible); 17480 } 17481 17482 /** 17483 * Set a listener to receive callbacks when the visibility of the system bar changes. 17484 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17485 */ 17486 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17487 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17488 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17489 mParent.recomputeViewAttributes(this); 17490 } 17491 } 17492 17493 /** 17494 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17495 * the view hierarchy. 17496 */ 17497 public void dispatchSystemUiVisibilityChanged(int visibility) { 17498 ListenerInfo li = mListenerInfo; 17499 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17500 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17501 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17502 } 17503 } 17504 17505 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17506 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17507 if (val != mSystemUiVisibility) { 17508 setSystemUiVisibility(val); 17509 return true; 17510 } 17511 return false; 17512 } 17513 17514 /** @hide */ 17515 public void setDisabledSystemUiVisibility(int flags) { 17516 if (mAttachInfo != null) { 17517 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17518 mAttachInfo.mDisabledSystemUiVisibility = flags; 17519 if (mParent != null) { 17520 mParent.recomputeViewAttributes(this); 17521 } 17522 } 17523 } 17524 } 17525 17526 /** 17527 * Creates an image that the system displays during the drag and drop 17528 * operation. This is called a "drag shadow". The default implementation 17529 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17530 * appearance as the given View. The default also positions the center of the drag shadow 17531 * directly under the touch point. If no View is provided (the constructor with no parameters 17532 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17533 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17534 * default is an invisible drag shadow. 17535 * <p> 17536 * You are not required to use the View you provide to the constructor as the basis of the 17537 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17538 * anything you want as the drag shadow. 17539 * </p> 17540 * <p> 17541 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17542 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17543 * size and position of the drag shadow. It uses this data to construct a 17544 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17545 * so that your application can draw the shadow image in the Canvas. 17546 * </p> 17547 * 17548 * <div class="special reference"> 17549 * <h3>Developer Guides</h3> 17550 * <p>For a guide to implementing drag and drop features, read the 17551 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17552 * </div> 17553 */ 17554 public static class DragShadowBuilder { 17555 private final WeakReference<View> mView; 17556 17557 /** 17558 * Constructs a shadow image builder based on a View. By default, the resulting drag 17559 * shadow will have the same appearance and dimensions as the View, with the touch point 17560 * over the center of the View. 17561 * @param view A View. Any View in scope can be used. 17562 */ 17563 public DragShadowBuilder(View view) { 17564 mView = new WeakReference<View>(view); 17565 } 17566 17567 /** 17568 * Construct a shadow builder object with no associated View. This 17569 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17570 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17571 * to supply the drag shadow's dimensions and appearance without 17572 * reference to any View object. If they are not overridden, then the result is an 17573 * invisible drag shadow. 17574 */ 17575 public DragShadowBuilder() { 17576 mView = new WeakReference<View>(null); 17577 } 17578 17579 /** 17580 * Returns the View object that had been passed to the 17581 * {@link #View.DragShadowBuilder(View)} 17582 * constructor. If that View parameter was {@code null} or if the 17583 * {@link #View.DragShadowBuilder()} 17584 * constructor was used to instantiate the builder object, this method will return 17585 * null. 17586 * 17587 * @return The View object associate with this builder object. 17588 */ 17589 @SuppressWarnings({"JavadocReference"}) 17590 final public View getView() { 17591 return mView.get(); 17592 } 17593 17594 /** 17595 * Provides the metrics for the shadow image. These include the dimensions of 17596 * the shadow image, and the point within that shadow that should 17597 * be centered under the touch location while dragging. 17598 * <p> 17599 * The default implementation sets the dimensions of the shadow to be the 17600 * same as the dimensions of the View itself and centers the shadow under 17601 * the touch point. 17602 * </p> 17603 * 17604 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17605 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17606 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17607 * image. 17608 * 17609 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17610 * shadow image that should be underneath the touch point during the drag and drop 17611 * operation. Your application must set {@link android.graphics.Point#x} to the 17612 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17613 */ 17614 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17615 final View view = mView.get(); 17616 if (view != null) { 17617 shadowSize.set(view.getWidth(), view.getHeight()); 17618 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17619 } else { 17620 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17621 } 17622 } 17623 17624 /** 17625 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17626 * based on the dimensions it received from the 17627 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17628 * 17629 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17630 */ 17631 public void onDrawShadow(Canvas canvas) { 17632 final View view = mView.get(); 17633 if (view != null) { 17634 view.draw(canvas); 17635 } else { 17636 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17637 } 17638 } 17639 } 17640 17641 /** 17642 * Starts a drag and drop operation. When your application calls this method, it passes a 17643 * {@link android.view.View.DragShadowBuilder} object to the system. The 17644 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17645 * to get metrics for the drag shadow, and then calls the object's 17646 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17647 * <p> 17648 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17649 * drag events to all the View objects in your application that are currently visible. It does 17650 * this either by calling the View object's drag listener (an implementation of 17651 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17652 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17653 * Both are passed a {@link android.view.DragEvent} object that has a 17654 * {@link android.view.DragEvent#getAction()} value of 17655 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17656 * </p> 17657 * <p> 17658 * Your application can invoke startDrag() on any attached View object. The View object does not 17659 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17660 * be related to the View the user selected for dragging. 17661 * </p> 17662 * @param data A {@link android.content.ClipData} object pointing to the data to be 17663 * transferred by the drag and drop operation. 17664 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17665 * drag shadow. 17666 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17667 * drop operation. This Object is put into every DragEvent object sent by the system during the 17668 * current drag. 17669 * <p> 17670 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17671 * to the target Views. For example, it can contain flags that differentiate between a 17672 * a copy operation and a move operation. 17673 * </p> 17674 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17675 * so the parameter should be set to 0. 17676 * @return {@code true} if the method completes successfully, or 17677 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17678 * do a drag, and so no drag operation is in progress. 17679 */ 17680 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17681 Object myLocalState, int flags) { 17682 if (ViewDebug.DEBUG_DRAG) { 17683 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17684 } 17685 boolean okay = false; 17686 17687 Point shadowSize = new Point(); 17688 Point shadowTouchPoint = new Point(); 17689 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17690 17691 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17692 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17693 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17694 } 17695 17696 if (ViewDebug.DEBUG_DRAG) { 17697 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17698 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17699 } 17700 Surface surface = new Surface(); 17701 try { 17702 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17703 flags, shadowSize.x, shadowSize.y, surface); 17704 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17705 + " surface=" + surface); 17706 if (token != null) { 17707 Canvas canvas = surface.lockCanvas(null); 17708 try { 17709 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17710 shadowBuilder.onDrawShadow(canvas); 17711 } finally { 17712 surface.unlockCanvasAndPost(canvas); 17713 } 17714 17715 final ViewRootImpl root = getViewRootImpl(); 17716 17717 // Cache the local state object for delivery with DragEvents 17718 root.setLocalDragState(myLocalState); 17719 17720 // repurpose 'shadowSize' for the last touch point 17721 root.getLastTouchPoint(shadowSize); 17722 17723 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17724 shadowSize.x, shadowSize.y, 17725 shadowTouchPoint.x, shadowTouchPoint.y, data); 17726 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17727 17728 // Off and running! Release our local surface instance; the drag 17729 // shadow surface is now managed by the system process. 17730 surface.release(); 17731 } 17732 } catch (Exception e) { 17733 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17734 surface.destroy(); 17735 } 17736 17737 return okay; 17738 } 17739 17740 /** 17741 * Handles drag events sent by the system following a call to 17742 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17743 *<p> 17744 * When the system calls this method, it passes a 17745 * {@link android.view.DragEvent} object. A call to 17746 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17747 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17748 * operation. 17749 * @param event The {@link android.view.DragEvent} sent by the system. 17750 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17751 * in DragEvent, indicating the type of drag event represented by this object. 17752 * @return {@code true} if the method was successful, otherwise {@code false}. 17753 * <p> 17754 * The method should return {@code true} in response to an action type of 17755 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17756 * operation. 17757 * </p> 17758 * <p> 17759 * The method should also return {@code true} in response to an action type of 17760 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17761 * {@code false} if it didn't. 17762 * </p> 17763 */ 17764 public boolean onDragEvent(DragEvent event) { 17765 return false; 17766 } 17767 17768 /** 17769 * Detects if this View is enabled and has a drag event listener. 17770 * If both are true, then it calls the drag event listener with the 17771 * {@link android.view.DragEvent} it received. If the drag event listener returns 17772 * {@code true}, then dispatchDragEvent() returns {@code true}. 17773 * <p> 17774 * For all other cases, the method calls the 17775 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17776 * method and returns its result. 17777 * </p> 17778 * <p> 17779 * This ensures that a drag event is always consumed, even if the View does not have a drag 17780 * event listener. However, if the View has a listener and the listener returns true, then 17781 * onDragEvent() is not called. 17782 * </p> 17783 */ 17784 public boolean dispatchDragEvent(DragEvent event) { 17785 ListenerInfo li = mListenerInfo; 17786 //noinspection SimplifiableIfStatement 17787 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17788 && li.mOnDragListener.onDrag(this, event)) { 17789 return true; 17790 } 17791 return onDragEvent(event); 17792 } 17793 17794 boolean canAcceptDrag() { 17795 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17796 } 17797 17798 /** 17799 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17800 * it is ever exposed at all. 17801 * @hide 17802 */ 17803 public void onCloseSystemDialogs(String reason) { 17804 } 17805 17806 /** 17807 * Given a Drawable whose bounds have been set to draw into this view, 17808 * update a Region being computed for 17809 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17810 * that any non-transparent parts of the Drawable are removed from the 17811 * given transparent region. 17812 * 17813 * @param dr The Drawable whose transparency is to be applied to the region. 17814 * @param region A Region holding the current transparency information, 17815 * where any parts of the region that are set are considered to be 17816 * transparent. On return, this region will be modified to have the 17817 * transparency information reduced by the corresponding parts of the 17818 * Drawable that are not transparent. 17819 * {@hide} 17820 */ 17821 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17822 if (DBG) { 17823 Log.i("View", "Getting transparent region for: " + this); 17824 } 17825 final Region r = dr.getTransparentRegion(); 17826 final Rect db = dr.getBounds(); 17827 final AttachInfo attachInfo = mAttachInfo; 17828 if (r != null && attachInfo != null) { 17829 final int w = getRight()-getLeft(); 17830 final int h = getBottom()-getTop(); 17831 if (db.left > 0) { 17832 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17833 r.op(0, 0, db.left, h, Region.Op.UNION); 17834 } 17835 if (db.right < w) { 17836 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17837 r.op(db.right, 0, w, h, Region.Op.UNION); 17838 } 17839 if (db.top > 0) { 17840 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17841 r.op(0, 0, w, db.top, Region.Op.UNION); 17842 } 17843 if (db.bottom < h) { 17844 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17845 r.op(0, db.bottom, w, h, Region.Op.UNION); 17846 } 17847 final int[] location = attachInfo.mTransparentLocation; 17848 getLocationInWindow(location); 17849 r.translate(location[0], location[1]); 17850 region.op(r, Region.Op.INTERSECT); 17851 } else { 17852 region.op(db, Region.Op.DIFFERENCE); 17853 } 17854 } 17855 17856 private void checkForLongClick(int delayOffset) { 17857 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17858 mHasPerformedLongPress = false; 17859 17860 if (mPendingCheckForLongPress == null) { 17861 mPendingCheckForLongPress = new CheckForLongPress(); 17862 } 17863 mPendingCheckForLongPress.rememberWindowAttachCount(); 17864 postDelayed(mPendingCheckForLongPress, 17865 ViewConfiguration.getLongPressTimeout() - delayOffset); 17866 } 17867 } 17868 17869 /** 17870 * Inflate a view from an XML resource. This convenience method wraps the {@link 17871 * LayoutInflater} class, which provides a full range of options for view inflation. 17872 * 17873 * @param context The Context object for your activity or application. 17874 * @param resource The resource ID to inflate 17875 * @param root A view group that will be the parent. Used to properly inflate the 17876 * layout_* parameters. 17877 * @see LayoutInflater 17878 */ 17879 public static View inflate(Context context, int resource, ViewGroup root) { 17880 LayoutInflater factory = LayoutInflater.from(context); 17881 return factory.inflate(resource, root); 17882 } 17883 17884 /** 17885 * Scroll the view with standard behavior for scrolling beyond the normal 17886 * content boundaries. Views that call this method should override 17887 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 17888 * results of an over-scroll operation. 17889 * 17890 * Views can use this method to handle any touch or fling-based scrolling. 17891 * 17892 * @param deltaX Change in X in pixels 17893 * @param deltaY Change in Y in pixels 17894 * @param scrollX Current X scroll value in pixels before applying deltaX 17895 * @param scrollY Current Y scroll value in pixels before applying deltaY 17896 * @param scrollRangeX Maximum content scroll range along the X axis 17897 * @param scrollRangeY Maximum content scroll range along the Y axis 17898 * @param maxOverScrollX Number of pixels to overscroll by in either direction 17899 * along the X axis. 17900 * @param maxOverScrollY Number of pixels to overscroll by in either direction 17901 * along the Y axis. 17902 * @param isTouchEvent true if this scroll operation is the result of a touch event. 17903 * @return true if scrolling was clamped to an over-scroll boundary along either 17904 * axis, false otherwise. 17905 */ 17906 @SuppressWarnings({"UnusedParameters"}) 17907 protected boolean overScrollBy(int deltaX, int deltaY, 17908 int scrollX, int scrollY, 17909 int scrollRangeX, int scrollRangeY, 17910 int maxOverScrollX, int maxOverScrollY, 17911 boolean isTouchEvent) { 17912 final int overScrollMode = mOverScrollMode; 17913 final boolean canScrollHorizontal = 17914 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 17915 final boolean canScrollVertical = 17916 computeVerticalScrollRange() > computeVerticalScrollExtent(); 17917 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 17918 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 17919 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 17920 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 17921 17922 int newScrollX = scrollX + deltaX; 17923 if (!overScrollHorizontal) { 17924 maxOverScrollX = 0; 17925 } 17926 17927 int newScrollY = scrollY + deltaY; 17928 if (!overScrollVertical) { 17929 maxOverScrollY = 0; 17930 } 17931 17932 // Clamp values if at the limits and record 17933 final int left = -maxOverScrollX; 17934 final int right = maxOverScrollX + scrollRangeX; 17935 final int top = -maxOverScrollY; 17936 final int bottom = maxOverScrollY + scrollRangeY; 17937 17938 boolean clampedX = false; 17939 if (newScrollX > right) { 17940 newScrollX = right; 17941 clampedX = true; 17942 } else if (newScrollX < left) { 17943 newScrollX = left; 17944 clampedX = true; 17945 } 17946 17947 boolean clampedY = false; 17948 if (newScrollY > bottom) { 17949 newScrollY = bottom; 17950 clampedY = true; 17951 } else if (newScrollY < top) { 17952 newScrollY = top; 17953 clampedY = true; 17954 } 17955 17956 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 17957 17958 return clampedX || clampedY; 17959 } 17960 17961 /** 17962 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 17963 * respond to the results of an over-scroll operation. 17964 * 17965 * @param scrollX New X scroll value in pixels 17966 * @param scrollY New Y scroll value in pixels 17967 * @param clampedX True if scrollX was clamped to an over-scroll boundary 17968 * @param clampedY True if scrollY was clamped to an over-scroll boundary 17969 */ 17970 protected void onOverScrolled(int scrollX, int scrollY, 17971 boolean clampedX, boolean clampedY) { 17972 // Intentionally empty. 17973 } 17974 17975 /** 17976 * Returns the over-scroll mode for this view. The result will be 17977 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17978 * (allow over-scrolling only if the view content is larger than the container), 17979 * or {@link #OVER_SCROLL_NEVER}. 17980 * 17981 * @return This view's over-scroll mode. 17982 */ 17983 public int getOverScrollMode() { 17984 return mOverScrollMode; 17985 } 17986 17987 /** 17988 * Set the over-scroll mode for this view. Valid over-scroll modes are 17989 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17990 * (allow over-scrolling only if the view content is larger than the container), 17991 * or {@link #OVER_SCROLL_NEVER}. 17992 * 17993 * Setting the over-scroll mode of a view will have an effect only if the 17994 * view is capable of scrolling. 17995 * 17996 * @param overScrollMode The new over-scroll mode for this view. 17997 */ 17998 public void setOverScrollMode(int overScrollMode) { 17999 if (overScrollMode != OVER_SCROLL_ALWAYS && 18000 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18001 overScrollMode != OVER_SCROLL_NEVER) { 18002 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18003 } 18004 mOverScrollMode = overScrollMode; 18005 } 18006 18007 /** 18008 * Gets a scale factor that determines the distance the view should scroll 18009 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18010 * @return The vertical scroll scale factor. 18011 * @hide 18012 */ 18013 protected float getVerticalScrollFactor() { 18014 if (mVerticalScrollFactor == 0) { 18015 TypedValue outValue = new TypedValue(); 18016 if (!mContext.getTheme().resolveAttribute( 18017 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18018 throw new IllegalStateException( 18019 "Expected theme to define listPreferredItemHeight."); 18020 } 18021 mVerticalScrollFactor = outValue.getDimension( 18022 mContext.getResources().getDisplayMetrics()); 18023 } 18024 return mVerticalScrollFactor; 18025 } 18026 18027 /** 18028 * Gets a scale factor that determines the distance the view should scroll 18029 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18030 * @return The horizontal scroll scale factor. 18031 * @hide 18032 */ 18033 protected float getHorizontalScrollFactor() { 18034 // TODO: Should use something else. 18035 return getVerticalScrollFactor(); 18036 } 18037 18038 /** 18039 * Return the value specifying the text direction or policy that was set with 18040 * {@link #setTextDirection(int)}. 18041 * 18042 * @return the defined text direction. It can be one of: 18043 * 18044 * {@link #TEXT_DIRECTION_INHERIT}, 18045 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18046 * {@link #TEXT_DIRECTION_ANY_RTL}, 18047 * {@link #TEXT_DIRECTION_LTR}, 18048 * {@link #TEXT_DIRECTION_RTL}, 18049 * {@link #TEXT_DIRECTION_LOCALE} 18050 * 18051 * @attr ref android.R.styleable#View_textDirection 18052 * 18053 * @hide 18054 */ 18055 @ViewDebug.ExportedProperty(category = "text", mapping = { 18056 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18057 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18058 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18059 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18060 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18061 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18062 }) 18063 public int getRawTextDirection() { 18064 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18065 } 18066 18067 /** 18068 * Set the text direction. 18069 * 18070 * @param textDirection the direction to set. Should be one of: 18071 * 18072 * {@link #TEXT_DIRECTION_INHERIT}, 18073 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18074 * {@link #TEXT_DIRECTION_ANY_RTL}, 18075 * {@link #TEXT_DIRECTION_LTR}, 18076 * {@link #TEXT_DIRECTION_RTL}, 18077 * {@link #TEXT_DIRECTION_LOCALE} 18078 * 18079 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18080 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18081 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18082 * 18083 * @attr ref android.R.styleable#View_textDirection 18084 */ 18085 public void setTextDirection(int textDirection) { 18086 if (getRawTextDirection() != textDirection) { 18087 // Reset the current text direction and the resolved one 18088 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18089 resetResolvedTextDirection(); 18090 // Set the new text direction 18091 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18092 // Do resolution 18093 resolveTextDirection(); 18094 // Notify change 18095 onRtlPropertiesChanged(getLayoutDirection()); 18096 // Refresh 18097 requestLayout(); 18098 invalidate(true); 18099 } 18100 } 18101 18102 /** 18103 * Return the resolved text direction. 18104 * 18105 * @return the resolved text direction. Returns one of: 18106 * 18107 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18108 * {@link #TEXT_DIRECTION_ANY_RTL}, 18109 * {@link #TEXT_DIRECTION_LTR}, 18110 * {@link #TEXT_DIRECTION_RTL}, 18111 * {@link #TEXT_DIRECTION_LOCALE} 18112 * 18113 * @attr ref android.R.styleable#View_textDirection 18114 */ 18115 @ViewDebug.ExportedProperty(category = "text", mapping = { 18116 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18117 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18118 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18119 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18120 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18121 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18122 }) 18123 public int getTextDirection() { 18124 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18125 } 18126 18127 /** 18128 * Resolve the text direction. 18129 * 18130 * @return true if resolution has been done, false otherwise. 18131 * 18132 * @hide 18133 */ 18134 public boolean resolveTextDirection() { 18135 // Reset any previous text direction resolution 18136 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18137 18138 if (hasRtlSupport()) { 18139 // Set resolved text direction flag depending on text direction flag 18140 final int textDirection = getRawTextDirection(); 18141 switch(textDirection) { 18142 case TEXT_DIRECTION_INHERIT: 18143 if (!canResolveTextDirection()) { 18144 // We cannot do the resolution if there is no parent, so use the default one 18145 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18146 // Resolution will need to happen again later 18147 return false; 18148 } 18149 18150 // Parent has not yet resolved, so we still return the default 18151 try { 18152 if (!mParent.isTextDirectionResolved()) { 18153 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18154 // Resolution will need to happen again later 18155 return false; 18156 } 18157 } catch (AbstractMethodError e) { 18158 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18159 " does not fully implement ViewParent", e); 18160 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18161 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18162 return true; 18163 } 18164 18165 // Set current resolved direction to the same value as the parent's one 18166 int parentResolvedDirection; 18167 try { 18168 parentResolvedDirection = mParent.getTextDirection(); 18169 } catch (AbstractMethodError e) { 18170 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18171 " does not fully implement ViewParent", e); 18172 parentResolvedDirection = TEXT_DIRECTION_LTR; 18173 } 18174 switch (parentResolvedDirection) { 18175 case TEXT_DIRECTION_FIRST_STRONG: 18176 case TEXT_DIRECTION_ANY_RTL: 18177 case TEXT_DIRECTION_LTR: 18178 case TEXT_DIRECTION_RTL: 18179 case TEXT_DIRECTION_LOCALE: 18180 mPrivateFlags2 |= 18181 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18182 break; 18183 default: 18184 // Default resolved direction is "first strong" heuristic 18185 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18186 } 18187 break; 18188 case TEXT_DIRECTION_FIRST_STRONG: 18189 case TEXT_DIRECTION_ANY_RTL: 18190 case TEXT_DIRECTION_LTR: 18191 case TEXT_DIRECTION_RTL: 18192 case TEXT_DIRECTION_LOCALE: 18193 // Resolved direction is the same as text direction 18194 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18195 break; 18196 default: 18197 // Default resolved direction is "first strong" heuristic 18198 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18199 } 18200 } else { 18201 // Default resolved direction is "first strong" heuristic 18202 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18203 } 18204 18205 // Set to resolved 18206 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18207 return true; 18208 } 18209 18210 /** 18211 * Check if text direction resolution can be done. 18212 * 18213 * @return true if text direction resolution can be done otherwise return false. 18214 */ 18215 public boolean canResolveTextDirection() { 18216 switch (getRawTextDirection()) { 18217 case TEXT_DIRECTION_INHERIT: 18218 if (mParent != null) { 18219 try { 18220 return mParent.canResolveTextDirection(); 18221 } catch (AbstractMethodError e) { 18222 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18223 " does not fully implement ViewParent", e); 18224 } 18225 } 18226 return false; 18227 18228 default: 18229 return true; 18230 } 18231 } 18232 18233 /** 18234 * Reset resolved text direction. Text direction will be resolved during a call to 18235 * {@link #onMeasure(int, int)}. 18236 * 18237 * @hide 18238 */ 18239 public void resetResolvedTextDirection() { 18240 // Reset any previous text direction resolution 18241 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18242 // Set to default value 18243 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18244 } 18245 18246 /** 18247 * @return true if text direction is inherited. 18248 * 18249 * @hide 18250 */ 18251 public boolean isTextDirectionInherited() { 18252 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18253 } 18254 18255 /** 18256 * @return true if text direction is resolved. 18257 */ 18258 public boolean isTextDirectionResolved() { 18259 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18260 } 18261 18262 /** 18263 * Return the value specifying the text alignment or policy that was set with 18264 * {@link #setTextAlignment(int)}. 18265 * 18266 * @return the defined text alignment. It can be one of: 18267 * 18268 * {@link #TEXT_ALIGNMENT_INHERIT}, 18269 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18270 * {@link #TEXT_ALIGNMENT_CENTER}, 18271 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18272 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18273 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18274 * {@link #TEXT_ALIGNMENT_VIEW_END} 18275 * 18276 * @attr ref android.R.styleable#View_textAlignment 18277 * 18278 * @hide 18279 */ 18280 @ViewDebug.ExportedProperty(category = "text", mapping = { 18281 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18282 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18283 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18284 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18285 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18286 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18287 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18288 }) 18289 @TextAlignment 18290 public int getRawTextAlignment() { 18291 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18292 } 18293 18294 /** 18295 * Set the text alignment. 18296 * 18297 * @param textAlignment The text alignment to set. Should be one of 18298 * 18299 * {@link #TEXT_ALIGNMENT_INHERIT}, 18300 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18301 * {@link #TEXT_ALIGNMENT_CENTER}, 18302 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18303 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18304 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18305 * {@link #TEXT_ALIGNMENT_VIEW_END} 18306 * 18307 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18308 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18309 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18310 * 18311 * @attr ref android.R.styleable#View_textAlignment 18312 */ 18313 public void setTextAlignment(@TextAlignment int textAlignment) { 18314 if (textAlignment != getRawTextAlignment()) { 18315 // Reset the current and resolved text alignment 18316 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18317 resetResolvedTextAlignment(); 18318 // Set the new text alignment 18319 mPrivateFlags2 |= 18320 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18321 // Do resolution 18322 resolveTextAlignment(); 18323 // Notify change 18324 onRtlPropertiesChanged(getLayoutDirection()); 18325 // Refresh 18326 requestLayout(); 18327 invalidate(true); 18328 } 18329 } 18330 18331 /** 18332 * Return the resolved text alignment. 18333 * 18334 * @return the resolved text alignment. Returns one of: 18335 * 18336 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18337 * {@link #TEXT_ALIGNMENT_CENTER}, 18338 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18339 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18340 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18341 * {@link #TEXT_ALIGNMENT_VIEW_END} 18342 * 18343 * @attr ref android.R.styleable#View_textAlignment 18344 */ 18345 @ViewDebug.ExportedProperty(category = "text", mapping = { 18346 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18347 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18348 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18349 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18350 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18351 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18352 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18353 }) 18354 @TextAlignment 18355 public int getTextAlignment() { 18356 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18357 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18358 } 18359 18360 /** 18361 * Resolve the text alignment. 18362 * 18363 * @return true if resolution has been done, false otherwise. 18364 * 18365 * @hide 18366 */ 18367 public boolean resolveTextAlignment() { 18368 // Reset any previous text alignment resolution 18369 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18370 18371 if (hasRtlSupport()) { 18372 // Set resolved text alignment flag depending on text alignment flag 18373 final int textAlignment = getRawTextAlignment(); 18374 switch (textAlignment) { 18375 case TEXT_ALIGNMENT_INHERIT: 18376 // Check if we can resolve the text alignment 18377 if (!canResolveTextAlignment()) { 18378 // We cannot do the resolution if there is no parent so use the default 18379 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18380 // Resolution will need to happen again later 18381 return false; 18382 } 18383 18384 // Parent has not yet resolved, so we still return the default 18385 try { 18386 if (!mParent.isTextAlignmentResolved()) { 18387 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18388 // Resolution will need to happen again later 18389 return false; 18390 } 18391 } catch (AbstractMethodError e) { 18392 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18393 " does not fully implement ViewParent", e); 18394 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18395 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18396 return true; 18397 } 18398 18399 int parentResolvedTextAlignment; 18400 try { 18401 parentResolvedTextAlignment = mParent.getTextAlignment(); 18402 } catch (AbstractMethodError e) { 18403 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18404 " does not fully implement ViewParent", e); 18405 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18406 } 18407 switch (parentResolvedTextAlignment) { 18408 case TEXT_ALIGNMENT_GRAVITY: 18409 case TEXT_ALIGNMENT_TEXT_START: 18410 case TEXT_ALIGNMENT_TEXT_END: 18411 case TEXT_ALIGNMENT_CENTER: 18412 case TEXT_ALIGNMENT_VIEW_START: 18413 case TEXT_ALIGNMENT_VIEW_END: 18414 // Resolved text alignment is the same as the parent resolved 18415 // text alignment 18416 mPrivateFlags2 |= 18417 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18418 break; 18419 default: 18420 // Use default resolved text alignment 18421 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18422 } 18423 break; 18424 case TEXT_ALIGNMENT_GRAVITY: 18425 case TEXT_ALIGNMENT_TEXT_START: 18426 case TEXT_ALIGNMENT_TEXT_END: 18427 case TEXT_ALIGNMENT_CENTER: 18428 case TEXT_ALIGNMENT_VIEW_START: 18429 case TEXT_ALIGNMENT_VIEW_END: 18430 // Resolved text alignment is the same as text alignment 18431 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18432 break; 18433 default: 18434 // Use default resolved text alignment 18435 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18436 } 18437 } else { 18438 // Use default resolved text alignment 18439 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18440 } 18441 18442 // Set the resolved 18443 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18444 return true; 18445 } 18446 18447 /** 18448 * Check if text alignment resolution can be done. 18449 * 18450 * @return true if text alignment resolution can be done otherwise return false. 18451 */ 18452 public boolean canResolveTextAlignment() { 18453 switch (getRawTextAlignment()) { 18454 case TEXT_DIRECTION_INHERIT: 18455 if (mParent != null) { 18456 try { 18457 return mParent.canResolveTextAlignment(); 18458 } catch (AbstractMethodError e) { 18459 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18460 " does not fully implement ViewParent", e); 18461 } 18462 } 18463 return false; 18464 18465 default: 18466 return true; 18467 } 18468 } 18469 18470 /** 18471 * Reset resolved text alignment. Text alignment will be resolved during a call to 18472 * {@link #onMeasure(int, int)}. 18473 * 18474 * @hide 18475 */ 18476 public void resetResolvedTextAlignment() { 18477 // Reset any previous text alignment resolution 18478 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18479 // Set to default 18480 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18481 } 18482 18483 /** 18484 * @return true if text alignment is inherited. 18485 * 18486 * @hide 18487 */ 18488 public boolean isTextAlignmentInherited() { 18489 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18490 } 18491 18492 /** 18493 * @return true if text alignment is resolved. 18494 */ 18495 public boolean isTextAlignmentResolved() { 18496 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18497 } 18498 18499 /** 18500 * Generate a value suitable for use in {@link #setId(int)}. 18501 * This value will not collide with ID values generated at build time by aapt for R.id. 18502 * 18503 * @return a generated ID value 18504 */ 18505 public static int generateViewId() { 18506 for (;;) { 18507 final int result = sNextGeneratedId.get(); 18508 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18509 int newValue = result + 1; 18510 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18511 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18512 return result; 18513 } 18514 } 18515 } 18516 18517 // 18518 // Properties 18519 // 18520 /** 18521 * A Property wrapper around the <code>alpha</code> functionality handled by the 18522 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18523 */ 18524 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18525 @Override 18526 public void setValue(View object, float value) { 18527 object.setAlpha(value); 18528 } 18529 18530 @Override 18531 public Float get(View object) { 18532 return object.getAlpha(); 18533 } 18534 }; 18535 18536 /** 18537 * A Property wrapper around the <code>translationX</code> functionality handled by the 18538 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 18539 */ 18540 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 18541 @Override 18542 public void setValue(View object, float value) { 18543 object.setTranslationX(value); 18544 } 18545 18546 @Override 18547 public Float get(View object) { 18548 return object.getTranslationX(); 18549 } 18550 }; 18551 18552 /** 18553 * A Property wrapper around the <code>translationY</code> functionality handled by the 18554 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 18555 */ 18556 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 18557 @Override 18558 public void setValue(View object, float value) { 18559 object.setTranslationY(value); 18560 } 18561 18562 @Override 18563 public Float get(View object) { 18564 return object.getTranslationY(); 18565 } 18566 }; 18567 18568 /** 18569 * A Property wrapper around the <code>translationZ</code> functionality handled by the 18570 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 18571 */ 18572 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 18573 @Override 18574 public void setValue(View object, float value) { 18575 object.setTranslationZ(value); 18576 } 18577 18578 @Override 18579 public Float get(View object) { 18580 return object.getTranslationZ(); 18581 } 18582 }; 18583 18584 /** 18585 * A Property wrapper around the <code>x</code> functionality handled by the 18586 * {@link View#setX(float)} and {@link View#getX()} methods. 18587 */ 18588 public static final Property<View, Float> X = new FloatProperty<View>("x") { 18589 @Override 18590 public void setValue(View object, float value) { 18591 object.setX(value); 18592 } 18593 18594 @Override 18595 public Float get(View object) { 18596 return object.getX(); 18597 } 18598 }; 18599 18600 /** 18601 * A Property wrapper around the <code>y</code> functionality handled by the 18602 * {@link View#setY(float)} and {@link View#getY()} methods. 18603 */ 18604 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 18605 @Override 18606 public void setValue(View object, float value) { 18607 object.setY(value); 18608 } 18609 18610 @Override 18611 public Float get(View object) { 18612 return object.getY(); 18613 } 18614 }; 18615 18616 /** 18617 * A Property wrapper around the <code>rotation</code> functionality handled by the 18618 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 18619 */ 18620 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 18621 @Override 18622 public void setValue(View object, float value) { 18623 object.setRotation(value); 18624 } 18625 18626 @Override 18627 public Float get(View object) { 18628 return object.getRotation(); 18629 } 18630 }; 18631 18632 /** 18633 * A Property wrapper around the <code>rotationX</code> functionality handled by the 18634 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 18635 */ 18636 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 18637 @Override 18638 public void setValue(View object, float value) { 18639 object.setRotationX(value); 18640 } 18641 18642 @Override 18643 public Float get(View object) { 18644 return object.getRotationX(); 18645 } 18646 }; 18647 18648 /** 18649 * A Property wrapper around the <code>rotationY</code> functionality handled by the 18650 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 18651 */ 18652 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 18653 @Override 18654 public void setValue(View object, float value) { 18655 object.setRotationY(value); 18656 } 18657 18658 @Override 18659 public Float get(View object) { 18660 return object.getRotationY(); 18661 } 18662 }; 18663 18664 /** 18665 * A Property wrapper around the <code>scaleX</code> functionality handled by the 18666 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 18667 */ 18668 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 18669 @Override 18670 public void setValue(View object, float value) { 18671 object.setScaleX(value); 18672 } 18673 18674 @Override 18675 public Float get(View object) { 18676 return object.getScaleX(); 18677 } 18678 }; 18679 18680 /** 18681 * A Property wrapper around the <code>scaleY</code> functionality handled by the 18682 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 18683 */ 18684 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 18685 @Override 18686 public void setValue(View object, float value) { 18687 object.setScaleY(value); 18688 } 18689 18690 @Override 18691 public Float get(View object) { 18692 return object.getScaleY(); 18693 } 18694 }; 18695 18696 /** 18697 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 18698 * Each MeasureSpec represents a requirement for either the width or the height. 18699 * A MeasureSpec is comprised of a size and a mode. There are three possible 18700 * modes: 18701 * <dl> 18702 * <dt>UNSPECIFIED</dt> 18703 * <dd> 18704 * The parent has not imposed any constraint on the child. It can be whatever size 18705 * it wants. 18706 * </dd> 18707 * 18708 * <dt>EXACTLY</dt> 18709 * <dd> 18710 * The parent has determined an exact size for the child. The child is going to be 18711 * given those bounds regardless of how big it wants to be. 18712 * </dd> 18713 * 18714 * <dt>AT_MOST</dt> 18715 * <dd> 18716 * The child can be as large as it wants up to the specified size. 18717 * </dd> 18718 * </dl> 18719 * 18720 * MeasureSpecs are implemented as ints to reduce object allocation. This class 18721 * is provided to pack and unpack the <size, mode> tuple into the int. 18722 */ 18723 public static class MeasureSpec { 18724 private static final int MODE_SHIFT = 30; 18725 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 18726 18727 /** 18728 * Measure specification mode: The parent has not imposed any constraint 18729 * on the child. It can be whatever size it wants. 18730 */ 18731 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 18732 18733 /** 18734 * Measure specification mode: The parent has determined an exact size 18735 * for the child. The child is going to be given those bounds regardless 18736 * of how big it wants to be. 18737 */ 18738 public static final int EXACTLY = 1 << MODE_SHIFT; 18739 18740 /** 18741 * Measure specification mode: The child can be as large as it wants up 18742 * to the specified size. 18743 */ 18744 public static final int AT_MOST = 2 << MODE_SHIFT; 18745 18746 /** 18747 * Creates a measure specification based on the supplied size and mode. 18748 * 18749 * The mode must always be one of the following: 18750 * <ul> 18751 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 18752 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 18753 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 18754 * </ul> 18755 * 18756 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 18757 * implementation was such that the order of arguments did not matter 18758 * and overflow in either value could impact the resulting MeasureSpec. 18759 * {@link android.widget.RelativeLayout} was affected by this bug. 18760 * Apps targeting API levels greater than 17 will get the fixed, more strict 18761 * behavior.</p> 18762 * 18763 * @param size the size of the measure specification 18764 * @param mode the mode of the measure specification 18765 * @return the measure specification based on size and mode 18766 */ 18767 public static int makeMeasureSpec(int size, int mode) { 18768 if (sUseBrokenMakeMeasureSpec) { 18769 return size + mode; 18770 } else { 18771 return (size & ~MODE_MASK) | (mode & MODE_MASK); 18772 } 18773 } 18774 18775 /** 18776 * Extracts the mode from the supplied measure specification. 18777 * 18778 * @param measureSpec the measure specification to extract the mode from 18779 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 18780 * {@link android.view.View.MeasureSpec#AT_MOST} or 18781 * {@link android.view.View.MeasureSpec#EXACTLY} 18782 */ 18783 public static int getMode(int measureSpec) { 18784 return (measureSpec & MODE_MASK); 18785 } 18786 18787 /** 18788 * Extracts the size from the supplied measure specification. 18789 * 18790 * @param measureSpec the measure specification to extract the size from 18791 * @return the size in pixels defined in the supplied measure specification 18792 */ 18793 public static int getSize(int measureSpec) { 18794 return (measureSpec & ~MODE_MASK); 18795 } 18796 18797 static int adjust(int measureSpec, int delta) { 18798 return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec)); 18799 } 18800 18801 /** 18802 * Returns a String representation of the specified measure 18803 * specification. 18804 * 18805 * @param measureSpec the measure specification to convert to a String 18806 * @return a String with the following format: "MeasureSpec: MODE SIZE" 18807 */ 18808 public static String toString(int measureSpec) { 18809 int mode = getMode(measureSpec); 18810 int size = getSize(measureSpec); 18811 18812 StringBuilder sb = new StringBuilder("MeasureSpec: "); 18813 18814 if (mode == UNSPECIFIED) 18815 sb.append("UNSPECIFIED "); 18816 else if (mode == EXACTLY) 18817 sb.append("EXACTLY "); 18818 else if (mode == AT_MOST) 18819 sb.append("AT_MOST "); 18820 else 18821 sb.append(mode).append(" "); 18822 18823 sb.append(size); 18824 return sb.toString(); 18825 } 18826 } 18827 18828 class CheckForLongPress implements Runnable { 18829 18830 private int mOriginalWindowAttachCount; 18831 18832 public void run() { 18833 if (isPressed() && (mParent != null) 18834 && mOriginalWindowAttachCount == mWindowAttachCount) { 18835 if (performLongClick()) { 18836 mHasPerformedLongPress = true; 18837 } 18838 } 18839 } 18840 18841 public void rememberWindowAttachCount() { 18842 mOriginalWindowAttachCount = mWindowAttachCount; 18843 } 18844 } 18845 18846 private final class CheckForTap implements Runnable { 18847 public void run() { 18848 mPrivateFlags &= ~PFLAG_PREPRESSED; 18849 setPressed(true); 18850 checkForLongClick(ViewConfiguration.getTapTimeout()); 18851 } 18852 } 18853 18854 private final class PerformClick implements Runnable { 18855 public void run() { 18856 performClick(); 18857 } 18858 } 18859 18860 /** @hide */ 18861 public void hackTurnOffWindowResizeAnim(boolean off) { 18862 mAttachInfo.mTurnOffWindowResizeAnim = off; 18863 } 18864 18865 /** 18866 * This method returns a ViewPropertyAnimator object, which can be used to animate 18867 * specific properties on this View. 18868 * 18869 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 18870 */ 18871 public ViewPropertyAnimator animate() { 18872 if (mAnimator == null) { 18873 mAnimator = new ViewPropertyAnimator(this); 18874 } 18875 return mAnimator; 18876 } 18877 18878 /** 18879 * Specifies that the shared name of the View to be shared with another Activity. 18880 * When transitioning between Activities, the name links a UI element in the starting 18881 * Activity to UI element in the called Activity. Names should be unique in the 18882 * View hierarchy. 18883 * 18884 * @param sharedElementName The cross-Activity View identifier. The called Activity will use 18885 * the name to match the location with a View in its layout. 18886 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(android.os.Bundle) 18887 */ 18888 public void setSharedElementName(String sharedElementName) { 18889 setTagInternal(com.android.internal.R.id.shared_element_name, sharedElementName); 18890 } 18891 18892 /** 18893 * Returns the shared name of the View to be shared with another Activity. 18894 * When transitioning between Activities, the name links a UI element in the starting 18895 * Activity to UI element in the called Activity. Names should be unique in the 18896 * View hierarchy. 18897 * 18898 * <p>This returns null if the View is not a shared element or the name if it is.</p> 18899 * 18900 * @return The name used for this View for cross-Activity transitions or null if 18901 * this View has not been identified as shared. 18902 */ 18903 public String getSharedElementName() { 18904 return (String) getTag(com.android.internal.R.id.shared_element_name); 18905 } 18906 18907 /** 18908 * Interface definition for a callback to be invoked when a hardware key event is 18909 * dispatched to this view. The callback will be invoked before the key event is 18910 * given to the view. This is only useful for hardware keyboards; a software input 18911 * method has no obligation to trigger this listener. 18912 */ 18913 public interface OnKeyListener { 18914 /** 18915 * Called when a hardware key is dispatched to a view. This allows listeners to 18916 * get a chance to respond before the target view. 18917 * <p>Key presses in software keyboards will generally NOT trigger this method, 18918 * although some may elect to do so in some situations. Do not assume a 18919 * software input method has to be key-based; even if it is, it may use key presses 18920 * in a different way than you expect, so there is no way to reliably catch soft 18921 * input key presses. 18922 * 18923 * @param v The view the key has been dispatched to. 18924 * @param keyCode The code for the physical key that was pressed 18925 * @param event The KeyEvent object containing full information about 18926 * the event. 18927 * @return True if the listener has consumed the event, false otherwise. 18928 */ 18929 boolean onKey(View v, int keyCode, KeyEvent event); 18930 } 18931 18932 /** 18933 * Interface definition for a callback to be invoked when a touch event is 18934 * dispatched to this view. The callback will be invoked before the touch 18935 * event is given to the view. 18936 */ 18937 public interface OnTouchListener { 18938 /** 18939 * Called when a touch event is dispatched to a view. This allows listeners to 18940 * get a chance to respond before the target view. 18941 * 18942 * @param v The view the touch event has been dispatched to. 18943 * @param event The MotionEvent object containing full information about 18944 * the event. 18945 * @return True if the listener has consumed the event, false otherwise. 18946 */ 18947 boolean onTouch(View v, MotionEvent event); 18948 } 18949 18950 /** 18951 * Interface definition for a callback to be invoked when a hover event is 18952 * dispatched to this view. The callback will be invoked before the hover 18953 * event is given to the view. 18954 */ 18955 public interface OnHoverListener { 18956 /** 18957 * Called when a hover event is dispatched to a view. This allows listeners to 18958 * get a chance to respond before the target view. 18959 * 18960 * @param v The view the hover event has been dispatched to. 18961 * @param event The MotionEvent object containing full information about 18962 * the event. 18963 * @return True if the listener has consumed the event, false otherwise. 18964 */ 18965 boolean onHover(View v, MotionEvent event); 18966 } 18967 18968 /** 18969 * Interface definition for a callback to be invoked when a generic motion event is 18970 * dispatched to this view. The callback will be invoked before the generic motion 18971 * event is given to the view. 18972 */ 18973 public interface OnGenericMotionListener { 18974 /** 18975 * Called when a generic motion event is dispatched to a view. This allows listeners to 18976 * get a chance to respond before the target view. 18977 * 18978 * @param v The view the generic motion event has been dispatched to. 18979 * @param event The MotionEvent object containing full information about 18980 * the event. 18981 * @return True if the listener has consumed the event, false otherwise. 18982 */ 18983 boolean onGenericMotion(View v, MotionEvent event); 18984 } 18985 18986 /** 18987 * Interface definition for a callback to be invoked when a view has been clicked and held. 18988 */ 18989 public interface OnLongClickListener { 18990 /** 18991 * Called when a view has been clicked and held. 18992 * 18993 * @param v The view that was clicked and held. 18994 * 18995 * @return true if the callback consumed the long click, false otherwise. 18996 */ 18997 boolean onLongClick(View v); 18998 } 18999 19000 /** 19001 * Interface definition for a callback to be invoked when a drag is being dispatched 19002 * to this view. The callback will be invoked before the hosting view's own 19003 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19004 * onDrag(event) behavior, it should return 'false' from this callback. 19005 * 19006 * <div class="special reference"> 19007 * <h3>Developer Guides</h3> 19008 * <p>For a guide to implementing drag and drop features, read the 19009 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19010 * </div> 19011 */ 19012 public interface OnDragListener { 19013 /** 19014 * Called when a drag event is dispatched to a view. This allows listeners 19015 * to get a chance to override base View behavior. 19016 * 19017 * @param v The View that received the drag event. 19018 * @param event The {@link android.view.DragEvent} object for the drag event. 19019 * @return {@code true} if the drag event was handled successfully, or {@code false} 19020 * if the drag event was not handled. Note that {@code false} will trigger the View 19021 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19022 */ 19023 boolean onDrag(View v, DragEvent event); 19024 } 19025 19026 /** 19027 * Interface definition for a callback to be invoked when the focus state of 19028 * a view changed. 19029 */ 19030 public interface OnFocusChangeListener { 19031 /** 19032 * Called when the focus state of a view has changed. 19033 * 19034 * @param v The view whose state has changed. 19035 * @param hasFocus The new focus state of v. 19036 */ 19037 void onFocusChange(View v, boolean hasFocus); 19038 } 19039 19040 /** 19041 * Interface definition for a callback to be invoked when a view is clicked. 19042 */ 19043 public interface OnClickListener { 19044 /** 19045 * Called when a view has been clicked. 19046 * 19047 * @param v The view that was clicked. 19048 */ 19049 void onClick(View v); 19050 } 19051 19052 /** 19053 * Interface definition for a callback to be invoked when the context menu 19054 * for this view is being built. 19055 */ 19056 public interface OnCreateContextMenuListener { 19057 /** 19058 * Called when the context menu for this view is being built. It is not 19059 * safe to hold onto the menu after this method returns. 19060 * 19061 * @param menu The context menu that is being built 19062 * @param v The view for which the context menu is being built 19063 * @param menuInfo Extra information about the item for which the 19064 * context menu should be shown. This information will vary 19065 * depending on the class of v. 19066 */ 19067 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19068 } 19069 19070 /** 19071 * Interface definition for a callback to be invoked when the status bar changes 19072 * visibility. This reports <strong>global</strong> changes to the system UI 19073 * state, not what the application is requesting. 19074 * 19075 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19076 */ 19077 public interface OnSystemUiVisibilityChangeListener { 19078 /** 19079 * Called when the status bar changes visibility because of a call to 19080 * {@link View#setSystemUiVisibility(int)}. 19081 * 19082 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19083 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19084 * This tells you the <strong>global</strong> state of these UI visibility 19085 * flags, not what your app is currently applying. 19086 */ 19087 public void onSystemUiVisibilityChange(int visibility); 19088 } 19089 19090 /** 19091 * Interface definition for a callback to be invoked when this view is attached 19092 * or detached from its window. 19093 */ 19094 public interface OnAttachStateChangeListener { 19095 /** 19096 * Called when the view is attached to a window. 19097 * @param v The view that was attached 19098 */ 19099 public void onViewAttachedToWindow(View v); 19100 /** 19101 * Called when the view is detached from a window. 19102 * @param v The view that was detached 19103 */ 19104 public void onViewDetachedFromWindow(View v); 19105 } 19106 19107 private final class UnsetPressedState implements Runnable { 19108 public void run() { 19109 setPressed(false); 19110 } 19111 } 19112 19113 /** 19114 * Base class for derived classes that want to save and restore their own 19115 * state in {@link android.view.View#onSaveInstanceState()}. 19116 */ 19117 public static class BaseSavedState extends AbsSavedState { 19118 /** 19119 * Constructor used when reading from a parcel. Reads the state of the superclass. 19120 * 19121 * @param source 19122 */ 19123 public BaseSavedState(Parcel source) { 19124 super(source); 19125 } 19126 19127 /** 19128 * Constructor called by derived classes when creating their SavedState objects 19129 * 19130 * @param superState The state of the superclass of this view 19131 */ 19132 public BaseSavedState(Parcelable superState) { 19133 super(superState); 19134 } 19135 19136 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19137 new Parcelable.Creator<BaseSavedState>() { 19138 public BaseSavedState createFromParcel(Parcel in) { 19139 return new BaseSavedState(in); 19140 } 19141 19142 public BaseSavedState[] newArray(int size) { 19143 return new BaseSavedState[size]; 19144 } 19145 }; 19146 } 19147 19148 /** 19149 * A set of information given to a view when it is attached to its parent 19150 * window. 19151 */ 19152 static class AttachInfo { 19153 interface Callbacks { 19154 void playSoundEffect(int effectId); 19155 boolean performHapticFeedback(int effectId, boolean always); 19156 } 19157 19158 /** 19159 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19160 * to a Handler. This class contains the target (View) to invalidate and 19161 * the coordinates of the dirty rectangle. 19162 * 19163 * For performance purposes, this class also implements a pool of up to 19164 * POOL_LIMIT objects that get reused. This reduces memory allocations 19165 * whenever possible. 19166 */ 19167 static class InvalidateInfo { 19168 private static final int POOL_LIMIT = 10; 19169 19170 private static final SynchronizedPool<InvalidateInfo> sPool = 19171 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19172 19173 View target; 19174 19175 int left; 19176 int top; 19177 int right; 19178 int bottom; 19179 19180 public static InvalidateInfo obtain() { 19181 InvalidateInfo instance = sPool.acquire(); 19182 return (instance != null) ? instance : new InvalidateInfo(); 19183 } 19184 19185 public void recycle() { 19186 target = null; 19187 sPool.release(this); 19188 } 19189 } 19190 19191 final IWindowSession mSession; 19192 19193 final IWindow mWindow; 19194 19195 final IBinder mWindowToken; 19196 19197 final Display mDisplay; 19198 19199 final Callbacks mRootCallbacks; 19200 19201 IWindowId mIWindowId; 19202 WindowId mWindowId; 19203 19204 /** 19205 * The top view of the hierarchy. 19206 */ 19207 View mRootView; 19208 19209 IBinder mPanelParentWindowToken; 19210 19211 boolean mHardwareAccelerated; 19212 boolean mHardwareAccelerationRequested; 19213 HardwareRenderer mHardwareRenderer; 19214 19215 boolean mScreenOn; 19216 19217 /** 19218 * Scale factor used by the compatibility mode 19219 */ 19220 float mApplicationScale; 19221 19222 /** 19223 * Indicates whether the application is in compatibility mode 19224 */ 19225 boolean mScalingRequired; 19226 19227 /** 19228 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19229 */ 19230 boolean mTurnOffWindowResizeAnim; 19231 19232 /** 19233 * Left position of this view's window 19234 */ 19235 int mWindowLeft; 19236 19237 /** 19238 * Top position of this view's window 19239 */ 19240 int mWindowTop; 19241 19242 /** 19243 * Indicates whether views need to use 32-bit drawing caches 19244 */ 19245 boolean mUse32BitDrawingCache; 19246 19247 /** 19248 * For windows that are full-screen but using insets to layout inside 19249 * of the screen areas, these are the current insets to appear inside 19250 * the overscan area of the display. 19251 */ 19252 final Rect mOverscanInsets = new Rect(); 19253 19254 /** 19255 * For windows that are full-screen but using insets to layout inside 19256 * of the screen decorations, these are the current insets for the 19257 * content of the window. 19258 */ 19259 final Rect mContentInsets = new Rect(); 19260 19261 /** 19262 * For windows that are full-screen but using insets to layout inside 19263 * of the screen decorations, these are the current insets for the 19264 * actual visible parts of the window. 19265 */ 19266 final Rect mVisibleInsets = new Rect(); 19267 19268 /** 19269 * The internal insets given by this window. This value is 19270 * supplied by the client (through 19271 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19272 * be given to the window manager when changed to be used in laying 19273 * out windows behind it. 19274 */ 19275 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19276 = new ViewTreeObserver.InternalInsetsInfo(); 19277 19278 /** 19279 * Set to true when mGivenInternalInsets is non-empty. 19280 */ 19281 boolean mHasNonEmptyGivenInternalInsets; 19282 19283 /** 19284 * All views in the window's hierarchy that serve as scroll containers, 19285 * used to determine if the window can be resized or must be panned 19286 * to adjust for a soft input area. 19287 */ 19288 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19289 19290 final KeyEvent.DispatcherState mKeyDispatchState 19291 = new KeyEvent.DispatcherState(); 19292 19293 /** 19294 * Indicates whether the view's window currently has the focus. 19295 */ 19296 boolean mHasWindowFocus; 19297 19298 /** 19299 * The current visibility of the window. 19300 */ 19301 int mWindowVisibility; 19302 19303 /** 19304 * Indicates the time at which drawing started to occur. 19305 */ 19306 long mDrawingTime; 19307 19308 /** 19309 * Indicates whether or not ignoring the DIRTY_MASK flags. 19310 */ 19311 boolean mIgnoreDirtyState; 19312 19313 /** 19314 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19315 * to avoid clearing that flag prematurely. 19316 */ 19317 boolean mSetIgnoreDirtyState = false; 19318 19319 /** 19320 * Indicates whether the view's window is currently in touch mode. 19321 */ 19322 boolean mInTouchMode; 19323 19324 /** 19325 * Indicates that ViewAncestor should trigger a global layout change 19326 * the next time it performs a traversal 19327 */ 19328 boolean mRecomputeGlobalAttributes; 19329 19330 /** 19331 * Always report new attributes at next traversal. 19332 */ 19333 boolean mForceReportNewAttributes; 19334 19335 /** 19336 * Set during a traveral if any views want to keep the screen on. 19337 */ 19338 boolean mKeepScreenOn; 19339 19340 /** 19341 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19342 */ 19343 int mSystemUiVisibility; 19344 19345 /** 19346 * Hack to force certain system UI visibility flags to be cleared. 19347 */ 19348 int mDisabledSystemUiVisibility; 19349 19350 /** 19351 * Last global system UI visibility reported by the window manager. 19352 */ 19353 int mGlobalSystemUiVisibility; 19354 19355 /** 19356 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19357 * attached. 19358 */ 19359 boolean mHasSystemUiListeners; 19360 19361 /** 19362 * Set if the window has requested to extend into the overscan region 19363 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19364 */ 19365 boolean mOverscanRequested; 19366 19367 /** 19368 * Set if the visibility of any views has changed. 19369 */ 19370 boolean mViewVisibilityChanged; 19371 19372 /** 19373 * Set to true if a view has been scrolled. 19374 */ 19375 boolean mViewScrollChanged; 19376 19377 /** 19378 * Global to the view hierarchy used as a temporary for dealing with 19379 * x/y points in the transparent region computations. 19380 */ 19381 final int[] mTransparentLocation = new int[2]; 19382 19383 /** 19384 * Global to the view hierarchy used as a temporary for dealing with 19385 * x/y points in the ViewGroup.invalidateChild implementation. 19386 */ 19387 final int[] mInvalidateChildLocation = new int[2]; 19388 19389 19390 /** 19391 * Global to the view hierarchy used as a temporary for dealing with 19392 * x/y location when view is transformed. 19393 */ 19394 final float[] mTmpTransformLocation = new float[2]; 19395 19396 /** 19397 * The view tree observer used to dispatch global events like 19398 * layout, pre-draw, touch mode change, etc. 19399 */ 19400 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19401 19402 /** 19403 * A Canvas used by the view hierarchy to perform bitmap caching. 19404 */ 19405 Canvas mCanvas; 19406 19407 /** 19408 * The view root impl. 19409 */ 19410 final ViewRootImpl mViewRootImpl; 19411 19412 /** 19413 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19414 * handler can be used to pump events in the UI events queue. 19415 */ 19416 final Handler mHandler; 19417 19418 /** 19419 * Temporary for use in computing invalidate rectangles while 19420 * calling up the hierarchy. 19421 */ 19422 final Rect mTmpInvalRect = new Rect(); 19423 19424 /** 19425 * Temporary for use in computing hit areas with transformed views 19426 */ 19427 final RectF mTmpTransformRect = new RectF(); 19428 19429 /** 19430 * Temporary for use in transforming invalidation rect 19431 */ 19432 final Matrix mTmpMatrix = new Matrix(); 19433 19434 /** 19435 * Temporary for use in transforming invalidation rect 19436 */ 19437 final Transformation mTmpTransformation = new Transformation(); 19438 19439 /** 19440 * Temporary list for use in collecting focusable descendents of a view. 19441 */ 19442 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19443 19444 /** 19445 * The id of the window for accessibility purposes. 19446 */ 19447 int mAccessibilityWindowId = View.NO_ID; 19448 19449 /** 19450 * Flags related to accessibility processing. 19451 * 19452 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 19453 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 19454 */ 19455 int mAccessibilityFetchFlags; 19456 19457 /** 19458 * The drawable for highlighting accessibility focus. 19459 */ 19460 Drawable mAccessibilityFocusDrawable; 19461 19462 /** 19463 * Show where the margins, bounds and layout bounds are for each view. 19464 */ 19465 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 19466 19467 /** 19468 * Point used to compute visible regions. 19469 */ 19470 final Point mPoint = new Point(); 19471 19472 /** 19473 * Used to track which View originated a requestLayout() call, used when 19474 * requestLayout() is called during layout. 19475 */ 19476 View mViewRequestingLayout; 19477 19478 /** 19479 * Creates a new set of attachment information with the specified 19480 * events handler and thread. 19481 * 19482 * @param handler the events handler the view must use 19483 */ 19484 AttachInfo(IWindowSession session, IWindow window, Display display, 19485 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 19486 mSession = session; 19487 mWindow = window; 19488 mWindowToken = window.asBinder(); 19489 mDisplay = display; 19490 mViewRootImpl = viewRootImpl; 19491 mHandler = handler; 19492 mRootCallbacks = effectPlayer; 19493 } 19494 } 19495 19496 /** 19497 * <p>ScrollabilityCache holds various fields used by a View when scrolling 19498 * is supported. This avoids keeping too many unused fields in most 19499 * instances of View.</p> 19500 */ 19501 private static class ScrollabilityCache implements Runnable { 19502 19503 /** 19504 * Scrollbars are not visible 19505 */ 19506 public static final int OFF = 0; 19507 19508 /** 19509 * Scrollbars are visible 19510 */ 19511 public static final int ON = 1; 19512 19513 /** 19514 * Scrollbars are fading away 19515 */ 19516 public static final int FADING = 2; 19517 19518 public boolean fadeScrollBars; 19519 19520 public int fadingEdgeLength; 19521 public int scrollBarDefaultDelayBeforeFade; 19522 public int scrollBarFadeDuration; 19523 19524 public int scrollBarSize; 19525 public ScrollBarDrawable scrollBar; 19526 public float[] interpolatorValues; 19527 public View host; 19528 19529 public final Paint paint; 19530 public final Matrix matrix; 19531 public Shader shader; 19532 19533 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 19534 19535 private static final float[] OPAQUE = { 255 }; 19536 private static final float[] TRANSPARENT = { 0.0f }; 19537 19538 /** 19539 * When fading should start. This time moves into the future every time 19540 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 19541 */ 19542 public long fadeStartTime; 19543 19544 19545 /** 19546 * The current state of the scrollbars: ON, OFF, or FADING 19547 */ 19548 public int state = OFF; 19549 19550 private int mLastColor; 19551 19552 public ScrollabilityCache(ViewConfiguration configuration, View host) { 19553 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 19554 scrollBarSize = configuration.getScaledScrollBarSize(); 19555 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 19556 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 19557 19558 paint = new Paint(); 19559 matrix = new Matrix(); 19560 // use use a height of 1, and then wack the matrix each time we 19561 // actually use it. 19562 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 19563 paint.setShader(shader); 19564 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 19565 19566 this.host = host; 19567 } 19568 19569 public void setFadeColor(int color) { 19570 if (color != mLastColor) { 19571 mLastColor = color; 19572 19573 if (color != 0) { 19574 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 19575 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 19576 paint.setShader(shader); 19577 // Restore the default transfer mode (src_over) 19578 paint.setXfermode(null); 19579 } else { 19580 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 19581 paint.setShader(shader); 19582 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 19583 } 19584 } 19585 } 19586 19587 public void run() { 19588 long now = AnimationUtils.currentAnimationTimeMillis(); 19589 if (now >= fadeStartTime) { 19590 19591 // the animation fades the scrollbars out by changing 19592 // the opacity (alpha) from fully opaque to fully 19593 // transparent 19594 int nextFrame = (int) now; 19595 int framesCount = 0; 19596 19597 Interpolator interpolator = scrollBarInterpolator; 19598 19599 // Start opaque 19600 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 19601 19602 // End transparent 19603 nextFrame += scrollBarFadeDuration; 19604 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 19605 19606 state = FADING; 19607 19608 // Kick off the fade animation 19609 host.invalidate(true); 19610 } 19611 } 19612 } 19613 19614 /** 19615 * Resuable callback for sending 19616 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 19617 */ 19618 private class SendViewScrolledAccessibilityEvent implements Runnable { 19619 public volatile boolean mIsPending; 19620 19621 public void run() { 19622 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 19623 mIsPending = false; 19624 } 19625 } 19626 19627 /** 19628 * <p> 19629 * This class represents a delegate that can be registered in a {@link View} 19630 * to enhance accessibility support via composition rather via inheritance. 19631 * It is specifically targeted to widget developers that extend basic View 19632 * classes i.e. classes in package android.view, that would like their 19633 * applications to be backwards compatible. 19634 * </p> 19635 * <div class="special reference"> 19636 * <h3>Developer Guides</h3> 19637 * <p>For more information about making applications accessible, read the 19638 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 19639 * developer guide.</p> 19640 * </div> 19641 * <p> 19642 * A scenario in which a developer would like to use an accessibility delegate 19643 * is overriding a method introduced in a later API version then the minimal API 19644 * version supported by the application. For example, the method 19645 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 19646 * in API version 4 when the accessibility APIs were first introduced. If a 19647 * developer would like his application to run on API version 4 devices (assuming 19648 * all other APIs used by the application are version 4 or lower) and take advantage 19649 * of this method, instead of overriding the method which would break the application's 19650 * backwards compatibility, he can override the corresponding method in this 19651 * delegate and register the delegate in the target View if the API version of 19652 * the system is high enough i.e. the API version is same or higher to the API 19653 * version that introduced 19654 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 19655 * </p> 19656 * <p> 19657 * Here is an example implementation: 19658 * </p> 19659 * <code><pre><p> 19660 * if (Build.VERSION.SDK_INT >= 14) { 19661 * // If the API version is equal of higher than the version in 19662 * // which onInitializeAccessibilityNodeInfo was introduced we 19663 * // register a delegate with a customized implementation. 19664 * View view = findViewById(R.id.view_id); 19665 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 19666 * public void onInitializeAccessibilityNodeInfo(View host, 19667 * AccessibilityNodeInfo info) { 19668 * // Let the default implementation populate the info. 19669 * super.onInitializeAccessibilityNodeInfo(host, info); 19670 * // Set some other information. 19671 * info.setEnabled(host.isEnabled()); 19672 * } 19673 * }); 19674 * } 19675 * </code></pre></p> 19676 * <p> 19677 * This delegate contains methods that correspond to the accessibility methods 19678 * in View. If a delegate has been specified the implementation in View hands 19679 * off handling to the corresponding method in this delegate. The default 19680 * implementation the delegate methods behaves exactly as the corresponding 19681 * method in View for the case of no accessibility delegate been set. Hence, 19682 * to customize the behavior of a View method, clients can override only the 19683 * corresponding delegate method without altering the behavior of the rest 19684 * accessibility related methods of the host view. 19685 * </p> 19686 */ 19687 public static class AccessibilityDelegate { 19688 19689 /** 19690 * Sends an accessibility event of the given type. If accessibility is not 19691 * enabled this method has no effect. 19692 * <p> 19693 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 19694 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 19695 * been set. 19696 * </p> 19697 * 19698 * @param host The View hosting the delegate. 19699 * @param eventType The type of the event to send. 19700 * 19701 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 19702 */ 19703 public void sendAccessibilityEvent(View host, int eventType) { 19704 host.sendAccessibilityEventInternal(eventType); 19705 } 19706 19707 /** 19708 * Performs the specified accessibility action on the view. For 19709 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 19710 * <p> 19711 * The default implementation behaves as 19712 * {@link View#performAccessibilityAction(int, Bundle) 19713 * View#performAccessibilityAction(int, Bundle)} for the case of 19714 * no accessibility delegate been set. 19715 * </p> 19716 * 19717 * @param action The action to perform. 19718 * @return Whether the action was performed. 19719 * 19720 * @see View#performAccessibilityAction(int, Bundle) 19721 * View#performAccessibilityAction(int, Bundle) 19722 */ 19723 public boolean performAccessibilityAction(View host, int action, Bundle args) { 19724 return host.performAccessibilityActionInternal(action, args); 19725 } 19726 19727 /** 19728 * Sends an accessibility event. This method behaves exactly as 19729 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 19730 * empty {@link AccessibilityEvent} and does not perform a check whether 19731 * accessibility is enabled. 19732 * <p> 19733 * The default implementation behaves as 19734 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19735 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 19736 * the case of no accessibility delegate been set. 19737 * </p> 19738 * 19739 * @param host The View hosting the delegate. 19740 * @param event The event to send. 19741 * 19742 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19743 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19744 */ 19745 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 19746 host.sendAccessibilityEventUncheckedInternal(event); 19747 } 19748 19749 /** 19750 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 19751 * to its children for adding their text content to the event. 19752 * <p> 19753 * The default implementation behaves as 19754 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19755 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 19756 * the case of no accessibility delegate been set. 19757 * </p> 19758 * 19759 * @param host The View hosting the delegate. 19760 * @param event The event. 19761 * @return True if the event population was completed. 19762 * 19763 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19764 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19765 */ 19766 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 19767 return host.dispatchPopulateAccessibilityEventInternal(event); 19768 } 19769 19770 /** 19771 * Gives a chance to the host View to populate the accessibility event with its 19772 * text content. 19773 * <p> 19774 * The default implementation behaves as 19775 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 19776 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 19777 * the case of no accessibility delegate been set. 19778 * </p> 19779 * 19780 * @param host The View hosting the delegate. 19781 * @param event The accessibility event which to populate. 19782 * 19783 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 19784 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 19785 */ 19786 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 19787 host.onPopulateAccessibilityEventInternal(event); 19788 } 19789 19790 /** 19791 * Initializes an {@link AccessibilityEvent} with information about the 19792 * the host View which is the event source. 19793 * <p> 19794 * The default implementation behaves as 19795 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 19796 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 19797 * the case of no accessibility delegate been set. 19798 * </p> 19799 * 19800 * @param host The View hosting the delegate. 19801 * @param event The event to initialize. 19802 * 19803 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 19804 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 19805 */ 19806 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 19807 host.onInitializeAccessibilityEventInternal(event); 19808 } 19809 19810 /** 19811 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 19812 * <p> 19813 * The default implementation behaves as 19814 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19815 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 19816 * the case of no accessibility delegate been set. 19817 * </p> 19818 * 19819 * @param host The View hosting the delegate. 19820 * @param info The instance to initialize. 19821 * 19822 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19823 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19824 */ 19825 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 19826 host.onInitializeAccessibilityNodeInfoInternal(info); 19827 } 19828 19829 /** 19830 * Called when a child of the host View has requested sending an 19831 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 19832 * to augment the event. 19833 * <p> 19834 * The default implementation behaves as 19835 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19836 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 19837 * the case of no accessibility delegate been set. 19838 * </p> 19839 * 19840 * @param host The View hosting the delegate. 19841 * @param child The child which requests sending the event. 19842 * @param event The event to be sent. 19843 * @return True if the event should be sent 19844 * 19845 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19846 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19847 */ 19848 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 19849 AccessibilityEvent event) { 19850 return host.onRequestSendAccessibilityEventInternal(child, event); 19851 } 19852 19853 /** 19854 * Gets the provider for managing a virtual view hierarchy rooted at this View 19855 * and reported to {@link android.accessibilityservice.AccessibilityService}s 19856 * that explore the window content. 19857 * <p> 19858 * The default implementation behaves as 19859 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 19860 * the case of no accessibility delegate been set. 19861 * </p> 19862 * 19863 * @return The provider. 19864 * 19865 * @see AccessibilityNodeProvider 19866 */ 19867 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 19868 return null; 19869 } 19870 19871 /** 19872 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 19873 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 19874 * This method is responsible for obtaining an accessibility node info from a 19875 * pool of reusable instances and calling 19876 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 19877 * view to initialize the former. 19878 * <p> 19879 * <strong>Note:</strong> The client is responsible for recycling the obtained 19880 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 19881 * creation. 19882 * </p> 19883 * <p> 19884 * The default implementation behaves as 19885 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 19886 * the case of no accessibility delegate been set. 19887 * </p> 19888 * @return A populated {@link AccessibilityNodeInfo}. 19889 * 19890 * @see AccessibilityNodeInfo 19891 * 19892 * @hide 19893 */ 19894 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 19895 return host.createAccessibilityNodeInfoInternal(); 19896 } 19897 } 19898 19899 private class MatchIdPredicate implements Predicate<View> { 19900 public int mId; 19901 19902 @Override 19903 public boolean apply(View view) { 19904 return (view.mID == mId); 19905 } 19906 } 19907 19908 private class MatchLabelForPredicate implements Predicate<View> { 19909 private int mLabeledId; 19910 19911 @Override 19912 public boolean apply(View view) { 19913 return (view.mLabelForId == mLabeledId); 19914 } 19915 } 19916 19917 private class SendViewStateChangedAccessibilityEvent implements Runnable { 19918 private int mChangeTypes = 0; 19919 private boolean mPosted; 19920 private boolean mPostedWithDelay; 19921 private long mLastEventTimeMillis; 19922 19923 @Override 19924 public void run() { 19925 mPosted = false; 19926 mPostedWithDelay = false; 19927 mLastEventTimeMillis = SystemClock.uptimeMillis(); 19928 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 19929 final AccessibilityEvent event = AccessibilityEvent.obtain(); 19930 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 19931 event.setContentChangeTypes(mChangeTypes); 19932 sendAccessibilityEventUnchecked(event); 19933 } 19934 mChangeTypes = 0; 19935 } 19936 19937 public void runOrPost(int changeType) { 19938 mChangeTypes |= changeType; 19939 19940 // If this is a live region or the child of a live region, collect 19941 // all events from this frame and send them on the next frame. 19942 if (inLiveRegion()) { 19943 // If we're already posted with a delay, remove that. 19944 if (mPostedWithDelay) { 19945 removeCallbacks(this); 19946 mPostedWithDelay = false; 19947 } 19948 // Only post if we're not already posted. 19949 if (!mPosted) { 19950 post(this); 19951 mPosted = true; 19952 } 19953 return; 19954 } 19955 19956 if (mPosted) { 19957 return; 19958 } 19959 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 19960 final long minEventIntevalMillis = 19961 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 19962 if (timeSinceLastMillis >= minEventIntevalMillis) { 19963 removeCallbacks(this); 19964 run(); 19965 } else { 19966 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 19967 mPosted = true; 19968 mPostedWithDelay = true; 19969 } 19970 } 19971 } 19972 19973 private boolean inLiveRegion() { 19974 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 19975 return true; 19976 } 19977 19978 ViewParent parent = getParent(); 19979 while (parent instanceof View) { 19980 if (((View) parent).getAccessibilityLiveRegion() 19981 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 19982 return true; 19983 } 19984 parent = parent.getParent(); 19985 } 19986 19987 return false; 19988 } 19989 19990 /** 19991 * Dump all private flags in readable format, useful for documentation and 19992 * sanity checking. 19993 */ 19994 private static void dumpFlags() { 19995 final HashMap<String, String> found = Maps.newHashMap(); 19996 try { 19997 for (Field field : View.class.getDeclaredFields()) { 19998 final int modifiers = field.getModifiers(); 19999 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20000 if (field.getType().equals(int.class)) { 20001 final int value = field.getInt(null); 20002 dumpFlag(found, field.getName(), value); 20003 } else if (field.getType().equals(int[].class)) { 20004 final int[] values = (int[]) field.get(null); 20005 for (int i = 0; i < values.length; i++) { 20006 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20007 } 20008 } 20009 } 20010 } 20011 } catch (IllegalAccessException e) { 20012 throw new RuntimeException(e); 20013 } 20014 20015 final ArrayList<String> keys = Lists.newArrayList(); 20016 keys.addAll(found.keySet()); 20017 Collections.sort(keys); 20018 for (String key : keys) { 20019 Log.d(VIEW_LOG_TAG, found.get(key)); 20020 } 20021 } 20022 20023 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20024 // Sort flags by prefix, then by bits, always keeping unique keys 20025 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20026 final int prefix = name.indexOf('_'); 20027 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20028 final String output = bits + " " + name; 20029 found.put(key, output); 20030 } 20031} 20032