View.java revision d82c8ac4db7091d2e976af4c89a1734465d20cd2
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.content.ClipData; 20import android.content.Context; 21import android.content.res.Configuration; 22import android.content.res.Resources; 23import android.content.res.TypedArray; 24import android.graphics.Bitmap; 25import android.graphics.Camera; 26import android.graphics.Canvas; 27import android.graphics.Insets; 28import android.graphics.Interpolator; 29import android.graphics.LinearGradient; 30import android.graphics.Matrix; 31import android.graphics.Paint; 32import android.graphics.PixelFormat; 33import android.graphics.Point; 34import android.graphics.PorterDuff; 35import android.graphics.PorterDuffXfermode; 36import android.graphics.Rect; 37import android.graphics.RectF; 38import android.graphics.Region; 39import android.graphics.Shader; 40import android.graphics.drawable.ColorDrawable; 41import android.graphics.drawable.Drawable; 42import android.hardware.display.DisplayManagerGlobal; 43import android.os.Bundle; 44import android.os.Handler; 45import android.os.IBinder; 46import android.os.Parcel; 47import android.os.Parcelable; 48import android.os.RemoteException; 49import android.os.SystemClock; 50import android.os.SystemProperties; 51import android.text.TextUtils; 52import android.util.AttributeSet; 53import android.util.FloatProperty; 54import android.util.LayoutDirection; 55import android.util.Log; 56import android.util.LongSparseLongArray; 57import android.util.Pools.SynchronizedPool; 58import android.util.Property; 59import android.util.SparseArray; 60import android.util.TypedValue; 61import android.view.ContextMenu.ContextMenuInfo; 62import android.view.AccessibilityIterators.TextSegmentIterator; 63import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 64import android.view.AccessibilityIterators.WordTextSegmentIterator; 65import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 66import android.view.accessibility.AccessibilityEvent; 67import android.view.accessibility.AccessibilityEventSource; 68import android.view.accessibility.AccessibilityManager; 69import android.view.accessibility.AccessibilityNodeInfo; 70import android.view.accessibility.AccessibilityNodeProvider; 71import android.view.animation.Animation; 72import android.view.animation.AnimationUtils; 73import android.view.animation.Transformation; 74import android.view.inputmethod.EditorInfo; 75import android.view.inputmethod.InputConnection; 76import android.view.inputmethod.InputMethodManager; 77import android.widget.ScrollBarDrawable; 78 79import static android.os.Build.VERSION_CODES.*; 80import static java.lang.Math.max; 81 82import com.android.internal.R; 83import com.android.internal.util.Predicate; 84import com.android.internal.view.menu.MenuBuilder; 85import com.google.android.collect.Lists; 86import com.google.android.collect.Maps; 87 88import java.lang.ref.WeakReference; 89import java.lang.reflect.Field; 90import java.lang.reflect.InvocationTargetException; 91import java.lang.reflect.Method; 92import java.lang.reflect.Modifier; 93import java.util.ArrayList; 94import java.util.Arrays; 95import java.util.Collections; 96import java.util.HashMap; 97import java.util.Locale; 98import java.util.concurrent.CopyOnWriteArrayList; 99import java.util.concurrent.atomic.AtomicInteger; 100 101/** 102 * <p> 103 * This class represents the basic building block for user interface components. A View 104 * occupies a rectangular area on the screen and is responsible for drawing and 105 * event handling. View is the base class for <em>widgets</em>, which are 106 * used to create interactive UI components (buttons, text fields, etc.). The 107 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 108 * are invisible containers that hold other Views (or other ViewGroups) and define 109 * their layout properties. 110 * </p> 111 * 112 * <div class="special reference"> 113 * <h3>Developer Guides</h3> 114 * <p>For information about using this class to develop your application's user interface, 115 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 116 * </div> 117 * 118 * <a name="Using"></a> 119 * <h3>Using Views</h3> 120 * <p> 121 * All of the views in a window are arranged in a single tree. You can add views 122 * either from code or by specifying a tree of views in one or more XML layout 123 * files. There are many specialized subclasses of views that act as controls or 124 * are capable of displaying text, images, or other content. 125 * </p> 126 * <p> 127 * Once you have created a tree of views, there are typically a few types of 128 * common operations you may wish to perform: 129 * <ul> 130 * <li><strong>Set properties:</strong> for example setting the text of a 131 * {@link android.widget.TextView}. The available properties and the methods 132 * that set them will vary among the different subclasses of views. Note that 133 * properties that are known at build time can be set in the XML layout 134 * files.</li> 135 * <li><strong>Set focus:</strong> The framework will handled moving focus in 136 * response to user input. To force focus to a specific view, call 137 * {@link #requestFocus}.</li> 138 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 139 * that will be notified when something interesting happens to the view. For 140 * example, all views will let you set a listener to be notified when the view 141 * gains or loses focus. You can register such a listener using 142 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 143 * Other view subclasses offer more specialized listeners. For example, a Button 144 * exposes a listener to notify clients when the button is clicked.</li> 145 * <li><strong>Set visibility:</strong> You can hide or show views using 146 * {@link #setVisibility(int)}.</li> 147 * </ul> 148 * </p> 149 * <p><em> 150 * Note: The Android framework is responsible for measuring, laying out and 151 * drawing views. You should not call methods that perform these actions on 152 * views yourself unless you are actually implementing a 153 * {@link android.view.ViewGroup}. 154 * </em></p> 155 * 156 * <a name="Lifecycle"></a> 157 * <h3>Implementing a Custom View</h3> 158 * 159 * <p> 160 * To implement a custom view, you will usually begin by providing overrides for 161 * some of the standard methods that the framework calls on all views. You do 162 * not need to override all of these methods. In fact, you can start by just 163 * overriding {@link #onDraw(android.graphics.Canvas)}. 164 * <table border="2" width="85%" align="center" cellpadding="5"> 165 * <thead> 166 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 167 * </thead> 168 * 169 * <tbody> 170 * <tr> 171 * <td rowspan="2">Creation</td> 172 * <td>Constructors</td> 173 * <td>There is a form of the constructor that are called when the view 174 * is created from code and a form that is called when the view is 175 * inflated from a layout file. The second form should parse and apply 176 * any attributes defined in the layout file. 177 * </td> 178 * </tr> 179 * <tr> 180 * <td><code>{@link #onFinishInflate()}</code></td> 181 * <td>Called after a view and all of its children has been inflated 182 * from XML.</td> 183 * </tr> 184 * 185 * <tr> 186 * <td rowspan="3">Layout</td> 187 * <td><code>{@link #onMeasure(int, int)}</code></td> 188 * <td>Called to determine the size requirements for this view and all 189 * of its children. 190 * </td> 191 * </tr> 192 * <tr> 193 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 194 * <td>Called when this view should assign a size and position to all 195 * of its children. 196 * </td> 197 * </tr> 198 * <tr> 199 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 200 * <td>Called when the size of this view has changed. 201 * </td> 202 * </tr> 203 * 204 * <tr> 205 * <td>Drawing</td> 206 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 207 * <td>Called when the view should render its content. 208 * </td> 209 * </tr> 210 * 211 * <tr> 212 * <td rowspan="4">Event processing</td> 213 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 214 * <td>Called when a new hardware key event occurs. 215 * </td> 216 * </tr> 217 * <tr> 218 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 219 * <td>Called when a hardware key up event occurs. 220 * </td> 221 * </tr> 222 * <tr> 223 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 224 * <td>Called when a trackball motion event occurs. 225 * </td> 226 * </tr> 227 * <tr> 228 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 229 * <td>Called when a touch screen motion event occurs. 230 * </td> 231 * </tr> 232 * 233 * <tr> 234 * <td rowspan="2">Focus</td> 235 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 236 * <td>Called when the view gains or loses focus. 237 * </td> 238 * </tr> 239 * 240 * <tr> 241 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 242 * <td>Called when the window containing the view gains or loses focus. 243 * </td> 244 * </tr> 245 * 246 * <tr> 247 * <td rowspan="3">Attaching</td> 248 * <td><code>{@link #onAttachedToWindow()}</code></td> 249 * <td>Called when the view is attached to a window. 250 * </td> 251 * </tr> 252 * 253 * <tr> 254 * <td><code>{@link #onDetachedFromWindow}</code></td> 255 * <td>Called when the view is detached from its window. 256 * </td> 257 * </tr> 258 * 259 * <tr> 260 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 261 * <td>Called when the visibility of the window containing the view 262 * has changed. 263 * </td> 264 * </tr> 265 * </tbody> 266 * 267 * </table> 268 * </p> 269 * 270 * <a name="IDs"></a> 271 * <h3>IDs</h3> 272 * Views may have an integer id associated with them. These ids are typically 273 * assigned in the layout XML files, and are used to find specific views within 274 * the view tree. A common pattern is to: 275 * <ul> 276 * <li>Define a Button in the layout file and assign it a unique ID. 277 * <pre> 278 * <Button 279 * android:id="@+id/my_button" 280 * android:layout_width="wrap_content" 281 * android:layout_height="wrap_content" 282 * android:text="@string/my_button_text"/> 283 * </pre></li> 284 * <li>From the onCreate method of an Activity, find the Button 285 * <pre class="prettyprint"> 286 * Button myButton = (Button) findViewById(R.id.my_button); 287 * </pre></li> 288 * </ul> 289 * <p> 290 * View IDs need not be unique throughout the tree, but it is good practice to 291 * ensure that they are at least unique within the part of the tree you are 292 * searching. 293 * </p> 294 * 295 * <a name="Position"></a> 296 * <h3>Position</h3> 297 * <p> 298 * The geometry of a view is that of a rectangle. A view has a location, 299 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 300 * two dimensions, expressed as a width and a height. The unit for location 301 * and dimensions is the pixel. 302 * </p> 303 * 304 * <p> 305 * It is possible to retrieve the location of a view by invoking the methods 306 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 307 * coordinate of the rectangle representing the view. The latter returns the 308 * top, or Y, coordinate of the rectangle representing the view. These methods 309 * both return the location of the view relative to its parent. For instance, 310 * when getLeft() returns 20, that means the view is located 20 pixels to the 311 * right of the left edge of its direct parent. 312 * </p> 313 * 314 * <p> 315 * In addition, several convenience methods are offered to avoid unnecessary 316 * computations, namely {@link #getRight()} and {@link #getBottom()}. 317 * These methods return the coordinates of the right and bottom edges of the 318 * rectangle representing the view. For instance, calling {@link #getRight()} 319 * is similar to the following computation: <code>getLeft() + getWidth()</code> 320 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 321 * </p> 322 * 323 * <a name="SizePaddingMargins"></a> 324 * <h3>Size, padding and margins</h3> 325 * <p> 326 * The size of a view is expressed with a width and a height. A view actually 327 * possess two pairs of width and height values. 328 * </p> 329 * 330 * <p> 331 * The first pair is known as <em>measured width</em> and 332 * <em>measured height</em>. These dimensions define how big a view wants to be 333 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 334 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 335 * and {@link #getMeasuredHeight()}. 336 * </p> 337 * 338 * <p> 339 * The second pair is simply known as <em>width</em> and <em>height</em>, or 340 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 341 * dimensions define the actual size of the view on screen, at drawing time and 342 * after layout. These values may, but do not have to, be different from the 343 * measured width and height. The width and height can be obtained by calling 344 * {@link #getWidth()} and {@link #getHeight()}. 345 * </p> 346 * 347 * <p> 348 * To measure its dimensions, a view takes into account its padding. The padding 349 * is expressed in pixels for the left, top, right and bottom parts of the view. 350 * Padding can be used to offset the content of the view by a specific amount of 351 * pixels. For instance, a left padding of 2 will push the view's content by 352 * 2 pixels to the right of the left edge. Padding can be set using the 353 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 354 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 355 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 356 * {@link #getPaddingEnd()}. 357 * </p> 358 * 359 * <p> 360 * Even though a view can define a padding, it does not provide any support for 361 * margins. However, view groups provide such a support. Refer to 362 * {@link android.view.ViewGroup} and 363 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 364 * </p> 365 * 366 * <a name="Layout"></a> 367 * <h3>Layout</h3> 368 * <p> 369 * Layout is a two pass process: a measure pass and a layout pass. The measuring 370 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 371 * of the view tree. Each view pushes dimension specifications down the tree 372 * during the recursion. At the end of the measure pass, every view has stored 373 * its measurements. The second pass happens in 374 * {@link #layout(int,int,int,int)} and is also top-down. During 375 * this pass each parent is responsible for positioning all of its children 376 * using the sizes computed in the measure pass. 377 * </p> 378 * 379 * <p> 380 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 381 * {@link #getMeasuredHeight()} values must be set, along with those for all of 382 * that view's descendants. A view's measured width and measured height values 383 * must respect the constraints imposed by the view's parents. This guarantees 384 * that at the end of the measure pass, all parents accept all of their 385 * children's measurements. A parent view may call measure() more than once on 386 * its children. For example, the parent may measure each child once with 387 * unspecified dimensions to find out how big they want to be, then call 388 * measure() on them again with actual numbers if the sum of all the children's 389 * unconstrained sizes is too big or too small. 390 * </p> 391 * 392 * <p> 393 * The measure pass uses two classes to communicate dimensions. The 394 * {@link MeasureSpec} class is used by views to tell their parents how they 395 * want to be measured and positioned. The base LayoutParams class just 396 * describes how big the view wants to be for both width and height. For each 397 * dimension, it can specify one of: 398 * <ul> 399 * <li> an exact number 400 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 401 * (minus padding) 402 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 403 * enclose its content (plus padding). 404 * </ul> 405 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 406 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 407 * an X and Y value. 408 * </p> 409 * 410 * <p> 411 * MeasureSpecs are used to push requirements down the tree from parent to 412 * child. A MeasureSpec can be in one of three modes: 413 * <ul> 414 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 415 * of a child view. For example, a LinearLayout may call measure() on its child 416 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 417 * tall the child view wants to be given a width of 240 pixels. 418 * <li>EXACTLY: This is used by the parent to impose an exact size on the 419 * child. The child must use this size, and guarantee that all of its 420 * descendants will fit within this size. 421 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 422 * child. The child must gurantee that it and all of its descendants will fit 423 * within this size. 424 * </ul> 425 * </p> 426 * 427 * <p> 428 * To intiate a layout, call {@link #requestLayout}. This method is typically 429 * called by a view on itself when it believes that is can no longer fit within 430 * its current bounds. 431 * </p> 432 * 433 * <a name="Drawing"></a> 434 * <h3>Drawing</h3> 435 * <p> 436 * Drawing is handled by walking the tree and rendering each view that 437 * intersects the invalid region. Because the tree is traversed in-order, 438 * this means that parents will draw before (i.e., behind) their children, with 439 * siblings drawn in the order they appear in the tree. 440 * If you set a background drawable for a View, then the View will draw it for you 441 * before calling back to its <code>onDraw()</code> method. 442 * </p> 443 * 444 * <p> 445 * Note that the framework will not draw views that are not in the invalid region. 446 * </p> 447 * 448 * <p> 449 * To force a view to draw, call {@link #invalidate()}. 450 * </p> 451 * 452 * <a name="EventHandlingThreading"></a> 453 * <h3>Event Handling and Threading</h3> 454 * <p> 455 * The basic cycle of a view is as follows: 456 * <ol> 457 * <li>An event comes in and is dispatched to the appropriate view. The view 458 * handles the event and notifies any listeners.</li> 459 * <li>If in the course of processing the event, the view's bounds may need 460 * to be changed, the view will call {@link #requestLayout()}.</li> 461 * <li>Similarly, if in the course of processing the event the view's appearance 462 * may need to be changed, the view will call {@link #invalidate()}.</li> 463 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 464 * the framework will take care of measuring, laying out, and drawing the tree 465 * as appropriate.</li> 466 * </ol> 467 * </p> 468 * 469 * <p><em>Note: The entire view tree is single threaded. You must always be on 470 * the UI thread when calling any method on any view.</em> 471 * If you are doing work on other threads and want to update the state of a view 472 * from that thread, you should use a {@link Handler}. 473 * </p> 474 * 475 * <a name="FocusHandling"></a> 476 * <h3>Focus Handling</h3> 477 * <p> 478 * The framework will handle routine focus movement in response to user input. 479 * This includes changing the focus as views are removed or hidden, or as new 480 * views become available. Views indicate their willingness to take focus 481 * through the {@link #isFocusable} method. To change whether a view can take 482 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 483 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 484 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 485 * </p> 486 * <p> 487 * Focus movement is based on an algorithm which finds the nearest neighbor in a 488 * given direction. In rare cases, the default algorithm may not match the 489 * intended behavior of the developer. In these situations, you can provide 490 * explicit overrides by using these XML attributes in the layout file: 491 * <pre> 492 * nextFocusDown 493 * nextFocusLeft 494 * nextFocusRight 495 * nextFocusUp 496 * </pre> 497 * </p> 498 * 499 * 500 * <p> 501 * To get a particular view to take focus, call {@link #requestFocus()}. 502 * </p> 503 * 504 * <a name="TouchMode"></a> 505 * <h3>Touch Mode</h3> 506 * <p> 507 * When a user is navigating a user interface via directional keys such as a D-pad, it is 508 * necessary to give focus to actionable items such as buttons so the user can see 509 * what will take input. If the device has touch capabilities, however, and the user 510 * begins interacting with the interface by touching it, it is no longer necessary to 511 * always highlight, or give focus to, a particular view. This motivates a mode 512 * for interaction named 'touch mode'. 513 * </p> 514 * <p> 515 * For a touch capable device, once the user touches the screen, the device 516 * will enter touch mode. From this point onward, only views for which 517 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 518 * Other views that are touchable, like buttons, will not take focus when touched; they will 519 * only fire the on click listeners. 520 * </p> 521 * <p> 522 * Any time a user hits a directional key, such as a D-pad direction, the view device will 523 * exit touch mode, and find a view to take focus, so that the user may resume interacting 524 * with the user interface without touching the screen again. 525 * </p> 526 * <p> 527 * The touch mode state is maintained across {@link android.app.Activity}s. Call 528 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 529 * </p> 530 * 531 * <a name="Scrolling"></a> 532 * <h3>Scrolling</h3> 533 * <p> 534 * The framework provides basic support for views that wish to internally 535 * scroll their content. This includes keeping track of the X and Y scroll 536 * offset as well as mechanisms for drawing scrollbars. See 537 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 538 * {@link #awakenScrollBars()} for more details. 539 * </p> 540 * 541 * <a name="Tags"></a> 542 * <h3>Tags</h3> 543 * <p> 544 * Unlike IDs, tags are not used to identify views. Tags are essentially an 545 * extra piece of information that can be associated with a view. They are most 546 * often used as a convenience to store data related to views in the views 547 * themselves rather than by putting them in a separate structure. 548 * </p> 549 * 550 * <a name="Properties"></a> 551 * <h3>Properties</h3> 552 * <p> 553 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 554 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 555 * available both in the {@link Property} form as well as in similarly-named setter/getter 556 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 557 * be used to set persistent state associated with these rendering-related properties on the view. 558 * The properties and methods can also be used in conjunction with 559 * {@link android.animation.Animator Animator}-based animations, described more in the 560 * <a href="#Animation">Animation</a> section. 561 * </p> 562 * 563 * <a name="Animation"></a> 564 * <h3>Animation</h3> 565 * <p> 566 * Starting with Android 3.0, the preferred way of animating views is to use the 567 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 568 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 569 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 570 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 571 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 572 * makes animating these View properties particularly easy and efficient. 573 * </p> 574 * <p> 575 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 576 * You can attach an {@link Animation} object to a view using 577 * {@link #setAnimation(Animation)} or 578 * {@link #startAnimation(Animation)}. The animation can alter the scale, 579 * rotation, translation and alpha of a view over time. If the animation is 580 * attached to a view that has children, the animation will affect the entire 581 * subtree rooted by that node. When an animation is started, the framework will 582 * take care of redrawing the appropriate views until the animation completes. 583 * </p> 584 * 585 * <a name="Security"></a> 586 * <h3>Security</h3> 587 * <p> 588 * Sometimes it is essential that an application be able to verify that an action 589 * is being performed with the full knowledge and consent of the user, such as 590 * granting a permission request, making a purchase or clicking on an advertisement. 591 * Unfortunately, a malicious application could try to spoof the user into 592 * performing these actions, unaware, by concealing the intended purpose of the view. 593 * As a remedy, the framework offers a touch filtering mechanism that can be used to 594 * improve the security of views that provide access to sensitive functionality. 595 * </p><p> 596 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 597 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 598 * will discard touches that are received whenever the view's window is obscured by 599 * another visible window. As a result, the view will not receive touches whenever a 600 * toast, dialog or other window appears above the view's window. 601 * </p><p> 602 * For more fine-grained control over security, consider overriding the 603 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 604 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 605 * </p> 606 * 607 * @attr ref android.R.styleable#View_alpha 608 * @attr ref android.R.styleable#View_background 609 * @attr ref android.R.styleable#View_clickable 610 * @attr ref android.R.styleable#View_contentDescription 611 * @attr ref android.R.styleable#View_drawingCacheQuality 612 * @attr ref android.R.styleable#View_duplicateParentState 613 * @attr ref android.R.styleable#View_id 614 * @attr ref android.R.styleable#View_requiresFadingEdge 615 * @attr ref android.R.styleable#View_fadeScrollbars 616 * @attr ref android.R.styleable#View_fadingEdgeLength 617 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 618 * @attr ref android.R.styleable#View_fitsSystemWindows 619 * @attr ref android.R.styleable#View_isScrollContainer 620 * @attr ref android.R.styleable#View_focusable 621 * @attr ref android.R.styleable#View_focusableInTouchMode 622 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 623 * @attr ref android.R.styleable#View_keepScreenOn 624 * @attr ref android.R.styleable#View_layerType 625 * @attr ref android.R.styleable#View_layoutDirection 626 * @attr ref android.R.styleable#View_longClickable 627 * @attr ref android.R.styleable#View_minHeight 628 * @attr ref android.R.styleable#View_minWidth 629 * @attr ref android.R.styleable#View_nextFocusDown 630 * @attr ref android.R.styleable#View_nextFocusLeft 631 * @attr ref android.R.styleable#View_nextFocusRight 632 * @attr ref android.R.styleable#View_nextFocusUp 633 * @attr ref android.R.styleable#View_onClick 634 * @attr ref android.R.styleable#View_padding 635 * @attr ref android.R.styleable#View_paddingBottom 636 * @attr ref android.R.styleable#View_paddingLeft 637 * @attr ref android.R.styleable#View_paddingRight 638 * @attr ref android.R.styleable#View_paddingTop 639 * @attr ref android.R.styleable#View_paddingStart 640 * @attr ref android.R.styleable#View_paddingEnd 641 * @attr ref android.R.styleable#View_saveEnabled 642 * @attr ref android.R.styleable#View_rotation 643 * @attr ref android.R.styleable#View_rotationX 644 * @attr ref android.R.styleable#View_rotationY 645 * @attr ref android.R.styleable#View_scaleX 646 * @attr ref android.R.styleable#View_scaleY 647 * @attr ref android.R.styleable#View_scrollX 648 * @attr ref android.R.styleable#View_scrollY 649 * @attr ref android.R.styleable#View_scrollbarSize 650 * @attr ref android.R.styleable#View_scrollbarStyle 651 * @attr ref android.R.styleable#View_scrollbars 652 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 653 * @attr ref android.R.styleable#View_scrollbarFadeDuration 654 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 655 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 656 * @attr ref android.R.styleable#View_scrollbarThumbVertical 657 * @attr ref android.R.styleable#View_scrollbarTrackVertical 658 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 660 * @attr ref android.R.styleable#View_soundEffectsEnabled 661 * @attr ref android.R.styleable#View_tag 662 * @attr ref android.R.styleable#View_textAlignment 663 * @attr ref android.R.styleable#View_textDirection 664 * @attr ref android.R.styleable#View_transformPivotX 665 * @attr ref android.R.styleable#View_transformPivotY 666 * @attr ref android.R.styleable#View_translationX 667 * @attr ref android.R.styleable#View_translationY 668 * @attr ref android.R.styleable#View_visibility 669 * 670 * @see android.view.ViewGroup 671 */ 672public class View implements Drawable.Callback, KeyEvent.Callback, 673 AccessibilityEventSource { 674 private static final boolean DBG = false; 675 676 /** 677 * The logging tag used by this class with android.util.Log. 678 */ 679 protected static final String VIEW_LOG_TAG = "View"; 680 681 /** 682 * When set to true, apps will draw debugging information about their layouts. 683 * 684 * @hide 685 */ 686 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 687 688 /** 689 * Used to mark a View that has no ID. 690 */ 691 public static final int NO_ID = -1; 692 693 private static boolean sUseBrokenMakeMeasureSpec = false; 694 695 /** 696 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 697 * calling setFlags. 698 */ 699 private static final int NOT_FOCUSABLE = 0x00000000; 700 701 /** 702 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 703 * setFlags. 704 */ 705 private static final int FOCUSABLE = 0x00000001; 706 707 /** 708 * Mask for use with setFlags indicating bits used for focus. 709 */ 710 private static final int FOCUSABLE_MASK = 0x00000001; 711 712 /** 713 * This view will adjust its padding to fit sytem windows (e.g. status bar) 714 */ 715 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 716 717 /** 718 * This view is visible. 719 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 720 * android:visibility}. 721 */ 722 public static final int VISIBLE = 0x00000000; 723 724 /** 725 * This view is invisible, but it still takes up space for layout purposes. 726 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 727 * android:visibility}. 728 */ 729 public static final int INVISIBLE = 0x00000004; 730 731 /** 732 * This view is invisible, and it doesn't take any space for layout 733 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 734 * android:visibility}. 735 */ 736 public static final int GONE = 0x00000008; 737 738 /** 739 * Mask for use with setFlags indicating bits used for visibility. 740 * {@hide} 741 */ 742 static final int VISIBILITY_MASK = 0x0000000C; 743 744 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 745 746 /** 747 * This view is enabled. Interpretation varies by subclass. 748 * Use with ENABLED_MASK when calling setFlags. 749 * {@hide} 750 */ 751 static final int ENABLED = 0x00000000; 752 753 /** 754 * This view is disabled. Interpretation varies by subclass. 755 * Use with ENABLED_MASK when calling setFlags. 756 * {@hide} 757 */ 758 static final int DISABLED = 0x00000020; 759 760 /** 761 * Mask for use with setFlags indicating bits used for indicating whether 762 * this view is enabled 763 * {@hide} 764 */ 765 static final int ENABLED_MASK = 0x00000020; 766 767 /** 768 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 769 * called and further optimizations will be performed. It is okay to have 770 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 771 * {@hide} 772 */ 773 static final int WILL_NOT_DRAW = 0x00000080; 774 775 /** 776 * Mask for use with setFlags indicating bits used for indicating whether 777 * this view is will draw 778 * {@hide} 779 */ 780 static final int DRAW_MASK = 0x00000080; 781 782 /** 783 * <p>This view doesn't show scrollbars.</p> 784 * {@hide} 785 */ 786 static final int SCROLLBARS_NONE = 0x00000000; 787 788 /** 789 * <p>This view shows horizontal scrollbars.</p> 790 * {@hide} 791 */ 792 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 793 794 /** 795 * <p>This view shows vertical scrollbars.</p> 796 * {@hide} 797 */ 798 static final int SCROLLBARS_VERTICAL = 0x00000200; 799 800 /** 801 * <p>Mask for use with setFlags indicating bits used for indicating which 802 * scrollbars are enabled.</p> 803 * {@hide} 804 */ 805 static final int SCROLLBARS_MASK = 0x00000300; 806 807 /** 808 * Indicates that the view should filter touches when its window is obscured. 809 * Refer to the class comments for more information about this security feature. 810 * {@hide} 811 */ 812 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 813 814 /** 815 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 816 * that they are optional and should be skipped if the window has 817 * requested system UI flags that ignore those insets for layout. 818 */ 819 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 820 821 /** 822 * <p>This view doesn't show fading edges.</p> 823 * {@hide} 824 */ 825 static final int FADING_EDGE_NONE = 0x00000000; 826 827 /** 828 * <p>This view shows horizontal fading edges.</p> 829 * {@hide} 830 */ 831 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 832 833 /** 834 * <p>This view shows vertical fading edges.</p> 835 * {@hide} 836 */ 837 static final int FADING_EDGE_VERTICAL = 0x00002000; 838 839 /** 840 * <p>Mask for use with setFlags indicating bits used for indicating which 841 * fading edges are enabled.</p> 842 * {@hide} 843 */ 844 static final int FADING_EDGE_MASK = 0x00003000; 845 846 /** 847 * <p>Indicates this view can be clicked. When clickable, a View reacts 848 * to clicks by notifying the OnClickListener.<p> 849 * {@hide} 850 */ 851 static final int CLICKABLE = 0x00004000; 852 853 /** 854 * <p>Indicates this view is caching its drawing into a bitmap.</p> 855 * {@hide} 856 */ 857 static final int DRAWING_CACHE_ENABLED = 0x00008000; 858 859 /** 860 * <p>Indicates that no icicle should be saved for this view.<p> 861 * {@hide} 862 */ 863 static final int SAVE_DISABLED = 0x000010000; 864 865 /** 866 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 867 * property.</p> 868 * {@hide} 869 */ 870 static final int SAVE_DISABLED_MASK = 0x000010000; 871 872 /** 873 * <p>Indicates that no drawing cache should ever be created for this view.<p> 874 * {@hide} 875 */ 876 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 877 878 /** 879 * <p>Indicates this view can take / keep focus when int touch mode.</p> 880 * {@hide} 881 */ 882 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 883 884 /** 885 * <p>Enables low quality mode for the drawing cache.</p> 886 */ 887 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 888 889 /** 890 * <p>Enables high quality mode for the drawing cache.</p> 891 */ 892 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 893 894 /** 895 * <p>Enables automatic quality mode for the drawing cache.</p> 896 */ 897 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 898 899 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 900 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 901 }; 902 903 /** 904 * <p>Mask for use with setFlags indicating bits used for the cache 905 * quality property.</p> 906 * {@hide} 907 */ 908 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 909 910 /** 911 * <p> 912 * Indicates this view can be long clicked. When long clickable, a View 913 * reacts to long clicks by notifying the OnLongClickListener or showing a 914 * context menu. 915 * </p> 916 * {@hide} 917 */ 918 static final int LONG_CLICKABLE = 0x00200000; 919 920 /** 921 * <p>Indicates that this view gets its drawable states from its direct parent 922 * and ignores its original internal states.</p> 923 * 924 * @hide 925 */ 926 static final int DUPLICATE_PARENT_STATE = 0x00400000; 927 928 /** 929 * The scrollbar style to display the scrollbars inside the content area, 930 * without increasing the padding. The scrollbars will be overlaid with 931 * translucency on the view's content. 932 */ 933 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 934 935 /** 936 * The scrollbar style to display the scrollbars inside the padded area, 937 * increasing the padding of the view. The scrollbars will not overlap the 938 * content area of the view. 939 */ 940 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 941 942 /** 943 * The scrollbar style to display the scrollbars at the edge of the view, 944 * without increasing the padding. The scrollbars will be overlaid with 945 * translucency. 946 */ 947 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 948 949 /** 950 * The scrollbar style to display the scrollbars at the edge of the view, 951 * increasing the padding of the view. The scrollbars will only overlap the 952 * background, if any. 953 */ 954 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 955 956 /** 957 * Mask to check if the scrollbar style is overlay or inset. 958 * {@hide} 959 */ 960 static final int SCROLLBARS_INSET_MASK = 0x01000000; 961 962 /** 963 * Mask to check if the scrollbar style is inside or outside. 964 * {@hide} 965 */ 966 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 967 968 /** 969 * Mask for scrollbar style. 970 * {@hide} 971 */ 972 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 973 974 /** 975 * View flag indicating that the screen should remain on while the 976 * window containing this view is visible to the user. This effectively 977 * takes care of automatically setting the WindowManager's 978 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 979 */ 980 public static final int KEEP_SCREEN_ON = 0x04000000; 981 982 /** 983 * View flag indicating whether this view should have sound effects enabled 984 * for events such as clicking and touching. 985 */ 986 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 987 988 /** 989 * View flag indicating whether this view should have haptic feedback 990 * enabled for events such as long presses. 991 */ 992 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 993 994 /** 995 * <p>Indicates that the view hierarchy should stop saving state when 996 * it reaches this view. If state saving is initiated immediately at 997 * the view, it will be allowed. 998 * {@hide} 999 */ 1000 static final int PARENT_SAVE_DISABLED = 0x20000000; 1001 1002 /** 1003 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1004 * {@hide} 1005 */ 1006 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1007 1008 /** 1009 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1010 * should add all focusable Views regardless if they are focusable in touch mode. 1011 */ 1012 public static final int FOCUSABLES_ALL = 0x00000000; 1013 1014 /** 1015 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1016 * should add only Views focusable in touch mode. 1017 */ 1018 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1019 1020 /** 1021 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1022 * item. 1023 */ 1024 public static final int FOCUS_BACKWARD = 0x00000001; 1025 1026 /** 1027 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1028 * item. 1029 */ 1030 public static final int FOCUS_FORWARD = 0x00000002; 1031 1032 /** 1033 * Use with {@link #focusSearch(int)}. Move focus to the left. 1034 */ 1035 public static final int FOCUS_LEFT = 0x00000011; 1036 1037 /** 1038 * Use with {@link #focusSearch(int)}. Move focus up. 1039 */ 1040 public static final int FOCUS_UP = 0x00000021; 1041 1042 /** 1043 * Use with {@link #focusSearch(int)}. Move focus to the right. 1044 */ 1045 public static final int FOCUS_RIGHT = 0x00000042; 1046 1047 /** 1048 * Use with {@link #focusSearch(int)}. Move focus down. 1049 */ 1050 public static final int FOCUS_DOWN = 0x00000082; 1051 1052 /** 1053 * Bits of {@link #getMeasuredWidthAndState()} and 1054 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1055 */ 1056 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1057 1058 /** 1059 * Bits of {@link #getMeasuredWidthAndState()} and 1060 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1061 */ 1062 public static final int MEASURED_STATE_MASK = 0xff000000; 1063 1064 /** 1065 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1066 * for functions that combine both width and height into a single int, 1067 * such as {@link #getMeasuredState()} and the childState argument of 1068 * {@link #resolveSizeAndState(int, int, int)}. 1069 */ 1070 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1071 1072 /** 1073 * Bit of {@link #getMeasuredWidthAndState()} and 1074 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1075 * is smaller that the space the view would like to have. 1076 */ 1077 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1078 1079 /** 1080 * Base View state sets 1081 */ 1082 // Singles 1083 /** 1084 * Indicates the view has no states set. States are used with 1085 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1086 * view depending on its state. 1087 * 1088 * @see android.graphics.drawable.Drawable 1089 * @see #getDrawableState() 1090 */ 1091 protected static final int[] EMPTY_STATE_SET; 1092 /** 1093 * Indicates the view is enabled. States are used with 1094 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1095 * view depending on its state. 1096 * 1097 * @see android.graphics.drawable.Drawable 1098 * @see #getDrawableState() 1099 */ 1100 protected static final int[] ENABLED_STATE_SET; 1101 /** 1102 * Indicates the view is focused. States are used with 1103 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1104 * view depending on its state. 1105 * 1106 * @see android.graphics.drawable.Drawable 1107 * @see #getDrawableState() 1108 */ 1109 protected static final int[] FOCUSED_STATE_SET; 1110 /** 1111 * Indicates the view is selected. States are used with 1112 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1113 * view depending on its state. 1114 * 1115 * @see android.graphics.drawable.Drawable 1116 * @see #getDrawableState() 1117 */ 1118 protected static final int[] SELECTED_STATE_SET; 1119 /** 1120 * Indicates the view is pressed. States are used with 1121 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1122 * view depending on its state. 1123 * 1124 * @see android.graphics.drawable.Drawable 1125 * @see #getDrawableState() 1126 */ 1127 protected static final int[] PRESSED_STATE_SET; 1128 /** 1129 * Indicates the view's window has focus. States are used with 1130 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1131 * view depending on its state. 1132 * 1133 * @see android.graphics.drawable.Drawable 1134 * @see #getDrawableState() 1135 */ 1136 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1137 // Doubles 1138 /** 1139 * Indicates the view is enabled and has the focus. 1140 * 1141 * @see #ENABLED_STATE_SET 1142 * @see #FOCUSED_STATE_SET 1143 */ 1144 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1145 /** 1146 * Indicates the view is enabled and selected. 1147 * 1148 * @see #ENABLED_STATE_SET 1149 * @see #SELECTED_STATE_SET 1150 */ 1151 protected static final int[] ENABLED_SELECTED_STATE_SET; 1152 /** 1153 * Indicates the view is enabled and that its window has focus. 1154 * 1155 * @see #ENABLED_STATE_SET 1156 * @see #WINDOW_FOCUSED_STATE_SET 1157 */ 1158 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1159 /** 1160 * Indicates the view is focused and selected. 1161 * 1162 * @see #FOCUSED_STATE_SET 1163 * @see #SELECTED_STATE_SET 1164 */ 1165 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1166 /** 1167 * Indicates the view has the focus and that its window has the focus. 1168 * 1169 * @see #FOCUSED_STATE_SET 1170 * @see #WINDOW_FOCUSED_STATE_SET 1171 */ 1172 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1173 /** 1174 * Indicates the view is selected and that its window has the focus. 1175 * 1176 * @see #SELECTED_STATE_SET 1177 * @see #WINDOW_FOCUSED_STATE_SET 1178 */ 1179 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1180 // Triples 1181 /** 1182 * Indicates the view is enabled, focused and selected. 1183 * 1184 * @see #ENABLED_STATE_SET 1185 * @see #FOCUSED_STATE_SET 1186 * @see #SELECTED_STATE_SET 1187 */ 1188 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1189 /** 1190 * Indicates the view is enabled, focused and its window has the focus. 1191 * 1192 * @see #ENABLED_STATE_SET 1193 * @see #FOCUSED_STATE_SET 1194 * @see #WINDOW_FOCUSED_STATE_SET 1195 */ 1196 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1197 /** 1198 * Indicates the view is enabled, selected and its window has the focus. 1199 * 1200 * @see #ENABLED_STATE_SET 1201 * @see #SELECTED_STATE_SET 1202 * @see #WINDOW_FOCUSED_STATE_SET 1203 */ 1204 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1205 /** 1206 * Indicates the view is focused, selected and its window has the focus. 1207 * 1208 * @see #FOCUSED_STATE_SET 1209 * @see #SELECTED_STATE_SET 1210 * @see #WINDOW_FOCUSED_STATE_SET 1211 */ 1212 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1213 /** 1214 * Indicates the view is enabled, focused, selected and its window 1215 * has the focus. 1216 * 1217 * @see #ENABLED_STATE_SET 1218 * @see #FOCUSED_STATE_SET 1219 * @see #SELECTED_STATE_SET 1220 * @see #WINDOW_FOCUSED_STATE_SET 1221 */ 1222 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1223 /** 1224 * Indicates the view is pressed and its window has the focus. 1225 * 1226 * @see #PRESSED_STATE_SET 1227 * @see #WINDOW_FOCUSED_STATE_SET 1228 */ 1229 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1230 /** 1231 * Indicates the view is pressed and selected. 1232 * 1233 * @see #PRESSED_STATE_SET 1234 * @see #SELECTED_STATE_SET 1235 */ 1236 protected static final int[] PRESSED_SELECTED_STATE_SET; 1237 /** 1238 * Indicates the view is pressed, selected and its window has the focus. 1239 * 1240 * @see #PRESSED_STATE_SET 1241 * @see #SELECTED_STATE_SET 1242 * @see #WINDOW_FOCUSED_STATE_SET 1243 */ 1244 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1245 /** 1246 * Indicates the view is pressed and focused. 1247 * 1248 * @see #PRESSED_STATE_SET 1249 * @see #FOCUSED_STATE_SET 1250 */ 1251 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1252 /** 1253 * Indicates the view is pressed, focused and its window has the focus. 1254 * 1255 * @see #PRESSED_STATE_SET 1256 * @see #FOCUSED_STATE_SET 1257 * @see #WINDOW_FOCUSED_STATE_SET 1258 */ 1259 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1260 /** 1261 * Indicates the view is pressed, focused and selected. 1262 * 1263 * @see #PRESSED_STATE_SET 1264 * @see #SELECTED_STATE_SET 1265 * @see #FOCUSED_STATE_SET 1266 */ 1267 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1268 /** 1269 * Indicates the view is pressed, focused, selected and its window has the focus. 1270 * 1271 * @see #PRESSED_STATE_SET 1272 * @see #FOCUSED_STATE_SET 1273 * @see #SELECTED_STATE_SET 1274 * @see #WINDOW_FOCUSED_STATE_SET 1275 */ 1276 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1277 /** 1278 * Indicates the view is pressed and enabled. 1279 * 1280 * @see #PRESSED_STATE_SET 1281 * @see #ENABLED_STATE_SET 1282 */ 1283 protected static final int[] PRESSED_ENABLED_STATE_SET; 1284 /** 1285 * Indicates the view is pressed, enabled and its window has the focus. 1286 * 1287 * @see #PRESSED_STATE_SET 1288 * @see #ENABLED_STATE_SET 1289 * @see #WINDOW_FOCUSED_STATE_SET 1290 */ 1291 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1292 /** 1293 * Indicates the view is pressed, enabled and selected. 1294 * 1295 * @see #PRESSED_STATE_SET 1296 * @see #ENABLED_STATE_SET 1297 * @see #SELECTED_STATE_SET 1298 */ 1299 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1300 /** 1301 * Indicates the view is pressed, enabled, selected and its window has the 1302 * focus. 1303 * 1304 * @see #PRESSED_STATE_SET 1305 * @see #ENABLED_STATE_SET 1306 * @see #SELECTED_STATE_SET 1307 * @see #WINDOW_FOCUSED_STATE_SET 1308 */ 1309 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1310 /** 1311 * Indicates the view is pressed, enabled and focused. 1312 * 1313 * @see #PRESSED_STATE_SET 1314 * @see #ENABLED_STATE_SET 1315 * @see #FOCUSED_STATE_SET 1316 */ 1317 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1318 /** 1319 * Indicates the view is pressed, enabled, focused and its window has the 1320 * focus. 1321 * 1322 * @see #PRESSED_STATE_SET 1323 * @see #ENABLED_STATE_SET 1324 * @see #FOCUSED_STATE_SET 1325 * @see #WINDOW_FOCUSED_STATE_SET 1326 */ 1327 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1328 /** 1329 * Indicates the view is pressed, enabled, focused and selected. 1330 * 1331 * @see #PRESSED_STATE_SET 1332 * @see #ENABLED_STATE_SET 1333 * @see #SELECTED_STATE_SET 1334 * @see #FOCUSED_STATE_SET 1335 */ 1336 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1337 /** 1338 * Indicates the view is pressed, enabled, focused, selected and its window 1339 * has the focus. 1340 * 1341 * @see #PRESSED_STATE_SET 1342 * @see #ENABLED_STATE_SET 1343 * @see #SELECTED_STATE_SET 1344 * @see #FOCUSED_STATE_SET 1345 * @see #WINDOW_FOCUSED_STATE_SET 1346 */ 1347 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1348 1349 /** 1350 * The order here is very important to {@link #getDrawableState()} 1351 */ 1352 private static final int[][] VIEW_STATE_SETS; 1353 1354 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1355 static final int VIEW_STATE_SELECTED = 1 << 1; 1356 static final int VIEW_STATE_FOCUSED = 1 << 2; 1357 static final int VIEW_STATE_ENABLED = 1 << 3; 1358 static final int VIEW_STATE_PRESSED = 1 << 4; 1359 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1360 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1361 static final int VIEW_STATE_HOVERED = 1 << 7; 1362 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1363 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1364 1365 static final int[] VIEW_STATE_IDS = new int[] { 1366 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1367 R.attr.state_selected, VIEW_STATE_SELECTED, 1368 R.attr.state_focused, VIEW_STATE_FOCUSED, 1369 R.attr.state_enabled, VIEW_STATE_ENABLED, 1370 R.attr.state_pressed, VIEW_STATE_PRESSED, 1371 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1372 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1373 R.attr.state_hovered, VIEW_STATE_HOVERED, 1374 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1375 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1376 }; 1377 1378 static { 1379 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1380 throw new IllegalStateException( 1381 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1382 } 1383 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1384 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1385 int viewState = R.styleable.ViewDrawableStates[i]; 1386 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1387 if (VIEW_STATE_IDS[j] == viewState) { 1388 orderedIds[i * 2] = viewState; 1389 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1390 } 1391 } 1392 } 1393 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1394 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1395 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1396 int numBits = Integer.bitCount(i); 1397 int[] set = new int[numBits]; 1398 int pos = 0; 1399 for (int j = 0; j < orderedIds.length; j += 2) { 1400 if ((i & orderedIds[j+1]) != 0) { 1401 set[pos++] = orderedIds[j]; 1402 } 1403 } 1404 VIEW_STATE_SETS[i] = set; 1405 } 1406 1407 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1408 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1409 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1410 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1411 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1412 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1413 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1414 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1415 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1416 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1417 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1418 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1419 | VIEW_STATE_FOCUSED]; 1420 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1421 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1422 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1423 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1424 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1425 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1426 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1427 | VIEW_STATE_ENABLED]; 1428 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1429 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1430 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1431 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1432 | VIEW_STATE_ENABLED]; 1433 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1434 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1435 | VIEW_STATE_ENABLED]; 1436 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1437 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1438 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1439 1440 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1441 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1442 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1443 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1444 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1445 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1446 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1447 | VIEW_STATE_PRESSED]; 1448 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1449 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1450 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1451 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1452 | VIEW_STATE_PRESSED]; 1453 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1454 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1455 | VIEW_STATE_PRESSED]; 1456 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1457 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1458 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1459 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1460 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1461 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1462 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1463 | VIEW_STATE_PRESSED]; 1464 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1465 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1466 | VIEW_STATE_PRESSED]; 1467 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1468 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1469 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1470 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1471 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1472 | VIEW_STATE_PRESSED]; 1473 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1474 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1475 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1476 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1477 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1478 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1479 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1480 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1481 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1482 | VIEW_STATE_PRESSED]; 1483 } 1484 1485 /** 1486 * Accessibility event types that are dispatched for text population. 1487 */ 1488 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1489 AccessibilityEvent.TYPE_VIEW_CLICKED 1490 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1491 | AccessibilityEvent.TYPE_VIEW_SELECTED 1492 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1493 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1494 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1495 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1496 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1497 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1498 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1499 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1500 1501 /** 1502 * Temporary Rect currently for use in setBackground(). This will probably 1503 * be extended in the future to hold our own class with more than just 1504 * a Rect. :) 1505 */ 1506 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1507 1508 /** 1509 * Map used to store views' tags. 1510 */ 1511 private SparseArray<Object> mKeyedTags; 1512 1513 /** 1514 * The next available accessibility id. 1515 */ 1516 private static int sNextAccessibilityViewId; 1517 1518 /** 1519 * The animation currently associated with this view. 1520 * @hide 1521 */ 1522 protected Animation mCurrentAnimation = null; 1523 1524 /** 1525 * Width as measured during measure pass. 1526 * {@hide} 1527 */ 1528 @ViewDebug.ExportedProperty(category = "measurement") 1529 int mMeasuredWidth; 1530 1531 /** 1532 * Height as measured during measure pass. 1533 * {@hide} 1534 */ 1535 @ViewDebug.ExportedProperty(category = "measurement") 1536 int mMeasuredHeight; 1537 1538 /** 1539 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1540 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1541 * its display list. This flag, used only when hw accelerated, allows us to clear the 1542 * flag while retaining this information until it's needed (at getDisplayList() time and 1543 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1544 * 1545 * {@hide} 1546 */ 1547 boolean mRecreateDisplayList = false; 1548 1549 /** 1550 * The view's identifier. 1551 * {@hide} 1552 * 1553 * @see #setId(int) 1554 * @see #getId() 1555 */ 1556 @ViewDebug.ExportedProperty(resolveId = true) 1557 int mID = NO_ID; 1558 1559 /** 1560 * The stable ID of this view for accessibility purposes. 1561 */ 1562 int mAccessibilityViewId = NO_ID; 1563 1564 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1565 1566 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1567 1568 /** 1569 * The view's tag. 1570 * {@hide} 1571 * 1572 * @see #setTag(Object) 1573 * @see #getTag() 1574 */ 1575 protected Object mTag; 1576 1577 // for mPrivateFlags: 1578 /** {@hide} */ 1579 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1580 /** {@hide} */ 1581 static final int PFLAG_FOCUSED = 0x00000002; 1582 /** {@hide} */ 1583 static final int PFLAG_SELECTED = 0x00000004; 1584 /** {@hide} */ 1585 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1586 /** {@hide} */ 1587 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1588 /** {@hide} */ 1589 static final int PFLAG_DRAWN = 0x00000020; 1590 /** 1591 * When this flag is set, this view is running an animation on behalf of its 1592 * children and should therefore not cancel invalidate requests, even if they 1593 * lie outside of this view's bounds. 1594 * 1595 * {@hide} 1596 */ 1597 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1598 /** {@hide} */ 1599 static final int PFLAG_SKIP_DRAW = 0x00000080; 1600 /** {@hide} */ 1601 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1602 /** {@hide} */ 1603 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1604 /** {@hide} */ 1605 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1606 /** {@hide} */ 1607 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1608 /** {@hide} */ 1609 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1610 /** {@hide} */ 1611 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1612 1613 private static final int PFLAG_PRESSED = 0x00004000; 1614 1615 /** {@hide} */ 1616 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1617 /** 1618 * Flag used to indicate that this view should be drawn once more (and only once 1619 * more) after its animation has completed. 1620 * {@hide} 1621 */ 1622 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1623 1624 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1625 1626 /** 1627 * Indicates that the View returned true when onSetAlpha() was called and that 1628 * the alpha must be restored. 1629 * {@hide} 1630 */ 1631 static final int PFLAG_ALPHA_SET = 0x00040000; 1632 1633 /** 1634 * Set by {@link #setScrollContainer(boolean)}. 1635 */ 1636 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1637 1638 /** 1639 * Set by {@link #setScrollContainer(boolean)}. 1640 */ 1641 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1642 1643 /** 1644 * View flag indicating whether this view was invalidated (fully or partially.) 1645 * 1646 * @hide 1647 */ 1648 static final int PFLAG_DIRTY = 0x00200000; 1649 1650 /** 1651 * View flag indicating whether this view was invalidated by an opaque 1652 * invalidate request. 1653 * 1654 * @hide 1655 */ 1656 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1657 1658 /** 1659 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1660 * 1661 * @hide 1662 */ 1663 static final int PFLAG_DIRTY_MASK = 0x00600000; 1664 1665 /** 1666 * Indicates whether the background is opaque. 1667 * 1668 * @hide 1669 */ 1670 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1671 1672 /** 1673 * Indicates whether the scrollbars are opaque. 1674 * 1675 * @hide 1676 */ 1677 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1678 1679 /** 1680 * Indicates whether the view is opaque. 1681 * 1682 * @hide 1683 */ 1684 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1685 1686 /** 1687 * Indicates a prepressed state; 1688 * the short time between ACTION_DOWN and recognizing 1689 * a 'real' press. Prepressed is used to recognize quick taps 1690 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1691 * 1692 * @hide 1693 */ 1694 private static final int PFLAG_PREPRESSED = 0x02000000; 1695 1696 /** 1697 * Indicates whether the view is temporarily detached. 1698 * 1699 * @hide 1700 */ 1701 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1702 1703 /** 1704 * Indicates that we should awaken scroll bars once attached 1705 * 1706 * @hide 1707 */ 1708 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1709 1710 /** 1711 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1712 * @hide 1713 */ 1714 private static final int PFLAG_HOVERED = 0x10000000; 1715 1716 /** 1717 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1718 * for transform operations 1719 * 1720 * @hide 1721 */ 1722 private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000; 1723 1724 /** {@hide} */ 1725 static final int PFLAG_ACTIVATED = 0x40000000; 1726 1727 /** 1728 * Indicates that this view was specifically invalidated, not just dirtied because some 1729 * child view was invalidated. The flag is used to determine when we need to recreate 1730 * a view's display list (as opposed to just returning a reference to its existing 1731 * display list). 1732 * 1733 * @hide 1734 */ 1735 static final int PFLAG_INVALIDATED = 0x80000000; 1736 1737 /** 1738 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1739 * 1740 * -------|-------|-------|-------| 1741 * PFLAG2_TEXT_ALIGNMENT_FLAGS[0] 1742 * PFLAG2_TEXT_DIRECTION_FLAGS[0] 1743 * 1 PFLAG2_DRAG_CAN_ACCEPT 1744 * 1 PFLAG2_DRAG_HOVERED 1745 * 1 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT 1746 * 11 PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1747 * 1 1 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT 1748 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1749 * 11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 1750 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1751 * 1 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT 1752 * 1 1 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT 1753 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1754 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1755 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1756 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1757 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1758 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1759 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1760 * 111 PFLAG2_TEXT_DIRECTION_MASK 1761 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1762 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1763 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1764 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1765 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1766 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1767 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1768 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1769 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1770 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1771 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1772 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1773 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1774 * 11 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1775 * 1 PFLAG2_HAS_TRANSIENT_STATE 1776 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1777 * 1 PFLAG2_ACCESSIBILITY_STATE_CHANGED 1778 * 1 PFLAG2_VIEW_QUICK_REJECTED 1779 * 1 PFLAG2_PADDING_RESOLVED 1780 * -------|-------|-------|-------| 1781 */ 1782 1783 /** 1784 * Indicates that this view has reported that it can accept the current drag's content. 1785 * Cleared when the drag operation concludes. 1786 * @hide 1787 */ 1788 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1789 1790 /** 1791 * Indicates that this view is currently directly under the drag location in a 1792 * drag-and-drop operation involving content that it can accept. Cleared when 1793 * the drag exits the view, or when the drag operation concludes. 1794 * @hide 1795 */ 1796 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1797 1798 /** 1799 * Horizontal layout direction of this view is from Left to Right. 1800 * Use with {@link #setLayoutDirection}. 1801 */ 1802 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1803 1804 /** 1805 * Horizontal layout direction of this view is from Right to Left. 1806 * Use with {@link #setLayoutDirection}. 1807 */ 1808 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1809 1810 /** 1811 * Horizontal layout direction of this view is inherited from its parent. 1812 * Use with {@link #setLayoutDirection}. 1813 */ 1814 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1815 1816 /** 1817 * Horizontal layout direction of this view is from deduced from the default language 1818 * script for the locale. Use with {@link #setLayoutDirection}. 1819 */ 1820 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1821 1822 /** 1823 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1824 * @hide 1825 */ 1826 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1827 1828 /** 1829 * Mask for use with private flags indicating bits used for horizontal layout direction. 1830 * @hide 1831 */ 1832 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1833 1834 /** 1835 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1836 * right-to-left direction. 1837 * @hide 1838 */ 1839 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1840 1841 /** 1842 * Indicates whether the view horizontal layout direction has been resolved. 1843 * @hide 1844 */ 1845 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1846 1847 /** 1848 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1849 * @hide 1850 */ 1851 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1852 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1853 1854 /* 1855 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1856 * flag value. 1857 * @hide 1858 */ 1859 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1860 LAYOUT_DIRECTION_LTR, 1861 LAYOUT_DIRECTION_RTL, 1862 LAYOUT_DIRECTION_INHERIT, 1863 LAYOUT_DIRECTION_LOCALE 1864 }; 1865 1866 /** 1867 * Default horizontal layout direction. 1868 */ 1869 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1870 1871 /** 1872 * Default horizontal layout direction. 1873 * @hide 1874 */ 1875 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1876 1877 /** 1878 * Indicates that the view is tracking some sort of transient state 1879 * that the app should not need to be aware of, but that the framework 1880 * should take special care to preserve. 1881 * 1882 * @hide 1883 */ 1884 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22; 1885 1886 /** 1887 * Text direction is inherited thru {@link ViewGroup} 1888 */ 1889 public static final int TEXT_DIRECTION_INHERIT = 0; 1890 1891 /** 1892 * Text direction is using "first strong algorithm". The first strong directional character 1893 * determines the paragraph direction. If there is no strong directional character, the 1894 * paragraph direction is the view's resolved layout direction. 1895 */ 1896 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1897 1898 /** 1899 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1900 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1901 * If there are neither, the paragraph direction is the view's resolved layout direction. 1902 */ 1903 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1904 1905 /** 1906 * Text direction is forced to LTR. 1907 */ 1908 public static final int TEXT_DIRECTION_LTR = 3; 1909 1910 /** 1911 * Text direction is forced to RTL. 1912 */ 1913 public static final int TEXT_DIRECTION_RTL = 4; 1914 1915 /** 1916 * Text direction is coming from the system Locale. 1917 */ 1918 public static final int TEXT_DIRECTION_LOCALE = 5; 1919 1920 /** 1921 * Default text direction is inherited 1922 */ 1923 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 1924 1925 /** 1926 * Default resolved text direction 1927 * @hide 1928 */ 1929 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 1930 1931 /** 1932 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 1933 * @hide 1934 */ 1935 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 1936 1937 /** 1938 * Mask for use with private flags indicating bits used for text direction. 1939 * @hide 1940 */ 1941 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 1942 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1943 1944 /** 1945 * Array of text direction flags for mapping attribute "textDirection" to correct 1946 * flag value. 1947 * @hide 1948 */ 1949 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 1950 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1951 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1952 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1953 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1954 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1955 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1956 }; 1957 1958 /** 1959 * Indicates whether the view text direction has been resolved. 1960 * @hide 1961 */ 1962 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 1963 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1964 1965 /** 1966 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1967 * @hide 1968 */ 1969 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 1970 1971 /** 1972 * Mask for use with private flags indicating bits used for resolved text direction. 1973 * @hide 1974 */ 1975 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 1976 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1977 1978 /** 1979 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 1980 * @hide 1981 */ 1982 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 1983 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1984 1985 /* 1986 * Default text alignment. The text alignment of this View is inherited from its parent. 1987 * Use with {@link #setTextAlignment(int)} 1988 */ 1989 public static final int TEXT_ALIGNMENT_INHERIT = 0; 1990 1991 /** 1992 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 1993 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 1994 * 1995 * Use with {@link #setTextAlignment(int)} 1996 */ 1997 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 1998 1999 /** 2000 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2001 * 2002 * Use with {@link #setTextAlignment(int)} 2003 */ 2004 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2005 2006 /** 2007 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2008 * 2009 * Use with {@link #setTextAlignment(int)} 2010 */ 2011 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2012 2013 /** 2014 * Center the paragraph, e.g. ALIGN_CENTER. 2015 * 2016 * Use with {@link #setTextAlignment(int)} 2017 */ 2018 public static final int TEXT_ALIGNMENT_CENTER = 4; 2019 2020 /** 2021 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2022 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2023 * 2024 * Use with {@link #setTextAlignment(int)} 2025 */ 2026 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2027 2028 /** 2029 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2030 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2031 * 2032 * Use with {@link #setTextAlignment(int)} 2033 */ 2034 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2035 2036 /** 2037 * Default text alignment is inherited 2038 */ 2039 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2040 2041 /** 2042 * Default resolved text alignment 2043 * @hide 2044 */ 2045 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2046 2047 /** 2048 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2049 * @hide 2050 */ 2051 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2052 2053 /** 2054 * Mask for use with private flags indicating bits used for text alignment. 2055 * @hide 2056 */ 2057 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2058 2059 /** 2060 * Array of text direction flags for mapping attribute "textAlignment" to correct 2061 * flag value. 2062 * @hide 2063 */ 2064 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2065 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2066 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2067 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2068 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2069 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2070 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2071 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2072 }; 2073 2074 /** 2075 * Indicates whether the view text alignment has been resolved. 2076 * @hide 2077 */ 2078 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2079 2080 /** 2081 * Bit shift to get the resolved text alignment. 2082 * @hide 2083 */ 2084 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2085 2086 /** 2087 * Mask for use with private flags indicating bits used for text alignment. 2088 * @hide 2089 */ 2090 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2091 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2092 2093 /** 2094 * Indicates whether if the view text alignment has been resolved to gravity 2095 */ 2096 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2097 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2098 2099 // Accessiblity constants for mPrivateFlags2 2100 2101 /** 2102 * Shift for the bits in {@link #mPrivateFlags2} related to the 2103 * "importantForAccessibility" attribute. 2104 */ 2105 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2106 2107 /** 2108 * Automatically determine whether a view is important for accessibility. 2109 */ 2110 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2111 2112 /** 2113 * The view is important for accessibility. 2114 */ 2115 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2116 2117 /** 2118 * The view is not important for accessibility. 2119 */ 2120 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2121 2122 /** 2123 * The default whether the view is important for accessibility. 2124 */ 2125 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2126 2127 /** 2128 * Mask for obtainig the bits which specify how to determine 2129 * whether a view is important for accessibility. 2130 */ 2131 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2132 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO) 2133 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2134 2135 /** 2136 * Flag indicating whether a view has accessibility focus. 2137 */ 2138 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2139 2140 /** 2141 * Flag whether the accessibility state of the subtree rooted at this view changed. 2142 */ 2143 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2144 2145 /** 2146 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2147 * is used to check whether later changes to the view's transform should invalidate the 2148 * view to force the quickReject test to run again. 2149 */ 2150 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2151 2152 /** 2153 * Flag indicating that start/end padding has been resolved into left/right padding 2154 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2155 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2156 * during measurement. In some special cases this is required such as when an adapter-based 2157 * view measures prospective children without attaching them to a window. 2158 */ 2159 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2160 2161 /** 2162 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2163 */ 2164 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2165 2166 /** 2167 * Group of bits indicating that RTL properties resolution is done. 2168 */ 2169 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2170 PFLAG2_TEXT_DIRECTION_RESOLVED | 2171 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2172 PFLAG2_PADDING_RESOLVED | 2173 PFLAG2_DRAWABLE_RESOLVED; 2174 2175 // There are a couple of flags left in mPrivateFlags2 2176 2177 /* End of masks for mPrivateFlags2 */ 2178 2179 /* Masks for mPrivateFlags3 */ 2180 2181 /** 2182 * Flag indicating that view has a transform animation set on it. This is used to track whether 2183 * an animation is cleared between successive frames, in order to tell the associated 2184 * DisplayList to clear its animation matrix. 2185 */ 2186 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2187 2188 /** 2189 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2190 * animation is cleared between successive frames, in order to tell the associated 2191 * DisplayList to restore its alpha value. 2192 */ 2193 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2194 2195 /** 2196 * Flag indicating that the view has been through at least one layout since it 2197 * was last attached to a window. 2198 */ 2199 static final int PFLAG3_IS_LAID_OUT = 0x4; 2200 2201 /** 2202 * Flag indicating that a call to measure() was skipped and should be done 2203 * instead when layout() is invoked. 2204 */ 2205 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2206 2207 2208 /* End of masks for mPrivateFlags3 */ 2209 2210 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2211 2212 /** 2213 * Always allow a user to over-scroll this view, provided it is a 2214 * view that can scroll. 2215 * 2216 * @see #getOverScrollMode() 2217 * @see #setOverScrollMode(int) 2218 */ 2219 public static final int OVER_SCROLL_ALWAYS = 0; 2220 2221 /** 2222 * Allow a user to over-scroll this view only if the content is large 2223 * enough to meaningfully scroll, provided it is a view that can scroll. 2224 * 2225 * @see #getOverScrollMode() 2226 * @see #setOverScrollMode(int) 2227 */ 2228 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2229 2230 /** 2231 * Never allow a user to over-scroll this view. 2232 * 2233 * @see #getOverScrollMode() 2234 * @see #setOverScrollMode(int) 2235 */ 2236 public static final int OVER_SCROLL_NEVER = 2; 2237 2238 /** 2239 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2240 * requested the system UI (status bar) to be visible (the default). 2241 * 2242 * @see #setSystemUiVisibility(int) 2243 */ 2244 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2245 2246 /** 2247 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2248 * system UI to enter an unobtrusive "low profile" mode. 2249 * 2250 * <p>This is for use in games, book readers, video players, or any other 2251 * "immersive" application where the usual system chrome is deemed too distracting. 2252 * 2253 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2254 * 2255 * @see #setSystemUiVisibility(int) 2256 */ 2257 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2258 2259 /** 2260 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2261 * system navigation be temporarily hidden. 2262 * 2263 * <p>This is an even less obtrusive state than that called for by 2264 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2265 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2266 * those to disappear. This is useful (in conjunction with the 2267 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2268 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2269 * window flags) for displaying content using every last pixel on the display. 2270 * 2271 * <p>There is a limitation: because navigation controls are so important, the least user 2272 * interaction will cause them to reappear immediately. When this happens, both 2273 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2274 * so that both elements reappear at the same time. 2275 * 2276 * @see #setSystemUiVisibility(int) 2277 */ 2278 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2279 2280 /** 2281 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2282 * into the normal fullscreen mode so that its content can take over the screen 2283 * while still allowing the user to interact with the application. 2284 * 2285 * <p>This has the same visual effect as 2286 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2287 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2288 * meaning that non-critical screen decorations (such as the status bar) will be 2289 * hidden while the user is in the View's window, focusing the experience on 2290 * that content. Unlike the window flag, if you are using ActionBar in 2291 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2292 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2293 * hide the action bar. 2294 * 2295 * <p>This approach to going fullscreen is best used over the window flag when 2296 * it is a transient state -- that is, the application does this at certain 2297 * points in its user interaction where it wants to allow the user to focus 2298 * on content, but not as a continuous state. For situations where the application 2299 * would like to simply stay full screen the entire time (such as a game that 2300 * wants to take over the screen), the 2301 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2302 * is usually a better approach. The state set here will be removed by the system 2303 * in various situations (such as the user moving to another application) like 2304 * the other system UI states. 2305 * 2306 * <p>When using this flag, the application should provide some easy facility 2307 * for the user to go out of it. A common example would be in an e-book 2308 * reader, where tapping on the screen brings back whatever screen and UI 2309 * decorations that had been hidden while the user was immersed in reading 2310 * the book. 2311 * 2312 * @see #setSystemUiVisibility(int) 2313 */ 2314 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2315 2316 /** 2317 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2318 * flags, we would like a stable view of the content insets given to 2319 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2320 * will always represent the worst case that the application can expect 2321 * as a continuous state. In the stock Android UI this is the space for 2322 * the system bar, nav bar, and status bar, but not more transient elements 2323 * such as an input method. 2324 * 2325 * The stable layout your UI sees is based on the system UI modes you can 2326 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2327 * then you will get a stable layout for changes of the 2328 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2329 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2330 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2331 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2332 * with a stable layout. (Note that you should avoid using 2333 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2334 * 2335 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2336 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2337 * then a hidden status bar will be considered a "stable" state for purposes 2338 * here. This allows your UI to continually hide the status bar, while still 2339 * using the system UI flags to hide the action bar while still retaining 2340 * a stable layout. Note that changing the window fullscreen flag will never 2341 * provide a stable layout for a clean transition. 2342 * 2343 * <p>If you are using ActionBar in 2344 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2345 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2346 * insets it adds to those given to the application. 2347 */ 2348 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2349 2350 /** 2351 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2352 * to be layed out as if it has requested 2353 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2354 * allows it to avoid artifacts when switching in and out of that mode, at 2355 * the expense that some of its user interface may be covered by screen 2356 * decorations when they are shown. You can perform layout of your inner 2357 * UI elements to account for the navigation system UI through the 2358 * {@link #fitSystemWindows(Rect)} method. 2359 */ 2360 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2361 2362 /** 2363 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2364 * to be layed out as if it has requested 2365 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2366 * allows it to avoid artifacts when switching in and out of that mode, at 2367 * the expense that some of its user interface may be covered by screen 2368 * decorations when they are shown. You can perform layout of your inner 2369 * UI elements to account for non-fullscreen system UI through the 2370 * {@link #fitSystemWindows(Rect)} method. 2371 */ 2372 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2373 2374 /** 2375 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2376 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2377 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2378 * experience while also hiding the system bars. If this flag is not set, 2379 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2380 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2381 * if the user swipes from the top of the screen. 2382 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2383 * system gestures, such as swiping from the top of the screen. These transient system bars 2384 * will overlay app’s content, may have some degree of transparency, and will automatically 2385 * hide after a short timeout. 2386 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2387 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2388 * with one or both of those flags.</p> 2389 */ 2390 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2391 2392 /** 2393 * Flag for {@link #setSystemUiVisibility(int)}: View would like the status bar to have 2394 * transparency. 2395 * 2396 * <p>The transparency request may be denied if the bar is in another mode with a specific 2397 * style, like {@link #SYSTEM_UI_FLAG_IMMERSIVE immersive mode}. 2398 */ 2399 public static final int SYSTEM_UI_FLAG_TRANSPARENT_STATUS = 0x00001000; 2400 2401 /** 2402 * Flag for {@link #setSystemUiVisibility(int)}: View would like the navigation bar to have 2403 * transparency. 2404 * 2405 * <p>The transparency request may be denied if the bar is in another mode with a specific 2406 * style, like {@link #SYSTEM_UI_FLAG_IMMERSIVE immersive mode}. 2407 */ 2408 public static final int SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION = 0x00002000; 2409 2410 /** 2411 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2412 */ 2413 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2414 2415 /** 2416 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2417 */ 2418 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2419 2420 /** 2421 * @hide 2422 * 2423 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2424 * out of the public fields to keep the undefined bits out of the developer's way. 2425 * 2426 * Flag to make the status bar not expandable. Unless you also 2427 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2428 */ 2429 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2430 2431 /** 2432 * @hide 2433 * 2434 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2435 * out of the public fields to keep the undefined bits out of the developer's way. 2436 * 2437 * Flag to hide notification icons and scrolling ticker text. 2438 */ 2439 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2440 2441 /** 2442 * @hide 2443 * 2444 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2445 * out of the public fields to keep the undefined bits out of the developer's way. 2446 * 2447 * Flag to disable incoming notification alerts. This will not block 2448 * icons, but it will block sound, vibrating and other visual or aural notifications. 2449 */ 2450 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2451 2452 /** 2453 * @hide 2454 * 2455 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2456 * out of the public fields to keep the undefined bits out of the developer's way. 2457 * 2458 * Flag to hide only the scrolling ticker. Note that 2459 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2460 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2461 */ 2462 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2463 2464 /** 2465 * @hide 2466 * 2467 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2468 * out of the public fields to keep the undefined bits out of the developer's way. 2469 * 2470 * Flag to hide the center system info area. 2471 */ 2472 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2473 2474 /** 2475 * @hide 2476 * 2477 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2478 * out of the public fields to keep the undefined bits out of the developer's way. 2479 * 2480 * Flag to hide only the home button. Don't use this 2481 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2482 */ 2483 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2484 2485 /** 2486 * @hide 2487 * 2488 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2489 * out of the public fields to keep the undefined bits out of the developer's way. 2490 * 2491 * Flag to hide only the back button. Don't use this 2492 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2493 */ 2494 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2495 2496 /** 2497 * @hide 2498 * 2499 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2500 * out of the public fields to keep the undefined bits out of the developer's way. 2501 * 2502 * Flag to hide only the clock. You might use this if your activity has 2503 * its own clock making the status bar's clock redundant. 2504 */ 2505 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2506 2507 /** 2508 * @hide 2509 * 2510 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2511 * out of the public fields to keep the undefined bits out of the developer's way. 2512 * 2513 * Flag to hide only the recent apps button. Don't use this 2514 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2515 */ 2516 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2517 2518 /** 2519 * @hide 2520 * 2521 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2522 * out of the public fields to keep the undefined bits out of the developer's way. 2523 * 2524 * Flag to disable the global search gesture. Don't use this 2525 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2526 */ 2527 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2528 2529 /** 2530 * @hide 2531 * 2532 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2533 * out of the public fields to keep the undefined bits out of the developer's way. 2534 * 2535 * Flag to specify that the status bar is displayed in transient mode. 2536 */ 2537 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2538 2539 /** 2540 * @hide 2541 * 2542 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2543 * out of the public fields to keep the undefined bits out of the developer's way. 2544 * 2545 * Flag to specify that the navigation bar is displayed in transient mode. 2546 */ 2547 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2548 2549 /** 2550 * @hide 2551 * 2552 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2553 * out of the public fields to keep the undefined bits out of the developer's way. 2554 * 2555 * Flag to specify that the hidden status bar would like to be shown. 2556 */ 2557 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2558 2559 /** 2560 * @hide 2561 * 2562 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2563 * out of the public fields to keep the undefined bits out of the developer's way. 2564 * 2565 * Flag to specify that the hidden navigation bar would like to be shown. 2566 */ 2567 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2568 2569 /** 2570 * @hide 2571 */ 2572 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2573 2574 /** 2575 * These are the system UI flags that can be cleared by events outside 2576 * of an application. Currently this is just the ability to tap on the 2577 * screen while hiding the navigation bar to have it return. 2578 * @hide 2579 */ 2580 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2581 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2582 | SYSTEM_UI_FLAG_FULLSCREEN; 2583 2584 /** 2585 * Flags that can impact the layout in relation to system UI. 2586 */ 2587 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2588 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2589 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2590 2591 /** 2592 * Find views that render the specified text. 2593 * 2594 * @see #findViewsWithText(ArrayList, CharSequence, int) 2595 */ 2596 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2597 2598 /** 2599 * Find find views that contain the specified content description. 2600 * 2601 * @see #findViewsWithText(ArrayList, CharSequence, int) 2602 */ 2603 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2604 2605 /** 2606 * Find views that contain {@link AccessibilityNodeProvider}. Such 2607 * a View is a root of virtual view hierarchy and may contain the searched 2608 * text. If this flag is set Views with providers are automatically 2609 * added and it is a responsibility of the client to call the APIs of 2610 * the provider to determine whether the virtual tree rooted at this View 2611 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2612 * represeting the virtual views with this text. 2613 * 2614 * @see #findViewsWithText(ArrayList, CharSequence, int) 2615 * 2616 * @hide 2617 */ 2618 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2619 2620 /** 2621 * The undefined cursor position. 2622 * 2623 * @hide 2624 */ 2625 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2626 2627 /** 2628 * Indicates that the screen has changed state and is now off. 2629 * 2630 * @see #onScreenStateChanged(int) 2631 */ 2632 public static final int SCREEN_STATE_OFF = 0x0; 2633 2634 /** 2635 * Indicates that the screen has changed state and is now on. 2636 * 2637 * @see #onScreenStateChanged(int) 2638 */ 2639 public static final int SCREEN_STATE_ON = 0x1; 2640 2641 /** 2642 * Controls the over-scroll mode for this view. 2643 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2644 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2645 * and {@link #OVER_SCROLL_NEVER}. 2646 */ 2647 private int mOverScrollMode; 2648 2649 /** 2650 * The parent this view is attached to. 2651 * {@hide} 2652 * 2653 * @see #getParent() 2654 */ 2655 protected ViewParent mParent; 2656 2657 /** 2658 * {@hide} 2659 */ 2660 AttachInfo mAttachInfo; 2661 2662 /** 2663 * {@hide} 2664 */ 2665 @ViewDebug.ExportedProperty(flagMapping = { 2666 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2667 name = "FORCE_LAYOUT"), 2668 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2669 name = "LAYOUT_REQUIRED"), 2670 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2671 name = "DRAWING_CACHE_INVALID", outputIf = false), 2672 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2673 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2674 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2675 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2676 }) 2677 int mPrivateFlags; 2678 int mPrivateFlags2; 2679 int mPrivateFlags3; 2680 2681 /** 2682 * This view's request for the visibility of the status bar. 2683 * @hide 2684 */ 2685 @ViewDebug.ExportedProperty(flagMapping = { 2686 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2687 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2688 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2689 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2690 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2691 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2692 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2693 equals = SYSTEM_UI_FLAG_VISIBLE, 2694 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2695 }) 2696 int mSystemUiVisibility; 2697 2698 /** 2699 * Reference count for transient state. 2700 * @see #setHasTransientState(boolean) 2701 */ 2702 int mTransientStateCount = 0; 2703 2704 /** 2705 * Count of how many windows this view has been attached to. 2706 */ 2707 int mWindowAttachCount; 2708 2709 /** 2710 * The layout parameters associated with this view and used by the parent 2711 * {@link android.view.ViewGroup} to determine how this view should be 2712 * laid out. 2713 * {@hide} 2714 */ 2715 protected ViewGroup.LayoutParams mLayoutParams; 2716 2717 /** 2718 * The view flags hold various views states. 2719 * {@hide} 2720 */ 2721 @ViewDebug.ExportedProperty 2722 int mViewFlags; 2723 2724 static class TransformationInfo { 2725 /** 2726 * The transform matrix for the View. This transform is calculated internally 2727 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2728 * is used by default. Do *not* use this variable directly; instead call 2729 * getMatrix(), which will automatically recalculate the matrix if necessary 2730 * to get the correct matrix based on the latest rotation and scale properties. 2731 */ 2732 private final Matrix mMatrix = new Matrix(); 2733 2734 /** 2735 * The transform matrix for the View. This transform is calculated internally 2736 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2737 * is used by default. Do *not* use this variable directly; instead call 2738 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2739 * to get the correct matrix based on the latest rotation and scale properties. 2740 */ 2741 private Matrix mInverseMatrix; 2742 2743 /** 2744 * An internal variable that tracks whether we need to recalculate the 2745 * transform matrix, based on whether the rotation or scaleX/Y properties 2746 * have changed since the matrix was last calculated. 2747 */ 2748 boolean mMatrixDirty = false; 2749 2750 /** 2751 * An internal variable that tracks whether we need to recalculate the 2752 * transform matrix, based on whether the rotation or scaleX/Y properties 2753 * have changed since the matrix was last calculated. 2754 */ 2755 private boolean mInverseMatrixDirty = true; 2756 2757 /** 2758 * A variable that tracks whether we need to recalculate the 2759 * transform matrix, based on whether the rotation or scaleX/Y properties 2760 * have changed since the matrix was last calculated. This variable 2761 * is only valid after a call to updateMatrix() or to a function that 2762 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2763 */ 2764 private boolean mMatrixIsIdentity = true; 2765 2766 /** 2767 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2768 */ 2769 private Camera mCamera = null; 2770 2771 /** 2772 * This matrix is used when computing the matrix for 3D rotations. 2773 */ 2774 private Matrix matrix3D = null; 2775 2776 /** 2777 * These prev values are used to recalculate a centered pivot point when necessary. The 2778 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2779 * set), so thes values are only used then as well. 2780 */ 2781 private int mPrevWidth = -1; 2782 private int mPrevHeight = -1; 2783 2784 /** 2785 * The degrees rotation around the vertical axis through the pivot point. 2786 */ 2787 @ViewDebug.ExportedProperty 2788 float mRotationY = 0f; 2789 2790 /** 2791 * The degrees rotation around the horizontal axis through the pivot point. 2792 */ 2793 @ViewDebug.ExportedProperty 2794 float mRotationX = 0f; 2795 2796 /** 2797 * The degrees rotation around the pivot point. 2798 */ 2799 @ViewDebug.ExportedProperty 2800 float mRotation = 0f; 2801 2802 /** 2803 * The amount of translation of the object away from its left property (post-layout). 2804 */ 2805 @ViewDebug.ExportedProperty 2806 float mTranslationX = 0f; 2807 2808 /** 2809 * The amount of translation of the object away from its top property (post-layout). 2810 */ 2811 @ViewDebug.ExportedProperty 2812 float mTranslationY = 0f; 2813 2814 /** 2815 * The amount of scale in the x direction around the pivot point. A 2816 * value of 1 means no scaling is applied. 2817 */ 2818 @ViewDebug.ExportedProperty 2819 float mScaleX = 1f; 2820 2821 /** 2822 * The amount of scale in the y direction around the pivot point. A 2823 * value of 1 means no scaling is applied. 2824 */ 2825 @ViewDebug.ExportedProperty 2826 float mScaleY = 1f; 2827 2828 /** 2829 * The x location of the point around which the view is rotated and scaled. 2830 */ 2831 @ViewDebug.ExportedProperty 2832 float mPivotX = 0f; 2833 2834 /** 2835 * The y location of the point around which the view is rotated and scaled. 2836 */ 2837 @ViewDebug.ExportedProperty 2838 float mPivotY = 0f; 2839 2840 /** 2841 * The opacity of the View. This is a value from 0 to 1, where 0 means 2842 * completely transparent and 1 means completely opaque. 2843 */ 2844 @ViewDebug.ExportedProperty 2845 float mAlpha = 1f; 2846 } 2847 2848 TransformationInfo mTransformationInfo; 2849 2850 /** 2851 * Current clip bounds. to which all drawing of this view are constrained. 2852 */ 2853 private Rect mClipBounds = null; 2854 2855 private boolean mLastIsOpaque; 2856 2857 /** 2858 * Convenience value to check for float values that are close enough to zero to be considered 2859 * zero. 2860 */ 2861 private static final float NONZERO_EPSILON = .001f; 2862 2863 /** 2864 * The distance in pixels from the left edge of this view's parent 2865 * to the left edge of this view. 2866 * {@hide} 2867 */ 2868 @ViewDebug.ExportedProperty(category = "layout") 2869 protected int mLeft; 2870 /** 2871 * The distance in pixels from the left edge of this view's parent 2872 * to the right edge of this view. 2873 * {@hide} 2874 */ 2875 @ViewDebug.ExportedProperty(category = "layout") 2876 protected int mRight; 2877 /** 2878 * The distance in pixels from the top edge of this view's parent 2879 * to the top edge of this view. 2880 * {@hide} 2881 */ 2882 @ViewDebug.ExportedProperty(category = "layout") 2883 protected int mTop; 2884 /** 2885 * The distance in pixels from the top edge of this view's parent 2886 * to the bottom edge of this view. 2887 * {@hide} 2888 */ 2889 @ViewDebug.ExportedProperty(category = "layout") 2890 protected int mBottom; 2891 2892 /** 2893 * The offset, in pixels, by which the content of this view is scrolled 2894 * horizontally. 2895 * {@hide} 2896 */ 2897 @ViewDebug.ExportedProperty(category = "scrolling") 2898 protected int mScrollX; 2899 /** 2900 * The offset, in pixels, by which the content of this view is scrolled 2901 * vertically. 2902 * {@hide} 2903 */ 2904 @ViewDebug.ExportedProperty(category = "scrolling") 2905 protected int mScrollY; 2906 2907 /** 2908 * The left padding in pixels, that is the distance in pixels between the 2909 * left edge of this view and the left edge of its content. 2910 * {@hide} 2911 */ 2912 @ViewDebug.ExportedProperty(category = "padding") 2913 protected int mPaddingLeft = 0; 2914 /** 2915 * The right padding in pixels, that is the distance in pixels between the 2916 * right edge of this view and the right edge of its content. 2917 * {@hide} 2918 */ 2919 @ViewDebug.ExportedProperty(category = "padding") 2920 protected int mPaddingRight = 0; 2921 /** 2922 * The top padding in pixels, that is the distance in pixels between the 2923 * top edge of this view and the top edge of its content. 2924 * {@hide} 2925 */ 2926 @ViewDebug.ExportedProperty(category = "padding") 2927 protected int mPaddingTop; 2928 /** 2929 * The bottom padding in pixels, that is the distance in pixels between the 2930 * bottom edge of this view and the bottom edge of its content. 2931 * {@hide} 2932 */ 2933 @ViewDebug.ExportedProperty(category = "padding") 2934 protected int mPaddingBottom; 2935 2936 /** 2937 * The layout insets in pixels, that is the distance in pixels between the 2938 * visible edges of this view its bounds. 2939 */ 2940 private Insets mLayoutInsets; 2941 2942 /** 2943 * Briefly describes the view and is primarily used for accessibility support. 2944 */ 2945 private CharSequence mContentDescription; 2946 2947 /** 2948 * Specifies the id of a view for which this view serves as a label for 2949 * accessibility purposes. 2950 */ 2951 private int mLabelForId = View.NO_ID; 2952 2953 /** 2954 * Predicate for matching labeled view id with its label for 2955 * accessibility purposes. 2956 */ 2957 private MatchLabelForPredicate mMatchLabelForPredicate; 2958 2959 /** 2960 * Predicate for matching a view by its id. 2961 */ 2962 private MatchIdPredicate mMatchIdPredicate; 2963 2964 /** 2965 * Cache the paddingRight set by the user to append to the scrollbar's size. 2966 * 2967 * @hide 2968 */ 2969 @ViewDebug.ExportedProperty(category = "padding") 2970 protected int mUserPaddingRight; 2971 2972 /** 2973 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2974 * 2975 * @hide 2976 */ 2977 @ViewDebug.ExportedProperty(category = "padding") 2978 protected int mUserPaddingBottom; 2979 2980 /** 2981 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2982 * 2983 * @hide 2984 */ 2985 @ViewDebug.ExportedProperty(category = "padding") 2986 protected int mUserPaddingLeft; 2987 2988 /** 2989 * Cache the paddingStart set by the user to append to the scrollbar's size. 2990 * 2991 */ 2992 @ViewDebug.ExportedProperty(category = "padding") 2993 int mUserPaddingStart; 2994 2995 /** 2996 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2997 * 2998 */ 2999 @ViewDebug.ExportedProperty(category = "padding") 3000 int mUserPaddingEnd; 3001 3002 /** 3003 * Cache initial left padding. 3004 * 3005 * @hide 3006 */ 3007 int mUserPaddingLeftInitial; 3008 3009 /** 3010 * Cache initial right padding. 3011 * 3012 * @hide 3013 */ 3014 int mUserPaddingRightInitial; 3015 3016 /** 3017 * Default undefined padding 3018 */ 3019 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3020 3021 /** 3022 * @hide 3023 */ 3024 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3025 /** 3026 * @hide 3027 */ 3028 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3029 3030 private LongSparseLongArray mMeasureCache; 3031 3032 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3033 private Drawable mBackground; 3034 3035 private int mBackgroundResource; 3036 private boolean mBackgroundSizeChanged; 3037 3038 static class ListenerInfo { 3039 /** 3040 * Listener used to dispatch focus change events. 3041 * This field should be made private, so it is hidden from the SDK. 3042 * {@hide} 3043 */ 3044 protected OnFocusChangeListener mOnFocusChangeListener; 3045 3046 /** 3047 * Listeners for layout change events. 3048 */ 3049 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3050 3051 /** 3052 * Listeners for attach events. 3053 */ 3054 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3055 3056 /** 3057 * Listener used to dispatch click events. 3058 * This field should be made private, so it is hidden from the SDK. 3059 * {@hide} 3060 */ 3061 public OnClickListener mOnClickListener; 3062 3063 /** 3064 * Listener used to dispatch long click events. 3065 * This field should be made private, so it is hidden from the SDK. 3066 * {@hide} 3067 */ 3068 protected OnLongClickListener mOnLongClickListener; 3069 3070 /** 3071 * Listener used to build the context menu. 3072 * This field should be made private, so it is hidden from the SDK. 3073 * {@hide} 3074 */ 3075 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3076 3077 private OnKeyListener mOnKeyListener; 3078 3079 private OnTouchListener mOnTouchListener; 3080 3081 private OnHoverListener mOnHoverListener; 3082 3083 private OnGenericMotionListener mOnGenericMotionListener; 3084 3085 private OnDragListener mOnDragListener; 3086 3087 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3088 } 3089 3090 ListenerInfo mListenerInfo; 3091 3092 /** 3093 * The application environment this view lives in. 3094 * This field should be made private, so it is hidden from the SDK. 3095 * {@hide} 3096 */ 3097 protected Context mContext; 3098 3099 private final Resources mResources; 3100 3101 private ScrollabilityCache mScrollCache; 3102 3103 private int[] mDrawableState = null; 3104 3105 /** 3106 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3107 * the user may specify which view to go to next. 3108 */ 3109 private int mNextFocusLeftId = View.NO_ID; 3110 3111 /** 3112 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3113 * the user may specify which view to go to next. 3114 */ 3115 private int mNextFocusRightId = View.NO_ID; 3116 3117 /** 3118 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3119 * the user may specify which view to go to next. 3120 */ 3121 private int mNextFocusUpId = View.NO_ID; 3122 3123 /** 3124 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3125 * the user may specify which view to go to next. 3126 */ 3127 private int mNextFocusDownId = View.NO_ID; 3128 3129 /** 3130 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3131 * the user may specify which view to go to next. 3132 */ 3133 int mNextFocusForwardId = View.NO_ID; 3134 3135 private CheckForLongPress mPendingCheckForLongPress; 3136 private CheckForTap mPendingCheckForTap = null; 3137 private PerformClick mPerformClick; 3138 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3139 3140 private UnsetPressedState mUnsetPressedState; 3141 3142 /** 3143 * Whether the long press's action has been invoked. The tap's action is invoked on the 3144 * up event while a long press is invoked as soon as the long press duration is reached, so 3145 * a long press could be performed before the tap is checked, in which case the tap's action 3146 * should not be invoked. 3147 */ 3148 private boolean mHasPerformedLongPress; 3149 3150 /** 3151 * The minimum height of the view. We'll try our best to have the height 3152 * of this view to at least this amount. 3153 */ 3154 @ViewDebug.ExportedProperty(category = "measurement") 3155 private int mMinHeight; 3156 3157 /** 3158 * The minimum width of the view. We'll try our best to have the width 3159 * of this view to at least this amount. 3160 */ 3161 @ViewDebug.ExportedProperty(category = "measurement") 3162 private int mMinWidth; 3163 3164 /** 3165 * The delegate to handle touch events that are physically in this view 3166 * but should be handled by another view. 3167 */ 3168 private TouchDelegate mTouchDelegate = null; 3169 3170 /** 3171 * Solid color to use as a background when creating the drawing cache. Enables 3172 * the cache to use 16 bit bitmaps instead of 32 bit. 3173 */ 3174 private int mDrawingCacheBackgroundColor = 0; 3175 3176 /** 3177 * Special tree observer used when mAttachInfo is null. 3178 */ 3179 private ViewTreeObserver mFloatingTreeObserver; 3180 3181 /** 3182 * Cache the touch slop from the context that created the view. 3183 */ 3184 private int mTouchSlop; 3185 3186 /** 3187 * Object that handles automatic animation of view properties. 3188 */ 3189 private ViewPropertyAnimator mAnimator = null; 3190 3191 /** 3192 * Flag indicating that a drag can cross window boundaries. When 3193 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3194 * with this flag set, all visible applications will be able to participate 3195 * in the drag operation and receive the dragged content. 3196 * 3197 * @hide 3198 */ 3199 public static final int DRAG_FLAG_GLOBAL = 1; 3200 3201 /** 3202 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3203 */ 3204 private float mVerticalScrollFactor; 3205 3206 /** 3207 * Position of the vertical scroll bar. 3208 */ 3209 private int mVerticalScrollbarPosition; 3210 3211 /** 3212 * Position the scroll bar at the default position as determined by the system. 3213 */ 3214 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3215 3216 /** 3217 * Position the scroll bar along the left edge. 3218 */ 3219 public static final int SCROLLBAR_POSITION_LEFT = 1; 3220 3221 /** 3222 * Position the scroll bar along the right edge. 3223 */ 3224 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3225 3226 /** 3227 * Indicates that the view does not have a layer. 3228 * 3229 * @see #getLayerType() 3230 * @see #setLayerType(int, android.graphics.Paint) 3231 * @see #LAYER_TYPE_SOFTWARE 3232 * @see #LAYER_TYPE_HARDWARE 3233 */ 3234 public static final int LAYER_TYPE_NONE = 0; 3235 3236 /** 3237 * <p>Indicates that the view has a software layer. A software layer is backed 3238 * by a bitmap and causes the view to be rendered using Android's software 3239 * rendering pipeline, even if hardware acceleration is enabled.</p> 3240 * 3241 * <p>Software layers have various usages:</p> 3242 * <p>When the application is not using hardware acceleration, a software layer 3243 * is useful to apply a specific color filter and/or blending mode and/or 3244 * translucency to a view and all its children.</p> 3245 * <p>When the application is using hardware acceleration, a software layer 3246 * is useful to render drawing primitives not supported by the hardware 3247 * accelerated pipeline. It can also be used to cache a complex view tree 3248 * into a texture and reduce the complexity of drawing operations. For instance, 3249 * when animating a complex view tree with a translation, a software layer can 3250 * be used to render the view tree only once.</p> 3251 * <p>Software layers should be avoided when the affected view tree updates 3252 * often. Every update will require to re-render the software layer, which can 3253 * potentially be slow (particularly when hardware acceleration is turned on 3254 * since the layer will have to be uploaded into a hardware texture after every 3255 * update.)</p> 3256 * 3257 * @see #getLayerType() 3258 * @see #setLayerType(int, android.graphics.Paint) 3259 * @see #LAYER_TYPE_NONE 3260 * @see #LAYER_TYPE_HARDWARE 3261 */ 3262 public static final int LAYER_TYPE_SOFTWARE = 1; 3263 3264 /** 3265 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3266 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3267 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3268 * rendering pipeline, but only if hardware acceleration is turned on for the 3269 * view hierarchy. When hardware acceleration is turned off, hardware layers 3270 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3271 * 3272 * <p>A hardware layer is useful to apply a specific color filter and/or 3273 * blending mode and/or translucency to a view and all its children.</p> 3274 * <p>A hardware layer can be used to cache a complex view tree into a 3275 * texture and reduce the complexity of drawing operations. For instance, 3276 * when animating a complex view tree with a translation, a hardware layer can 3277 * be used to render the view tree only once.</p> 3278 * <p>A hardware layer can also be used to increase the rendering quality when 3279 * rotation transformations are applied on a view. It can also be used to 3280 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3281 * 3282 * @see #getLayerType() 3283 * @see #setLayerType(int, android.graphics.Paint) 3284 * @see #LAYER_TYPE_NONE 3285 * @see #LAYER_TYPE_SOFTWARE 3286 */ 3287 public static final int LAYER_TYPE_HARDWARE = 2; 3288 3289 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3290 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3291 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3292 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3293 }) 3294 int mLayerType = LAYER_TYPE_NONE; 3295 Paint mLayerPaint; 3296 Rect mLocalDirtyRect; 3297 private HardwareLayer mHardwareLayer; 3298 3299 /** 3300 * Set to true when drawing cache is enabled and cannot be created. 3301 * 3302 * @hide 3303 */ 3304 public boolean mCachingFailed; 3305 private Bitmap mDrawingCache; 3306 private Bitmap mUnscaledDrawingCache; 3307 3308 DisplayList mDisplayList; 3309 3310 /** 3311 * Set to true when the view is sending hover accessibility events because it 3312 * is the innermost hovered view. 3313 */ 3314 private boolean mSendingHoverAccessibilityEvents; 3315 3316 /** 3317 * Delegate for injecting accessibility functionality. 3318 */ 3319 AccessibilityDelegate mAccessibilityDelegate; 3320 3321 /** 3322 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3323 * and add/remove objects to/from the overlay directly through the Overlay methods. 3324 */ 3325 ViewOverlay mOverlay; 3326 3327 /** 3328 * Consistency verifier for debugging purposes. 3329 * @hide 3330 */ 3331 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3332 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3333 new InputEventConsistencyVerifier(this, 0) : null; 3334 3335 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3336 3337 /** 3338 * Simple constructor to use when creating a view from code. 3339 * 3340 * @param context The Context the view is running in, through which it can 3341 * access the current theme, resources, etc. 3342 */ 3343 public View(Context context) { 3344 mContext = context; 3345 mResources = context != null ? context.getResources() : null; 3346 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3347 // Set some flags defaults 3348 mPrivateFlags2 = 3349 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3350 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3351 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3352 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3353 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3354 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3355 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3356 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3357 mUserPaddingStart = UNDEFINED_PADDING; 3358 mUserPaddingEnd = UNDEFINED_PADDING; 3359 3360 if (!sUseBrokenMakeMeasureSpec && context != null && 3361 context.getApplicationInfo().targetSdkVersion <= JELLY_BEAN_MR1) { 3362 // Older apps may need this compatibility hack for measurement. 3363 sUseBrokenMakeMeasureSpec = true; 3364 } 3365 } 3366 3367 /** 3368 * Constructor that is called when inflating a view from XML. This is called 3369 * when a view is being constructed from an XML file, supplying attributes 3370 * that were specified in the XML file. This version uses a default style of 3371 * 0, so the only attribute values applied are those in the Context's Theme 3372 * and the given AttributeSet. 3373 * 3374 * <p> 3375 * The method onFinishInflate() will be called after all children have been 3376 * added. 3377 * 3378 * @param context The Context the view is running in, through which it can 3379 * access the current theme, resources, etc. 3380 * @param attrs The attributes of the XML tag that is inflating the view. 3381 * @see #View(Context, AttributeSet, int) 3382 */ 3383 public View(Context context, AttributeSet attrs) { 3384 this(context, attrs, 0); 3385 } 3386 3387 /** 3388 * Perform inflation from XML and apply a class-specific base style. This 3389 * constructor of View allows subclasses to use their own base style when 3390 * they are inflating. For example, a Button class's constructor would call 3391 * this version of the super class constructor and supply 3392 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 3393 * the theme's button style to modify all of the base view attributes (in 3394 * particular its background) as well as the Button class's attributes. 3395 * 3396 * @param context The Context the view is running in, through which it can 3397 * access the current theme, resources, etc. 3398 * @param attrs The attributes of the XML tag that is inflating the view. 3399 * @param defStyleAttr An attribute in the current theme that contains a 3400 * reference to a style resource to apply to this view. If 0, no 3401 * default style will be applied. 3402 * @see #View(Context, AttributeSet) 3403 */ 3404 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3405 this(context); 3406 3407 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 3408 defStyleAttr, 0); 3409 3410 Drawable background = null; 3411 3412 int leftPadding = -1; 3413 int topPadding = -1; 3414 int rightPadding = -1; 3415 int bottomPadding = -1; 3416 int startPadding = UNDEFINED_PADDING; 3417 int endPadding = UNDEFINED_PADDING; 3418 3419 int padding = -1; 3420 3421 int viewFlagValues = 0; 3422 int viewFlagMasks = 0; 3423 3424 boolean setScrollContainer = false; 3425 3426 int x = 0; 3427 int y = 0; 3428 3429 float tx = 0; 3430 float ty = 0; 3431 float rotation = 0; 3432 float rotationX = 0; 3433 float rotationY = 0; 3434 float sx = 1f; 3435 float sy = 1f; 3436 boolean transformSet = false; 3437 3438 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3439 int overScrollMode = mOverScrollMode; 3440 boolean initializeScrollbars = false; 3441 3442 boolean leftPaddingDefined = false; 3443 boolean rightPaddingDefined = false; 3444 boolean startPaddingDefined = false; 3445 boolean endPaddingDefined = false; 3446 3447 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3448 3449 final int N = a.getIndexCount(); 3450 for (int i = 0; i < N; i++) { 3451 int attr = a.getIndex(i); 3452 switch (attr) { 3453 case com.android.internal.R.styleable.View_background: 3454 background = a.getDrawable(attr); 3455 break; 3456 case com.android.internal.R.styleable.View_padding: 3457 padding = a.getDimensionPixelSize(attr, -1); 3458 mUserPaddingLeftInitial = padding; 3459 mUserPaddingRightInitial = padding; 3460 leftPaddingDefined = true; 3461 rightPaddingDefined = true; 3462 break; 3463 case com.android.internal.R.styleable.View_paddingLeft: 3464 leftPadding = a.getDimensionPixelSize(attr, -1); 3465 mUserPaddingLeftInitial = leftPadding; 3466 leftPaddingDefined = true; 3467 break; 3468 case com.android.internal.R.styleable.View_paddingTop: 3469 topPadding = a.getDimensionPixelSize(attr, -1); 3470 break; 3471 case com.android.internal.R.styleable.View_paddingRight: 3472 rightPadding = a.getDimensionPixelSize(attr, -1); 3473 mUserPaddingRightInitial = rightPadding; 3474 rightPaddingDefined = true; 3475 break; 3476 case com.android.internal.R.styleable.View_paddingBottom: 3477 bottomPadding = a.getDimensionPixelSize(attr, -1); 3478 break; 3479 case com.android.internal.R.styleable.View_paddingStart: 3480 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3481 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3482 break; 3483 case com.android.internal.R.styleable.View_paddingEnd: 3484 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3485 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3486 break; 3487 case com.android.internal.R.styleable.View_scrollX: 3488 x = a.getDimensionPixelOffset(attr, 0); 3489 break; 3490 case com.android.internal.R.styleable.View_scrollY: 3491 y = a.getDimensionPixelOffset(attr, 0); 3492 break; 3493 case com.android.internal.R.styleable.View_alpha: 3494 setAlpha(a.getFloat(attr, 1f)); 3495 break; 3496 case com.android.internal.R.styleable.View_transformPivotX: 3497 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3498 break; 3499 case com.android.internal.R.styleable.View_transformPivotY: 3500 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3501 break; 3502 case com.android.internal.R.styleable.View_translationX: 3503 tx = a.getDimensionPixelOffset(attr, 0); 3504 transformSet = true; 3505 break; 3506 case com.android.internal.R.styleable.View_translationY: 3507 ty = a.getDimensionPixelOffset(attr, 0); 3508 transformSet = true; 3509 break; 3510 case com.android.internal.R.styleable.View_rotation: 3511 rotation = a.getFloat(attr, 0); 3512 transformSet = true; 3513 break; 3514 case com.android.internal.R.styleable.View_rotationX: 3515 rotationX = a.getFloat(attr, 0); 3516 transformSet = true; 3517 break; 3518 case com.android.internal.R.styleable.View_rotationY: 3519 rotationY = a.getFloat(attr, 0); 3520 transformSet = true; 3521 break; 3522 case com.android.internal.R.styleable.View_scaleX: 3523 sx = a.getFloat(attr, 1f); 3524 transformSet = true; 3525 break; 3526 case com.android.internal.R.styleable.View_scaleY: 3527 sy = a.getFloat(attr, 1f); 3528 transformSet = true; 3529 break; 3530 case com.android.internal.R.styleable.View_id: 3531 mID = a.getResourceId(attr, NO_ID); 3532 break; 3533 case com.android.internal.R.styleable.View_tag: 3534 mTag = a.getText(attr); 3535 break; 3536 case com.android.internal.R.styleable.View_fitsSystemWindows: 3537 if (a.getBoolean(attr, false)) { 3538 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3539 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3540 } 3541 break; 3542 case com.android.internal.R.styleable.View_focusable: 3543 if (a.getBoolean(attr, false)) { 3544 viewFlagValues |= FOCUSABLE; 3545 viewFlagMasks |= FOCUSABLE_MASK; 3546 } 3547 break; 3548 case com.android.internal.R.styleable.View_focusableInTouchMode: 3549 if (a.getBoolean(attr, false)) { 3550 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3551 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3552 } 3553 break; 3554 case com.android.internal.R.styleable.View_clickable: 3555 if (a.getBoolean(attr, false)) { 3556 viewFlagValues |= CLICKABLE; 3557 viewFlagMasks |= CLICKABLE; 3558 } 3559 break; 3560 case com.android.internal.R.styleable.View_longClickable: 3561 if (a.getBoolean(attr, false)) { 3562 viewFlagValues |= LONG_CLICKABLE; 3563 viewFlagMasks |= LONG_CLICKABLE; 3564 } 3565 break; 3566 case com.android.internal.R.styleable.View_saveEnabled: 3567 if (!a.getBoolean(attr, true)) { 3568 viewFlagValues |= SAVE_DISABLED; 3569 viewFlagMasks |= SAVE_DISABLED_MASK; 3570 } 3571 break; 3572 case com.android.internal.R.styleable.View_duplicateParentState: 3573 if (a.getBoolean(attr, false)) { 3574 viewFlagValues |= DUPLICATE_PARENT_STATE; 3575 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3576 } 3577 break; 3578 case com.android.internal.R.styleable.View_visibility: 3579 final int visibility = a.getInt(attr, 0); 3580 if (visibility != 0) { 3581 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3582 viewFlagMasks |= VISIBILITY_MASK; 3583 } 3584 break; 3585 case com.android.internal.R.styleable.View_layoutDirection: 3586 // Clear any layout direction flags (included resolved bits) already set 3587 mPrivateFlags2 &= 3588 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3589 // Set the layout direction flags depending on the value of the attribute 3590 final int layoutDirection = a.getInt(attr, -1); 3591 final int value = (layoutDirection != -1) ? 3592 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3593 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3594 break; 3595 case com.android.internal.R.styleable.View_drawingCacheQuality: 3596 final int cacheQuality = a.getInt(attr, 0); 3597 if (cacheQuality != 0) { 3598 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3599 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3600 } 3601 break; 3602 case com.android.internal.R.styleable.View_contentDescription: 3603 setContentDescription(a.getString(attr)); 3604 break; 3605 case com.android.internal.R.styleable.View_labelFor: 3606 setLabelFor(a.getResourceId(attr, NO_ID)); 3607 break; 3608 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3609 if (!a.getBoolean(attr, true)) { 3610 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3611 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3612 } 3613 break; 3614 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3615 if (!a.getBoolean(attr, true)) { 3616 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3617 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3618 } 3619 break; 3620 case R.styleable.View_scrollbars: 3621 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3622 if (scrollbars != SCROLLBARS_NONE) { 3623 viewFlagValues |= scrollbars; 3624 viewFlagMasks |= SCROLLBARS_MASK; 3625 initializeScrollbars = true; 3626 } 3627 break; 3628 //noinspection deprecation 3629 case R.styleable.View_fadingEdge: 3630 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3631 // Ignore the attribute starting with ICS 3632 break; 3633 } 3634 // With builds < ICS, fall through and apply fading edges 3635 case R.styleable.View_requiresFadingEdge: 3636 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3637 if (fadingEdge != FADING_EDGE_NONE) { 3638 viewFlagValues |= fadingEdge; 3639 viewFlagMasks |= FADING_EDGE_MASK; 3640 initializeFadingEdge(a); 3641 } 3642 break; 3643 case R.styleable.View_scrollbarStyle: 3644 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3645 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3646 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3647 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3648 } 3649 break; 3650 case R.styleable.View_isScrollContainer: 3651 setScrollContainer = true; 3652 if (a.getBoolean(attr, false)) { 3653 setScrollContainer(true); 3654 } 3655 break; 3656 case com.android.internal.R.styleable.View_keepScreenOn: 3657 if (a.getBoolean(attr, false)) { 3658 viewFlagValues |= KEEP_SCREEN_ON; 3659 viewFlagMasks |= KEEP_SCREEN_ON; 3660 } 3661 break; 3662 case R.styleable.View_filterTouchesWhenObscured: 3663 if (a.getBoolean(attr, false)) { 3664 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3665 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3666 } 3667 break; 3668 case R.styleable.View_nextFocusLeft: 3669 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3670 break; 3671 case R.styleable.View_nextFocusRight: 3672 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3673 break; 3674 case R.styleable.View_nextFocusUp: 3675 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3676 break; 3677 case R.styleable.View_nextFocusDown: 3678 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3679 break; 3680 case R.styleable.View_nextFocusForward: 3681 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3682 break; 3683 case R.styleable.View_minWidth: 3684 mMinWidth = a.getDimensionPixelSize(attr, 0); 3685 break; 3686 case R.styleable.View_minHeight: 3687 mMinHeight = a.getDimensionPixelSize(attr, 0); 3688 break; 3689 case R.styleable.View_onClick: 3690 if (context.isRestricted()) { 3691 throw new IllegalStateException("The android:onClick attribute cannot " 3692 + "be used within a restricted context"); 3693 } 3694 3695 final String handlerName = a.getString(attr); 3696 if (handlerName != null) { 3697 setOnClickListener(new OnClickListener() { 3698 private Method mHandler; 3699 3700 public void onClick(View v) { 3701 if (mHandler == null) { 3702 try { 3703 mHandler = getContext().getClass().getMethod(handlerName, 3704 View.class); 3705 } catch (NoSuchMethodException e) { 3706 int id = getId(); 3707 String idText = id == NO_ID ? "" : " with id '" 3708 + getContext().getResources().getResourceEntryName( 3709 id) + "'"; 3710 throw new IllegalStateException("Could not find a method " + 3711 handlerName + "(View) in the activity " 3712 + getContext().getClass() + " for onClick handler" 3713 + " on view " + View.this.getClass() + idText, e); 3714 } 3715 } 3716 3717 try { 3718 mHandler.invoke(getContext(), View.this); 3719 } catch (IllegalAccessException e) { 3720 throw new IllegalStateException("Could not execute non " 3721 + "public method of the activity", e); 3722 } catch (InvocationTargetException e) { 3723 throw new IllegalStateException("Could not execute " 3724 + "method of the activity", e); 3725 } 3726 } 3727 }); 3728 } 3729 break; 3730 case R.styleable.View_overScrollMode: 3731 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3732 break; 3733 case R.styleable.View_verticalScrollbarPosition: 3734 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3735 break; 3736 case R.styleable.View_layerType: 3737 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3738 break; 3739 case R.styleable.View_textDirection: 3740 // Clear any text direction flag already set 3741 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3742 // Set the text direction flags depending on the value of the attribute 3743 final int textDirection = a.getInt(attr, -1); 3744 if (textDirection != -1) { 3745 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3746 } 3747 break; 3748 case R.styleable.View_textAlignment: 3749 // Clear any text alignment flag already set 3750 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3751 // Set the text alignment flag depending on the value of the attribute 3752 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3753 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 3754 break; 3755 case R.styleable.View_importantForAccessibility: 3756 setImportantForAccessibility(a.getInt(attr, 3757 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 3758 break; 3759 } 3760 } 3761 3762 setOverScrollMode(overScrollMode); 3763 3764 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 3765 // the resolved layout direction). Those cached values will be used later during padding 3766 // resolution. 3767 mUserPaddingStart = startPadding; 3768 mUserPaddingEnd = endPadding; 3769 3770 if (background != null) { 3771 setBackground(background); 3772 } 3773 3774 if (padding >= 0) { 3775 leftPadding = padding; 3776 topPadding = padding; 3777 rightPadding = padding; 3778 bottomPadding = padding; 3779 mUserPaddingLeftInitial = padding; 3780 mUserPaddingRightInitial = padding; 3781 } 3782 3783 if (isRtlCompatibilityMode()) { 3784 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 3785 // left / right padding are used if defined (meaning here nothing to do). If they are not 3786 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 3787 // start / end and resolve them as left / right (layout direction is not taken into account). 3788 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3789 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3790 // defined. 3791 if (!leftPaddingDefined && startPaddingDefined) { 3792 leftPadding = startPadding; 3793 } 3794 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 3795 if (!rightPaddingDefined && endPaddingDefined) { 3796 rightPadding = endPadding; 3797 } 3798 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 3799 } else { 3800 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 3801 // values defined. Otherwise, left /right values are used. 3802 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3803 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3804 // defined. 3805 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 3806 3807 if (leftPaddingDefined && !hasRelativePadding) { 3808 mUserPaddingLeftInitial = leftPadding; 3809 } 3810 if (rightPaddingDefined && !hasRelativePadding) { 3811 mUserPaddingRightInitial = rightPadding; 3812 } 3813 } 3814 3815 internalSetPadding( 3816 mUserPaddingLeftInitial, 3817 topPadding >= 0 ? topPadding : mPaddingTop, 3818 mUserPaddingRightInitial, 3819 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3820 3821 if (viewFlagMasks != 0) { 3822 setFlags(viewFlagValues, viewFlagMasks); 3823 } 3824 3825 if (initializeScrollbars) { 3826 initializeScrollbars(a); 3827 } 3828 3829 a.recycle(); 3830 3831 // Needs to be called after mViewFlags is set 3832 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3833 recomputePadding(); 3834 } 3835 3836 if (x != 0 || y != 0) { 3837 scrollTo(x, y); 3838 } 3839 3840 if (transformSet) { 3841 setTranslationX(tx); 3842 setTranslationY(ty); 3843 setRotation(rotation); 3844 setRotationX(rotationX); 3845 setRotationY(rotationY); 3846 setScaleX(sx); 3847 setScaleY(sy); 3848 } 3849 3850 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3851 setScrollContainer(true); 3852 } 3853 3854 computeOpaqueFlags(); 3855 } 3856 3857 /** 3858 * Non-public constructor for use in testing 3859 */ 3860 View() { 3861 mResources = null; 3862 } 3863 3864 public String toString() { 3865 StringBuilder out = new StringBuilder(128); 3866 out.append(getClass().getName()); 3867 out.append('{'); 3868 out.append(Integer.toHexString(System.identityHashCode(this))); 3869 out.append(' '); 3870 switch (mViewFlags&VISIBILITY_MASK) { 3871 case VISIBLE: out.append('V'); break; 3872 case INVISIBLE: out.append('I'); break; 3873 case GONE: out.append('G'); break; 3874 default: out.append('.'); break; 3875 } 3876 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 3877 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 3878 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 3879 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 3880 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 3881 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 3882 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 3883 out.append(' '); 3884 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 3885 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 3886 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 3887 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 3888 out.append('p'); 3889 } else { 3890 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 3891 } 3892 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 3893 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 3894 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 3895 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 3896 out.append(' '); 3897 out.append(mLeft); 3898 out.append(','); 3899 out.append(mTop); 3900 out.append('-'); 3901 out.append(mRight); 3902 out.append(','); 3903 out.append(mBottom); 3904 final int id = getId(); 3905 if (id != NO_ID) { 3906 out.append(" #"); 3907 out.append(Integer.toHexString(id)); 3908 final Resources r = mResources; 3909 if (id != 0 && r != null) { 3910 try { 3911 String pkgname; 3912 switch (id&0xff000000) { 3913 case 0x7f000000: 3914 pkgname="app"; 3915 break; 3916 case 0x01000000: 3917 pkgname="android"; 3918 break; 3919 default: 3920 pkgname = r.getResourcePackageName(id); 3921 break; 3922 } 3923 String typename = r.getResourceTypeName(id); 3924 String entryname = r.getResourceEntryName(id); 3925 out.append(" "); 3926 out.append(pkgname); 3927 out.append(":"); 3928 out.append(typename); 3929 out.append("/"); 3930 out.append(entryname); 3931 } catch (Resources.NotFoundException e) { 3932 } 3933 } 3934 } 3935 out.append("}"); 3936 return out.toString(); 3937 } 3938 3939 /** 3940 * <p> 3941 * Initializes the fading edges from a given set of styled attributes. This 3942 * method should be called by subclasses that need fading edges and when an 3943 * instance of these subclasses is created programmatically rather than 3944 * being inflated from XML. This method is automatically called when the XML 3945 * is inflated. 3946 * </p> 3947 * 3948 * @param a the styled attributes set to initialize the fading edges from 3949 */ 3950 protected void initializeFadingEdge(TypedArray a) { 3951 initScrollCache(); 3952 3953 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3954 R.styleable.View_fadingEdgeLength, 3955 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3956 } 3957 3958 /** 3959 * Returns the size of the vertical faded edges used to indicate that more 3960 * content in this view is visible. 3961 * 3962 * @return The size in pixels of the vertical faded edge or 0 if vertical 3963 * faded edges are not enabled for this view. 3964 * @attr ref android.R.styleable#View_fadingEdgeLength 3965 */ 3966 public int getVerticalFadingEdgeLength() { 3967 if (isVerticalFadingEdgeEnabled()) { 3968 ScrollabilityCache cache = mScrollCache; 3969 if (cache != null) { 3970 return cache.fadingEdgeLength; 3971 } 3972 } 3973 return 0; 3974 } 3975 3976 /** 3977 * Set the size of the faded edge used to indicate that more content in this 3978 * view is available. Will not change whether the fading edge is enabled; use 3979 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3980 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3981 * for the vertical or horizontal fading edges. 3982 * 3983 * @param length The size in pixels of the faded edge used to indicate that more 3984 * content in this view is visible. 3985 */ 3986 public void setFadingEdgeLength(int length) { 3987 initScrollCache(); 3988 mScrollCache.fadingEdgeLength = length; 3989 } 3990 3991 /** 3992 * Returns the size of the horizontal faded edges used to indicate that more 3993 * content in this view is visible. 3994 * 3995 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3996 * faded edges are not enabled for this view. 3997 * @attr ref android.R.styleable#View_fadingEdgeLength 3998 */ 3999 public int getHorizontalFadingEdgeLength() { 4000 if (isHorizontalFadingEdgeEnabled()) { 4001 ScrollabilityCache cache = mScrollCache; 4002 if (cache != null) { 4003 return cache.fadingEdgeLength; 4004 } 4005 } 4006 return 0; 4007 } 4008 4009 /** 4010 * Returns the width of the vertical scrollbar. 4011 * 4012 * @return The width in pixels of the vertical scrollbar or 0 if there 4013 * is no vertical scrollbar. 4014 */ 4015 public int getVerticalScrollbarWidth() { 4016 ScrollabilityCache cache = mScrollCache; 4017 if (cache != null) { 4018 ScrollBarDrawable scrollBar = cache.scrollBar; 4019 if (scrollBar != null) { 4020 int size = scrollBar.getSize(true); 4021 if (size <= 0) { 4022 size = cache.scrollBarSize; 4023 } 4024 return size; 4025 } 4026 return 0; 4027 } 4028 return 0; 4029 } 4030 4031 /** 4032 * Returns the height of the horizontal scrollbar. 4033 * 4034 * @return The height in pixels of the horizontal scrollbar or 0 if 4035 * there is no horizontal scrollbar. 4036 */ 4037 protected int getHorizontalScrollbarHeight() { 4038 ScrollabilityCache cache = mScrollCache; 4039 if (cache != null) { 4040 ScrollBarDrawable scrollBar = cache.scrollBar; 4041 if (scrollBar != null) { 4042 int size = scrollBar.getSize(false); 4043 if (size <= 0) { 4044 size = cache.scrollBarSize; 4045 } 4046 return size; 4047 } 4048 return 0; 4049 } 4050 return 0; 4051 } 4052 4053 /** 4054 * <p> 4055 * Initializes the scrollbars from a given set of styled attributes. This 4056 * method should be called by subclasses that need scrollbars and when an 4057 * instance of these subclasses is created programmatically rather than 4058 * being inflated from XML. This method is automatically called when the XML 4059 * is inflated. 4060 * </p> 4061 * 4062 * @param a the styled attributes set to initialize the scrollbars from 4063 */ 4064 protected void initializeScrollbars(TypedArray a) { 4065 initScrollCache(); 4066 4067 final ScrollabilityCache scrollabilityCache = mScrollCache; 4068 4069 if (scrollabilityCache.scrollBar == null) { 4070 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4071 } 4072 4073 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4074 4075 if (!fadeScrollbars) { 4076 scrollabilityCache.state = ScrollabilityCache.ON; 4077 } 4078 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4079 4080 4081 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4082 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4083 .getScrollBarFadeDuration()); 4084 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4085 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4086 ViewConfiguration.getScrollDefaultDelay()); 4087 4088 4089 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4090 com.android.internal.R.styleable.View_scrollbarSize, 4091 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4092 4093 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4094 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4095 4096 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4097 if (thumb != null) { 4098 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4099 } 4100 4101 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4102 false); 4103 if (alwaysDraw) { 4104 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4105 } 4106 4107 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4108 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4109 4110 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4111 if (thumb != null) { 4112 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4113 } 4114 4115 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4116 false); 4117 if (alwaysDraw) { 4118 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4119 } 4120 4121 // Apply layout direction to the new Drawables if needed 4122 final int layoutDirection = getLayoutDirection(); 4123 if (track != null) { 4124 track.setLayoutDirection(layoutDirection); 4125 } 4126 if (thumb != null) { 4127 thumb.setLayoutDirection(layoutDirection); 4128 } 4129 4130 // Re-apply user/background padding so that scrollbar(s) get added 4131 resolvePadding(); 4132 } 4133 4134 /** 4135 * <p> 4136 * Initalizes the scrollability cache if necessary. 4137 * </p> 4138 */ 4139 private void initScrollCache() { 4140 if (mScrollCache == null) { 4141 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4142 } 4143 } 4144 4145 private ScrollabilityCache getScrollCache() { 4146 initScrollCache(); 4147 return mScrollCache; 4148 } 4149 4150 /** 4151 * Set the position of the vertical scroll bar. Should be one of 4152 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4153 * {@link #SCROLLBAR_POSITION_RIGHT}. 4154 * 4155 * @param position Where the vertical scroll bar should be positioned. 4156 */ 4157 public void setVerticalScrollbarPosition(int position) { 4158 if (mVerticalScrollbarPosition != position) { 4159 mVerticalScrollbarPosition = position; 4160 computeOpaqueFlags(); 4161 resolvePadding(); 4162 } 4163 } 4164 4165 /** 4166 * @return The position where the vertical scroll bar will show, if applicable. 4167 * @see #setVerticalScrollbarPosition(int) 4168 */ 4169 public int getVerticalScrollbarPosition() { 4170 return mVerticalScrollbarPosition; 4171 } 4172 4173 ListenerInfo getListenerInfo() { 4174 if (mListenerInfo != null) { 4175 return mListenerInfo; 4176 } 4177 mListenerInfo = new ListenerInfo(); 4178 return mListenerInfo; 4179 } 4180 4181 /** 4182 * Register a callback to be invoked when focus of this view changed. 4183 * 4184 * @param l The callback that will run. 4185 */ 4186 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4187 getListenerInfo().mOnFocusChangeListener = l; 4188 } 4189 4190 /** 4191 * Add a listener that will be called when the bounds of the view change due to 4192 * layout processing. 4193 * 4194 * @param listener The listener that will be called when layout bounds change. 4195 */ 4196 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4197 ListenerInfo li = getListenerInfo(); 4198 if (li.mOnLayoutChangeListeners == null) { 4199 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4200 } 4201 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4202 li.mOnLayoutChangeListeners.add(listener); 4203 } 4204 } 4205 4206 /** 4207 * Remove a listener for layout changes. 4208 * 4209 * @param listener The listener for layout bounds change. 4210 */ 4211 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4212 ListenerInfo li = mListenerInfo; 4213 if (li == null || li.mOnLayoutChangeListeners == null) { 4214 return; 4215 } 4216 li.mOnLayoutChangeListeners.remove(listener); 4217 } 4218 4219 /** 4220 * Add a listener for attach state changes. 4221 * 4222 * This listener will be called whenever this view is attached or detached 4223 * from a window. Remove the listener using 4224 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4225 * 4226 * @param listener Listener to attach 4227 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4228 */ 4229 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4230 ListenerInfo li = getListenerInfo(); 4231 if (li.mOnAttachStateChangeListeners == null) { 4232 li.mOnAttachStateChangeListeners 4233 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4234 } 4235 li.mOnAttachStateChangeListeners.add(listener); 4236 } 4237 4238 /** 4239 * Remove a listener for attach state changes. The listener will receive no further 4240 * notification of window attach/detach events. 4241 * 4242 * @param listener Listener to remove 4243 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4244 */ 4245 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4246 ListenerInfo li = mListenerInfo; 4247 if (li == null || li.mOnAttachStateChangeListeners == null) { 4248 return; 4249 } 4250 li.mOnAttachStateChangeListeners.remove(listener); 4251 } 4252 4253 /** 4254 * Returns the focus-change callback registered for this view. 4255 * 4256 * @return The callback, or null if one is not registered. 4257 */ 4258 public OnFocusChangeListener getOnFocusChangeListener() { 4259 ListenerInfo li = mListenerInfo; 4260 return li != null ? li.mOnFocusChangeListener : null; 4261 } 4262 4263 /** 4264 * Register a callback to be invoked when this view is clicked. If this view is not 4265 * clickable, it becomes clickable. 4266 * 4267 * @param l The callback that will run 4268 * 4269 * @see #setClickable(boolean) 4270 */ 4271 public void setOnClickListener(OnClickListener l) { 4272 if (!isClickable()) { 4273 setClickable(true); 4274 } 4275 getListenerInfo().mOnClickListener = l; 4276 } 4277 4278 /** 4279 * Return whether this view has an attached OnClickListener. Returns 4280 * true if there is a listener, false if there is none. 4281 */ 4282 public boolean hasOnClickListeners() { 4283 ListenerInfo li = mListenerInfo; 4284 return (li != null && li.mOnClickListener != null); 4285 } 4286 4287 /** 4288 * Register a callback to be invoked when this view is clicked and held. If this view is not 4289 * long clickable, it becomes long clickable. 4290 * 4291 * @param l The callback that will run 4292 * 4293 * @see #setLongClickable(boolean) 4294 */ 4295 public void setOnLongClickListener(OnLongClickListener l) { 4296 if (!isLongClickable()) { 4297 setLongClickable(true); 4298 } 4299 getListenerInfo().mOnLongClickListener = l; 4300 } 4301 4302 /** 4303 * Register a callback to be invoked when the context menu for this view is 4304 * being built. If this view is not long clickable, it becomes long clickable. 4305 * 4306 * @param l The callback that will run 4307 * 4308 */ 4309 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4310 if (!isLongClickable()) { 4311 setLongClickable(true); 4312 } 4313 getListenerInfo().mOnCreateContextMenuListener = l; 4314 } 4315 4316 /** 4317 * Call this view's OnClickListener, if it is defined. Performs all normal 4318 * actions associated with clicking: reporting accessibility event, playing 4319 * a sound, etc. 4320 * 4321 * @return True there was an assigned OnClickListener that was called, false 4322 * otherwise is returned. 4323 */ 4324 public boolean performClick() { 4325 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4326 4327 ListenerInfo li = mListenerInfo; 4328 if (li != null && li.mOnClickListener != null) { 4329 playSoundEffect(SoundEffectConstants.CLICK); 4330 li.mOnClickListener.onClick(this); 4331 return true; 4332 } 4333 4334 return false; 4335 } 4336 4337 /** 4338 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4339 * this only calls the listener, and does not do any associated clicking 4340 * actions like reporting an accessibility event. 4341 * 4342 * @return True there was an assigned OnClickListener that was called, false 4343 * otherwise is returned. 4344 */ 4345 public boolean callOnClick() { 4346 ListenerInfo li = mListenerInfo; 4347 if (li != null && li.mOnClickListener != null) { 4348 li.mOnClickListener.onClick(this); 4349 return true; 4350 } 4351 return false; 4352 } 4353 4354 /** 4355 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4356 * OnLongClickListener did not consume the event. 4357 * 4358 * @return True if one of the above receivers consumed the event, false otherwise. 4359 */ 4360 public boolean performLongClick() { 4361 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4362 4363 boolean handled = false; 4364 ListenerInfo li = mListenerInfo; 4365 if (li != null && li.mOnLongClickListener != null) { 4366 handled = li.mOnLongClickListener.onLongClick(View.this); 4367 } 4368 if (!handled) { 4369 handled = showContextMenu(); 4370 } 4371 if (handled) { 4372 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4373 } 4374 return handled; 4375 } 4376 4377 /** 4378 * Performs button-related actions during a touch down event. 4379 * 4380 * @param event The event. 4381 * @return True if the down was consumed. 4382 * 4383 * @hide 4384 */ 4385 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4386 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4387 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4388 return true; 4389 } 4390 } 4391 return false; 4392 } 4393 4394 /** 4395 * Bring up the context menu for this view. 4396 * 4397 * @return Whether a context menu was displayed. 4398 */ 4399 public boolean showContextMenu() { 4400 return getParent().showContextMenuForChild(this); 4401 } 4402 4403 /** 4404 * Bring up the context menu for this view, referring to the item under the specified point. 4405 * 4406 * @param x The referenced x coordinate. 4407 * @param y The referenced y coordinate. 4408 * @param metaState The keyboard modifiers that were pressed. 4409 * @return Whether a context menu was displayed. 4410 * 4411 * @hide 4412 */ 4413 public boolean showContextMenu(float x, float y, int metaState) { 4414 return showContextMenu(); 4415 } 4416 4417 /** 4418 * Start an action mode. 4419 * 4420 * @param callback Callback that will control the lifecycle of the action mode 4421 * @return The new action mode if it is started, null otherwise 4422 * 4423 * @see ActionMode 4424 */ 4425 public ActionMode startActionMode(ActionMode.Callback callback) { 4426 ViewParent parent = getParent(); 4427 if (parent == null) return null; 4428 return parent.startActionModeForChild(this, callback); 4429 } 4430 4431 /** 4432 * Register a callback to be invoked when a hardware key is pressed in this view. 4433 * Key presses in software input methods will generally not trigger the methods of 4434 * this listener. 4435 * @param l the key listener to attach to this view 4436 */ 4437 public void setOnKeyListener(OnKeyListener l) { 4438 getListenerInfo().mOnKeyListener = l; 4439 } 4440 4441 /** 4442 * Register a callback to be invoked when a touch event is sent to this view. 4443 * @param l the touch listener to attach to this view 4444 */ 4445 public void setOnTouchListener(OnTouchListener l) { 4446 getListenerInfo().mOnTouchListener = l; 4447 } 4448 4449 /** 4450 * Register a callback to be invoked when a generic motion event is sent to this view. 4451 * @param l the generic motion listener to attach to this view 4452 */ 4453 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4454 getListenerInfo().mOnGenericMotionListener = l; 4455 } 4456 4457 /** 4458 * Register a callback to be invoked when a hover event is sent to this view. 4459 * @param l the hover listener to attach to this view 4460 */ 4461 public void setOnHoverListener(OnHoverListener l) { 4462 getListenerInfo().mOnHoverListener = l; 4463 } 4464 4465 /** 4466 * Register a drag event listener callback object for this View. The parameter is 4467 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4468 * View, the system calls the 4469 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4470 * @param l An implementation of {@link android.view.View.OnDragListener}. 4471 */ 4472 public void setOnDragListener(OnDragListener l) { 4473 getListenerInfo().mOnDragListener = l; 4474 } 4475 4476 /** 4477 * Give this view focus. This will cause 4478 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4479 * 4480 * Note: this does not check whether this {@link View} should get focus, it just 4481 * gives it focus no matter what. It should only be called internally by framework 4482 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4483 * 4484 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4485 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4486 * focus moved when requestFocus() is called. It may not always 4487 * apply, in which case use the default View.FOCUS_DOWN. 4488 * @param previouslyFocusedRect The rectangle of the view that had focus 4489 * prior in this View's coordinate system. 4490 */ 4491 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 4492 if (DBG) { 4493 System.out.println(this + " requestFocus()"); 4494 } 4495 4496 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4497 mPrivateFlags |= PFLAG_FOCUSED; 4498 4499 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4500 4501 if (mParent != null) { 4502 mParent.requestChildFocus(this, this); 4503 } 4504 4505 if (mAttachInfo != null) { 4506 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4507 } 4508 4509 onFocusChanged(true, direction, previouslyFocusedRect); 4510 refreshDrawableState(); 4511 } 4512 } 4513 4514 /** 4515 * Request that a rectangle of this view be visible on the screen, 4516 * scrolling if necessary just enough. 4517 * 4518 * <p>A View should call this if it maintains some notion of which part 4519 * of its content is interesting. For example, a text editing view 4520 * should call this when its cursor moves. 4521 * 4522 * @param rectangle The rectangle. 4523 * @return Whether any parent scrolled. 4524 */ 4525 public boolean requestRectangleOnScreen(Rect rectangle) { 4526 return requestRectangleOnScreen(rectangle, false); 4527 } 4528 4529 /** 4530 * Request that a rectangle of this view be visible on the screen, 4531 * scrolling if necessary just enough. 4532 * 4533 * <p>A View should call this if it maintains some notion of which part 4534 * of its content is interesting. For example, a text editing view 4535 * should call this when its cursor moves. 4536 * 4537 * <p>When <code>immediate</code> is set to true, scrolling will not be 4538 * animated. 4539 * 4540 * @param rectangle The rectangle. 4541 * @param immediate True to forbid animated scrolling, false otherwise 4542 * @return Whether any parent scrolled. 4543 */ 4544 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4545 if (mParent == null) { 4546 return false; 4547 } 4548 4549 View child = this; 4550 4551 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4552 position.set(rectangle); 4553 4554 ViewParent parent = mParent; 4555 boolean scrolled = false; 4556 while (parent != null) { 4557 rectangle.set((int) position.left, (int) position.top, 4558 (int) position.right, (int) position.bottom); 4559 4560 scrolled |= parent.requestChildRectangleOnScreen(child, 4561 rectangle, immediate); 4562 4563 if (!child.hasIdentityMatrix()) { 4564 child.getMatrix().mapRect(position); 4565 } 4566 4567 position.offset(child.mLeft, child.mTop); 4568 4569 if (!(parent instanceof View)) { 4570 break; 4571 } 4572 4573 View parentView = (View) parent; 4574 4575 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4576 4577 child = parentView; 4578 parent = child.getParent(); 4579 } 4580 4581 return scrolled; 4582 } 4583 4584 /** 4585 * Called when this view wants to give up focus. If focus is cleared 4586 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4587 * <p> 4588 * <strong>Note:</strong> When a View clears focus the framework is trying 4589 * to give focus to the first focusable View from the top. Hence, if this 4590 * View is the first from the top that can take focus, then all callbacks 4591 * related to clearing focus will be invoked after wich the framework will 4592 * give focus to this view. 4593 * </p> 4594 */ 4595 public void clearFocus() { 4596 if (DBG) { 4597 System.out.println(this + " clearFocus()"); 4598 } 4599 4600 clearFocusInternal(true, true); 4601 } 4602 4603 /** 4604 * Clears focus from the view, optionally propagating the change up through 4605 * the parent hierarchy and requesting that the root view place new focus. 4606 * 4607 * @param propagate whether to propagate the change up through the parent 4608 * hierarchy 4609 * @param refocus when propagate is true, specifies whether to request the 4610 * root view place new focus 4611 */ 4612 void clearFocusInternal(boolean propagate, boolean refocus) { 4613 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4614 mPrivateFlags &= ~PFLAG_FOCUSED; 4615 4616 if (propagate && mParent != null) { 4617 mParent.clearChildFocus(this); 4618 } 4619 4620 onFocusChanged(false, 0, null); 4621 4622 refreshDrawableState(); 4623 4624 if (propagate && (!refocus || !rootViewRequestFocus())) { 4625 notifyGlobalFocusCleared(this); 4626 } 4627 } 4628 } 4629 4630 void notifyGlobalFocusCleared(View oldFocus) { 4631 if (oldFocus != null && mAttachInfo != null) { 4632 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4633 } 4634 } 4635 4636 boolean rootViewRequestFocus() { 4637 final View root = getRootView(); 4638 return root != null && root.requestFocus(); 4639 } 4640 4641 /** 4642 * Called internally by the view system when a new view is getting focus. 4643 * This is what clears the old focus. 4644 * <p> 4645 * <b>NOTE:</b> The parent view's focused child must be updated manually 4646 * after calling this method. Otherwise, the view hierarchy may be left in 4647 * an inconstent state. 4648 */ 4649 void unFocus() { 4650 if (DBG) { 4651 System.out.println(this + " unFocus()"); 4652 } 4653 4654 clearFocusInternal(false, false); 4655 } 4656 4657 /** 4658 * Returns true if this view has focus iteself, or is the ancestor of the 4659 * view that has focus. 4660 * 4661 * @return True if this view has or contains focus, false otherwise. 4662 */ 4663 @ViewDebug.ExportedProperty(category = "focus") 4664 public boolean hasFocus() { 4665 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4666 } 4667 4668 /** 4669 * Returns true if this view is focusable or if it contains a reachable View 4670 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4671 * is a View whose parents do not block descendants focus. 4672 * 4673 * Only {@link #VISIBLE} views are considered focusable. 4674 * 4675 * @return True if the view is focusable or if the view contains a focusable 4676 * View, false otherwise. 4677 * 4678 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4679 */ 4680 public boolean hasFocusable() { 4681 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4682 } 4683 4684 /** 4685 * Called by the view system when the focus state of this view changes. 4686 * When the focus change event is caused by directional navigation, direction 4687 * and previouslyFocusedRect provide insight into where the focus is coming from. 4688 * When overriding, be sure to call up through to the super class so that 4689 * the standard focus handling will occur. 4690 * 4691 * @param gainFocus True if the View has focus; false otherwise. 4692 * @param direction The direction focus has moved when requestFocus() 4693 * is called to give this view focus. Values are 4694 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4695 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4696 * It may not always apply, in which case use the default. 4697 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4698 * system, of the previously focused view. If applicable, this will be 4699 * passed in as finer grained information about where the focus is coming 4700 * from (in addition to direction). Will be <code>null</code> otherwise. 4701 */ 4702 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 4703 if (gainFocus) { 4704 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4705 } else { 4706 notifyViewAccessibilityStateChangedIfNeeded(); 4707 } 4708 4709 InputMethodManager imm = InputMethodManager.peekInstance(); 4710 if (!gainFocus) { 4711 if (isPressed()) { 4712 setPressed(false); 4713 } 4714 if (imm != null && mAttachInfo != null 4715 && mAttachInfo.mHasWindowFocus) { 4716 imm.focusOut(this); 4717 } 4718 onFocusLost(); 4719 } else if (imm != null && mAttachInfo != null 4720 && mAttachInfo.mHasWindowFocus) { 4721 imm.focusIn(this); 4722 } 4723 4724 invalidate(true); 4725 ListenerInfo li = mListenerInfo; 4726 if (li != null && li.mOnFocusChangeListener != null) { 4727 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 4728 } 4729 4730 if (mAttachInfo != null) { 4731 mAttachInfo.mKeyDispatchState.reset(this); 4732 } 4733 } 4734 4735 /** 4736 * Sends an accessibility event of the given type. If accessibility is 4737 * not enabled this method has no effect. The default implementation calls 4738 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 4739 * to populate information about the event source (this View), then calls 4740 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 4741 * populate the text content of the event source including its descendants, 4742 * and last calls 4743 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 4744 * on its parent to resuest sending of the event to interested parties. 4745 * <p> 4746 * If an {@link AccessibilityDelegate} has been specified via calling 4747 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4748 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 4749 * responsible for handling this call. 4750 * </p> 4751 * 4752 * @param eventType The type of the event to send, as defined by several types from 4753 * {@link android.view.accessibility.AccessibilityEvent}, such as 4754 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 4755 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 4756 * 4757 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4758 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4759 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 4760 * @see AccessibilityDelegate 4761 */ 4762 public void sendAccessibilityEvent(int eventType) { 4763 // Excluded views do not send accessibility events. 4764 if (!includeForAccessibility()) { 4765 return; 4766 } 4767 if (mAccessibilityDelegate != null) { 4768 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 4769 } else { 4770 sendAccessibilityEventInternal(eventType); 4771 } 4772 } 4773 4774 /** 4775 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 4776 * {@link AccessibilityEvent} to make an announcement which is related to some 4777 * sort of a context change for which none of the events representing UI transitions 4778 * is a good fit. For example, announcing a new page in a book. If accessibility 4779 * is not enabled this method does nothing. 4780 * 4781 * @param text The announcement text. 4782 */ 4783 public void announceForAccessibility(CharSequence text) { 4784 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 4785 AccessibilityEvent event = AccessibilityEvent.obtain( 4786 AccessibilityEvent.TYPE_ANNOUNCEMENT); 4787 onInitializeAccessibilityEvent(event); 4788 event.getText().add(text); 4789 event.setContentDescription(null); 4790 mParent.requestSendAccessibilityEvent(this, event); 4791 } 4792 } 4793 4794 /** 4795 * @see #sendAccessibilityEvent(int) 4796 * 4797 * Note: Called from the default {@link AccessibilityDelegate}. 4798 */ 4799 void sendAccessibilityEventInternal(int eventType) { 4800 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4801 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 4802 } 4803 } 4804 4805 /** 4806 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 4807 * takes as an argument an empty {@link AccessibilityEvent} and does not 4808 * perform a check whether accessibility is enabled. 4809 * <p> 4810 * If an {@link AccessibilityDelegate} has been specified via calling 4811 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4812 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 4813 * is responsible for handling this call. 4814 * </p> 4815 * 4816 * @param event The event to send. 4817 * 4818 * @see #sendAccessibilityEvent(int) 4819 */ 4820 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 4821 if (mAccessibilityDelegate != null) { 4822 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 4823 } else { 4824 sendAccessibilityEventUncheckedInternal(event); 4825 } 4826 } 4827 4828 /** 4829 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 4830 * 4831 * Note: Called from the default {@link AccessibilityDelegate}. 4832 */ 4833 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 4834 if (!isShown()) { 4835 return; 4836 } 4837 onInitializeAccessibilityEvent(event); 4838 // Only a subset of accessibility events populates text content. 4839 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4840 dispatchPopulateAccessibilityEvent(event); 4841 } 4842 // In the beginning we called #isShown(), so we know that getParent() is not null. 4843 getParent().requestSendAccessibilityEvent(this, event); 4844 } 4845 4846 /** 4847 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4848 * to its children for adding their text content to the event. Note that the 4849 * event text is populated in a separate dispatch path since we add to the 4850 * event not only the text of the source but also the text of all its descendants. 4851 * A typical implementation will call 4852 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4853 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4854 * on each child. Override this method if custom population of the event text 4855 * content is required. 4856 * <p> 4857 * If an {@link AccessibilityDelegate} has been specified via calling 4858 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4859 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4860 * is responsible for handling this call. 4861 * </p> 4862 * <p> 4863 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4864 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4865 * </p> 4866 * 4867 * @param event The event. 4868 * 4869 * @return True if the event population was completed. 4870 */ 4871 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4872 if (mAccessibilityDelegate != null) { 4873 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4874 } else { 4875 return dispatchPopulateAccessibilityEventInternal(event); 4876 } 4877 } 4878 4879 /** 4880 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4881 * 4882 * Note: Called from the default {@link AccessibilityDelegate}. 4883 */ 4884 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4885 onPopulateAccessibilityEvent(event); 4886 return false; 4887 } 4888 4889 /** 4890 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4891 * giving a chance to this View to populate the accessibility event with its 4892 * text content. While this method is free to modify event 4893 * attributes other than text content, doing so should normally be performed in 4894 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4895 * <p> 4896 * Example: Adding formatted date string to an accessibility event in addition 4897 * to the text added by the super implementation: 4898 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4899 * super.onPopulateAccessibilityEvent(event); 4900 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4901 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4902 * mCurrentDate.getTimeInMillis(), flags); 4903 * event.getText().add(selectedDateUtterance); 4904 * }</pre> 4905 * <p> 4906 * If an {@link AccessibilityDelegate} has been specified via calling 4907 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4908 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 4909 * is responsible for handling this call. 4910 * </p> 4911 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4912 * information to the event, in case the default implementation has basic information to add. 4913 * </p> 4914 * 4915 * @param event The accessibility event which to populate. 4916 * 4917 * @see #sendAccessibilityEvent(int) 4918 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4919 */ 4920 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4921 if (mAccessibilityDelegate != null) { 4922 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 4923 } else { 4924 onPopulateAccessibilityEventInternal(event); 4925 } 4926 } 4927 4928 /** 4929 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 4930 * 4931 * Note: Called from the default {@link AccessibilityDelegate}. 4932 */ 4933 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4934 } 4935 4936 /** 4937 * Initializes an {@link AccessibilityEvent} with information about 4938 * this View which is the event source. In other words, the source of 4939 * an accessibility event is the view whose state change triggered firing 4940 * the event. 4941 * <p> 4942 * Example: Setting the password property of an event in addition 4943 * to properties set by the super implementation: 4944 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4945 * super.onInitializeAccessibilityEvent(event); 4946 * event.setPassword(true); 4947 * }</pre> 4948 * <p> 4949 * If an {@link AccessibilityDelegate} has been specified via calling 4950 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4951 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4952 * is responsible for handling this call. 4953 * </p> 4954 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4955 * information to the event, in case the default implementation has basic information to add. 4956 * </p> 4957 * @param event The event to initialize. 4958 * 4959 * @see #sendAccessibilityEvent(int) 4960 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4961 */ 4962 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4963 if (mAccessibilityDelegate != null) { 4964 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 4965 } else { 4966 onInitializeAccessibilityEventInternal(event); 4967 } 4968 } 4969 4970 /** 4971 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4972 * 4973 * Note: Called from the default {@link AccessibilityDelegate}. 4974 */ 4975 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 4976 event.setSource(this); 4977 event.setClassName(View.class.getName()); 4978 event.setPackageName(getContext().getPackageName()); 4979 event.setEnabled(isEnabled()); 4980 event.setContentDescription(mContentDescription); 4981 4982 switch (event.getEventType()) { 4983 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 4984 ArrayList<View> focusablesTempList = (mAttachInfo != null) 4985 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 4986 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 4987 event.setItemCount(focusablesTempList.size()); 4988 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4989 if (mAttachInfo != null) { 4990 focusablesTempList.clear(); 4991 } 4992 } break; 4993 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 4994 CharSequence text = getIterableTextForAccessibility(); 4995 if (text != null && text.length() > 0) { 4996 event.setFromIndex(getAccessibilitySelectionStart()); 4997 event.setToIndex(getAccessibilitySelectionEnd()); 4998 event.setItemCount(text.length()); 4999 } 5000 } break; 5001 } 5002 } 5003 5004 /** 5005 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5006 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5007 * This method is responsible for obtaining an accessibility node info from a 5008 * pool of reusable instances and calling 5009 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5010 * initialize the former. 5011 * <p> 5012 * Note: The client is responsible for recycling the obtained instance by calling 5013 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5014 * </p> 5015 * 5016 * @return A populated {@link AccessibilityNodeInfo}. 5017 * 5018 * @see AccessibilityNodeInfo 5019 */ 5020 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5021 if (mAccessibilityDelegate != null) { 5022 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5023 } else { 5024 return createAccessibilityNodeInfoInternal(); 5025 } 5026 } 5027 5028 /** 5029 * @see #createAccessibilityNodeInfo() 5030 */ 5031 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5032 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5033 if (provider != null) { 5034 return provider.createAccessibilityNodeInfo(View.NO_ID); 5035 } else { 5036 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5037 onInitializeAccessibilityNodeInfo(info); 5038 return info; 5039 } 5040 } 5041 5042 /** 5043 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5044 * The base implementation sets: 5045 * <ul> 5046 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5047 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5048 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5049 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5050 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5051 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5052 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5053 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5054 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5055 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5056 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5057 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5058 * </ul> 5059 * <p> 5060 * Subclasses should override this method, call the super implementation, 5061 * and set additional attributes. 5062 * </p> 5063 * <p> 5064 * If an {@link AccessibilityDelegate} has been specified via calling 5065 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5066 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5067 * is responsible for handling this call. 5068 * </p> 5069 * 5070 * @param info The instance to initialize. 5071 */ 5072 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5073 if (mAccessibilityDelegate != null) { 5074 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5075 } else { 5076 onInitializeAccessibilityNodeInfoInternal(info); 5077 } 5078 } 5079 5080 /** 5081 * Gets the location of this view in screen coordintates. 5082 * 5083 * @param outRect The output location 5084 */ 5085 void getBoundsOnScreen(Rect outRect) { 5086 if (mAttachInfo == null) { 5087 return; 5088 } 5089 5090 RectF position = mAttachInfo.mTmpTransformRect; 5091 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5092 5093 if (!hasIdentityMatrix()) { 5094 getMatrix().mapRect(position); 5095 } 5096 5097 position.offset(mLeft, mTop); 5098 5099 ViewParent parent = mParent; 5100 while (parent instanceof View) { 5101 View parentView = (View) parent; 5102 5103 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5104 5105 if (!parentView.hasIdentityMatrix()) { 5106 parentView.getMatrix().mapRect(position); 5107 } 5108 5109 position.offset(parentView.mLeft, parentView.mTop); 5110 5111 parent = parentView.mParent; 5112 } 5113 5114 if (parent instanceof ViewRootImpl) { 5115 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5116 position.offset(0, -viewRootImpl.mCurScrollY); 5117 } 5118 5119 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5120 5121 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5122 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5123 } 5124 5125 /** 5126 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5127 * 5128 * Note: Called from the default {@link AccessibilityDelegate}. 5129 */ 5130 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5131 Rect bounds = mAttachInfo.mTmpInvalRect; 5132 5133 getDrawingRect(bounds); 5134 info.setBoundsInParent(bounds); 5135 5136 getBoundsOnScreen(bounds); 5137 info.setBoundsInScreen(bounds); 5138 5139 ViewParent parent = getParentForAccessibility(); 5140 if (parent instanceof View) { 5141 info.setParent((View) parent); 5142 } 5143 5144 if (mID != View.NO_ID) { 5145 View rootView = getRootView(); 5146 if (rootView == null) { 5147 rootView = this; 5148 } 5149 View label = rootView.findLabelForView(this, mID); 5150 if (label != null) { 5151 info.setLabeledBy(label); 5152 } 5153 5154 if ((mAttachInfo.mAccessibilityFetchFlags 5155 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5156 && Resources.resourceHasPackage(mID)) { 5157 try { 5158 String viewId = getResources().getResourceName(mID); 5159 info.setViewIdResourceName(viewId); 5160 } catch (Resources.NotFoundException nfe) { 5161 /* ignore */ 5162 } 5163 } 5164 } 5165 5166 if (mLabelForId != View.NO_ID) { 5167 View rootView = getRootView(); 5168 if (rootView == null) { 5169 rootView = this; 5170 } 5171 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5172 if (labeled != null) { 5173 info.setLabelFor(labeled); 5174 } 5175 } 5176 5177 info.setVisibleToUser(isVisibleToUser()); 5178 5179 info.setPackageName(mContext.getPackageName()); 5180 info.setClassName(View.class.getName()); 5181 info.setContentDescription(getContentDescription()); 5182 5183 info.setEnabled(isEnabled()); 5184 info.setClickable(isClickable()); 5185 info.setFocusable(isFocusable()); 5186 info.setFocused(isFocused()); 5187 info.setAccessibilityFocused(isAccessibilityFocused()); 5188 info.setSelected(isSelected()); 5189 info.setLongClickable(isLongClickable()); 5190 5191 // TODO: These make sense only if we are in an AdapterView but all 5192 // views can be selected. Maybe from accessibility perspective 5193 // we should report as selectable view in an AdapterView. 5194 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5195 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5196 5197 if (isFocusable()) { 5198 if (isFocused()) { 5199 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5200 } else { 5201 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5202 } 5203 } 5204 5205 if (!isAccessibilityFocused()) { 5206 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5207 } else { 5208 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5209 } 5210 5211 if (isClickable() && isEnabled()) { 5212 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5213 } 5214 5215 if (isLongClickable() && isEnabled()) { 5216 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5217 } 5218 5219 CharSequence text = getIterableTextForAccessibility(); 5220 if (text != null && text.length() > 0) { 5221 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5222 5223 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5224 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5225 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5226 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5227 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5228 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5229 } 5230 } 5231 5232 private View findLabelForView(View view, int labeledId) { 5233 if (mMatchLabelForPredicate == null) { 5234 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5235 } 5236 mMatchLabelForPredicate.mLabeledId = labeledId; 5237 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5238 } 5239 5240 /** 5241 * Computes whether this view is visible to the user. Such a view is 5242 * attached, visible, all its predecessors are visible, it is not clipped 5243 * entirely by its predecessors, and has an alpha greater than zero. 5244 * 5245 * @return Whether the view is visible on the screen. 5246 * 5247 * @hide 5248 */ 5249 protected boolean isVisibleToUser() { 5250 return isVisibleToUser(null); 5251 } 5252 5253 /** 5254 * Computes whether the given portion of this view is visible to the user. 5255 * Such a view is attached, visible, all its predecessors are visible, 5256 * has an alpha greater than zero, and the specified portion is not 5257 * clipped entirely by its predecessors. 5258 * 5259 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5260 * <code>null</code>, and the entire view will be tested in this case. 5261 * When <code>true</code> is returned by the function, the actual visible 5262 * region will be stored in this parameter; that is, if boundInView is fully 5263 * contained within the view, no modification will be made, otherwise regions 5264 * outside of the visible area of the view will be clipped. 5265 * 5266 * @return Whether the specified portion of the view is visible on the screen. 5267 * 5268 * @hide 5269 */ 5270 protected boolean isVisibleToUser(Rect boundInView) { 5271 if (mAttachInfo != null) { 5272 // Attached to invisible window means this view is not visible. 5273 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5274 return false; 5275 } 5276 // An invisible predecessor or one with alpha zero means 5277 // that this view is not visible to the user. 5278 Object current = this; 5279 while (current instanceof View) { 5280 View view = (View) current; 5281 // We have attach info so this view is attached and there is no 5282 // need to check whether we reach to ViewRootImpl on the way up. 5283 if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) { 5284 return false; 5285 } 5286 current = view.mParent; 5287 } 5288 // Check if the view is entirely covered by its predecessors. 5289 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5290 Point offset = mAttachInfo.mPoint; 5291 if (!getGlobalVisibleRect(visibleRect, offset)) { 5292 return false; 5293 } 5294 // Check if the visible portion intersects the rectangle of interest. 5295 if (boundInView != null) { 5296 visibleRect.offset(-offset.x, -offset.y); 5297 return boundInView.intersect(visibleRect); 5298 } 5299 return true; 5300 } 5301 return false; 5302 } 5303 5304 /** 5305 * Returns the delegate for implementing accessibility support via 5306 * composition. For more details see {@link AccessibilityDelegate}. 5307 * 5308 * @return The delegate, or null if none set. 5309 * 5310 * @hide 5311 */ 5312 public AccessibilityDelegate getAccessibilityDelegate() { 5313 return mAccessibilityDelegate; 5314 } 5315 5316 /** 5317 * Sets a delegate for implementing accessibility support via composition as 5318 * opposed to inheritance. The delegate's primary use is for implementing 5319 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5320 * 5321 * @param delegate The delegate instance. 5322 * 5323 * @see AccessibilityDelegate 5324 */ 5325 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5326 mAccessibilityDelegate = delegate; 5327 } 5328 5329 /** 5330 * Gets the provider for managing a virtual view hierarchy rooted at this View 5331 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5332 * that explore the window content. 5333 * <p> 5334 * If this method returns an instance, this instance is responsible for managing 5335 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5336 * View including the one representing the View itself. Similarly the returned 5337 * instance is responsible for performing accessibility actions on any virtual 5338 * view or the root view itself. 5339 * </p> 5340 * <p> 5341 * If an {@link AccessibilityDelegate} has been specified via calling 5342 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5343 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5344 * is responsible for handling this call. 5345 * </p> 5346 * 5347 * @return The provider. 5348 * 5349 * @see AccessibilityNodeProvider 5350 */ 5351 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5352 if (mAccessibilityDelegate != null) { 5353 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5354 } else { 5355 return null; 5356 } 5357 } 5358 5359 /** 5360 * Gets the unique identifier of this view on the screen for accessibility purposes. 5361 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5362 * 5363 * @return The view accessibility id. 5364 * 5365 * @hide 5366 */ 5367 public int getAccessibilityViewId() { 5368 if (mAccessibilityViewId == NO_ID) { 5369 mAccessibilityViewId = sNextAccessibilityViewId++; 5370 } 5371 return mAccessibilityViewId; 5372 } 5373 5374 /** 5375 * Gets the unique identifier of the window in which this View reseides. 5376 * 5377 * @return The window accessibility id. 5378 * 5379 * @hide 5380 */ 5381 public int getAccessibilityWindowId() { 5382 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 5383 } 5384 5385 /** 5386 * Gets the {@link View} description. It briefly describes the view and is 5387 * primarily used for accessibility support. Set this property to enable 5388 * better accessibility support for your application. This is especially 5389 * true for views that do not have textual representation (For example, 5390 * ImageButton). 5391 * 5392 * @return The content description. 5393 * 5394 * @attr ref android.R.styleable#View_contentDescription 5395 */ 5396 @ViewDebug.ExportedProperty(category = "accessibility") 5397 public CharSequence getContentDescription() { 5398 return mContentDescription; 5399 } 5400 5401 /** 5402 * Sets the {@link View} description. It briefly describes the view and is 5403 * primarily used for accessibility support. Set this property to enable 5404 * better accessibility support for your application. This is especially 5405 * true for views that do not have textual representation (For example, 5406 * ImageButton). 5407 * 5408 * @param contentDescription The content description. 5409 * 5410 * @attr ref android.R.styleable#View_contentDescription 5411 */ 5412 @RemotableViewMethod 5413 public void setContentDescription(CharSequence contentDescription) { 5414 if (mContentDescription == null) { 5415 if (contentDescription == null) { 5416 return; 5417 } 5418 } else if (mContentDescription.equals(contentDescription)) { 5419 return; 5420 } 5421 mContentDescription = contentDescription; 5422 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5423 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5424 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5425 notifySubtreeAccessibilityStateChangedIfNeeded(); 5426 } else { 5427 notifyViewAccessibilityStateChangedIfNeeded(); 5428 } 5429 } 5430 5431 /** 5432 * Gets the id of a view for which this view serves as a label for 5433 * accessibility purposes. 5434 * 5435 * @return The labeled view id. 5436 */ 5437 @ViewDebug.ExportedProperty(category = "accessibility") 5438 public int getLabelFor() { 5439 return mLabelForId; 5440 } 5441 5442 /** 5443 * Sets the id of a view for which this view serves as a label for 5444 * accessibility purposes. 5445 * 5446 * @param id The labeled view id. 5447 */ 5448 @RemotableViewMethod 5449 public void setLabelFor(int id) { 5450 mLabelForId = id; 5451 if (mLabelForId != View.NO_ID 5452 && mID == View.NO_ID) { 5453 mID = generateViewId(); 5454 } 5455 } 5456 5457 /** 5458 * Invoked whenever this view loses focus, either by losing window focus or by losing 5459 * focus within its window. This method can be used to clear any state tied to the 5460 * focus. For instance, if a button is held pressed with the trackball and the window 5461 * loses focus, this method can be used to cancel the press. 5462 * 5463 * Subclasses of View overriding this method should always call super.onFocusLost(). 5464 * 5465 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5466 * @see #onWindowFocusChanged(boolean) 5467 * 5468 * @hide pending API council approval 5469 */ 5470 protected void onFocusLost() { 5471 resetPressedState(); 5472 } 5473 5474 private void resetPressedState() { 5475 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5476 return; 5477 } 5478 5479 if (isPressed()) { 5480 setPressed(false); 5481 5482 if (!mHasPerformedLongPress) { 5483 removeLongPressCallback(); 5484 } 5485 } 5486 } 5487 5488 /** 5489 * Returns true if this view has focus 5490 * 5491 * @return True if this view has focus, false otherwise. 5492 */ 5493 @ViewDebug.ExportedProperty(category = "focus") 5494 public boolean isFocused() { 5495 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5496 } 5497 5498 /** 5499 * Find the view in the hierarchy rooted at this view that currently has 5500 * focus. 5501 * 5502 * @return The view that currently has focus, or null if no focused view can 5503 * be found. 5504 */ 5505 public View findFocus() { 5506 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5507 } 5508 5509 /** 5510 * Indicates whether this view is one of the set of scrollable containers in 5511 * its window. 5512 * 5513 * @return whether this view is one of the set of scrollable containers in 5514 * its window 5515 * 5516 * @attr ref android.R.styleable#View_isScrollContainer 5517 */ 5518 public boolean isScrollContainer() { 5519 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5520 } 5521 5522 /** 5523 * Change whether this view is one of the set of scrollable containers in 5524 * its window. This will be used to determine whether the window can 5525 * resize or must pan when a soft input area is open -- scrollable 5526 * containers allow the window to use resize mode since the container 5527 * will appropriately shrink. 5528 * 5529 * @attr ref android.R.styleable#View_isScrollContainer 5530 */ 5531 public void setScrollContainer(boolean isScrollContainer) { 5532 if (isScrollContainer) { 5533 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5534 mAttachInfo.mScrollContainers.add(this); 5535 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5536 } 5537 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5538 } else { 5539 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5540 mAttachInfo.mScrollContainers.remove(this); 5541 } 5542 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5543 } 5544 } 5545 5546 /** 5547 * Returns the quality of the drawing cache. 5548 * 5549 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5550 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5551 * 5552 * @see #setDrawingCacheQuality(int) 5553 * @see #setDrawingCacheEnabled(boolean) 5554 * @see #isDrawingCacheEnabled() 5555 * 5556 * @attr ref android.R.styleable#View_drawingCacheQuality 5557 */ 5558 public int getDrawingCacheQuality() { 5559 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5560 } 5561 5562 /** 5563 * Set the drawing cache quality of this view. This value is used only when the 5564 * drawing cache is enabled 5565 * 5566 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5567 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5568 * 5569 * @see #getDrawingCacheQuality() 5570 * @see #setDrawingCacheEnabled(boolean) 5571 * @see #isDrawingCacheEnabled() 5572 * 5573 * @attr ref android.R.styleable#View_drawingCacheQuality 5574 */ 5575 public void setDrawingCacheQuality(int quality) { 5576 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5577 } 5578 5579 /** 5580 * Returns whether the screen should remain on, corresponding to the current 5581 * value of {@link #KEEP_SCREEN_ON}. 5582 * 5583 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5584 * 5585 * @see #setKeepScreenOn(boolean) 5586 * 5587 * @attr ref android.R.styleable#View_keepScreenOn 5588 */ 5589 public boolean getKeepScreenOn() { 5590 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5591 } 5592 5593 /** 5594 * Controls whether the screen should remain on, modifying the 5595 * value of {@link #KEEP_SCREEN_ON}. 5596 * 5597 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5598 * 5599 * @see #getKeepScreenOn() 5600 * 5601 * @attr ref android.R.styleable#View_keepScreenOn 5602 */ 5603 public void setKeepScreenOn(boolean keepScreenOn) { 5604 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5605 } 5606 5607 /** 5608 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5609 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5610 * 5611 * @attr ref android.R.styleable#View_nextFocusLeft 5612 */ 5613 public int getNextFocusLeftId() { 5614 return mNextFocusLeftId; 5615 } 5616 5617 /** 5618 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5619 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5620 * decide automatically. 5621 * 5622 * @attr ref android.R.styleable#View_nextFocusLeft 5623 */ 5624 public void setNextFocusLeftId(int nextFocusLeftId) { 5625 mNextFocusLeftId = nextFocusLeftId; 5626 } 5627 5628 /** 5629 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5630 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5631 * 5632 * @attr ref android.R.styleable#View_nextFocusRight 5633 */ 5634 public int getNextFocusRightId() { 5635 return mNextFocusRightId; 5636 } 5637 5638 /** 5639 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5640 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5641 * decide automatically. 5642 * 5643 * @attr ref android.R.styleable#View_nextFocusRight 5644 */ 5645 public void setNextFocusRightId(int nextFocusRightId) { 5646 mNextFocusRightId = nextFocusRightId; 5647 } 5648 5649 /** 5650 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5651 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5652 * 5653 * @attr ref android.R.styleable#View_nextFocusUp 5654 */ 5655 public int getNextFocusUpId() { 5656 return mNextFocusUpId; 5657 } 5658 5659 /** 5660 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5661 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5662 * decide automatically. 5663 * 5664 * @attr ref android.R.styleable#View_nextFocusUp 5665 */ 5666 public void setNextFocusUpId(int nextFocusUpId) { 5667 mNextFocusUpId = nextFocusUpId; 5668 } 5669 5670 /** 5671 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5672 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5673 * 5674 * @attr ref android.R.styleable#View_nextFocusDown 5675 */ 5676 public int getNextFocusDownId() { 5677 return mNextFocusDownId; 5678 } 5679 5680 /** 5681 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5682 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5683 * decide automatically. 5684 * 5685 * @attr ref android.R.styleable#View_nextFocusDown 5686 */ 5687 public void setNextFocusDownId(int nextFocusDownId) { 5688 mNextFocusDownId = nextFocusDownId; 5689 } 5690 5691 /** 5692 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5693 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5694 * 5695 * @attr ref android.R.styleable#View_nextFocusForward 5696 */ 5697 public int getNextFocusForwardId() { 5698 return mNextFocusForwardId; 5699 } 5700 5701 /** 5702 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5703 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 5704 * decide automatically. 5705 * 5706 * @attr ref android.R.styleable#View_nextFocusForward 5707 */ 5708 public void setNextFocusForwardId(int nextFocusForwardId) { 5709 mNextFocusForwardId = nextFocusForwardId; 5710 } 5711 5712 /** 5713 * Returns the visibility of this view and all of its ancestors 5714 * 5715 * @return True if this view and all of its ancestors are {@link #VISIBLE} 5716 */ 5717 public boolean isShown() { 5718 View current = this; 5719 //noinspection ConstantConditions 5720 do { 5721 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5722 return false; 5723 } 5724 ViewParent parent = current.mParent; 5725 if (parent == null) { 5726 return false; // We are not attached to the view root 5727 } 5728 if (!(parent instanceof View)) { 5729 return true; 5730 } 5731 current = (View) parent; 5732 } while (current != null); 5733 5734 return false; 5735 } 5736 5737 /** 5738 * Called by the view hierarchy when the content insets for a window have 5739 * changed, to allow it to adjust its content to fit within those windows. 5740 * The content insets tell you the space that the status bar, input method, 5741 * and other system windows infringe on the application's window. 5742 * 5743 * <p>You do not normally need to deal with this function, since the default 5744 * window decoration given to applications takes care of applying it to the 5745 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 5746 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 5747 * and your content can be placed under those system elements. You can then 5748 * use this method within your view hierarchy if you have parts of your UI 5749 * which you would like to ensure are not being covered. 5750 * 5751 * <p>The default implementation of this method simply applies the content 5752 * insets to the view's padding, consuming that content (modifying the 5753 * insets to be 0), and returning true. This behavior is off by default, but can 5754 * be enabled through {@link #setFitsSystemWindows(boolean)}. 5755 * 5756 * <p>This function's traversal down the hierarchy is depth-first. The same content 5757 * insets object is propagated down the hierarchy, so any changes made to it will 5758 * be seen by all following views (including potentially ones above in 5759 * the hierarchy since this is a depth-first traversal). The first view 5760 * that returns true will abort the entire traversal. 5761 * 5762 * <p>The default implementation works well for a situation where it is 5763 * used with a container that covers the entire window, allowing it to 5764 * apply the appropriate insets to its content on all edges. If you need 5765 * a more complicated layout (such as two different views fitting system 5766 * windows, one on the top of the window, and one on the bottom), 5767 * you can override the method and handle the insets however you would like. 5768 * Note that the insets provided by the framework are always relative to the 5769 * far edges of the window, not accounting for the location of the called view 5770 * within that window. (In fact when this method is called you do not yet know 5771 * where the layout will place the view, as it is done before layout happens.) 5772 * 5773 * <p>Note: unlike many View methods, there is no dispatch phase to this 5774 * call. If you are overriding it in a ViewGroup and want to allow the 5775 * call to continue to your children, you must be sure to call the super 5776 * implementation. 5777 * 5778 * <p>Here is a sample layout that makes use of fitting system windows 5779 * to have controls for a video view placed inside of the window decorations 5780 * that it hides and shows. This can be used with code like the second 5781 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 5782 * 5783 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 5784 * 5785 * @param insets Current content insets of the window. Prior to 5786 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 5787 * the insets or else you and Android will be unhappy. 5788 * 5789 * @return {@code true} if this view applied the insets and it should not 5790 * continue propagating further down the hierarchy, {@code false} otherwise. 5791 * @see #getFitsSystemWindows() 5792 * @see #setFitsSystemWindows(boolean) 5793 * @see #setSystemUiVisibility(int) 5794 */ 5795 protected boolean fitSystemWindows(Rect insets) { 5796 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 5797 mUserPaddingStart = UNDEFINED_PADDING; 5798 mUserPaddingEnd = UNDEFINED_PADDING; 5799 Rect localInsets = sThreadLocal.get(); 5800 if (localInsets == null) { 5801 localInsets = new Rect(); 5802 sThreadLocal.set(localInsets); 5803 } 5804 boolean res = computeFitSystemWindows(insets, localInsets); 5805 internalSetPadding(localInsets.left, localInsets.top, 5806 localInsets.right, localInsets.bottom); 5807 return res; 5808 } 5809 return false; 5810 } 5811 5812 /** 5813 * @hide Compute the insets that should be consumed by this view and the ones 5814 * that should propagate to those under it. 5815 */ 5816 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 5817 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 5818 || mAttachInfo == null 5819 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 5820 && !mAttachInfo.mOverscanRequested)) { 5821 outLocalInsets.set(inoutInsets); 5822 inoutInsets.set(0, 0, 0, 0); 5823 return true; 5824 } else { 5825 // The application wants to take care of fitting system window for 5826 // the content... however we still need to take care of any overscan here. 5827 final Rect overscan = mAttachInfo.mOverscanInsets; 5828 outLocalInsets.set(overscan); 5829 inoutInsets.left -= overscan.left; 5830 inoutInsets.top -= overscan.top; 5831 inoutInsets.right -= overscan.right; 5832 inoutInsets.bottom -= overscan.bottom; 5833 return false; 5834 } 5835 } 5836 5837 /** 5838 * Sets whether or not this view should account for system screen decorations 5839 * such as the status bar and inset its content; that is, controlling whether 5840 * the default implementation of {@link #fitSystemWindows(Rect)} will be 5841 * executed. See that method for more details. 5842 * 5843 * <p>Note that if you are providing your own implementation of 5844 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 5845 * flag to true -- your implementation will be overriding the default 5846 * implementation that checks this flag. 5847 * 5848 * @param fitSystemWindows If true, then the default implementation of 5849 * {@link #fitSystemWindows(Rect)} will be executed. 5850 * 5851 * @attr ref android.R.styleable#View_fitsSystemWindows 5852 * @see #getFitsSystemWindows() 5853 * @see #fitSystemWindows(Rect) 5854 * @see #setSystemUiVisibility(int) 5855 */ 5856 public void setFitsSystemWindows(boolean fitSystemWindows) { 5857 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 5858 } 5859 5860 /** 5861 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 5862 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 5863 * will be executed. 5864 * 5865 * @return {@code true} if the default implementation of 5866 * {@link #fitSystemWindows(Rect)} will be executed. 5867 * 5868 * @attr ref android.R.styleable#View_fitsSystemWindows 5869 * @see #setFitsSystemWindows(boolean) 5870 * @see #fitSystemWindows(Rect) 5871 * @see #setSystemUiVisibility(int) 5872 */ 5873 public boolean getFitsSystemWindows() { 5874 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 5875 } 5876 5877 /** @hide */ 5878 public boolean fitsSystemWindows() { 5879 return getFitsSystemWindows(); 5880 } 5881 5882 /** 5883 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 5884 */ 5885 public void requestFitSystemWindows() { 5886 if (mParent != null) { 5887 mParent.requestFitSystemWindows(); 5888 } 5889 } 5890 5891 /** 5892 * For use by PhoneWindow to make its own system window fitting optional. 5893 * @hide 5894 */ 5895 public void makeOptionalFitsSystemWindows() { 5896 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 5897 } 5898 5899 /** 5900 * Returns the visibility status for this view. 5901 * 5902 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5903 * @attr ref android.R.styleable#View_visibility 5904 */ 5905 @ViewDebug.ExportedProperty(mapping = { 5906 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 5907 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 5908 @ViewDebug.IntToString(from = GONE, to = "GONE") 5909 }) 5910 public int getVisibility() { 5911 return mViewFlags & VISIBILITY_MASK; 5912 } 5913 5914 /** 5915 * Set the enabled state of this view. 5916 * 5917 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5918 * @attr ref android.R.styleable#View_visibility 5919 */ 5920 @RemotableViewMethod 5921 public void setVisibility(int visibility) { 5922 setFlags(visibility, VISIBILITY_MASK); 5923 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 5924 } 5925 5926 /** 5927 * Returns the enabled status for this view. The interpretation of the 5928 * enabled state varies by subclass. 5929 * 5930 * @return True if this view is enabled, false otherwise. 5931 */ 5932 @ViewDebug.ExportedProperty 5933 public boolean isEnabled() { 5934 return (mViewFlags & ENABLED_MASK) == ENABLED; 5935 } 5936 5937 /** 5938 * Set the enabled state of this view. The interpretation of the enabled 5939 * state varies by subclass. 5940 * 5941 * @param enabled True if this view is enabled, false otherwise. 5942 */ 5943 @RemotableViewMethod 5944 public void setEnabled(boolean enabled) { 5945 if (enabled == isEnabled()) return; 5946 5947 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 5948 5949 /* 5950 * The View most likely has to change its appearance, so refresh 5951 * the drawable state. 5952 */ 5953 refreshDrawableState(); 5954 5955 // Invalidate too, since the default behavior for views is to be 5956 // be drawn at 50% alpha rather than to change the drawable. 5957 invalidate(true); 5958 } 5959 5960 /** 5961 * Set whether this view can receive the focus. 5962 * 5963 * Setting this to false will also ensure that this view is not focusable 5964 * in touch mode. 5965 * 5966 * @param focusable If true, this view can receive the focus. 5967 * 5968 * @see #setFocusableInTouchMode(boolean) 5969 * @attr ref android.R.styleable#View_focusable 5970 */ 5971 public void setFocusable(boolean focusable) { 5972 if (!focusable) { 5973 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 5974 } 5975 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 5976 } 5977 5978 /** 5979 * Set whether this view can receive focus while in touch mode. 5980 * 5981 * Setting this to true will also ensure that this view is focusable. 5982 * 5983 * @param focusableInTouchMode If true, this view can receive the focus while 5984 * in touch mode. 5985 * 5986 * @see #setFocusable(boolean) 5987 * @attr ref android.R.styleable#View_focusableInTouchMode 5988 */ 5989 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 5990 // Focusable in touch mode should always be set before the focusable flag 5991 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 5992 // which, in touch mode, will not successfully request focus on this view 5993 // because the focusable in touch mode flag is not set 5994 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 5995 if (focusableInTouchMode) { 5996 setFlags(FOCUSABLE, FOCUSABLE_MASK); 5997 } 5998 } 5999 6000 /** 6001 * Set whether this view should have sound effects enabled for events such as 6002 * clicking and touching. 6003 * 6004 * <p>You may wish to disable sound effects for a view if you already play sounds, 6005 * for instance, a dial key that plays dtmf tones. 6006 * 6007 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6008 * @see #isSoundEffectsEnabled() 6009 * @see #playSoundEffect(int) 6010 * @attr ref android.R.styleable#View_soundEffectsEnabled 6011 */ 6012 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6013 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6014 } 6015 6016 /** 6017 * @return whether this view should have sound effects enabled for events such as 6018 * clicking and touching. 6019 * 6020 * @see #setSoundEffectsEnabled(boolean) 6021 * @see #playSoundEffect(int) 6022 * @attr ref android.R.styleable#View_soundEffectsEnabled 6023 */ 6024 @ViewDebug.ExportedProperty 6025 public boolean isSoundEffectsEnabled() { 6026 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6027 } 6028 6029 /** 6030 * Set whether this view should have haptic feedback for events such as 6031 * long presses. 6032 * 6033 * <p>You may wish to disable haptic feedback if your view already controls 6034 * its own haptic feedback. 6035 * 6036 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6037 * @see #isHapticFeedbackEnabled() 6038 * @see #performHapticFeedback(int) 6039 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6040 */ 6041 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6042 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6043 } 6044 6045 /** 6046 * @return whether this view should have haptic feedback enabled for events 6047 * long presses. 6048 * 6049 * @see #setHapticFeedbackEnabled(boolean) 6050 * @see #performHapticFeedback(int) 6051 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6052 */ 6053 @ViewDebug.ExportedProperty 6054 public boolean isHapticFeedbackEnabled() { 6055 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6056 } 6057 6058 /** 6059 * Returns the layout direction for this view. 6060 * 6061 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6062 * {@link #LAYOUT_DIRECTION_RTL}, 6063 * {@link #LAYOUT_DIRECTION_INHERIT} or 6064 * {@link #LAYOUT_DIRECTION_LOCALE}. 6065 * 6066 * @attr ref android.R.styleable#View_layoutDirection 6067 * 6068 * @hide 6069 */ 6070 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6071 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6072 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6073 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6074 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6075 }) 6076 public int getRawLayoutDirection() { 6077 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6078 } 6079 6080 /** 6081 * Set the layout direction for this view. This will propagate a reset of layout direction 6082 * resolution to the view's children and resolve layout direction for this view. 6083 * 6084 * @param layoutDirection the layout direction to set. Should be one of: 6085 * 6086 * {@link #LAYOUT_DIRECTION_LTR}, 6087 * {@link #LAYOUT_DIRECTION_RTL}, 6088 * {@link #LAYOUT_DIRECTION_INHERIT}, 6089 * {@link #LAYOUT_DIRECTION_LOCALE}. 6090 * 6091 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6092 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6093 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6094 * 6095 * @attr ref android.R.styleable#View_layoutDirection 6096 */ 6097 @RemotableViewMethod 6098 public void setLayoutDirection(int layoutDirection) { 6099 if (getRawLayoutDirection() != layoutDirection) { 6100 // Reset the current layout direction and the resolved one 6101 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6102 resetRtlProperties(); 6103 // Set the new layout direction (filtered) 6104 mPrivateFlags2 |= 6105 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6106 // We need to resolve all RTL properties as they all depend on layout direction 6107 resolveRtlPropertiesIfNeeded(); 6108 requestLayout(); 6109 invalidate(true); 6110 } 6111 } 6112 6113 /** 6114 * Returns the resolved layout direction for this view. 6115 * 6116 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6117 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6118 * 6119 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6120 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6121 * 6122 * @attr ref android.R.styleable#View_layoutDirection 6123 */ 6124 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6125 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6126 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6127 }) 6128 public int getLayoutDirection() { 6129 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6130 if (targetSdkVersion < JELLY_BEAN_MR1) { 6131 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6132 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6133 } 6134 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6135 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6136 } 6137 6138 /** 6139 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6140 * layout attribute and/or the inherited value from the parent 6141 * 6142 * @return true if the layout is right-to-left. 6143 * 6144 * @hide 6145 */ 6146 @ViewDebug.ExportedProperty(category = "layout") 6147 public boolean isLayoutRtl() { 6148 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6149 } 6150 6151 /** 6152 * Indicates whether the view is currently tracking transient state that the 6153 * app should not need to concern itself with saving and restoring, but that 6154 * the framework should take special note to preserve when possible. 6155 * 6156 * <p>A view with transient state cannot be trivially rebound from an external 6157 * data source, such as an adapter binding item views in a list. This may be 6158 * because the view is performing an animation, tracking user selection 6159 * of content, or similar.</p> 6160 * 6161 * @return true if the view has transient state 6162 */ 6163 @ViewDebug.ExportedProperty(category = "layout") 6164 public boolean hasTransientState() { 6165 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6166 } 6167 6168 /** 6169 * Set whether this view is currently tracking transient state that the 6170 * framework should attempt to preserve when possible. This flag is reference counted, 6171 * so every call to setHasTransientState(true) should be paired with a later call 6172 * to setHasTransientState(false). 6173 * 6174 * <p>A view with transient state cannot be trivially rebound from an external 6175 * data source, such as an adapter binding item views in a list. This may be 6176 * because the view is performing an animation, tracking user selection 6177 * of content, or similar.</p> 6178 * 6179 * @param hasTransientState true if this view has transient state 6180 */ 6181 public void setHasTransientState(boolean hasTransientState) { 6182 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6183 mTransientStateCount - 1; 6184 if (mTransientStateCount < 0) { 6185 mTransientStateCount = 0; 6186 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6187 "unmatched pair of setHasTransientState calls"); 6188 } else if ((hasTransientState && mTransientStateCount == 1) || 6189 (!hasTransientState && mTransientStateCount == 0)) { 6190 // update flag if we've just incremented up from 0 or decremented down to 0 6191 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6192 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6193 if (mParent != null) { 6194 try { 6195 mParent.childHasTransientStateChanged(this, hasTransientState); 6196 } catch (AbstractMethodError e) { 6197 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6198 " does not fully implement ViewParent", e); 6199 } 6200 } 6201 } 6202 } 6203 6204 /** 6205 * Returns true if this view is currently attached to a window. 6206 */ 6207 public boolean isAttachedToWindow() { 6208 return mAttachInfo != null; 6209 } 6210 6211 /** 6212 * Returns true if this view has been through at least one layout since it 6213 * was last attached to or detached from a window. 6214 */ 6215 public boolean isLaidOut() { 6216 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6217 } 6218 6219 /** 6220 * If this view doesn't do any drawing on its own, set this flag to 6221 * allow further optimizations. By default, this flag is not set on 6222 * View, but could be set on some View subclasses such as ViewGroup. 6223 * 6224 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6225 * you should clear this flag. 6226 * 6227 * @param willNotDraw whether or not this View draw on its own 6228 */ 6229 public void setWillNotDraw(boolean willNotDraw) { 6230 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6231 } 6232 6233 /** 6234 * Returns whether or not this View draws on its own. 6235 * 6236 * @return true if this view has nothing to draw, false otherwise 6237 */ 6238 @ViewDebug.ExportedProperty(category = "drawing") 6239 public boolean willNotDraw() { 6240 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6241 } 6242 6243 /** 6244 * When a View's drawing cache is enabled, drawing is redirected to an 6245 * offscreen bitmap. Some views, like an ImageView, must be able to 6246 * bypass this mechanism if they already draw a single bitmap, to avoid 6247 * unnecessary usage of the memory. 6248 * 6249 * @param willNotCacheDrawing true if this view does not cache its 6250 * drawing, false otherwise 6251 */ 6252 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6253 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6254 } 6255 6256 /** 6257 * Returns whether or not this View can cache its drawing or not. 6258 * 6259 * @return true if this view does not cache its drawing, false otherwise 6260 */ 6261 @ViewDebug.ExportedProperty(category = "drawing") 6262 public boolean willNotCacheDrawing() { 6263 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6264 } 6265 6266 /** 6267 * Indicates whether this view reacts to click events or not. 6268 * 6269 * @return true if the view is clickable, false otherwise 6270 * 6271 * @see #setClickable(boolean) 6272 * @attr ref android.R.styleable#View_clickable 6273 */ 6274 @ViewDebug.ExportedProperty 6275 public boolean isClickable() { 6276 return (mViewFlags & CLICKABLE) == CLICKABLE; 6277 } 6278 6279 /** 6280 * Enables or disables click events for this view. When a view 6281 * is clickable it will change its state to "pressed" on every click. 6282 * Subclasses should set the view clickable to visually react to 6283 * user's clicks. 6284 * 6285 * @param clickable true to make the view clickable, false otherwise 6286 * 6287 * @see #isClickable() 6288 * @attr ref android.R.styleable#View_clickable 6289 */ 6290 public void setClickable(boolean clickable) { 6291 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6292 } 6293 6294 /** 6295 * Indicates whether this view reacts to long click events or not. 6296 * 6297 * @return true if the view is long clickable, false otherwise 6298 * 6299 * @see #setLongClickable(boolean) 6300 * @attr ref android.R.styleable#View_longClickable 6301 */ 6302 public boolean isLongClickable() { 6303 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6304 } 6305 6306 /** 6307 * Enables or disables long click events for this view. When a view is long 6308 * clickable it reacts to the user holding down the button for a longer 6309 * duration than a tap. This event can either launch the listener or a 6310 * context menu. 6311 * 6312 * @param longClickable true to make the view long clickable, false otherwise 6313 * @see #isLongClickable() 6314 * @attr ref android.R.styleable#View_longClickable 6315 */ 6316 public void setLongClickable(boolean longClickable) { 6317 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6318 } 6319 6320 /** 6321 * Sets the pressed state for this view. 6322 * 6323 * @see #isClickable() 6324 * @see #setClickable(boolean) 6325 * 6326 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6327 * the View's internal state from a previously set "pressed" state. 6328 */ 6329 public void setPressed(boolean pressed) { 6330 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6331 6332 if (pressed) { 6333 mPrivateFlags |= PFLAG_PRESSED; 6334 } else { 6335 mPrivateFlags &= ~PFLAG_PRESSED; 6336 } 6337 6338 if (needsRefresh) { 6339 refreshDrawableState(); 6340 } 6341 dispatchSetPressed(pressed); 6342 } 6343 6344 /** 6345 * Dispatch setPressed to all of this View's children. 6346 * 6347 * @see #setPressed(boolean) 6348 * 6349 * @param pressed The new pressed state 6350 */ 6351 protected void dispatchSetPressed(boolean pressed) { 6352 } 6353 6354 /** 6355 * Indicates whether the view is currently in pressed state. Unless 6356 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6357 * the pressed state. 6358 * 6359 * @see #setPressed(boolean) 6360 * @see #isClickable() 6361 * @see #setClickable(boolean) 6362 * 6363 * @return true if the view is currently pressed, false otherwise 6364 */ 6365 public boolean isPressed() { 6366 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6367 } 6368 6369 /** 6370 * Indicates whether this view will save its state (that is, 6371 * whether its {@link #onSaveInstanceState} method will be called). 6372 * 6373 * @return Returns true if the view state saving is enabled, else false. 6374 * 6375 * @see #setSaveEnabled(boolean) 6376 * @attr ref android.R.styleable#View_saveEnabled 6377 */ 6378 public boolean isSaveEnabled() { 6379 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6380 } 6381 6382 /** 6383 * Controls whether the saving of this view's state is 6384 * enabled (that is, whether its {@link #onSaveInstanceState} method 6385 * will be called). Note that even if freezing is enabled, the 6386 * view still must have an id assigned to it (via {@link #setId(int)}) 6387 * for its state to be saved. This flag can only disable the 6388 * saving of this view; any child views may still have their state saved. 6389 * 6390 * @param enabled Set to false to <em>disable</em> state saving, or true 6391 * (the default) to allow it. 6392 * 6393 * @see #isSaveEnabled() 6394 * @see #setId(int) 6395 * @see #onSaveInstanceState() 6396 * @attr ref android.R.styleable#View_saveEnabled 6397 */ 6398 public void setSaveEnabled(boolean enabled) { 6399 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6400 } 6401 6402 /** 6403 * Gets whether the framework should discard touches when the view's 6404 * window is obscured by another visible window. 6405 * Refer to the {@link View} security documentation for more details. 6406 * 6407 * @return True if touch filtering is enabled. 6408 * 6409 * @see #setFilterTouchesWhenObscured(boolean) 6410 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6411 */ 6412 @ViewDebug.ExportedProperty 6413 public boolean getFilterTouchesWhenObscured() { 6414 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6415 } 6416 6417 /** 6418 * Sets whether the framework should discard touches when the view's 6419 * window is obscured by another visible window. 6420 * Refer to the {@link View} security documentation for more details. 6421 * 6422 * @param enabled True if touch filtering should be enabled. 6423 * 6424 * @see #getFilterTouchesWhenObscured 6425 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6426 */ 6427 public void setFilterTouchesWhenObscured(boolean enabled) { 6428 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 6429 FILTER_TOUCHES_WHEN_OBSCURED); 6430 } 6431 6432 /** 6433 * Indicates whether the entire hierarchy under this view will save its 6434 * state when a state saving traversal occurs from its parent. The default 6435 * is true; if false, these views will not be saved unless 6436 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6437 * 6438 * @return Returns true if the view state saving from parent is enabled, else false. 6439 * 6440 * @see #setSaveFromParentEnabled(boolean) 6441 */ 6442 public boolean isSaveFromParentEnabled() { 6443 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6444 } 6445 6446 /** 6447 * Controls whether the entire hierarchy under this view will save its 6448 * state when a state saving traversal occurs from its parent. The default 6449 * is true; if false, these views will not be saved unless 6450 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6451 * 6452 * @param enabled Set to false to <em>disable</em> state saving, or true 6453 * (the default) to allow it. 6454 * 6455 * @see #isSaveFromParentEnabled() 6456 * @see #setId(int) 6457 * @see #onSaveInstanceState() 6458 */ 6459 public void setSaveFromParentEnabled(boolean enabled) { 6460 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6461 } 6462 6463 6464 /** 6465 * Returns whether this View is able to take focus. 6466 * 6467 * @return True if this view can take focus, or false otherwise. 6468 * @attr ref android.R.styleable#View_focusable 6469 */ 6470 @ViewDebug.ExportedProperty(category = "focus") 6471 public final boolean isFocusable() { 6472 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6473 } 6474 6475 /** 6476 * When a view is focusable, it may not want to take focus when in touch mode. 6477 * For example, a button would like focus when the user is navigating via a D-pad 6478 * so that the user can click on it, but once the user starts touching the screen, 6479 * the button shouldn't take focus 6480 * @return Whether the view is focusable in touch mode. 6481 * @attr ref android.R.styleable#View_focusableInTouchMode 6482 */ 6483 @ViewDebug.ExportedProperty 6484 public final boolean isFocusableInTouchMode() { 6485 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6486 } 6487 6488 /** 6489 * Find the nearest view in the specified direction that can take focus. 6490 * This does not actually give focus to that view. 6491 * 6492 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6493 * 6494 * @return The nearest focusable in the specified direction, or null if none 6495 * can be found. 6496 */ 6497 public View focusSearch(int direction) { 6498 if (mParent != null) { 6499 return mParent.focusSearch(this, direction); 6500 } else { 6501 return null; 6502 } 6503 } 6504 6505 /** 6506 * This method is the last chance for the focused view and its ancestors to 6507 * respond to an arrow key. This is called when the focused view did not 6508 * consume the key internally, nor could the view system find a new view in 6509 * the requested direction to give focus to. 6510 * 6511 * @param focused The currently focused view. 6512 * @param direction The direction focus wants to move. One of FOCUS_UP, 6513 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6514 * @return True if the this view consumed this unhandled move. 6515 */ 6516 public boolean dispatchUnhandledMove(View focused, int direction) { 6517 return false; 6518 } 6519 6520 /** 6521 * If a user manually specified the next view id for a particular direction, 6522 * use the root to look up the view. 6523 * @param root The root view of the hierarchy containing this view. 6524 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6525 * or FOCUS_BACKWARD. 6526 * @return The user specified next view, or null if there is none. 6527 */ 6528 View findUserSetNextFocus(View root, int direction) { 6529 switch (direction) { 6530 case FOCUS_LEFT: 6531 if (mNextFocusLeftId == View.NO_ID) return null; 6532 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6533 case FOCUS_RIGHT: 6534 if (mNextFocusRightId == View.NO_ID) return null; 6535 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6536 case FOCUS_UP: 6537 if (mNextFocusUpId == View.NO_ID) return null; 6538 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6539 case FOCUS_DOWN: 6540 if (mNextFocusDownId == View.NO_ID) return null; 6541 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6542 case FOCUS_FORWARD: 6543 if (mNextFocusForwardId == View.NO_ID) return null; 6544 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6545 case FOCUS_BACKWARD: { 6546 if (mID == View.NO_ID) return null; 6547 final int id = mID; 6548 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6549 @Override 6550 public boolean apply(View t) { 6551 return t.mNextFocusForwardId == id; 6552 } 6553 }); 6554 } 6555 } 6556 return null; 6557 } 6558 6559 private View findViewInsideOutShouldExist(View root, int id) { 6560 if (mMatchIdPredicate == null) { 6561 mMatchIdPredicate = new MatchIdPredicate(); 6562 } 6563 mMatchIdPredicate.mId = id; 6564 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6565 if (result == null) { 6566 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6567 } 6568 return result; 6569 } 6570 6571 /** 6572 * Find and return all focusable views that are descendants of this view, 6573 * possibly including this view if it is focusable itself. 6574 * 6575 * @param direction The direction of the focus 6576 * @return A list of focusable views 6577 */ 6578 public ArrayList<View> getFocusables(int direction) { 6579 ArrayList<View> result = new ArrayList<View>(24); 6580 addFocusables(result, direction); 6581 return result; 6582 } 6583 6584 /** 6585 * Add any focusable views that are descendants of this view (possibly 6586 * including this view if it is focusable itself) to views. If we are in touch mode, 6587 * only add views that are also focusable in touch mode. 6588 * 6589 * @param views Focusable views found so far 6590 * @param direction The direction of the focus 6591 */ 6592 public void addFocusables(ArrayList<View> views, int direction) { 6593 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6594 } 6595 6596 /** 6597 * Adds any focusable views that are descendants of this view (possibly 6598 * including this view if it is focusable itself) to views. This method 6599 * adds all focusable views regardless if we are in touch mode or 6600 * only views focusable in touch mode if we are in touch mode or 6601 * only views that can take accessibility focus if accessibility is enabeld 6602 * depending on the focusable mode paramater. 6603 * 6604 * @param views Focusable views found so far or null if all we are interested is 6605 * the number of focusables. 6606 * @param direction The direction of the focus. 6607 * @param focusableMode The type of focusables to be added. 6608 * 6609 * @see #FOCUSABLES_ALL 6610 * @see #FOCUSABLES_TOUCH_MODE 6611 */ 6612 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 6613 if (views == null) { 6614 return; 6615 } 6616 if (!isFocusable()) { 6617 return; 6618 } 6619 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6620 && isInTouchMode() && !isFocusableInTouchMode()) { 6621 return; 6622 } 6623 views.add(this); 6624 } 6625 6626 /** 6627 * Finds the Views that contain given text. The containment is case insensitive. 6628 * The search is performed by either the text that the View renders or the content 6629 * description that describes the view for accessibility purposes and the view does 6630 * not render or both. Clients can specify how the search is to be performed via 6631 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 6632 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 6633 * 6634 * @param outViews The output list of matching Views. 6635 * @param searched The text to match against. 6636 * 6637 * @see #FIND_VIEWS_WITH_TEXT 6638 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 6639 * @see #setContentDescription(CharSequence) 6640 */ 6641 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 6642 if (getAccessibilityNodeProvider() != null) { 6643 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 6644 outViews.add(this); 6645 } 6646 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 6647 && (searched != null && searched.length() > 0) 6648 && (mContentDescription != null && mContentDescription.length() > 0)) { 6649 String searchedLowerCase = searched.toString().toLowerCase(); 6650 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 6651 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 6652 outViews.add(this); 6653 } 6654 } 6655 } 6656 6657 /** 6658 * Find and return all touchable views that are descendants of this view, 6659 * possibly including this view if it is touchable itself. 6660 * 6661 * @return A list of touchable views 6662 */ 6663 public ArrayList<View> getTouchables() { 6664 ArrayList<View> result = new ArrayList<View>(); 6665 addTouchables(result); 6666 return result; 6667 } 6668 6669 /** 6670 * Add any touchable views that are descendants of this view (possibly 6671 * including this view if it is touchable itself) to views. 6672 * 6673 * @param views Touchable views found so far 6674 */ 6675 public void addTouchables(ArrayList<View> views) { 6676 final int viewFlags = mViewFlags; 6677 6678 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 6679 && (viewFlags & ENABLED_MASK) == ENABLED) { 6680 views.add(this); 6681 } 6682 } 6683 6684 /** 6685 * Returns whether this View is accessibility focused. 6686 * 6687 * @return True if this View is accessibility focused. 6688 * @hide 6689 */ 6690 public boolean isAccessibilityFocused() { 6691 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 6692 } 6693 6694 /** 6695 * Call this to try to give accessibility focus to this view. 6696 * 6697 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 6698 * returns false or the view is no visible or the view already has accessibility 6699 * focus. 6700 * 6701 * See also {@link #focusSearch(int)}, which is what you call to say that you 6702 * have focus, and you want your parent to look for the next one. 6703 * 6704 * @return Whether this view actually took accessibility focus. 6705 * 6706 * @hide 6707 */ 6708 public boolean requestAccessibilityFocus() { 6709 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 6710 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 6711 return false; 6712 } 6713 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6714 return false; 6715 } 6716 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 6717 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 6718 ViewRootImpl viewRootImpl = getViewRootImpl(); 6719 if (viewRootImpl != null) { 6720 viewRootImpl.setAccessibilityFocus(this, null); 6721 } 6722 invalidate(); 6723 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 6724 return true; 6725 } 6726 return false; 6727 } 6728 6729 /** 6730 * Call this to try to clear accessibility focus of this view. 6731 * 6732 * See also {@link #focusSearch(int)}, which is what you call to say that you 6733 * have focus, and you want your parent to look for the next one. 6734 * 6735 * @hide 6736 */ 6737 public void clearAccessibilityFocus() { 6738 clearAccessibilityFocusNoCallbacks(); 6739 // Clear the global reference of accessibility focus if this 6740 // view or any of its descendants had accessibility focus. 6741 ViewRootImpl viewRootImpl = getViewRootImpl(); 6742 if (viewRootImpl != null) { 6743 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 6744 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 6745 viewRootImpl.setAccessibilityFocus(null, null); 6746 } 6747 } 6748 } 6749 6750 private void sendAccessibilityHoverEvent(int eventType) { 6751 // Since we are not delivering to a client accessibility events from not 6752 // important views (unless the clinet request that) we need to fire the 6753 // event from the deepest view exposed to the client. As a consequence if 6754 // the user crosses a not exposed view the client will see enter and exit 6755 // of the exposed predecessor followed by and enter and exit of that same 6756 // predecessor when entering and exiting the not exposed descendant. This 6757 // is fine since the client has a clear idea which view is hovered at the 6758 // price of a couple more events being sent. This is a simple and 6759 // working solution. 6760 View source = this; 6761 while (true) { 6762 if (source.includeForAccessibility()) { 6763 source.sendAccessibilityEvent(eventType); 6764 return; 6765 } 6766 ViewParent parent = source.getParent(); 6767 if (parent instanceof View) { 6768 source = (View) parent; 6769 } else { 6770 return; 6771 } 6772 } 6773 } 6774 6775 /** 6776 * Clears accessibility focus without calling any callback methods 6777 * normally invoked in {@link #clearAccessibilityFocus()}. This method 6778 * is used for clearing accessibility focus when giving this focus to 6779 * another view. 6780 */ 6781 void clearAccessibilityFocusNoCallbacks() { 6782 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6783 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6784 invalidate(); 6785 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 6786 } 6787 } 6788 6789 /** 6790 * Call this to try to give focus to a specific view or to one of its 6791 * descendants. 6792 * 6793 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6794 * false), or if it is focusable and it is not focusable in touch mode 6795 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6796 * 6797 * See also {@link #focusSearch(int)}, which is what you call to say that you 6798 * have focus, and you want your parent to look for the next one. 6799 * 6800 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 6801 * {@link #FOCUS_DOWN} and <code>null</code>. 6802 * 6803 * @return Whether this view or one of its descendants actually took focus. 6804 */ 6805 public final boolean requestFocus() { 6806 return requestFocus(View.FOCUS_DOWN); 6807 } 6808 6809 /** 6810 * Call this to try to give focus to a specific view or to one of its 6811 * descendants and give it a hint about what direction focus is heading. 6812 * 6813 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6814 * false), or if it is focusable and it is not focusable in touch mode 6815 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6816 * 6817 * See also {@link #focusSearch(int)}, which is what you call to say that you 6818 * have focus, and you want your parent to look for the next one. 6819 * 6820 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 6821 * <code>null</code> set for the previously focused rectangle. 6822 * 6823 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6824 * @return Whether this view or one of its descendants actually took focus. 6825 */ 6826 public final boolean requestFocus(int direction) { 6827 return requestFocus(direction, null); 6828 } 6829 6830 /** 6831 * Call this to try to give focus to a specific view or to one of its descendants 6832 * and give it hints about the direction and a specific rectangle that the focus 6833 * is coming from. The rectangle can help give larger views a finer grained hint 6834 * about where focus is coming from, and therefore, where to show selection, or 6835 * forward focus change internally. 6836 * 6837 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6838 * false), or if it is focusable and it is not focusable in touch mode 6839 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6840 * 6841 * A View will not take focus if it is not visible. 6842 * 6843 * A View will not take focus if one of its parents has 6844 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 6845 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 6846 * 6847 * See also {@link #focusSearch(int)}, which is what you call to say that you 6848 * have focus, and you want your parent to look for the next one. 6849 * 6850 * You may wish to override this method if your custom {@link View} has an internal 6851 * {@link View} that it wishes to forward the request to. 6852 * 6853 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6854 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 6855 * to give a finer grained hint about where focus is coming from. May be null 6856 * if there is no hint. 6857 * @return Whether this view or one of its descendants actually took focus. 6858 */ 6859 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 6860 return requestFocusNoSearch(direction, previouslyFocusedRect); 6861 } 6862 6863 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 6864 // need to be focusable 6865 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 6866 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6867 return false; 6868 } 6869 6870 // need to be focusable in touch mode if in touch mode 6871 if (isInTouchMode() && 6872 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 6873 return false; 6874 } 6875 6876 // need to not have any parents blocking us 6877 if (hasAncestorThatBlocksDescendantFocus()) { 6878 return false; 6879 } 6880 6881 handleFocusGainInternal(direction, previouslyFocusedRect); 6882 return true; 6883 } 6884 6885 /** 6886 * Call this to try to give focus to a specific view or to one of its descendants. This is a 6887 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 6888 * touch mode to request focus when they are touched. 6889 * 6890 * @return Whether this view or one of its descendants actually took focus. 6891 * 6892 * @see #isInTouchMode() 6893 * 6894 */ 6895 public final boolean requestFocusFromTouch() { 6896 // Leave touch mode if we need to 6897 if (isInTouchMode()) { 6898 ViewRootImpl viewRoot = getViewRootImpl(); 6899 if (viewRoot != null) { 6900 viewRoot.ensureTouchMode(false); 6901 } 6902 } 6903 return requestFocus(View.FOCUS_DOWN); 6904 } 6905 6906 /** 6907 * @return Whether any ancestor of this view blocks descendant focus. 6908 */ 6909 private boolean hasAncestorThatBlocksDescendantFocus() { 6910 ViewParent ancestor = mParent; 6911 while (ancestor instanceof ViewGroup) { 6912 final ViewGroup vgAncestor = (ViewGroup) ancestor; 6913 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 6914 return true; 6915 } else { 6916 ancestor = vgAncestor.getParent(); 6917 } 6918 } 6919 return false; 6920 } 6921 6922 /** 6923 * Gets the mode for determining whether this View is important for accessibility 6924 * which is if it fires accessibility events and if it is reported to 6925 * accessibility services that query the screen. 6926 * 6927 * @return The mode for determining whether a View is important for accessibility. 6928 * 6929 * @attr ref android.R.styleable#View_importantForAccessibility 6930 * 6931 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6932 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6933 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6934 */ 6935 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 6936 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 6937 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 6938 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no") 6939 }) 6940 public int getImportantForAccessibility() { 6941 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6942 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6943 } 6944 6945 /** 6946 * Sets how to determine whether this view is important for accessibility 6947 * which is if it fires accessibility events and if it is reported to 6948 * accessibility services that query the screen. 6949 * 6950 * @param mode How to determine whether this view is important for accessibility. 6951 * 6952 * @attr ref android.R.styleable#View_importantForAccessibility 6953 * 6954 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6955 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6956 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6957 */ 6958 public void setImportantForAccessibility(int mode) { 6959 final boolean oldIncludeForAccessibility = includeForAccessibility(); 6960 if (mode != getImportantForAccessibility()) { 6961 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6962 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 6963 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6964 if (oldIncludeForAccessibility != includeForAccessibility()) { 6965 notifySubtreeAccessibilityStateChangedIfNeeded(); 6966 } else { 6967 notifyViewAccessibilityStateChangedIfNeeded(); 6968 } 6969 } 6970 } 6971 6972 /** 6973 * Gets whether this view should be exposed for accessibility. 6974 * 6975 * @return Whether the view is exposed for accessibility. 6976 * 6977 * @hide 6978 */ 6979 public boolean isImportantForAccessibility() { 6980 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6981 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6982 switch (mode) { 6983 case IMPORTANT_FOR_ACCESSIBILITY_YES: 6984 return true; 6985 case IMPORTANT_FOR_ACCESSIBILITY_NO: 6986 return false; 6987 case IMPORTANT_FOR_ACCESSIBILITY_AUTO: 6988 return isActionableForAccessibility() || hasListenersForAccessibility() 6989 || getAccessibilityNodeProvider() != null; 6990 default: 6991 throw new IllegalArgumentException("Unknow important for accessibility mode: " 6992 + mode); 6993 } 6994 } 6995 6996 /** 6997 * Gets the parent for accessibility purposes. Note that the parent for 6998 * accessibility is not necessary the immediate parent. It is the first 6999 * predecessor that is important for accessibility. 7000 * 7001 * @return The parent for accessibility purposes. 7002 */ 7003 public ViewParent getParentForAccessibility() { 7004 if (mParent instanceof View) { 7005 View parentView = (View) mParent; 7006 if (parentView.includeForAccessibility()) { 7007 return mParent; 7008 } else { 7009 return mParent.getParentForAccessibility(); 7010 } 7011 } 7012 return null; 7013 } 7014 7015 /** 7016 * Adds the children of a given View for accessibility. Since some Views are 7017 * not important for accessibility the children for accessibility are not 7018 * necessarily direct children of the view, rather they are the first level of 7019 * descendants important for accessibility. 7020 * 7021 * @param children The list of children for accessibility. 7022 */ 7023 public void addChildrenForAccessibility(ArrayList<View> children) { 7024 if (includeForAccessibility()) { 7025 children.add(this); 7026 } 7027 } 7028 7029 /** 7030 * Whether to regard this view for accessibility. A view is regarded for 7031 * accessibility if it is important for accessibility or the querying 7032 * accessibility service has explicitly requested that view not 7033 * important for accessibility are regarded. 7034 * 7035 * @return Whether to regard the view for accessibility. 7036 * 7037 * @hide 7038 */ 7039 public boolean includeForAccessibility() { 7040 //noinspection SimplifiableIfStatement 7041 if (mAttachInfo != null) { 7042 return (mAttachInfo.mAccessibilityFetchFlags 7043 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7044 || isImportantForAccessibility(); 7045 } 7046 return false; 7047 } 7048 7049 /** 7050 * Returns whether the View is considered actionable from 7051 * accessibility perspective. Such view are important for 7052 * accessibility. 7053 * 7054 * @return True if the view is actionable for accessibility. 7055 * 7056 * @hide 7057 */ 7058 public boolean isActionableForAccessibility() { 7059 return (isClickable() || isLongClickable() || isFocusable()); 7060 } 7061 7062 /** 7063 * Returns whether the View has registered callbacks wich makes it 7064 * important for accessibility. 7065 * 7066 * @return True if the view is actionable for accessibility. 7067 */ 7068 private boolean hasListenersForAccessibility() { 7069 ListenerInfo info = getListenerInfo(); 7070 return mTouchDelegate != null || info.mOnKeyListener != null 7071 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7072 || info.mOnHoverListener != null || info.mOnDragListener != null; 7073 } 7074 7075 /** 7076 * Notifies that the accessibility state of this view changed. The change 7077 * is local to this view and does not represent structural changes such 7078 * as children and parent. For example, the view became focusable. The 7079 * notification is at at most once every 7080 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7081 * to avoid unnecessary load to the system. Also once a view has a pending 7082 * notifucation this method is a NOP until the notification has been sent. 7083 * 7084 * @hide 7085 */ 7086 public void notifyViewAccessibilityStateChangedIfNeeded() { 7087 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7088 return; 7089 } 7090 if (mSendViewStateChangedAccessibilityEvent == null) { 7091 mSendViewStateChangedAccessibilityEvent = 7092 new SendViewStateChangedAccessibilityEvent(); 7093 } 7094 mSendViewStateChangedAccessibilityEvent.runOrPost(); 7095 } 7096 7097 /** 7098 * Notifies that the accessibility state of this view changed. The change 7099 * is *not* local to this view and does represent structural changes such 7100 * as children and parent. For example, the view size changed. The 7101 * notification is at at most once every 7102 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7103 * to avoid unnecessary load to the system. Also once a view has a pending 7104 * notifucation this method is a NOP until the notification has been sent. 7105 * 7106 * @hide 7107 */ 7108 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7109 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7110 return; 7111 } 7112 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7113 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7114 if (mParent != null) { 7115 try { 7116 mParent.childAccessibilityStateChanged(this); 7117 } catch (AbstractMethodError e) { 7118 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7119 " does not fully implement ViewParent", e); 7120 } 7121 } 7122 } 7123 } 7124 7125 /** 7126 * Reset the flag indicating the accessibility state of the subtree rooted 7127 * at this view changed. 7128 */ 7129 void resetSubtreeAccessibilityStateChanged() { 7130 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7131 } 7132 7133 /** 7134 * Performs the specified accessibility action on the view. For 7135 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7136 * <p> 7137 * If an {@link AccessibilityDelegate} has been specified via calling 7138 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7139 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7140 * is responsible for handling this call. 7141 * </p> 7142 * 7143 * @param action The action to perform. 7144 * @param arguments Optional action arguments. 7145 * @return Whether the action was performed. 7146 */ 7147 public boolean performAccessibilityAction(int action, Bundle arguments) { 7148 if (mAccessibilityDelegate != null) { 7149 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7150 } else { 7151 return performAccessibilityActionInternal(action, arguments); 7152 } 7153 } 7154 7155 /** 7156 * @see #performAccessibilityAction(int, Bundle) 7157 * 7158 * Note: Called from the default {@link AccessibilityDelegate}. 7159 */ 7160 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7161 switch (action) { 7162 case AccessibilityNodeInfo.ACTION_CLICK: { 7163 if (isClickable()) { 7164 performClick(); 7165 return true; 7166 } 7167 } break; 7168 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7169 if (isLongClickable()) { 7170 performLongClick(); 7171 return true; 7172 } 7173 } break; 7174 case AccessibilityNodeInfo.ACTION_FOCUS: { 7175 if (!hasFocus()) { 7176 // Get out of touch mode since accessibility 7177 // wants to move focus around. 7178 getViewRootImpl().ensureTouchMode(false); 7179 return requestFocus(); 7180 } 7181 } break; 7182 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7183 if (hasFocus()) { 7184 clearFocus(); 7185 return !isFocused(); 7186 } 7187 } break; 7188 case AccessibilityNodeInfo.ACTION_SELECT: { 7189 if (!isSelected()) { 7190 setSelected(true); 7191 return isSelected(); 7192 } 7193 } break; 7194 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7195 if (isSelected()) { 7196 setSelected(false); 7197 return !isSelected(); 7198 } 7199 } break; 7200 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7201 if (!isAccessibilityFocused()) { 7202 return requestAccessibilityFocus(); 7203 } 7204 } break; 7205 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7206 if (isAccessibilityFocused()) { 7207 clearAccessibilityFocus(); 7208 return true; 7209 } 7210 } break; 7211 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7212 if (arguments != null) { 7213 final int granularity = arguments.getInt( 7214 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7215 final boolean extendSelection = arguments.getBoolean( 7216 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7217 return traverseAtGranularity(granularity, true, extendSelection); 7218 } 7219 } break; 7220 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7221 if (arguments != null) { 7222 final int granularity = arguments.getInt( 7223 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7224 final boolean extendSelection = arguments.getBoolean( 7225 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7226 return traverseAtGranularity(granularity, false, extendSelection); 7227 } 7228 } break; 7229 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7230 CharSequence text = getIterableTextForAccessibility(); 7231 if (text == null) { 7232 return false; 7233 } 7234 final int start = (arguments != null) ? arguments.getInt( 7235 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7236 final int end = (arguments != null) ? arguments.getInt( 7237 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7238 // Only cursor position can be specified (selection length == 0) 7239 if ((getAccessibilitySelectionStart() != start 7240 || getAccessibilitySelectionEnd() != end) 7241 && (start == end)) { 7242 setAccessibilitySelection(start, end); 7243 notifyViewAccessibilityStateChangedIfNeeded(); 7244 return true; 7245 } 7246 } break; 7247 } 7248 return false; 7249 } 7250 7251 private boolean traverseAtGranularity(int granularity, boolean forward, 7252 boolean extendSelection) { 7253 CharSequence text = getIterableTextForAccessibility(); 7254 if (text == null || text.length() == 0) { 7255 return false; 7256 } 7257 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7258 if (iterator == null) { 7259 return false; 7260 } 7261 int current = getAccessibilitySelectionEnd(); 7262 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7263 current = forward ? 0 : text.length(); 7264 } 7265 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7266 if (range == null) { 7267 return false; 7268 } 7269 final int segmentStart = range[0]; 7270 final int segmentEnd = range[1]; 7271 int selectionStart; 7272 int selectionEnd; 7273 if (extendSelection && isAccessibilitySelectionExtendable()) { 7274 selectionStart = getAccessibilitySelectionStart(); 7275 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7276 selectionStart = forward ? segmentStart : segmentEnd; 7277 } 7278 selectionEnd = forward ? segmentEnd : segmentStart; 7279 } else { 7280 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7281 } 7282 setAccessibilitySelection(selectionStart, selectionEnd); 7283 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7284 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7285 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7286 return true; 7287 } 7288 7289 /** 7290 * Gets the text reported for accessibility purposes. 7291 * 7292 * @return The accessibility text. 7293 * 7294 * @hide 7295 */ 7296 public CharSequence getIterableTextForAccessibility() { 7297 return getContentDescription(); 7298 } 7299 7300 /** 7301 * Gets whether accessibility selection can be extended. 7302 * 7303 * @return If selection is extensible. 7304 * 7305 * @hide 7306 */ 7307 public boolean isAccessibilitySelectionExtendable() { 7308 return false; 7309 } 7310 7311 /** 7312 * @hide 7313 */ 7314 public int getAccessibilitySelectionStart() { 7315 return mAccessibilityCursorPosition; 7316 } 7317 7318 /** 7319 * @hide 7320 */ 7321 public int getAccessibilitySelectionEnd() { 7322 return getAccessibilitySelectionStart(); 7323 } 7324 7325 /** 7326 * @hide 7327 */ 7328 public void setAccessibilitySelection(int start, int end) { 7329 if (start == end && end == mAccessibilityCursorPosition) { 7330 return; 7331 } 7332 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7333 mAccessibilityCursorPosition = start; 7334 } else { 7335 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7336 } 7337 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7338 } 7339 7340 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7341 int fromIndex, int toIndex) { 7342 if (mParent == null) { 7343 return; 7344 } 7345 AccessibilityEvent event = AccessibilityEvent.obtain( 7346 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7347 onInitializeAccessibilityEvent(event); 7348 onPopulateAccessibilityEvent(event); 7349 event.setFromIndex(fromIndex); 7350 event.setToIndex(toIndex); 7351 event.setAction(action); 7352 event.setMovementGranularity(granularity); 7353 mParent.requestSendAccessibilityEvent(this, event); 7354 } 7355 7356 /** 7357 * @hide 7358 */ 7359 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7360 switch (granularity) { 7361 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7362 CharSequence text = getIterableTextForAccessibility(); 7363 if (text != null && text.length() > 0) { 7364 CharacterTextSegmentIterator iterator = 7365 CharacterTextSegmentIterator.getInstance( 7366 mContext.getResources().getConfiguration().locale); 7367 iterator.initialize(text.toString()); 7368 return iterator; 7369 } 7370 } break; 7371 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7372 CharSequence text = getIterableTextForAccessibility(); 7373 if (text != null && text.length() > 0) { 7374 WordTextSegmentIterator iterator = 7375 WordTextSegmentIterator.getInstance( 7376 mContext.getResources().getConfiguration().locale); 7377 iterator.initialize(text.toString()); 7378 return iterator; 7379 } 7380 } break; 7381 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7382 CharSequence text = getIterableTextForAccessibility(); 7383 if (text != null && text.length() > 0) { 7384 ParagraphTextSegmentIterator iterator = 7385 ParagraphTextSegmentIterator.getInstance(); 7386 iterator.initialize(text.toString()); 7387 return iterator; 7388 } 7389 } break; 7390 } 7391 return null; 7392 } 7393 7394 /** 7395 * @hide 7396 */ 7397 public void dispatchStartTemporaryDetach() { 7398 clearDisplayList(); 7399 7400 onStartTemporaryDetach(); 7401 } 7402 7403 /** 7404 * This is called when a container is going to temporarily detach a child, with 7405 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7406 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7407 * {@link #onDetachedFromWindow()} when the container is done. 7408 */ 7409 public void onStartTemporaryDetach() { 7410 removeUnsetPressCallback(); 7411 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7412 } 7413 7414 /** 7415 * @hide 7416 */ 7417 public void dispatchFinishTemporaryDetach() { 7418 onFinishTemporaryDetach(); 7419 } 7420 7421 /** 7422 * Called after {@link #onStartTemporaryDetach} when the container is done 7423 * changing the view. 7424 */ 7425 public void onFinishTemporaryDetach() { 7426 } 7427 7428 /** 7429 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7430 * for this view's window. Returns null if the view is not currently attached 7431 * to the window. Normally you will not need to use this directly, but 7432 * just use the standard high-level event callbacks like 7433 * {@link #onKeyDown(int, KeyEvent)}. 7434 */ 7435 public KeyEvent.DispatcherState getKeyDispatcherState() { 7436 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7437 } 7438 7439 /** 7440 * Dispatch a key event before it is processed by any input method 7441 * associated with the view hierarchy. This can be used to intercept 7442 * key events in special situations before the IME consumes them; a 7443 * typical example would be handling the BACK key to update the application's 7444 * UI instead of allowing the IME to see it and close itself. 7445 * 7446 * @param event The key event to be dispatched. 7447 * @return True if the event was handled, false otherwise. 7448 */ 7449 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7450 return onKeyPreIme(event.getKeyCode(), event); 7451 } 7452 7453 /** 7454 * Dispatch a key event to the next view on the focus path. This path runs 7455 * from the top of the view tree down to the currently focused view. If this 7456 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7457 * the next node down the focus path. This method also fires any key 7458 * listeners. 7459 * 7460 * @param event The key event to be dispatched. 7461 * @return True if the event was handled, false otherwise. 7462 */ 7463 public boolean dispatchKeyEvent(KeyEvent event) { 7464 if (mInputEventConsistencyVerifier != null) { 7465 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7466 } 7467 7468 // Give any attached key listener a first crack at the event. 7469 //noinspection SimplifiableIfStatement 7470 ListenerInfo li = mListenerInfo; 7471 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7472 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7473 return true; 7474 } 7475 7476 if (event.dispatch(this, mAttachInfo != null 7477 ? mAttachInfo.mKeyDispatchState : null, this)) { 7478 return true; 7479 } 7480 7481 if (mInputEventConsistencyVerifier != null) { 7482 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7483 } 7484 return false; 7485 } 7486 7487 /** 7488 * Dispatches a key shortcut event. 7489 * 7490 * @param event The key event to be dispatched. 7491 * @return True if the event was handled by the view, false otherwise. 7492 */ 7493 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 7494 return onKeyShortcut(event.getKeyCode(), event); 7495 } 7496 7497 /** 7498 * Pass the touch screen motion event down to the target view, or this 7499 * view if it is the target. 7500 * 7501 * @param event The motion event to be dispatched. 7502 * @return True if the event was handled by the view, false otherwise. 7503 */ 7504 public boolean dispatchTouchEvent(MotionEvent event) { 7505 if (mInputEventConsistencyVerifier != null) { 7506 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 7507 } 7508 7509 if (onFilterTouchEventForSecurity(event)) { 7510 //noinspection SimplifiableIfStatement 7511 ListenerInfo li = mListenerInfo; 7512 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7513 && li.mOnTouchListener.onTouch(this, event)) { 7514 return true; 7515 } 7516 7517 if (onTouchEvent(event)) { 7518 return true; 7519 } 7520 } 7521 7522 if (mInputEventConsistencyVerifier != null) { 7523 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7524 } 7525 return false; 7526 } 7527 7528 /** 7529 * Filter the touch event to apply security policies. 7530 * 7531 * @param event The motion event to be filtered. 7532 * @return True if the event should be dispatched, false if the event should be dropped. 7533 * 7534 * @see #getFilterTouchesWhenObscured 7535 */ 7536 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 7537 //noinspection RedundantIfStatement 7538 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 7539 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 7540 // Window is obscured, drop this touch. 7541 return false; 7542 } 7543 return true; 7544 } 7545 7546 /** 7547 * Pass a trackball motion event down to the focused view. 7548 * 7549 * @param event The motion event to be dispatched. 7550 * @return True if the event was handled by the view, false otherwise. 7551 */ 7552 public boolean dispatchTrackballEvent(MotionEvent event) { 7553 if (mInputEventConsistencyVerifier != null) { 7554 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 7555 } 7556 7557 return onTrackballEvent(event); 7558 } 7559 7560 /** 7561 * Dispatch a generic motion event. 7562 * <p> 7563 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7564 * are delivered to the view under the pointer. All other generic motion events are 7565 * delivered to the focused view. Hover events are handled specially and are delivered 7566 * to {@link #onHoverEvent(MotionEvent)}. 7567 * </p> 7568 * 7569 * @param event The motion event to be dispatched. 7570 * @return True if the event was handled by the view, false otherwise. 7571 */ 7572 public boolean dispatchGenericMotionEvent(MotionEvent event) { 7573 if (mInputEventConsistencyVerifier != null) { 7574 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 7575 } 7576 7577 final int source = event.getSource(); 7578 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7579 final int action = event.getAction(); 7580 if (action == MotionEvent.ACTION_HOVER_ENTER 7581 || action == MotionEvent.ACTION_HOVER_MOVE 7582 || action == MotionEvent.ACTION_HOVER_EXIT) { 7583 if (dispatchHoverEvent(event)) { 7584 return true; 7585 } 7586 } else if (dispatchGenericPointerEvent(event)) { 7587 return true; 7588 } 7589 } else if (dispatchGenericFocusedEvent(event)) { 7590 return true; 7591 } 7592 7593 if (dispatchGenericMotionEventInternal(event)) { 7594 return true; 7595 } 7596 7597 if (mInputEventConsistencyVerifier != null) { 7598 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7599 } 7600 return false; 7601 } 7602 7603 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 7604 //noinspection SimplifiableIfStatement 7605 ListenerInfo li = mListenerInfo; 7606 if (li != null && li.mOnGenericMotionListener != null 7607 && (mViewFlags & ENABLED_MASK) == ENABLED 7608 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 7609 return true; 7610 } 7611 7612 if (onGenericMotionEvent(event)) { 7613 return true; 7614 } 7615 7616 if (mInputEventConsistencyVerifier != null) { 7617 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7618 } 7619 return false; 7620 } 7621 7622 /** 7623 * Dispatch a hover event. 7624 * <p> 7625 * Do not call this method directly. 7626 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7627 * </p> 7628 * 7629 * @param event The motion event to be dispatched. 7630 * @return True if the event was handled by the view, false otherwise. 7631 */ 7632 protected boolean dispatchHoverEvent(MotionEvent event) { 7633 ListenerInfo li = mListenerInfo; 7634 //noinspection SimplifiableIfStatement 7635 if (li != null && li.mOnHoverListener != null 7636 && (mViewFlags & ENABLED_MASK) == ENABLED 7637 && li.mOnHoverListener.onHover(this, event)) { 7638 return true; 7639 } 7640 7641 return onHoverEvent(event); 7642 } 7643 7644 /** 7645 * Returns true if the view has a child to which it has recently sent 7646 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 7647 * it does not have a hovered child, then it must be the innermost hovered view. 7648 * @hide 7649 */ 7650 protected boolean hasHoveredChild() { 7651 return false; 7652 } 7653 7654 /** 7655 * Dispatch a generic motion event to the view under the first pointer. 7656 * <p> 7657 * Do not call this method directly. 7658 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7659 * </p> 7660 * 7661 * @param event The motion event to be dispatched. 7662 * @return True if the event was handled by the view, false otherwise. 7663 */ 7664 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 7665 return false; 7666 } 7667 7668 /** 7669 * Dispatch a generic motion event to the currently focused view. 7670 * <p> 7671 * Do not call this method directly. 7672 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7673 * </p> 7674 * 7675 * @param event The motion event to be dispatched. 7676 * @return True if the event was handled by the view, false otherwise. 7677 */ 7678 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 7679 return false; 7680 } 7681 7682 /** 7683 * Dispatch a pointer event. 7684 * <p> 7685 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 7686 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 7687 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 7688 * and should not be expected to handle other pointing device features. 7689 * </p> 7690 * 7691 * @param event The motion event to be dispatched. 7692 * @return True if the event was handled by the view, false otherwise. 7693 * @hide 7694 */ 7695 public final boolean dispatchPointerEvent(MotionEvent event) { 7696 if (event.isTouchEvent()) { 7697 return dispatchTouchEvent(event); 7698 } else { 7699 return dispatchGenericMotionEvent(event); 7700 } 7701 } 7702 7703 /** 7704 * Called when the window containing this view gains or loses window focus. 7705 * ViewGroups should override to route to their children. 7706 * 7707 * @param hasFocus True if the window containing this view now has focus, 7708 * false otherwise. 7709 */ 7710 public void dispatchWindowFocusChanged(boolean hasFocus) { 7711 onWindowFocusChanged(hasFocus); 7712 } 7713 7714 /** 7715 * Called when the window containing this view gains or loses focus. Note 7716 * that this is separate from view focus: to receive key events, both 7717 * your view and its window must have focus. If a window is displayed 7718 * on top of yours that takes input focus, then your own window will lose 7719 * focus but the view focus will remain unchanged. 7720 * 7721 * @param hasWindowFocus True if the window containing this view now has 7722 * focus, false otherwise. 7723 */ 7724 public void onWindowFocusChanged(boolean hasWindowFocus) { 7725 InputMethodManager imm = InputMethodManager.peekInstance(); 7726 if (!hasWindowFocus) { 7727 if (isPressed()) { 7728 setPressed(false); 7729 } 7730 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7731 imm.focusOut(this); 7732 } 7733 removeLongPressCallback(); 7734 removeTapCallback(); 7735 onFocusLost(); 7736 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7737 imm.focusIn(this); 7738 } 7739 refreshDrawableState(); 7740 } 7741 7742 /** 7743 * Returns true if this view is in a window that currently has window focus. 7744 * Note that this is not the same as the view itself having focus. 7745 * 7746 * @return True if this view is in a window that currently has window focus. 7747 */ 7748 public boolean hasWindowFocus() { 7749 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 7750 } 7751 7752 /** 7753 * Dispatch a view visibility change down the view hierarchy. 7754 * ViewGroups should override to route to their children. 7755 * @param changedView The view whose visibility changed. Could be 'this' or 7756 * an ancestor view. 7757 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7758 * {@link #INVISIBLE} or {@link #GONE}. 7759 */ 7760 protected void dispatchVisibilityChanged(View changedView, int visibility) { 7761 onVisibilityChanged(changedView, visibility); 7762 } 7763 7764 /** 7765 * Called when the visibility of the view or an ancestor of the view is changed. 7766 * @param changedView The view whose visibility changed. Could be 'this' or 7767 * an ancestor view. 7768 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7769 * {@link #INVISIBLE} or {@link #GONE}. 7770 */ 7771 protected void onVisibilityChanged(View changedView, int visibility) { 7772 if (visibility == VISIBLE) { 7773 if (mAttachInfo != null) { 7774 initialAwakenScrollBars(); 7775 } else { 7776 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 7777 } 7778 } 7779 } 7780 7781 /** 7782 * Dispatch a hint about whether this view is displayed. For instance, when 7783 * a View moves out of the screen, it might receives a display hint indicating 7784 * the view is not displayed. Applications should not <em>rely</em> on this hint 7785 * as there is no guarantee that they will receive one. 7786 * 7787 * @param hint A hint about whether or not this view is displayed: 7788 * {@link #VISIBLE} or {@link #INVISIBLE}. 7789 */ 7790 public void dispatchDisplayHint(int hint) { 7791 onDisplayHint(hint); 7792 } 7793 7794 /** 7795 * Gives this view a hint about whether is displayed or not. For instance, when 7796 * a View moves out of the screen, it might receives a display hint indicating 7797 * the view is not displayed. Applications should not <em>rely</em> on this hint 7798 * as there is no guarantee that they will receive one. 7799 * 7800 * @param hint A hint about whether or not this view is displayed: 7801 * {@link #VISIBLE} or {@link #INVISIBLE}. 7802 */ 7803 protected void onDisplayHint(int hint) { 7804 } 7805 7806 /** 7807 * Dispatch a window visibility change down the view hierarchy. 7808 * ViewGroups should override to route to their children. 7809 * 7810 * @param visibility The new visibility of the window. 7811 * 7812 * @see #onWindowVisibilityChanged(int) 7813 */ 7814 public void dispatchWindowVisibilityChanged(int visibility) { 7815 onWindowVisibilityChanged(visibility); 7816 } 7817 7818 /** 7819 * Called when the window containing has change its visibility 7820 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 7821 * that this tells you whether or not your window is being made visible 7822 * to the window manager; this does <em>not</em> tell you whether or not 7823 * your window is obscured by other windows on the screen, even if it 7824 * is itself visible. 7825 * 7826 * @param visibility The new visibility of the window. 7827 */ 7828 protected void onWindowVisibilityChanged(int visibility) { 7829 if (visibility == VISIBLE) { 7830 initialAwakenScrollBars(); 7831 } 7832 } 7833 7834 /** 7835 * Returns the current visibility of the window this view is attached to 7836 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 7837 * 7838 * @return Returns the current visibility of the view's window. 7839 */ 7840 public int getWindowVisibility() { 7841 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 7842 } 7843 7844 /** 7845 * Retrieve the overall visible display size in which the window this view is 7846 * attached to has been positioned in. This takes into account screen 7847 * decorations above the window, for both cases where the window itself 7848 * is being position inside of them or the window is being placed under 7849 * then and covered insets are used for the window to position its content 7850 * inside. In effect, this tells you the available area where content can 7851 * be placed and remain visible to users. 7852 * 7853 * <p>This function requires an IPC back to the window manager to retrieve 7854 * the requested information, so should not be used in performance critical 7855 * code like drawing. 7856 * 7857 * @param outRect Filled in with the visible display frame. If the view 7858 * is not attached to a window, this is simply the raw display size. 7859 */ 7860 public void getWindowVisibleDisplayFrame(Rect outRect) { 7861 if (mAttachInfo != null) { 7862 try { 7863 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 7864 } catch (RemoteException e) { 7865 return; 7866 } 7867 // XXX This is really broken, and probably all needs to be done 7868 // in the window manager, and we need to know more about whether 7869 // we want the area behind or in front of the IME. 7870 final Rect insets = mAttachInfo.mVisibleInsets; 7871 outRect.left += insets.left; 7872 outRect.top += insets.top; 7873 outRect.right -= insets.right; 7874 outRect.bottom -= insets.bottom; 7875 return; 7876 } 7877 // The view is not attached to a display so we don't have a context. 7878 // Make a best guess about the display size. 7879 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 7880 d.getRectSize(outRect); 7881 } 7882 7883 /** 7884 * Dispatch a notification about a resource configuration change down 7885 * the view hierarchy. 7886 * ViewGroups should override to route to their children. 7887 * 7888 * @param newConfig The new resource configuration. 7889 * 7890 * @see #onConfigurationChanged(android.content.res.Configuration) 7891 */ 7892 public void dispatchConfigurationChanged(Configuration newConfig) { 7893 onConfigurationChanged(newConfig); 7894 } 7895 7896 /** 7897 * Called when the current configuration of the resources being used 7898 * by the application have changed. You can use this to decide when 7899 * to reload resources that can changed based on orientation and other 7900 * configuration characterstics. You only need to use this if you are 7901 * not relying on the normal {@link android.app.Activity} mechanism of 7902 * recreating the activity instance upon a configuration change. 7903 * 7904 * @param newConfig The new resource configuration. 7905 */ 7906 protected void onConfigurationChanged(Configuration newConfig) { 7907 } 7908 7909 /** 7910 * Private function to aggregate all per-view attributes in to the view 7911 * root. 7912 */ 7913 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7914 performCollectViewAttributes(attachInfo, visibility); 7915 } 7916 7917 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7918 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 7919 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 7920 attachInfo.mKeepScreenOn = true; 7921 } 7922 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 7923 ListenerInfo li = mListenerInfo; 7924 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 7925 attachInfo.mHasSystemUiListeners = true; 7926 } 7927 } 7928 } 7929 7930 void needGlobalAttributesUpdate(boolean force) { 7931 final AttachInfo ai = mAttachInfo; 7932 if (ai != null && !ai.mRecomputeGlobalAttributes) { 7933 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 7934 || ai.mHasSystemUiListeners) { 7935 ai.mRecomputeGlobalAttributes = true; 7936 } 7937 } 7938 } 7939 7940 /** 7941 * Returns whether the device is currently in touch mode. Touch mode is entered 7942 * once the user begins interacting with the device by touch, and affects various 7943 * things like whether focus is always visible to the user. 7944 * 7945 * @return Whether the device is in touch mode. 7946 */ 7947 @ViewDebug.ExportedProperty 7948 public boolean isInTouchMode() { 7949 if (mAttachInfo != null) { 7950 return mAttachInfo.mInTouchMode; 7951 } else { 7952 return ViewRootImpl.isInTouchMode(); 7953 } 7954 } 7955 7956 /** 7957 * Returns the context the view is running in, through which it can 7958 * access the current theme, resources, etc. 7959 * 7960 * @return The view's Context. 7961 */ 7962 @ViewDebug.CapturedViewProperty 7963 public final Context getContext() { 7964 return mContext; 7965 } 7966 7967 /** 7968 * Handle a key event before it is processed by any input method 7969 * associated with the view hierarchy. This can be used to intercept 7970 * key events in special situations before the IME consumes them; a 7971 * typical example would be handling the BACK key to update the application's 7972 * UI instead of allowing the IME to see it and close itself. 7973 * 7974 * @param keyCode The value in event.getKeyCode(). 7975 * @param event Description of the key event. 7976 * @return If you handled the event, return true. If you want to allow the 7977 * event to be handled by the next receiver, return false. 7978 */ 7979 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 7980 return false; 7981 } 7982 7983 /** 7984 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 7985 * KeyEvent.Callback.onKeyDown()}: perform press of the view 7986 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 7987 * is released, if the view is enabled and clickable. 7988 * 7989 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7990 * although some may elect to do so in some situations. Do not rely on this to 7991 * catch software key presses. 7992 * 7993 * @param keyCode A key code that represents the button pressed, from 7994 * {@link android.view.KeyEvent}. 7995 * @param event The KeyEvent object that defines the button action. 7996 */ 7997 public boolean onKeyDown(int keyCode, KeyEvent event) { 7998 boolean result = false; 7999 8000 if (KeyEvent.isConfirmKey(event.getKeyCode())) { 8001 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8002 return true; 8003 } 8004 // Long clickable items don't necessarily have to be clickable 8005 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8006 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8007 (event.getRepeatCount() == 0)) { 8008 setPressed(true); 8009 checkForLongClick(0); 8010 return true; 8011 } 8012 } 8013 return result; 8014 } 8015 8016 /** 8017 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8018 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8019 * the event). 8020 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8021 * although some may elect to do so in some situations. Do not rely on this to 8022 * catch software key presses. 8023 */ 8024 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8025 return false; 8026 } 8027 8028 /** 8029 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8030 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8031 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8032 * {@link KeyEvent#KEYCODE_ENTER} is released. 8033 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8034 * although some may elect to do so in some situations. Do not rely on this to 8035 * catch software key presses. 8036 * 8037 * @param keyCode A key code that represents the button pressed, from 8038 * {@link android.view.KeyEvent}. 8039 * @param event The KeyEvent object that defines the button action. 8040 */ 8041 public boolean onKeyUp(int keyCode, KeyEvent event) { 8042 boolean result = false; 8043 8044 switch (keyCode) { 8045 case KeyEvent.KEYCODE_DPAD_CENTER: 8046 case KeyEvent.KEYCODE_ENTER: { 8047 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8048 return true; 8049 } 8050 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8051 setPressed(false); 8052 8053 if (!mHasPerformedLongPress) { 8054 // This is a tap, so remove the longpress check 8055 removeLongPressCallback(); 8056 8057 result = performClick(); 8058 } 8059 } 8060 break; 8061 } 8062 } 8063 return result; 8064 } 8065 8066 /** 8067 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8068 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8069 * the event). 8070 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8071 * although some may elect to do so in some situations. Do not rely on this to 8072 * catch software key presses. 8073 * 8074 * @param keyCode A key code that represents the button pressed, from 8075 * {@link android.view.KeyEvent}. 8076 * @param repeatCount The number of times the action was made. 8077 * @param event The KeyEvent object that defines the button action. 8078 */ 8079 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8080 return false; 8081 } 8082 8083 /** 8084 * Called on the focused view when a key shortcut event is not handled. 8085 * Override this method to implement local key shortcuts for the View. 8086 * Key shortcuts can also be implemented by setting the 8087 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8088 * 8089 * @param keyCode The value in event.getKeyCode(). 8090 * @param event Description of the key event. 8091 * @return If you handled the event, return true. If you want to allow the 8092 * event to be handled by the next receiver, return false. 8093 */ 8094 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8095 return false; 8096 } 8097 8098 /** 8099 * Check whether the called view is a text editor, in which case it 8100 * would make sense to automatically display a soft input window for 8101 * it. Subclasses should override this if they implement 8102 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8103 * a call on that method would return a non-null InputConnection, and 8104 * they are really a first-class editor that the user would normally 8105 * start typing on when the go into a window containing your view. 8106 * 8107 * <p>The default implementation always returns false. This does 8108 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8109 * will not be called or the user can not otherwise perform edits on your 8110 * view; it is just a hint to the system that this is not the primary 8111 * purpose of this view. 8112 * 8113 * @return Returns true if this view is a text editor, else false. 8114 */ 8115 public boolean onCheckIsTextEditor() { 8116 return false; 8117 } 8118 8119 /** 8120 * Create a new InputConnection for an InputMethod to interact 8121 * with the view. The default implementation returns null, since it doesn't 8122 * support input methods. You can override this to implement such support. 8123 * This is only needed for views that take focus and text input. 8124 * 8125 * <p>When implementing this, you probably also want to implement 8126 * {@link #onCheckIsTextEditor()} to indicate you will return a 8127 * non-null InputConnection. 8128 * 8129 * @param outAttrs Fill in with attribute information about the connection. 8130 */ 8131 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8132 return null; 8133 } 8134 8135 /** 8136 * Called by the {@link android.view.inputmethod.InputMethodManager} 8137 * when a view who is not the current 8138 * input connection target is trying to make a call on the manager. The 8139 * default implementation returns false; you can override this to return 8140 * true for certain views if you are performing InputConnection proxying 8141 * to them. 8142 * @param view The View that is making the InputMethodManager call. 8143 * @return Return true to allow the call, false to reject. 8144 */ 8145 public boolean checkInputConnectionProxy(View view) { 8146 return false; 8147 } 8148 8149 /** 8150 * Show the context menu for this view. It is not safe to hold on to the 8151 * menu after returning from this method. 8152 * 8153 * You should normally not overload this method. Overload 8154 * {@link #onCreateContextMenu(ContextMenu)} or define an 8155 * {@link OnCreateContextMenuListener} to add items to the context menu. 8156 * 8157 * @param menu The context menu to populate 8158 */ 8159 public void createContextMenu(ContextMenu menu) { 8160 ContextMenuInfo menuInfo = getContextMenuInfo(); 8161 8162 // Sets the current menu info so all items added to menu will have 8163 // my extra info set. 8164 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8165 8166 onCreateContextMenu(menu); 8167 ListenerInfo li = mListenerInfo; 8168 if (li != null && li.mOnCreateContextMenuListener != null) { 8169 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8170 } 8171 8172 // Clear the extra information so subsequent items that aren't mine don't 8173 // have my extra info. 8174 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8175 8176 if (mParent != null) { 8177 mParent.createContextMenu(menu); 8178 } 8179 } 8180 8181 /** 8182 * Views should implement this if they have extra information to associate 8183 * with the context menu. The return result is supplied as a parameter to 8184 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8185 * callback. 8186 * 8187 * @return Extra information about the item for which the context menu 8188 * should be shown. This information will vary across different 8189 * subclasses of View. 8190 */ 8191 protected ContextMenuInfo getContextMenuInfo() { 8192 return null; 8193 } 8194 8195 /** 8196 * Views should implement this if the view itself is going to add items to 8197 * the context menu. 8198 * 8199 * @param menu the context menu to populate 8200 */ 8201 protected void onCreateContextMenu(ContextMenu menu) { 8202 } 8203 8204 /** 8205 * Implement this method to handle trackball motion events. The 8206 * <em>relative</em> movement of the trackball since the last event 8207 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8208 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8209 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8210 * they will often be fractional values, representing the more fine-grained 8211 * movement information available from a trackball). 8212 * 8213 * @param event The motion event. 8214 * @return True if the event was handled, false otherwise. 8215 */ 8216 public boolean onTrackballEvent(MotionEvent event) { 8217 return false; 8218 } 8219 8220 /** 8221 * Implement this method to handle generic motion events. 8222 * <p> 8223 * Generic motion events describe joystick movements, mouse hovers, track pad 8224 * touches, scroll wheel movements and other input events. The 8225 * {@link MotionEvent#getSource() source} of the motion event specifies 8226 * the class of input that was received. Implementations of this method 8227 * must examine the bits in the source before processing the event. 8228 * The following code example shows how this is done. 8229 * </p><p> 8230 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8231 * are delivered to the view under the pointer. All other generic motion events are 8232 * delivered to the focused view. 8233 * </p> 8234 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8235 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8236 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8237 * // process the joystick movement... 8238 * return true; 8239 * } 8240 * } 8241 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8242 * switch (event.getAction()) { 8243 * case MotionEvent.ACTION_HOVER_MOVE: 8244 * // process the mouse hover movement... 8245 * return true; 8246 * case MotionEvent.ACTION_SCROLL: 8247 * // process the scroll wheel movement... 8248 * return true; 8249 * } 8250 * } 8251 * return super.onGenericMotionEvent(event); 8252 * }</pre> 8253 * 8254 * @param event The generic motion event being processed. 8255 * @return True if the event was handled, false otherwise. 8256 */ 8257 public boolean onGenericMotionEvent(MotionEvent event) { 8258 return false; 8259 } 8260 8261 /** 8262 * Implement this method to handle hover events. 8263 * <p> 8264 * This method is called whenever a pointer is hovering into, over, or out of the 8265 * bounds of a view and the view is not currently being touched. 8266 * Hover events are represented as pointer events with action 8267 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8268 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8269 * </p> 8270 * <ul> 8271 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8272 * when the pointer enters the bounds of the view.</li> 8273 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8274 * when the pointer has already entered the bounds of the view and has moved.</li> 8275 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8276 * when the pointer has exited the bounds of the view or when the pointer is 8277 * about to go down due to a button click, tap, or similar user action that 8278 * causes the view to be touched.</li> 8279 * </ul> 8280 * <p> 8281 * The view should implement this method to return true to indicate that it is 8282 * handling the hover event, such as by changing its drawable state. 8283 * </p><p> 8284 * The default implementation calls {@link #setHovered} to update the hovered state 8285 * of the view when a hover enter or hover exit event is received, if the view 8286 * is enabled and is clickable. The default implementation also sends hover 8287 * accessibility events. 8288 * </p> 8289 * 8290 * @param event The motion event that describes the hover. 8291 * @return True if the view handled the hover event. 8292 * 8293 * @see #isHovered 8294 * @see #setHovered 8295 * @see #onHoverChanged 8296 */ 8297 public boolean onHoverEvent(MotionEvent event) { 8298 // The root view may receive hover (or touch) events that are outside the bounds of 8299 // the window. This code ensures that we only send accessibility events for 8300 // hovers that are actually within the bounds of the root view. 8301 final int action = event.getActionMasked(); 8302 if (!mSendingHoverAccessibilityEvents) { 8303 if ((action == MotionEvent.ACTION_HOVER_ENTER 8304 || action == MotionEvent.ACTION_HOVER_MOVE) 8305 && !hasHoveredChild() 8306 && pointInView(event.getX(), event.getY())) { 8307 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8308 mSendingHoverAccessibilityEvents = true; 8309 } 8310 } else { 8311 if (action == MotionEvent.ACTION_HOVER_EXIT 8312 || (action == MotionEvent.ACTION_MOVE 8313 && !pointInView(event.getX(), event.getY()))) { 8314 mSendingHoverAccessibilityEvents = false; 8315 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8316 // If the window does not have input focus we take away accessibility 8317 // focus as soon as the user stop hovering over the view. 8318 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 8319 getViewRootImpl().setAccessibilityFocus(null, null); 8320 } 8321 } 8322 } 8323 8324 if (isHoverable()) { 8325 switch (action) { 8326 case MotionEvent.ACTION_HOVER_ENTER: 8327 setHovered(true); 8328 break; 8329 case MotionEvent.ACTION_HOVER_EXIT: 8330 setHovered(false); 8331 break; 8332 } 8333 8334 // Dispatch the event to onGenericMotionEvent before returning true. 8335 // This is to provide compatibility with existing applications that 8336 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8337 // break because of the new default handling for hoverable views 8338 // in onHoverEvent. 8339 // Note that onGenericMotionEvent will be called by default when 8340 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8341 dispatchGenericMotionEventInternal(event); 8342 // The event was already handled by calling setHovered(), so always 8343 // return true. 8344 return true; 8345 } 8346 8347 return false; 8348 } 8349 8350 /** 8351 * Returns true if the view should handle {@link #onHoverEvent} 8352 * by calling {@link #setHovered} to change its hovered state. 8353 * 8354 * @return True if the view is hoverable. 8355 */ 8356 private boolean isHoverable() { 8357 final int viewFlags = mViewFlags; 8358 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8359 return false; 8360 } 8361 8362 return (viewFlags & CLICKABLE) == CLICKABLE 8363 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8364 } 8365 8366 /** 8367 * Returns true if the view is currently hovered. 8368 * 8369 * @return True if the view is currently hovered. 8370 * 8371 * @see #setHovered 8372 * @see #onHoverChanged 8373 */ 8374 @ViewDebug.ExportedProperty 8375 public boolean isHovered() { 8376 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8377 } 8378 8379 /** 8380 * Sets whether the view is currently hovered. 8381 * <p> 8382 * Calling this method also changes the drawable state of the view. This 8383 * enables the view to react to hover by using different drawable resources 8384 * to change its appearance. 8385 * </p><p> 8386 * The {@link #onHoverChanged} method is called when the hovered state changes. 8387 * </p> 8388 * 8389 * @param hovered True if the view is hovered. 8390 * 8391 * @see #isHovered 8392 * @see #onHoverChanged 8393 */ 8394 public void setHovered(boolean hovered) { 8395 if (hovered) { 8396 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8397 mPrivateFlags |= PFLAG_HOVERED; 8398 refreshDrawableState(); 8399 onHoverChanged(true); 8400 } 8401 } else { 8402 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8403 mPrivateFlags &= ~PFLAG_HOVERED; 8404 refreshDrawableState(); 8405 onHoverChanged(false); 8406 } 8407 } 8408 } 8409 8410 /** 8411 * Implement this method to handle hover state changes. 8412 * <p> 8413 * This method is called whenever the hover state changes as a result of a 8414 * call to {@link #setHovered}. 8415 * </p> 8416 * 8417 * @param hovered The current hover state, as returned by {@link #isHovered}. 8418 * 8419 * @see #isHovered 8420 * @see #setHovered 8421 */ 8422 public void onHoverChanged(boolean hovered) { 8423 } 8424 8425 /** 8426 * Implement this method to handle touch screen motion events. 8427 * <p> 8428 * If this method is used to detect click actions, it is recommended that 8429 * the actions be performed by implementing and calling 8430 * {@link #performClick()}. This will ensure consistent system behavior, 8431 * including: 8432 * <ul> 8433 * <li>obeying click sound preferences 8434 * <li>dispatching OnClickListener calls 8435 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 8436 * accessibility features are enabled 8437 * </ul> 8438 * 8439 * @param event The motion event. 8440 * @return True if the event was handled, false otherwise. 8441 */ 8442 public boolean onTouchEvent(MotionEvent event) { 8443 final int viewFlags = mViewFlags; 8444 8445 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8446 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8447 setPressed(false); 8448 } 8449 // A disabled view that is clickable still consumes the touch 8450 // events, it just doesn't respond to them. 8451 return (((viewFlags & CLICKABLE) == CLICKABLE || 8452 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8453 } 8454 8455 if (mTouchDelegate != null) { 8456 if (mTouchDelegate.onTouchEvent(event)) { 8457 return true; 8458 } 8459 } 8460 8461 if (((viewFlags & CLICKABLE) == CLICKABLE || 8462 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8463 switch (event.getAction()) { 8464 case MotionEvent.ACTION_UP: 8465 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8466 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8467 // take focus if we don't have it already and we should in 8468 // touch mode. 8469 boolean focusTaken = false; 8470 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8471 focusTaken = requestFocus(); 8472 } 8473 8474 if (prepressed) { 8475 // The button is being released before we actually 8476 // showed it as pressed. Make it show the pressed 8477 // state now (before scheduling the click) to ensure 8478 // the user sees it. 8479 setPressed(true); 8480 } 8481 8482 if (!mHasPerformedLongPress) { 8483 // This is a tap, so remove the longpress check 8484 removeLongPressCallback(); 8485 8486 // Only perform take click actions if we were in the pressed state 8487 if (!focusTaken) { 8488 // Use a Runnable and post this rather than calling 8489 // performClick directly. This lets other visual state 8490 // of the view update before click actions start. 8491 if (mPerformClick == null) { 8492 mPerformClick = new PerformClick(); 8493 } 8494 if (!post(mPerformClick)) { 8495 performClick(); 8496 } 8497 } 8498 } 8499 8500 if (mUnsetPressedState == null) { 8501 mUnsetPressedState = new UnsetPressedState(); 8502 } 8503 8504 if (prepressed) { 8505 postDelayed(mUnsetPressedState, 8506 ViewConfiguration.getPressedStateDuration()); 8507 } else if (!post(mUnsetPressedState)) { 8508 // If the post failed, unpress right now 8509 mUnsetPressedState.run(); 8510 } 8511 removeTapCallback(); 8512 } 8513 break; 8514 8515 case MotionEvent.ACTION_DOWN: 8516 mHasPerformedLongPress = false; 8517 8518 if (performButtonActionOnTouchDown(event)) { 8519 break; 8520 } 8521 8522 // Walk up the hierarchy to determine if we're inside a scrolling container. 8523 boolean isInScrollingContainer = isInScrollingContainer(); 8524 8525 // For views inside a scrolling container, delay the pressed feedback for 8526 // a short period in case this is a scroll. 8527 if (isInScrollingContainer) { 8528 mPrivateFlags |= PFLAG_PREPRESSED; 8529 if (mPendingCheckForTap == null) { 8530 mPendingCheckForTap = new CheckForTap(); 8531 } 8532 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 8533 } else { 8534 // Not inside a scrolling container, so show the feedback right away 8535 setPressed(true); 8536 checkForLongClick(0); 8537 } 8538 break; 8539 8540 case MotionEvent.ACTION_CANCEL: 8541 setPressed(false); 8542 removeTapCallback(); 8543 removeLongPressCallback(); 8544 break; 8545 8546 case MotionEvent.ACTION_MOVE: 8547 final int x = (int) event.getX(); 8548 final int y = (int) event.getY(); 8549 8550 // Be lenient about moving outside of buttons 8551 if (!pointInView(x, y, mTouchSlop)) { 8552 // Outside button 8553 removeTapCallback(); 8554 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 8555 // Remove any future long press/tap checks 8556 removeLongPressCallback(); 8557 8558 setPressed(false); 8559 } 8560 } 8561 break; 8562 } 8563 return true; 8564 } 8565 8566 return false; 8567 } 8568 8569 /** 8570 * @hide 8571 */ 8572 public boolean isInScrollingContainer() { 8573 ViewParent p = getParent(); 8574 while (p != null && p instanceof ViewGroup) { 8575 if (((ViewGroup) p).shouldDelayChildPressedState()) { 8576 return true; 8577 } 8578 p = p.getParent(); 8579 } 8580 return false; 8581 } 8582 8583 /** 8584 * Remove the longpress detection timer. 8585 */ 8586 private void removeLongPressCallback() { 8587 if (mPendingCheckForLongPress != null) { 8588 removeCallbacks(mPendingCheckForLongPress); 8589 } 8590 } 8591 8592 /** 8593 * Remove the pending click action 8594 */ 8595 private void removePerformClickCallback() { 8596 if (mPerformClick != null) { 8597 removeCallbacks(mPerformClick); 8598 } 8599 } 8600 8601 /** 8602 * Remove the prepress detection timer. 8603 */ 8604 private void removeUnsetPressCallback() { 8605 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 8606 setPressed(false); 8607 removeCallbacks(mUnsetPressedState); 8608 } 8609 } 8610 8611 /** 8612 * Remove the tap detection timer. 8613 */ 8614 private void removeTapCallback() { 8615 if (mPendingCheckForTap != null) { 8616 mPrivateFlags &= ~PFLAG_PREPRESSED; 8617 removeCallbacks(mPendingCheckForTap); 8618 } 8619 } 8620 8621 /** 8622 * Cancels a pending long press. Your subclass can use this if you 8623 * want the context menu to come up if the user presses and holds 8624 * at the same place, but you don't want it to come up if they press 8625 * and then move around enough to cause scrolling. 8626 */ 8627 public void cancelLongPress() { 8628 removeLongPressCallback(); 8629 8630 /* 8631 * The prepressed state handled by the tap callback is a display 8632 * construct, but the tap callback will post a long press callback 8633 * less its own timeout. Remove it here. 8634 */ 8635 removeTapCallback(); 8636 } 8637 8638 /** 8639 * Remove the pending callback for sending a 8640 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 8641 */ 8642 private void removeSendViewScrolledAccessibilityEventCallback() { 8643 if (mSendViewScrolledAccessibilityEvent != null) { 8644 removeCallbacks(mSendViewScrolledAccessibilityEvent); 8645 mSendViewScrolledAccessibilityEvent.mIsPending = false; 8646 } 8647 } 8648 8649 /** 8650 * Sets the TouchDelegate for this View. 8651 */ 8652 public void setTouchDelegate(TouchDelegate delegate) { 8653 mTouchDelegate = delegate; 8654 } 8655 8656 /** 8657 * Gets the TouchDelegate for this View. 8658 */ 8659 public TouchDelegate getTouchDelegate() { 8660 return mTouchDelegate; 8661 } 8662 8663 /** 8664 * Set flags controlling behavior of this view. 8665 * 8666 * @param flags Constant indicating the value which should be set 8667 * @param mask Constant indicating the bit range that should be changed 8668 */ 8669 void setFlags(int flags, int mask) { 8670 final boolean accessibilityEnabled = 8671 AccessibilityManager.getInstance(mContext).isEnabled(); 8672 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 8673 8674 int old = mViewFlags; 8675 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 8676 8677 int changed = mViewFlags ^ old; 8678 if (changed == 0) { 8679 return; 8680 } 8681 int privateFlags = mPrivateFlags; 8682 8683 /* Check if the FOCUSABLE bit has changed */ 8684 if (((changed & FOCUSABLE_MASK) != 0) && 8685 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 8686 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 8687 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 8688 /* Give up focus if we are no longer focusable */ 8689 clearFocus(); 8690 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 8691 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 8692 /* 8693 * Tell the view system that we are now available to take focus 8694 * if no one else already has it. 8695 */ 8696 if (mParent != null) mParent.focusableViewAvailable(this); 8697 } 8698 } 8699 8700 final int newVisibility = flags & VISIBILITY_MASK; 8701 if (newVisibility == VISIBLE) { 8702 if ((changed & VISIBILITY_MASK) != 0) { 8703 /* 8704 * If this view is becoming visible, invalidate it in case it changed while 8705 * it was not visible. Marking it drawn ensures that the invalidation will 8706 * go through. 8707 */ 8708 mPrivateFlags |= PFLAG_DRAWN; 8709 invalidate(true); 8710 8711 needGlobalAttributesUpdate(true); 8712 8713 // a view becoming visible is worth notifying the parent 8714 // about in case nothing has focus. even if this specific view 8715 // isn't focusable, it may contain something that is, so let 8716 // the root view try to give this focus if nothing else does. 8717 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 8718 mParent.focusableViewAvailable(this); 8719 } 8720 } 8721 } 8722 8723 /* Check if the GONE bit has changed */ 8724 if ((changed & GONE) != 0) { 8725 needGlobalAttributesUpdate(false); 8726 requestLayout(); 8727 8728 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 8729 if (hasFocus()) clearFocus(); 8730 clearAccessibilityFocus(); 8731 destroyDrawingCache(); 8732 if (mParent instanceof View) { 8733 // GONE views noop invalidation, so invalidate the parent 8734 ((View) mParent).invalidate(true); 8735 } 8736 // Mark the view drawn to ensure that it gets invalidated properly the next 8737 // time it is visible and gets invalidated 8738 mPrivateFlags |= PFLAG_DRAWN; 8739 } 8740 if (mAttachInfo != null) { 8741 mAttachInfo.mViewVisibilityChanged = true; 8742 } 8743 } 8744 8745 /* Check if the VISIBLE bit has changed */ 8746 if ((changed & INVISIBLE) != 0) { 8747 needGlobalAttributesUpdate(false); 8748 /* 8749 * If this view is becoming invisible, set the DRAWN flag so that 8750 * the next invalidate() will not be skipped. 8751 */ 8752 mPrivateFlags |= PFLAG_DRAWN; 8753 8754 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 8755 // root view becoming invisible shouldn't clear focus and accessibility focus 8756 if (getRootView() != this) { 8757 clearFocus(); 8758 clearAccessibilityFocus(); 8759 } 8760 } 8761 if (mAttachInfo != null) { 8762 mAttachInfo.mViewVisibilityChanged = true; 8763 } 8764 } 8765 8766 if ((changed & VISIBILITY_MASK) != 0) { 8767 // If the view is invisible, cleanup its display list to free up resources 8768 if (newVisibility != VISIBLE) { 8769 cleanupDraw(); 8770 } 8771 8772 if (mParent instanceof ViewGroup) { 8773 ((ViewGroup) mParent).onChildVisibilityChanged(this, 8774 (changed & VISIBILITY_MASK), newVisibility); 8775 ((View) mParent).invalidate(true); 8776 } else if (mParent != null) { 8777 mParent.invalidateChild(this, null); 8778 } 8779 dispatchVisibilityChanged(this, newVisibility); 8780 } 8781 8782 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 8783 destroyDrawingCache(); 8784 } 8785 8786 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 8787 destroyDrawingCache(); 8788 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8789 invalidateParentCaches(); 8790 } 8791 8792 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 8793 destroyDrawingCache(); 8794 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8795 } 8796 8797 if ((changed & DRAW_MASK) != 0) { 8798 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 8799 if (mBackground != null) { 8800 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8801 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 8802 } else { 8803 mPrivateFlags |= PFLAG_SKIP_DRAW; 8804 } 8805 } else { 8806 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8807 } 8808 requestLayout(); 8809 invalidate(true); 8810 } 8811 8812 if ((changed & KEEP_SCREEN_ON) != 0) { 8813 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 8814 mParent.recomputeViewAttributes(this); 8815 } 8816 } 8817 8818 if (accessibilityEnabled) { 8819 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 8820 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 8821 if (oldIncludeForAccessibility != includeForAccessibility()) { 8822 notifySubtreeAccessibilityStateChangedIfNeeded(); 8823 } else { 8824 notifyViewAccessibilityStateChangedIfNeeded(); 8825 } 8826 } 8827 if ((changed & ENABLED_MASK) != 0) { 8828 notifyViewAccessibilityStateChangedIfNeeded(); 8829 } 8830 } 8831 } 8832 8833 /** 8834 * Change the view's z order in the tree, so it's on top of other sibling 8835 * views. This ordering change may affect layout, if the parent container 8836 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 8837 * to {@link android.os.Build.VERSION_CODES#KEY_LIME_PIE} this 8838 * method should be followed by calls to {@link #requestLayout()} and 8839 * {@link View#invalidate()} on the view's parent to force the parent to redraw 8840 * with the new child ordering. 8841 * 8842 * @see ViewGroup#bringChildToFront(View) 8843 */ 8844 public void bringToFront() { 8845 if (mParent != null) { 8846 mParent.bringChildToFront(this); 8847 } 8848 } 8849 8850 /** 8851 * This is called in response to an internal scroll in this view (i.e., the 8852 * view scrolled its own contents). This is typically as a result of 8853 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 8854 * called. 8855 * 8856 * @param l Current horizontal scroll origin. 8857 * @param t Current vertical scroll origin. 8858 * @param oldl Previous horizontal scroll origin. 8859 * @param oldt Previous vertical scroll origin. 8860 */ 8861 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 8862 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8863 postSendViewScrolledAccessibilityEventCallback(); 8864 } 8865 8866 mBackgroundSizeChanged = true; 8867 8868 final AttachInfo ai = mAttachInfo; 8869 if (ai != null) { 8870 ai.mViewScrollChanged = true; 8871 } 8872 } 8873 8874 /** 8875 * Interface definition for a callback to be invoked when the layout bounds of a view 8876 * changes due to layout processing. 8877 */ 8878 public interface OnLayoutChangeListener { 8879 /** 8880 * Called when the focus state of a view has changed. 8881 * 8882 * @param v The view whose state has changed. 8883 * @param left The new value of the view's left property. 8884 * @param top The new value of the view's top property. 8885 * @param right The new value of the view's right property. 8886 * @param bottom The new value of the view's bottom property. 8887 * @param oldLeft The previous value of the view's left property. 8888 * @param oldTop The previous value of the view's top property. 8889 * @param oldRight The previous value of the view's right property. 8890 * @param oldBottom The previous value of the view's bottom property. 8891 */ 8892 void onLayoutChange(View v, int left, int top, int right, int bottom, 8893 int oldLeft, int oldTop, int oldRight, int oldBottom); 8894 } 8895 8896 /** 8897 * This is called during layout when the size of this view has changed. If 8898 * you were just added to the view hierarchy, you're called with the old 8899 * values of 0. 8900 * 8901 * @param w Current width of this view. 8902 * @param h Current height of this view. 8903 * @param oldw Old width of this view. 8904 * @param oldh Old height of this view. 8905 */ 8906 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 8907 } 8908 8909 /** 8910 * Called by draw to draw the child views. This may be overridden 8911 * by derived classes to gain control just before its children are drawn 8912 * (but after its own view has been drawn). 8913 * @param canvas the canvas on which to draw the view 8914 */ 8915 protected void dispatchDraw(Canvas canvas) { 8916 8917 } 8918 8919 /** 8920 * Gets the parent of this view. Note that the parent is a 8921 * ViewParent and not necessarily a View. 8922 * 8923 * @return Parent of this view. 8924 */ 8925 public final ViewParent getParent() { 8926 return mParent; 8927 } 8928 8929 /** 8930 * Set the horizontal scrolled position of your view. This will cause a call to 8931 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8932 * invalidated. 8933 * @param value the x position to scroll to 8934 */ 8935 public void setScrollX(int value) { 8936 scrollTo(value, mScrollY); 8937 } 8938 8939 /** 8940 * Set the vertical scrolled position of your view. This will cause a call to 8941 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8942 * invalidated. 8943 * @param value the y position to scroll to 8944 */ 8945 public void setScrollY(int value) { 8946 scrollTo(mScrollX, value); 8947 } 8948 8949 /** 8950 * Return the scrolled left position of this view. This is the left edge of 8951 * the displayed part of your view. You do not need to draw any pixels 8952 * farther left, since those are outside of the frame of your view on 8953 * screen. 8954 * 8955 * @return The left edge of the displayed part of your view, in pixels. 8956 */ 8957 public final int getScrollX() { 8958 return mScrollX; 8959 } 8960 8961 /** 8962 * Return the scrolled top position of this view. This is the top edge of 8963 * the displayed part of your view. You do not need to draw any pixels above 8964 * it, since those are outside of the frame of your view on screen. 8965 * 8966 * @return The top edge of the displayed part of your view, in pixels. 8967 */ 8968 public final int getScrollY() { 8969 return mScrollY; 8970 } 8971 8972 /** 8973 * Return the width of the your view. 8974 * 8975 * @return The width of your view, in pixels. 8976 */ 8977 @ViewDebug.ExportedProperty(category = "layout") 8978 public final int getWidth() { 8979 return mRight - mLeft; 8980 } 8981 8982 /** 8983 * Return the height of your view. 8984 * 8985 * @return The height of your view, in pixels. 8986 */ 8987 @ViewDebug.ExportedProperty(category = "layout") 8988 public final int getHeight() { 8989 return mBottom - mTop; 8990 } 8991 8992 /** 8993 * Return the visible drawing bounds of your view. Fills in the output 8994 * rectangle with the values from getScrollX(), getScrollY(), 8995 * getWidth(), and getHeight(). These bounds do not account for any 8996 * transformation properties currently set on the view, such as 8997 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 8998 * 8999 * @param outRect The (scrolled) drawing bounds of the view. 9000 */ 9001 public void getDrawingRect(Rect outRect) { 9002 outRect.left = mScrollX; 9003 outRect.top = mScrollY; 9004 outRect.right = mScrollX + (mRight - mLeft); 9005 outRect.bottom = mScrollY + (mBottom - mTop); 9006 } 9007 9008 /** 9009 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9010 * raw width component (that is the result is masked by 9011 * {@link #MEASURED_SIZE_MASK}). 9012 * 9013 * @return The raw measured width of this view. 9014 */ 9015 public final int getMeasuredWidth() { 9016 return mMeasuredWidth & MEASURED_SIZE_MASK; 9017 } 9018 9019 /** 9020 * Return the full width measurement information for this view as computed 9021 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9022 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9023 * This should be used during measurement and layout calculations only. Use 9024 * {@link #getWidth()} to see how wide a view is after layout. 9025 * 9026 * @return The measured width of this view as a bit mask. 9027 */ 9028 public final int getMeasuredWidthAndState() { 9029 return mMeasuredWidth; 9030 } 9031 9032 /** 9033 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9034 * raw width component (that is the result is masked by 9035 * {@link #MEASURED_SIZE_MASK}). 9036 * 9037 * @return The raw measured height of this view. 9038 */ 9039 public final int getMeasuredHeight() { 9040 return mMeasuredHeight & MEASURED_SIZE_MASK; 9041 } 9042 9043 /** 9044 * Return the full height measurement information for this view as computed 9045 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9046 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9047 * This should be used during measurement and layout calculations only. Use 9048 * {@link #getHeight()} to see how wide a view is after layout. 9049 * 9050 * @return The measured width of this view as a bit mask. 9051 */ 9052 public final int getMeasuredHeightAndState() { 9053 return mMeasuredHeight; 9054 } 9055 9056 /** 9057 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9058 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9059 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9060 * and the height component is at the shifted bits 9061 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9062 */ 9063 public final int getMeasuredState() { 9064 return (mMeasuredWidth&MEASURED_STATE_MASK) 9065 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9066 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9067 } 9068 9069 /** 9070 * The transform matrix of this view, which is calculated based on the current 9071 * roation, scale, and pivot properties. 9072 * 9073 * @see #getRotation() 9074 * @see #getScaleX() 9075 * @see #getScaleY() 9076 * @see #getPivotX() 9077 * @see #getPivotY() 9078 * @return The current transform matrix for the view 9079 */ 9080 public Matrix getMatrix() { 9081 if (mTransformationInfo != null) { 9082 updateMatrix(); 9083 return mTransformationInfo.mMatrix; 9084 } 9085 return Matrix.IDENTITY_MATRIX; 9086 } 9087 9088 /** 9089 * Utility function to determine if the value is far enough away from zero to be 9090 * considered non-zero. 9091 * @param value A floating point value to check for zero-ness 9092 * @return whether the passed-in value is far enough away from zero to be considered non-zero 9093 */ 9094 private static boolean nonzero(float value) { 9095 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 9096 } 9097 9098 /** 9099 * Returns true if the transform matrix is the identity matrix. 9100 * Recomputes the matrix if necessary. 9101 * 9102 * @return True if the transform matrix is the identity matrix, false otherwise. 9103 */ 9104 final boolean hasIdentityMatrix() { 9105 if (mTransformationInfo != null) { 9106 updateMatrix(); 9107 return mTransformationInfo.mMatrixIsIdentity; 9108 } 9109 return true; 9110 } 9111 9112 void ensureTransformationInfo() { 9113 if (mTransformationInfo == null) { 9114 mTransformationInfo = new TransformationInfo(); 9115 } 9116 } 9117 9118 /** 9119 * Recomputes the transform matrix if necessary. 9120 */ 9121 private void updateMatrix() { 9122 final TransformationInfo info = mTransformationInfo; 9123 if (info == null) { 9124 return; 9125 } 9126 if (info.mMatrixDirty) { 9127 // transform-related properties have changed since the last time someone 9128 // asked for the matrix; recalculate it with the current values 9129 9130 // Figure out if we need to update the pivot point 9131 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9132 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 9133 info.mPrevWidth = mRight - mLeft; 9134 info.mPrevHeight = mBottom - mTop; 9135 info.mPivotX = info.mPrevWidth / 2f; 9136 info.mPivotY = info.mPrevHeight / 2f; 9137 } 9138 } 9139 info.mMatrix.reset(); 9140 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 9141 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 9142 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 9143 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9144 } else { 9145 if (info.mCamera == null) { 9146 info.mCamera = new Camera(); 9147 info.matrix3D = new Matrix(); 9148 } 9149 info.mCamera.save(); 9150 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9151 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 9152 info.mCamera.getMatrix(info.matrix3D); 9153 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 9154 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 9155 info.mPivotY + info.mTranslationY); 9156 info.mMatrix.postConcat(info.matrix3D); 9157 info.mCamera.restore(); 9158 } 9159 info.mMatrixDirty = false; 9160 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 9161 info.mInverseMatrixDirty = true; 9162 } 9163 } 9164 9165 /** 9166 * Utility method to retrieve the inverse of the current mMatrix property. 9167 * We cache the matrix to avoid recalculating it when transform properties 9168 * have not changed. 9169 * 9170 * @return The inverse of the current matrix of this view. 9171 */ 9172 final Matrix getInverseMatrix() { 9173 final TransformationInfo info = mTransformationInfo; 9174 if (info != null) { 9175 updateMatrix(); 9176 if (info.mInverseMatrixDirty) { 9177 if (info.mInverseMatrix == null) { 9178 info.mInverseMatrix = new Matrix(); 9179 } 9180 info.mMatrix.invert(info.mInverseMatrix); 9181 info.mInverseMatrixDirty = false; 9182 } 9183 return info.mInverseMatrix; 9184 } 9185 return Matrix.IDENTITY_MATRIX; 9186 } 9187 9188 /** 9189 * Gets the distance along the Z axis from the camera to this view. 9190 * 9191 * @see #setCameraDistance(float) 9192 * 9193 * @return The distance along the Z axis. 9194 */ 9195 public float getCameraDistance() { 9196 ensureTransformationInfo(); 9197 final float dpi = mResources.getDisplayMetrics().densityDpi; 9198 final TransformationInfo info = mTransformationInfo; 9199 if (info.mCamera == null) { 9200 info.mCamera = new Camera(); 9201 info.matrix3D = new Matrix(); 9202 } 9203 return -(info.mCamera.getLocationZ() * dpi); 9204 } 9205 9206 /** 9207 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9208 * views are drawn) from the camera to this view. The camera's distance 9209 * affects 3D transformations, for instance rotations around the X and Y 9210 * axis. If the rotationX or rotationY properties are changed and this view is 9211 * large (more than half the size of the screen), it is recommended to always 9212 * use a camera distance that's greater than the height (X axis rotation) or 9213 * the width (Y axis rotation) of this view.</p> 9214 * 9215 * <p>The distance of the camera from the view plane can have an affect on the 9216 * perspective distortion of the view when it is rotated around the x or y axis. 9217 * For example, a large distance will result in a large viewing angle, and there 9218 * will not be much perspective distortion of the view as it rotates. A short 9219 * distance may cause much more perspective distortion upon rotation, and can 9220 * also result in some drawing artifacts if the rotated view ends up partially 9221 * behind the camera (which is why the recommendation is to use a distance at 9222 * least as far as the size of the view, if the view is to be rotated.)</p> 9223 * 9224 * <p>The distance is expressed in "depth pixels." The default distance depends 9225 * on the screen density. For instance, on a medium density display, the 9226 * default distance is 1280. On a high density display, the default distance 9227 * is 1920.</p> 9228 * 9229 * <p>If you want to specify a distance that leads to visually consistent 9230 * results across various densities, use the following formula:</p> 9231 * <pre> 9232 * float scale = context.getResources().getDisplayMetrics().density; 9233 * view.setCameraDistance(distance * scale); 9234 * </pre> 9235 * 9236 * <p>The density scale factor of a high density display is 1.5, 9237 * and 1920 = 1280 * 1.5.</p> 9238 * 9239 * @param distance The distance in "depth pixels", if negative the opposite 9240 * value is used 9241 * 9242 * @see #setRotationX(float) 9243 * @see #setRotationY(float) 9244 */ 9245 public void setCameraDistance(float distance) { 9246 invalidateViewProperty(true, false); 9247 9248 ensureTransformationInfo(); 9249 final float dpi = mResources.getDisplayMetrics().densityDpi; 9250 final TransformationInfo info = mTransformationInfo; 9251 if (info.mCamera == null) { 9252 info.mCamera = new Camera(); 9253 info.matrix3D = new Matrix(); 9254 } 9255 9256 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 9257 info.mMatrixDirty = true; 9258 9259 invalidateViewProperty(false, false); 9260 if (mDisplayList != null) { 9261 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 9262 } 9263 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9264 // View was rejected last time it was drawn by its parent; this may have changed 9265 invalidateParentIfNeeded(); 9266 } 9267 } 9268 9269 /** 9270 * The degrees that the view is rotated around the pivot point. 9271 * 9272 * @see #setRotation(float) 9273 * @see #getPivotX() 9274 * @see #getPivotY() 9275 * 9276 * @return The degrees of rotation. 9277 */ 9278 @ViewDebug.ExportedProperty(category = "drawing") 9279 public float getRotation() { 9280 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 9281 } 9282 9283 /** 9284 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9285 * result in clockwise rotation. 9286 * 9287 * @param rotation The degrees of rotation. 9288 * 9289 * @see #getRotation() 9290 * @see #getPivotX() 9291 * @see #getPivotY() 9292 * @see #setRotationX(float) 9293 * @see #setRotationY(float) 9294 * 9295 * @attr ref android.R.styleable#View_rotation 9296 */ 9297 public void setRotation(float rotation) { 9298 ensureTransformationInfo(); 9299 final TransformationInfo info = mTransformationInfo; 9300 if (info.mRotation != rotation) { 9301 // Double-invalidation is necessary to capture view's old and new areas 9302 invalidateViewProperty(true, false); 9303 info.mRotation = rotation; 9304 info.mMatrixDirty = true; 9305 invalidateViewProperty(false, true); 9306 if (mDisplayList != null) { 9307 mDisplayList.setRotation(rotation); 9308 } 9309 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9310 // View was rejected last time it was drawn by its parent; this may have changed 9311 invalidateParentIfNeeded(); 9312 } 9313 } 9314 } 9315 9316 /** 9317 * The degrees that the view is rotated around the vertical axis through the pivot point. 9318 * 9319 * @see #getPivotX() 9320 * @see #getPivotY() 9321 * @see #setRotationY(float) 9322 * 9323 * @return The degrees of Y rotation. 9324 */ 9325 @ViewDebug.ExportedProperty(category = "drawing") 9326 public float getRotationY() { 9327 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 9328 } 9329 9330 /** 9331 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9332 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9333 * down the y axis. 9334 * 9335 * When rotating large views, it is recommended to adjust the camera distance 9336 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9337 * 9338 * @param rotationY The degrees of Y rotation. 9339 * 9340 * @see #getRotationY() 9341 * @see #getPivotX() 9342 * @see #getPivotY() 9343 * @see #setRotation(float) 9344 * @see #setRotationX(float) 9345 * @see #setCameraDistance(float) 9346 * 9347 * @attr ref android.R.styleable#View_rotationY 9348 */ 9349 public void setRotationY(float rotationY) { 9350 ensureTransformationInfo(); 9351 final TransformationInfo info = mTransformationInfo; 9352 if (info.mRotationY != rotationY) { 9353 invalidateViewProperty(true, false); 9354 info.mRotationY = rotationY; 9355 info.mMatrixDirty = true; 9356 invalidateViewProperty(false, true); 9357 if (mDisplayList != null) { 9358 mDisplayList.setRotationY(rotationY); 9359 } 9360 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9361 // View was rejected last time it was drawn by its parent; this may have changed 9362 invalidateParentIfNeeded(); 9363 } 9364 } 9365 } 9366 9367 /** 9368 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9369 * 9370 * @see #getPivotX() 9371 * @see #getPivotY() 9372 * @see #setRotationX(float) 9373 * 9374 * @return The degrees of X rotation. 9375 */ 9376 @ViewDebug.ExportedProperty(category = "drawing") 9377 public float getRotationX() { 9378 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 9379 } 9380 9381 /** 9382 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9383 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9384 * x axis. 9385 * 9386 * When rotating large views, it is recommended to adjust the camera distance 9387 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9388 * 9389 * @param rotationX The degrees of X rotation. 9390 * 9391 * @see #getRotationX() 9392 * @see #getPivotX() 9393 * @see #getPivotY() 9394 * @see #setRotation(float) 9395 * @see #setRotationY(float) 9396 * @see #setCameraDistance(float) 9397 * 9398 * @attr ref android.R.styleable#View_rotationX 9399 */ 9400 public void setRotationX(float rotationX) { 9401 ensureTransformationInfo(); 9402 final TransformationInfo info = mTransformationInfo; 9403 if (info.mRotationX != rotationX) { 9404 invalidateViewProperty(true, false); 9405 info.mRotationX = rotationX; 9406 info.mMatrixDirty = true; 9407 invalidateViewProperty(false, true); 9408 if (mDisplayList != null) { 9409 mDisplayList.setRotationX(rotationX); 9410 } 9411 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9412 // View was rejected last time it was drawn by its parent; this may have changed 9413 invalidateParentIfNeeded(); 9414 } 9415 } 9416 } 9417 9418 /** 9419 * The amount that the view is scaled in x around the pivot point, as a proportion of 9420 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9421 * 9422 * <p>By default, this is 1.0f. 9423 * 9424 * @see #getPivotX() 9425 * @see #getPivotY() 9426 * @return The scaling factor. 9427 */ 9428 @ViewDebug.ExportedProperty(category = "drawing") 9429 public float getScaleX() { 9430 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 9431 } 9432 9433 /** 9434 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9435 * the view's unscaled width. A value of 1 means that no scaling is applied. 9436 * 9437 * @param scaleX The scaling factor. 9438 * @see #getPivotX() 9439 * @see #getPivotY() 9440 * 9441 * @attr ref android.R.styleable#View_scaleX 9442 */ 9443 public void setScaleX(float scaleX) { 9444 ensureTransformationInfo(); 9445 final TransformationInfo info = mTransformationInfo; 9446 if (info.mScaleX != scaleX) { 9447 invalidateViewProperty(true, false); 9448 info.mScaleX = scaleX; 9449 info.mMatrixDirty = true; 9450 invalidateViewProperty(false, true); 9451 if (mDisplayList != null) { 9452 mDisplayList.setScaleX(scaleX); 9453 } 9454 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9455 // View was rejected last time it was drawn by its parent; this may have changed 9456 invalidateParentIfNeeded(); 9457 } 9458 } 9459 } 9460 9461 /** 9462 * The amount that the view is scaled in y around the pivot point, as a proportion of 9463 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9464 * 9465 * <p>By default, this is 1.0f. 9466 * 9467 * @see #getPivotX() 9468 * @see #getPivotY() 9469 * @return The scaling factor. 9470 */ 9471 @ViewDebug.ExportedProperty(category = "drawing") 9472 public float getScaleY() { 9473 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 9474 } 9475 9476 /** 9477 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9478 * the view's unscaled width. A value of 1 means that no scaling is applied. 9479 * 9480 * @param scaleY The scaling factor. 9481 * @see #getPivotX() 9482 * @see #getPivotY() 9483 * 9484 * @attr ref android.R.styleable#View_scaleY 9485 */ 9486 public void setScaleY(float scaleY) { 9487 ensureTransformationInfo(); 9488 final TransformationInfo info = mTransformationInfo; 9489 if (info.mScaleY != scaleY) { 9490 invalidateViewProperty(true, false); 9491 info.mScaleY = scaleY; 9492 info.mMatrixDirty = true; 9493 invalidateViewProperty(false, true); 9494 if (mDisplayList != null) { 9495 mDisplayList.setScaleY(scaleY); 9496 } 9497 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9498 // View was rejected last time it was drawn by its parent; this may have changed 9499 invalidateParentIfNeeded(); 9500 } 9501 } 9502 } 9503 9504 /** 9505 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9506 * and {@link #setScaleX(float) scaled}. 9507 * 9508 * @see #getRotation() 9509 * @see #getScaleX() 9510 * @see #getScaleY() 9511 * @see #getPivotY() 9512 * @return The x location of the pivot point. 9513 * 9514 * @attr ref android.R.styleable#View_transformPivotX 9515 */ 9516 @ViewDebug.ExportedProperty(category = "drawing") 9517 public float getPivotX() { 9518 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 9519 } 9520 9521 /** 9522 * Sets the x location of the point around which the view is 9523 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9524 * By default, the pivot point is centered on the object. 9525 * Setting this property disables this behavior and causes the view to use only the 9526 * explicitly set pivotX and pivotY values. 9527 * 9528 * @param pivotX The x location of the pivot point. 9529 * @see #getRotation() 9530 * @see #getScaleX() 9531 * @see #getScaleY() 9532 * @see #getPivotY() 9533 * 9534 * @attr ref android.R.styleable#View_transformPivotX 9535 */ 9536 public void setPivotX(float pivotX) { 9537 ensureTransformationInfo(); 9538 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9539 final TransformationInfo info = mTransformationInfo; 9540 if (info.mPivotX != pivotX) { 9541 invalidateViewProperty(true, false); 9542 info.mPivotX = pivotX; 9543 info.mMatrixDirty = true; 9544 invalidateViewProperty(false, true); 9545 if (mDisplayList != null) { 9546 mDisplayList.setPivotX(pivotX); 9547 } 9548 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9549 // View was rejected last time it was drawn by its parent; this may have changed 9550 invalidateParentIfNeeded(); 9551 } 9552 } 9553 } 9554 9555 /** 9556 * The y location of the point around which the view is {@link #setRotation(float) rotated} 9557 * and {@link #setScaleY(float) scaled}. 9558 * 9559 * @see #getRotation() 9560 * @see #getScaleX() 9561 * @see #getScaleY() 9562 * @see #getPivotY() 9563 * @return The y location of the pivot point. 9564 * 9565 * @attr ref android.R.styleable#View_transformPivotY 9566 */ 9567 @ViewDebug.ExportedProperty(category = "drawing") 9568 public float getPivotY() { 9569 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 9570 } 9571 9572 /** 9573 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 9574 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 9575 * Setting this property disables this behavior and causes the view to use only the 9576 * explicitly set pivotX and pivotY values. 9577 * 9578 * @param pivotY The y location of the pivot point. 9579 * @see #getRotation() 9580 * @see #getScaleX() 9581 * @see #getScaleY() 9582 * @see #getPivotY() 9583 * 9584 * @attr ref android.R.styleable#View_transformPivotY 9585 */ 9586 public void setPivotY(float pivotY) { 9587 ensureTransformationInfo(); 9588 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9589 final TransformationInfo info = mTransformationInfo; 9590 if (info.mPivotY != pivotY) { 9591 invalidateViewProperty(true, false); 9592 info.mPivotY = pivotY; 9593 info.mMatrixDirty = true; 9594 invalidateViewProperty(false, true); 9595 if (mDisplayList != null) { 9596 mDisplayList.setPivotY(pivotY); 9597 } 9598 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9599 // View was rejected last time it was drawn by its parent; this may have changed 9600 invalidateParentIfNeeded(); 9601 } 9602 } 9603 } 9604 9605 /** 9606 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 9607 * completely transparent and 1 means the view is completely opaque. 9608 * 9609 * <p>By default this is 1.0f. 9610 * @return The opacity of the view. 9611 */ 9612 @ViewDebug.ExportedProperty(category = "drawing") 9613 public float getAlpha() { 9614 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 9615 } 9616 9617 /** 9618 * Returns whether this View has content which overlaps. This function, intended to be 9619 * overridden by specific View types, is an optimization when alpha is set on a view. If 9620 * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer 9621 * and then composited it into place, which can be expensive. If the view has no overlapping 9622 * rendering, the view can draw each primitive with the appropriate alpha value directly. 9623 * An example of overlapping rendering is a TextView with a background image, such as a 9624 * Button. An example of non-overlapping rendering is a TextView with no background, or 9625 * an ImageView with only the foreground image. The default implementation returns true; 9626 * subclasses should override if they have cases which can be optimized. 9627 * 9628 * @return true if the content in this view might overlap, false otherwise. 9629 */ 9630 public boolean hasOverlappingRendering() { 9631 return true; 9632 } 9633 9634 /** 9635 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 9636 * completely transparent and 1 means the view is completely opaque.</p> 9637 * 9638 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 9639 * performance implications, especially for large views. It is best to use the alpha property 9640 * sparingly and transiently, as in the case of fading animations.</p> 9641 * 9642 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 9643 * strongly recommended for performance reasons to either override 9644 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 9645 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 9646 * 9647 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 9648 * responsible for applying the opacity itself.</p> 9649 * 9650 * <p>Note that if the view is backed by a 9651 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 9652 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 9653 * 1.0 will supercede the alpha of the layer paint.</p> 9654 * 9655 * @param alpha The opacity of the view. 9656 * 9657 * @see #hasOverlappingRendering() 9658 * @see #setLayerType(int, android.graphics.Paint) 9659 * 9660 * @attr ref android.R.styleable#View_alpha 9661 */ 9662 public void setAlpha(float alpha) { 9663 ensureTransformationInfo(); 9664 if (mTransformationInfo.mAlpha != alpha) { 9665 mTransformationInfo.mAlpha = alpha; 9666 if (onSetAlpha((int) (alpha * 255))) { 9667 mPrivateFlags |= PFLAG_ALPHA_SET; 9668 // subclass is handling alpha - don't optimize rendering cache invalidation 9669 invalidateParentCaches(); 9670 invalidate(true); 9671 } else { 9672 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9673 invalidateViewProperty(true, false); 9674 if (mDisplayList != null) { 9675 mDisplayList.setAlpha(alpha); 9676 } 9677 } 9678 } 9679 } 9680 9681 /** 9682 * Faster version of setAlpha() which performs the same steps except there are 9683 * no calls to invalidate(). The caller of this function should perform proper invalidation 9684 * on the parent and this object. The return value indicates whether the subclass handles 9685 * alpha (the return value for onSetAlpha()). 9686 * 9687 * @param alpha The new value for the alpha property 9688 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 9689 * the new value for the alpha property is different from the old value 9690 */ 9691 boolean setAlphaNoInvalidation(float alpha) { 9692 ensureTransformationInfo(); 9693 if (mTransformationInfo.mAlpha != alpha) { 9694 mTransformationInfo.mAlpha = alpha; 9695 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 9696 if (subclassHandlesAlpha) { 9697 mPrivateFlags |= PFLAG_ALPHA_SET; 9698 return true; 9699 } else { 9700 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9701 if (mDisplayList != null) { 9702 mDisplayList.setAlpha(alpha); 9703 } 9704 } 9705 } 9706 return false; 9707 } 9708 9709 /** 9710 * Top position of this view relative to its parent. 9711 * 9712 * @return The top of this view, in pixels. 9713 */ 9714 @ViewDebug.CapturedViewProperty 9715 public final int getTop() { 9716 return mTop; 9717 } 9718 9719 /** 9720 * Sets the top position of this view relative to its parent. This method is meant to be called 9721 * by the layout system and should not generally be called otherwise, because the property 9722 * may be changed at any time by the layout. 9723 * 9724 * @param top The top of this view, in pixels. 9725 */ 9726 public final void setTop(int top) { 9727 if (top != mTop) { 9728 updateMatrix(); 9729 final boolean matrixIsIdentity = mTransformationInfo == null 9730 || mTransformationInfo.mMatrixIsIdentity; 9731 if (matrixIsIdentity) { 9732 if (mAttachInfo != null) { 9733 int minTop; 9734 int yLoc; 9735 if (top < mTop) { 9736 minTop = top; 9737 yLoc = top - mTop; 9738 } else { 9739 minTop = mTop; 9740 yLoc = 0; 9741 } 9742 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 9743 } 9744 } else { 9745 // Double-invalidation is necessary to capture view's old and new areas 9746 invalidate(true); 9747 } 9748 9749 int width = mRight - mLeft; 9750 int oldHeight = mBottom - mTop; 9751 9752 mTop = top; 9753 if (mDisplayList != null) { 9754 mDisplayList.setTop(mTop); 9755 } 9756 9757 sizeChange(width, mBottom - mTop, width, oldHeight); 9758 9759 if (!matrixIsIdentity) { 9760 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9761 // A change in dimension means an auto-centered pivot point changes, too 9762 mTransformationInfo.mMatrixDirty = true; 9763 } 9764 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9765 invalidate(true); 9766 } 9767 mBackgroundSizeChanged = true; 9768 invalidateParentIfNeeded(); 9769 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9770 // View was rejected last time it was drawn by its parent; this may have changed 9771 invalidateParentIfNeeded(); 9772 } 9773 } 9774 } 9775 9776 /** 9777 * Bottom position of this view relative to its parent. 9778 * 9779 * @return The bottom of this view, in pixels. 9780 */ 9781 @ViewDebug.CapturedViewProperty 9782 public final int getBottom() { 9783 return mBottom; 9784 } 9785 9786 /** 9787 * True if this view has changed since the last time being drawn. 9788 * 9789 * @return The dirty state of this view. 9790 */ 9791 public boolean isDirty() { 9792 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 9793 } 9794 9795 /** 9796 * Sets the bottom position of this view relative to its parent. This method is meant to be 9797 * called by the layout system and should not generally be called otherwise, because the 9798 * property may be changed at any time by the layout. 9799 * 9800 * @param bottom The bottom of this view, in pixels. 9801 */ 9802 public final void setBottom(int bottom) { 9803 if (bottom != mBottom) { 9804 updateMatrix(); 9805 final boolean matrixIsIdentity = mTransformationInfo == null 9806 || mTransformationInfo.mMatrixIsIdentity; 9807 if (matrixIsIdentity) { 9808 if (mAttachInfo != null) { 9809 int maxBottom; 9810 if (bottom < mBottom) { 9811 maxBottom = mBottom; 9812 } else { 9813 maxBottom = bottom; 9814 } 9815 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 9816 } 9817 } else { 9818 // Double-invalidation is necessary to capture view's old and new areas 9819 invalidate(true); 9820 } 9821 9822 int width = mRight - mLeft; 9823 int oldHeight = mBottom - mTop; 9824 9825 mBottom = bottom; 9826 if (mDisplayList != null) { 9827 mDisplayList.setBottom(mBottom); 9828 } 9829 9830 sizeChange(width, mBottom - mTop, width, oldHeight); 9831 9832 if (!matrixIsIdentity) { 9833 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9834 // A change in dimension means an auto-centered pivot point changes, too 9835 mTransformationInfo.mMatrixDirty = true; 9836 } 9837 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9838 invalidate(true); 9839 } 9840 mBackgroundSizeChanged = true; 9841 invalidateParentIfNeeded(); 9842 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9843 // View was rejected last time it was drawn by its parent; this may have changed 9844 invalidateParentIfNeeded(); 9845 } 9846 } 9847 } 9848 9849 /** 9850 * Left position of this view relative to its parent. 9851 * 9852 * @return The left edge of this view, in pixels. 9853 */ 9854 @ViewDebug.CapturedViewProperty 9855 public final int getLeft() { 9856 return mLeft; 9857 } 9858 9859 /** 9860 * Sets the left position of this view relative to its parent. This method is meant to be called 9861 * by the layout system and should not generally be called otherwise, because the property 9862 * may be changed at any time by the layout. 9863 * 9864 * @param left The bottom of this view, in pixels. 9865 */ 9866 public final void setLeft(int left) { 9867 if (left != mLeft) { 9868 updateMatrix(); 9869 final boolean matrixIsIdentity = mTransformationInfo == null 9870 || mTransformationInfo.mMatrixIsIdentity; 9871 if (matrixIsIdentity) { 9872 if (mAttachInfo != null) { 9873 int minLeft; 9874 int xLoc; 9875 if (left < mLeft) { 9876 minLeft = left; 9877 xLoc = left - mLeft; 9878 } else { 9879 minLeft = mLeft; 9880 xLoc = 0; 9881 } 9882 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 9883 } 9884 } else { 9885 // Double-invalidation is necessary to capture view's old and new areas 9886 invalidate(true); 9887 } 9888 9889 int oldWidth = mRight - mLeft; 9890 int height = mBottom - mTop; 9891 9892 mLeft = left; 9893 if (mDisplayList != null) { 9894 mDisplayList.setLeft(left); 9895 } 9896 9897 sizeChange(mRight - mLeft, height, oldWidth, height); 9898 9899 if (!matrixIsIdentity) { 9900 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9901 // A change in dimension means an auto-centered pivot point changes, too 9902 mTransformationInfo.mMatrixDirty = true; 9903 } 9904 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9905 invalidate(true); 9906 } 9907 mBackgroundSizeChanged = true; 9908 invalidateParentIfNeeded(); 9909 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9910 // View was rejected last time it was drawn by its parent; this may have changed 9911 invalidateParentIfNeeded(); 9912 } 9913 } 9914 } 9915 9916 /** 9917 * Right position of this view relative to its parent. 9918 * 9919 * @return The right edge of this view, in pixels. 9920 */ 9921 @ViewDebug.CapturedViewProperty 9922 public final int getRight() { 9923 return mRight; 9924 } 9925 9926 /** 9927 * Sets the right position of this view relative to its parent. This method is meant to be called 9928 * by the layout system and should not generally be called otherwise, because the property 9929 * may be changed at any time by the layout. 9930 * 9931 * @param right The bottom of this view, in pixels. 9932 */ 9933 public final void setRight(int right) { 9934 if (right != mRight) { 9935 updateMatrix(); 9936 final boolean matrixIsIdentity = mTransformationInfo == null 9937 || mTransformationInfo.mMatrixIsIdentity; 9938 if (matrixIsIdentity) { 9939 if (mAttachInfo != null) { 9940 int maxRight; 9941 if (right < mRight) { 9942 maxRight = mRight; 9943 } else { 9944 maxRight = right; 9945 } 9946 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 9947 } 9948 } else { 9949 // Double-invalidation is necessary to capture view's old and new areas 9950 invalidate(true); 9951 } 9952 9953 int oldWidth = mRight - mLeft; 9954 int height = mBottom - mTop; 9955 9956 mRight = right; 9957 if (mDisplayList != null) { 9958 mDisplayList.setRight(mRight); 9959 } 9960 9961 sizeChange(mRight - mLeft, height, oldWidth, height); 9962 9963 if (!matrixIsIdentity) { 9964 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9965 // A change in dimension means an auto-centered pivot point changes, too 9966 mTransformationInfo.mMatrixDirty = true; 9967 } 9968 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9969 invalidate(true); 9970 } 9971 mBackgroundSizeChanged = true; 9972 invalidateParentIfNeeded(); 9973 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9974 // View was rejected last time it was drawn by its parent; this may have changed 9975 invalidateParentIfNeeded(); 9976 } 9977 } 9978 } 9979 9980 /** 9981 * The visual x position of this view, in pixels. This is equivalent to the 9982 * {@link #setTranslationX(float) translationX} property plus the current 9983 * {@link #getLeft() left} property. 9984 * 9985 * @return The visual x position of this view, in pixels. 9986 */ 9987 @ViewDebug.ExportedProperty(category = "drawing") 9988 public float getX() { 9989 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 9990 } 9991 9992 /** 9993 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 9994 * {@link #setTranslationX(float) translationX} property to be the difference between 9995 * the x value passed in and the current {@link #getLeft() left} property. 9996 * 9997 * @param x The visual x position of this view, in pixels. 9998 */ 9999 public void setX(float x) { 10000 setTranslationX(x - mLeft); 10001 } 10002 10003 /** 10004 * The visual y position of this view, in pixels. This is equivalent to the 10005 * {@link #setTranslationY(float) translationY} property plus the current 10006 * {@link #getTop() top} property. 10007 * 10008 * @return The visual y position of this view, in pixels. 10009 */ 10010 @ViewDebug.ExportedProperty(category = "drawing") 10011 public float getY() { 10012 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 10013 } 10014 10015 /** 10016 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10017 * {@link #setTranslationY(float) translationY} property to be the difference between 10018 * the y value passed in and the current {@link #getTop() top} property. 10019 * 10020 * @param y The visual y position of this view, in pixels. 10021 */ 10022 public void setY(float y) { 10023 setTranslationY(y - mTop); 10024 } 10025 10026 10027 /** 10028 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10029 * This position is post-layout, in addition to wherever the object's 10030 * layout placed it. 10031 * 10032 * @return The horizontal position of this view relative to its left position, in pixels. 10033 */ 10034 @ViewDebug.ExportedProperty(category = "drawing") 10035 public float getTranslationX() { 10036 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 10037 } 10038 10039 /** 10040 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10041 * This effectively positions the object post-layout, in addition to wherever the object's 10042 * layout placed it. 10043 * 10044 * @param translationX The horizontal position of this view relative to its left position, 10045 * in pixels. 10046 * 10047 * @attr ref android.R.styleable#View_translationX 10048 */ 10049 public void setTranslationX(float translationX) { 10050 ensureTransformationInfo(); 10051 final TransformationInfo info = mTransformationInfo; 10052 if (info.mTranslationX != translationX) { 10053 // Double-invalidation is necessary to capture view's old and new areas 10054 invalidateViewProperty(true, false); 10055 info.mTranslationX = translationX; 10056 info.mMatrixDirty = true; 10057 invalidateViewProperty(false, true); 10058 if (mDisplayList != null) { 10059 mDisplayList.setTranslationX(translationX); 10060 } 10061 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10062 // View was rejected last time it was drawn by its parent; this may have changed 10063 invalidateParentIfNeeded(); 10064 } 10065 } 10066 } 10067 10068 /** 10069 * The horizontal location of this view relative to its {@link #getTop() top} position. 10070 * This position is post-layout, in addition to wherever the object's 10071 * layout placed it. 10072 * 10073 * @return The vertical position of this view relative to its top position, 10074 * in pixels. 10075 */ 10076 @ViewDebug.ExportedProperty(category = "drawing") 10077 public float getTranslationY() { 10078 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 10079 } 10080 10081 /** 10082 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10083 * This effectively positions the object post-layout, in addition to wherever the object's 10084 * layout placed it. 10085 * 10086 * @param translationY The vertical position of this view relative to its top position, 10087 * in pixels. 10088 * 10089 * @attr ref android.R.styleable#View_translationY 10090 */ 10091 public void setTranslationY(float translationY) { 10092 ensureTransformationInfo(); 10093 final TransformationInfo info = mTransformationInfo; 10094 if (info.mTranslationY != translationY) { 10095 invalidateViewProperty(true, false); 10096 info.mTranslationY = translationY; 10097 info.mMatrixDirty = true; 10098 invalidateViewProperty(false, true); 10099 if (mDisplayList != null) { 10100 mDisplayList.setTranslationY(translationY); 10101 } 10102 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10103 // View was rejected last time it was drawn by its parent; this may have changed 10104 invalidateParentIfNeeded(); 10105 } 10106 } 10107 } 10108 10109 /** 10110 * Hit rectangle in parent's coordinates 10111 * 10112 * @param outRect The hit rectangle of the view. 10113 */ 10114 public void getHitRect(Rect outRect) { 10115 updateMatrix(); 10116 final TransformationInfo info = mTransformationInfo; 10117 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 10118 outRect.set(mLeft, mTop, mRight, mBottom); 10119 } else { 10120 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10121 tmpRect.set(0, 0, getWidth(), getHeight()); 10122 info.mMatrix.mapRect(tmpRect); 10123 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10124 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10125 } 10126 } 10127 10128 /** 10129 * Determines whether the given point, in local coordinates is inside the view. 10130 */ 10131 /*package*/ final boolean pointInView(float localX, float localY) { 10132 return localX >= 0 && localX < (mRight - mLeft) 10133 && localY >= 0 && localY < (mBottom - mTop); 10134 } 10135 10136 /** 10137 * Utility method to determine whether the given point, in local coordinates, 10138 * is inside the view, where the area of the view is expanded by the slop factor. 10139 * This method is called while processing touch-move events to determine if the event 10140 * is still within the view. 10141 * 10142 * @hide 10143 */ 10144 public boolean pointInView(float localX, float localY, float slop) { 10145 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10146 localY < ((mBottom - mTop) + slop); 10147 } 10148 10149 /** 10150 * When a view has focus and the user navigates away from it, the next view is searched for 10151 * starting from the rectangle filled in by this method. 10152 * 10153 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10154 * of the view. However, if your view maintains some idea of internal selection, 10155 * such as a cursor, or a selected row or column, you should override this method and 10156 * fill in a more specific rectangle. 10157 * 10158 * @param r The rectangle to fill in, in this view's coordinates. 10159 */ 10160 public void getFocusedRect(Rect r) { 10161 getDrawingRect(r); 10162 } 10163 10164 /** 10165 * If some part of this view is not clipped by any of its parents, then 10166 * return that area in r in global (root) coordinates. To convert r to local 10167 * coordinates (without taking possible View rotations into account), offset 10168 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10169 * If the view is completely clipped or translated out, return false. 10170 * 10171 * @param r If true is returned, r holds the global coordinates of the 10172 * visible portion of this view. 10173 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10174 * between this view and its root. globalOffet may be null. 10175 * @return true if r is non-empty (i.e. part of the view is visible at the 10176 * root level. 10177 */ 10178 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10179 int width = mRight - mLeft; 10180 int height = mBottom - mTop; 10181 if (width > 0 && height > 0) { 10182 r.set(0, 0, width, height); 10183 if (globalOffset != null) { 10184 globalOffset.set(-mScrollX, -mScrollY); 10185 } 10186 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10187 } 10188 return false; 10189 } 10190 10191 public final boolean getGlobalVisibleRect(Rect r) { 10192 return getGlobalVisibleRect(r, null); 10193 } 10194 10195 public final boolean getLocalVisibleRect(Rect r) { 10196 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10197 if (getGlobalVisibleRect(r, offset)) { 10198 r.offset(-offset.x, -offset.y); // make r local 10199 return true; 10200 } 10201 return false; 10202 } 10203 10204 /** 10205 * Offset this view's vertical location by the specified number of pixels. 10206 * 10207 * @param offset the number of pixels to offset the view by 10208 */ 10209 public void offsetTopAndBottom(int offset) { 10210 if (offset != 0) { 10211 updateMatrix(); 10212 final boolean matrixIsIdentity = mTransformationInfo == null 10213 || mTransformationInfo.mMatrixIsIdentity; 10214 if (matrixIsIdentity) { 10215 if (mDisplayList != null) { 10216 invalidateViewProperty(false, false); 10217 } else { 10218 final ViewParent p = mParent; 10219 if (p != null && mAttachInfo != null) { 10220 final Rect r = mAttachInfo.mTmpInvalRect; 10221 int minTop; 10222 int maxBottom; 10223 int yLoc; 10224 if (offset < 0) { 10225 minTop = mTop + offset; 10226 maxBottom = mBottom; 10227 yLoc = offset; 10228 } else { 10229 minTop = mTop; 10230 maxBottom = mBottom + offset; 10231 yLoc = 0; 10232 } 10233 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10234 p.invalidateChild(this, r); 10235 } 10236 } 10237 } else { 10238 invalidateViewProperty(false, false); 10239 } 10240 10241 mTop += offset; 10242 mBottom += offset; 10243 if (mDisplayList != null) { 10244 mDisplayList.offsetTopAndBottom(offset); 10245 invalidateViewProperty(false, false); 10246 } else { 10247 if (!matrixIsIdentity) { 10248 invalidateViewProperty(false, true); 10249 } 10250 invalidateParentIfNeeded(); 10251 } 10252 } 10253 } 10254 10255 /** 10256 * Offset this view's horizontal location by the specified amount of pixels. 10257 * 10258 * @param offset the number of pixels to offset the view by 10259 */ 10260 public void offsetLeftAndRight(int offset) { 10261 if (offset != 0) { 10262 updateMatrix(); 10263 final boolean matrixIsIdentity = mTransformationInfo == null 10264 || mTransformationInfo.mMatrixIsIdentity; 10265 if (matrixIsIdentity) { 10266 if (mDisplayList != null) { 10267 invalidateViewProperty(false, false); 10268 } else { 10269 final ViewParent p = mParent; 10270 if (p != null && mAttachInfo != null) { 10271 final Rect r = mAttachInfo.mTmpInvalRect; 10272 int minLeft; 10273 int maxRight; 10274 if (offset < 0) { 10275 minLeft = mLeft + offset; 10276 maxRight = mRight; 10277 } else { 10278 minLeft = mLeft; 10279 maxRight = mRight + offset; 10280 } 10281 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10282 p.invalidateChild(this, r); 10283 } 10284 } 10285 } else { 10286 invalidateViewProperty(false, false); 10287 } 10288 10289 mLeft += offset; 10290 mRight += offset; 10291 if (mDisplayList != null) { 10292 mDisplayList.offsetLeftAndRight(offset); 10293 invalidateViewProperty(false, false); 10294 } else { 10295 if (!matrixIsIdentity) { 10296 invalidateViewProperty(false, true); 10297 } 10298 invalidateParentIfNeeded(); 10299 } 10300 } 10301 } 10302 10303 /** 10304 * Get the LayoutParams associated with this view. All views should have 10305 * layout parameters. These supply parameters to the <i>parent</i> of this 10306 * view specifying how it should be arranged. There are many subclasses of 10307 * ViewGroup.LayoutParams, and these correspond to the different subclasses 10308 * of ViewGroup that are responsible for arranging their children. 10309 * 10310 * This method may return null if this View is not attached to a parent 10311 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 10312 * was not invoked successfully. When a View is attached to a parent 10313 * ViewGroup, this method must not return null. 10314 * 10315 * @return The LayoutParams associated with this view, or null if no 10316 * parameters have been set yet 10317 */ 10318 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 10319 public ViewGroup.LayoutParams getLayoutParams() { 10320 return mLayoutParams; 10321 } 10322 10323 /** 10324 * Set the layout parameters associated with this view. These supply 10325 * parameters to the <i>parent</i> of this view specifying how it should be 10326 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 10327 * correspond to the different subclasses of ViewGroup that are responsible 10328 * for arranging their children. 10329 * 10330 * @param params The layout parameters for this view, cannot be null 10331 */ 10332 public void setLayoutParams(ViewGroup.LayoutParams params) { 10333 if (params == null) { 10334 throw new NullPointerException("Layout parameters cannot be null"); 10335 } 10336 mLayoutParams = params; 10337 resolveLayoutParams(); 10338 if (mParent instanceof ViewGroup) { 10339 ((ViewGroup) mParent).onSetLayoutParams(this, params); 10340 } 10341 requestLayout(); 10342 } 10343 10344 /** 10345 * Resolve the layout parameters depending on the resolved layout direction 10346 * 10347 * @hide 10348 */ 10349 public void resolveLayoutParams() { 10350 if (mLayoutParams != null) { 10351 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 10352 } 10353 } 10354 10355 /** 10356 * Set the scrolled position of your view. This will cause a call to 10357 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10358 * invalidated. 10359 * @param x the x position to scroll to 10360 * @param y the y position to scroll to 10361 */ 10362 public void scrollTo(int x, int y) { 10363 if (mScrollX != x || mScrollY != y) { 10364 int oldX = mScrollX; 10365 int oldY = mScrollY; 10366 mScrollX = x; 10367 mScrollY = y; 10368 invalidateParentCaches(); 10369 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 10370 if (!awakenScrollBars()) { 10371 postInvalidateOnAnimation(); 10372 } 10373 } 10374 } 10375 10376 /** 10377 * Move the scrolled position of your view. This will cause a call to 10378 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10379 * invalidated. 10380 * @param x the amount of pixels to scroll by horizontally 10381 * @param y the amount of pixels to scroll by vertically 10382 */ 10383 public void scrollBy(int x, int y) { 10384 scrollTo(mScrollX + x, mScrollY + y); 10385 } 10386 10387 /** 10388 * <p>Trigger the scrollbars to draw. When invoked this method starts an 10389 * animation to fade the scrollbars out after a default delay. If a subclass 10390 * provides animated scrolling, the start delay should equal the duration 10391 * of the scrolling animation.</p> 10392 * 10393 * <p>The animation starts only if at least one of the scrollbars is 10394 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 10395 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10396 * this method returns true, and false otherwise. If the animation is 10397 * started, this method calls {@link #invalidate()}; in that case the 10398 * caller should not call {@link #invalidate()}.</p> 10399 * 10400 * <p>This method should be invoked every time a subclass directly updates 10401 * the scroll parameters.</p> 10402 * 10403 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 10404 * and {@link #scrollTo(int, int)}.</p> 10405 * 10406 * @return true if the animation is played, false otherwise 10407 * 10408 * @see #awakenScrollBars(int) 10409 * @see #scrollBy(int, int) 10410 * @see #scrollTo(int, int) 10411 * @see #isHorizontalScrollBarEnabled() 10412 * @see #isVerticalScrollBarEnabled() 10413 * @see #setHorizontalScrollBarEnabled(boolean) 10414 * @see #setVerticalScrollBarEnabled(boolean) 10415 */ 10416 protected boolean awakenScrollBars() { 10417 return mScrollCache != null && 10418 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 10419 } 10420 10421 /** 10422 * Trigger the scrollbars to draw. 10423 * This method differs from awakenScrollBars() only in its default duration. 10424 * initialAwakenScrollBars() will show the scroll bars for longer than 10425 * usual to give the user more of a chance to notice them. 10426 * 10427 * @return true if the animation is played, false otherwise. 10428 */ 10429 private boolean initialAwakenScrollBars() { 10430 return mScrollCache != null && 10431 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 10432 } 10433 10434 /** 10435 * <p> 10436 * Trigger the scrollbars to draw. When invoked this method starts an 10437 * animation to fade the scrollbars out after a fixed delay. If a subclass 10438 * provides animated scrolling, the start delay should equal the duration of 10439 * the scrolling animation. 10440 * </p> 10441 * 10442 * <p> 10443 * The animation starts only if at least one of the scrollbars is enabled, 10444 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10445 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10446 * this method returns true, and false otherwise. If the animation is 10447 * started, this method calls {@link #invalidate()}; in that case the caller 10448 * should not call {@link #invalidate()}. 10449 * </p> 10450 * 10451 * <p> 10452 * This method should be invoked everytime a subclass directly updates the 10453 * scroll parameters. 10454 * </p> 10455 * 10456 * @param startDelay the delay, in milliseconds, after which the animation 10457 * should start; when the delay is 0, the animation starts 10458 * immediately 10459 * @return true if the animation is played, false otherwise 10460 * 10461 * @see #scrollBy(int, int) 10462 * @see #scrollTo(int, int) 10463 * @see #isHorizontalScrollBarEnabled() 10464 * @see #isVerticalScrollBarEnabled() 10465 * @see #setHorizontalScrollBarEnabled(boolean) 10466 * @see #setVerticalScrollBarEnabled(boolean) 10467 */ 10468 protected boolean awakenScrollBars(int startDelay) { 10469 return awakenScrollBars(startDelay, true); 10470 } 10471 10472 /** 10473 * <p> 10474 * Trigger the scrollbars to draw. When invoked this method starts an 10475 * animation to fade the scrollbars out after a fixed delay. If a subclass 10476 * provides animated scrolling, the start delay should equal the duration of 10477 * the scrolling animation. 10478 * </p> 10479 * 10480 * <p> 10481 * The animation starts only if at least one of the scrollbars is enabled, 10482 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10483 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10484 * this method returns true, and false otherwise. If the animation is 10485 * started, this method calls {@link #invalidate()} if the invalidate parameter 10486 * is set to true; in that case the caller 10487 * should not call {@link #invalidate()}. 10488 * </p> 10489 * 10490 * <p> 10491 * This method should be invoked everytime a subclass directly updates the 10492 * scroll parameters. 10493 * </p> 10494 * 10495 * @param startDelay the delay, in milliseconds, after which the animation 10496 * should start; when the delay is 0, the animation starts 10497 * immediately 10498 * 10499 * @param invalidate Wheter this method should call invalidate 10500 * 10501 * @return true if the animation is played, false otherwise 10502 * 10503 * @see #scrollBy(int, int) 10504 * @see #scrollTo(int, int) 10505 * @see #isHorizontalScrollBarEnabled() 10506 * @see #isVerticalScrollBarEnabled() 10507 * @see #setHorizontalScrollBarEnabled(boolean) 10508 * @see #setVerticalScrollBarEnabled(boolean) 10509 */ 10510 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 10511 final ScrollabilityCache scrollCache = mScrollCache; 10512 10513 if (scrollCache == null || !scrollCache.fadeScrollBars) { 10514 return false; 10515 } 10516 10517 if (scrollCache.scrollBar == null) { 10518 scrollCache.scrollBar = new ScrollBarDrawable(); 10519 } 10520 10521 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 10522 10523 if (invalidate) { 10524 // Invalidate to show the scrollbars 10525 postInvalidateOnAnimation(); 10526 } 10527 10528 if (scrollCache.state == ScrollabilityCache.OFF) { 10529 // FIXME: this is copied from WindowManagerService. 10530 // We should get this value from the system when it 10531 // is possible to do so. 10532 final int KEY_REPEAT_FIRST_DELAY = 750; 10533 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 10534 } 10535 10536 // Tell mScrollCache when we should start fading. This may 10537 // extend the fade start time if one was already scheduled 10538 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 10539 scrollCache.fadeStartTime = fadeStartTime; 10540 scrollCache.state = ScrollabilityCache.ON; 10541 10542 // Schedule our fader to run, unscheduling any old ones first 10543 if (mAttachInfo != null) { 10544 mAttachInfo.mHandler.removeCallbacks(scrollCache); 10545 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 10546 } 10547 10548 return true; 10549 } 10550 10551 return false; 10552 } 10553 10554 /** 10555 * Do not invalidate views which are not visible and which are not running an animation. They 10556 * will not get drawn and they should not set dirty flags as if they will be drawn 10557 */ 10558 private boolean skipInvalidate() { 10559 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 10560 (!(mParent instanceof ViewGroup) || 10561 !((ViewGroup) mParent).isViewTransitioning(this)); 10562 } 10563 /** 10564 * Mark the area defined by dirty as needing to be drawn. If the view is 10565 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 10566 * in the future. This must be called from a UI thread. To call from a non-UI 10567 * thread, call {@link #postInvalidate()}. 10568 * 10569 * WARNING: This method is destructive to dirty. 10570 * @param dirty the rectangle representing the bounds of the dirty region 10571 */ 10572 public void invalidate(Rect dirty) { 10573 if (skipInvalidate()) { 10574 return; 10575 } 10576 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10577 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10578 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10579 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10580 mPrivateFlags |= PFLAG_INVALIDATED; 10581 mPrivateFlags |= PFLAG_DIRTY; 10582 final ViewParent p = mParent; 10583 final AttachInfo ai = mAttachInfo; 10584 //noinspection PointlessBooleanExpression,ConstantConditions 10585 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10586 if (p != null && ai != null && ai.mHardwareAccelerated) { 10587 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10588 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10589 p.invalidateChild(this, null); 10590 return; 10591 } 10592 } 10593 if (p != null && ai != null) { 10594 final int scrollX = mScrollX; 10595 final int scrollY = mScrollY; 10596 final Rect r = ai.mTmpInvalRect; 10597 r.set(dirty.left - scrollX, dirty.top - scrollY, 10598 dirty.right - scrollX, dirty.bottom - scrollY); 10599 mParent.invalidateChild(this, r); 10600 } 10601 } 10602 } 10603 10604 /** 10605 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 10606 * The coordinates of the dirty rect are relative to the view. 10607 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 10608 * will be called at some point in the future. This must be called from 10609 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 10610 * @param l the left position of the dirty region 10611 * @param t the top position of the dirty region 10612 * @param r the right position of the dirty region 10613 * @param b the bottom position of the dirty region 10614 */ 10615 public void invalidate(int l, int t, int r, int b) { 10616 if (skipInvalidate()) { 10617 return; 10618 } 10619 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10620 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10621 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10622 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10623 mPrivateFlags |= PFLAG_INVALIDATED; 10624 mPrivateFlags |= PFLAG_DIRTY; 10625 final ViewParent p = mParent; 10626 final AttachInfo ai = mAttachInfo; 10627 //noinspection PointlessBooleanExpression,ConstantConditions 10628 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10629 if (p != null && ai != null && ai.mHardwareAccelerated) { 10630 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10631 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10632 p.invalidateChild(this, null); 10633 return; 10634 } 10635 } 10636 if (p != null && ai != null && l < r && t < b) { 10637 final int scrollX = mScrollX; 10638 final int scrollY = mScrollY; 10639 final Rect tmpr = ai.mTmpInvalRect; 10640 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 10641 p.invalidateChild(this, tmpr); 10642 } 10643 } 10644 } 10645 10646 /** 10647 * Invalidate the whole view. If the view is visible, 10648 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 10649 * the future. This must be called from a UI thread. To call from a non-UI thread, 10650 * call {@link #postInvalidate()}. 10651 */ 10652 public void invalidate() { 10653 invalidate(true); 10654 } 10655 10656 /** 10657 * This is where the invalidate() work actually happens. A full invalidate() 10658 * causes the drawing cache to be invalidated, but this function can be called with 10659 * invalidateCache set to false to skip that invalidation step for cases that do not 10660 * need it (for example, a component that remains at the same dimensions with the same 10661 * content). 10662 * 10663 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 10664 * well. This is usually true for a full invalidate, but may be set to false if the 10665 * View's contents or dimensions have not changed. 10666 */ 10667 void invalidate(boolean invalidateCache) { 10668 if (skipInvalidate()) { 10669 return; 10670 } 10671 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10672 (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) || 10673 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) { 10674 mLastIsOpaque = isOpaque(); 10675 mPrivateFlags &= ~PFLAG_DRAWN; 10676 mPrivateFlags |= PFLAG_DIRTY; 10677 if (invalidateCache) { 10678 mPrivateFlags |= PFLAG_INVALIDATED; 10679 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10680 } 10681 final AttachInfo ai = mAttachInfo; 10682 final ViewParent p = mParent; 10683 //noinspection PointlessBooleanExpression,ConstantConditions 10684 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10685 if (p != null && ai != null && ai.mHardwareAccelerated) { 10686 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10687 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10688 p.invalidateChild(this, null); 10689 return; 10690 } 10691 } 10692 10693 if (p != null && ai != null) { 10694 final Rect r = ai.mTmpInvalRect; 10695 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10696 // Don't call invalidate -- we don't want to internally scroll 10697 // our own bounds 10698 p.invalidateChild(this, r); 10699 } 10700 } 10701 } 10702 10703 /** 10704 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 10705 * set any flags or handle all of the cases handled by the default invalidation methods. 10706 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 10707 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 10708 * walk up the hierarchy, transforming the dirty rect as necessary. 10709 * 10710 * The method also handles normal invalidation logic if display list properties are not 10711 * being used in this view. The invalidateParent and forceRedraw flags are used by that 10712 * backup approach, to handle these cases used in the various property-setting methods. 10713 * 10714 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 10715 * are not being used in this view 10716 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 10717 * list properties are not being used in this view 10718 */ 10719 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 10720 if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) { 10721 if (invalidateParent) { 10722 invalidateParentCaches(); 10723 } 10724 if (forceRedraw) { 10725 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10726 } 10727 invalidate(false); 10728 } else { 10729 final AttachInfo ai = mAttachInfo; 10730 final ViewParent p = mParent; 10731 if (p != null && ai != null) { 10732 final Rect r = ai.mTmpInvalRect; 10733 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10734 if (mParent instanceof ViewGroup) { 10735 ((ViewGroup) mParent).invalidateChildFast(this, r); 10736 } else { 10737 mParent.invalidateChild(this, r); 10738 } 10739 } 10740 } 10741 } 10742 10743 /** 10744 * Utility method to transform a given Rect by the current matrix of this view. 10745 */ 10746 void transformRect(final Rect rect) { 10747 if (!getMatrix().isIdentity()) { 10748 RectF boundingRect = mAttachInfo.mTmpTransformRect; 10749 boundingRect.set(rect); 10750 getMatrix().mapRect(boundingRect); 10751 rect.set((int) Math.floor(boundingRect.left), 10752 (int) Math.floor(boundingRect.top), 10753 (int) Math.ceil(boundingRect.right), 10754 (int) Math.ceil(boundingRect.bottom)); 10755 } 10756 } 10757 10758 /** 10759 * Used to indicate that the parent of this view should clear its caches. This functionality 10760 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10761 * which is necessary when various parent-managed properties of the view change, such as 10762 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 10763 * clears the parent caches and does not causes an invalidate event. 10764 * 10765 * @hide 10766 */ 10767 protected void invalidateParentCaches() { 10768 if (mParent instanceof View) { 10769 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 10770 } 10771 } 10772 10773 /** 10774 * Used to indicate that the parent of this view should be invalidated. This functionality 10775 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10776 * which is necessary when various parent-managed properties of the view change, such as 10777 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 10778 * an invalidation event to the parent. 10779 * 10780 * @hide 10781 */ 10782 protected void invalidateParentIfNeeded() { 10783 if (isHardwareAccelerated() && mParent instanceof View) { 10784 ((View) mParent).invalidate(true); 10785 } 10786 } 10787 10788 /** 10789 * Indicates whether this View is opaque. An opaque View guarantees that it will 10790 * draw all the pixels overlapping its bounds using a fully opaque color. 10791 * 10792 * Subclasses of View should override this method whenever possible to indicate 10793 * whether an instance is opaque. Opaque Views are treated in a special way by 10794 * the View hierarchy, possibly allowing it to perform optimizations during 10795 * invalidate/draw passes. 10796 * 10797 * @return True if this View is guaranteed to be fully opaque, false otherwise. 10798 */ 10799 @ViewDebug.ExportedProperty(category = "drawing") 10800 public boolean isOpaque() { 10801 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 10802 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f); 10803 } 10804 10805 /** 10806 * @hide 10807 */ 10808 protected void computeOpaqueFlags() { 10809 // Opaque if: 10810 // - Has a background 10811 // - Background is opaque 10812 // - Doesn't have scrollbars or scrollbars overlay 10813 10814 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 10815 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 10816 } else { 10817 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 10818 } 10819 10820 final int flags = mViewFlags; 10821 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 10822 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 10823 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 10824 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 10825 } else { 10826 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 10827 } 10828 } 10829 10830 /** 10831 * @hide 10832 */ 10833 protected boolean hasOpaqueScrollbars() { 10834 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 10835 } 10836 10837 /** 10838 * @return A handler associated with the thread running the View. This 10839 * handler can be used to pump events in the UI events queue. 10840 */ 10841 public Handler getHandler() { 10842 final AttachInfo attachInfo = mAttachInfo; 10843 if (attachInfo != null) { 10844 return attachInfo.mHandler; 10845 } 10846 return null; 10847 } 10848 10849 /** 10850 * Gets the view root associated with the View. 10851 * @return The view root, or null if none. 10852 * @hide 10853 */ 10854 public ViewRootImpl getViewRootImpl() { 10855 if (mAttachInfo != null) { 10856 return mAttachInfo.mViewRootImpl; 10857 } 10858 return null; 10859 } 10860 10861 /** 10862 * <p>Causes the Runnable to be added to the message queue. 10863 * The runnable will be run on the user interface thread.</p> 10864 * 10865 * @param action The Runnable that will be executed. 10866 * 10867 * @return Returns true if the Runnable was successfully placed in to the 10868 * message queue. Returns false on failure, usually because the 10869 * looper processing the message queue is exiting. 10870 * 10871 * @see #postDelayed 10872 * @see #removeCallbacks 10873 */ 10874 public boolean post(Runnable action) { 10875 final AttachInfo attachInfo = mAttachInfo; 10876 if (attachInfo != null) { 10877 return attachInfo.mHandler.post(action); 10878 } 10879 // Assume that post will succeed later 10880 ViewRootImpl.getRunQueue().post(action); 10881 return true; 10882 } 10883 10884 /** 10885 * <p>Causes the Runnable to be added to the message queue, to be run 10886 * after the specified amount of time elapses. 10887 * The runnable will be run on the user interface thread.</p> 10888 * 10889 * @param action The Runnable that will be executed. 10890 * @param delayMillis The delay (in milliseconds) until the Runnable 10891 * will be executed. 10892 * 10893 * @return true if the Runnable was successfully placed in to the 10894 * message queue. Returns false on failure, usually because the 10895 * looper processing the message queue is exiting. Note that a 10896 * result of true does not mean the Runnable will be processed -- 10897 * if the looper is quit before the delivery time of the message 10898 * occurs then the message will be dropped. 10899 * 10900 * @see #post 10901 * @see #removeCallbacks 10902 */ 10903 public boolean postDelayed(Runnable action, long delayMillis) { 10904 final AttachInfo attachInfo = mAttachInfo; 10905 if (attachInfo != null) { 10906 return attachInfo.mHandler.postDelayed(action, delayMillis); 10907 } 10908 // Assume that post will succeed later 10909 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10910 return true; 10911 } 10912 10913 /** 10914 * <p>Causes the Runnable to execute on the next animation time step. 10915 * The runnable will be run on the user interface thread.</p> 10916 * 10917 * @param action The Runnable that will be executed. 10918 * 10919 * @see #postOnAnimationDelayed 10920 * @see #removeCallbacks 10921 */ 10922 public void postOnAnimation(Runnable action) { 10923 final AttachInfo attachInfo = mAttachInfo; 10924 if (attachInfo != null) { 10925 attachInfo.mViewRootImpl.mChoreographer.postCallback( 10926 Choreographer.CALLBACK_ANIMATION, action, null); 10927 } else { 10928 // Assume that post will succeed later 10929 ViewRootImpl.getRunQueue().post(action); 10930 } 10931 } 10932 10933 /** 10934 * <p>Causes the Runnable to execute on the next animation time step, 10935 * after the specified amount of time elapses. 10936 * The runnable will be run on the user interface thread.</p> 10937 * 10938 * @param action The Runnable that will be executed. 10939 * @param delayMillis The delay (in milliseconds) until the Runnable 10940 * will be executed. 10941 * 10942 * @see #postOnAnimation 10943 * @see #removeCallbacks 10944 */ 10945 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 10946 final AttachInfo attachInfo = mAttachInfo; 10947 if (attachInfo != null) { 10948 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 10949 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 10950 } else { 10951 // Assume that post will succeed later 10952 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10953 } 10954 } 10955 10956 /** 10957 * <p>Removes the specified Runnable from the message queue.</p> 10958 * 10959 * @param action The Runnable to remove from the message handling queue 10960 * 10961 * @return true if this view could ask the Handler to remove the Runnable, 10962 * false otherwise. When the returned value is true, the Runnable 10963 * may or may not have been actually removed from the message queue 10964 * (for instance, if the Runnable was not in the queue already.) 10965 * 10966 * @see #post 10967 * @see #postDelayed 10968 * @see #postOnAnimation 10969 * @see #postOnAnimationDelayed 10970 */ 10971 public boolean removeCallbacks(Runnable action) { 10972 if (action != null) { 10973 final AttachInfo attachInfo = mAttachInfo; 10974 if (attachInfo != null) { 10975 attachInfo.mHandler.removeCallbacks(action); 10976 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 10977 Choreographer.CALLBACK_ANIMATION, action, null); 10978 } else { 10979 // Assume that post will succeed later 10980 ViewRootImpl.getRunQueue().removeCallbacks(action); 10981 } 10982 } 10983 return true; 10984 } 10985 10986 /** 10987 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 10988 * Use this to invalidate the View from a non-UI thread.</p> 10989 * 10990 * <p>This method can be invoked from outside of the UI thread 10991 * only when this View is attached to a window.</p> 10992 * 10993 * @see #invalidate() 10994 * @see #postInvalidateDelayed(long) 10995 */ 10996 public void postInvalidate() { 10997 postInvalidateDelayed(0); 10998 } 10999 11000 /** 11001 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11002 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11003 * 11004 * <p>This method can be invoked from outside of the UI thread 11005 * only when this View is attached to a window.</p> 11006 * 11007 * @param left The left coordinate of the rectangle to invalidate. 11008 * @param top The top coordinate of the rectangle to invalidate. 11009 * @param right The right coordinate of the rectangle to invalidate. 11010 * @param bottom The bottom coordinate of the rectangle to invalidate. 11011 * 11012 * @see #invalidate(int, int, int, int) 11013 * @see #invalidate(Rect) 11014 * @see #postInvalidateDelayed(long, int, int, int, int) 11015 */ 11016 public void postInvalidate(int left, int top, int right, int bottom) { 11017 postInvalidateDelayed(0, left, top, right, bottom); 11018 } 11019 11020 /** 11021 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11022 * loop. Waits for the specified amount of time.</p> 11023 * 11024 * <p>This method can be invoked from outside of the UI thread 11025 * only when this View is attached to a window.</p> 11026 * 11027 * @param delayMilliseconds the duration in milliseconds to delay the 11028 * invalidation by 11029 * 11030 * @see #invalidate() 11031 * @see #postInvalidate() 11032 */ 11033 public void postInvalidateDelayed(long delayMilliseconds) { 11034 // We try only with the AttachInfo because there's no point in invalidating 11035 // if we are not attached to our window 11036 final AttachInfo attachInfo = mAttachInfo; 11037 if (attachInfo != null) { 11038 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11039 } 11040 } 11041 11042 /** 11043 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11044 * through the event loop. Waits for the specified amount of time.</p> 11045 * 11046 * <p>This method can be invoked from outside of the UI thread 11047 * only when this View is attached to a window.</p> 11048 * 11049 * @param delayMilliseconds the duration in milliseconds to delay the 11050 * invalidation by 11051 * @param left The left coordinate of the rectangle to invalidate. 11052 * @param top The top coordinate of the rectangle to invalidate. 11053 * @param right The right coordinate of the rectangle to invalidate. 11054 * @param bottom The bottom coordinate of the rectangle to invalidate. 11055 * 11056 * @see #invalidate(int, int, int, int) 11057 * @see #invalidate(Rect) 11058 * @see #postInvalidate(int, int, int, int) 11059 */ 11060 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11061 int right, int bottom) { 11062 11063 // We try only with the AttachInfo because there's no point in invalidating 11064 // if we are not attached to our window 11065 final AttachInfo attachInfo = mAttachInfo; 11066 if (attachInfo != null) { 11067 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11068 info.target = this; 11069 info.left = left; 11070 info.top = top; 11071 info.right = right; 11072 info.bottom = bottom; 11073 11074 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11075 } 11076 } 11077 11078 /** 11079 * <p>Cause an invalidate to happen on the next animation time step, typically the 11080 * next display frame.</p> 11081 * 11082 * <p>This method can be invoked from outside of the UI thread 11083 * only when this View is attached to a window.</p> 11084 * 11085 * @see #invalidate() 11086 */ 11087 public void postInvalidateOnAnimation() { 11088 // We try only with the AttachInfo because there's no point in invalidating 11089 // if we are not attached to our window 11090 final AttachInfo attachInfo = mAttachInfo; 11091 if (attachInfo != null) { 11092 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11093 } 11094 } 11095 11096 /** 11097 * <p>Cause an invalidate of the specified area to happen on the next animation 11098 * time step, typically the next display frame.</p> 11099 * 11100 * <p>This method can be invoked from outside of the UI thread 11101 * only when this View is attached to a window.</p> 11102 * 11103 * @param left The left coordinate of the rectangle to invalidate. 11104 * @param top The top coordinate of the rectangle to invalidate. 11105 * @param right The right coordinate of the rectangle to invalidate. 11106 * @param bottom The bottom coordinate of the rectangle to invalidate. 11107 * 11108 * @see #invalidate(int, int, int, int) 11109 * @see #invalidate(Rect) 11110 */ 11111 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11112 // We try only with the AttachInfo because there's no point in invalidating 11113 // if we are not attached to our window 11114 final AttachInfo attachInfo = mAttachInfo; 11115 if (attachInfo != null) { 11116 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11117 info.target = this; 11118 info.left = left; 11119 info.top = top; 11120 info.right = right; 11121 info.bottom = bottom; 11122 11123 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11124 } 11125 } 11126 11127 /** 11128 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11129 * This event is sent at most once every 11130 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11131 */ 11132 private void postSendViewScrolledAccessibilityEventCallback() { 11133 if (mSendViewScrolledAccessibilityEvent == null) { 11134 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11135 } 11136 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11137 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11138 postDelayed(mSendViewScrolledAccessibilityEvent, 11139 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11140 } 11141 } 11142 11143 /** 11144 * Called by a parent to request that a child update its values for mScrollX 11145 * and mScrollY if necessary. This will typically be done if the child is 11146 * animating a scroll using a {@link android.widget.Scroller Scroller} 11147 * object. 11148 */ 11149 public void computeScroll() { 11150 } 11151 11152 /** 11153 * <p>Indicate whether the horizontal edges are faded when the view is 11154 * scrolled horizontally.</p> 11155 * 11156 * @return true if the horizontal edges should are faded on scroll, false 11157 * otherwise 11158 * 11159 * @see #setHorizontalFadingEdgeEnabled(boolean) 11160 * 11161 * @attr ref android.R.styleable#View_requiresFadingEdge 11162 */ 11163 public boolean isHorizontalFadingEdgeEnabled() { 11164 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11165 } 11166 11167 /** 11168 * <p>Define whether the horizontal edges should be faded when this view 11169 * is scrolled horizontally.</p> 11170 * 11171 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11172 * be faded when the view is scrolled 11173 * horizontally 11174 * 11175 * @see #isHorizontalFadingEdgeEnabled() 11176 * 11177 * @attr ref android.R.styleable#View_requiresFadingEdge 11178 */ 11179 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11180 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11181 if (horizontalFadingEdgeEnabled) { 11182 initScrollCache(); 11183 } 11184 11185 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11186 } 11187 } 11188 11189 /** 11190 * <p>Indicate whether the vertical edges are faded when the view is 11191 * scrolled horizontally.</p> 11192 * 11193 * @return true if the vertical edges should are faded on scroll, false 11194 * otherwise 11195 * 11196 * @see #setVerticalFadingEdgeEnabled(boolean) 11197 * 11198 * @attr ref android.R.styleable#View_requiresFadingEdge 11199 */ 11200 public boolean isVerticalFadingEdgeEnabled() { 11201 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11202 } 11203 11204 /** 11205 * <p>Define whether the vertical edges should be faded when this view 11206 * is scrolled vertically.</p> 11207 * 11208 * @param verticalFadingEdgeEnabled true if the vertical edges should 11209 * be faded when the view is scrolled 11210 * vertically 11211 * 11212 * @see #isVerticalFadingEdgeEnabled() 11213 * 11214 * @attr ref android.R.styleable#View_requiresFadingEdge 11215 */ 11216 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11217 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11218 if (verticalFadingEdgeEnabled) { 11219 initScrollCache(); 11220 } 11221 11222 mViewFlags ^= FADING_EDGE_VERTICAL; 11223 } 11224 } 11225 11226 /** 11227 * Returns the strength, or intensity, of the top faded edge. The strength is 11228 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11229 * returns 0.0 or 1.0 but no value in between. 11230 * 11231 * Subclasses should override this method to provide a smoother fade transition 11232 * when scrolling occurs. 11233 * 11234 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11235 */ 11236 protected float getTopFadingEdgeStrength() { 11237 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11238 } 11239 11240 /** 11241 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11242 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11243 * returns 0.0 or 1.0 but no value in between. 11244 * 11245 * Subclasses should override this method to provide a smoother fade transition 11246 * when scrolling occurs. 11247 * 11248 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11249 */ 11250 protected float getBottomFadingEdgeStrength() { 11251 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11252 computeVerticalScrollRange() ? 1.0f : 0.0f; 11253 } 11254 11255 /** 11256 * Returns the strength, or intensity, of the left faded edge. The strength is 11257 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11258 * returns 0.0 or 1.0 but no value in between. 11259 * 11260 * Subclasses should override this method to provide a smoother fade transition 11261 * when scrolling occurs. 11262 * 11263 * @return the intensity of the left fade as a float between 0.0f and 1.0f 11264 */ 11265 protected float getLeftFadingEdgeStrength() { 11266 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 11267 } 11268 11269 /** 11270 * Returns the strength, or intensity, of the right faded edge. The strength is 11271 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11272 * returns 0.0 or 1.0 but no value in between. 11273 * 11274 * Subclasses should override this method to provide a smoother fade transition 11275 * when scrolling occurs. 11276 * 11277 * @return the intensity of the right fade as a float between 0.0f and 1.0f 11278 */ 11279 protected float getRightFadingEdgeStrength() { 11280 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 11281 computeHorizontalScrollRange() ? 1.0f : 0.0f; 11282 } 11283 11284 /** 11285 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 11286 * scrollbar is not drawn by default.</p> 11287 * 11288 * @return true if the horizontal scrollbar should be painted, false 11289 * otherwise 11290 * 11291 * @see #setHorizontalScrollBarEnabled(boolean) 11292 */ 11293 public boolean isHorizontalScrollBarEnabled() { 11294 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11295 } 11296 11297 /** 11298 * <p>Define whether the horizontal scrollbar should be drawn or not. The 11299 * scrollbar is not drawn by default.</p> 11300 * 11301 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 11302 * be painted 11303 * 11304 * @see #isHorizontalScrollBarEnabled() 11305 */ 11306 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 11307 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 11308 mViewFlags ^= SCROLLBARS_HORIZONTAL; 11309 computeOpaqueFlags(); 11310 resolvePadding(); 11311 } 11312 } 11313 11314 /** 11315 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 11316 * scrollbar is not drawn by default.</p> 11317 * 11318 * @return true if the vertical scrollbar should be painted, false 11319 * otherwise 11320 * 11321 * @see #setVerticalScrollBarEnabled(boolean) 11322 */ 11323 public boolean isVerticalScrollBarEnabled() { 11324 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 11325 } 11326 11327 /** 11328 * <p>Define whether the vertical scrollbar should be drawn or not. The 11329 * scrollbar is not drawn by default.</p> 11330 * 11331 * @param verticalScrollBarEnabled true if the vertical scrollbar should 11332 * be painted 11333 * 11334 * @see #isVerticalScrollBarEnabled() 11335 */ 11336 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 11337 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 11338 mViewFlags ^= SCROLLBARS_VERTICAL; 11339 computeOpaqueFlags(); 11340 resolvePadding(); 11341 } 11342 } 11343 11344 /** 11345 * @hide 11346 */ 11347 protected void recomputePadding() { 11348 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 11349 } 11350 11351 /** 11352 * Define whether scrollbars will fade when the view is not scrolling. 11353 * 11354 * @param fadeScrollbars wheter to enable fading 11355 * 11356 * @attr ref android.R.styleable#View_fadeScrollbars 11357 */ 11358 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 11359 initScrollCache(); 11360 final ScrollabilityCache scrollabilityCache = mScrollCache; 11361 scrollabilityCache.fadeScrollBars = fadeScrollbars; 11362 if (fadeScrollbars) { 11363 scrollabilityCache.state = ScrollabilityCache.OFF; 11364 } else { 11365 scrollabilityCache.state = ScrollabilityCache.ON; 11366 } 11367 } 11368 11369 /** 11370 * 11371 * Returns true if scrollbars will fade when this view is not scrolling 11372 * 11373 * @return true if scrollbar fading is enabled 11374 * 11375 * @attr ref android.R.styleable#View_fadeScrollbars 11376 */ 11377 public boolean isScrollbarFadingEnabled() { 11378 return mScrollCache != null && mScrollCache.fadeScrollBars; 11379 } 11380 11381 /** 11382 * 11383 * Returns the delay before scrollbars fade. 11384 * 11385 * @return the delay before scrollbars fade 11386 * 11387 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11388 */ 11389 public int getScrollBarDefaultDelayBeforeFade() { 11390 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 11391 mScrollCache.scrollBarDefaultDelayBeforeFade; 11392 } 11393 11394 /** 11395 * Define the delay before scrollbars fade. 11396 * 11397 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 11398 * 11399 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11400 */ 11401 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 11402 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 11403 } 11404 11405 /** 11406 * 11407 * Returns the scrollbar fade duration. 11408 * 11409 * @return the scrollbar fade duration 11410 * 11411 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11412 */ 11413 public int getScrollBarFadeDuration() { 11414 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 11415 mScrollCache.scrollBarFadeDuration; 11416 } 11417 11418 /** 11419 * Define the scrollbar fade duration. 11420 * 11421 * @param scrollBarFadeDuration - the scrollbar fade duration 11422 * 11423 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11424 */ 11425 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 11426 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 11427 } 11428 11429 /** 11430 * 11431 * Returns the scrollbar size. 11432 * 11433 * @return the scrollbar size 11434 * 11435 * @attr ref android.R.styleable#View_scrollbarSize 11436 */ 11437 public int getScrollBarSize() { 11438 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 11439 mScrollCache.scrollBarSize; 11440 } 11441 11442 /** 11443 * Define the scrollbar size. 11444 * 11445 * @param scrollBarSize - the scrollbar size 11446 * 11447 * @attr ref android.R.styleable#View_scrollbarSize 11448 */ 11449 public void setScrollBarSize(int scrollBarSize) { 11450 getScrollCache().scrollBarSize = scrollBarSize; 11451 } 11452 11453 /** 11454 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 11455 * inset. When inset, they add to the padding of the view. And the scrollbars 11456 * can be drawn inside the padding area or on the edge of the view. For example, 11457 * if a view has a background drawable and you want to draw the scrollbars 11458 * inside the padding specified by the drawable, you can use 11459 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 11460 * appear at the edge of the view, ignoring the padding, then you can use 11461 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 11462 * @param style the style of the scrollbars. Should be one of 11463 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 11464 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 11465 * @see #SCROLLBARS_INSIDE_OVERLAY 11466 * @see #SCROLLBARS_INSIDE_INSET 11467 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11468 * @see #SCROLLBARS_OUTSIDE_INSET 11469 * 11470 * @attr ref android.R.styleable#View_scrollbarStyle 11471 */ 11472 public void setScrollBarStyle(int style) { 11473 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 11474 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 11475 computeOpaqueFlags(); 11476 resolvePadding(); 11477 } 11478 } 11479 11480 /** 11481 * <p>Returns the current scrollbar style.</p> 11482 * @return the current scrollbar style 11483 * @see #SCROLLBARS_INSIDE_OVERLAY 11484 * @see #SCROLLBARS_INSIDE_INSET 11485 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11486 * @see #SCROLLBARS_OUTSIDE_INSET 11487 * 11488 * @attr ref android.R.styleable#View_scrollbarStyle 11489 */ 11490 @ViewDebug.ExportedProperty(mapping = { 11491 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 11492 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 11493 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 11494 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 11495 }) 11496 public int getScrollBarStyle() { 11497 return mViewFlags & SCROLLBARS_STYLE_MASK; 11498 } 11499 11500 /** 11501 * <p>Compute the horizontal range that the horizontal scrollbar 11502 * represents.</p> 11503 * 11504 * <p>The range is expressed in arbitrary units that must be the same as the 11505 * units used by {@link #computeHorizontalScrollExtent()} and 11506 * {@link #computeHorizontalScrollOffset()}.</p> 11507 * 11508 * <p>The default range is the drawing width of this view.</p> 11509 * 11510 * @return the total horizontal range represented by the horizontal 11511 * scrollbar 11512 * 11513 * @see #computeHorizontalScrollExtent() 11514 * @see #computeHorizontalScrollOffset() 11515 * @see android.widget.ScrollBarDrawable 11516 */ 11517 protected int computeHorizontalScrollRange() { 11518 return getWidth(); 11519 } 11520 11521 /** 11522 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 11523 * within the horizontal range. This value is used to compute the position 11524 * of the thumb within the scrollbar's track.</p> 11525 * 11526 * <p>The range is expressed in arbitrary units that must be the same as the 11527 * units used by {@link #computeHorizontalScrollRange()} and 11528 * {@link #computeHorizontalScrollExtent()}.</p> 11529 * 11530 * <p>The default offset is the scroll offset of this view.</p> 11531 * 11532 * @return the horizontal offset of the scrollbar's thumb 11533 * 11534 * @see #computeHorizontalScrollRange() 11535 * @see #computeHorizontalScrollExtent() 11536 * @see android.widget.ScrollBarDrawable 11537 */ 11538 protected int computeHorizontalScrollOffset() { 11539 return mScrollX; 11540 } 11541 11542 /** 11543 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 11544 * within the horizontal range. This value is used to compute the length 11545 * of the thumb within the scrollbar's track.</p> 11546 * 11547 * <p>The range is expressed in arbitrary units that must be the same as the 11548 * units used by {@link #computeHorizontalScrollRange()} and 11549 * {@link #computeHorizontalScrollOffset()}.</p> 11550 * 11551 * <p>The default extent is the drawing width of this view.</p> 11552 * 11553 * @return the horizontal extent of the scrollbar's thumb 11554 * 11555 * @see #computeHorizontalScrollRange() 11556 * @see #computeHorizontalScrollOffset() 11557 * @see android.widget.ScrollBarDrawable 11558 */ 11559 protected int computeHorizontalScrollExtent() { 11560 return getWidth(); 11561 } 11562 11563 /** 11564 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 11565 * 11566 * <p>The range is expressed in arbitrary units that must be the same as the 11567 * units used by {@link #computeVerticalScrollExtent()} and 11568 * {@link #computeVerticalScrollOffset()}.</p> 11569 * 11570 * @return the total vertical range represented by the vertical scrollbar 11571 * 11572 * <p>The default range is the drawing height of this view.</p> 11573 * 11574 * @see #computeVerticalScrollExtent() 11575 * @see #computeVerticalScrollOffset() 11576 * @see android.widget.ScrollBarDrawable 11577 */ 11578 protected int computeVerticalScrollRange() { 11579 return getHeight(); 11580 } 11581 11582 /** 11583 * <p>Compute the vertical offset of the vertical scrollbar's thumb 11584 * within the horizontal range. This value is used to compute the position 11585 * of the thumb within the scrollbar's track.</p> 11586 * 11587 * <p>The range is expressed in arbitrary units that must be the same as the 11588 * units used by {@link #computeVerticalScrollRange()} and 11589 * {@link #computeVerticalScrollExtent()}.</p> 11590 * 11591 * <p>The default offset is the scroll offset of this view.</p> 11592 * 11593 * @return the vertical offset of the scrollbar's thumb 11594 * 11595 * @see #computeVerticalScrollRange() 11596 * @see #computeVerticalScrollExtent() 11597 * @see android.widget.ScrollBarDrawable 11598 */ 11599 protected int computeVerticalScrollOffset() { 11600 return mScrollY; 11601 } 11602 11603 /** 11604 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 11605 * within the vertical range. This value is used to compute the length 11606 * of the thumb within the scrollbar's track.</p> 11607 * 11608 * <p>The range is expressed in arbitrary units that must be the same as the 11609 * units used by {@link #computeVerticalScrollRange()} and 11610 * {@link #computeVerticalScrollOffset()}.</p> 11611 * 11612 * <p>The default extent is the drawing height of this view.</p> 11613 * 11614 * @return the vertical extent of the scrollbar's thumb 11615 * 11616 * @see #computeVerticalScrollRange() 11617 * @see #computeVerticalScrollOffset() 11618 * @see android.widget.ScrollBarDrawable 11619 */ 11620 protected int computeVerticalScrollExtent() { 11621 return getHeight(); 11622 } 11623 11624 /** 11625 * Check if this view can be scrolled horizontally in a certain direction. 11626 * 11627 * @param direction Negative to check scrolling left, positive to check scrolling right. 11628 * @return true if this view can be scrolled in the specified direction, false otherwise. 11629 */ 11630 public boolean canScrollHorizontally(int direction) { 11631 final int offset = computeHorizontalScrollOffset(); 11632 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 11633 if (range == 0) return false; 11634 if (direction < 0) { 11635 return offset > 0; 11636 } else { 11637 return offset < range - 1; 11638 } 11639 } 11640 11641 /** 11642 * Check if this view can be scrolled vertically in a certain direction. 11643 * 11644 * @param direction Negative to check scrolling up, positive to check scrolling down. 11645 * @return true if this view can be scrolled in the specified direction, false otherwise. 11646 */ 11647 public boolean canScrollVertically(int direction) { 11648 final int offset = computeVerticalScrollOffset(); 11649 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 11650 if (range == 0) return false; 11651 if (direction < 0) { 11652 return offset > 0; 11653 } else { 11654 return offset < range - 1; 11655 } 11656 } 11657 11658 /** 11659 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 11660 * scrollbars are painted only if they have been awakened first.</p> 11661 * 11662 * @param canvas the canvas on which to draw the scrollbars 11663 * 11664 * @see #awakenScrollBars(int) 11665 */ 11666 protected final void onDrawScrollBars(Canvas canvas) { 11667 // scrollbars are drawn only when the animation is running 11668 final ScrollabilityCache cache = mScrollCache; 11669 if (cache != null) { 11670 11671 int state = cache.state; 11672 11673 if (state == ScrollabilityCache.OFF) { 11674 return; 11675 } 11676 11677 boolean invalidate = false; 11678 11679 if (state == ScrollabilityCache.FADING) { 11680 // We're fading -- get our fade interpolation 11681 if (cache.interpolatorValues == null) { 11682 cache.interpolatorValues = new float[1]; 11683 } 11684 11685 float[] values = cache.interpolatorValues; 11686 11687 // Stops the animation if we're done 11688 if (cache.scrollBarInterpolator.timeToValues(values) == 11689 Interpolator.Result.FREEZE_END) { 11690 cache.state = ScrollabilityCache.OFF; 11691 } else { 11692 cache.scrollBar.setAlpha(Math.round(values[0])); 11693 } 11694 11695 // This will make the scroll bars inval themselves after 11696 // drawing. We only want this when we're fading so that 11697 // we prevent excessive redraws 11698 invalidate = true; 11699 } else { 11700 // We're just on -- but we may have been fading before so 11701 // reset alpha 11702 cache.scrollBar.setAlpha(255); 11703 } 11704 11705 11706 final int viewFlags = mViewFlags; 11707 11708 final boolean drawHorizontalScrollBar = 11709 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11710 final boolean drawVerticalScrollBar = 11711 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 11712 && !isVerticalScrollBarHidden(); 11713 11714 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 11715 final int width = mRight - mLeft; 11716 final int height = mBottom - mTop; 11717 11718 final ScrollBarDrawable scrollBar = cache.scrollBar; 11719 11720 final int scrollX = mScrollX; 11721 final int scrollY = mScrollY; 11722 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 11723 11724 int left; 11725 int top; 11726 int right; 11727 int bottom; 11728 11729 if (drawHorizontalScrollBar) { 11730 int size = scrollBar.getSize(false); 11731 if (size <= 0) { 11732 size = cache.scrollBarSize; 11733 } 11734 11735 scrollBar.setParameters(computeHorizontalScrollRange(), 11736 computeHorizontalScrollOffset(), 11737 computeHorizontalScrollExtent(), false); 11738 final int verticalScrollBarGap = drawVerticalScrollBar ? 11739 getVerticalScrollbarWidth() : 0; 11740 top = scrollY + height - size - (mUserPaddingBottom & inside); 11741 left = scrollX + (mPaddingLeft & inside); 11742 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 11743 bottom = top + size; 11744 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 11745 if (invalidate) { 11746 invalidate(left, top, right, bottom); 11747 } 11748 } 11749 11750 if (drawVerticalScrollBar) { 11751 int size = scrollBar.getSize(true); 11752 if (size <= 0) { 11753 size = cache.scrollBarSize; 11754 } 11755 11756 scrollBar.setParameters(computeVerticalScrollRange(), 11757 computeVerticalScrollOffset(), 11758 computeVerticalScrollExtent(), true); 11759 int verticalScrollbarPosition = mVerticalScrollbarPosition; 11760 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 11761 verticalScrollbarPosition = isLayoutRtl() ? 11762 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 11763 } 11764 switch (verticalScrollbarPosition) { 11765 default: 11766 case SCROLLBAR_POSITION_RIGHT: 11767 left = scrollX + width - size - (mUserPaddingRight & inside); 11768 break; 11769 case SCROLLBAR_POSITION_LEFT: 11770 left = scrollX + (mUserPaddingLeft & inside); 11771 break; 11772 } 11773 top = scrollY + (mPaddingTop & inside); 11774 right = left + size; 11775 bottom = scrollY + height - (mUserPaddingBottom & inside); 11776 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 11777 if (invalidate) { 11778 invalidate(left, top, right, bottom); 11779 } 11780 } 11781 } 11782 } 11783 } 11784 11785 /** 11786 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 11787 * FastScroller is visible. 11788 * @return whether to temporarily hide the vertical scrollbar 11789 * @hide 11790 */ 11791 protected boolean isVerticalScrollBarHidden() { 11792 return false; 11793 } 11794 11795 /** 11796 * <p>Draw the horizontal scrollbar if 11797 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 11798 * 11799 * @param canvas the canvas on which to draw the scrollbar 11800 * @param scrollBar the scrollbar's drawable 11801 * 11802 * @see #isHorizontalScrollBarEnabled() 11803 * @see #computeHorizontalScrollRange() 11804 * @see #computeHorizontalScrollExtent() 11805 * @see #computeHorizontalScrollOffset() 11806 * @see android.widget.ScrollBarDrawable 11807 * @hide 11808 */ 11809 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 11810 int l, int t, int r, int b) { 11811 scrollBar.setBounds(l, t, r, b); 11812 scrollBar.draw(canvas); 11813 } 11814 11815 /** 11816 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 11817 * returns true.</p> 11818 * 11819 * @param canvas the canvas on which to draw the scrollbar 11820 * @param scrollBar the scrollbar's drawable 11821 * 11822 * @see #isVerticalScrollBarEnabled() 11823 * @see #computeVerticalScrollRange() 11824 * @see #computeVerticalScrollExtent() 11825 * @see #computeVerticalScrollOffset() 11826 * @see android.widget.ScrollBarDrawable 11827 * @hide 11828 */ 11829 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 11830 int l, int t, int r, int b) { 11831 scrollBar.setBounds(l, t, r, b); 11832 scrollBar.draw(canvas); 11833 } 11834 11835 /** 11836 * Implement this to do your drawing. 11837 * 11838 * @param canvas the canvas on which the background will be drawn 11839 */ 11840 protected void onDraw(Canvas canvas) { 11841 } 11842 11843 /* 11844 * Caller is responsible for calling requestLayout if necessary. 11845 * (This allows addViewInLayout to not request a new layout.) 11846 */ 11847 void assignParent(ViewParent parent) { 11848 if (mParent == null) { 11849 mParent = parent; 11850 } else if (parent == null) { 11851 mParent = null; 11852 } else { 11853 throw new RuntimeException("view " + this + " being added, but" 11854 + " it already has a parent"); 11855 } 11856 } 11857 11858 /** 11859 * This is called when the view is attached to a window. At this point it 11860 * has a Surface and will start drawing. Note that this function is 11861 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 11862 * however it may be called any time before the first onDraw -- including 11863 * before or after {@link #onMeasure(int, int)}. 11864 * 11865 * @see #onDetachedFromWindow() 11866 */ 11867 protected void onAttachedToWindow() { 11868 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 11869 mParent.requestTransparentRegion(this); 11870 } 11871 11872 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 11873 initialAwakenScrollBars(); 11874 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 11875 } 11876 11877 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 11878 11879 jumpDrawablesToCurrentState(); 11880 11881 resetSubtreeAccessibilityStateChanged(); 11882 11883 if (isFocused()) { 11884 InputMethodManager imm = InputMethodManager.peekInstance(); 11885 imm.focusIn(this); 11886 } 11887 11888 if (mDisplayList != null) { 11889 mDisplayList.clearDirty(); 11890 } 11891 } 11892 11893 /** 11894 * Resolve all RTL related properties. 11895 * 11896 * @return true if resolution of RTL properties has been done 11897 * 11898 * @hide 11899 */ 11900 public boolean resolveRtlPropertiesIfNeeded() { 11901 if (!needRtlPropertiesResolution()) return false; 11902 11903 // Order is important here: LayoutDirection MUST be resolved first 11904 if (!isLayoutDirectionResolved()) { 11905 resolveLayoutDirection(); 11906 resolveLayoutParams(); 11907 } 11908 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 11909 if (!isTextDirectionResolved()) { 11910 resolveTextDirection(); 11911 } 11912 if (!isTextAlignmentResolved()) { 11913 resolveTextAlignment(); 11914 } 11915 if (!isPaddingResolved()) { 11916 resolvePadding(); 11917 } 11918 if (!isDrawablesResolved()) { 11919 resolveDrawables(); 11920 } 11921 onRtlPropertiesChanged(getLayoutDirection()); 11922 return true; 11923 } 11924 11925 /** 11926 * Reset resolution of all RTL related properties. 11927 * 11928 * @hide 11929 */ 11930 public void resetRtlProperties() { 11931 resetResolvedLayoutDirection(); 11932 resetResolvedTextDirection(); 11933 resetResolvedTextAlignment(); 11934 resetResolvedPadding(); 11935 resetResolvedDrawables(); 11936 } 11937 11938 /** 11939 * @see #onScreenStateChanged(int) 11940 */ 11941 void dispatchScreenStateChanged(int screenState) { 11942 onScreenStateChanged(screenState); 11943 } 11944 11945 /** 11946 * This method is called whenever the state of the screen this view is 11947 * attached to changes. A state change will usually occurs when the screen 11948 * turns on or off (whether it happens automatically or the user does it 11949 * manually.) 11950 * 11951 * @param screenState The new state of the screen. Can be either 11952 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 11953 */ 11954 public void onScreenStateChanged(int screenState) { 11955 } 11956 11957 /** 11958 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 11959 */ 11960 private boolean hasRtlSupport() { 11961 return mContext.getApplicationInfo().hasRtlSupport(); 11962 } 11963 11964 /** 11965 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 11966 * RTL not supported) 11967 */ 11968 private boolean isRtlCompatibilityMode() { 11969 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 11970 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 11971 } 11972 11973 /** 11974 * @return true if RTL properties need resolution. 11975 * 11976 */ 11977 private boolean needRtlPropertiesResolution() { 11978 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 11979 } 11980 11981 /** 11982 * Called when any RTL property (layout direction or text direction or text alignment) has 11983 * been changed. 11984 * 11985 * Subclasses need to override this method to take care of cached information that depends on the 11986 * resolved layout direction, or to inform child views that inherit their layout direction. 11987 * 11988 * The default implementation does nothing. 11989 * 11990 * @param layoutDirection the direction of the layout 11991 * 11992 * @see #LAYOUT_DIRECTION_LTR 11993 * @see #LAYOUT_DIRECTION_RTL 11994 */ 11995 public void onRtlPropertiesChanged(int layoutDirection) { 11996 } 11997 11998 /** 11999 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12000 * that the parent directionality can and will be resolved before its children. 12001 * 12002 * @return true if resolution has been done, false otherwise. 12003 * 12004 * @hide 12005 */ 12006 public boolean resolveLayoutDirection() { 12007 // Clear any previous layout direction resolution 12008 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12009 12010 if (hasRtlSupport()) { 12011 // Set resolved depending on layout direction 12012 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12013 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12014 case LAYOUT_DIRECTION_INHERIT: 12015 // We cannot resolve yet. LTR is by default and let the resolution happen again 12016 // later to get the correct resolved value 12017 if (!canResolveLayoutDirection()) return false; 12018 12019 // Parent has not yet resolved, LTR is still the default 12020 try { 12021 if (!mParent.isLayoutDirectionResolved()) return false; 12022 12023 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12024 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12025 } 12026 } catch (AbstractMethodError e) { 12027 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12028 " does not fully implement ViewParent", e); 12029 } 12030 break; 12031 case LAYOUT_DIRECTION_RTL: 12032 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12033 break; 12034 case LAYOUT_DIRECTION_LOCALE: 12035 if((LAYOUT_DIRECTION_RTL == 12036 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12037 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12038 } 12039 break; 12040 default: 12041 // Nothing to do, LTR by default 12042 } 12043 } 12044 12045 // Set to resolved 12046 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12047 return true; 12048 } 12049 12050 /** 12051 * Check if layout direction resolution can be done. 12052 * 12053 * @return true if layout direction resolution can be done otherwise return false. 12054 */ 12055 public boolean canResolveLayoutDirection() { 12056 switch (getRawLayoutDirection()) { 12057 case LAYOUT_DIRECTION_INHERIT: 12058 if (mParent != null) { 12059 try { 12060 return mParent.canResolveLayoutDirection(); 12061 } catch (AbstractMethodError e) { 12062 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12063 " does not fully implement ViewParent", e); 12064 } 12065 } 12066 return false; 12067 12068 default: 12069 return true; 12070 } 12071 } 12072 12073 /** 12074 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12075 * {@link #onMeasure(int, int)}. 12076 * 12077 * @hide 12078 */ 12079 public void resetResolvedLayoutDirection() { 12080 // Reset the current resolved bits 12081 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12082 } 12083 12084 /** 12085 * @return true if the layout direction is inherited. 12086 * 12087 * @hide 12088 */ 12089 public boolean isLayoutDirectionInherited() { 12090 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12091 } 12092 12093 /** 12094 * @return true if layout direction has been resolved. 12095 */ 12096 public boolean isLayoutDirectionResolved() { 12097 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12098 } 12099 12100 /** 12101 * Return if padding has been resolved 12102 * 12103 * @hide 12104 */ 12105 boolean isPaddingResolved() { 12106 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12107 } 12108 12109 /** 12110 * Resolves padding depending on layout direction, if applicable, and 12111 * recomputes internal padding values to adjust for scroll bars. 12112 * 12113 * @hide 12114 */ 12115 public void resolvePadding() { 12116 final int resolvedLayoutDirection = getLayoutDirection(); 12117 12118 if (!isRtlCompatibilityMode()) { 12119 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12120 // If start / end padding are defined, they will be resolved (hence overriding) to 12121 // left / right or right / left depending on the resolved layout direction. 12122 // If start / end padding are not defined, use the left / right ones. 12123 switch (resolvedLayoutDirection) { 12124 case LAYOUT_DIRECTION_RTL: 12125 if (mUserPaddingStart != UNDEFINED_PADDING) { 12126 mUserPaddingRight = mUserPaddingStart; 12127 } else { 12128 mUserPaddingRight = mUserPaddingRightInitial; 12129 } 12130 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12131 mUserPaddingLeft = mUserPaddingEnd; 12132 } else { 12133 mUserPaddingLeft = mUserPaddingLeftInitial; 12134 } 12135 break; 12136 case LAYOUT_DIRECTION_LTR: 12137 default: 12138 if (mUserPaddingStart != UNDEFINED_PADDING) { 12139 mUserPaddingLeft = mUserPaddingStart; 12140 } else { 12141 mUserPaddingLeft = mUserPaddingLeftInitial; 12142 } 12143 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12144 mUserPaddingRight = mUserPaddingEnd; 12145 } else { 12146 mUserPaddingRight = mUserPaddingRightInitial; 12147 } 12148 } 12149 12150 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12151 } 12152 12153 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12154 onRtlPropertiesChanged(resolvedLayoutDirection); 12155 12156 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12157 } 12158 12159 /** 12160 * Reset the resolved layout direction. 12161 * 12162 * @hide 12163 */ 12164 public void resetResolvedPadding() { 12165 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12166 } 12167 12168 /** 12169 * This is called when the view is detached from a window. At this point it 12170 * no longer has a surface for drawing. 12171 * 12172 * @see #onAttachedToWindow() 12173 */ 12174 protected void onDetachedFromWindow() { 12175 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12176 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12177 12178 removeUnsetPressCallback(); 12179 removeLongPressCallback(); 12180 removePerformClickCallback(); 12181 removeSendViewScrolledAccessibilityEventCallback(); 12182 12183 destroyDrawingCache(); 12184 destroyLayer(false); 12185 12186 cleanupDraw(); 12187 12188 mCurrentAnimation = null; 12189 } 12190 12191 private void cleanupDraw() { 12192 if (mAttachInfo != null) { 12193 if (mDisplayList != null) { 12194 mDisplayList.markDirty(); 12195 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList); 12196 } 12197 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12198 } else { 12199 // Should never happen 12200 resetDisplayList(); 12201 } 12202 } 12203 12204 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12205 } 12206 12207 /** 12208 * @return The number of times this view has been attached to a window 12209 */ 12210 protected int getWindowAttachCount() { 12211 return mWindowAttachCount; 12212 } 12213 12214 /** 12215 * Retrieve a unique token identifying the window this view is attached to. 12216 * @return Return the window's token for use in 12217 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 12218 */ 12219 public IBinder getWindowToken() { 12220 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 12221 } 12222 12223 /** 12224 * Retrieve the {@link WindowId} for the window this view is 12225 * currently attached to. 12226 */ 12227 public WindowId getWindowId() { 12228 if (mAttachInfo == null) { 12229 return null; 12230 } 12231 if (mAttachInfo.mWindowId == null) { 12232 try { 12233 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 12234 mAttachInfo.mWindowToken); 12235 mAttachInfo.mWindowId = new WindowId( 12236 mAttachInfo.mIWindowId); 12237 } catch (RemoteException e) { 12238 } 12239 } 12240 return mAttachInfo.mWindowId; 12241 } 12242 12243 /** 12244 * Retrieve a unique token identifying the top-level "real" window of 12245 * the window that this view is attached to. That is, this is like 12246 * {@link #getWindowToken}, except if the window this view in is a panel 12247 * window (attached to another containing window), then the token of 12248 * the containing window is returned instead. 12249 * 12250 * @return Returns the associated window token, either 12251 * {@link #getWindowToken()} or the containing window's token. 12252 */ 12253 public IBinder getApplicationWindowToken() { 12254 AttachInfo ai = mAttachInfo; 12255 if (ai != null) { 12256 IBinder appWindowToken = ai.mPanelParentWindowToken; 12257 if (appWindowToken == null) { 12258 appWindowToken = ai.mWindowToken; 12259 } 12260 return appWindowToken; 12261 } 12262 return null; 12263 } 12264 12265 /** 12266 * Gets the logical display to which the view's window has been attached. 12267 * 12268 * @return The logical display, or null if the view is not currently attached to a window. 12269 */ 12270 public Display getDisplay() { 12271 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 12272 } 12273 12274 /** 12275 * Retrieve private session object this view hierarchy is using to 12276 * communicate with the window manager. 12277 * @return the session object to communicate with the window manager 12278 */ 12279 /*package*/ IWindowSession getWindowSession() { 12280 return mAttachInfo != null ? mAttachInfo.mSession : null; 12281 } 12282 12283 /** 12284 * @param info the {@link android.view.View.AttachInfo} to associated with 12285 * this view 12286 */ 12287 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 12288 //System.out.println("Attached! " + this); 12289 mAttachInfo = info; 12290 if (mOverlay != null) { 12291 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 12292 } 12293 mWindowAttachCount++; 12294 // We will need to evaluate the drawable state at least once. 12295 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 12296 if (mFloatingTreeObserver != null) { 12297 info.mTreeObserver.merge(mFloatingTreeObserver); 12298 mFloatingTreeObserver = null; 12299 } 12300 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 12301 mAttachInfo.mScrollContainers.add(this); 12302 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 12303 } 12304 performCollectViewAttributes(mAttachInfo, visibility); 12305 onAttachedToWindow(); 12306 12307 ListenerInfo li = mListenerInfo; 12308 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12309 li != null ? li.mOnAttachStateChangeListeners : null; 12310 if (listeners != null && listeners.size() > 0) { 12311 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12312 // perform the dispatching. The iterator is a safe guard against listeners that 12313 // could mutate the list by calling the various add/remove methods. This prevents 12314 // the array from being modified while we iterate it. 12315 for (OnAttachStateChangeListener listener : listeners) { 12316 listener.onViewAttachedToWindow(this); 12317 } 12318 } 12319 12320 int vis = info.mWindowVisibility; 12321 if (vis != GONE) { 12322 onWindowVisibilityChanged(vis); 12323 } 12324 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 12325 // If nobody has evaluated the drawable state yet, then do it now. 12326 refreshDrawableState(); 12327 } 12328 needGlobalAttributesUpdate(false); 12329 } 12330 12331 void dispatchDetachedFromWindow() { 12332 AttachInfo info = mAttachInfo; 12333 if (info != null) { 12334 int vis = info.mWindowVisibility; 12335 if (vis != GONE) { 12336 onWindowVisibilityChanged(GONE); 12337 } 12338 } 12339 12340 onDetachedFromWindow(); 12341 12342 ListenerInfo li = mListenerInfo; 12343 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12344 li != null ? li.mOnAttachStateChangeListeners : null; 12345 if (listeners != null && listeners.size() > 0) { 12346 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12347 // perform the dispatching. The iterator is a safe guard against listeners that 12348 // could mutate the list by calling the various add/remove methods. This prevents 12349 // the array from being modified while we iterate it. 12350 for (OnAttachStateChangeListener listener : listeners) { 12351 listener.onViewDetachedFromWindow(this); 12352 } 12353 } 12354 12355 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 12356 mAttachInfo.mScrollContainers.remove(this); 12357 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 12358 } 12359 12360 mAttachInfo = null; 12361 if (mOverlay != null) { 12362 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 12363 } 12364 } 12365 12366 /** 12367 * Store this view hierarchy's frozen state into the given container. 12368 * 12369 * @param container The SparseArray in which to save the view's state. 12370 * 12371 * @see #restoreHierarchyState(android.util.SparseArray) 12372 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12373 * @see #onSaveInstanceState() 12374 */ 12375 public void saveHierarchyState(SparseArray<Parcelable> container) { 12376 dispatchSaveInstanceState(container); 12377 } 12378 12379 /** 12380 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 12381 * this view and its children. May be overridden to modify how freezing happens to a 12382 * view's children; for example, some views may want to not store state for their children. 12383 * 12384 * @param container The SparseArray in which to save the view's state. 12385 * 12386 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12387 * @see #saveHierarchyState(android.util.SparseArray) 12388 * @see #onSaveInstanceState() 12389 */ 12390 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 12391 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 12392 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 12393 Parcelable state = onSaveInstanceState(); 12394 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 12395 throw new IllegalStateException( 12396 "Derived class did not call super.onSaveInstanceState()"); 12397 } 12398 if (state != null) { 12399 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 12400 // + ": " + state); 12401 container.put(mID, state); 12402 } 12403 } 12404 } 12405 12406 /** 12407 * Hook allowing a view to generate a representation of its internal state 12408 * that can later be used to create a new instance with that same state. 12409 * This state should only contain information that is not persistent or can 12410 * not be reconstructed later. For example, you will never store your 12411 * current position on screen because that will be computed again when a 12412 * new instance of the view is placed in its view hierarchy. 12413 * <p> 12414 * Some examples of things you may store here: the current cursor position 12415 * in a text view (but usually not the text itself since that is stored in a 12416 * content provider or other persistent storage), the currently selected 12417 * item in a list view. 12418 * 12419 * @return Returns a Parcelable object containing the view's current dynamic 12420 * state, or null if there is nothing interesting to save. The 12421 * default implementation returns null. 12422 * @see #onRestoreInstanceState(android.os.Parcelable) 12423 * @see #saveHierarchyState(android.util.SparseArray) 12424 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12425 * @see #setSaveEnabled(boolean) 12426 */ 12427 protected Parcelable onSaveInstanceState() { 12428 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12429 return BaseSavedState.EMPTY_STATE; 12430 } 12431 12432 /** 12433 * Restore this view hierarchy's frozen state from the given container. 12434 * 12435 * @param container The SparseArray which holds previously frozen states. 12436 * 12437 * @see #saveHierarchyState(android.util.SparseArray) 12438 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12439 * @see #onRestoreInstanceState(android.os.Parcelable) 12440 */ 12441 public void restoreHierarchyState(SparseArray<Parcelable> container) { 12442 dispatchRestoreInstanceState(container); 12443 } 12444 12445 /** 12446 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 12447 * state for this view and its children. May be overridden to modify how restoring 12448 * happens to a view's children; for example, some views may want to not store state 12449 * for their children. 12450 * 12451 * @param container The SparseArray which holds previously saved state. 12452 * 12453 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12454 * @see #restoreHierarchyState(android.util.SparseArray) 12455 * @see #onRestoreInstanceState(android.os.Parcelable) 12456 */ 12457 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 12458 if (mID != NO_ID) { 12459 Parcelable state = container.get(mID); 12460 if (state != null) { 12461 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 12462 // + ": " + state); 12463 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 12464 onRestoreInstanceState(state); 12465 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 12466 throw new IllegalStateException( 12467 "Derived class did not call super.onRestoreInstanceState()"); 12468 } 12469 } 12470 } 12471 } 12472 12473 /** 12474 * Hook allowing a view to re-apply a representation of its internal state that had previously 12475 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 12476 * null state. 12477 * 12478 * @param state The frozen state that had previously been returned by 12479 * {@link #onSaveInstanceState}. 12480 * 12481 * @see #onSaveInstanceState() 12482 * @see #restoreHierarchyState(android.util.SparseArray) 12483 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12484 */ 12485 protected void onRestoreInstanceState(Parcelable state) { 12486 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12487 if (state != BaseSavedState.EMPTY_STATE && state != null) { 12488 throw new IllegalArgumentException("Wrong state class, expecting View State but " 12489 + "received " + state.getClass().toString() + " instead. This usually happens " 12490 + "when two views of different type have the same id in the same hierarchy. " 12491 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 12492 + "other views do not use the same id."); 12493 } 12494 } 12495 12496 /** 12497 * <p>Return the time at which the drawing of the view hierarchy started.</p> 12498 * 12499 * @return the drawing start time in milliseconds 12500 */ 12501 public long getDrawingTime() { 12502 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 12503 } 12504 12505 /** 12506 * <p>Enables or disables the duplication of the parent's state into this view. When 12507 * duplication is enabled, this view gets its drawable state from its parent rather 12508 * than from its own internal properties.</p> 12509 * 12510 * <p>Note: in the current implementation, setting this property to true after the 12511 * view was added to a ViewGroup might have no effect at all. This property should 12512 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 12513 * 12514 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 12515 * property is enabled, an exception will be thrown.</p> 12516 * 12517 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 12518 * parent, these states should not be affected by this method.</p> 12519 * 12520 * @param enabled True to enable duplication of the parent's drawable state, false 12521 * to disable it. 12522 * 12523 * @see #getDrawableState() 12524 * @see #isDuplicateParentStateEnabled() 12525 */ 12526 public void setDuplicateParentStateEnabled(boolean enabled) { 12527 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 12528 } 12529 12530 /** 12531 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 12532 * 12533 * @return True if this view's drawable state is duplicated from the parent, 12534 * false otherwise 12535 * 12536 * @see #getDrawableState() 12537 * @see #setDuplicateParentStateEnabled(boolean) 12538 */ 12539 public boolean isDuplicateParentStateEnabled() { 12540 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 12541 } 12542 12543 /** 12544 * <p>Specifies the type of layer backing this view. The layer can be 12545 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12546 * {@link #LAYER_TYPE_HARDWARE}.</p> 12547 * 12548 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12549 * instance that controls how the layer is composed on screen. The following 12550 * properties of the paint are taken into account when composing the layer:</p> 12551 * <ul> 12552 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12553 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12554 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12555 * </ul> 12556 * 12557 * <p>If this view has an alpha value set to < 1.0 by calling 12558 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 12559 * by this view's alpha value.</p> 12560 * 12561 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 12562 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 12563 * for more information on when and how to use layers.</p> 12564 * 12565 * @param layerType The type of layer to use with this view, must be one of 12566 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12567 * {@link #LAYER_TYPE_HARDWARE} 12568 * @param paint The paint used to compose the layer. This argument is optional 12569 * and can be null. It is ignored when the layer type is 12570 * {@link #LAYER_TYPE_NONE} 12571 * 12572 * @see #getLayerType() 12573 * @see #LAYER_TYPE_NONE 12574 * @see #LAYER_TYPE_SOFTWARE 12575 * @see #LAYER_TYPE_HARDWARE 12576 * @see #setAlpha(float) 12577 * 12578 * @attr ref android.R.styleable#View_layerType 12579 */ 12580 public void setLayerType(int layerType, Paint paint) { 12581 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 12582 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 12583 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 12584 } 12585 12586 if (layerType == mLayerType) { 12587 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 12588 mLayerPaint = paint == null ? new Paint() : paint; 12589 invalidateParentCaches(); 12590 invalidate(true); 12591 } 12592 return; 12593 } 12594 12595 // Destroy any previous software drawing cache if needed 12596 switch (mLayerType) { 12597 case LAYER_TYPE_HARDWARE: 12598 destroyLayer(false); 12599 // fall through - non-accelerated views may use software layer mechanism instead 12600 case LAYER_TYPE_SOFTWARE: 12601 destroyDrawingCache(); 12602 break; 12603 default: 12604 break; 12605 } 12606 12607 mLayerType = layerType; 12608 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 12609 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 12610 mLocalDirtyRect = layerDisabled ? null : new Rect(); 12611 12612 invalidateParentCaches(); 12613 invalidate(true); 12614 } 12615 12616 /** 12617 * Updates the {@link Paint} object used with the current layer (used only if the current 12618 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 12619 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 12620 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 12621 * ensure that the view gets redrawn immediately. 12622 * 12623 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12624 * instance that controls how the layer is composed on screen. The following 12625 * properties of the paint are taken into account when composing the layer:</p> 12626 * <ul> 12627 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12628 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12629 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12630 * </ul> 12631 * 12632 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 12633 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 12634 * 12635 * @param paint The paint used to compose the layer. This argument is optional 12636 * and can be null. It is ignored when the layer type is 12637 * {@link #LAYER_TYPE_NONE} 12638 * 12639 * @see #setLayerType(int, android.graphics.Paint) 12640 */ 12641 public void setLayerPaint(Paint paint) { 12642 int layerType = getLayerType(); 12643 if (layerType != LAYER_TYPE_NONE) { 12644 mLayerPaint = paint == null ? new Paint() : paint; 12645 if (layerType == LAYER_TYPE_HARDWARE) { 12646 HardwareLayer layer = getHardwareLayer(); 12647 if (layer != null) { 12648 layer.setLayerPaint(paint); 12649 } 12650 invalidateViewProperty(false, false); 12651 } else { 12652 invalidate(); 12653 } 12654 } 12655 } 12656 12657 /** 12658 * Indicates whether this view has a static layer. A view with layer type 12659 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 12660 * dynamic. 12661 */ 12662 boolean hasStaticLayer() { 12663 return true; 12664 } 12665 12666 /** 12667 * Indicates what type of layer is currently associated with this view. By default 12668 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 12669 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 12670 * for more information on the different types of layers. 12671 * 12672 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12673 * {@link #LAYER_TYPE_HARDWARE} 12674 * 12675 * @see #setLayerType(int, android.graphics.Paint) 12676 * @see #buildLayer() 12677 * @see #LAYER_TYPE_NONE 12678 * @see #LAYER_TYPE_SOFTWARE 12679 * @see #LAYER_TYPE_HARDWARE 12680 */ 12681 public int getLayerType() { 12682 return mLayerType; 12683 } 12684 12685 /** 12686 * Forces this view's layer to be created and this view to be rendered 12687 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 12688 * invoking this method will have no effect. 12689 * 12690 * This method can for instance be used to render a view into its layer before 12691 * starting an animation. If this view is complex, rendering into the layer 12692 * before starting the animation will avoid skipping frames. 12693 * 12694 * @throws IllegalStateException If this view is not attached to a window 12695 * 12696 * @see #setLayerType(int, android.graphics.Paint) 12697 */ 12698 public void buildLayer() { 12699 if (mLayerType == LAYER_TYPE_NONE) return; 12700 12701 final AttachInfo attachInfo = mAttachInfo; 12702 if (attachInfo == null) { 12703 throw new IllegalStateException("This view must be attached to a window first"); 12704 } 12705 12706 switch (mLayerType) { 12707 case LAYER_TYPE_HARDWARE: 12708 if (attachInfo.mHardwareRenderer != null && 12709 attachInfo.mHardwareRenderer.isEnabled() && 12710 attachInfo.mHardwareRenderer.validate()) { 12711 getHardwareLayer(); 12712 // TODO: We need a better way to handle this case 12713 // If views have registered pre-draw listeners they need 12714 // to be notified before we build the layer. Those listeners 12715 // may however rely on other events to happen first so we 12716 // cannot just invoke them here until they don't cancel the 12717 // current frame 12718 if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) { 12719 attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates(); 12720 } 12721 } 12722 break; 12723 case LAYER_TYPE_SOFTWARE: 12724 buildDrawingCache(true); 12725 break; 12726 } 12727 } 12728 12729 /** 12730 * <p>Returns a hardware layer that can be used to draw this view again 12731 * without executing its draw method.</p> 12732 * 12733 * @return A HardwareLayer ready to render, or null if an error occurred. 12734 */ 12735 HardwareLayer getHardwareLayer() { 12736 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 12737 !mAttachInfo.mHardwareRenderer.isEnabled()) { 12738 return null; 12739 } 12740 12741 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 12742 12743 final int width = mRight - mLeft; 12744 final int height = mBottom - mTop; 12745 12746 if (width == 0 || height == 0) { 12747 return null; 12748 } 12749 12750 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 12751 if (mHardwareLayer == null) { 12752 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 12753 width, height, isOpaque()); 12754 mLocalDirtyRect.set(0, 0, width, height); 12755 } else { 12756 if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 12757 if (mHardwareLayer.resize(width, height)) { 12758 mLocalDirtyRect.set(0, 0, width, height); 12759 } 12760 } 12761 12762 // This should not be necessary but applications that change 12763 // the parameters of their background drawable without calling 12764 // this.setBackground(Drawable) can leave the view in a bad state 12765 // (for instance isOpaque() returns true, but the background is 12766 // not opaque.) 12767 computeOpaqueFlags(); 12768 12769 final boolean opaque = isOpaque(); 12770 if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) { 12771 mHardwareLayer.setOpaque(opaque); 12772 mLocalDirtyRect.set(0, 0, width, height); 12773 } 12774 } 12775 12776 // The layer is not valid if the underlying GPU resources cannot be allocated 12777 if (!mHardwareLayer.isValid()) { 12778 return null; 12779 } 12780 12781 mHardwareLayer.setLayerPaint(mLayerPaint); 12782 mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 12783 ViewRootImpl viewRoot = getViewRootImpl(); 12784 if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer); 12785 12786 mLocalDirtyRect.setEmpty(); 12787 } 12788 12789 return mHardwareLayer; 12790 } 12791 12792 /** 12793 * Destroys this View's hardware layer if possible. 12794 * 12795 * @return True if the layer was destroyed, false otherwise. 12796 * 12797 * @see #setLayerType(int, android.graphics.Paint) 12798 * @see #LAYER_TYPE_HARDWARE 12799 */ 12800 boolean destroyLayer(boolean valid) { 12801 if (mHardwareLayer != null) { 12802 AttachInfo info = mAttachInfo; 12803 if (info != null && info.mHardwareRenderer != null && 12804 info.mHardwareRenderer.isEnabled() && 12805 (valid || info.mHardwareRenderer.validate())) { 12806 12807 info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer); 12808 mHardwareLayer.destroy(); 12809 mHardwareLayer = null; 12810 12811 invalidate(true); 12812 invalidateParentCaches(); 12813 } 12814 return true; 12815 } 12816 return false; 12817 } 12818 12819 /** 12820 * Destroys all hardware rendering resources. This method is invoked 12821 * when the system needs to reclaim resources. Upon execution of this 12822 * method, you should free any OpenGL resources created by the view. 12823 * 12824 * Note: you <strong>must</strong> call 12825 * <code>super.destroyHardwareResources()</code> when overriding 12826 * this method. 12827 * 12828 * @hide 12829 */ 12830 protected void destroyHardwareResources() { 12831 resetDisplayList(); 12832 destroyLayer(true); 12833 } 12834 12835 /** 12836 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 12837 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 12838 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 12839 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 12840 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 12841 * null.</p> 12842 * 12843 * <p>Enabling the drawing cache is similar to 12844 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 12845 * acceleration is turned off. When hardware acceleration is turned on, enabling the 12846 * drawing cache has no effect on rendering because the system uses a different mechanism 12847 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 12848 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 12849 * for information on how to enable software and hardware layers.</p> 12850 * 12851 * <p>This API can be used to manually generate 12852 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 12853 * {@link #getDrawingCache()}.</p> 12854 * 12855 * @param enabled true to enable the drawing cache, false otherwise 12856 * 12857 * @see #isDrawingCacheEnabled() 12858 * @see #getDrawingCache() 12859 * @see #buildDrawingCache() 12860 * @see #setLayerType(int, android.graphics.Paint) 12861 */ 12862 public void setDrawingCacheEnabled(boolean enabled) { 12863 mCachingFailed = false; 12864 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 12865 } 12866 12867 /** 12868 * <p>Indicates whether the drawing cache is enabled for this view.</p> 12869 * 12870 * @return true if the drawing cache is enabled 12871 * 12872 * @see #setDrawingCacheEnabled(boolean) 12873 * @see #getDrawingCache() 12874 */ 12875 @ViewDebug.ExportedProperty(category = "drawing") 12876 public boolean isDrawingCacheEnabled() { 12877 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 12878 } 12879 12880 /** 12881 * Debugging utility which recursively outputs the dirty state of a view and its 12882 * descendants. 12883 * 12884 * @hide 12885 */ 12886 @SuppressWarnings({"UnusedDeclaration"}) 12887 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 12888 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 12889 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 12890 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 12891 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 12892 if (clear) { 12893 mPrivateFlags &= clearMask; 12894 } 12895 if (this instanceof ViewGroup) { 12896 ViewGroup parent = (ViewGroup) this; 12897 final int count = parent.getChildCount(); 12898 for (int i = 0; i < count; i++) { 12899 final View child = parent.getChildAt(i); 12900 child.outputDirtyFlags(indent + " ", clear, clearMask); 12901 } 12902 } 12903 } 12904 12905 /** 12906 * This method is used by ViewGroup to cause its children to restore or recreate their 12907 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 12908 * to recreate its own display list, which would happen if it went through the normal 12909 * draw/dispatchDraw mechanisms. 12910 * 12911 * @hide 12912 */ 12913 protected void dispatchGetDisplayList() {} 12914 12915 /** 12916 * A view that is not attached or hardware accelerated cannot create a display list. 12917 * This method checks these conditions and returns the appropriate result. 12918 * 12919 * @return true if view has the ability to create a display list, false otherwise. 12920 * 12921 * @hide 12922 */ 12923 public boolean canHaveDisplayList() { 12924 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 12925 } 12926 12927 /** 12928 * @return The {@link HardwareRenderer} associated with that view or null if 12929 * hardware rendering is not supported or this view is not attached 12930 * to a window. 12931 * 12932 * @hide 12933 */ 12934 public HardwareRenderer getHardwareRenderer() { 12935 if (mAttachInfo != null) { 12936 return mAttachInfo.mHardwareRenderer; 12937 } 12938 return null; 12939 } 12940 12941 /** 12942 * Returns a DisplayList. If the incoming displayList is null, one will be created. 12943 * Otherwise, the same display list will be returned (after having been rendered into 12944 * along the way, depending on the invalidation state of the view). 12945 * 12946 * @param displayList The previous version of this displayList, could be null. 12947 * @param isLayer Whether the requester of the display list is a layer. If so, 12948 * the view will avoid creating a layer inside the resulting display list. 12949 * @return A new or reused DisplayList object. 12950 */ 12951 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 12952 if (!canHaveDisplayList()) { 12953 return null; 12954 } 12955 12956 if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || 12957 displayList == null || !displayList.isValid() || 12958 (!isLayer && mRecreateDisplayList))) { 12959 // Don't need to recreate the display list, just need to tell our 12960 // children to restore/recreate theirs 12961 if (displayList != null && displayList.isValid() && 12962 !isLayer && !mRecreateDisplayList) { 12963 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12964 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12965 dispatchGetDisplayList(); 12966 12967 return displayList; 12968 } 12969 12970 if (!isLayer) { 12971 // If we got here, we're recreating it. Mark it as such to ensure that 12972 // we copy in child display lists into ours in drawChild() 12973 mRecreateDisplayList = true; 12974 } 12975 if (displayList == null) { 12976 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName()); 12977 // If we're creating a new display list, make sure our parent gets invalidated 12978 // since they will need to recreate their display list to account for this 12979 // new child display list. 12980 invalidateParentCaches(); 12981 } 12982 12983 boolean caching = false; 12984 int width = mRight - mLeft; 12985 int height = mBottom - mTop; 12986 int layerType = getLayerType(); 12987 12988 final HardwareCanvas canvas = displayList.start(width, height); 12989 12990 try { 12991 if (!isLayer && layerType != LAYER_TYPE_NONE) { 12992 if (layerType == LAYER_TYPE_HARDWARE) { 12993 final HardwareLayer layer = getHardwareLayer(); 12994 if (layer != null && layer.isValid()) { 12995 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 12996 } else { 12997 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 12998 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 12999 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13000 } 13001 caching = true; 13002 } else { 13003 buildDrawingCache(true); 13004 Bitmap cache = getDrawingCache(true); 13005 if (cache != null) { 13006 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13007 caching = true; 13008 } 13009 } 13010 } else { 13011 13012 computeScroll(); 13013 13014 canvas.translate(-mScrollX, -mScrollY); 13015 if (!isLayer) { 13016 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13017 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13018 } 13019 13020 // Fast path for layouts with no backgrounds 13021 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13022 dispatchDraw(canvas); 13023 if (mOverlay != null && !mOverlay.isEmpty()) { 13024 mOverlay.getOverlayView().draw(canvas); 13025 } 13026 } else { 13027 draw(canvas); 13028 } 13029 } 13030 } finally { 13031 displayList.end(); 13032 displayList.setCaching(caching); 13033 if (isLayer) { 13034 displayList.setLeftTopRightBottom(0, 0, width, height); 13035 } else { 13036 setDisplayListProperties(displayList); 13037 } 13038 } 13039 } else if (!isLayer) { 13040 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13041 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13042 } 13043 13044 return displayList; 13045 } 13046 13047 /** 13048 * Get the DisplayList for the HardwareLayer 13049 * 13050 * @param layer The HardwareLayer whose DisplayList we want 13051 * @return A DisplayList fopr the specified HardwareLayer 13052 */ 13053 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 13054 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 13055 layer.setDisplayList(displayList); 13056 return displayList; 13057 } 13058 13059 13060 /** 13061 * <p>Returns a display list that can be used to draw this view again 13062 * without executing its draw method.</p> 13063 * 13064 * @return A DisplayList ready to replay, or null if caching is not enabled. 13065 * 13066 * @hide 13067 */ 13068 public DisplayList getDisplayList() { 13069 mDisplayList = getDisplayList(mDisplayList, false); 13070 return mDisplayList; 13071 } 13072 13073 private void clearDisplayList() { 13074 if (mDisplayList != null) { 13075 mDisplayList.clear(); 13076 } 13077 } 13078 13079 private void resetDisplayList() { 13080 if (mDisplayList != null) { 13081 mDisplayList.reset(); 13082 } 13083 } 13084 13085 /** 13086 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13087 * 13088 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13089 * 13090 * @see #getDrawingCache(boolean) 13091 */ 13092 public Bitmap getDrawingCache() { 13093 return getDrawingCache(false); 13094 } 13095 13096 /** 13097 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13098 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13099 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13100 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13101 * request the drawing cache by calling this method and draw it on screen if the 13102 * returned bitmap is not null.</p> 13103 * 13104 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13105 * this method will create a bitmap of the same size as this view. Because this bitmap 13106 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13107 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13108 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13109 * size than the view. This implies that your application must be able to handle this 13110 * size.</p> 13111 * 13112 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13113 * the current density of the screen when the application is in compatibility 13114 * mode. 13115 * 13116 * @return A bitmap representing this view or null if cache is disabled. 13117 * 13118 * @see #setDrawingCacheEnabled(boolean) 13119 * @see #isDrawingCacheEnabled() 13120 * @see #buildDrawingCache(boolean) 13121 * @see #destroyDrawingCache() 13122 */ 13123 public Bitmap getDrawingCache(boolean autoScale) { 13124 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13125 return null; 13126 } 13127 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13128 buildDrawingCache(autoScale); 13129 } 13130 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13131 } 13132 13133 /** 13134 * <p>Frees the resources used by the drawing cache. If you call 13135 * {@link #buildDrawingCache()} manually without calling 13136 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13137 * should cleanup the cache with this method afterwards.</p> 13138 * 13139 * @see #setDrawingCacheEnabled(boolean) 13140 * @see #buildDrawingCache() 13141 * @see #getDrawingCache() 13142 */ 13143 public void destroyDrawingCache() { 13144 if (mDrawingCache != null) { 13145 mDrawingCache.recycle(); 13146 mDrawingCache = null; 13147 } 13148 if (mUnscaledDrawingCache != null) { 13149 mUnscaledDrawingCache.recycle(); 13150 mUnscaledDrawingCache = null; 13151 } 13152 } 13153 13154 /** 13155 * Setting a solid background color for the drawing cache's bitmaps will improve 13156 * performance and memory usage. Note, though that this should only be used if this 13157 * view will always be drawn on top of a solid color. 13158 * 13159 * @param color The background color to use for the drawing cache's bitmap 13160 * 13161 * @see #setDrawingCacheEnabled(boolean) 13162 * @see #buildDrawingCache() 13163 * @see #getDrawingCache() 13164 */ 13165 public void setDrawingCacheBackgroundColor(int color) { 13166 if (color != mDrawingCacheBackgroundColor) { 13167 mDrawingCacheBackgroundColor = color; 13168 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13169 } 13170 } 13171 13172 /** 13173 * @see #setDrawingCacheBackgroundColor(int) 13174 * 13175 * @return The background color to used for the drawing cache's bitmap 13176 */ 13177 public int getDrawingCacheBackgroundColor() { 13178 return mDrawingCacheBackgroundColor; 13179 } 13180 13181 /** 13182 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13183 * 13184 * @see #buildDrawingCache(boolean) 13185 */ 13186 public void buildDrawingCache() { 13187 buildDrawingCache(false); 13188 } 13189 13190 /** 13191 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13192 * 13193 * <p>If you call {@link #buildDrawingCache()} manually without calling 13194 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13195 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13196 * 13197 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13198 * this method will create a bitmap of the same size as this view. Because this bitmap 13199 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13200 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13201 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13202 * size than the view. This implies that your application must be able to handle this 13203 * size.</p> 13204 * 13205 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13206 * you do not need the drawing cache bitmap, calling this method will increase memory 13207 * usage and cause the view to be rendered in software once, thus negatively impacting 13208 * performance.</p> 13209 * 13210 * @see #getDrawingCache() 13211 * @see #destroyDrawingCache() 13212 */ 13213 public void buildDrawingCache(boolean autoScale) { 13214 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13215 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13216 mCachingFailed = false; 13217 13218 int width = mRight - mLeft; 13219 int height = mBottom - mTop; 13220 13221 final AttachInfo attachInfo = mAttachInfo; 13222 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13223 13224 if (autoScale && scalingRequired) { 13225 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13226 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13227 } 13228 13229 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13230 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13231 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13232 13233 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13234 final long drawingCacheSize = 13235 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13236 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13237 if (width > 0 && height > 0) { 13238 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13239 + projectedBitmapSize + " bytes, only " 13240 + drawingCacheSize + " available"); 13241 } 13242 destroyDrawingCache(); 13243 mCachingFailed = true; 13244 return; 13245 } 13246 13247 boolean clear = true; 13248 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13249 13250 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13251 Bitmap.Config quality; 13252 if (!opaque) { 13253 // Never pick ARGB_4444 because it looks awful 13254 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13255 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13256 case DRAWING_CACHE_QUALITY_AUTO: 13257 case DRAWING_CACHE_QUALITY_LOW: 13258 case DRAWING_CACHE_QUALITY_HIGH: 13259 default: 13260 quality = Bitmap.Config.ARGB_8888; 13261 break; 13262 } 13263 } else { 13264 // Optimization for translucent windows 13265 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13266 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13267 } 13268 13269 // Try to cleanup memory 13270 if (bitmap != null) bitmap.recycle(); 13271 13272 try { 13273 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13274 width, height, quality); 13275 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 13276 if (autoScale) { 13277 mDrawingCache = bitmap; 13278 } else { 13279 mUnscaledDrawingCache = bitmap; 13280 } 13281 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 13282 } catch (OutOfMemoryError e) { 13283 // If there is not enough memory to create the bitmap cache, just 13284 // ignore the issue as bitmap caches are not required to draw the 13285 // view hierarchy 13286 if (autoScale) { 13287 mDrawingCache = null; 13288 } else { 13289 mUnscaledDrawingCache = null; 13290 } 13291 mCachingFailed = true; 13292 return; 13293 } 13294 13295 clear = drawingCacheBackgroundColor != 0; 13296 } 13297 13298 Canvas canvas; 13299 if (attachInfo != null) { 13300 canvas = attachInfo.mCanvas; 13301 if (canvas == null) { 13302 canvas = new Canvas(); 13303 } 13304 canvas.setBitmap(bitmap); 13305 // Temporarily clobber the cached Canvas in case one of our children 13306 // is also using a drawing cache. Without this, the children would 13307 // steal the canvas by attaching their own bitmap to it and bad, bad 13308 // thing would happen (invisible views, corrupted drawings, etc.) 13309 attachInfo.mCanvas = null; 13310 } else { 13311 // This case should hopefully never or seldom happen 13312 canvas = new Canvas(bitmap); 13313 } 13314 13315 if (clear) { 13316 bitmap.eraseColor(drawingCacheBackgroundColor); 13317 } 13318 13319 computeScroll(); 13320 final int restoreCount = canvas.save(); 13321 13322 if (autoScale && scalingRequired) { 13323 final float scale = attachInfo.mApplicationScale; 13324 canvas.scale(scale, scale); 13325 } 13326 13327 canvas.translate(-mScrollX, -mScrollY); 13328 13329 mPrivateFlags |= PFLAG_DRAWN; 13330 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 13331 mLayerType != LAYER_TYPE_NONE) { 13332 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 13333 } 13334 13335 // Fast path for layouts with no backgrounds 13336 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13337 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13338 dispatchDraw(canvas); 13339 if (mOverlay != null && !mOverlay.isEmpty()) { 13340 mOverlay.getOverlayView().draw(canvas); 13341 } 13342 } else { 13343 draw(canvas); 13344 } 13345 13346 canvas.restoreToCount(restoreCount); 13347 canvas.setBitmap(null); 13348 13349 if (attachInfo != null) { 13350 // Restore the cached Canvas for our siblings 13351 attachInfo.mCanvas = canvas; 13352 } 13353 } 13354 } 13355 13356 /** 13357 * Create a snapshot of the view into a bitmap. We should probably make 13358 * some form of this public, but should think about the API. 13359 */ 13360 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 13361 int width = mRight - mLeft; 13362 int height = mBottom - mTop; 13363 13364 final AttachInfo attachInfo = mAttachInfo; 13365 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 13366 width = (int) ((width * scale) + 0.5f); 13367 height = (int) ((height * scale) + 0.5f); 13368 13369 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13370 width > 0 ? width : 1, height > 0 ? height : 1, quality); 13371 if (bitmap == null) { 13372 throw new OutOfMemoryError(); 13373 } 13374 13375 Resources resources = getResources(); 13376 if (resources != null) { 13377 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 13378 } 13379 13380 Canvas canvas; 13381 if (attachInfo != null) { 13382 canvas = attachInfo.mCanvas; 13383 if (canvas == null) { 13384 canvas = new Canvas(); 13385 } 13386 canvas.setBitmap(bitmap); 13387 // Temporarily clobber the cached Canvas in case one of our children 13388 // is also using a drawing cache. Without this, the children would 13389 // steal the canvas by attaching their own bitmap to it and bad, bad 13390 // things would happen (invisible views, corrupted drawings, etc.) 13391 attachInfo.mCanvas = null; 13392 } else { 13393 // This case should hopefully never or seldom happen 13394 canvas = new Canvas(bitmap); 13395 } 13396 13397 if ((backgroundColor & 0xff000000) != 0) { 13398 bitmap.eraseColor(backgroundColor); 13399 } 13400 13401 computeScroll(); 13402 final int restoreCount = canvas.save(); 13403 canvas.scale(scale, scale); 13404 canvas.translate(-mScrollX, -mScrollY); 13405 13406 // Temporarily remove the dirty mask 13407 int flags = mPrivateFlags; 13408 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13409 13410 // Fast path for layouts with no backgrounds 13411 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13412 dispatchDraw(canvas); 13413 } else { 13414 draw(canvas); 13415 } 13416 13417 mPrivateFlags = flags; 13418 13419 canvas.restoreToCount(restoreCount); 13420 canvas.setBitmap(null); 13421 13422 if (attachInfo != null) { 13423 // Restore the cached Canvas for our siblings 13424 attachInfo.mCanvas = canvas; 13425 } 13426 13427 return bitmap; 13428 } 13429 13430 /** 13431 * Indicates whether this View is currently in edit mode. A View is usually 13432 * in edit mode when displayed within a developer tool. For instance, if 13433 * this View is being drawn by a visual user interface builder, this method 13434 * should return true. 13435 * 13436 * Subclasses should check the return value of this method to provide 13437 * different behaviors if their normal behavior might interfere with the 13438 * host environment. For instance: the class spawns a thread in its 13439 * constructor, the drawing code relies on device-specific features, etc. 13440 * 13441 * This method is usually checked in the drawing code of custom widgets. 13442 * 13443 * @return True if this View is in edit mode, false otherwise. 13444 */ 13445 public boolean isInEditMode() { 13446 return false; 13447 } 13448 13449 /** 13450 * If the View draws content inside its padding and enables fading edges, 13451 * it needs to support padding offsets. Padding offsets are added to the 13452 * fading edges to extend the length of the fade so that it covers pixels 13453 * drawn inside the padding. 13454 * 13455 * Subclasses of this class should override this method if they need 13456 * to draw content inside the padding. 13457 * 13458 * @return True if padding offset must be applied, false otherwise. 13459 * 13460 * @see #getLeftPaddingOffset() 13461 * @see #getRightPaddingOffset() 13462 * @see #getTopPaddingOffset() 13463 * @see #getBottomPaddingOffset() 13464 * 13465 * @since CURRENT 13466 */ 13467 protected boolean isPaddingOffsetRequired() { 13468 return false; 13469 } 13470 13471 /** 13472 * Amount by which to extend the left fading region. Called only when 13473 * {@link #isPaddingOffsetRequired()} returns true. 13474 * 13475 * @return The left padding offset in pixels. 13476 * 13477 * @see #isPaddingOffsetRequired() 13478 * 13479 * @since CURRENT 13480 */ 13481 protected int getLeftPaddingOffset() { 13482 return 0; 13483 } 13484 13485 /** 13486 * Amount by which to extend the right fading region. Called only when 13487 * {@link #isPaddingOffsetRequired()} returns true. 13488 * 13489 * @return The right padding offset in pixels. 13490 * 13491 * @see #isPaddingOffsetRequired() 13492 * 13493 * @since CURRENT 13494 */ 13495 protected int getRightPaddingOffset() { 13496 return 0; 13497 } 13498 13499 /** 13500 * Amount by which to extend the top fading region. Called only when 13501 * {@link #isPaddingOffsetRequired()} returns true. 13502 * 13503 * @return The top padding offset in pixels. 13504 * 13505 * @see #isPaddingOffsetRequired() 13506 * 13507 * @since CURRENT 13508 */ 13509 protected int getTopPaddingOffset() { 13510 return 0; 13511 } 13512 13513 /** 13514 * Amount by which to extend the bottom fading region. Called only when 13515 * {@link #isPaddingOffsetRequired()} returns true. 13516 * 13517 * @return The bottom padding offset in pixels. 13518 * 13519 * @see #isPaddingOffsetRequired() 13520 * 13521 * @since CURRENT 13522 */ 13523 protected int getBottomPaddingOffset() { 13524 return 0; 13525 } 13526 13527 /** 13528 * @hide 13529 * @param offsetRequired 13530 */ 13531 protected int getFadeTop(boolean offsetRequired) { 13532 int top = mPaddingTop; 13533 if (offsetRequired) top += getTopPaddingOffset(); 13534 return top; 13535 } 13536 13537 /** 13538 * @hide 13539 * @param offsetRequired 13540 */ 13541 protected int getFadeHeight(boolean offsetRequired) { 13542 int padding = mPaddingTop; 13543 if (offsetRequired) padding += getTopPaddingOffset(); 13544 return mBottom - mTop - mPaddingBottom - padding; 13545 } 13546 13547 /** 13548 * <p>Indicates whether this view is attached to a hardware accelerated 13549 * window or not.</p> 13550 * 13551 * <p>Even if this method returns true, it does not mean that every call 13552 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 13553 * accelerated {@link android.graphics.Canvas}. For instance, if this view 13554 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 13555 * window is hardware accelerated, 13556 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 13557 * return false, and this method will return true.</p> 13558 * 13559 * @return True if the view is attached to a window and the window is 13560 * hardware accelerated; false in any other case. 13561 */ 13562 public boolean isHardwareAccelerated() { 13563 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13564 } 13565 13566 /** 13567 * Sets a rectangular area on this view to which the view will be clipped 13568 * when it is drawn. Setting the value to null will remove the clip bounds 13569 * and the view will draw normally, using its full bounds. 13570 * 13571 * @param clipBounds The rectangular area, in the local coordinates of 13572 * this view, to which future drawing operations will be clipped. 13573 */ 13574 public void setClipBounds(Rect clipBounds) { 13575 if (clipBounds != null) { 13576 if (clipBounds.equals(mClipBounds)) { 13577 return; 13578 } 13579 if (mClipBounds == null) { 13580 invalidate(); 13581 mClipBounds = new Rect(clipBounds); 13582 } else { 13583 invalidate(Math.min(mClipBounds.left, clipBounds.left), 13584 Math.min(mClipBounds.top, clipBounds.top), 13585 Math.max(mClipBounds.right, clipBounds.right), 13586 Math.max(mClipBounds.bottom, clipBounds.bottom)); 13587 mClipBounds.set(clipBounds); 13588 } 13589 } else { 13590 if (mClipBounds != null) { 13591 invalidate(); 13592 mClipBounds = null; 13593 } 13594 } 13595 } 13596 13597 /** 13598 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 13599 * 13600 * @return A copy of the current clip bounds if clip bounds are set, 13601 * otherwise null. 13602 */ 13603 public Rect getClipBounds() { 13604 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 13605 } 13606 13607 /** 13608 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 13609 * case of an active Animation being run on the view. 13610 */ 13611 private boolean drawAnimation(ViewGroup parent, long drawingTime, 13612 Animation a, boolean scalingRequired) { 13613 Transformation invalidationTransform; 13614 final int flags = parent.mGroupFlags; 13615 final boolean initialized = a.isInitialized(); 13616 if (!initialized) { 13617 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 13618 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 13619 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 13620 onAnimationStart(); 13621 } 13622 13623 final Transformation t = parent.getChildTransformation(); 13624 boolean more = a.getTransformation(drawingTime, t, 1f); 13625 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 13626 if (parent.mInvalidationTransformation == null) { 13627 parent.mInvalidationTransformation = new Transformation(); 13628 } 13629 invalidationTransform = parent.mInvalidationTransformation; 13630 a.getTransformation(drawingTime, invalidationTransform, 1f); 13631 } else { 13632 invalidationTransform = t; 13633 } 13634 13635 if (more) { 13636 if (!a.willChangeBounds()) { 13637 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 13638 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 13639 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 13640 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 13641 // The child need to draw an animation, potentially offscreen, so 13642 // make sure we do not cancel invalidate requests 13643 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13644 parent.invalidate(mLeft, mTop, mRight, mBottom); 13645 } 13646 } else { 13647 if (parent.mInvalidateRegion == null) { 13648 parent.mInvalidateRegion = new RectF(); 13649 } 13650 final RectF region = parent.mInvalidateRegion; 13651 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 13652 invalidationTransform); 13653 13654 // The child need to draw an animation, potentially offscreen, so 13655 // make sure we do not cancel invalidate requests 13656 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13657 13658 final int left = mLeft + (int) region.left; 13659 final int top = mTop + (int) region.top; 13660 parent.invalidate(left, top, left + (int) (region.width() + .5f), 13661 top + (int) (region.height() + .5f)); 13662 } 13663 } 13664 return more; 13665 } 13666 13667 /** 13668 * This method is called by getDisplayList() when a display list is created or re-rendered. 13669 * It sets or resets the current value of all properties on that display list (resetting is 13670 * necessary when a display list is being re-created, because we need to make sure that 13671 * previously-set transform values 13672 */ 13673 void setDisplayListProperties(DisplayList displayList) { 13674 if (displayList != null) { 13675 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 13676 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 13677 if (mParent instanceof ViewGroup) { 13678 displayList.setClipToBounds( 13679 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 13680 } 13681 float alpha = 1; 13682 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 13683 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13684 ViewGroup parentVG = (ViewGroup) mParent; 13685 final Transformation t = parentVG.getChildTransformation(); 13686 if (parentVG.getChildStaticTransformation(this, t)) { 13687 final int transformType = t.getTransformationType(); 13688 if (transformType != Transformation.TYPE_IDENTITY) { 13689 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 13690 alpha = t.getAlpha(); 13691 } 13692 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 13693 displayList.setMatrix(t.getMatrix()); 13694 } 13695 } 13696 } 13697 } 13698 if (mTransformationInfo != null) { 13699 alpha *= mTransformationInfo.mAlpha; 13700 if (alpha < 1) { 13701 final int multipliedAlpha = (int) (255 * alpha); 13702 if (onSetAlpha(multipliedAlpha)) { 13703 alpha = 1; 13704 } 13705 } 13706 displayList.setTransformationInfo(alpha, 13707 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 13708 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 13709 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 13710 mTransformationInfo.mScaleY); 13711 if (mTransformationInfo.mCamera == null) { 13712 mTransformationInfo.mCamera = new Camera(); 13713 mTransformationInfo.matrix3D = new Matrix(); 13714 } 13715 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 13716 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) { 13717 displayList.setPivotX(getPivotX()); 13718 displayList.setPivotY(getPivotY()); 13719 } 13720 } else if (alpha < 1) { 13721 displayList.setAlpha(alpha); 13722 } 13723 } 13724 } 13725 13726 /** 13727 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 13728 * This draw() method is an implementation detail and is not intended to be overridden or 13729 * to be called from anywhere else other than ViewGroup.drawChild(). 13730 */ 13731 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 13732 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13733 boolean more = false; 13734 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 13735 final int flags = parent.mGroupFlags; 13736 13737 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 13738 parent.getChildTransformation().clear(); 13739 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13740 } 13741 13742 Transformation transformToApply = null; 13743 boolean concatMatrix = false; 13744 13745 boolean scalingRequired = false; 13746 boolean caching; 13747 int layerType = getLayerType(); 13748 13749 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 13750 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 13751 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 13752 caching = true; 13753 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 13754 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 13755 } else { 13756 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 13757 } 13758 13759 final Animation a = getAnimation(); 13760 if (a != null) { 13761 more = drawAnimation(parent, drawingTime, a, scalingRequired); 13762 concatMatrix = a.willChangeTransformationMatrix(); 13763 if (concatMatrix) { 13764 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13765 } 13766 transformToApply = parent.getChildTransformation(); 13767 } else { 13768 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == 13769 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) { 13770 // No longer animating: clear out old animation matrix 13771 mDisplayList.setAnimationMatrix(null); 13772 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13773 } 13774 if (!useDisplayListProperties && 13775 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13776 final Transformation t = parent.getChildTransformation(); 13777 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 13778 if (hasTransform) { 13779 final int transformType = t.getTransformationType(); 13780 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 13781 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 13782 } 13783 } 13784 } 13785 13786 concatMatrix |= !childHasIdentityMatrix; 13787 13788 // Sets the flag as early as possible to allow draw() implementations 13789 // to call invalidate() successfully when doing animations 13790 mPrivateFlags |= PFLAG_DRAWN; 13791 13792 if (!concatMatrix && 13793 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 13794 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 13795 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 13796 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 13797 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 13798 return more; 13799 } 13800 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 13801 13802 if (hardwareAccelerated) { 13803 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 13804 // retain the flag's value temporarily in the mRecreateDisplayList flag 13805 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 13806 mPrivateFlags &= ~PFLAG_INVALIDATED; 13807 } 13808 13809 DisplayList displayList = null; 13810 Bitmap cache = null; 13811 boolean hasDisplayList = false; 13812 if (caching) { 13813 if (!hardwareAccelerated) { 13814 if (layerType != LAYER_TYPE_NONE) { 13815 layerType = LAYER_TYPE_SOFTWARE; 13816 buildDrawingCache(true); 13817 } 13818 cache = getDrawingCache(true); 13819 } else { 13820 switch (layerType) { 13821 case LAYER_TYPE_SOFTWARE: 13822 if (useDisplayListProperties) { 13823 hasDisplayList = canHaveDisplayList(); 13824 } else { 13825 buildDrawingCache(true); 13826 cache = getDrawingCache(true); 13827 } 13828 break; 13829 case LAYER_TYPE_HARDWARE: 13830 if (useDisplayListProperties) { 13831 hasDisplayList = canHaveDisplayList(); 13832 } 13833 break; 13834 case LAYER_TYPE_NONE: 13835 // Delay getting the display list until animation-driven alpha values are 13836 // set up and possibly passed on to the view 13837 hasDisplayList = canHaveDisplayList(); 13838 break; 13839 } 13840 } 13841 } 13842 useDisplayListProperties &= hasDisplayList; 13843 if (useDisplayListProperties) { 13844 displayList = getDisplayList(); 13845 if (!displayList.isValid()) { 13846 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13847 // to getDisplayList(), the display list will be marked invalid and we should not 13848 // try to use it again. 13849 displayList = null; 13850 hasDisplayList = false; 13851 useDisplayListProperties = false; 13852 } 13853 } 13854 13855 int sx = 0; 13856 int sy = 0; 13857 if (!hasDisplayList) { 13858 computeScroll(); 13859 sx = mScrollX; 13860 sy = mScrollY; 13861 } 13862 13863 final boolean hasNoCache = cache == null || hasDisplayList; 13864 final boolean offsetForScroll = cache == null && !hasDisplayList && 13865 layerType != LAYER_TYPE_HARDWARE; 13866 13867 int restoreTo = -1; 13868 if (!useDisplayListProperties || transformToApply != null) { 13869 restoreTo = canvas.save(); 13870 } 13871 if (offsetForScroll) { 13872 canvas.translate(mLeft - sx, mTop - sy); 13873 } else { 13874 if (!useDisplayListProperties) { 13875 canvas.translate(mLeft, mTop); 13876 } 13877 if (scalingRequired) { 13878 if (useDisplayListProperties) { 13879 // TODO: Might not need this if we put everything inside the DL 13880 restoreTo = canvas.save(); 13881 } 13882 // mAttachInfo cannot be null, otherwise scalingRequired == false 13883 final float scale = 1.0f / mAttachInfo.mApplicationScale; 13884 canvas.scale(scale, scale); 13885 } 13886 } 13887 13888 float alpha = useDisplayListProperties ? 1 : getAlpha(); 13889 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 13890 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13891 if (transformToApply != null || !childHasIdentityMatrix) { 13892 int transX = 0; 13893 int transY = 0; 13894 13895 if (offsetForScroll) { 13896 transX = -sx; 13897 transY = -sy; 13898 } 13899 13900 if (transformToApply != null) { 13901 if (concatMatrix) { 13902 if (useDisplayListProperties) { 13903 displayList.setAnimationMatrix(transformToApply.getMatrix()); 13904 } else { 13905 // Undo the scroll translation, apply the transformation matrix, 13906 // then redo the scroll translate to get the correct result. 13907 canvas.translate(-transX, -transY); 13908 canvas.concat(transformToApply.getMatrix()); 13909 canvas.translate(transX, transY); 13910 } 13911 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13912 } 13913 13914 float transformAlpha = transformToApply.getAlpha(); 13915 if (transformAlpha < 1) { 13916 alpha *= transformAlpha; 13917 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13918 } 13919 } 13920 13921 if (!childHasIdentityMatrix && !useDisplayListProperties) { 13922 canvas.translate(-transX, -transY); 13923 canvas.concat(getMatrix()); 13924 canvas.translate(transX, transY); 13925 } 13926 } 13927 13928 // Deal with alpha if it is or used to be <1 13929 if (alpha < 1 || 13930 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13931 if (alpha < 1) { 13932 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13933 } else { 13934 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13935 } 13936 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13937 if (hasNoCache) { 13938 final int multipliedAlpha = (int) (255 * alpha); 13939 if (!onSetAlpha(multipliedAlpha)) { 13940 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13941 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 13942 layerType != LAYER_TYPE_NONE) { 13943 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 13944 } 13945 if (useDisplayListProperties) { 13946 displayList.setAlpha(alpha * getAlpha()); 13947 } else if (layerType == LAYER_TYPE_NONE) { 13948 final int scrollX = hasDisplayList ? 0 : sx; 13949 final int scrollY = hasDisplayList ? 0 : sy; 13950 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 13951 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 13952 } 13953 } else { 13954 // Alpha is handled by the child directly, clobber the layer's alpha 13955 mPrivateFlags |= PFLAG_ALPHA_SET; 13956 } 13957 } 13958 } 13959 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 13960 onSetAlpha(255); 13961 mPrivateFlags &= ~PFLAG_ALPHA_SET; 13962 } 13963 13964 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 13965 !useDisplayListProperties && cache == null) { 13966 if (offsetForScroll) { 13967 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 13968 } else { 13969 if (!scalingRequired || cache == null) { 13970 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 13971 } else { 13972 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 13973 } 13974 } 13975 } 13976 13977 if (!useDisplayListProperties && hasDisplayList) { 13978 displayList = getDisplayList(); 13979 if (!displayList.isValid()) { 13980 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13981 // to getDisplayList(), the display list will be marked invalid and we should not 13982 // try to use it again. 13983 displayList = null; 13984 hasDisplayList = false; 13985 } 13986 } 13987 13988 if (hasNoCache) { 13989 boolean layerRendered = false; 13990 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 13991 final HardwareLayer layer = getHardwareLayer(); 13992 if (layer != null && layer.isValid()) { 13993 mLayerPaint.setAlpha((int) (alpha * 255)); 13994 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 13995 layerRendered = true; 13996 } else { 13997 final int scrollX = hasDisplayList ? 0 : sx; 13998 final int scrollY = hasDisplayList ? 0 : sy; 13999 canvas.saveLayer(scrollX, scrollY, 14000 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14001 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14002 } 14003 } 14004 14005 if (!layerRendered) { 14006 if (!hasDisplayList) { 14007 // Fast path for layouts with no backgrounds 14008 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14009 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14010 dispatchDraw(canvas); 14011 } else { 14012 draw(canvas); 14013 } 14014 } else { 14015 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14016 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14017 } 14018 } 14019 } else if (cache != null) { 14020 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14021 Paint cachePaint; 14022 14023 if (layerType == LAYER_TYPE_NONE) { 14024 cachePaint = parent.mCachePaint; 14025 if (cachePaint == null) { 14026 cachePaint = new Paint(); 14027 cachePaint.setDither(false); 14028 parent.mCachePaint = cachePaint; 14029 } 14030 if (alpha < 1) { 14031 cachePaint.setAlpha((int) (alpha * 255)); 14032 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14033 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14034 cachePaint.setAlpha(255); 14035 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14036 } 14037 } else { 14038 cachePaint = mLayerPaint; 14039 cachePaint.setAlpha((int) (alpha * 255)); 14040 } 14041 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14042 } 14043 14044 if (restoreTo >= 0) { 14045 canvas.restoreToCount(restoreTo); 14046 } 14047 14048 if (a != null && !more) { 14049 if (!hardwareAccelerated && !a.getFillAfter()) { 14050 onSetAlpha(255); 14051 } 14052 parent.finishAnimatingView(this, a); 14053 } 14054 14055 if (more && hardwareAccelerated) { 14056 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14057 // alpha animations should cause the child to recreate its display list 14058 invalidate(true); 14059 } 14060 } 14061 14062 mRecreateDisplayList = false; 14063 14064 return more; 14065 } 14066 14067 /** 14068 * Manually render this view (and all of its children) to the given Canvas. 14069 * The view must have already done a full layout before this function is 14070 * called. When implementing a view, implement 14071 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14072 * If you do need to override this method, call the superclass version. 14073 * 14074 * @param canvas The Canvas to which the View is rendered. 14075 */ 14076 public void draw(Canvas canvas) { 14077 if (mClipBounds != null) { 14078 canvas.clipRect(mClipBounds); 14079 } 14080 final int privateFlags = mPrivateFlags; 14081 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14082 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14083 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14084 14085 /* 14086 * Draw traversal performs several drawing steps which must be executed 14087 * in the appropriate order: 14088 * 14089 * 1. Draw the background 14090 * 2. If necessary, save the canvas' layers to prepare for fading 14091 * 3. Draw view's content 14092 * 4. Draw children 14093 * 5. If necessary, draw the fading edges and restore layers 14094 * 6. Draw decorations (scrollbars for instance) 14095 */ 14096 14097 // Step 1, draw the background, if needed 14098 int saveCount; 14099 14100 if (!dirtyOpaque) { 14101 final Drawable background = mBackground; 14102 if (background != null) { 14103 final int scrollX = mScrollX; 14104 final int scrollY = mScrollY; 14105 14106 if (mBackgroundSizeChanged) { 14107 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14108 mBackgroundSizeChanged = false; 14109 } 14110 14111 if ((scrollX | scrollY) == 0) { 14112 background.draw(canvas); 14113 } else { 14114 canvas.translate(scrollX, scrollY); 14115 background.draw(canvas); 14116 canvas.translate(-scrollX, -scrollY); 14117 } 14118 } 14119 } 14120 14121 // skip step 2 & 5 if possible (common case) 14122 final int viewFlags = mViewFlags; 14123 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14124 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14125 if (!verticalEdges && !horizontalEdges) { 14126 // Step 3, draw the content 14127 if (!dirtyOpaque) onDraw(canvas); 14128 14129 // Step 4, draw the children 14130 dispatchDraw(canvas); 14131 14132 // Step 6, draw decorations (scrollbars) 14133 onDrawScrollBars(canvas); 14134 14135 if (mOverlay != null && !mOverlay.isEmpty()) { 14136 mOverlay.getOverlayView().dispatchDraw(canvas); 14137 } 14138 14139 // we're done... 14140 return; 14141 } 14142 14143 /* 14144 * Here we do the full fledged routine... 14145 * (this is an uncommon case where speed matters less, 14146 * this is why we repeat some of the tests that have been 14147 * done above) 14148 */ 14149 14150 boolean drawTop = false; 14151 boolean drawBottom = false; 14152 boolean drawLeft = false; 14153 boolean drawRight = false; 14154 14155 float topFadeStrength = 0.0f; 14156 float bottomFadeStrength = 0.0f; 14157 float leftFadeStrength = 0.0f; 14158 float rightFadeStrength = 0.0f; 14159 14160 // Step 2, save the canvas' layers 14161 int paddingLeft = mPaddingLeft; 14162 14163 final boolean offsetRequired = isPaddingOffsetRequired(); 14164 if (offsetRequired) { 14165 paddingLeft += getLeftPaddingOffset(); 14166 } 14167 14168 int left = mScrollX + paddingLeft; 14169 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14170 int top = mScrollY + getFadeTop(offsetRequired); 14171 int bottom = top + getFadeHeight(offsetRequired); 14172 14173 if (offsetRequired) { 14174 right += getRightPaddingOffset(); 14175 bottom += getBottomPaddingOffset(); 14176 } 14177 14178 final ScrollabilityCache scrollabilityCache = mScrollCache; 14179 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14180 int length = (int) fadeHeight; 14181 14182 // clip the fade length if top and bottom fades overlap 14183 // overlapping fades produce odd-looking artifacts 14184 if (verticalEdges && (top + length > bottom - length)) { 14185 length = (bottom - top) / 2; 14186 } 14187 14188 // also clip horizontal fades if necessary 14189 if (horizontalEdges && (left + length > right - length)) { 14190 length = (right - left) / 2; 14191 } 14192 14193 if (verticalEdges) { 14194 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14195 drawTop = topFadeStrength * fadeHeight > 1.0f; 14196 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14197 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14198 } 14199 14200 if (horizontalEdges) { 14201 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14202 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14203 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14204 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14205 } 14206 14207 saveCount = canvas.getSaveCount(); 14208 14209 int solidColor = getSolidColor(); 14210 if (solidColor == 0) { 14211 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14212 14213 if (drawTop) { 14214 canvas.saveLayer(left, top, right, top + length, null, flags); 14215 } 14216 14217 if (drawBottom) { 14218 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14219 } 14220 14221 if (drawLeft) { 14222 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14223 } 14224 14225 if (drawRight) { 14226 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14227 } 14228 } else { 14229 scrollabilityCache.setFadeColor(solidColor); 14230 } 14231 14232 // Step 3, draw the content 14233 if (!dirtyOpaque) onDraw(canvas); 14234 14235 // Step 4, draw the children 14236 dispatchDraw(canvas); 14237 14238 // Step 5, draw the fade effect and restore layers 14239 final Paint p = scrollabilityCache.paint; 14240 final Matrix matrix = scrollabilityCache.matrix; 14241 final Shader fade = scrollabilityCache.shader; 14242 14243 if (drawTop) { 14244 matrix.setScale(1, fadeHeight * topFadeStrength); 14245 matrix.postTranslate(left, top); 14246 fade.setLocalMatrix(matrix); 14247 canvas.drawRect(left, top, right, top + length, p); 14248 } 14249 14250 if (drawBottom) { 14251 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14252 matrix.postRotate(180); 14253 matrix.postTranslate(left, bottom); 14254 fade.setLocalMatrix(matrix); 14255 canvas.drawRect(left, bottom - length, right, bottom, p); 14256 } 14257 14258 if (drawLeft) { 14259 matrix.setScale(1, fadeHeight * leftFadeStrength); 14260 matrix.postRotate(-90); 14261 matrix.postTranslate(left, top); 14262 fade.setLocalMatrix(matrix); 14263 canvas.drawRect(left, top, left + length, bottom, p); 14264 } 14265 14266 if (drawRight) { 14267 matrix.setScale(1, fadeHeight * rightFadeStrength); 14268 matrix.postRotate(90); 14269 matrix.postTranslate(right, top); 14270 fade.setLocalMatrix(matrix); 14271 canvas.drawRect(right - length, top, right, bottom, p); 14272 } 14273 14274 canvas.restoreToCount(saveCount); 14275 14276 // Step 6, draw decorations (scrollbars) 14277 onDrawScrollBars(canvas); 14278 14279 if (mOverlay != null && !mOverlay.isEmpty()) { 14280 mOverlay.getOverlayView().dispatchDraw(canvas); 14281 } 14282 } 14283 14284 /** 14285 * Returns the overlay for this view, creating it if it does not yet exist. 14286 * Adding drawables to the overlay will cause them to be displayed whenever 14287 * the view itself is redrawn. Objects in the overlay should be actively 14288 * managed: remove them when they should not be displayed anymore. The 14289 * overlay will always have the same size as its host view. 14290 * 14291 * <p>Note: Overlays do not currently work correctly with {@link 14292 * SurfaceView} or {@link TextureView}; contents in overlays for these 14293 * types of views may not display correctly.</p> 14294 * 14295 * @return The ViewOverlay object for this view. 14296 * @see ViewOverlay 14297 */ 14298 public ViewOverlay getOverlay() { 14299 if (mOverlay == null) { 14300 mOverlay = new ViewOverlay(mContext, this); 14301 } 14302 return mOverlay; 14303 } 14304 14305 /** 14306 * Override this if your view is known to always be drawn on top of a solid color background, 14307 * and needs to draw fading edges. Returning a non-zero color enables the view system to 14308 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 14309 * should be set to 0xFF. 14310 * 14311 * @see #setVerticalFadingEdgeEnabled(boolean) 14312 * @see #setHorizontalFadingEdgeEnabled(boolean) 14313 * 14314 * @return The known solid color background for this view, or 0 if the color may vary 14315 */ 14316 @ViewDebug.ExportedProperty(category = "drawing") 14317 public int getSolidColor() { 14318 return 0; 14319 } 14320 14321 /** 14322 * Build a human readable string representation of the specified view flags. 14323 * 14324 * @param flags the view flags to convert to a string 14325 * @return a String representing the supplied flags 14326 */ 14327 private static String printFlags(int flags) { 14328 String output = ""; 14329 int numFlags = 0; 14330 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 14331 output += "TAKES_FOCUS"; 14332 numFlags++; 14333 } 14334 14335 switch (flags & VISIBILITY_MASK) { 14336 case INVISIBLE: 14337 if (numFlags > 0) { 14338 output += " "; 14339 } 14340 output += "INVISIBLE"; 14341 // USELESS HERE numFlags++; 14342 break; 14343 case GONE: 14344 if (numFlags > 0) { 14345 output += " "; 14346 } 14347 output += "GONE"; 14348 // USELESS HERE numFlags++; 14349 break; 14350 default: 14351 break; 14352 } 14353 return output; 14354 } 14355 14356 /** 14357 * Build a human readable string representation of the specified private 14358 * view flags. 14359 * 14360 * @param privateFlags the private view flags to convert to a string 14361 * @return a String representing the supplied flags 14362 */ 14363 private static String printPrivateFlags(int privateFlags) { 14364 String output = ""; 14365 int numFlags = 0; 14366 14367 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 14368 output += "WANTS_FOCUS"; 14369 numFlags++; 14370 } 14371 14372 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 14373 if (numFlags > 0) { 14374 output += " "; 14375 } 14376 output += "FOCUSED"; 14377 numFlags++; 14378 } 14379 14380 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 14381 if (numFlags > 0) { 14382 output += " "; 14383 } 14384 output += "SELECTED"; 14385 numFlags++; 14386 } 14387 14388 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 14389 if (numFlags > 0) { 14390 output += " "; 14391 } 14392 output += "IS_ROOT_NAMESPACE"; 14393 numFlags++; 14394 } 14395 14396 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 14397 if (numFlags > 0) { 14398 output += " "; 14399 } 14400 output += "HAS_BOUNDS"; 14401 numFlags++; 14402 } 14403 14404 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 14405 if (numFlags > 0) { 14406 output += " "; 14407 } 14408 output += "DRAWN"; 14409 // USELESS HERE numFlags++; 14410 } 14411 return output; 14412 } 14413 14414 /** 14415 * <p>Indicates whether or not this view's layout will be requested during 14416 * the next hierarchy layout pass.</p> 14417 * 14418 * @return true if the layout will be forced during next layout pass 14419 */ 14420 public boolean isLayoutRequested() { 14421 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 14422 } 14423 14424 /** 14425 * Return true if o is a ViewGroup that is laying out using optical bounds. 14426 * @hide 14427 */ 14428 public static boolean isLayoutModeOptical(Object o) { 14429 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 14430 } 14431 14432 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 14433 Insets parentInsets = mParent instanceof View ? 14434 ((View) mParent).getOpticalInsets() : Insets.NONE; 14435 Insets childInsets = getOpticalInsets(); 14436 return setFrame( 14437 left + parentInsets.left - childInsets.left, 14438 top + parentInsets.top - childInsets.top, 14439 right + parentInsets.left + childInsets.right, 14440 bottom + parentInsets.top + childInsets.bottom); 14441 } 14442 14443 /** 14444 * Assign a size and position to a view and all of its 14445 * descendants 14446 * 14447 * <p>This is the second phase of the layout mechanism. 14448 * (The first is measuring). In this phase, each parent calls 14449 * layout on all of its children to position them. 14450 * This is typically done using the child measurements 14451 * that were stored in the measure pass().</p> 14452 * 14453 * <p>Derived classes should not override this method. 14454 * Derived classes with children should override 14455 * onLayout. In that method, they should 14456 * call layout on each of their children.</p> 14457 * 14458 * @param l Left position, relative to parent 14459 * @param t Top position, relative to parent 14460 * @param r Right position, relative to parent 14461 * @param b Bottom position, relative to parent 14462 */ 14463 @SuppressWarnings({"unchecked"}) 14464 public void layout(int l, int t, int r, int b) { 14465 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 14466 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 14467 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 14468 } 14469 14470 int oldL = mLeft; 14471 int oldT = mTop; 14472 int oldB = mBottom; 14473 int oldR = mRight; 14474 14475 boolean changed = isLayoutModeOptical(mParent) ? 14476 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 14477 14478 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 14479 onLayout(changed, l, t, r, b); 14480 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 14481 14482 ListenerInfo li = mListenerInfo; 14483 if (li != null && li.mOnLayoutChangeListeners != null) { 14484 ArrayList<OnLayoutChangeListener> listenersCopy = 14485 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 14486 int numListeners = listenersCopy.size(); 14487 for (int i = 0; i < numListeners; ++i) { 14488 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 14489 } 14490 } 14491 } 14492 14493 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 14494 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 14495 } 14496 14497 /** 14498 * Called from layout when this view should 14499 * assign a size and position to each of its children. 14500 * 14501 * Derived classes with children should override 14502 * this method and call layout on each of 14503 * their children. 14504 * @param changed This is a new size or position for this view 14505 * @param left Left position, relative to parent 14506 * @param top Top position, relative to parent 14507 * @param right Right position, relative to parent 14508 * @param bottom Bottom position, relative to parent 14509 */ 14510 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 14511 } 14512 14513 /** 14514 * Assign a size and position to this view. 14515 * 14516 * This is called from layout. 14517 * 14518 * @param left Left position, relative to parent 14519 * @param top Top position, relative to parent 14520 * @param right Right position, relative to parent 14521 * @param bottom Bottom position, relative to parent 14522 * @return true if the new size and position are different than the 14523 * previous ones 14524 * {@hide} 14525 */ 14526 protected boolean setFrame(int left, int top, int right, int bottom) { 14527 boolean changed = false; 14528 14529 if (DBG) { 14530 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 14531 + right + "," + bottom + ")"); 14532 } 14533 14534 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 14535 changed = true; 14536 14537 // Remember our drawn bit 14538 int drawn = mPrivateFlags & PFLAG_DRAWN; 14539 14540 int oldWidth = mRight - mLeft; 14541 int oldHeight = mBottom - mTop; 14542 int newWidth = right - left; 14543 int newHeight = bottom - top; 14544 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 14545 14546 // Invalidate our old position 14547 invalidate(sizeChanged); 14548 14549 mLeft = left; 14550 mTop = top; 14551 mRight = right; 14552 mBottom = bottom; 14553 if (mDisplayList != null) { 14554 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 14555 } 14556 14557 mPrivateFlags |= PFLAG_HAS_BOUNDS; 14558 14559 14560 if (sizeChanged) { 14561 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 14562 // A change in dimension means an auto-centered pivot point changes, too 14563 if (mTransformationInfo != null) { 14564 mTransformationInfo.mMatrixDirty = true; 14565 } 14566 } 14567 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 14568 } 14569 14570 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 14571 // If we are visible, force the DRAWN bit to on so that 14572 // this invalidate will go through (at least to our parent). 14573 // This is because someone may have invalidated this view 14574 // before this call to setFrame came in, thereby clearing 14575 // the DRAWN bit. 14576 mPrivateFlags |= PFLAG_DRAWN; 14577 invalidate(sizeChanged); 14578 // parent display list may need to be recreated based on a change in the bounds 14579 // of any child 14580 invalidateParentCaches(); 14581 } 14582 14583 // Reset drawn bit to original value (invalidate turns it off) 14584 mPrivateFlags |= drawn; 14585 14586 mBackgroundSizeChanged = true; 14587 14588 notifySubtreeAccessibilityStateChangedIfNeeded(); 14589 } 14590 return changed; 14591 } 14592 14593 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 14594 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 14595 if (mOverlay != null) { 14596 mOverlay.getOverlayView().setRight(newWidth); 14597 mOverlay.getOverlayView().setBottom(newHeight); 14598 } 14599 } 14600 14601 /** 14602 * Finalize inflating a view from XML. This is called as the last phase 14603 * of inflation, after all child views have been added. 14604 * 14605 * <p>Even if the subclass overrides onFinishInflate, they should always be 14606 * sure to call the super method, so that we get called. 14607 */ 14608 protected void onFinishInflate() { 14609 } 14610 14611 /** 14612 * Returns the resources associated with this view. 14613 * 14614 * @return Resources object. 14615 */ 14616 public Resources getResources() { 14617 return mResources; 14618 } 14619 14620 /** 14621 * Invalidates the specified Drawable. 14622 * 14623 * @param drawable the drawable to invalidate 14624 */ 14625 public void invalidateDrawable(Drawable drawable) { 14626 if (verifyDrawable(drawable)) { 14627 final Rect dirty = drawable.getBounds(); 14628 final int scrollX = mScrollX; 14629 final int scrollY = mScrollY; 14630 14631 invalidate(dirty.left + scrollX, dirty.top + scrollY, 14632 dirty.right + scrollX, dirty.bottom + scrollY); 14633 } 14634 } 14635 14636 /** 14637 * Schedules an action on a drawable to occur at a specified time. 14638 * 14639 * @param who the recipient of the action 14640 * @param what the action to run on the drawable 14641 * @param when the time at which the action must occur. Uses the 14642 * {@link SystemClock#uptimeMillis} timebase. 14643 */ 14644 public void scheduleDrawable(Drawable who, Runnable what, long when) { 14645 if (verifyDrawable(who) && what != null) { 14646 final long delay = when - SystemClock.uptimeMillis(); 14647 if (mAttachInfo != null) { 14648 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 14649 Choreographer.CALLBACK_ANIMATION, what, who, 14650 Choreographer.subtractFrameDelay(delay)); 14651 } else { 14652 ViewRootImpl.getRunQueue().postDelayed(what, delay); 14653 } 14654 } 14655 } 14656 14657 /** 14658 * Cancels a scheduled action on a drawable. 14659 * 14660 * @param who the recipient of the action 14661 * @param what the action to cancel 14662 */ 14663 public void unscheduleDrawable(Drawable who, Runnable what) { 14664 if (verifyDrawable(who) && what != null) { 14665 if (mAttachInfo != null) { 14666 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14667 Choreographer.CALLBACK_ANIMATION, what, who); 14668 } else { 14669 ViewRootImpl.getRunQueue().removeCallbacks(what); 14670 } 14671 } 14672 } 14673 14674 /** 14675 * Unschedule any events associated with the given Drawable. This can be 14676 * used when selecting a new Drawable into a view, so that the previous 14677 * one is completely unscheduled. 14678 * 14679 * @param who The Drawable to unschedule. 14680 * 14681 * @see #drawableStateChanged 14682 */ 14683 public void unscheduleDrawable(Drawable who) { 14684 if (mAttachInfo != null && who != null) { 14685 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14686 Choreographer.CALLBACK_ANIMATION, null, who); 14687 } 14688 } 14689 14690 /** 14691 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 14692 * that the View directionality can and will be resolved before its Drawables. 14693 * 14694 * Will call {@link View#onResolveDrawables} when resolution is done. 14695 * 14696 * @hide 14697 */ 14698 protected void resolveDrawables() { 14699 // Drawables resolution may need to happen before resolving the layout direction (which is 14700 // done only during the measure() call). 14701 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 14702 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 14703 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 14704 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 14705 // direction to be resolved as its resolved value will be the same as its raw value. 14706 if (!isLayoutDirectionResolved() && 14707 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 14708 return; 14709 } 14710 14711 final int layoutDirection = isLayoutDirectionResolved() ? 14712 getLayoutDirection() : getRawLayoutDirection(); 14713 14714 if (mBackground != null) { 14715 mBackground.setLayoutDirection(layoutDirection); 14716 } 14717 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 14718 onResolveDrawables(layoutDirection); 14719 } 14720 14721 /** 14722 * Called when layout direction has been resolved. 14723 * 14724 * The default implementation does nothing. 14725 * 14726 * @param layoutDirection The resolved layout direction. 14727 * 14728 * @see #LAYOUT_DIRECTION_LTR 14729 * @see #LAYOUT_DIRECTION_RTL 14730 * 14731 * @hide 14732 */ 14733 public void onResolveDrawables(int layoutDirection) { 14734 } 14735 14736 /** 14737 * @hide 14738 */ 14739 protected void resetResolvedDrawables() { 14740 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 14741 } 14742 14743 private boolean isDrawablesResolved() { 14744 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 14745 } 14746 14747 /** 14748 * If your view subclass is displaying its own Drawable objects, it should 14749 * override this function and return true for any Drawable it is 14750 * displaying. This allows animations for those drawables to be 14751 * scheduled. 14752 * 14753 * <p>Be sure to call through to the super class when overriding this 14754 * function. 14755 * 14756 * @param who The Drawable to verify. Return true if it is one you are 14757 * displaying, else return the result of calling through to the 14758 * super class. 14759 * 14760 * @return boolean If true than the Drawable is being displayed in the 14761 * view; else false and it is not allowed to animate. 14762 * 14763 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 14764 * @see #drawableStateChanged() 14765 */ 14766 protected boolean verifyDrawable(Drawable who) { 14767 return who == mBackground; 14768 } 14769 14770 /** 14771 * This function is called whenever the state of the view changes in such 14772 * a way that it impacts the state of drawables being shown. 14773 * 14774 * <p>Be sure to call through to the superclass when overriding this 14775 * function. 14776 * 14777 * @see Drawable#setState(int[]) 14778 */ 14779 protected void drawableStateChanged() { 14780 Drawable d = mBackground; 14781 if (d != null && d.isStateful()) { 14782 d.setState(getDrawableState()); 14783 } 14784 } 14785 14786 /** 14787 * Call this to force a view to update its drawable state. This will cause 14788 * drawableStateChanged to be called on this view. Views that are interested 14789 * in the new state should call getDrawableState. 14790 * 14791 * @see #drawableStateChanged 14792 * @see #getDrawableState 14793 */ 14794 public void refreshDrawableState() { 14795 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 14796 drawableStateChanged(); 14797 14798 ViewParent parent = mParent; 14799 if (parent != null) { 14800 parent.childDrawableStateChanged(this); 14801 } 14802 } 14803 14804 /** 14805 * Return an array of resource IDs of the drawable states representing the 14806 * current state of the view. 14807 * 14808 * @return The current drawable state 14809 * 14810 * @see Drawable#setState(int[]) 14811 * @see #drawableStateChanged() 14812 * @see #onCreateDrawableState(int) 14813 */ 14814 public final int[] getDrawableState() { 14815 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 14816 return mDrawableState; 14817 } else { 14818 mDrawableState = onCreateDrawableState(0); 14819 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 14820 return mDrawableState; 14821 } 14822 } 14823 14824 /** 14825 * Generate the new {@link android.graphics.drawable.Drawable} state for 14826 * this view. This is called by the view 14827 * system when the cached Drawable state is determined to be invalid. To 14828 * retrieve the current state, you should use {@link #getDrawableState}. 14829 * 14830 * @param extraSpace if non-zero, this is the number of extra entries you 14831 * would like in the returned array in which you can place your own 14832 * states. 14833 * 14834 * @return Returns an array holding the current {@link Drawable} state of 14835 * the view. 14836 * 14837 * @see #mergeDrawableStates(int[], int[]) 14838 */ 14839 protected int[] onCreateDrawableState(int extraSpace) { 14840 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 14841 mParent instanceof View) { 14842 return ((View) mParent).onCreateDrawableState(extraSpace); 14843 } 14844 14845 int[] drawableState; 14846 14847 int privateFlags = mPrivateFlags; 14848 14849 int viewStateIndex = 0; 14850 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 14851 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 14852 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 14853 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 14854 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 14855 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 14856 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 14857 HardwareRenderer.isAvailable()) { 14858 // This is set if HW acceleration is requested, even if the current 14859 // process doesn't allow it. This is just to allow app preview 14860 // windows to better match their app. 14861 viewStateIndex |= VIEW_STATE_ACCELERATED; 14862 } 14863 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 14864 14865 final int privateFlags2 = mPrivateFlags2; 14866 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 14867 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 14868 14869 drawableState = VIEW_STATE_SETS[viewStateIndex]; 14870 14871 //noinspection ConstantIfStatement 14872 if (false) { 14873 Log.i("View", "drawableStateIndex=" + viewStateIndex); 14874 Log.i("View", toString() 14875 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 14876 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 14877 + " fo=" + hasFocus() 14878 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 14879 + " wf=" + hasWindowFocus() 14880 + ": " + Arrays.toString(drawableState)); 14881 } 14882 14883 if (extraSpace == 0) { 14884 return drawableState; 14885 } 14886 14887 final int[] fullState; 14888 if (drawableState != null) { 14889 fullState = new int[drawableState.length + extraSpace]; 14890 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 14891 } else { 14892 fullState = new int[extraSpace]; 14893 } 14894 14895 return fullState; 14896 } 14897 14898 /** 14899 * Merge your own state values in <var>additionalState</var> into the base 14900 * state values <var>baseState</var> that were returned by 14901 * {@link #onCreateDrawableState(int)}. 14902 * 14903 * @param baseState The base state values returned by 14904 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 14905 * own additional state values. 14906 * 14907 * @param additionalState The additional state values you would like 14908 * added to <var>baseState</var>; this array is not modified. 14909 * 14910 * @return As a convenience, the <var>baseState</var> array you originally 14911 * passed into the function is returned. 14912 * 14913 * @see #onCreateDrawableState(int) 14914 */ 14915 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 14916 final int N = baseState.length; 14917 int i = N - 1; 14918 while (i >= 0 && baseState[i] == 0) { 14919 i--; 14920 } 14921 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 14922 return baseState; 14923 } 14924 14925 /** 14926 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 14927 * on all Drawable objects associated with this view. 14928 */ 14929 public void jumpDrawablesToCurrentState() { 14930 if (mBackground != null) { 14931 mBackground.jumpToCurrentState(); 14932 } 14933 } 14934 14935 /** 14936 * Sets the background color for this view. 14937 * @param color the color of the background 14938 */ 14939 @RemotableViewMethod 14940 public void setBackgroundColor(int color) { 14941 if (mBackground instanceof ColorDrawable) { 14942 ((ColorDrawable) mBackground.mutate()).setColor(color); 14943 computeOpaqueFlags(); 14944 mBackgroundResource = 0; 14945 } else { 14946 setBackground(new ColorDrawable(color)); 14947 } 14948 } 14949 14950 /** 14951 * Set the background to a given resource. The resource should refer to 14952 * a Drawable object or 0 to remove the background. 14953 * @param resid The identifier of the resource. 14954 * 14955 * @attr ref android.R.styleable#View_background 14956 */ 14957 @RemotableViewMethod 14958 public void setBackgroundResource(int resid) { 14959 if (resid != 0 && resid == mBackgroundResource) { 14960 return; 14961 } 14962 14963 Drawable d= null; 14964 if (resid != 0) { 14965 d = mResources.getDrawable(resid); 14966 } 14967 setBackground(d); 14968 14969 mBackgroundResource = resid; 14970 } 14971 14972 /** 14973 * Set the background to a given Drawable, or remove the background. If the 14974 * background has padding, this View's padding is set to the background's 14975 * padding. However, when a background is removed, this View's padding isn't 14976 * touched. If setting the padding is desired, please use 14977 * {@link #setPadding(int, int, int, int)}. 14978 * 14979 * @param background The Drawable to use as the background, or null to remove the 14980 * background 14981 */ 14982 public void setBackground(Drawable background) { 14983 //noinspection deprecation 14984 setBackgroundDrawable(background); 14985 } 14986 14987 /** 14988 * @deprecated use {@link #setBackground(Drawable)} instead 14989 */ 14990 @Deprecated 14991 public void setBackgroundDrawable(Drawable background) { 14992 computeOpaqueFlags(); 14993 14994 if (background == mBackground) { 14995 return; 14996 } 14997 14998 boolean requestLayout = false; 14999 15000 mBackgroundResource = 0; 15001 15002 /* 15003 * Regardless of whether we're setting a new background or not, we want 15004 * to clear the previous drawable. 15005 */ 15006 if (mBackground != null) { 15007 mBackground.setCallback(null); 15008 unscheduleDrawable(mBackground); 15009 } 15010 15011 if (background != null) { 15012 Rect padding = sThreadLocal.get(); 15013 if (padding == null) { 15014 padding = new Rect(); 15015 sThreadLocal.set(padding); 15016 } 15017 resetResolvedDrawables(); 15018 background.setLayoutDirection(getLayoutDirection()); 15019 if (background.getPadding(padding)) { 15020 resetResolvedPadding(); 15021 switch (background.getLayoutDirection()) { 15022 case LAYOUT_DIRECTION_RTL: 15023 mUserPaddingLeftInitial = padding.right; 15024 mUserPaddingRightInitial = padding.left; 15025 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15026 break; 15027 case LAYOUT_DIRECTION_LTR: 15028 default: 15029 mUserPaddingLeftInitial = padding.left; 15030 mUserPaddingRightInitial = padding.right; 15031 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15032 } 15033 } 15034 15035 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15036 // if it has a different minimum size, we should layout again 15037 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 15038 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15039 requestLayout = true; 15040 } 15041 15042 background.setCallback(this); 15043 if (background.isStateful()) { 15044 background.setState(getDrawableState()); 15045 } 15046 background.setVisible(getVisibility() == VISIBLE, false); 15047 mBackground = background; 15048 15049 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15050 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15051 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15052 requestLayout = true; 15053 } 15054 } else { 15055 /* Remove the background */ 15056 mBackground = null; 15057 15058 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15059 /* 15060 * This view ONLY drew the background before and we're removing 15061 * the background, so now it won't draw anything 15062 * (hence we SKIP_DRAW) 15063 */ 15064 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15065 mPrivateFlags |= PFLAG_SKIP_DRAW; 15066 } 15067 15068 /* 15069 * When the background is set, we try to apply its padding to this 15070 * View. When the background is removed, we don't touch this View's 15071 * padding. This is noted in the Javadocs. Hence, we don't need to 15072 * requestLayout(), the invalidate() below is sufficient. 15073 */ 15074 15075 // The old background's minimum size could have affected this 15076 // View's layout, so let's requestLayout 15077 requestLayout = true; 15078 } 15079 15080 computeOpaqueFlags(); 15081 15082 if (requestLayout) { 15083 requestLayout(); 15084 } 15085 15086 mBackgroundSizeChanged = true; 15087 invalidate(true); 15088 } 15089 15090 /** 15091 * Gets the background drawable 15092 * 15093 * @return The drawable used as the background for this view, if any. 15094 * 15095 * @see #setBackground(Drawable) 15096 * 15097 * @attr ref android.R.styleable#View_background 15098 */ 15099 public Drawable getBackground() { 15100 return mBackground; 15101 } 15102 15103 /** 15104 * Sets the padding. The view may add on the space required to display 15105 * the scrollbars, depending on the style and visibility of the scrollbars. 15106 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15107 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15108 * from the values set in this call. 15109 * 15110 * @attr ref android.R.styleable#View_padding 15111 * @attr ref android.R.styleable#View_paddingBottom 15112 * @attr ref android.R.styleable#View_paddingLeft 15113 * @attr ref android.R.styleable#View_paddingRight 15114 * @attr ref android.R.styleable#View_paddingTop 15115 * @param left the left padding in pixels 15116 * @param top the top padding in pixels 15117 * @param right the right padding in pixels 15118 * @param bottom the bottom padding in pixels 15119 */ 15120 public void setPadding(int left, int top, int right, int bottom) { 15121 resetResolvedPadding(); 15122 15123 mUserPaddingStart = UNDEFINED_PADDING; 15124 mUserPaddingEnd = UNDEFINED_PADDING; 15125 15126 mUserPaddingLeftInitial = left; 15127 mUserPaddingRightInitial = right; 15128 15129 internalSetPadding(left, top, right, bottom); 15130 } 15131 15132 /** 15133 * @hide 15134 */ 15135 protected void internalSetPadding(int left, int top, int right, int bottom) { 15136 mUserPaddingLeft = left; 15137 mUserPaddingRight = right; 15138 mUserPaddingBottom = bottom; 15139 15140 final int viewFlags = mViewFlags; 15141 boolean changed = false; 15142 15143 // Common case is there are no scroll bars. 15144 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15145 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15146 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15147 ? 0 : getVerticalScrollbarWidth(); 15148 switch (mVerticalScrollbarPosition) { 15149 case SCROLLBAR_POSITION_DEFAULT: 15150 if (isLayoutRtl()) { 15151 left += offset; 15152 } else { 15153 right += offset; 15154 } 15155 break; 15156 case SCROLLBAR_POSITION_RIGHT: 15157 right += offset; 15158 break; 15159 case SCROLLBAR_POSITION_LEFT: 15160 left += offset; 15161 break; 15162 } 15163 } 15164 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 15165 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 15166 ? 0 : getHorizontalScrollbarHeight(); 15167 } 15168 } 15169 15170 if (mPaddingLeft != left) { 15171 changed = true; 15172 mPaddingLeft = left; 15173 } 15174 if (mPaddingTop != top) { 15175 changed = true; 15176 mPaddingTop = top; 15177 } 15178 if (mPaddingRight != right) { 15179 changed = true; 15180 mPaddingRight = right; 15181 } 15182 if (mPaddingBottom != bottom) { 15183 changed = true; 15184 mPaddingBottom = bottom; 15185 } 15186 15187 if (changed) { 15188 requestLayout(); 15189 } 15190 } 15191 15192 /** 15193 * Sets the relative padding. The view may add on the space required to display 15194 * the scrollbars, depending on the style and visibility of the scrollbars. 15195 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 15196 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 15197 * from the values set in this call. 15198 * 15199 * @attr ref android.R.styleable#View_padding 15200 * @attr ref android.R.styleable#View_paddingBottom 15201 * @attr ref android.R.styleable#View_paddingStart 15202 * @attr ref android.R.styleable#View_paddingEnd 15203 * @attr ref android.R.styleable#View_paddingTop 15204 * @param start the start padding in pixels 15205 * @param top the top padding in pixels 15206 * @param end the end padding in pixels 15207 * @param bottom the bottom padding in pixels 15208 */ 15209 public void setPaddingRelative(int start, int top, int end, int bottom) { 15210 resetResolvedPadding(); 15211 15212 mUserPaddingStart = start; 15213 mUserPaddingEnd = end; 15214 15215 switch(getLayoutDirection()) { 15216 case LAYOUT_DIRECTION_RTL: 15217 mUserPaddingLeftInitial = end; 15218 mUserPaddingRightInitial = start; 15219 internalSetPadding(end, top, start, bottom); 15220 break; 15221 case LAYOUT_DIRECTION_LTR: 15222 default: 15223 mUserPaddingLeftInitial = start; 15224 mUserPaddingRightInitial = end; 15225 internalSetPadding(start, top, end, bottom); 15226 } 15227 } 15228 15229 /** 15230 * Returns the top padding of this view. 15231 * 15232 * @return the top padding in pixels 15233 */ 15234 public int getPaddingTop() { 15235 return mPaddingTop; 15236 } 15237 15238 /** 15239 * Returns the bottom padding of this view. If there are inset and enabled 15240 * scrollbars, this value may include the space required to display the 15241 * scrollbars as well. 15242 * 15243 * @return the bottom padding in pixels 15244 */ 15245 public int getPaddingBottom() { 15246 return mPaddingBottom; 15247 } 15248 15249 /** 15250 * Returns the left padding of this view. If there are inset and enabled 15251 * scrollbars, this value may include the space required to display the 15252 * scrollbars as well. 15253 * 15254 * @return the left padding in pixels 15255 */ 15256 public int getPaddingLeft() { 15257 if (!isPaddingResolved()) { 15258 resolvePadding(); 15259 } 15260 return mPaddingLeft; 15261 } 15262 15263 /** 15264 * Returns the start padding of this view depending on its resolved layout direction. 15265 * If there are inset and enabled scrollbars, this value may include the space 15266 * required to display the scrollbars as well. 15267 * 15268 * @return the start padding in pixels 15269 */ 15270 public int getPaddingStart() { 15271 if (!isPaddingResolved()) { 15272 resolvePadding(); 15273 } 15274 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 15275 mPaddingRight : mPaddingLeft; 15276 } 15277 15278 /** 15279 * Returns the right padding of this view. If there are inset and enabled 15280 * scrollbars, this value may include the space required to display the 15281 * scrollbars as well. 15282 * 15283 * @return the right padding in pixels 15284 */ 15285 public int getPaddingRight() { 15286 if (!isPaddingResolved()) { 15287 resolvePadding(); 15288 } 15289 return mPaddingRight; 15290 } 15291 15292 /** 15293 * Returns the end padding of this view depending on its resolved layout direction. 15294 * If there are inset and enabled scrollbars, this value may include the space 15295 * required to display the scrollbars as well. 15296 * 15297 * @return the end padding in pixels 15298 */ 15299 public int getPaddingEnd() { 15300 if (!isPaddingResolved()) { 15301 resolvePadding(); 15302 } 15303 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 15304 mPaddingLeft : mPaddingRight; 15305 } 15306 15307 /** 15308 * Return if the padding as been set thru relative values 15309 * {@link #setPaddingRelative(int, int, int, int)} or thru 15310 * @attr ref android.R.styleable#View_paddingStart or 15311 * @attr ref android.R.styleable#View_paddingEnd 15312 * 15313 * @return true if the padding is relative or false if it is not. 15314 */ 15315 public boolean isPaddingRelative() { 15316 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 15317 } 15318 15319 Insets computeOpticalInsets() { 15320 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 15321 } 15322 15323 /** 15324 * @hide 15325 */ 15326 public void resetPaddingToInitialValues() { 15327 if (isRtlCompatibilityMode()) { 15328 mPaddingLeft = mUserPaddingLeftInitial; 15329 mPaddingRight = mUserPaddingRightInitial; 15330 return; 15331 } 15332 if (isLayoutRtl()) { 15333 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 15334 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 15335 } else { 15336 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 15337 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 15338 } 15339 } 15340 15341 /** 15342 * @hide 15343 */ 15344 public Insets getOpticalInsets() { 15345 if (mLayoutInsets == null) { 15346 mLayoutInsets = computeOpticalInsets(); 15347 } 15348 return mLayoutInsets; 15349 } 15350 15351 /** 15352 * Changes the selection state of this view. A view can be selected or not. 15353 * Note that selection is not the same as focus. Views are typically 15354 * selected in the context of an AdapterView like ListView or GridView; 15355 * the selected view is the view that is highlighted. 15356 * 15357 * @param selected true if the view must be selected, false otherwise 15358 */ 15359 public void setSelected(boolean selected) { 15360 //noinspection DoubleNegation 15361 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 15362 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 15363 if (!selected) resetPressedState(); 15364 invalidate(true); 15365 refreshDrawableState(); 15366 dispatchSetSelected(selected); 15367 notifyViewAccessibilityStateChangedIfNeeded(); 15368 } 15369 } 15370 15371 /** 15372 * Dispatch setSelected to all of this View's children. 15373 * 15374 * @see #setSelected(boolean) 15375 * 15376 * @param selected The new selected state 15377 */ 15378 protected void dispatchSetSelected(boolean selected) { 15379 } 15380 15381 /** 15382 * Indicates the selection state of this view. 15383 * 15384 * @return true if the view is selected, false otherwise 15385 */ 15386 @ViewDebug.ExportedProperty 15387 public boolean isSelected() { 15388 return (mPrivateFlags & PFLAG_SELECTED) != 0; 15389 } 15390 15391 /** 15392 * Changes the activated state of this view. A view can be activated or not. 15393 * Note that activation is not the same as selection. Selection is 15394 * a transient property, representing the view (hierarchy) the user is 15395 * currently interacting with. Activation is a longer-term state that the 15396 * user can move views in and out of. For example, in a list view with 15397 * single or multiple selection enabled, the views in the current selection 15398 * set are activated. (Um, yeah, we are deeply sorry about the terminology 15399 * here.) The activated state is propagated down to children of the view it 15400 * is set on. 15401 * 15402 * @param activated true if the view must be activated, false otherwise 15403 */ 15404 public void setActivated(boolean activated) { 15405 //noinspection DoubleNegation 15406 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 15407 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 15408 invalidate(true); 15409 refreshDrawableState(); 15410 dispatchSetActivated(activated); 15411 } 15412 } 15413 15414 /** 15415 * Dispatch setActivated to all of this View's children. 15416 * 15417 * @see #setActivated(boolean) 15418 * 15419 * @param activated The new activated state 15420 */ 15421 protected void dispatchSetActivated(boolean activated) { 15422 } 15423 15424 /** 15425 * Indicates the activation state of this view. 15426 * 15427 * @return true if the view is activated, false otherwise 15428 */ 15429 @ViewDebug.ExportedProperty 15430 public boolean isActivated() { 15431 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 15432 } 15433 15434 /** 15435 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 15436 * observer can be used to get notifications when global events, like 15437 * layout, happen. 15438 * 15439 * The returned ViewTreeObserver observer is not guaranteed to remain 15440 * valid for the lifetime of this View. If the caller of this method keeps 15441 * a long-lived reference to ViewTreeObserver, it should always check for 15442 * the return value of {@link ViewTreeObserver#isAlive()}. 15443 * 15444 * @return The ViewTreeObserver for this view's hierarchy. 15445 */ 15446 public ViewTreeObserver getViewTreeObserver() { 15447 if (mAttachInfo != null) { 15448 return mAttachInfo.mTreeObserver; 15449 } 15450 if (mFloatingTreeObserver == null) { 15451 mFloatingTreeObserver = new ViewTreeObserver(); 15452 } 15453 return mFloatingTreeObserver; 15454 } 15455 15456 /** 15457 * <p>Finds the topmost view in the current view hierarchy.</p> 15458 * 15459 * @return the topmost view containing this view 15460 */ 15461 public View getRootView() { 15462 if (mAttachInfo != null) { 15463 final View v = mAttachInfo.mRootView; 15464 if (v != null) { 15465 return v; 15466 } 15467 } 15468 15469 View parent = this; 15470 15471 while (parent.mParent != null && parent.mParent instanceof View) { 15472 parent = (View) parent.mParent; 15473 } 15474 15475 return parent; 15476 } 15477 15478 /** 15479 * Transforms a motion event from view-local coordinates to on-screen 15480 * coordinates. 15481 * 15482 * @param ev the view-local motion event 15483 * @return false if the transformation could not be applied 15484 * @hide 15485 */ 15486 public boolean toGlobalMotionEvent(MotionEvent ev) { 15487 final AttachInfo info = mAttachInfo; 15488 if (info == null) { 15489 return false; 15490 } 15491 15492 transformMotionEventToGlobal(ev); 15493 ev.offsetLocation(info.mWindowLeft, info.mWindowTop); 15494 return true; 15495 } 15496 15497 /** 15498 * Transforms a motion event from on-screen coordinates to view-local 15499 * coordinates. 15500 * 15501 * @param ev the on-screen motion event 15502 * @return false if the transformation could not be applied 15503 * @hide 15504 */ 15505 public boolean toLocalMotionEvent(MotionEvent ev) { 15506 final AttachInfo info = mAttachInfo; 15507 if (info == null) { 15508 return false; 15509 } 15510 15511 ev.offsetLocation(-info.mWindowLeft, -info.mWindowTop); 15512 transformMotionEventToLocal(ev); 15513 return true; 15514 } 15515 15516 /** 15517 * Recursive helper method that applies transformations in post-order. 15518 * 15519 * @param ev the on-screen motion event 15520 */ 15521 private void transformMotionEventToLocal(MotionEvent ev) { 15522 final ViewParent parent = mParent; 15523 if (parent instanceof View) { 15524 final View vp = (View) parent; 15525 vp.transformMotionEventToLocal(ev); 15526 ev.offsetLocation(vp.mScrollX, vp.mScrollY); 15527 } else if (parent instanceof ViewRootImpl) { 15528 final ViewRootImpl vr = (ViewRootImpl) parent; 15529 ev.offsetLocation(0, vr.mCurScrollY); 15530 } 15531 15532 ev.offsetLocation(-mLeft, -mTop); 15533 15534 if (!hasIdentityMatrix()) { 15535 ev.transform(getInverseMatrix()); 15536 } 15537 } 15538 15539 /** 15540 * Recursive helper method that applies transformations in pre-order. 15541 * 15542 * @param ev the on-screen motion event 15543 */ 15544 private void transformMotionEventToGlobal(MotionEvent ev) { 15545 if (!hasIdentityMatrix()) { 15546 ev.transform(getMatrix()); 15547 } 15548 15549 ev.offsetLocation(mLeft, mTop); 15550 15551 final ViewParent parent = mParent; 15552 if (parent instanceof View) { 15553 final View vp = (View) parent; 15554 ev.offsetLocation(-vp.mScrollX, -vp.mScrollY); 15555 vp.transformMotionEventToGlobal(ev); 15556 } else if (parent instanceof ViewRootImpl) { 15557 final ViewRootImpl vr = (ViewRootImpl) parent; 15558 ev.offsetLocation(0, -vr.mCurScrollY); 15559 } 15560 } 15561 15562 /** 15563 * <p>Computes the coordinates of this view on the screen. The argument 15564 * must be an array of two integers. After the method returns, the array 15565 * contains the x and y location in that order.</p> 15566 * 15567 * @param location an array of two integers in which to hold the coordinates 15568 */ 15569 public void getLocationOnScreen(int[] location) { 15570 getLocationInWindow(location); 15571 15572 final AttachInfo info = mAttachInfo; 15573 if (info != null) { 15574 location[0] += info.mWindowLeft; 15575 location[1] += info.mWindowTop; 15576 } 15577 } 15578 15579 /** 15580 * <p>Computes the coordinates of this view in its window. The argument 15581 * must be an array of two integers. After the method returns, the array 15582 * contains the x and y location in that order.</p> 15583 * 15584 * @param location an array of two integers in which to hold the coordinates 15585 */ 15586 public void getLocationInWindow(int[] location) { 15587 if (location == null || location.length < 2) { 15588 throw new IllegalArgumentException("location must be an array of two integers"); 15589 } 15590 15591 if (mAttachInfo == null) { 15592 // When the view is not attached to a window, this method does not make sense 15593 location[0] = location[1] = 0; 15594 return; 15595 } 15596 15597 float[] position = mAttachInfo.mTmpTransformLocation; 15598 position[0] = position[1] = 0.0f; 15599 15600 if (!hasIdentityMatrix()) { 15601 getMatrix().mapPoints(position); 15602 } 15603 15604 position[0] += mLeft; 15605 position[1] += mTop; 15606 15607 ViewParent viewParent = mParent; 15608 while (viewParent instanceof View) { 15609 final View view = (View) viewParent; 15610 15611 position[0] -= view.mScrollX; 15612 position[1] -= view.mScrollY; 15613 15614 if (!view.hasIdentityMatrix()) { 15615 view.getMatrix().mapPoints(position); 15616 } 15617 15618 position[0] += view.mLeft; 15619 position[1] += view.mTop; 15620 15621 viewParent = view.mParent; 15622 } 15623 15624 if (viewParent instanceof ViewRootImpl) { 15625 // *cough* 15626 final ViewRootImpl vr = (ViewRootImpl) viewParent; 15627 position[1] -= vr.mCurScrollY; 15628 } 15629 15630 location[0] = (int) (position[0] + 0.5f); 15631 location[1] = (int) (position[1] + 0.5f); 15632 } 15633 15634 /** 15635 * {@hide} 15636 * @param id the id of the view to be found 15637 * @return the view of the specified id, null if cannot be found 15638 */ 15639 protected View findViewTraversal(int id) { 15640 if (id == mID) { 15641 return this; 15642 } 15643 return null; 15644 } 15645 15646 /** 15647 * {@hide} 15648 * @param tag the tag of the view to be found 15649 * @return the view of specified tag, null if cannot be found 15650 */ 15651 protected View findViewWithTagTraversal(Object tag) { 15652 if (tag != null && tag.equals(mTag)) { 15653 return this; 15654 } 15655 return null; 15656 } 15657 15658 /** 15659 * {@hide} 15660 * @param predicate The predicate to evaluate. 15661 * @param childToSkip If not null, ignores this child during the recursive traversal. 15662 * @return The first view that matches the predicate or null. 15663 */ 15664 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 15665 if (predicate.apply(this)) { 15666 return this; 15667 } 15668 return null; 15669 } 15670 15671 /** 15672 * Look for a child view with the given id. If this view has the given 15673 * id, return this view. 15674 * 15675 * @param id The id to search for. 15676 * @return The view that has the given id in the hierarchy or null 15677 */ 15678 public final View findViewById(int id) { 15679 if (id < 0) { 15680 return null; 15681 } 15682 return findViewTraversal(id); 15683 } 15684 15685 /** 15686 * Finds a view by its unuque and stable accessibility id. 15687 * 15688 * @param accessibilityId The searched accessibility id. 15689 * @return The found view. 15690 */ 15691 final View findViewByAccessibilityId(int accessibilityId) { 15692 if (accessibilityId < 0) { 15693 return null; 15694 } 15695 return findViewByAccessibilityIdTraversal(accessibilityId); 15696 } 15697 15698 /** 15699 * Performs the traversal to find a view by its unuque and stable accessibility id. 15700 * 15701 * <strong>Note:</strong>This method does not stop at the root namespace 15702 * boundary since the user can touch the screen at an arbitrary location 15703 * potentially crossing the root namespace bounday which will send an 15704 * accessibility event to accessibility services and they should be able 15705 * to obtain the event source. Also accessibility ids are guaranteed to be 15706 * unique in the window. 15707 * 15708 * @param accessibilityId The accessibility id. 15709 * @return The found view. 15710 * 15711 * @hide 15712 */ 15713 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 15714 if (getAccessibilityViewId() == accessibilityId) { 15715 return this; 15716 } 15717 return null; 15718 } 15719 15720 /** 15721 * Look for a child view with the given tag. If this view has the given 15722 * tag, return this view. 15723 * 15724 * @param tag The tag to search for, using "tag.equals(getTag())". 15725 * @return The View that has the given tag in the hierarchy or null 15726 */ 15727 public final View findViewWithTag(Object tag) { 15728 if (tag == null) { 15729 return null; 15730 } 15731 return findViewWithTagTraversal(tag); 15732 } 15733 15734 /** 15735 * {@hide} 15736 * Look for a child view that matches the specified predicate. 15737 * If this view matches the predicate, return this view. 15738 * 15739 * @param predicate The predicate to evaluate. 15740 * @return The first view that matches the predicate or null. 15741 */ 15742 public final View findViewByPredicate(Predicate<View> predicate) { 15743 return findViewByPredicateTraversal(predicate, null); 15744 } 15745 15746 /** 15747 * {@hide} 15748 * Look for a child view that matches the specified predicate, 15749 * starting with the specified view and its descendents and then 15750 * recusively searching the ancestors and siblings of that view 15751 * until this view is reached. 15752 * 15753 * This method is useful in cases where the predicate does not match 15754 * a single unique view (perhaps multiple views use the same id) 15755 * and we are trying to find the view that is "closest" in scope to the 15756 * starting view. 15757 * 15758 * @param start The view to start from. 15759 * @param predicate The predicate to evaluate. 15760 * @return The first view that matches the predicate or null. 15761 */ 15762 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 15763 View childToSkip = null; 15764 for (;;) { 15765 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 15766 if (view != null || start == this) { 15767 return view; 15768 } 15769 15770 ViewParent parent = start.getParent(); 15771 if (parent == null || !(parent instanceof View)) { 15772 return null; 15773 } 15774 15775 childToSkip = start; 15776 start = (View) parent; 15777 } 15778 } 15779 15780 /** 15781 * Sets the identifier for this view. The identifier does not have to be 15782 * unique in this view's hierarchy. The identifier should be a positive 15783 * number. 15784 * 15785 * @see #NO_ID 15786 * @see #getId() 15787 * @see #findViewById(int) 15788 * 15789 * @param id a number used to identify the view 15790 * 15791 * @attr ref android.R.styleable#View_id 15792 */ 15793 public void setId(int id) { 15794 mID = id; 15795 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 15796 mID = generateViewId(); 15797 } 15798 } 15799 15800 /** 15801 * {@hide} 15802 * 15803 * @param isRoot true if the view belongs to the root namespace, false 15804 * otherwise 15805 */ 15806 public void setIsRootNamespace(boolean isRoot) { 15807 if (isRoot) { 15808 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 15809 } else { 15810 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 15811 } 15812 } 15813 15814 /** 15815 * {@hide} 15816 * 15817 * @return true if the view belongs to the root namespace, false otherwise 15818 */ 15819 public boolean isRootNamespace() { 15820 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 15821 } 15822 15823 /** 15824 * Returns this view's identifier. 15825 * 15826 * @return a positive integer used to identify the view or {@link #NO_ID} 15827 * if the view has no ID 15828 * 15829 * @see #setId(int) 15830 * @see #findViewById(int) 15831 * @attr ref android.R.styleable#View_id 15832 */ 15833 @ViewDebug.CapturedViewProperty 15834 public int getId() { 15835 return mID; 15836 } 15837 15838 /** 15839 * Returns this view's tag. 15840 * 15841 * @return the Object stored in this view as a tag 15842 * 15843 * @see #setTag(Object) 15844 * @see #getTag(int) 15845 */ 15846 @ViewDebug.ExportedProperty 15847 public Object getTag() { 15848 return mTag; 15849 } 15850 15851 /** 15852 * Sets the tag associated with this view. A tag can be used to mark 15853 * a view in its hierarchy and does not have to be unique within the 15854 * hierarchy. Tags can also be used to store data within a view without 15855 * resorting to another data structure. 15856 * 15857 * @param tag an Object to tag the view with 15858 * 15859 * @see #getTag() 15860 * @see #setTag(int, Object) 15861 */ 15862 public void setTag(final Object tag) { 15863 mTag = tag; 15864 } 15865 15866 /** 15867 * Returns the tag associated with this view and the specified key. 15868 * 15869 * @param key The key identifying the tag 15870 * 15871 * @return the Object stored in this view as a tag 15872 * 15873 * @see #setTag(int, Object) 15874 * @see #getTag() 15875 */ 15876 public Object getTag(int key) { 15877 if (mKeyedTags != null) return mKeyedTags.get(key); 15878 return null; 15879 } 15880 15881 /** 15882 * Sets a tag associated with this view and a key. A tag can be used 15883 * to mark a view in its hierarchy and does not have to be unique within 15884 * the hierarchy. Tags can also be used to store data within a view 15885 * without resorting to another data structure. 15886 * 15887 * The specified key should be an id declared in the resources of the 15888 * application to ensure it is unique (see the <a 15889 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 15890 * Keys identified as belonging to 15891 * the Android framework or not associated with any package will cause 15892 * an {@link IllegalArgumentException} to be thrown. 15893 * 15894 * @param key The key identifying the tag 15895 * @param tag An Object to tag the view with 15896 * 15897 * @throws IllegalArgumentException If they specified key is not valid 15898 * 15899 * @see #setTag(Object) 15900 * @see #getTag(int) 15901 */ 15902 public void setTag(int key, final Object tag) { 15903 // If the package id is 0x00 or 0x01, it's either an undefined package 15904 // or a framework id 15905 if ((key >>> 24) < 2) { 15906 throw new IllegalArgumentException("The key must be an application-specific " 15907 + "resource id."); 15908 } 15909 15910 setKeyedTag(key, tag); 15911 } 15912 15913 /** 15914 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 15915 * framework id. 15916 * 15917 * @hide 15918 */ 15919 public void setTagInternal(int key, Object tag) { 15920 if ((key >>> 24) != 0x1) { 15921 throw new IllegalArgumentException("The key must be a framework-specific " 15922 + "resource id."); 15923 } 15924 15925 setKeyedTag(key, tag); 15926 } 15927 15928 private void setKeyedTag(int key, Object tag) { 15929 if (mKeyedTags == null) { 15930 mKeyedTags = new SparseArray<Object>(2); 15931 } 15932 15933 mKeyedTags.put(key, tag); 15934 } 15935 15936 /** 15937 * Prints information about this view in the log output, with the tag 15938 * {@link #VIEW_LOG_TAG}. 15939 * 15940 * @hide 15941 */ 15942 public void debug() { 15943 debug(0); 15944 } 15945 15946 /** 15947 * Prints information about this view in the log output, with the tag 15948 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 15949 * indentation defined by the <code>depth</code>. 15950 * 15951 * @param depth the indentation level 15952 * 15953 * @hide 15954 */ 15955 protected void debug(int depth) { 15956 String output = debugIndent(depth - 1); 15957 15958 output += "+ " + this; 15959 int id = getId(); 15960 if (id != -1) { 15961 output += " (id=" + id + ")"; 15962 } 15963 Object tag = getTag(); 15964 if (tag != null) { 15965 output += " (tag=" + tag + ")"; 15966 } 15967 Log.d(VIEW_LOG_TAG, output); 15968 15969 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 15970 output = debugIndent(depth) + " FOCUSED"; 15971 Log.d(VIEW_LOG_TAG, output); 15972 } 15973 15974 output = debugIndent(depth); 15975 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 15976 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 15977 + "} "; 15978 Log.d(VIEW_LOG_TAG, output); 15979 15980 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 15981 || mPaddingBottom != 0) { 15982 output = debugIndent(depth); 15983 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 15984 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 15985 Log.d(VIEW_LOG_TAG, output); 15986 } 15987 15988 output = debugIndent(depth); 15989 output += "mMeasureWidth=" + mMeasuredWidth + 15990 " mMeasureHeight=" + mMeasuredHeight; 15991 Log.d(VIEW_LOG_TAG, output); 15992 15993 output = debugIndent(depth); 15994 if (mLayoutParams == null) { 15995 output += "BAD! no layout params"; 15996 } else { 15997 output = mLayoutParams.debug(output); 15998 } 15999 Log.d(VIEW_LOG_TAG, output); 16000 16001 output = debugIndent(depth); 16002 output += "flags={"; 16003 output += View.printFlags(mViewFlags); 16004 output += "}"; 16005 Log.d(VIEW_LOG_TAG, output); 16006 16007 output = debugIndent(depth); 16008 output += "privateFlags={"; 16009 output += View.printPrivateFlags(mPrivateFlags); 16010 output += "}"; 16011 Log.d(VIEW_LOG_TAG, output); 16012 } 16013 16014 /** 16015 * Creates a string of whitespaces used for indentation. 16016 * 16017 * @param depth the indentation level 16018 * @return a String containing (depth * 2 + 3) * 2 white spaces 16019 * 16020 * @hide 16021 */ 16022 protected static String debugIndent(int depth) { 16023 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16024 for (int i = 0; i < (depth * 2) + 3; i++) { 16025 spaces.append(' ').append(' '); 16026 } 16027 return spaces.toString(); 16028 } 16029 16030 /** 16031 * <p>Return the offset of the widget's text baseline from the widget's top 16032 * boundary. If this widget does not support baseline alignment, this 16033 * method returns -1. </p> 16034 * 16035 * @return the offset of the baseline within the widget's bounds or -1 16036 * if baseline alignment is not supported 16037 */ 16038 @ViewDebug.ExportedProperty(category = "layout") 16039 public int getBaseline() { 16040 return -1; 16041 } 16042 16043 /** 16044 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16045 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16046 * a layout pass. 16047 * 16048 * @return whether the view hierarchy is currently undergoing a layout pass 16049 */ 16050 public boolean isInLayout() { 16051 ViewRootImpl viewRoot = getViewRootImpl(); 16052 return (viewRoot != null && viewRoot.isInLayout()); 16053 } 16054 16055 /** 16056 * Call this when something has changed which has invalidated the 16057 * layout of this view. This will schedule a layout pass of the view 16058 * tree. This should not be called while the view hierarchy is currently in a layout 16059 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16060 * end of the current layout pass (and then layout will run again) or after the current 16061 * frame is drawn and the next layout occurs. 16062 * 16063 * <p>Subclasses which override this method should call the superclass method to 16064 * handle possible request-during-layout errors correctly.</p> 16065 */ 16066 public void requestLayout() { 16067 if (mMeasureCache != null) mMeasureCache.clear(); 16068 16069 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16070 // Only trigger request-during-layout logic if this is the view requesting it, 16071 // not the views in its parent hierarchy 16072 ViewRootImpl viewRoot = getViewRootImpl(); 16073 if (viewRoot != null && viewRoot.isInLayout()) { 16074 if (!viewRoot.requestLayoutDuringLayout(this)) { 16075 return; 16076 } 16077 } 16078 mAttachInfo.mViewRequestingLayout = this; 16079 } 16080 16081 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16082 mPrivateFlags |= PFLAG_INVALIDATED; 16083 16084 if (mParent != null && !mParent.isLayoutRequested()) { 16085 mParent.requestLayout(); 16086 } 16087 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16088 mAttachInfo.mViewRequestingLayout = null; 16089 } 16090 } 16091 16092 /** 16093 * Forces this view to be laid out during the next layout pass. 16094 * This method does not call requestLayout() or forceLayout() 16095 * on the parent. 16096 */ 16097 public void forceLayout() { 16098 if (mMeasureCache != null) mMeasureCache.clear(); 16099 16100 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16101 mPrivateFlags |= PFLAG_INVALIDATED; 16102 } 16103 16104 /** 16105 * <p> 16106 * This is called to find out how big a view should be. The parent 16107 * supplies constraint information in the width and height parameters. 16108 * </p> 16109 * 16110 * <p> 16111 * The actual measurement work of a view is performed in 16112 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16113 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16114 * </p> 16115 * 16116 * 16117 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16118 * parent 16119 * @param heightMeasureSpec Vertical space requirements as imposed by the 16120 * parent 16121 * 16122 * @see #onMeasure(int, int) 16123 */ 16124 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16125 boolean optical = isLayoutModeOptical(this); 16126 if (optical != isLayoutModeOptical(mParent)) { 16127 Insets insets = getOpticalInsets(); 16128 int oWidth = insets.left + insets.right; 16129 int oHeight = insets.top + insets.bottom; 16130 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 16131 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 16132 } 16133 16134 // Suppress sign extension for the low bytes 16135 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 16136 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 16137 16138 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 16139 widthMeasureSpec != mOldWidthMeasureSpec || 16140 heightMeasureSpec != mOldHeightMeasureSpec) { 16141 16142 // first clears the measured dimension flag 16143 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 16144 16145 resolveRtlPropertiesIfNeeded(); 16146 16147 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 16148 mMeasureCache.indexOfKey(key); 16149 if (cacheIndex < 0) { 16150 // measure ourselves, this should set the measured dimension flag back 16151 onMeasure(widthMeasureSpec, heightMeasureSpec); 16152 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16153 } else { 16154 long value = mMeasureCache.valueAt(cacheIndex); 16155 // Casting a long to int drops the high 32 bits, no mask needed 16156 setMeasuredDimension((int) (value >> 32), (int) value); 16157 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16158 } 16159 16160 // flag not set, setMeasuredDimension() was not invoked, we raise 16161 // an exception to warn the developer 16162 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 16163 throw new IllegalStateException("onMeasure() did not set the" 16164 + " measured dimension by calling" 16165 + " setMeasuredDimension()"); 16166 } 16167 16168 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 16169 } 16170 16171 mOldWidthMeasureSpec = widthMeasureSpec; 16172 mOldHeightMeasureSpec = heightMeasureSpec; 16173 16174 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 16175 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 16176 } 16177 16178 /** 16179 * <p> 16180 * Measure the view and its content to determine the measured width and the 16181 * measured height. This method is invoked by {@link #measure(int, int)} and 16182 * should be overriden by subclasses to provide accurate and efficient 16183 * measurement of their contents. 16184 * </p> 16185 * 16186 * <p> 16187 * <strong>CONTRACT:</strong> When overriding this method, you 16188 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 16189 * measured width and height of this view. Failure to do so will trigger an 16190 * <code>IllegalStateException</code>, thrown by 16191 * {@link #measure(int, int)}. Calling the superclass' 16192 * {@link #onMeasure(int, int)} is a valid use. 16193 * </p> 16194 * 16195 * <p> 16196 * The base class implementation of measure defaults to the background size, 16197 * unless a larger size is allowed by the MeasureSpec. Subclasses should 16198 * override {@link #onMeasure(int, int)} to provide better measurements of 16199 * their content. 16200 * </p> 16201 * 16202 * <p> 16203 * If this method is overridden, it is the subclass's responsibility to make 16204 * sure the measured height and width are at least the view's minimum height 16205 * and width ({@link #getSuggestedMinimumHeight()} and 16206 * {@link #getSuggestedMinimumWidth()}). 16207 * </p> 16208 * 16209 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 16210 * The requirements are encoded with 16211 * {@link android.view.View.MeasureSpec}. 16212 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 16213 * The requirements are encoded with 16214 * {@link android.view.View.MeasureSpec}. 16215 * 16216 * @see #getMeasuredWidth() 16217 * @see #getMeasuredHeight() 16218 * @see #setMeasuredDimension(int, int) 16219 * @see #getSuggestedMinimumHeight() 16220 * @see #getSuggestedMinimumWidth() 16221 * @see android.view.View.MeasureSpec#getMode(int) 16222 * @see android.view.View.MeasureSpec#getSize(int) 16223 */ 16224 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 16225 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 16226 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 16227 } 16228 16229 /** 16230 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 16231 * measured width and measured height. Failing to do so will trigger an 16232 * exception at measurement time.</p> 16233 * 16234 * @param measuredWidth The measured width of this view. May be a complex 16235 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16236 * {@link #MEASURED_STATE_TOO_SMALL}. 16237 * @param measuredHeight The measured height of this view. May be a complex 16238 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16239 * {@link #MEASURED_STATE_TOO_SMALL}. 16240 */ 16241 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 16242 boolean optical = isLayoutModeOptical(this); 16243 if (optical != isLayoutModeOptical(mParent)) { 16244 Insets insets = getOpticalInsets(); 16245 int opticalWidth = insets.left + insets.right; 16246 int opticalHeight = insets.top + insets.bottom; 16247 16248 measuredWidth += optical ? opticalWidth : -opticalWidth; 16249 measuredHeight += optical ? opticalHeight : -opticalHeight; 16250 } 16251 mMeasuredWidth = measuredWidth; 16252 mMeasuredHeight = measuredHeight; 16253 16254 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 16255 } 16256 16257 /** 16258 * Merge two states as returned by {@link #getMeasuredState()}. 16259 * @param curState The current state as returned from a view or the result 16260 * of combining multiple views. 16261 * @param newState The new view state to combine. 16262 * @return Returns a new integer reflecting the combination of the two 16263 * states. 16264 */ 16265 public static int combineMeasuredStates(int curState, int newState) { 16266 return curState | newState; 16267 } 16268 16269 /** 16270 * Version of {@link #resolveSizeAndState(int, int, int)} 16271 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 16272 */ 16273 public static int resolveSize(int size, int measureSpec) { 16274 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 16275 } 16276 16277 /** 16278 * Utility to reconcile a desired size and state, with constraints imposed 16279 * by a MeasureSpec. Will take the desired size, unless a different size 16280 * is imposed by the constraints. The returned value is a compound integer, 16281 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 16282 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 16283 * size is smaller than the size the view wants to be. 16284 * 16285 * @param size How big the view wants to be 16286 * @param measureSpec Constraints imposed by the parent 16287 * @return Size information bit mask as defined by 16288 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 16289 */ 16290 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 16291 int result = size; 16292 int specMode = MeasureSpec.getMode(measureSpec); 16293 int specSize = MeasureSpec.getSize(measureSpec); 16294 switch (specMode) { 16295 case MeasureSpec.UNSPECIFIED: 16296 result = size; 16297 break; 16298 case MeasureSpec.AT_MOST: 16299 if (specSize < size) { 16300 result = specSize | MEASURED_STATE_TOO_SMALL; 16301 } else { 16302 result = size; 16303 } 16304 break; 16305 case MeasureSpec.EXACTLY: 16306 result = specSize; 16307 break; 16308 } 16309 return result | (childMeasuredState&MEASURED_STATE_MASK); 16310 } 16311 16312 /** 16313 * Utility to return a default size. Uses the supplied size if the 16314 * MeasureSpec imposed no constraints. Will get larger if allowed 16315 * by the MeasureSpec. 16316 * 16317 * @param size Default size for this view 16318 * @param measureSpec Constraints imposed by the parent 16319 * @return The size this view should be. 16320 */ 16321 public static int getDefaultSize(int size, int measureSpec) { 16322 int result = size; 16323 int specMode = MeasureSpec.getMode(measureSpec); 16324 int specSize = MeasureSpec.getSize(measureSpec); 16325 16326 switch (specMode) { 16327 case MeasureSpec.UNSPECIFIED: 16328 result = size; 16329 break; 16330 case MeasureSpec.AT_MOST: 16331 case MeasureSpec.EXACTLY: 16332 result = specSize; 16333 break; 16334 } 16335 return result; 16336 } 16337 16338 /** 16339 * Returns the suggested minimum height that the view should use. This 16340 * returns the maximum of the view's minimum height 16341 * and the background's minimum height 16342 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 16343 * <p> 16344 * When being used in {@link #onMeasure(int, int)}, the caller should still 16345 * ensure the returned height is within the requirements of the parent. 16346 * 16347 * @return The suggested minimum height of the view. 16348 */ 16349 protected int getSuggestedMinimumHeight() { 16350 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 16351 16352 } 16353 16354 /** 16355 * Returns the suggested minimum width that the view should use. This 16356 * returns the maximum of the view's minimum width) 16357 * and the background's minimum width 16358 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 16359 * <p> 16360 * When being used in {@link #onMeasure(int, int)}, the caller should still 16361 * ensure the returned width is within the requirements of the parent. 16362 * 16363 * @return The suggested minimum width of the view. 16364 */ 16365 protected int getSuggestedMinimumWidth() { 16366 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 16367 } 16368 16369 /** 16370 * Returns the minimum height of the view. 16371 * 16372 * @return the minimum height the view will try to be. 16373 * 16374 * @see #setMinimumHeight(int) 16375 * 16376 * @attr ref android.R.styleable#View_minHeight 16377 */ 16378 public int getMinimumHeight() { 16379 return mMinHeight; 16380 } 16381 16382 /** 16383 * Sets the minimum height of the view. It is not guaranteed the view will 16384 * be able to achieve this minimum height (for example, if its parent layout 16385 * constrains it with less available height). 16386 * 16387 * @param minHeight The minimum height the view will try to be. 16388 * 16389 * @see #getMinimumHeight() 16390 * 16391 * @attr ref android.R.styleable#View_minHeight 16392 */ 16393 public void setMinimumHeight(int minHeight) { 16394 mMinHeight = minHeight; 16395 requestLayout(); 16396 } 16397 16398 /** 16399 * Returns the minimum width of the view. 16400 * 16401 * @return the minimum width the view will try to be. 16402 * 16403 * @see #setMinimumWidth(int) 16404 * 16405 * @attr ref android.R.styleable#View_minWidth 16406 */ 16407 public int getMinimumWidth() { 16408 return mMinWidth; 16409 } 16410 16411 /** 16412 * Sets the minimum width of the view. It is not guaranteed the view will 16413 * be able to achieve this minimum width (for example, if its parent layout 16414 * constrains it with less available width). 16415 * 16416 * @param minWidth The minimum width the view will try to be. 16417 * 16418 * @see #getMinimumWidth() 16419 * 16420 * @attr ref android.R.styleable#View_minWidth 16421 */ 16422 public void setMinimumWidth(int minWidth) { 16423 mMinWidth = minWidth; 16424 requestLayout(); 16425 16426 } 16427 16428 /** 16429 * Get the animation currently associated with this view. 16430 * 16431 * @return The animation that is currently playing or 16432 * scheduled to play for this view. 16433 */ 16434 public Animation getAnimation() { 16435 return mCurrentAnimation; 16436 } 16437 16438 /** 16439 * Start the specified animation now. 16440 * 16441 * @param animation the animation to start now 16442 */ 16443 public void startAnimation(Animation animation) { 16444 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 16445 setAnimation(animation); 16446 invalidateParentCaches(); 16447 invalidate(true); 16448 } 16449 16450 /** 16451 * Cancels any animations for this view. 16452 */ 16453 public void clearAnimation() { 16454 if (mCurrentAnimation != null) { 16455 mCurrentAnimation.detach(); 16456 } 16457 mCurrentAnimation = null; 16458 invalidateParentIfNeeded(); 16459 } 16460 16461 /** 16462 * Sets the next animation to play for this view. 16463 * If you want the animation to play immediately, use 16464 * {@link #startAnimation(android.view.animation.Animation)} instead. 16465 * This method provides allows fine-grained 16466 * control over the start time and invalidation, but you 16467 * must make sure that 1) the animation has a start time set, and 16468 * 2) the view's parent (which controls animations on its children) 16469 * will be invalidated when the animation is supposed to 16470 * start. 16471 * 16472 * @param animation The next animation, or null. 16473 */ 16474 public void setAnimation(Animation animation) { 16475 mCurrentAnimation = animation; 16476 16477 if (animation != null) { 16478 // If the screen is off assume the animation start time is now instead of 16479 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 16480 // would cause the animation to start when the screen turns back on 16481 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 16482 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 16483 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 16484 } 16485 animation.reset(); 16486 } 16487 } 16488 16489 /** 16490 * Invoked by a parent ViewGroup to notify the start of the animation 16491 * currently associated with this view. If you override this method, 16492 * always call super.onAnimationStart(); 16493 * 16494 * @see #setAnimation(android.view.animation.Animation) 16495 * @see #getAnimation() 16496 */ 16497 protected void onAnimationStart() { 16498 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 16499 } 16500 16501 /** 16502 * Invoked by a parent ViewGroup to notify the end of the animation 16503 * currently associated with this view. If you override this method, 16504 * always call super.onAnimationEnd(); 16505 * 16506 * @see #setAnimation(android.view.animation.Animation) 16507 * @see #getAnimation() 16508 */ 16509 protected void onAnimationEnd() { 16510 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 16511 } 16512 16513 /** 16514 * Invoked if there is a Transform that involves alpha. Subclass that can 16515 * draw themselves with the specified alpha should return true, and then 16516 * respect that alpha when their onDraw() is called. If this returns false 16517 * then the view may be redirected to draw into an offscreen buffer to 16518 * fulfill the request, which will look fine, but may be slower than if the 16519 * subclass handles it internally. The default implementation returns false. 16520 * 16521 * @param alpha The alpha (0..255) to apply to the view's drawing 16522 * @return true if the view can draw with the specified alpha. 16523 */ 16524 protected boolean onSetAlpha(int alpha) { 16525 return false; 16526 } 16527 16528 /** 16529 * This is used by the RootView to perform an optimization when 16530 * the view hierarchy contains one or several SurfaceView. 16531 * SurfaceView is always considered transparent, but its children are not, 16532 * therefore all View objects remove themselves from the global transparent 16533 * region (passed as a parameter to this function). 16534 * 16535 * @param region The transparent region for this ViewAncestor (window). 16536 * 16537 * @return Returns true if the effective visibility of the view at this 16538 * point is opaque, regardless of the transparent region; returns false 16539 * if it is possible for underlying windows to be seen behind the view. 16540 * 16541 * {@hide} 16542 */ 16543 public boolean gatherTransparentRegion(Region region) { 16544 final AttachInfo attachInfo = mAttachInfo; 16545 if (region != null && attachInfo != null) { 16546 final int pflags = mPrivateFlags; 16547 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 16548 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 16549 // remove it from the transparent region. 16550 final int[] location = attachInfo.mTransparentLocation; 16551 getLocationInWindow(location); 16552 region.op(location[0], location[1], location[0] + mRight - mLeft, 16553 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 16554 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 16555 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 16556 // exists, so we remove the background drawable's non-transparent 16557 // parts from this transparent region. 16558 applyDrawableToTransparentRegion(mBackground, region); 16559 } 16560 } 16561 return true; 16562 } 16563 16564 /** 16565 * Play a sound effect for this view. 16566 * 16567 * <p>The framework will play sound effects for some built in actions, such as 16568 * clicking, but you may wish to play these effects in your widget, 16569 * for instance, for internal navigation. 16570 * 16571 * <p>The sound effect will only be played if sound effects are enabled by the user, and 16572 * {@link #isSoundEffectsEnabled()} is true. 16573 * 16574 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 16575 */ 16576 public void playSoundEffect(int soundConstant) { 16577 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 16578 return; 16579 } 16580 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 16581 } 16582 16583 /** 16584 * BZZZTT!!1! 16585 * 16586 * <p>Provide haptic feedback to the user for this view. 16587 * 16588 * <p>The framework will provide haptic feedback for some built in actions, 16589 * such as long presses, but you may wish to provide feedback for your 16590 * own widget. 16591 * 16592 * <p>The feedback will only be performed if 16593 * {@link #isHapticFeedbackEnabled()} is true. 16594 * 16595 * @param feedbackConstant One of the constants defined in 16596 * {@link HapticFeedbackConstants} 16597 */ 16598 public boolean performHapticFeedback(int feedbackConstant) { 16599 return performHapticFeedback(feedbackConstant, 0); 16600 } 16601 16602 /** 16603 * BZZZTT!!1! 16604 * 16605 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 16606 * 16607 * @param feedbackConstant One of the constants defined in 16608 * {@link HapticFeedbackConstants} 16609 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 16610 */ 16611 public boolean performHapticFeedback(int feedbackConstant, int flags) { 16612 if (mAttachInfo == null) { 16613 return false; 16614 } 16615 //noinspection SimplifiableIfStatement 16616 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 16617 && !isHapticFeedbackEnabled()) { 16618 return false; 16619 } 16620 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 16621 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 16622 } 16623 16624 /** 16625 * Request that the visibility of the status bar or other screen/window 16626 * decorations be changed. 16627 * 16628 * <p>This method is used to put the over device UI into temporary modes 16629 * where the user's attention is focused more on the application content, 16630 * by dimming or hiding surrounding system affordances. This is typically 16631 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 16632 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 16633 * to be placed behind the action bar (and with these flags other system 16634 * affordances) so that smooth transitions between hiding and showing them 16635 * can be done. 16636 * 16637 * <p>Two representative examples of the use of system UI visibility is 16638 * implementing a content browsing application (like a magazine reader) 16639 * and a video playing application. 16640 * 16641 * <p>The first code shows a typical implementation of a View in a content 16642 * browsing application. In this implementation, the application goes 16643 * into a content-oriented mode by hiding the status bar and action bar, 16644 * and putting the navigation elements into lights out mode. The user can 16645 * then interact with content while in this mode. Such an application should 16646 * provide an easy way for the user to toggle out of the mode (such as to 16647 * check information in the status bar or access notifications). In the 16648 * implementation here, this is done simply by tapping on the content. 16649 * 16650 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 16651 * content} 16652 * 16653 * <p>This second code sample shows a typical implementation of a View 16654 * in a video playing application. In this situation, while the video is 16655 * playing the application would like to go into a complete full-screen mode, 16656 * to use as much of the display as possible for the video. When in this state 16657 * the user can not interact with the application; the system intercepts 16658 * touching on the screen to pop the UI out of full screen mode. See 16659 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 16660 * 16661 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 16662 * content} 16663 * 16664 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 16665 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 16666 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 16667 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 16668 * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS}, 16669 * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}. 16670 */ 16671 public void setSystemUiVisibility(int visibility) { 16672 if (visibility != mSystemUiVisibility) { 16673 mSystemUiVisibility = visibility; 16674 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 16675 mParent.recomputeViewAttributes(this); 16676 } 16677 } 16678 } 16679 16680 /** 16681 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 16682 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 16683 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 16684 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 16685 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 16686 * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS}, 16687 * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}. 16688 */ 16689 public int getSystemUiVisibility() { 16690 return mSystemUiVisibility; 16691 } 16692 16693 /** 16694 * Returns the current system UI visibility that is currently set for 16695 * the entire window. This is the combination of the 16696 * {@link #setSystemUiVisibility(int)} values supplied by all of the 16697 * views in the window. 16698 */ 16699 public int getWindowSystemUiVisibility() { 16700 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 16701 } 16702 16703 /** 16704 * Override to find out when the window's requested system UI visibility 16705 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 16706 * This is different from the callbacks received through 16707 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 16708 * in that this is only telling you about the local request of the window, 16709 * not the actual values applied by the system. 16710 */ 16711 public void onWindowSystemUiVisibilityChanged(int visible) { 16712 } 16713 16714 /** 16715 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 16716 * the view hierarchy. 16717 */ 16718 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 16719 onWindowSystemUiVisibilityChanged(visible); 16720 } 16721 16722 /** 16723 * Set a listener to receive callbacks when the visibility of the system bar changes. 16724 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 16725 */ 16726 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 16727 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 16728 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 16729 mParent.recomputeViewAttributes(this); 16730 } 16731 } 16732 16733 /** 16734 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 16735 * the view hierarchy. 16736 */ 16737 public void dispatchSystemUiVisibilityChanged(int visibility) { 16738 ListenerInfo li = mListenerInfo; 16739 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 16740 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 16741 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 16742 } 16743 } 16744 16745 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 16746 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 16747 if (val != mSystemUiVisibility) { 16748 setSystemUiVisibility(val); 16749 return true; 16750 } 16751 return false; 16752 } 16753 16754 /** @hide */ 16755 public void setDisabledSystemUiVisibility(int flags) { 16756 if (mAttachInfo != null) { 16757 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 16758 mAttachInfo.mDisabledSystemUiVisibility = flags; 16759 if (mParent != null) { 16760 mParent.recomputeViewAttributes(this); 16761 } 16762 } 16763 } 16764 } 16765 16766 /** 16767 * Creates an image that the system displays during the drag and drop 16768 * operation. This is called a "drag shadow". The default implementation 16769 * for a DragShadowBuilder based on a View returns an image that has exactly the same 16770 * appearance as the given View. The default also positions the center of the drag shadow 16771 * directly under the touch point. If no View is provided (the constructor with no parameters 16772 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 16773 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 16774 * default is an invisible drag shadow. 16775 * <p> 16776 * You are not required to use the View you provide to the constructor as the basis of the 16777 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 16778 * anything you want as the drag shadow. 16779 * </p> 16780 * <p> 16781 * You pass a DragShadowBuilder object to the system when you start the drag. The system 16782 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 16783 * size and position of the drag shadow. It uses this data to construct a 16784 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 16785 * so that your application can draw the shadow image in the Canvas. 16786 * </p> 16787 * 16788 * <div class="special reference"> 16789 * <h3>Developer Guides</h3> 16790 * <p>For a guide to implementing drag and drop features, read the 16791 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 16792 * </div> 16793 */ 16794 public static class DragShadowBuilder { 16795 private final WeakReference<View> mView; 16796 16797 /** 16798 * Constructs a shadow image builder based on a View. By default, the resulting drag 16799 * shadow will have the same appearance and dimensions as the View, with the touch point 16800 * over the center of the View. 16801 * @param view A View. Any View in scope can be used. 16802 */ 16803 public DragShadowBuilder(View view) { 16804 mView = new WeakReference<View>(view); 16805 } 16806 16807 /** 16808 * Construct a shadow builder object with no associated View. This 16809 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 16810 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 16811 * to supply the drag shadow's dimensions and appearance without 16812 * reference to any View object. If they are not overridden, then the result is an 16813 * invisible drag shadow. 16814 */ 16815 public DragShadowBuilder() { 16816 mView = new WeakReference<View>(null); 16817 } 16818 16819 /** 16820 * Returns the View object that had been passed to the 16821 * {@link #View.DragShadowBuilder(View)} 16822 * constructor. If that View parameter was {@code null} or if the 16823 * {@link #View.DragShadowBuilder()} 16824 * constructor was used to instantiate the builder object, this method will return 16825 * null. 16826 * 16827 * @return The View object associate with this builder object. 16828 */ 16829 @SuppressWarnings({"JavadocReference"}) 16830 final public View getView() { 16831 return mView.get(); 16832 } 16833 16834 /** 16835 * Provides the metrics for the shadow image. These include the dimensions of 16836 * the shadow image, and the point within that shadow that should 16837 * be centered under the touch location while dragging. 16838 * <p> 16839 * The default implementation sets the dimensions of the shadow to be the 16840 * same as the dimensions of the View itself and centers the shadow under 16841 * the touch point. 16842 * </p> 16843 * 16844 * @param shadowSize A {@link android.graphics.Point} containing the width and height 16845 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 16846 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 16847 * image. 16848 * 16849 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 16850 * shadow image that should be underneath the touch point during the drag and drop 16851 * operation. Your application must set {@link android.graphics.Point#x} to the 16852 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 16853 */ 16854 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 16855 final View view = mView.get(); 16856 if (view != null) { 16857 shadowSize.set(view.getWidth(), view.getHeight()); 16858 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 16859 } else { 16860 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 16861 } 16862 } 16863 16864 /** 16865 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 16866 * based on the dimensions it received from the 16867 * {@link #onProvideShadowMetrics(Point, Point)} callback. 16868 * 16869 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 16870 */ 16871 public void onDrawShadow(Canvas canvas) { 16872 final View view = mView.get(); 16873 if (view != null) { 16874 view.draw(canvas); 16875 } else { 16876 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 16877 } 16878 } 16879 } 16880 16881 /** 16882 * Starts a drag and drop operation. When your application calls this method, it passes a 16883 * {@link android.view.View.DragShadowBuilder} object to the system. The 16884 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 16885 * to get metrics for the drag shadow, and then calls the object's 16886 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 16887 * <p> 16888 * Once the system has the drag shadow, it begins the drag and drop operation by sending 16889 * drag events to all the View objects in your application that are currently visible. It does 16890 * this either by calling the View object's drag listener (an implementation of 16891 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 16892 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 16893 * Both are passed a {@link android.view.DragEvent} object that has a 16894 * {@link android.view.DragEvent#getAction()} value of 16895 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 16896 * </p> 16897 * <p> 16898 * Your application can invoke startDrag() on any attached View object. The View object does not 16899 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 16900 * be related to the View the user selected for dragging. 16901 * </p> 16902 * @param data A {@link android.content.ClipData} object pointing to the data to be 16903 * transferred by the drag and drop operation. 16904 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 16905 * drag shadow. 16906 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 16907 * drop operation. This Object is put into every DragEvent object sent by the system during the 16908 * current drag. 16909 * <p> 16910 * myLocalState is a lightweight mechanism for the sending information from the dragged View 16911 * to the target Views. For example, it can contain flags that differentiate between a 16912 * a copy operation and a move operation. 16913 * </p> 16914 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 16915 * so the parameter should be set to 0. 16916 * @return {@code true} if the method completes successfully, or 16917 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 16918 * do a drag, and so no drag operation is in progress. 16919 */ 16920 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 16921 Object myLocalState, int flags) { 16922 if (ViewDebug.DEBUG_DRAG) { 16923 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 16924 } 16925 boolean okay = false; 16926 16927 Point shadowSize = new Point(); 16928 Point shadowTouchPoint = new Point(); 16929 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 16930 16931 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 16932 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 16933 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 16934 } 16935 16936 if (ViewDebug.DEBUG_DRAG) { 16937 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 16938 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 16939 } 16940 Surface surface = new Surface(); 16941 try { 16942 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 16943 flags, shadowSize.x, shadowSize.y, surface); 16944 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 16945 + " surface=" + surface); 16946 if (token != null) { 16947 Canvas canvas = surface.lockCanvas(null); 16948 try { 16949 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 16950 shadowBuilder.onDrawShadow(canvas); 16951 } finally { 16952 surface.unlockCanvasAndPost(canvas); 16953 } 16954 16955 final ViewRootImpl root = getViewRootImpl(); 16956 16957 // Cache the local state object for delivery with DragEvents 16958 root.setLocalDragState(myLocalState); 16959 16960 // repurpose 'shadowSize' for the last touch point 16961 root.getLastTouchPoint(shadowSize); 16962 16963 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 16964 shadowSize.x, shadowSize.y, 16965 shadowTouchPoint.x, shadowTouchPoint.y, data); 16966 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 16967 16968 // Off and running! Release our local surface instance; the drag 16969 // shadow surface is now managed by the system process. 16970 surface.release(); 16971 } 16972 } catch (Exception e) { 16973 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 16974 surface.destroy(); 16975 } 16976 16977 return okay; 16978 } 16979 16980 /** 16981 * Handles drag events sent by the system following a call to 16982 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 16983 *<p> 16984 * When the system calls this method, it passes a 16985 * {@link android.view.DragEvent} object. A call to 16986 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 16987 * in DragEvent. The method uses these to determine what is happening in the drag and drop 16988 * operation. 16989 * @param event The {@link android.view.DragEvent} sent by the system. 16990 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 16991 * in DragEvent, indicating the type of drag event represented by this object. 16992 * @return {@code true} if the method was successful, otherwise {@code false}. 16993 * <p> 16994 * The method should return {@code true} in response to an action type of 16995 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 16996 * operation. 16997 * </p> 16998 * <p> 16999 * The method should also return {@code true} in response to an action type of 17000 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17001 * {@code false} if it didn't. 17002 * </p> 17003 */ 17004 public boolean onDragEvent(DragEvent event) { 17005 return false; 17006 } 17007 17008 /** 17009 * Detects if this View is enabled and has a drag event listener. 17010 * If both are true, then it calls the drag event listener with the 17011 * {@link android.view.DragEvent} it received. If the drag event listener returns 17012 * {@code true}, then dispatchDragEvent() returns {@code true}. 17013 * <p> 17014 * For all other cases, the method calls the 17015 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17016 * method and returns its result. 17017 * </p> 17018 * <p> 17019 * This ensures that a drag event is always consumed, even if the View does not have a drag 17020 * event listener. However, if the View has a listener and the listener returns true, then 17021 * onDragEvent() is not called. 17022 * </p> 17023 */ 17024 public boolean dispatchDragEvent(DragEvent event) { 17025 ListenerInfo li = mListenerInfo; 17026 //noinspection SimplifiableIfStatement 17027 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17028 && li.mOnDragListener.onDrag(this, event)) { 17029 return true; 17030 } 17031 return onDragEvent(event); 17032 } 17033 17034 boolean canAcceptDrag() { 17035 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17036 } 17037 17038 /** 17039 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17040 * it is ever exposed at all. 17041 * @hide 17042 */ 17043 public void onCloseSystemDialogs(String reason) { 17044 } 17045 17046 /** 17047 * Given a Drawable whose bounds have been set to draw into this view, 17048 * update a Region being computed for 17049 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17050 * that any non-transparent parts of the Drawable are removed from the 17051 * given transparent region. 17052 * 17053 * @param dr The Drawable whose transparency is to be applied to the region. 17054 * @param region A Region holding the current transparency information, 17055 * where any parts of the region that are set are considered to be 17056 * transparent. On return, this region will be modified to have the 17057 * transparency information reduced by the corresponding parts of the 17058 * Drawable that are not transparent. 17059 * {@hide} 17060 */ 17061 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17062 if (DBG) { 17063 Log.i("View", "Getting transparent region for: " + this); 17064 } 17065 final Region r = dr.getTransparentRegion(); 17066 final Rect db = dr.getBounds(); 17067 final AttachInfo attachInfo = mAttachInfo; 17068 if (r != null && attachInfo != null) { 17069 final int w = getRight()-getLeft(); 17070 final int h = getBottom()-getTop(); 17071 if (db.left > 0) { 17072 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17073 r.op(0, 0, db.left, h, Region.Op.UNION); 17074 } 17075 if (db.right < w) { 17076 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17077 r.op(db.right, 0, w, h, Region.Op.UNION); 17078 } 17079 if (db.top > 0) { 17080 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17081 r.op(0, 0, w, db.top, Region.Op.UNION); 17082 } 17083 if (db.bottom < h) { 17084 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17085 r.op(0, db.bottom, w, h, Region.Op.UNION); 17086 } 17087 final int[] location = attachInfo.mTransparentLocation; 17088 getLocationInWindow(location); 17089 r.translate(location[0], location[1]); 17090 region.op(r, Region.Op.INTERSECT); 17091 } else { 17092 region.op(db, Region.Op.DIFFERENCE); 17093 } 17094 } 17095 17096 private void checkForLongClick(int delayOffset) { 17097 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17098 mHasPerformedLongPress = false; 17099 17100 if (mPendingCheckForLongPress == null) { 17101 mPendingCheckForLongPress = new CheckForLongPress(); 17102 } 17103 mPendingCheckForLongPress.rememberWindowAttachCount(); 17104 postDelayed(mPendingCheckForLongPress, 17105 ViewConfiguration.getLongPressTimeout() - delayOffset); 17106 } 17107 } 17108 17109 /** 17110 * Inflate a view from an XML resource. This convenience method wraps the {@link 17111 * LayoutInflater} class, which provides a full range of options for view inflation. 17112 * 17113 * @param context The Context object for your activity or application. 17114 * @param resource The resource ID to inflate 17115 * @param root A view group that will be the parent. Used to properly inflate the 17116 * layout_* parameters. 17117 * @see LayoutInflater 17118 */ 17119 public static View inflate(Context context, int resource, ViewGroup root) { 17120 LayoutInflater factory = LayoutInflater.from(context); 17121 return factory.inflate(resource, root); 17122 } 17123 17124 /** 17125 * Scroll the view with standard behavior for scrolling beyond the normal 17126 * content boundaries. Views that call this method should override 17127 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 17128 * results of an over-scroll operation. 17129 * 17130 * Views can use this method to handle any touch or fling-based scrolling. 17131 * 17132 * @param deltaX Change in X in pixels 17133 * @param deltaY Change in Y in pixels 17134 * @param scrollX Current X scroll value in pixels before applying deltaX 17135 * @param scrollY Current Y scroll value in pixels before applying deltaY 17136 * @param scrollRangeX Maximum content scroll range along the X axis 17137 * @param scrollRangeY Maximum content scroll range along the Y axis 17138 * @param maxOverScrollX Number of pixels to overscroll by in either direction 17139 * along the X axis. 17140 * @param maxOverScrollY Number of pixels to overscroll by in either direction 17141 * along the Y axis. 17142 * @param isTouchEvent true if this scroll operation is the result of a touch event. 17143 * @return true if scrolling was clamped to an over-scroll boundary along either 17144 * axis, false otherwise. 17145 */ 17146 @SuppressWarnings({"UnusedParameters"}) 17147 protected boolean overScrollBy(int deltaX, int deltaY, 17148 int scrollX, int scrollY, 17149 int scrollRangeX, int scrollRangeY, 17150 int maxOverScrollX, int maxOverScrollY, 17151 boolean isTouchEvent) { 17152 final int overScrollMode = mOverScrollMode; 17153 final boolean canScrollHorizontal = 17154 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 17155 final boolean canScrollVertical = 17156 computeVerticalScrollRange() > computeVerticalScrollExtent(); 17157 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 17158 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 17159 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 17160 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 17161 17162 int newScrollX = scrollX + deltaX; 17163 if (!overScrollHorizontal) { 17164 maxOverScrollX = 0; 17165 } 17166 17167 int newScrollY = scrollY + deltaY; 17168 if (!overScrollVertical) { 17169 maxOverScrollY = 0; 17170 } 17171 17172 // Clamp values if at the limits and record 17173 final int left = -maxOverScrollX; 17174 final int right = maxOverScrollX + scrollRangeX; 17175 final int top = -maxOverScrollY; 17176 final int bottom = maxOverScrollY + scrollRangeY; 17177 17178 boolean clampedX = false; 17179 if (newScrollX > right) { 17180 newScrollX = right; 17181 clampedX = true; 17182 } else if (newScrollX < left) { 17183 newScrollX = left; 17184 clampedX = true; 17185 } 17186 17187 boolean clampedY = false; 17188 if (newScrollY > bottom) { 17189 newScrollY = bottom; 17190 clampedY = true; 17191 } else if (newScrollY < top) { 17192 newScrollY = top; 17193 clampedY = true; 17194 } 17195 17196 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 17197 17198 return clampedX || clampedY; 17199 } 17200 17201 /** 17202 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 17203 * respond to the results of an over-scroll operation. 17204 * 17205 * @param scrollX New X scroll value in pixels 17206 * @param scrollY New Y scroll value in pixels 17207 * @param clampedX True if scrollX was clamped to an over-scroll boundary 17208 * @param clampedY True if scrollY was clamped to an over-scroll boundary 17209 */ 17210 protected void onOverScrolled(int scrollX, int scrollY, 17211 boolean clampedX, boolean clampedY) { 17212 // Intentionally empty. 17213 } 17214 17215 /** 17216 * Returns the over-scroll mode for this view. The result will be 17217 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17218 * (allow over-scrolling only if the view content is larger than the container), 17219 * or {@link #OVER_SCROLL_NEVER}. 17220 * 17221 * @return This view's over-scroll mode. 17222 */ 17223 public int getOverScrollMode() { 17224 return mOverScrollMode; 17225 } 17226 17227 /** 17228 * Set the over-scroll mode for this view. Valid over-scroll modes are 17229 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17230 * (allow over-scrolling only if the view content is larger than the container), 17231 * or {@link #OVER_SCROLL_NEVER}. 17232 * 17233 * Setting the over-scroll mode of a view will have an effect only if the 17234 * view is capable of scrolling. 17235 * 17236 * @param overScrollMode The new over-scroll mode for this view. 17237 */ 17238 public void setOverScrollMode(int overScrollMode) { 17239 if (overScrollMode != OVER_SCROLL_ALWAYS && 17240 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 17241 overScrollMode != OVER_SCROLL_NEVER) { 17242 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 17243 } 17244 mOverScrollMode = overScrollMode; 17245 } 17246 17247 /** 17248 * Gets a scale factor that determines the distance the view should scroll 17249 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 17250 * @return The vertical scroll scale factor. 17251 * @hide 17252 */ 17253 protected float getVerticalScrollFactor() { 17254 if (mVerticalScrollFactor == 0) { 17255 TypedValue outValue = new TypedValue(); 17256 if (!mContext.getTheme().resolveAttribute( 17257 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 17258 throw new IllegalStateException( 17259 "Expected theme to define listPreferredItemHeight."); 17260 } 17261 mVerticalScrollFactor = outValue.getDimension( 17262 mContext.getResources().getDisplayMetrics()); 17263 } 17264 return mVerticalScrollFactor; 17265 } 17266 17267 /** 17268 * Gets a scale factor that determines the distance the view should scroll 17269 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 17270 * @return The horizontal scroll scale factor. 17271 * @hide 17272 */ 17273 protected float getHorizontalScrollFactor() { 17274 // TODO: Should use something else. 17275 return getVerticalScrollFactor(); 17276 } 17277 17278 /** 17279 * Return the value specifying the text direction or policy that was set with 17280 * {@link #setTextDirection(int)}. 17281 * 17282 * @return the defined text direction. It can be one of: 17283 * 17284 * {@link #TEXT_DIRECTION_INHERIT}, 17285 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17286 * {@link #TEXT_DIRECTION_ANY_RTL}, 17287 * {@link #TEXT_DIRECTION_LTR}, 17288 * {@link #TEXT_DIRECTION_RTL}, 17289 * {@link #TEXT_DIRECTION_LOCALE} 17290 * 17291 * @attr ref android.R.styleable#View_textDirection 17292 * 17293 * @hide 17294 */ 17295 @ViewDebug.ExportedProperty(category = "text", mapping = { 17296 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 17297 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 17298 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 17299 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 17300 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 17301 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 17302 }) 17303 public int getRawTextDirection() { 17304 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 17305 } 17306 17307 /** 17308 * Set the text direction. 17309 * 17310 * @param textDirection the direction to set. Should be one of: 17311 * 17312 * {@link #TEXT_DIRECTION_INHERIT}, 17313 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17314 * {@link #TEXT_DIRECTION_ANY_RTL}, 17315 * {@link #TEXT_DIRECTION_LTR}, 17316 * {@link #TEXT_DIRECTION_RTL}, 17317 * {@link #TEXT_DIRECTION_LOCALE} 17318 * 17319 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 17320 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 17321 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 17322 * 17323 * @attr ref android.R.styleable#View_textDirection 17324 */ 17325 public void setTextDirection(int textDirection) { 17326 if (getRawTextDirection() != textDirection) { 17327 // Reset the current text direction and the resolved one 17328 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 17329 resetResolvedTextDirection(); 17330 // Set the new text direction 17331 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 17332 // Do resolution 17333 resolveTextDirection(); 17334 // Notify change 17335 onRtlPropertiesChanged(getLayoutDirection()); 17336 // Refresh 17337 requestLayout(); 17338 invalidate(true); 17339 } 17340 } 17341 17342 /** 17343 * Return the resolved text direction. 17344 * 17345 * @return the resolved text direction. Returns one of: 17346 * 17347 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17348 * {@link #TEXT_DIRECTION_ANY_RTL}, 17349 * {@link #TEXT_DIRECTION_LTR}, 17350 * {@link #TEXT_DIRECTION_RTL}, 17351 * {@link #TEXT_DIRECTION_LOCALE} 17352 * 17353 * @attr ref android.R.styleable#View_textDirection 17354 */ 17355 @ViewDebug.ExportedProperty(category = "text", mapping = { 17356 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 17357 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 17358 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 17359 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 17360 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 17361 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 17362 }) 17363 public int getTextDirection() { 17364 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 17365 } 17366 17367 /** 17368 * Resolve the text direction. 17369 * 17370 * @return true if resolution has been done, false otherwise. 17371 * 17372 * @hide 17373 */ 17374 public boolean resolveTextDirection() { 17375 // Reset any previous text direction resolution 17376 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 17377 17378 if (hasRtlSupport()) { 17379 // Set resolved text direction flag depending on text direction flag 17380 final int textDirection = getRawTextDirection(); 17381 switch(textDirection) { 17382 case TEXT_DIRECTION_INHERIT: 17383 if (!canResolveTextDirection()) { 17384 // We cannot do the resolution if there is no parent, so use the default one 17385 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17386 // Resolution will need to happen again later 17387 return false; 17388 } 17389 17390 // Parent has not yet resolved, so we still return the default 17391 try { 17392 if (!mParent.isTextDirectionResolved()) { 17393 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17394 // Resolution will need to happen again later 17395 return false; 17396 } 17397 } catch (AbstractMethodError e) { 17398 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17399 " does not fully implement ViewParent", e); 17400 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 17401 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17402 return true; 17403 } 17404 17405 // Set current resolved direction to the same value as the parent's one 17406 int parentResolvedDirection; 17407 try { 17408 parentResolvedDirection = mParent.getTextDirection(); 17409 } catch (AbstractMethodError e) { 17410 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17411 " does not fully implement ViewParent", e); 17412 parentResolvedDirection = TEXT_DIRECTION_LTR; 17413 } 17414 switch (parentResolvedDirection) { 17415 case TEXT_DIRECTION_FIRST_STRONG: 17416 case TEXT_DIRECTION_ANY_RTL: 17417 case TEXT_DIRECTION_LTR: 17418 case TEXT_DIRECTION_RTL: 17419 case TEXT_DIRECTION_LOCALE: 17420 mPrivateFlags2 |= 17421 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 17422 break; 17423 default: 17424 // Default resolved direction is "first strong" heuristic 17425 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17426 } 17427 break; 17428 case TEXT_DIRECTION_FIRST_STRONG: 17429 case TEXT_DIRECTION_ANY_RTL: 17430 case TEXT_DIRECTION_LTR: 17431 case TEXT_DIRECTION_RTL: 17432 case TEXT_DIRECTION_LOCALE: 17433 // Resolved direction is the same as text direction 17434 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 17435 break; 17436 default: 17437 // Default resolved direction is "first strong" heuristic 17438 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17439 } 17440 } else { 17441 // Default resolved direction is "first strong" heuristic 17442 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17443 } 17444 17445 // Set to resolved 17446 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 17447 return true; 17448 } 17449 17450 /** 17451 * Check if text direction resolution can be done. 17452 * 17453 * @return true if text direction resolution can be done otherwise return false. 17454 */ 17455 public boolean canResolveTextDirection() { 17456 switch (getRawTextDirection()) { 17457 case TEXT_DIRECTION_INHERIT: 17458 if (mParent != null) { 17459 try { 17460 return mParent.canResolveTextDirection(); 17461 } catch (AbstractMethodError e) { 17462 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17463 " does not fully implement ViewParent", e); 17464 } 17465 } 17466 return false; 17467 17468 default: 17469 return true; 17470 } 17471 } 17472 17473 /** 17474 * Reset resolved text direction. Text direction will be resolved during a call to 17475 * {@link #onMeasure(int, int)}. 17476 * 17477 * @hide 17478 */ 17479 public void resetResolvedTextDirection() { 17480 // Reset any previous text direction resolution 17481 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 17482 // Set to default value 17483 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17484 } 17485 17486 /** 17487 * @return true if text direction is inherited. 17488 * 17489 * @hide 17490 */ 17491 public boolean isTextDirectionInherited() { 17492 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 17493 } 17494 17495 /** 17496 * @return true if text direction is resolved. 17497 */ 17498 public boolean isTextDirectionResolved() { 17499 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 17500 } 17501 17502 /** 17503 * Return the value specifying the text alignment or policy that was set with 17504 * {@link #setTextAlignment(int)}. 17505 * 17506 * @return the defined text alignment. It can be one of: 17507 * 17508 * {@link #TEXT_ALIGNMENT_INHERIT}, 17509 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17510 * {@link #TEXT_ALIGNMENT_CENTER}, 17511 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17512 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17513 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17514 * {@link #TEXT_ALIGNMENT_VIEW_END} 17515 * 17516 * @attr ref android.R.styleable#View_textAlignment 17517 * 17518 * @hide 17519 */ 17520 @ViewDebug.ExportedProperty(category = "text", mapping = { 17521 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 17522 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 17523 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 17524 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 17525 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 17526 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 17527 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 17528 }) 17529 public int getRawTextAlignment() { 17530 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 17531 } 17532 17533 /** 17534 * Set the text alignment. 17535 * 17536 * @param textAlignment The text alignment to set. Should be one of 17537 * 17538 * {@link #TEXT_ALIGNMENT_INHERIT}, 17539 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17540 * {@link #TEXT_ALIGNMENT_CENTER}, 17541 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17542 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17543 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17544 * {@link #TEXT_ALIGNMENT_VIEW_END} 17545 * 17546 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 17547 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 17548 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 17549 * 17550 * @attr ref android.R.styleable#View_textAlignment 17551 */ 17552 public void setTextAlignment(int textAlignment) { 17553 if (textAlignment != getRawTextAlignment()) { 17554 // Reset the current and resolved text alignment 17555 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 17556 resetResolvedTextAlignment(); 17557 // Set the new text alignment 17558 mPrivateFlags2 |= 17559 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 17560 // Do resolution 17561 resolveTextAlignment(); 17562 // Notify change 17563 onRtlPropertiesChanged(getLayoutDirection()); 17564 // Refresh 17565 requestLayout(); 17566 invalidate(true); 17567 } 17568 } 17569 17570 /** 17571 * Return the resolved text alignment. 17572 * 17573 * @return the resolved text alignment. Returns one of: 17574 * 17575 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17576 * {@link #TEXT_ALIGNMENT_CENTER}, 17577 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17578 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17579 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17580 * {@link #TEXT_ALIGNMENT_VIEW_END} 17581 * 17582 * @attr ref android.R.styleable#View_textAlignment 17583 */ 17584 @ViewDebug.ExportedProperty(category = "text", mapping = { 17585 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 17586 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 17587 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 17588 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 17589 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 17590 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 17591 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 17592 }) 17593 public int getTextAlignment() { 17594 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 17595 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 17596 } 17597 17598 /** 17599 * Resolve the text alignment. 17600 * 17601 * @return true if resolution has been done, false otherwise. 17602 * 17603 * @hide 17604 */ 17605 public boolean resolveTextAlignment() { 17606 // Reset any previous text alignment resolution 17607 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 17608 17609 if (hasRtlSupport()) { 17610 // Set resolved text alignment flag depending on text alignment flag 17611 final int textAlignment = getRawTextAlignment(); 17612 switch (textAlignment) { 17613 case TEXT_ALIGNMENT_INHERIT: 17614 // Check if we can resolve the text alignment 17615 if (!canResolveTextAlignment()) { 17616 // We cannot do the resolution if there is no parent so use the default 17617 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17618 // Resolution will need to happen again later 17619 return false; 17620 } 17621 17622 // Parent has not yet resolved, so we still return the default 17623 try { 17624 if (!mParent.isTextAlignmentResolved()) { 17625 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17626 // Resolution will need to happen again later 17627 return false; 17628 } 17629 } catch (AbstractMethodError e) { 17630 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17631 " does not fully implement ViewParent", e); 17632 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 17633 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17634 return true; 17635 } 17636 17637 int parentResolvedTextAlignment; 17638 try { 17639 parentResolvedTextAlignment = mParent.getTextAlignment(); 17640 } catch (AbstractMethodError e) { 17641 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17642 " does not fully implement ViewParent", e); 17643 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 17644 } 17645 switch (parentResolvedTextAlignment) { 17646 case TEXT_ALIGNMENT_GRAVITY: 17647 case TEXT_ALIGNMENT_TEXT_START: 17648 case TEXT_ALIGNMENT_TEXT_END: 17649 case TEXT_ALIGNMENT_CENTER: 17650 case TEXT_ALIGNMENT_VIEW_START: 17651 case TEXT_ALIGNMENT_VIEW_END: 17652 // Resolved text alignment is the same as the parent resolved 17653 // text alignment 17654 mPrivateFlags2 |= 17655 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 17656 break; 17657 default: 17658 // Use default resolved text alignment 17659 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17660 } 17661 break; 17662 case TEXT_ALIGNMENT_GRAVITY: 17663 case TEXT_ALIGNMENT_TEXT_START: 17664 case TEXT_ALIGNMENT_TEXT_END: 17665 case TEXT_ALIGNMENT_CENTER: 17666 case TEXT_ALIGNMENT_VIEW_START: 17667 case TEXT_ALIGNMENT_VIEW_END: 17668 // Resolved text alignment is the same as text alignment 17669 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 17670 break; 17671 default: 17672 // Use default resolved text alignment 17673 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17674 } 17675 } else { 17676 // Use default resolved text alignment 17677 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17678 } 17679 17680 // Set the resolved 17681 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 17682 return true; 17683 } 17684 17685 /** 17686 * Check if text alignment resolution can be done. 17687 * 17688 * @return true if text alignment resolution can be done otherwise return false. 17689 */ 17690 public boolean canResolveTextAlignment() { 17691 switch (getRawTextAlignment()) { 17692 case TEXT_DIRECTION_INHERIT: 17693 if (mParent != null) { 17694 try { 17695 return mParent.canResolveTextAlignment(); 17696 } catch (AbstractMethodError e) { 17697 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17698 " does not fully implement ViewParent", e); 17699 } 17700 } 17701 return false; 17702 17703 default: 17704 return true; 17705 } 17706 } 17707 17708 /** 17709 * Reset resolved text alignment. Text alignment will be resolved during a call to 17710 * {@link #onMeasure(int, int)}. 17711 * 17712 * @hide 17713 */ 17714 public void resetResolvedTextAlignment() { 17715 // Reset any previous text alignment resolution 17716 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 17717 // Set to default 17718 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17719 } 17720 17721 /** 17722 * @return true if text alignment is inherited. 17723 * 17724 * @hide 17725 */ 17726 public boolean isTextAlignmentInherited() { 17727 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 17728 } 17729 17730 /** 17731 * @return true if text alignment is resolved. 17732 */ 17733 public boolean isTextAlignmentResolved() { 17734 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 17735 } 17736 17737 /** 17738 * Generate a value suitable for use in {@link #setId(int)}. 17739 * This value will not collide with ID values generated at build time by aapt for R.id. 17740 * 17741 * @return a generated ID value 17742 */ 17743 public static int generateViewId() { 17744 for (;;) { 17745 final int result = sNextGeneratedId.get(); 17746 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 17747 int newValue = result + 1; 17748 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 17749 if (sNextGeneratedId.compareAndSet(result, newValue)) { 17750 return result; 17751 } 17752 } 17753 } 17754 17755 // 17756 // Properties 17757 // 17758 /** 17759 * A Property wrapper around the <code>alpha</code> functionality handled by the 17760 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 17761 */ 17762 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 17763 @Override 17764 public void setValue(View object, float value) { 17765 object.setAlpha(value); 17766 } 17767 17768 @Override 17769 public Float get(View object) { 17770 return object.getAlpha(); 17771 } 17772 }; 17773 17774 /** 17775 * A Property wrapper around the <code>translationX</code> functionality handled by the 17776 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 17777 */ 17778 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 17779 @Override 17780 public void setValue(View object, float value) { 17781 object.setTranslationX(value); 17782 } 17783 17784 @Override 17785 public Float get(View object) { 17786 return object.getTranslationX(); 17787 } 17788 }; 17789 17790 /** 17791 * A Property wrapper around the <code>translationY</code> functionality handled by the 17792 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 17793 */ 17794 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 17795 @Override 17796 public void setValue(View object, float value) { 17797 object.setTranslationY(value); 17798 } 17799 17800 @Override 17801 public Float get(View object) { 17802 return object.getTranslationY(); 17803 } 17804 }; 17805 17806 /** 17807 * A Property wrapper around the <code>x</code> functionality handled by the 17808 * {@link View#setX(float)} and {@link View#getX()} methods. 17809 */ 17810 public static final Property<View, Float> X = new FloatProperty<View>("x") { 17811 @Override 17812 public void setValue(View object, float value) { 17813 object.setX(value); 17814 } 17815 17816 @Override 17817 public Float get(View object) { 17818 return object.getX(); 17819 } 17820 }; 17821 17822 /** 17823 * A Property wrapper around the <code>y</code> functionality handled by the 17824 * {@link View#setY(float)} and {@link View#getY()} methods. 17825 */ 17826 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 17827 @Override 17828 public void setValue(View object, float value) { 17829 object.setY(value); 17830 } 17831 17832 @Override 17833 public Float get(View object) { 17834 return object.getY(); 17835 } 17836 }; 17837 17838 /** 17839 * A Property wrapper around the <code>rotation</code> functionality handled by the 17840 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 17841 */ 17842 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 17843 @Override 17844 public void setValue(View object, float value) { 17845 object.setRotation(value); 17846 } 17847 17848 @Override 17849 public Float get(View object) { 17850 return object.getRotation(); 17851 } 17852 }; 17853 17854 /** 17855 * A Property wrapper around the <code>rotationX</code> functionality handled by the 17856 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 17857 */ 17858 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 17859 @Override 17860 public void setValue(View object, float value) { 17861 object.setRotationX(value); 17862 } 17863 17864 @Override 17865 public Float get(View object) { 17866 return object.getRotationX(); 17867 } 17868 }; 17869 17870 /** 17871 * A Property wrapper around the <code>rotationY</code> functionality handled by the 17872 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 17873 */ 17874 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 17875 @Override 17876 public void setValue(View object, float value) { 17877 object.setRotationY(value); 17878 } 17879 17880 @Override 17881 public Float get(View object) { 17882 return object.getRotationY(); 17883 } 17884 }; 17885 17886 /** 17887 * A Property wrapper around the <code>scaleX</code> functionality handled by the 17888 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 17889 */ 17890 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 17891 @Override 17892 public void setValue(View object, float value) { 17893 object.setScaleX(value); 17894 } 17895 17896 @Override 17897 public Float get(View object) { 17898 return object.getScaleX(); 17899 } 17900 }; 17901 17902 /** 17903 * A Property wrapper around the <code>scaleY</code> functionality handled by the 17904 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 17905 */ 17906 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 17907 @Override 17908 public void setValue(View object, float value) { 17909 object.setScaleY(value); 17910 } 17911 17912 @Override 17913 public Float get(View object) { 17914 return object.getScaleY(); 17915 } 17916 }; 17917 17918 /** 17919 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 17920 * Each MeasureSpec represents a requirement for either the width or the height. 17921 * A MeasureSpec is comprised of a size and a mode. There are three possible 17922 * modes: 17923 * <dl> 17924 * <dt>UNSPECIFIED</dt> 17925 * <dd> 17926 * The parent has not imposed any constraint on the child. It can be whatever size 17927 * it wants. 17928 * </dd> 17929 * 17930 * <dt>EXACTLY</dt> 17931 * <dd> 17932 * The parent has determined an exact size for the child. The child is going to be 17933 * given those bounds regardless of how big it wants to be. 17934 * </dd> 17935 * 17936 * <dt>AT_MOST</dt> 17937 * <dd> 17938 * The child can be as large as it wants up to the specified size. 17939 * </dd> 17940 * </dl> 17941 * 17942 * MeasureSpecs are implemented as ints to reduce object allocation. This class 17943 * is provided to pack and unpack the <size, mode> tuple into the int. 17944 */ 17945 public static class MeasureSpec { 17946 private static final int MODE_SHIFT = 30; 17947 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 17948 17949 /** 17950 * Measure specification mode: The parent has not imposed any constraint 17951 * on the child. It can be whatever size it wants. 17952 */ 17953 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 17954 17955 /** 17956 * Measure specification mode: The parent has determined an exact size 17957 * for the child. The child is going to be given those bounds regardless 17958 * of how big it wants to be. 17959 */ 17960 public static final int EXACTLY = 1 << MODE_SHIFT; 17961 17962 /** 17963 * Measure specification mode: The child can be as large as it wants up 17964 * to the specified size. 17965 */ 17966 public static final int AT_MOST = 2 << MODE_SHIFT; 17967 17968 /** 17969 * Creates a measure specification based on the supplied size and mode. 17970 * 17971 * The mode must always be one of the following: 17972 * <ul> 17973 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 17974 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 17975 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 17976 * </ul> 17977 * 17978 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 17979 * implementation was such that the order of arguments did not matter 17980 * and overflow in either value could impact the resulting MeasureSpec. 17981 * {@link android.widget.RelativeLayout} was affected by this bug. 17982 * Apps targeting API levels greater than 17 will get the fixed, more strict 17983 * behavior.</p> 17984 * 17985 * @param size the size of the measure specification 17986 * @param mode the mode of the measure specification 17987 * @return the measure specification based on size and mode 17988 */ 17989 public static int makeMeasureSpec(int size, int mode) { 17990 if (sUseBrokenMakeMeasureSpec) { 17991 return size + mode; 17992 } else { 17993 return (size & ~MODE_MASK) | (mode & MODE_MASK); 17994 } 17995 } 17996 17997 /** 17998 * Extracts the mode from the supplied measure specification. 17999 * 18000 * @param measureSpec the measure specification to extract the mode from 18001 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 18002 * {@link android.view.View.MeasureSpec#AT_MOST} or 18003 * {@link android.view.View.MeasureSpec#EXACTLY} 18004 */ 18005 public static int getMode(int measureSpec) { 18006 return (measureSpec & MODE_MASK); 18007 } 18008 18009 /** 18010 * Extracts the size from the supplied measure specification. 18011 * 18012 * @param measureSpec the measure specification to extract the size from 18013 * @return the size in pixels defined in the supplied measure specification 18014 */ 18015 public static int getSize(int measureSpec) { 18016 return (measureSpec & ~MODE_MASK); 18017 } 18018 18019 static int adjust(int measureSpec, int delta) { 18020 return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec)); 18021 } 18022 18023 /** 18024 * Returns a String representation of the specified measure 18025 * specification. 18026 * 18027 * @param measureSpec the measure specification to convert to a String 18028 * @return a String with the following format: "MeasureSpec: MODE SIZE" 18029 */ 18030 public static String toString(int measureSpec) { 18031 int mode = getMode(measureSpec); 18032 int size = getSize(measureSpec); 18033 18034 StringBuilder sb = new StringBuilder("MeasureSpec: "); 18035 18036 if (mode == UNSPECIFIED) 18037 sb.append("UNSPECIFIED "); 18038 else if (mode == EXACTLY) 18039 sb.append("EXACTLY "); 18040 else if (mode == AT_MOST) 18041 sb.append("AT_MOST "); 18042 else 18043 sb.append(mode).append(" "); 18044 18045 sb.append(size); 18046 return sb.toString(); 18047 } 18048 } 18049 18050 class CheckForLongPress implements Runnable { 18051 18052 private int mOriginalWindowAttachCount; 18053 18054 public void run() { 18055 if (isPressed() && (mParent != null) 18056 && mOriginalWindowAttachCount == mWindowAttachCount) { 18057 if (performLongClick()) { 18058 mHasPerformedLongPress = true; 18059 } 18060 } 18061 } 18062 18063 public void rememberWindowAttachCount() { 18064 mOriginalWindowAttachCount = mWindowAttachCount; 18065 } 18066 } 18067 18068 private final class CheckForTap implements Runnable { 18069 public void run() { 18070 mPrivateFlags &= ~PFLAG_PREPRESSED; 18071 setPressed(true); 18072 checkForLongClick(ViewConfiguration.getTapTimeout()); 18073 } 18074 } 18075 18076 private final class PerformClick implements Runnable { 18077 public void run() { 18078 performClick(); 18079 } 18080 } 18081 18082 /** @hide */ 18083 public void hackTurnOffWindowResizeAnim(boolean off) { 18084 mAttachInfo.mTurnOffWindowResizeAnim = off; 18085 } 18086 18087 /** 18088 * This method returns a ViewPropertyAnimator object, which can be used to animate 18089 * specific properties on this View. 18090 * 18091 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 18092 */ 18093 public ViewPropertyAnimator animate() { 18094 if (mAnimator == null) { 18095 mAnimator = new ViewPropertyAnimator(this); 18096 } 18097 return mAnimator; 18098 } 18099 18100 /** 18101 * Interface definition for a callback to be invoked when a hardware key event is 18102 * dispatched to this view. The callback will be invoked before the key event is 18103 * given to the view. This is only useful for hardware keyboards; a software input 18104 * method has no obligation to trigger this listener. 18105 */ 18106 public interface OnKeyListener { 18107 /** 18108 * Called when a hardware key is dispatched to a view. This allows listeners to 18109 * get a chance to respond before the target view. 18110 * <p>Key presses in software keyboards will generally NOT trigger this method, 18111 * although some may elect to do so in some situations. Do not assume a 18112 * software input method has to be key-based; even if it is, it may use key presses 18113 * in a different way than you expect, so there is no way to reliably catch soft 18114 * input key presses. 18115 * 18116 * @param v The view the key has been dispatched to. 18117 * @param keyCode The code for the physical key that was pressed 18118 * @param event The KeyEvent object containing full information about 18119 * the event. 18120 * @return True if the listener has consumed the event, false otherwise. 18121 */ 18122 boolean onKey(View v, int keyCode, KeyEvent event); 18123 } 18124 18125 /** 18126 * Interface definition for a callback to be invoked when a touch event is 18127 * dispatched to this view. The callback will be invoked before the touch 18128 * event is given to the view. 18129 */ 18130 public interface OnTouchListener { 18131 /** 18132 * Called when a touch event is dispatched to a view. This allows listeners to 18133 * get a chance to respond before the target view. 18134 * 18135 * @param v The view the touch event has been dispatched to. 18136 * @param event The MotionEvent object containing full information about 18137 * the event. 18138 * @return True if the listener has consumed the event, false otherwise. 18139 */ 18140 boolean onTouch(View v, MotionEvent event); 18141 } 18142 18143 /** 18144 * Interface definition for a callback to be invoked when a hover event is 18145 * dispatched to this view. The callback will be invoked before the hover 18146 * event is given to the view. 18147 */ 18148 public interface OnHoverListener { 18149 /** 18150 * Called when a hover event is dispatched to a view. This allows listeners to 18151 * get a chance to respond before the target view. 18152 * 18153 * @param v The view the hover event has been dispatched to. 18154 * @param event The MotionEvent object containing full information about 18155 * the event. 18156 * @return True if the listener has consumed the event, false otherwise. 18157 */ 18158 boolean onHover(View v, MotionEvent event); 18159 } 18160 18161 /** 18162 * Interface definition for a callback to be invoked when a generic motion event is 18163 * dispatched to this view. The callback will be invoked before the generic motion 18164 * event is given to the view. 18165 */ 18166 public interface OnGenericMotionListener { 18167 /** 18168 * Called when a generic motion event is dispatched to a view. This allows listeners to 18169 * get a chance to respond before the target view. 18170 * 18171 * @param v The view the generic motion event has been dispatched to. 18172 * @param event The MotionEvent object containing full information about 18173 * the event. 18174 * @return True if the listener has consumed the event, false otherwise. 18175 */ 18176 boolean onGenericMotion(View v, MotionEvent event); 18177 } 18178 18179 /** 18180 * Interface definition for a callback to be invoked when a view has been clicked and held. 18181 */ 18182 public interface OnLongClickListener { 18183 /** 18184 * Called when a view has been clicked and held. 18185 * 18186 * @param v The view that was clicked and held. 18187 * 18188 * @return true if the callback consumed the long click, false otherwise. 18189 */ 18190 boolean onLongClick(View v); 18191 } 18192 18193 /** 18194 * Interface definition for a callback to be invoked when a drag is being dispatched 18195 * to this view. The callback will be invoked before the hosting view's own 18196 * onDrag(event) method. If the listener wants to fall back to the hosting view's 18197 * onDrag(event) behavior, it should return 'false' from this callback. 18198 * 18199 * <div class="special reference"> 18200 * <h3>Developer Guides</h3> 18201 * <p>For a guide to implementing drag and drop features, read the 18202 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 18203 * </div> 18204 */ 18205 public interface OnDragListener { 18206 /** 18207 * Called when a drag event is dispatched to a view. This allows listeners 18208 * to get a chance to override base View behavior. 18209 * 18210 * @param v The View that received the drag event. 18211 * @param event The {@link android.view.DragEvent} object for the drag event. 18212 * @return {@code true} if the drag event was handled successfully, or {@code false} 18213 * if the drag event was not handled. Note that {@code false} will trigger the View 18214 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 18215 */ 18216 boolean onDrag(View v, DragEvent event); 18217 } 18218 18219 /** 18220 * Interface definition for a callback to be invoked when the focus state of 18221 * a view changed. 18222 */ 18223 public interface OnFocusChangeListener { 18224 /** 18225 * Called when the focus state of a view has changed. 18226 * 18227 * @param v The view whose state has changed. 18228 * @param hasFocus The new focus state of v. 18229 */ 18230 void onFocusChange(View v, boolean hasFocus); 18231 } 18232 18233 /** 18234 * Interface definition for a callback to be invoked when a view is clicked. 18235 */ 18236 public interface OnClickListener { 18237 /** 18238 * Called when a view has been clicked. 18239 * 18240 * @param v The view that was clicked. 18241 */ 18242 void onClick(View v); 18243 } 18244 18245 /** 18246 * Interface definition for a callback to be invoked when the context menu 18247 * for this view is being built. 18248 */ 18249 public interface OnCreateContextMenuListener { 18250 /** 18251 * Called when the context menu for this view is being built. It is not 18252 * safe to hold onto the menu after this method returns. 18253 * 18254 * @param menu The context menu that is being built 18255 * @param v The view for which the context menu is being built 18256 * @param menuInfo Extra information about the item for which the 18257 * context menu should be shown. This information will vary 18258 * depending on the class of v. 18259 */ 18260 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 18261 } 18262 18263 /** 18264 * Interface definition for a callback to be invoked when the status bar changes 18265 * visibility. This reports <strong>global</strong> changes to the system UI 18266 * state, not what the application is requesting. 18267 * 18268 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 18269 */ 18270 public interface OnSystemUiVisibilityChangeListener { 18271 /** 18272 * Called when the status bar changes visibility because of a call to 18273 * {@link View#setSystemUiVisibility(int)}. 18274 * 18275 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18276 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 18277 * This tells you the <strong>global</strong> state of these UI visibility 18278 * flags, not what your app is currently applying. 18279 */ 18280 public void onSystemUiVisibilityChange(int visibility); 18281 } 18282 18283 /** 18284 * Interface definition for a callback to be invoked when this view is attached 18285 * or detached from its window. 18286 */ 18287 public interface OnAttachStateChangeListener { 18288 /** 18289 * Called when the view is attached to a window. 18290 * @param v The view that was attached 18291 */ 18292 public void onViewAttachedToWindow(View v); 18293 /** 18294 * Called when the view is detached from a window. 18295 * @param v The view that was detached 18296 */ 18297 public void onViewDetachedFromWindow(View v); 18298 } 18299 18300 private final class UnsetPressedState implements Runnable { 18301 public void run() { 18302 setPressed(false); 18303 } 18304 } 18305 18306 /** 18307 * Base class for derived classes that want to save and restore their own 18308 * state in {@link android.view.View#onSaveInstanceState()}. 18309 */ 18310 public static class BaseSavedState extends AbsSavedState { 18311 /** 18312 * Constructor used when reading from a parcel. Reads the state of the superclass. 18313 * 18314 * @param source 18315 */ 18316 public BaseSavedState(Parcel source) { 18317 super(source); 18318 } 18319 18320 /** 18321 * Constructor called by derived classes when creating their SavedState objects 18322 * 18323 * @param superState The state of the superclass of this view 18324 */ 18325 public BaseSavedState(Parcelable superState) { 18326 super(superState); 18327 } 18328 18329 public static final Parcelable.Creator<BaseSavedState> CREATOR = 18330 new Parcelable.Creator<BaseSavedState>() { 18331 public BaseSavedState createFromParcel(Parcel in) { 18332 return new BaseSavedState(in); 18333 } 18334 18335 public BaseSavedState[] newArray(int size) { 18336 return new BaseSavedState[size]; 18337 } 18338 }; 18339 } 18340 18341 /** 18342 * A set of information given to a view when it is attached to its parent 18343 * window. 18344 */ 18345 static class AttachInfo { 18346 interface Callbacks { 18347 void playSoundEffect(int effectId); 18348 boolean performHapticFeedback(int effectId, boolean always); 18349 } 18350 18351 /** 18352 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 18353 * to a Handler. This class contains the target (View) to invalidate and 18354 * the coordinates of the dirty rectangle. 18355 * 18356 * For performance purposes, this class also implements a pool of up to 18357 * POOL_LIMIT objects that get reused. This reduces memory allocations 18358 * whenever possible. 18359 */ 18360 static class InvalidateInfo { 18361 private static final int POOL_LIMIT = 10; 18362 18363 private static final SynchronizedPool<InvalidateInfo> sPool = 18364 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 18365 18366 View target; 18367 18368 int left; 18369 int top; 18370 int right; 18371 int bottom; 18372 18373 public static InvalidateInfo obtain() { 18374 InvalidateInfo instance = sPool.acquire(); 18375 return (instance != null) ? instance : new InvalidateInfo(); 18376 } 18377 18378 public void recycle() { 18379 target = null; 18380 sPool.release(this); 18381 } 18382 } 18383 18384 final IWindowSession mSession; 18385 18386 final IWindow mWindow; 18387 18388 final IBinder mWindowToken; 18389 18390 final Display mDisplay; 18391 18392 final Callbacks mRootCallbacks; 18393 18394 HardwareCanvas mHardwareCanvas; 18395 18396 IWindowId mIWindowId; 18397 WindowId mWindowId; 18398 18399 /** 18400 * The top view of the hierarchy. 18401 */ 18402 View mRootView; 18403 18404 IBinder mPanelParentWindowToken; 18405 Surface mSurface; 18406 18407 boolean mHardwareAccelerated; 18408 boolean mHardwareAccelerationRequested; 18409 HardwareRenderer mHardwareRenderer; 18410 18411 boolean mScreenOn; 18412 18413 /** 18414 * Scale factor used by the compatibility mode 18415 */ 18416 float mApplicationScale; 18417 18418 /** 18419 * Indicates whether the application is in compatibility mode 18420 */ 18421 boolean mScalingRequired; 18422 18423 /** 18424 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 18425 */ 18426 boolean mTurnOffWindowResizeAnim; 18427 18428 /** 18429 * Left position of this view's window 18430 */ 18431 int mWindowLeft; 18432 18433 /** 18434 * Top position of this view's window 18435 */ 18436 int mWindowTop; 18437 18438 /** 18439 * Indicates whether views need to use 32-bit drawing caches 18440 */ 18441 boolean mUse32BitDrawingCache; 18442 18443 /** 18444 * For windows that are full-screen but using insets to layout inside 18445 * of the screen areas, these are the current insets to appear inside 18446 * the overscan area of the display. 18447 */ 18448 final Rect mOverscanInsets = new Rect(); 18449 18450 /** 18451 * For windows that are full-screen but using insets to layout inside 18452 * of the screen decorations, these are the current insets for the 18453 * content of the window. 18454 */ 18455 final Rect mContentInsets = new Rect(); 18456 18457 /** 18458 * For windows that are full-screen but using insets to layout inside 18459 * of the screen decorations, these are the current insets for the 18460 * actual visible parts of the window. 18461 */ 18462 final Rect mVisibleInsets = new Rect(); 18463 18464 /** 18465 * The internal insets given by this window. This value is 18466 * supplied by the client (through 18467 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 18468 * be given to the window manager when changed to be used in laying 18469 * out windows behind it. 18470 */ 18471 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 18472 = new ViewTreeObserver.InternalInsetsInfo(); 18473 18474 /** 18475 * All views in the window's hierarchy that serve as scroll containers, 18476 * used to determine if the window can be resized or must be panned 18477 * to adjust for a soft input area. 18478 */ 18479 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 18480 18481 final KeyEvent.DispatcherState mKeyDispatchState 18482 = new KeyEvent.DispatcherState(); 18483 18484 /** 18485 * Indicates whether the view's window currently has the focus. 18486 */ 18487 boolean mHasWindowFocus; 18488 18489 /** 18490 * The current visibility of the window. 18491 */ 18492 int mWindowVisibility; 18493 18494 /** 18495 * Indicates the time at which drawing started to occur. 18496 */ 18497 long mDrawingTime; 18498 18499 /** 18500 * Indicates whether or not ignoring the DIRTY_MASK flags. 18501 */ 18502 boolean mIgnoreDirtyState; 18503 18504 /** 18505 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 18506 * to avoid clearing that flag prematurely. 18507 */ 18508 boolean mSetIgnoreDirtyState = false; 18509 18510 /** 18511 * Indicates whether the view's window is currently in touch mode. 18512 */ 18513 boolean mInTouchMode; 18514 18515 /** 18516 * Indicates that ViewAncestor should trigger a global layout change 18517 * the next time it performs a traversal 18518 */ 18519 boolean mRecomputeGlobalAttributes; 18520 18521 /** 18522 * Always report new attributes at next traversal. 18523 */ 18524 boolean mForceReportNewAttributes; 18525 18526 /** 18527 * Set during a traveral if any views want to keep the screen on. 18528 */ 18529 boolean mKeepScreenOn; 18530 18531 /** 18532 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 18533 */ 18534 int mSystemUiVisibility; 18535 18536 /** 18537 * Hack to force certain system UI visibility flags to be cleared. 18538 */ 18539 int mDisabledSystemUiVisibility; 18540 18541 /** 18542 * Last global system UI visibility reported by the window manager. 18543 */ 18544 int mGlobalSystemUiVisibility; 18545 18546 /** 18547 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 18548 * attached. 18549 */ 18550 boolean mHasSystemUiListeners; 18551 18552 /** 18553 * Set if the window has requested to extend into the overscan region 18554 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 18555 */ 18556 boolean mOverscanRequested; 18557 18558 /** 18559 * Set if the visibility of any views has changed. 18560 */ 18561 boolean mViewVisibilityChanged; 18562 18563 /** 18564 * Set to true if a view has been scrolled. 18565 */ 18566 boolean mViewScrollChanged; 18567 18568 /** 18569 * Global to the view hierarchy used as a temporary for dealing with 18570 * x/y points in the transparent region computations. 18571 */ 18572 final int[] mTransparentLocation = new int[2]; 18573 18574 /** 18575 * Global to the view hierarchy used as a temporary for dealing with 18576 * x/y points in the ViewGroup.invalidateChild implementation. 18577 */ 18578 final int[] mInvalidateChildLocation = new int[2]; 18579 18580 18581 /** 18582 * Global to the view hierarchy used as a temporary for dealing with 18583 * x/y location when view is transformed. 18584 */ 18585 final float[] mTmpTransformLocation = new float[2]; 18586 18587 /** 18588 * The view tree observer used to dispatch global events like 18589 * layout, pre-draw, touch mode change, etc. 18590 */ 18591 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 18592 18593 /** 18594 * A Canvas used by the view hierarchy to perform bitmap caching. 18595 */ 18596 Canvas mCanvas; 18597 18598 /** 18599 * The view root impl. 18600 */ 18601 final ViewRootImpl mViewRootImpl; 18602 18603 /** 18604 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 18605 * handler can be used to pump events in the UI events queue. 18606 */ 18607 final Handler mHandler; 18608 18609 /** 18610 * Temporary for use in computing invalidate rectangles while 18611 * calling up the hierarchy. 18612 */ 18613 final Rect mTmpInvalRect = new Rect(); 18614 18615 /** 18616 * Temporary for use in computing hit areas with transformed views 18617 */ 18618 final RectF mTmpTransformRect = new RectF(); 18619 18620 /** 18621 * Temporary for use in transforming invalidation rect 18622 */ 18623 final Matrix mTmpMatrix = new Matrix(); 18624 18625 /** 18626 * Temporary for use in transforming invalidation rect 18627 */ 18628 final Transformation mTmpTransformation = new Transformation(); 18629 18630 /** 18631 * Temporary list for use in collecting focusable descendents of a view. 18632 */ 18633 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 18634 18635 /** 18636 * The id of the window for accessibility purposes. 18637 */ 18638 int mAccessibilityWindowId = View.NO_ID; 18639 18640 /** 18641 * Flags related to accessibility processing. 18642 * 18643 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 18644 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 18645 */ 18646 int mAccessibilityFetchFlags; 18647 18648 /** 18649 * The drawable for highlighting accessibility focus. 18650 */ 18651 Drawable mAccessibilityFocusDrawable; 18652 18653 /** 18654 * Show where the margins, bounds and layout bounds are for each view. 18655 */ 18656 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 18657 18658 /** 18659 * Point used to compute visible regions. 18660 */ 18661 final Point mPoint = new Point(); 18662 18663 /** 18664 * Used to track which View originated a requestLayout() call, used when 18665 * requestLayout() is called during layout. 18666 */ 18667 View mViewRequestingLayout; 18668 18669 /** 18670 * Creates a new set of attachment information with the specified 18671 * events handler and thread. 18672 * 18673 * @param handler the events handler the view must use 18674 */ 18675 AttachInfo(IWindowSession session, IWindow window, Display display, 18676 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 18677 mSession = session; 18678 mWindow = window; 18679 mWindowToken = window.asBinder(); 18680 mDisplay = display; 18681 mViewRootImpl = viewRootImpl; 18682 mHandler = handler; 18683 mRootCallbacks = effectPlayer; 18684 } 18685 } 18686 18687 /** 18688 * <p>ScrollabilityCache holds various fields used by a View when scrolling 18689 * is supported. This avoids keeping too many unused fields in most 18690 * instances of View.</p> 18691 */ 18692 private static class ScrollabilityCache implements Runnable { 18693 18694 /** 18695 * Scrollbars are not visible 18696 */ 18697 public static final int OFF = 0; 18698 18699 /** 18700 * Scrollbars are visible 18701 */ 18702 public static final int ON = 1; 18703 18704 /** 18705 * Scrollbars are fading away 18706 */ 18707 public static final int FADING = 2; 18708 18709 public boolean fadeScrollBars; 18710 18711 public int fadingEdgeLength; 18712 public int scrollBarDefaultDelayBeforeFade; 18713 public int scrollBarFadeDuration; 18714 18715 public int scrollBarSize; 18716 public ScrollBarDrawable scrollBar; 18717 public float[] interpolatorValues; 18718 public View host; 18719 18720 public final Paint paint; 18721 public final Matrix matrix; 18722 public Shader shader; 18723 18724 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 18725 18726 private static final float[] OPAQUE = { 255 }; 18727 private static final float[] TRANSPARENT = { 0.0f }; 18728 18729 /** 18730 * When fading should start. This time moves into the future every time 18731 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 18732 */ 18733 public long fadeStartTime; 18734 18735 18736 /** 18737 * The current state of the scrollbars: ON, OFF, or FADING 18738 */ 18739 public int state = OFF; 18740 18741 private int mLastColor; 18742 18743 public ScrollabilityCache(ViewConfiguration configuration, View host) { 18744 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 18745 scrollBarSize = configuration.getScaledScrollBarSize(); 18746 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 18747 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 18748 18749 paint = new Paint(); 18750 matrix = new Matrix(); 18751 // use use a height of 1, and then wack the matrix each time we 18752 // actually use it. 18753 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 18754 paint.setShader(shader); 18755 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 18756 18757 this.host = host; 18758 } 18759 18760 public void setFadeColor(int color) { 18761 if (color != mLastColor) { 18762 mLastColor = color; 18763 18764 if (color != 0) { 18765 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 18766 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 18767 paint.setShader(shader); 18768 // Restore the default transfer mode (src_over) 18769 paint.setXfermode(null); 18770 } else { 18771 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 18772 paint.setShader(shader); 18773 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 18774 } 18775 } 18776 } 18777 18778 public void run() { 18779 long now = AnimationUtils.currentAnimationTimeMillis(); 18780 if (now >= fadeStartTime) { 18781 18782 // the animation fades the scrollbars out by changing 18783 // the opacity (alpha) from fully opaque to fully 18784 // transparent 18785 int nextFrame = (int) now; 18786 int framesCount = 0; 18787 18788 Interpolator interpolator = scrollBarInterpolator; 18789 18790 // Start opaque 18791 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 18792 18793 // End transparent 18794 nextFrame += scrollBarFadeDuration; 18795 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 18796 18797 state = FADING; 18798 18799 // Kick off the fade animation 18800 host.invalidate(true); 18801 } 18802 } 18803 } 18804 18805 /** 18806 * Resuable callback for sending 18807 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 18808 */ 18809 private class SendViewScrolledAccessibilityEvent implements Runnable { 18810 public volatile boolean mIsPending; 18811 18812 public void run() { 18813 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 18814 mIsPending = false; 18815 } 18816 } 18817 18818 /** 18819 * <p> 18820 * This class represents a delegate that can be registered in a {@link View} 18821 * to enhance accessibility support via composition rather via inheritance. 18822 * It is specifically targeted to widget developers that extend basic View 18823 * classes i.e. classes in package android.view, that would like their 18824 * applications to be backwards compatible. 18825 * </p> 18826 * <div class="special reference"> 18827 * <h3>Developer Guides</h3> 18828 * <p>For more information about making applications accessible, read the 18829 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 18830 * developer guide.</p> 18831 * </div> 18832 * <p> 18833 * A scenario in which a developer would like to use an accessibility delegate 18834 * is overriding a method introduced in a later API version then the minimal API 18835 * version supported by the application. For example, the method 18836 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 18837 * in API version 4 when the accessibility APIs were first introduced. If a 18838 * developer would like his application to run on API version 4 devices (assuming 18839 * all other APIs used by the application are version 4 or lower) and take advantage 18840 * of this method, instead of overriding the method which would break the application's 18841 * backwards compatibility, he can override the corresponding method in this 18842 * delegate and register the delegate in the target View if the API version of 18843 * the system is high enough i.e. the API version is same or higher to the API 18844 * version that introduced 18845 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 18846 * </p> 18847 * <p> 18848 * Here is an example implementation: 18849 * </p> 18850 * <code><pre><p> 18851 * if (Build.VERSION.SDK_INT >= 14) { 18852 * // If the API version is equal of higher than the version in 18853 * // which onInitializeAccessibilityNodeInfo was introduced we 18854 * // register a delegate with a customized implementation. 18855 * View view = findViewById(R.id.view_id); 18856 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 18857 * public void onInitializeAccessibilityNodeInfo(View host, 18858 * AccessibilityNodeInfo info) { 18859 * // Let the default implementation populate the info. 18860 * super.onInitializeAccessibilityNodeInfo(host, info); 18861 * // Set some other information. 18862 * info.setEnabled(host.isEnabled()); 18863 * } 18864 * }); 18865 * } 18866 * </code></pre></p> 18867 * <p> 18868 * This delegate contains methods that correspond to the accessibility methods 18869 * in View. If a delegate has been specified the implementation in View hands 18870 * off handling to the corresponding method in this delegate. The default 18871 * implementation the delegate methods behaves exactly as the corresponding 18872 * method in View for the case of no accessibility delegate been set. Hence, 18873 * to customize the behavior of a View method, clients can override only the 18874 * corresponding delegate method without altering the behavior of the rest 18875 * accessibility related methods of the host view. 18876 * </p> 18877 */ 18878 public static class AccessibilityDelegate { 18879 18880 /** 18881 * Sends an accessibility event of the given type. If accessibility is not 18882 * enabled this method has no effect. 18883 * <p> 18884 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 18885 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 18886 * been set. 18887 * </p> 18888 * 18889 * @param host The View hosting the delegate. 18890 * @param eventType The type of the event to send. 18891 * 18892 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 18893 */ 18894 public void sendAccessibilityEvent(View host, int eventType) { 18895 host.sendAccessibilityEventInternal(eventType); 18896 } 18897 18898 /** 18899 * Performs the specified accessibility action on the view. For 18900 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 18901 * <p> 18902 * The default implementation behaves as 18903 * {@link View#performAccessibilityAction(int, Bundle) 18904 * View#performAccessibilityAction(int, Bundle)} for the case of 18905 * no accessibility delegate been set. 18906 * </p> 18907 * 18908 * @param action The action to perform. 18909 * @return Whether the action was performed. 18910 * 18911 * @see View#performAccessibilityAction(int, Bundle) 18912 * View#performAccessibilityAction(int, Bundle) 18913 */ 18914 public boolean performAccessibilityAction(View host, int action, Bundle args) { 18915 return host.performAccessibilityActionInternal(action, args); 18916 } 18917 18918 /** 18919 * Sends an accessibility event. This method behaves exactly as 18920 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 18921 * empty {@link AccessibilityEvent} and does not perform a check whether 18922 * accessibility is enabled. 18923 * <p> 18924 * The default implementation behaves as 18925 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18926 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 18927 * the case of no accessibility delegate been set. 18928 * </p> 18929 * 18930 * @param host The View hosting the delegate. 18931 * @param event The event to send. 18932 * 18933 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18934 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18935 */ 18936 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 18937 host.sendAccessibilityEventUncheckedInternal(event); 18938 } 18939 18940 /** 18941 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 18942 * to its children for adding their text content to the event. 18943 * <p> 18944 * The default implementation behaves as 18945 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18946 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 18947 * the case of no accessibility delegate been set. 18948 * </p> 18949 * 18950 * @param host The View hosting the delegate. 18951 * @param event The event. 18952 * @return True if the event population was completed. 18953 * 18954 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18955 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18956 */ 18957 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18958 return host.dispatchPopulateAccessibilityEventInternal(event); 18959 } 18960 18961 /** 18962 * Gives a chance to the host View to populate the accessibility event with its 18963 * text content. 18964 * <p> 18965 * The default implementation behaves as 18966 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 18967 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 18968 * the case of no accessibility delegate been set. 18969 * </p> 18970 * 18971 * @param host The View hosting the delegate. 18972 * @param event The accessibility event which to populate. 18973 * 18974 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 18975 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 18976 */ 18977 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18978 host.onPopulateAccessibilityEventInternal(event); 18979 } 18980 18981 /** 18982 * Initializes an {@link AccessibilityEvent} with information about the 18983 * the host View which is the event source. 18984 * <p> 18985 * The default implementation behaves as 18986 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 18987 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 18988 * the case of no accessibility delegate been set. 18989 * </p> 18990 * 18991 * @param host The View hosting the delegate. 18992 * @param event The event to initialize. 18993 * 18994 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 18995 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 18996 */ 18997 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 18998 host.onInitializeAccessibilityEventInternal(event); 18999 } 19000 19001 /** 19002 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 19003 * <p> 19004 * The default implementation behaves as 19005 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19006 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 19007 * the case of no accessibility delegate been set. 19008 * </p> 19009 * 19010 * @param host The View hosting the delegate. 19011 * @param info The instance to initialize. 19012 * 19013 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19014 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19015 */ 19016 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 19017 host.onInitializeAccessibilityNodeInfoInternal(info); 19018 } 19019 19020 /** 19021 * Called when a child of the host View has requested sending an 19022 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 19023 * to augment the event. 19024 * <p> 19025 * The default implementation behaves as 19026 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19027 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 19028 * the case of no accessibility delegate been set. 19029 * </p> 19030 * 19031 * @param host The View hosting the delegate. 19032 * @param child The child which requests sending the event. 19033 * @param event The event to be sent. 19034 * @return True if the event should be sent 19035 * 19036 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19037 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19038 */ 19039 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 19040 AccessibilityEvent event) { 19041 return host.onRequestSendAccessibilityEventInternal(child, event); 19042 } 19043 19044 /** 19045 * Gets the provider for managing a virtual view hierarchy rooted at this View 19046 * and reported to {@link android.accessibilityservice.AccessibilityService}s 19047 * that explore the window content. 19048 * <p> 19049 * The default implementation behaves as 19050 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 19051 * the case of no accessibility delegate been set. 19052 * </p> 19053 * 19054 * @return The provider. 19055 * 19056 * @see AccessibilityNodeProvider 19057 */ 19058 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 19059 return null; 19060 } 19061 19062 /** 19063 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 19064 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 19065 * This method is responsible for obtaining an accessibility node info from a 19066 * pool of reusable instances and calling 19067 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 19068 * view to initialize the former. 19069 * <p> 19070 * <strong>Note:</strong> The client is responsible for recycling the obtained 19071 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 19072 * creation. 19073 * </p> 19074 * <p> 19075 * The default implementation behaves as 19076 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 19077 * the case of no accessibility delegate been set. 19078 * </p> 19079 * @return A populated {@link AccessibilityNodeInfo}. 19080 * 19081 * @see AccessibilityNodeInfo 19082 * 19083 * @hide 19084 */ 19085 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 19086 return host.createAccessibilityNodeInfoInternal(); 19087 } 19088 } 19089 19090 private class MatchIdPredicate implements Predicate<View> { 19091 public int mId; 19092 19093 @Override 19094 public boolean apply(View view) { 19095 return (view.mID == mId); 19096 } 19097 } 19098 19099 private class MatchLabelForPredicate implements Predicate<View> { 19100 private int mLabeledId; 19101 19102 @Override 19103 public boolean apply(View view) { 19104 return (view.mLabelForId == mLabeledId); 19105 } 19106 } 19107 19108 private class SendViewStateChangedAccessibilityEvent implements Runnable { 19109 private boolean mPosted; 19110 private long mLastEventTimeMillis; 19111 19112 public void run() { 19113 mPosted = false; 19114 mLastEventTimeMillis = SystemClock.uptimeMillis(); 19115 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 19116 AccessibilityEvent event = AccessibilityEvent.obtain(); 19117 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 19118 event.setContentChangeType(AccessibilityEvent.CONTENT_CHANGE_TYPE_NODE); 19119 sendAccessibilityEventUnchecked(event); 19120 } 19121 } 19122 19123 public void runOrPost() { 19124 if (mPosted) { 19125 return; 19126 } 19127 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 19128 final long minEventIntevalMillis = 19129 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 19130 if (timeSinceLastMillis >= minEventIntevalMillis) { 19131 removeCallbacks(this); 19132 run(); 19133 } else { 19134 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 19135 mPosted = true; 19136 } 19137 } 19138 } 19139 19140 /** 19141 * Dump all private flags in readable format, useful for documentation and 19142 * sanity checking. 19143 */ 19144 private static void dumpFlags() { 19145 final HashMap<String, String> found = Maps.newHashMap(); 19146 try { 19147 for (Field field : View.class.getDeclaredFields()) { 19148 final int modifiers = field.getModifiers(); 19149 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 19150 if (field.getType().equals(int.class)) { 19151 final int value = field.getInt(null); 19152 dumpFlag(found, field.getName(), value); 19153 } else if (field.getType().equals(int[].class)) { 19154 final int[] values = (int[]) field.get(null); 19155 for (int i = 0; i < values.length; i++) { 19156 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 19157 } 19158 } 19159 } 19160 } 19161 } catch (IllegalAccessException e) { 19162 throw new RuntimeException(e); 19163 } 19164 19165 final ArrayList<String> keys = Lists.newArrayList(); 19166 keys.addAll(found.keySet()); 19167 Collections.sort(keys); 19168 for (String key : keys) { 19169 Log.d(VIEW_LOG_TAG, found.get(key)); 19170 } 19171 } 19172 19173 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 19174 // Sort flags by prefix, then by bits, always keeping unique keys 19175 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 19176 final int prefix = name.indexOf('_'); 19177 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 19178 final String output = bits + " " + name; 19179 found.put(key, output); 19180 } 19181} 19182