View.java revision 2918ab6c3258639148b8a5c78a34483af195246e
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.Log; 55import android.util.Pool; 56import android.util.Poolable; 57import android.util.PoolableManager; 58import android.util.Pools; 59import android.util.Property; 60import android.util.SparseArray; 61import android.util.TypedValue; 62import android.view.ContextMenu.ContextMenuInfo; 63import android.view.AccessibilityIterators.TextSegmentIterator; 64import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 65import android.view.AccessibilityIterators.WordTextSegmentIterator; 66import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 67import android.view.accessibility.AccessibilityEvent; 68import android.view.accessibility.AccessibilityEventSource; 69import android.view.accessibility.AccessibilityManager; 70import android.view.accessibility.AccessibilityNodeInfo; 71import android.view.accessibility.AccessibilityNodeProvider; 72import android.view.animation.Animation; 73import android.view.animation.AnimationUtils; 74import android.view.animation.Transformation; 75import android.view.inputmethod.EditorInfo; 76import android.view.inputmethod.InputConnection; 77import android.view.inputmethod.InputMethodManager; 78import android.widget.ScrollBarDrawable; 79 80import static android.os.Build.VERSION_CODES.*; 81import static java.lang.Math.max; 82 83import com.android.internal.R; 84import com.android.internal.util.Predicate; 85import com.android.internal.view.menu.MenuBuilder; 86import com.google.android.collect.Lists; 87import com.google.android.collect.Maps; 88 89import java.lang.ref.WeakReference; 90import java.lang.reflect.Field; 91import java.lang.reflect.InvocationTargetException; 92import java.lang.reflect.Method; 93import java.lang.reflect.Modifier; 94import java.util.ArrayList; 95import java.util.Arrays; 96import java.util.Collections; 97import java.util.HashMap; 98import java.util.Locale; 99import java.util.concurrent.CopyOnWriteArrayList; 100import java.util.concurrent.atomic.AtomicInteger; 101 102/** 103 * <p> 104 * This class represents the basic building block for user interface components. A View 105 * occupies a rectangular area on the screen and is responsible for drawing and 106 * event handling. View is the base class for <em>widgets</em>, which are 107 * used to create interactive UI components (buttons, text fields, etc.). The 108 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 109 * are invisible containers that hold other Views (or other ViewGroups) and define 110 * their layout properties. 111 * </p> 112 * 113 * <div class="special reference"> 114 * <h3>Developer Guides</h3> 115 * <p>For information about using this class to develop your application's user interface, 116 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 117 * </div> 118 * 119 * <a name="Using"></a> 120 * <h3>Using Views</h3> 121 * <p> 122 * All of the views in a window are arranged in a single tree. You can add views 123 * either from code or by specifying a tree of views in one or more XML layout 124 * files. There are many specialized subclasses of views that act as controls or 125 * are capable of displaying text, images, or other content. 126 * </p> 127 * <p> 128 * Once you have created a tree of views, there are typically a few types of 129 * common operations you may wish to perform: 130 * <ul> 131 * <li><strong>Set properties:</strong> for example setting the text of a 132 * {@link android.widget.TextView}. The available properties and the methods 133 * that set them will vary among the different subclasses of views. Note that 134 * properties that are known at build time can be set in the XML layout 135 * files.</li> 136 * <li><strong>Set focus:</strong> The framework will handled moving focus in 137 * response to user input. To force focus to a specific view, call 138 * {@link #requestFocus}.</li> 139 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 140 * that will be notified when something interesting happens to the view. For 141 * example, all views will let you set a listener to be notified when the view 142 * gains or loses focus. You can register such a listener using 143 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 144 * Other view subclasses offer more specialized listeners. For example, a Button 145 * exposes a listener to notify clients when the button is clicked.</li> 146 * <li><strong>Set visibility:</strong> You can hide or show views using 147 * {@link #setVisibility(int)}.</li> 148 * </ul> 149 * </p> 150 * <p><em> 151 * Note: The Android framework is responsible for measuring, laying out and 152 * drawing views. You should not call methods that perform these actions on 153 * views yourself unless you are actually implementing a 154 * {@link android.view.ViewGroup}. 155 * </em></p> 156 * 157 * <a name="Lifecycle"></a> 158 * <h3>Implementing a Custom View</h3> 159 * 160 * <p> 161 * To implement a custom view, you will usually begin by providing overrides for 162 * some of the standard methods that the framework calls on all views. You do 163 * not need to override all of these methods. In fact, you can start by just 164 * overriding {@link #onDraw(android.graphics.Canvas)}. 165 * <table border="2" width="85%" align="center" cellpadding="5"> 166 * <thead> 167 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 168 * </thead> 169 * 170 * <tbody> 171 * <tr> 172 * <td rowspan="2">Creation</td> 173 * <td>Constructors</td> 174 * <td>There is a form of the constructor that are called when the view 175 * is created from code and a form that is called when the view is 176 * inflated from a layout file. The second form should parse and apply 177 * any attributes defined in the layout file. 178 * </td> 179 * </tr> 180 * <tr> 181 * <td><code>{@link #onFinishInflate()}</code></td> 182 * <td>Called after a view and all of its children has been inflated 183 * from XML.</td> 184 * </tr> 185 * 186 * <tr> 187 * <td rowspan="3">Layout</td> 188 * <td><code>{@link #onMeasure(int, int)}</code></td> 189 * <td>Called to determine the size requirements for this view and all 190 * of its children. 191 * </td> 192 * </tr> 193 * <tr> 194 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 195 * <td>Called when this view should assign a size and position to all 196 * of its children. 197 * </td> 198 * </tr> 199 * <tr> 200 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 201 * <td>Called when the size of this view has changed. 202 * </td> 203 * </tr> 204 * 205 * <tr> 206 * <td>Drawing</td> 207 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 208 * <td>Called when the view should render its content. 209 * </td> 210 * </tr> 211 * 212 * <tr> 213 * <td rowspan="4">Event processing</td> 214 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 215 * <td>Called when a new hardware key event occurs. 216 * </td> 217 * </tr> 218 * <tr> 219 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 220 * <td>Called when a hardware key up event occurs. 221 * </td> 222 * </tr> 223 * <tr> 224 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 225 * <td>Called when a trackball motion event occurs. 226 * </td> 227 * </tr> 228 * <tr> 229 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 230 * <td>Called when a touch screen motion event occurs. 231 * </td> 232 * </tr> 233 * 234 * <tr> 235 * <td rowspan="2">Focus</td> 236 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 237 * <td>Called when the view gains or loses focus. 238 * </td> 239 * </tr> 240 * 241 * <tr> 242 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 243 * <td>Called when the window containing the view gains or loses focus. 244 * </td> 245 * </tr> 246 * 247 * <tr> 248 * <td rowspan="3">Attaching</td> 249 * <td><code>{@link #onAttachedToWindow()}</code></td> 250 * <td>Called when the view is attached to a window. 251 * </td> 252 * </tr> 253 * 254 * <tr> 255 * <td><code>{@link #onDetachedFromWindow}</code></td> 256 * <td>Called when the view is detached from its window. 257 * </td> 258 * </tr> 259 * 260 * <tr> 261 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 262 * <td>Called when the visibility of the window containing the view 263 * has changed. 264 * </td> 265 * </tr> 266 * </tbody> 267 * 268 * </table> 269 * </p> 270 * 271 * <a name="IDs"></a> 272 * <h3>IDs</h3> 273 * Views may have an integer id associated with them. These ids are typically 274 * assigned in the layout XML files, and are used to find specific views within 275 * the view tree. A common pattern is to: 276 * <ul> 277 * <li>Define a Button in the layout file and assign it a unique ID. 278 * <pre> 279 * <Button 280 * android:id="@+id/my_button" 281 * android:layout_width="wrap_content" 282 * android:layout_height="wrap_content" 283 * android:text="@string/my_button_text"/> 284 * </pre></li> 285 * <li>From the onCreate method of an Activity, find the Button 286 * <pre class="prettyprint"> 287 * Button myButton = (Button) findViewById(R.id.my_button); 288 * </pre></li> 289 * </ul> 290 * <p> 291 * View IDs need not be unique throughout the tree, but it is good practice to 292 * ensure that they are at least unique within the part of the tree you are 293 * searching. 294 * </p> 295 * 296 * <a name="Position"></a> 297 * <h3>Position</h3> 298 * <p> 299 * The geometry of a view is that of a rectangle. A view has a location, 300 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 301 * two dimensions, expressed as a width and a height. The unit for location 302 * and dimensions is the pixel. 303 * </p> 304 * 305 * <p> 306 * It is possible to retrieve the location of a view by invoking the methods 307 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 308 * coordinate of the rectangle representing the view. The latter returns the 309 * top, or Y, coordinate of the rectangle representing the view. These methods 310 * both return the location of the view relative to its parent. For instance, 311 * when getLeft() returns 20, that means the view is located 20 pixels to the 312 * right of the left edge of its direct parent. 313 * </p> 314 * 315 * <p> 316 * In addition, several convenience methods are offered to avoid unnecessary 317 * computations, namely {@link #getRight()} and {@link #getBottom()}. 318 * These methods return the coordinates of the right and bottom edges of the 319 * rectangle representing the view. For instance, calling {@link #getRight()} 320 * is similar to the following computation: <code>getLeft() + getWidth()</code> 321 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 322 * </p> 323 * 324 * <a name="SizePaddingMargins"></a> 325 * <h3>Size, padding and margins</h3> 326 * <p> 327 * The size of a view is expressed with a width and a height. A view actually 328 * possess two pairs of width and height values. 329 * </p> 330 * 331 * <p> 332 * The first pair is known as <em>measured width</em> and 333 * <em>measured height</em>. These dimensions define how big a view wants to be 334 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 335 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 336 * and {@link #getMeasuredHeight()}. 337 * </p> 338 * 339 * <p> 340 * The second pair is simply known as <em>width</em> and <em>height</em>, or 341 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 342 * dimensions define the actual size of the view on screen, at drawing time and 343 * after layout. These values may, but do not have to, be different from the 344 * measured width and height. The width and height can be obtained by calling 345 * {@link #getWidth()} and {@link #getHeight()}. 346 * </p> 347 * 348 * <p> 349 * To measure its dimensions, a view takes into account its padding. The padding 350 * is expressed in pixels for the left, top, right and bottom parts of the view. 351 * Padding can be used to offset the content of the view by a specific amount of 352 * pixels. For instance, a left padding of 2 will push the view's content by 353 * 2 pixels to the right of the left edge. Padding can be set using the 354 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 355 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 356 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 357 * {@link #getPaddingEnd()}. 358 * </p> 359 * 360 * <p> 361 * Even though a view can define a padding, it does not provide any support for 362 * margins. However, view groups provide such a support. Refer to 363 * {@link android.view.ViewGroup} and 364 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 365 * </p> 366 * 367 * <a name="Layout"></a> 368 * <h3>Layout</h3> 369 * <p> 370 * Layout is a two pass process: a measure pass and a layout pass. The measuring 371 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 372 * of the view tree. Each view pushes dimension specifications down the tree 373 * during the recursion. At the end of the measure pass, every view has stored 374 * its measurements. The second pass happens in 375 * {@link #layout(int,int,int,int)} and is also top-down. During 376 * this pass each parent is responsible for positioning all of its children 377 * using the sizes computed in the measure pass. 378 * </p> 379 * 380 * <p> 381 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 382 * {@link #getMeasuredHeight()} values must be set, along with those for all of 383 * that view's descendants. A view's measured width and measured height values 384 * must respect the constraints imposed by the view's parents. This guarantees 385 * that at the end of the measure pass, all parents accept all of their 386 * children's measurements. A parent view may call measure() more than once on 387 * its children. For example, the parent may measure each child once with 388 * unspecified dimensions to find out how big they want to be, then call 389 * measure() on them again with actual numbers if the sum of all the children's 390 * unconstrained sizes is too big or too small. 391 * </p> 392 * 393 * <p> 394 * The measure pass uses two classes to communicate dimensions. The 395 * {@link MeasureSpec} class is used by views to tell their parents how they 396 * want to be measured and positioned. The base LayoutParams class just 397 * describes how big the view wants to be for both width and height. For each 398 * dimension, it can specify one of: 399 * <ul> 400 * <li> an exact number 401 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 402 * (minus padding) 403 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 404 * enclose its content (plus padding). 405 * </ul> 406 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 407 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 408 * an X and Y value. 409 * </p> 410 * 411 * <p> 412 * MeasureSpecs are used to push requirements down the tree from parent to 413 * child. A MeasureSpec can be in one of three modes: 414 * <ul> 415 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 416 * of a child view. For example, a LinearLayout may call measure() on its child 417 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 418 * tall the child view wants to be given a width of 240 pixels. 419 * <li>EXACTLY: This is used by the parent to impose an exact size on the 420 * child. The child must use this size, and guarantee that all of its 421 * descendants will fit within this size. 422 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 423 * child. The child must gurantee that it and all of its descendants will fit 424 * within this size. 425 * </ul> 426 * </p> 427 * 428 * <p> 429 * To intiate a layout, call {@link #requestLayout}. This method is typically 430 * called by a view on itself when it believes that is can no longer fit within 431 * its current bounds. 432 * </p> 433 * 434 * <a name="Drawing"></a> 435 * <h3>Drawing</h3> 436 * <p> 437 * Drawing is handled by walking the tree and rendering each view that 438 * intersects the invalid region. Because the tree is traversed in-order, 439 * this means that parents will draw before (i.e., behind) their children, with 440 * siblings drawn in the order they appear in the tree. 441 * If you set a background drawable for a View, then the View will draw it for you 442 * before calling back to its <code>onDraw()</code> method. 443 * </p> 444 * 445 * <p> 446 * Note that the framework will not draw views that are not in the invalid region. 447 * </p> 448 * 449 * <p> 450 * To force a view to draw, call {@link #invalidate()}. 451 * </p> 452 * 453 * <a name="EventHandlingThreading"></a> 454 * <h3>Event Handling and Threading</h3> 455 * <p> 456 * The basic cycle of a view is as follows: 457 * <ol> 458 * <li>An event comes in and is dispatched to the appropriate view. The view 459 * handles the event and notifies any listeners.</li> 460 * <li>If in the course of processing the event, the view's bounds may need 461 * to be changed, the view will call {@link #requestLayout()}.</li> 462 * <li>Similarly, if in the course of processing the event the view's appearance 463 * may need to be changed, the view will call {@link #invalidate()}.</li> 464 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 465 * the framework will take care of measuring, laying out, and drawing the tree 466 * as appropriate.</li> 467 * </ol> 468 * </p> 469 * 470 * <p><em>Note: The entire view tree is single threaded. You must always be on 471 * the UI thread when calling any method on any view.</em> 472 * If you are doing work on other threads and want to update the state of a view 473 * from that thread, you should use a {@link Handler}. 474 * </p> 475 * 476 * <a name="FocusHandling"></a> 477 * <h3>Focus Handling</h3> 478 * <p> 479 * The framework will handle routine focus movement in response to user input. 480 * This includes changing the focus as views are removed or hidden, or as new 481 * views become available. Views indicate their willingness to take focus 482 * through the {@link #isFocusable} method. To change whether a view can take 483 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 484 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 485 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 486 * </p> 487 * <p> 488 * Focus movement is based on an algorithm which finds the nearest neighbor in a 489 * given direction. In rare cases, the default algorithm may not match the 490 * intended behavior of the developer. In these situations, you can provide 491 * explicit overrides by using these XML attributes in the layout file: 492 * <pre> 493 * nextFocusDown 494 * nextFocusLeft 495 * nextFocusRight 496 * nextFocusUp 497 * </pre> 498 * </p> 499 * 500 * 501 * <p> 502 * To get a particular view to take focus, call {@link #requestFocus()}. 503 * </p> 504 * 505 * <a name="TouchMode"></a> 506 * <h3>Touch Mode</h3> 507 * <p> 508 * When a user is navigating a user interface via directional keys such as a D-pad, it is 509 * necessary to give focus to actionable items such as buttons so the user can see 510 * what will take input. If the device has touch capabilities, however, and the user 511 * begins interacting with the interface by touching it, it is no longer necessary to 512 * always highlight, or give focus to, a particular view. This motivates a mode 513 * for interaction named 'touch mode'. 514 * </p> 515 * <p> 516 * For a touch capable device, once the user touches the screen, the device 517 * will enter touch mode. From this point onward, only views for which 518 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 519 * Other views that are touchable, like buttons, will not take focus when touched; they will 520 * only fire the on click listeners. 521 * </p> 522 * <p> 523 * Any time a user hits a directional key, such as a D-pad direction, the view device will 524 * exit touch mode, and find a view to take focus, so that the user may resume interacting 525 * with the user interface without touching the screen again. 526 * </p> 527 * <p> 528 * The touch mode state is maintained across {@link android.app.Activity}s. Call 529 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 530 * </p> 531 * 532 * <a name="Scrolling"></a> 533 * <h3>Scrolling</h3> 534 * <p> 535 * The framework provides basic support for views that wish to internally 536 * scroll their content. This includes keeping track of the X and Y scroll 537 * offset as well as mechanisms for drawing scrollbars. See 538 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 539 * {@link #awakenScrollBars()} for more details. 540 * </p> 541 * 542 * <a name="Tags"></a> 543 * <h3>Tags</h3> 544 * <p> 545 * Unlike IDs, tags are not used to identify views. Tags are essentially an 546 * extra piece of information that can be associated with a view. They are most 547 * often used as a convenience to store data related to views in the views 548 * themselves rather than by putting them in a separate structure. 549 * </p> 550 * 551 * <a name="Properties"></a> 552 * <h3>Properties</h3> 553 * <p> 554 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 555 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 556 * available both in the {@link Property} form as well as in similarly-named setter/getter 557 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 558 * be used to set persistent state associated with these rendering-related properties on the view. 559 * The properties and methods can also be used in conjunction with 560 * {@link android.animation.Animator Animator}-based animations, described more in the 561 * <a href="#Animation">Animation</a> section. 562 * </p> 563 * 564 * <a name="Animation"></a> 565 * <h3>Animation</h3> 566 * <p> 567 * Starting with Android 3.0, the preferred way of animating views is to use the 568 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 569 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 570 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 571 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 572 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 573 * makes animating these View properties particularly easy and efficient. 574 * </p> 575 * <p> 576 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 577 * You can attach an {@link Animation} object to a view using 578 * {@link #setAnimation(Animation)} or 579 * {@link #startAnimation(Animation)}. The animation can alter the scale, 580 * rotation, translation and alpha of a view over time. If the animation is 581 * attached to a view that has children, the animation will affect the entire 582 * subtree rooted by that node. When an animation is started, the framework will 583 * take care of redrawing the appropriate views until the animation completes. 584 * </p> 585 * 586 * <a name="Security"></a> 587 * <h3>Security</h3> 588 * <p> 589 * Sometimes it is essential that an application be able to verify that an action 590 * is being performed with the full knowledge and consent of the user, such as 591 * granting a permission request, making a purchase or clicking on an advertisement. 592 * Unfortunately, a malicious application could try to spoof the user into 593 * performing these actions, unaware, by concealing the intended purpose of the view. 594 * As a remedy, the framework offers a touch filtering mechanism that can be used to 595 * improve the security of views that provide access to sensitive functionality. 596 * </p><p> 597 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 598 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 599 * will discard touches that are received whenever the view's window is obscured by 600 * another visible window. As a result, the view will not receive touches whenever a 601 * toast, dialog or other window appears above the view's window. 602 * </p><p> 603 * For more fine-grained control over security, consider overriding the 604 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 605 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 606 * </p> 607 * 608 * @attr ref android.R.styleable#View_alpha 609 * @attr ref android.R.styleable#View_background 610 * @attr ref android.R.styleable#View_clickable 611 * @attr ref android.R.styleable#View_contentDescription 612 * @attr ref android.R.styleable#View_drawingCacheQuality 613 * @attr ref android.R.styleable#View_duplicateParentState 614 * @attr ref android.R.styleable#View_id 615 * @attr ref android.R.styleable#View_requiresFadingEdge 616 * @attr ref android.R.styleable#View_fadeScrollbars 617 * @attr ref android.R.styleable#View_fadingEdgeLength 618 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 619 * @attr ref android.R.styleable#View_fitsSystemWindows 620 * @attr ref android.R.styleable#View_isScrollContainer 621 * @attr ref android.R.styleable#View_focusable 622 * @attr ref android.R.styleable#View_focusableInTouchMode 623 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 624 * @attr ref android.R.styleable#View_keepScreenOn 625 * @attr ref android.R.styleable#View_layerType 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_transformPivotX 664 * @attr ref android.R.styleable#View_transformPivotY 665 * @attr ref android.R.styleable#View_translationX 666 * @attr ref android.R.styleable#View_translationY 667 * @attr ref android.R.styleable#View_visibility 668 * 669 * @see android.view.ViewGroup 670 */ 671public class View implements Drawable.Callback, KeyEvent.Callback, 672 AccessibilityEventSource { 673 private static final boolean DBG = false; 674 675 /** 676 * The logging tag used by this class with android.util.Log. 677 */ 678 protected static final String VIEW_LOG_TAG = "View"; 679 680 /** 681 * When set to true, apps will draw debugging information about their layouts. 682 * 683 * @hide 684 */ 685 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 686 687 /** 688 * Used to mark a View that has no ID. 689 */ 690 public static final int NO_ID = -1; 691 692 /** 693 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 694 * calling setFlags. 695 */ 696 private static final int NOT_FOCUSABLE = 0x00000000; 697 698 /** 699 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 700 * setFlags. 701 */ 702 private static final int FOCUSABLE = 0x00000001; 703 704 /** 705 * Mask for use with setFlags indicating bits used for focus. 706 */ 707 private static final int FOCUSABLE_MASK = 0x00000001; 708 709 /** 710 * This view will adjust its padding to fit sytem windows (e.g. status bar) 711 */ 712 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 713 714 /** 715 * This view is visible. 716 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 717 * android:visibility}. 718 */ 719 public static final int VISIBLE = 0x00000000; 720 721 /** 722 * This view is invisible, but it still takes up space for layout purposes. 723 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 724 * android:visibility}. 725 */ 726 public static final int INVISIBLE = 0x00000004; 727 728 /** 729 * This view is invisible, and it doesn't take any space for layout 730 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 731 * android:visibility}. 732 */ 733 public static final int GONE = 0x00000008; 734 735 /** 736 * Mask for use with setFlags indicating bits used for visibility. 737 * {@hide} 738 */ 739 static final int VISIBILITY_MASK = 0x0000000C; 740 741 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 742 743 /** 744 * This view is enabled. Interpretation varies by subclass. 745 * Use with ENABLED_MASK when calling setFlags. 746 * {@hide} 747 */ 748 static final int ENABLED = 0x00000000; 749 750 /** 751 * This view is disabled. Interpretation varies by subclass. 752 * Use with ENABLED_MASK when calling setFlags. 753 * {@hide} 754 */ 755 static final int DISABLED = 0x00000020; 756 757 /** 758 * Mask for use with setFlags indicating bits used for indicating whether 759 * this view is enabled 760 * {@hide} 761 */ 762 static final int ENABLED_MASK = 0x00000020; 763 764 /** 765 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 766 * called and further optimizations will be performed. It is okay to have 767 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 768 * {@hide} 769 */ 770 static final int WILL_NOT_DRAW = 0x00000080; 771 772 /** 773 * Mask for use with setFlags indicating bits used for indicating whether 774 * this view is will draw 775 * {@hide} 776 */ 777 static final int DRAW_MASK = 0x00000080; 778 779 /** 780 * <p>This view doesn't show scrollbars.</p> 781 * {@hide} 782 */ 783 static final int SCROLLBARS_NONE = 0x00000000; 784 785 /** 786 * <p>This view shows horizontal scrollbars.</p> 787 * {@hide} 788 */ 789 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 790 791 /** 792 * <p>This view shows vertical scrollbars.</p> 793 * {@hide} 794 */ 795 static final int SCROLLBARS_VERTICAL = 0x00000200; 796 797 /** 798 * <p>Mask for use with setFlags indicating bits used for indicating which 799 * scrollbars are enabled.</p> 800 * {@hide} 801 */ 802 static final int SCROLLBARS_MASK = 0x00000300; 803 804 /** 805 * Indicates that the view should filter touches when its window is obscured. 806 * Refer to the class comments for more information about this security feature. 807 * {@hide} 808 */ 809 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 810 811 /** 812 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 813 * that they are optional and should be skipped if the window has 814 * requested system UI flags that ignore those insets for layout. 815 */ 816 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 817 818 /** 819 * <p>This view doesn't show fading edges.</p> 820 * {@hide} 821 */ 822 static final int FADING_EDGE_NONE = 0x00000000; 823 824 /** 825 * <p>This view shows horizontal fading edges.</p> 826 * {@hide} 827 */ 828 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 829 830 /** 831 * <p>This view shows vertical fading edges.</p> 832 * {@hide} 833 */ 834 static final int FADING_EDGE_VERTICAL = 0x00002000; 835 836 /** 837 * <p>Mask for use with setFlags indicating bits used for indicating which 838 * fading edges are enabled.</p> 839 * {@hide} 840 */ 841 static final int FADING_EDGE_MASK = 0x00003000; 842 843 /** 844 * <p>Indicates this view can be clicked. When clickable, a View reacts 845 * to clicks by notifying the OnClickListener.<p> 846 * {@hide} 847 */ 848 static final int CLICKABLE = 0x00004000; 849 850 /** 851 * <p>Indicates this view is caching its drawing into a bitmap.</p> 852 * {@hide} 853 */ 854 static final int DRAWING_CACHE_ENABLED = 0x00008000; 855 856 /** 857 * <p>Indicates that no icicle should be saved for this view.<p> 858 * {@hide} 859 */ 860 static final int SAVE_DISABLED = 0x000010000; 861 862 /** 863 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 864 * property.</p> 865 * {@hide} 866 */ 867 static final int SAVE_DISABLED_MASK = 0x000010000; 868 869 /** 870 * <p>Indicates that no drawing cache should ever be created for this view.<p> 871 * {@hide} 872 */ 873 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 874 875 /** 876 * <p>Indicates this view can take / keep focus when int touch mode.</p> 877 * {@hide} 878 */ 879 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 880 881 /** 882 * <p>Enables low quality mode for the drawing cache.</p> 883 */ 884 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 885 886 /** 887 * <p>Enables high quality mode for the drawing cache.</p> 888 */ 889 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 890 891 /** 892 * <p>Enables automatic quality mode for the drawing cache.</p> 893 */ 894 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 895 896 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 897 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 898 }; 899 900 /** 901 * <p>Mask for use with setFlags indicating bits used for the cache 902 * quality property.</p> 903 * {@hide} 904 */ 905 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 906 907 /** 908 * <p> 909 * Indicates this view can be long clicked. When long clickable, a View 910 * reacts to long clicks by notifying the OnLongClickListener or showing a 911 * context menu. 912 * </p> 913 * {@hide} 914 */ 915 static final int LONG_CLICKABLE = 0x00200000; 916 917 /** 918 * <p>Indicates that this view gets its drawable states from its direct parent 919 * and ignores its original internal states.</p> 920 * 921 * @hide 922 */ 923 static final int DUPLICATE_PARENT_STATE = 0x00400000; 924 925 /** 926 * The scrollbar style to display the scrollbars inside the content area, 927 * without increasing the padding. The scrollbars will be overlaid with 928 * translucency on the view's content. 929 */ 930 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 931 932 /** 933 * The scrollbar style to display the scrollbars inside the padded area, 934 * increasing the padding of the view. The scrollbars will not overlap the 935 * content area of the view. 936 */ 937 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 938 939 /** 940 * The scrollbar style to display the scrollbars at the edge of the view, 941 * without increasing the padding. The scrollbars will be overlaid with 942 * translucency. 943 */ 944 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 945 946 /** 947 * The scrollbar style to display the scrollbars at the edge of the view, 948 * increasing the padding of the view. The scrollbars will only overlap the 949 * background, if any. 950 */ 951 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 952 953 /** 954 * Mask to check if the scrollbar style is overlay or inset. 955 * {@hide} 956 */ 957 static final int SCROLLBARS_INSET_MASK = 0x01000000; 958 959 /** 960 * Mask to check if the scrollbar style is inside or outside. 961 * {@hide} 962 */ 963 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 964 965 /** 966 * Mask for scrollbar style. 967 * {@hide} 968 */ 969 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 970 971 /** 972 * View flag indicating that the screen should remain on while the 973 * window containing this view is visible to the user. This effectively 974 * takes care of automatically setting the WindowManager's 975 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 976 */ 977 public static final int KEEP_SCREEN_ON = 0x04000000; 978 979 /** 980 * View flag indicating whether this view should have sound effects enabled 981 * for events such as clicking and touching. 982 */ 983 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 984 985 /** 986 * View flag indicating whether this view should have haptic feedback 987 * enabled for events such as long presses. 988 */ 989 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 990 991 /** 992 * <p>Indicates that the view hierarchy should stop saving state when 993 * it reaches this view. If state saving is initiated immediately at 994 * the view, it will be allowed. 995 * {@hide} 996 */ 997 static final int PARENT_SAVE_DISABLED = 0x20000000; 998 999 /** 1000 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1001 * {@hide} 1002 */ 1003 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1004 1005 /** 1006 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1007 * should add all focusable Views regardless if they are focusable in touch mode. 1008 */ 1009 public static final int FOCUSABLES_ALL = 0x00000000; 1010 1011 /** 1012 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1013 * should add only Views focusable in touch mode. 1014 */ 1015 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1016 1017 /** 1018 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1019 * item. 1020 */ 1021 public static final int FOCUS_BACKWARD = 0x00000001; 1022 1023 /** 1024 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1025 * item. 1026 */ 1027 public static final int FOCUS_FORWARD = 0x00000002; 1028 1029 /** 1030 * Use with {@link #focusSearch(int)}. Move focus to the left. 1031 */ 1032 public static final int FOCUS_LEFT = 0x00000011; 1033 1034 /** 1035 * Use with {@link #focusSearch(int)}. Move focus up. 1036 */ 1037 public static final int FOCUS_UP = 0x00000021; 1038 1039 /** 1040 * Use with {@link #focusSearch(int)}. Move focus to the right. 1041 */ 1042 public static final int FOCUS_RIGHT = 0x00000042; 1043 1044 /** 1045 * Use with {@link #focusSearch(int)}. Move focus down. 1046 */ 1047 public static final int FOCUS_DOWN = 0x00000082; 1048 1049 /** 1050 * Bits of {@link #getMeasuredWidthAndState()} and 1051 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1052 */ 1053 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1054 1055 /** 1056 * Bits of {@link #getMeasuredWidthAndState()} and 1057 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1058 */ 1059 public static final int MEASURED_STATE_MASK = 0xff000000; 1060 1061 /** 1062 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1063 * for functions that combine both width and height into a single int, 1064 * such as {@link #getMeasuredState()} and the childState argument of 1065 * {@link #resolveSizeAndState(int, int, int)}. 1066 */ 1067 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1068 1069 /** 1070 * Bit of {@link #getMeasuredWidthAndState()} and 1071 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1072 * is smaller that the space the view would like to have. 1073 */ 1074 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1075 1076 /** 1077 * Base View state sets 1078 */ 1079 // Singles 1080 /** 1081 * Indicates the view has no states set. States are used with 1082 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1083 * view depending on its state. 1084 * 1085 * @see android.graphics.drawable.Drawable 1086 * @see #getDrawableState() 1087 */ 1088 protected static final int[] EMPTY_STATE_SET; 1089 /** 1090 * Indicates the view is enabled. States are used with 1091 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1092 * view depending on its state. 1093 * 1094 * @see android.graphics.drawable.Drawable 1095 * @see #getDrawableState() 1096 */ 1097 protected static final int[] ENABLED_STATE_SET; 1098 /** 1099 * Indicates the view is focused. States are used with 1100 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1101 * view depending on its state. 1102 * 1103 * @see android.graphics.drawable.Drawable 1104 * @see #getDrawableState() 1105 */ 1106 protected static final int[] FOCUSED_STATE_SET; 1107 /** 1108 * Indicates the view is selected. States are used with 1109 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1110 * view depending on its state. 1111 * 1112 * @see android.graphics.drawable.Drawable 1113 * @see #getDrawableState() 1114 */ 1115 protected static final int[] SELECTED_STATE_SET; 1116 /** 1117 * Indicates the view is pressed. States are used with 1118 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1119 * view depending on its state. 1120 * 1121 * @see android.graphics.drawable.Drawable 1122 * @see #getDrawableState() 1123 * @hide 1124 */ 1125 protected static final int[] PRESSED_STATE_SET; 1126 /** 1127 * Indicates the view's window has focus. States are used with 1128 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1129 * view depending on its state. 1130 * 1131 * @see android.graphics.drawable.Drawable 1132 * @see #getDrawableState() 1133 */ 1134 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1135 // Doubles 1136 /** 1137 * Indicates the view is enabled and has the focus. 1138 * 1139 * @see #ENABLED_STATE_SET 1140 * @see #FOCUSED_STATE_SET 1141 */ 1142 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1143 /** 1144 * Indicates the view is enabled and selected. 1145 * 1146 * @see #ENABLED_STATE_SET 1147 * @see #SELECTED_STATE_SET 1148 */ 1149 protected static final int[] ENABLED_SELECTED_STATE_SET; 1150 /** 1151 * Indicates the view is enabled and that its window has focus. 1152 * 1153 * @see #ENABLED_STATE_SET 1154 * @see #WINDOW_FOCUSED_STATE_SET 1155 */ 1156 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1157 /** 1158 * Indicates the view is focused and selected. 1159 * 1160 * @see #FOCUSED_STATE_SET 1161 * @see #SELECTED_STATE_SET 1162 */ 1163 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1164 /** 1165 * Indicates the view has the focus and that its window has the focus. 1166 * 1167 * @see #FOCUSED_STATE_SET 1168 * @see #WINDOW_FOCUSED_STATE_SET 1169 */ 1170 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1171 /** 1172 * Indicates the view is selected and that its window has the focus. 1173 * 1174 * @see #SELECTED_STATE_SET 1175 * @see #WINDOW_FOCUSED_STATE_SET 1176 */ 1177 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1178 // Triples 1179 /** 1180 * Indicates the view is enabled, focused and selected. 1181 * 1182 * @see #ENABLED_STATE_SET 1183 * @see #FOCUSED_STATE_SET 1184 * @see #SELECTED_STATE_SET 1185 */ 1186 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1187 /** 1188 * Indicates the view is enabled, focused and its window has the focus. 1189 * 1190 * @see #ENABLED_STATE_SET 1191 * @see #FOCUSED_STATE_SET 1192 * @see #WINDOW_FOCUSED_STATE_SET 1193 */ 1194 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1195 /** 1196 * Indicates the view is enabled, selected and its window has the focus. 1197 * 1198 * @see #ENABLED_STATE_SET 1199 * @see #SELECTED_STATE_SET 1200 * @see #WINDOW_FOCUSED_STATE_SET 1201 */ 1202 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1203 /** 1204 * Indicates the view is focused, selected and its window has the focus. 1205 * 1206 * @see #FOCUSED_STATE_SET 1207 * @see #SELECTED_STATE_SET 1208 * @see #WINDOW_FOCUSED_STATE_SET 1209 */ 1210 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1211 /** 1212 * Indicates the view is enabled, focused, selected and its window 1213 * has the focus. 1214 * 1215 * @see #ENABLED_STATE_SET 1216 * @see #FOCUSED_STATE_SET 1217 * @see #SELECTED_STATE_SET 1218 * @see #WINDOW_FOCUSED_STATE_SET 1219 */ 1220 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1221 /** 1222 * Indicates the view is pressed and its window has the focus. 1223 * 1224 * @see #PRESSED_STATE_SET 1225 * @see #WINDOW_FOCUSED_STATE_SET 1226 */ 1227 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1228 /** 1229 * Indicates the view is pressed and selected. 1230 * 1231 * @see #PRESSED_STATE_SET 1232 * @see #SELECTED_STATE_SET 1233 */ 1234 protected static final int[] PRESSED_SELECTED_STATE_SET; 1235 /** 1236 * Indicates the view is pressed, selected and its window has the focus. 1237 * 1238 * @see #PRESSED_STATE_SET 1239 * @see #SELECTED_STATE_SET 1240 * @see #WINDOW_FOCUSED_STATE_SET 1241 */ 1242 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1243 /** 1244 * Indicates the view is pressed and focused. 1245 * 1246 * @see #PRESSED_STATE_SET 1247 * @see #FOCUSED_STATE_SET 1248 */ 1249 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1250 /** 1251 * Indicates the view is pressed, focused and its window has the focus. 1252 * 1253 * @see #PRESSED_STATE_SET 1254 * @see #FOCUSED_STATE_SET 1255 * @see #WINDOW_FOCUSED_STATE_SET 1256 */ 1257 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1258 /** 1259 * Indicates the view is pressed, focused and selected. 1260 * 1261 * @see #PRESSED_STATE_SET 1262 * @see #SELECTED_STATE_SET 1263 * @see #FOCUSED_STATE_SET 1264 */ 1265 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1266 /** 1267 * Indicates the view is pressed, focused, selected and its window has the focus. 1268 * 1269 * @see #PRESSED_STATE_SET 1270 * @see #FOCUSED_STATE_SET 1271 * @see #SELECTED_STATE_SET 1272 * @see #WINDOW_FOCUSED_STATE_SET 1273 */ 1274 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1275 /** 1276 * Indicates the view is pressed and enabled. 1277 * 1278 * @see #PRESSED_STATE_SET 1279 * @see #ENABLED_STATE_SET 1280 */ 1281 protected static final int[] PRESSED_ENABLED_STATE_SET; 1282 /** 1283 * Indicates the view is pressed, enabled and its window has the focus. 1284 * 1285 * @see #PRESSED_STATE_SET 1286 * @see #ENABLED_STATE_SET 1287 * @see #WINDOW_FOCUSED_STATE_SET 1288 */ 1289 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1290 /** 1291 * Indicates the view is pressed, enabled and selected. 1292 * 1293 * @see #PRESSED_STATE_SET 1294 * @see #ENABLED_STATE_SET 1295 * @see #SELECTED_STATE_SET 1296 */ 1297 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1298 /** 1299 * Indicates the view is pressed, enabled, selected and its window has the 1300 * focus. 1301 * 1302 * @see #PRESSED_STATE_SET 1303 * @see #ENABLED_STATE_SET 1304 * @see #SELECTED_STATE_SET 1305 * @see #WINDOW_FOCUSED_STATE_SET 1306 */ 1307 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1308 /** 1309 * Indicates the view is pressed, enabled and focused. 1310 * 1311 * @see #PRESSED_STATE_SET 1312 * @see #ENABLED_STATE_SET 1313 * @see #FOCUSED_STATE_SET 1314 */ 1315 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1316 /** 1317 * Indicates the view is pressed, enabled, focused and its window has the 1318 * focus. 1319 * 1320 * @see #PRESSED_STATE_SET 1321 * @see #ENABLED_STATE_SET 1322 * @see #FOCUSED_STATE_SET 1323 * @see #WINDOW_FOCUSED_STATE_SET 1324 */ 1325 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1326 /** 1327 * Indicates the view is pressed, enabled, focused and selected. 1328 * 1329 * @see #PRESSED_STATE_SET 1330 * @see #ENABLED_STATE_SET 1331 * @see #SELECTED_STATE_SET 1332 * @see #FOCUSED_STATE_SET 1333 */ 1334 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1335 /** 1336 * Indicates the view is pressed, enabled, focused, selected and its window 1337 * has the focus. 1338 * 1339 * @see #PRESSED_STATE_SET 1340 * @see #ENABLED_STATE_SET 1341 * @see #SELECTED_STATE_SET 1342 * @see #FOCUSED_STATE_SET 1343 * @see #WINDOW_FOCUSED_STATE_SET 1344 */ 1345 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1346 1347 /** 1348 * The order here is very important to {@link #getDrawableState()} 1349 */ 1350 private static final int[][] VIEW_STATE_SETS; 1351 1352 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1353 static final int VIEW_STATE_SELECTED = 1 << 1; 1354 static final int VIEW_STATE_FOCUSED = 1 << 2; 1355 static final int VIEW_STATE_ENABLED = 1 << 3; 1356 static final int VIEW_STATE_PRESSED = 1 << 4; 1357 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1358 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1359 static final int VIEW_STATE_HOVERED = 1 << 7; 1360 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1361 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1362 1363 static final int[] VIEW_STATE_IDS = new int[] { 1364 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1365 R.attr.state_selected, VIEW_STATE_SELECTED, 1366 R.attr.state_focused, VIEW_STATE_FOCUSED, 1367 R.attr.state_enabled, VIEW_STATE_ENABLED, 1368 R.attr.state_pressed, VIEW_STATE_PRESSED, 1369 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1370 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1371 R.attr.state_hovered, VIEW_STATE_HOVERED, 1372 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1373 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1374 }; 1375 1376 static { 1377 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1378 throw new IllegalStateException( 1379 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1380 } 1381 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1382 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1383 int viewState = R.styleable.ViewDrawableStates[i]; 1384 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1385 if (VIEW_STATE_IDS[j] == viewState) { 1386 orderedIds[i * 2] = viewState; 1387 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1388 } 1389 } 1390 } 1391 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1392 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1393 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1394 int numBits = Integer.bitCount(i); 1395 int[] set = new int[numBits]; 1396 int pos = 0; 1397 for (int j = 0; j < orderedIds.length; j += 2) { 1398 if ((i & orderedIds[j+1]) != 0) { 1399 set[pos++] = orderedIds[j]; 1400 } 1401 } 1402 VIEW_STATE_SETS[i] = set; 1403 } 1404 1405 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1406 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1407 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1408 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1409 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1410 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1411 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1412 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1413 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1414 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1415 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1416 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1417 | VIEW_STATE_FOCUSED]; 1418 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1419 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1420 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1421 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1422 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1423 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1424 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1425 | VIEW_STATE_ENABLED]; 1426 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1427 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1428 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1429 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1430 | VIEW_STATE_ENABLED]; 1431 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1432 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1433 | VIEW_STATE_ENABLED]; 1434 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1435 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1436 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1437 1438 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1439 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1440 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1441 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1442 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1443 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1444 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1445 | VIEW_STATE_PRESSED]; 1446 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1447 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1448 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1449 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1450 | VIEW_STATE_PRESSED]; 1451 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1452 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1453 | VIEW_STATE_PRESSED]; 1454 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1455 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1456 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1457 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1458 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1459 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1460 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1461 | VIEW_STATE_PRESSED]; 1462 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1463 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1464 | VIEW_STATE_PRESSED]; 1465 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1466 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1467 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1468 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1469 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1470 | VIEW_STATE_PRESSED]; 1471 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1472 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1473 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1474 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1475 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1476 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1477 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1478 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1479 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1480 | VIEW_STATE_PRESSED]; 1481 } 1482 1483 /** 1484 * Accessibility event types that are dispatched for text population. 1485 */ 1486 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1487 AccessibilityEvent.TYPE_VIEW_CLICKED 1488 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1489 | AccessibilityEvent.TYPE_VIEW_SELECTED 1490 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1491 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1492 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1493 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1494 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1495 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1496 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1497 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1498 1499 /** 1500 * Temporary Rect currently for use in setBackground(). This will probably 1501 * be extended in the future to hold our own class with more than just 1502 * a Rect. :) 1503 */ 1504 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1505 1506 /** 1507 * Map used to store views' tags. 1508 */ 1509 private SparseArray<Object> mKeyedTags; 1510 1511 /** 1512 * The next available accessibility id. 1513 */ 1514 private static int sNextAccessibilityViewId; 1515 1516 /** 1517 * The animation currently associated with this view. 1518 * @hide 1519 */ 1520 protected Animation mCurrentAnimation = null; 1521 1522 /** 1523 * Width as measured during measure pass. 1524 * {@hide} 1525 */ 1526 @ViewDebug.ExportedProperty(category = "measurement") 1527 int mMeasuredWidth; 1528 1529 /** 1530 * Height as measured during measure pass. 1531 * {@hide} 1532 */ 1533 @ViewDebug.ExportedProperty(category = "measurement") 1534 int mMeasuredHeight; 1535 1536 /** 1537 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1538 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1539 * its display list. This flag, used only when hw accelerated, allows us to clear the 1540 * flag while retaining this information until it's needed (at getDisplayList() time and 1541 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1542 * 1543 * {@hide} 1544 */ 1545 boolean mRecreateDisplayList = false; 1546 1547 /** 1548 * The view's identifier. 1549 * {@hide} 1550 * 1551 * @see #setId(int) 1552 * @see #getId() 1553 */ 1554 @ViewDebug.ExportedProperty(resolveId = true) 1555 int mID = NO_ID; 1556 1557 /** 1558 * The stable ID of this view for accessibility purposes. 1559 */ 1560 int mAccessibilityViewId = NO_ID; 1561 1562 /** 1563 * @hide 1564 */ 1565 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1566 1567 /** 1568 * The view's tag. 1569 * {@hide} 1570 * 1571 * @see #setTag(Object) 1572 * @see #getTag() 1573 */ 1574 protected Object mTag; 1575 1576 // for mPrivateFlags: 1577 /** {@hide} */ 1578 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1579 /** {@hide} */ 1580 static final int PFLAG_FOCUSED = 0x00000002; 1581 /** {@hide} */ 1582 static final int PFLAG_SELECTED = 0x00000004; 1583 /** {@hide} */ 1584 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1585 /** {@hide} */ 1586 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1587 /** {@hide} */ 1588 static final int PFLAG_DRAWN = 0x00000020; 1589 /** 1590 * When this flag is set, this view is running an animation on behalf of its 1591 * children and should therefore not cancel invalidate requests, even if they 1592 * lie outside of this view's bounds. 1593 * 1594 * {@hide} 1595 */ 1596 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1597 /** {@hide} */ 1598 static final int PFLAG_SKIP_DRAW = 0x00000080; 1599 /** {@hide} */ 1600 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1601 /** {@hide} */ 1602 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1603 /** {@hide} */ 1604 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1605 /** {@hide} */ 1606 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1607 /** {@hide} */ 1608 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1609 /** {@hide} */ 1610 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1611 1612 private static final int PFLAG_PRESSED = 0x00004000; 1613 1614 /** {@hide} */ 1615 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1616 /** 1617 * Flag used to indicate that this view should be drawn once more (and only once 1618 * more) after its animation has completed. 1619 * {@hide} 1620 */ 1621 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1622 1623 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1624 1625 /** 1626 * Indicates that the View returned true when onSetAlpha() was called and that 1627 * the alpha must be restored. 1628 * {@hide} 1629 */ 1630 static final int PFLAG_ALPHA_SET = 0x00040000; 1631 1632 /** 1633 * Set by {@link #setScrollContainer(boolean)}. 1634 */ 1635 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1636 1637 /** 1638 * Set by {@link #setScrollContainer(boolean)}. 1639 */ 1640 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1641 1642 /** 1643 * View flag indicating whether this view was invalidated (fully or partially.) 1644 * 1645 * @hide 1646 */ 1647 static final int PFLAG_DIRTY = 0x00200000; 1648 1649 /** 1650 * View flag indicating whether this view was invalidated by an opaque 1651 * invalidate request. 1652 * 1653 * @hide 1654 */ 1655 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1656 1657 /** 1658 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1659 * 1660 * @hide 1661 */ 1662 static final int PFLAG_DIRTY_MASK = 0x00600000; 1663 1664 /** 1665 * Indicates whether the background is opaque. 1666 * 1667 * @hide 1668 */ 1669 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1670 1671 /** 1672 * Indicates whether the scrollbars are opaque. 1673 * 1674 * @hide 1675 */ 1676 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1677 1678 /** 1679 * Indicates whether the view is opaque. 1680 * 1681 * @hide 1682 */ 1683 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1684 1685 /** 1686 * Indicates a prepressed state; 1687 * the short time between ACTION_DOWN and recognizing 1688 * a 'real' press. Prepressed is used to recognize quick taps 1689 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1690 * 1691 * @hide 1692 */ 1693 private static final int PFLAG_PREPRESSED = 0x02000000; 1694 1695 /** 1696 * Indicates whether the view is temporarily detached. 1697 * 1698 * @hide 1699 */ 1700 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1701 1702 /** 1703 * Indicates that we should awaken scroll bars once attached 1704 * 1705 * @hide 1706 */ 1707 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1708 1709 /** 1710 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1711 * @hide 1712 */ 1713 private static final int PFLAG_HOVERED = 0x10000000; 1714 1715 /** 1716 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1717 * for transform operations 1718 * 1719 * @hide 1720 */ 1721 private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000; 1722 1723 /** {@hide} */ 1724 static final int PFLAG_ACTIVATED = 0x40000000; 1725 1726 /** 1727 * Indicates that this view was specifically invalidated, not just dirtied because some 1728 * child view was invalidated. The flag is used to determine when we need to recreate 1729 * a view's display list (as opposed to just returning a reference to its existing 1730 * display list). 1731 * 1732 * @hide 1733 */ 1734 static final int PFLAG_INVALIDATED = 0x80000000; 1735 1736 /** 1737 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1738 * 1739 * -------|-------|-------|-------| 1740 * PFLAG2_TEXT_ALIGNMENT_FLAGS[0] 1741 * PFLAG2_TEXT_DIRECTION_FLAGS[0] 1742 * 1 PFLAG2_DRAG_CAN_ACCEPT 1743 * 1 PFLAG2_DRAG_HOVERED 1744 * 1 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT 1745 * 11 PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1746 * 1 1 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT 1747 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1748 * 11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 1749 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1750 * 1 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT 1751 * 1 1 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT 1752 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1753 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1754 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1755 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1756 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1757 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1758 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1759 * 111 PFLAG2_TEXT_DIRECTION_MASK 1760 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1761 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1762 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1763 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1764 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1765 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1766 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1767 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1768 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1769 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1770 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1771 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1772 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1773 * 11 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1774 * 1 PFLAG2_HAS_TRANSIENT_STATE 1775 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1776 * 1 PFLAG2_ACCESSIBILITY_STATE_CHANGED 1777 * 1 PFLAG2_VIEW_QUICK_REJECTED 1778 * 1 PFLAG2_PADDING_RESOLVED 1779 * -------|-------|-------|-------| 1780 */ 1781 1782 /** 1783 * Indicates that this view has reported that it can accept the current drag's content. 1784 * Cleared when the drag operation concludes. 1785 * @hide 1786 */ 1787 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1788 1789 /** 1790 * Indicates that this view is currently directly under the drag location in a 1791 * drag-and-drop operation involving content that it can accept. Cleared when 1792 * the drag exits the view, or when the drag operation concludes. 1793 * @hide 1794 */ 1795 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1796 1797 /** 1798 * Horizontal layout direction of this view is from Left to Right. 1799 * Use with {@link #setLayoutDirection}. 1800 */ 1801 public static final int LAYOUT_DIRECTION_LTR = 0; 1802 1803 /** 1804 * Horizontal layout direction of this view is from Right to Left. 1805 * Use with {@link #setLayoutDirection}. 1806 */ 1807 public static final int LAYOUT_DIRECTION_RTL = 1; 1808 1809 /** 1810 * Horizontal layout direction of this view is inherited from its parent. 1811 * Use with {@link #setLayoutDirection}. 1812 */ 1813 public static final int LAYOUT_DIRECTION_INHERIT = 2; 1814 1815 /** 1816 * Horizontal layout direction of this view is from deduced from the default language 1817 * script for the locale. Use with {@link #setLayoutDirection}. 1818 */ 1819 public static final int LAYOUT_DIRECTION_LOCALE = 3; 1820 1821 /** 1822 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1823 * @hide 1824 */ 1825 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1826 1827 /** 1828 * Mask for use with private flags indicating bits used for horizontal layout direction. 1829 * @hide 1830 */ 1831 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1832 1833 /** 1834 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1835 * right-to-left direction. 1836 * @hide 1837 */ 1838 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1839 1840 /** 1841 * Indicates whether the view horizontal layout direction has been resolved. 1842 * @hide 1843 */ 1844 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1845 1846 /** 1847 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1848 * @hide 1849 */ 1850 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1851 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1852 1853 /* 1854 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1855 * flag value. 1856 * @hide 1857 */ 1858 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1859 LAYOUT_DIRECTION_LTR, 1860 LAYOUT_DIRECTION_RTL, 1861 LAYOUT_DIRECTION_INHERIT, 1862 LAYOUT_DIRECTION_LOCALE 1863 }; 1864 1865 /** 1866 * Default horizontal layout direction. 1867 * @hide 1868 */ 1869 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1870 1871 /** 1872 * Indicates that the view is tracking some sort of transient state 1873 * that the app should not need to be aware of, but that the framework 1874 * should take special care to preserve. 1875 * 1876 * @hide 1877 */ 1878 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22; 1879 1880 /** 1881 * Text direction is inherited thru {@link ViewGroup} 1882 */ 1883 public static final int TEXT_DIRECTION_INHERIT = 0; 1884 1885 /** 1886 * Text direction is using "first strong algorithm". The first strong directional character 1887 * determines the paragraph direction. If there is no strong directional character, the 1888 * paragraph direction is the view's resolved layout direction. 1889 */ 1890 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1891 1892 /** 1893 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1894 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1895 * If there are neither, the paragraph direction is the view's resolved layout direction. 1896 */ 1897 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1898 1899 /** 1900 * Text direction is forced to LTR. 1901 */ 1902 public static final int TEXT_DIRECTION_LTR = 3; 1903 1904 /** 1905 * Text direction is forced to RTL. 1906 */ 1907 public static final int TEXT_DIRECTION_RTL = 4; 1908 1909 /** 1910 * Text direction is coming from the system Locale. 1911 */ 1912 public static final int TEXT_DIRECTION_LOCALE = 5; 1913 1914 /** 1915 * Default text direction is inherited 1916 */ 1917 public static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 1918 1919 /** 1920 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 1921 * @hide 1922 */ 1923 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 1924 1925 /** 1926 * Mask for use with private flags indicating bits used for text direction. 1927 * @hide 1928 */ 1929 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 1930 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1931 1932 /** 1933 * Array of text direction flags for mapping attribute "textDirection" to correct 1934 * flag value. 1935 * @hide 1936 */ 1937 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 1938 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1939 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1940 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1941 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1942 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1943 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1944 }; 1945 1946 /** 1947 * Indicates whether the view text direction has been resolved. 1948 * @hide 1949 */ 1950 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 1951 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1952 1953 /** 1954 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1955 * @hide 1956 */ 1957 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 1958 1959 /** 1960 * Mask for use with private flags indicating bits used for resolved text direction. 1961 * @hide 1962 */ 1963 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 1964 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1965 1966 /** 1967 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 1968 * @hide 1969 */ 1970 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 1971 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1972 1973 /* 1974 * Default text alignment. The text alignment of this View is inherited from its parent. 1975 * Use with {@link #setTextAlignment(int)} 1976 */ 1977 public static final int TEXT_ALIGNMENT_INHERIT = 0; 1978 1979 /** 1980 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 1981 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 1982 * 1983 * Use with {@link #setTextAlignment(int)} 1984 */ 1985 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 1986 1987 /** 1988 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 1989 * 1990 * Use with {@link #setTextAlignment(int)} 1991 */ 1992 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 1993 1994 /** 1995 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 1996 * 1997 * Use with {@link #setTextAlignment(int)} 1998 */ 1999 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2000 2001 /** 2002 * Center the paragraph, e.g. ALIGN_CENTER. 2003 * 2004 * Use with {@link #setTextAlignment(int)} 2005 */ 2006 public static final int TEXT_ALIGNMENT_CENTER = 4; 2007 2008 /** 2009 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2010 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2011 * 2012 * Use with {@link #setTextAlignment(int)} 2013 */ 2014 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2015 2016 /** 2017 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2018 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2019 * 2020 * Use with {@link #setTextAlignment(int)} 2021 */ 2022 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2023 2024 /** 2025 * Default text alignment is inherited 2026 */ 2027 public static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2028 2029 /** 2030 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2031 * @hide 2032 */ 2033 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2034 2035 /** 2036 * Mask for use with private flags indicating bits used for text alignment. 2037 * @hide 2038 */ 2039 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2040 2041 /** 2042 * Array of text direction flags for mapping attribute "textAlignment" to correct 2043 * flag value. 2044 * @hide 2045 */ 2046 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2047 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2048 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2049 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2050 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2051 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2052 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2053 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2054 }; 2055 2056 /** 2057 * Indicates whether the view text alignment has been resolved. 2058 * @hide 2059 */ 2060 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2061 2062 /** 2063 * Bit shift to get the resolved text alignment. 2064 * @hide 2065 */ 2066 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2067 2068 /** 2069 * Mask for use with private flags indicating bits used for text alignment. 2070 * @hide 2071 */ 2072 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2073 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2074 2075 /** 2076 * Indicates whether if the view text alignment has been resolved to gravity 2077 */ 2078 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2079 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2080 2081 // Accessiblity constants for mPrivateFlags2 2082 2083 /** 2084 * Shift for the bits in {@link #mPrivateFlags2} related to the 2085 * "importantForAccessibility" attribute. 2086 */ 2087 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2088 2089 /** 2090 * Automatically determine whether a view is important for accessibility. 2091 */ 2092 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2093 2094 /** 2095 * The view is important for accessibility. 2096 */ 2097 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2098 2099 /** 2100 * The view is not important for accessibility. 2101 */ 2102 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2103 2104 /** 2105 * The default whether the view is important for accessibility. 2106 */ 2107 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2108 2109 /** 2110 * Mask for obtainig the bits which specify how to determine 2111 * whether a view is important for accessibility. 2112 */ 2113 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2114 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO) 2115 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2116 2117 /** 2118 * Flag indicating whether a view has accessibility focus. 2119 */ 2120 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x00000040 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2121 2122 /** 2123 * Flag indicating whether a view state for accessibility has changed. 2124 */ 2125 static final int PFLAG2_ACCESSIBILITY_STATE_CHANGED = 0x00000080 2126 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2127 2128 /** 2129 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2130 * is used to check whether later changes to the view's transform should invalidate the 2131 * view to force the quickReject test to run again. 2132 */ 2133 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2134 2135 /** 2136 * Flag indicating that start/end padding has been resolved into left/right padding 2137 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2138 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2139 * during measurement. In some special cases this is required such as when an adapter-based 2140 * view measures prospective children without attaching them to a window. 2141 */ 2142 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2143 2144 /** 2145 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2146 */ 2147 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2148 2149 /** 2150 * Group of bits indicating that RTL properties resolution is done. 2151 */ 2152 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2153 PFLAG2_TEXT_DIRECTION_RESOLVED | 2154 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2155 PFLAG2_PADDING_RESOLVED | 2156 PFLAG2_DRAWABLE_RESOLVED; 2157 2158 // There are a couple of flags left in mPrivateFlags2 2159 2160 /* End of masks for mPrivateFlags2 */ 2161 2162 /* Masks for mPrivateFlags3 */ 2163 2164 /** 2165 * Flag indicating that view has a transform animation set on it. This is used to track whether 2166 * an animation is cleared between successive frames, in order to tell the associated 2167 * DisplayList to clear its animation matrix. 2168 */ 2169 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2170 2171 /** 2172 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2173 * animation is cleared between successive frames, in order to tell the associated 2174 * DisplayList to restore its alpha value. 2175 */ 2176 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2177 2178 2179 /* End of masks for mPrivateFlags3 */ 2180 2181 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2182 2183 /** 2184 * Always allow a user to over-scroll this view, provided it is a 2185 * view that can scroll. 2186 * 2187 * @see #getOverScrollMode() 2188 * @see #setOverScrollMode(int) 2189 */ 2190 public static final int OVER_SCROLL_ALWAYS = 0; 2191 2192 /** 2193 * Allow a user to over-scroll this view only if the content is large 2194 * enough to meaningfully scroll, provided it is a view that can scroll. 2195 * 2196 * @see #getOverScrollMode() 2197 * @see #setOverScrollMode(int) 2198 */ 2199 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2200 2201 /** 2202 * Never allow a user to over-scroll this view. 2203 * 2204 * @see #getOverScrollMode() 2205 * @see #setOverScrollMode(int) 2206 */ 2207 public static final int OVER_SCROLL_NEVER = 2; 2208 2209 /** 2210 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2211 * requested the system UI (status bar) to be visible (the default). 2212 * 2213 * @see #setSystemUiVisibility(int) 2214 */ 2215 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2216 2217 /** 2218 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2219 * system UI to enter an unobtrusive "low profile" mode. 2220 * 2221 * <p>This is for use in games, book readers, video players, or any other 2222 * "immersive" application where the usual system chrome is deemed too distracting. 2223 * 2224 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2225 * 2226 * @see #setSystemUiVisibility(int) 2227 */ 2228 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2229 2230 /** 2231 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2232 * system navigation be temporarily hidden. 2233 * 2234 * <p>This is an even less obtrusive state than that called for by 2235 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2236 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2237 * those to disappear. This is useful (in conjunction with the 2238 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2239 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2240 * window flags) for displaying content using every last pixel on the display. 2241 * 2242 * <p>There is a limitation: because navigation controls are so important, the least user 2243 * interaction will cause them to reappear immediately. When this happens, both 2244 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2245 * so that both elements reappear at the same time. 2246 * 2247 * @see #setSystemUiVisibility(int) 2248 */ 2249 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2250 2251 /** 2252 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2253 * into the normal fullscreen mode so that its content can take over the screen 2254 * while still allowing the user to interact with the application. 2255 * 2256 * <p>This has the same visual effect as 2257 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2258 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2259 * meaning that non-critical screen decorations (such as the status bar) will be 2260 * hidden while the user is in the View's window, focusing the experience on 2261 * that content. Unlike the window flag, if you are using ActionBar in 2262 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2263 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2264 * hide the action bar. 2265 * 2266 * <p>This approach to going fullscreen is best used over the window flag when 2267 * it is a transient state -- that is, the application does this at certain 2268 * points in its user interaction where it wants to allow the user to focus 2269 * on content, but not as a continuous state. For situations where the application 2270 * would like to simply stay full screen the entire time (such as a game that 2271 * wants to take over the screen), the 2272 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2273 * is usually a better approach. The state set here will be removed by the system 2274 * in various situations (such as the user moving to another application) like 2275 * the other system UI states. 2276 * 2277 * <p>When using this flag, the application should provide some easy facility 2278 * for the user to go out of it. A common example would be in an e-book 2279 * reader, where tapping on the screen brings back whatever screen and UI 2280 * decorations that had been hidden while the user was immersed in reading 2281 * the book. 2282 * 2283 * @see #setSystemUiVisibility(int) 2284 */ 2285 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2286 2287 /** 2288 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2289 * flags, we would like a stable view of the content insets given to 2290 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2291 * will always represent the worst case that the application can expect 2292 * as a continuous state. In the stock Android UI this is the space for 2293 * the system bar, nav bar, and status bar, but not more transient elements 2294 * such as an input method. 2295 * 2296 * The stable layout your UI sees is based on the system UI modes you can 2297 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2298 * then you will get a stable layout for changes of the 2299 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2300 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2301 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2302 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2303 * with a stable layout. (Note that you should avoid using 2304 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2305 * 2306 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2307 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2308 * then a hidden status bar will be considered a "stable" state for purposes 2309 * here. This allows your UI to continually hide the status bar, while still 2310 * using the system UI flags to hide the action bar while still retaining 2311 * a stable layout. Note that changing the window fullscreen flag will never 2312 * provide a stable layout for a clean transition. 2313 * 2314 * <p>If you are using ActionBar in 2315 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2316 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2317 * insets it adds to those given to the application. 2318 */ 2319 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2320 2321 /** 2322 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2323 * to be layed out as if it has requested 2324 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2325 * allows it to avoid artifacts when switching in and out of that mode, at 2326 * the expense that some of its user interface may be covered by screen 2327 * decorations when they are shown. You can perform layout of your inner 2328 * UI elements to account for the navagation system UI through the 2329 * {@link #fitSystemWindows(Rect)} method. 2330 */ 2331 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2332 2333 /** 2334 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2335 * to be layed out as if it has requested 2336 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2337 * allows it to avoid artifacts when switching in and out of that mode, at 2338 * the expense that some of its user interface may be covered by screen 2339 * decorations when they are shown. You can perform layout of your inner 2340 * UI elements to account for non-fullscreen system UI through the 2341 * {@link #fitSystemWindows(Rect)} method. 2342 */ 2343 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2344 2345 /** 2346 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2347 */ 2348 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2349 2350 /** 2351 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2352 */ 2353 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2354 2355 /** 2356 * @hide 2357 * 2358 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2359 * out of the public fields to keep the undefined bits out of the developer's way. 2360 * 2361 * Flag to make the status bar not expandable. Unless you also 2362 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2363 */ 2364 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2365 2366 /** 2367 * @hide 2368 * 2369 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2370 * out of the public fields to keep the undefined bits out of the developer's way. 2371 * 2372 * Flag to hide notification icons and scrolling ticker text. 2373 */ 2374 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2375 2376 /** 2377 * @hide 2378 * 2379 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2380 * out of the public fields to keep the undefined bits out of the developer's way. 2381 * 2382 * Flag to disable incoming notification alerts. This will not block 2383 * icons, but it will block sound, vibrating and other visual or aural notifications. 2384 */ 2385 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2386 2387 /** 2388 * @hide 2389 * 2390 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2391 * out of the public fields to keep the undefined bits out of the developer's way. 2392 * 2393 * Flag to hide only the scrolling ticker. Note that 2394 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2395 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2396 */ 2397 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2398 2399 /** 2400 * @hide 2401 * 2402 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2403 * out of the public fields to keep the undefined bits out of the developer's way. 2404 * 2405 * Flag to hide the center system info area. 2406 */ 2407 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2408 2409 /** 2410 * @hide 2411 * 2412 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2413 * out of the public fields to keep the undefined bits out of the developer's way. 2414 * 2415 * Flag to hide only the home button. Don't use this 2416 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2417 */ 2418 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 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 hide only the back button. Don't use this 2427 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2428 */ 2429 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 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 only the clock. You might use this if your activity has 2438 * its own clock making the status bar's clock redundant. 2439 */ 2440 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2441 2442 /** 2443 * @hide 2444 * 2445 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2446 * out of the public fields to keep the undefined bits out of the developer's way. 2447 * 2448 * Flag to hide only the recent apps button. Don't use this 2449 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2450 */ 2451 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2452 2453 /** 2454 * @hide 2455 */ 2456 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2457 2458 /** 2459 * These are the system UI flags that can be cleared by events outside 2460 * of an application. Currently this is just the ability to tap on the 2461 * screen while hiding the navigation bar to have it return. 2462 * @hide 2463 */ 2464 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2465 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2466 | SYSTEM_UI_FLAG_FULLSCREEN; 2467 2468 /** 2469 * Flags that can impact the layout in relation to system UI. 2470 */ 2471 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2472 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2473 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2474 2475 /** 2476 * Find views that render the specified text. 2477 * 2478 * @see #findViewsWithText(ArrayList, CharSequence, int) 2479 */ 2480 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2481 2482 /** 2483 * Find find views that contain the specified content description. 2484 * 2485 * @see #findViewsWithText(ArrayList, CharSequence, int) 2486 */ 2487 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2488 2489 /** 2490 * Find views that contain {@link AccessibilityNodeProvider}. Such 2491 * a View is a root of virtual view hierarchy and may contain the searched 2492 * text. If this flag is set Views with providers are automatically 2493 * added and it is a responsibility of the client to call the APIs of 2494 * the provider to determine whether the virtual tree rooted at this View 2495 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2496 * represeting the virtual views with this text. 2497 * 2498 * @see #findViewsWithText(ArrayList, CharSequence, int) 2499 * 2500 * @hide 2501 */ 2502 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2503 2504 /** 2505 * The undefined cursor position. 2506 */ 2507 private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2508 2509 /** 2510 * Indicates that the screen has changed state and is now off. 2511 * 2512 * @see #onScreenStateChanged(int) 2513 */ 2514 public static final int SCREEN_STATE_OFF = 0x0; 2515 2516 /** 2517 * Indicates that the screen has changed state and is now on. 2518 * 2519 * @see #onScreenStateChanged(int) 2520 */ 2521 public static final int SCREEN_STATE_ON = 0x1; 2522 2523 /** 2524 * Controls the over-scroll mode for this view. 2525 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2526 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2527 * and {@link #OVER_SCROLL_NEVER}. 2528 */ 2529 private int mOverScrollMode; 2530 2531 /** 2532 * The parent this view is attached to. 2533 * {@hide} 2534 * 2535 * @see #getParent() 2536 */ 2537 protected ViewParent mParent; 2538 2539 /** 2540 * {@hide} 2541 */ 2542 AttachInfo mAttachInfo; 2543 2544 /** 2545 * {@hide} 2546 */ 2547 @ViewDebug.ExportedProperty(flagMapping = { 2548 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2549 name = "FORCE_LAYOUT"), 2550 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2551 name = "LAYOUT_REQUIRED"), 2552 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2553 name = "DRAWING_CACHE_INVALID", outputIf = false), 2554 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2555 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2556 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2557 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2558 }) 2559 int mPrivateFlags; 2560 int mPrivateFlags2; 2561 int mPrivateFlags3; 2562 2563 /** 2564 * This view's request for the visibility of the status bar. 2565 * @hide 2566 */ 2567 @ViewDebug.ExportedProperty(flagMapping = { 2568 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2569 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2570 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2571 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2572 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2573 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2574 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2575 equals = SYSTEM_UI_FLAG_VISIBLE, 2576 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2577 }) 2578 int mSystemUiVisibility; 2579 2580 /** 2581 * Reference count for transient state. 2582 * @see #setHasTransientState(boolean) 2583 */ 2584 int mTransientStateCount = 0; 2585 2586 /** 2587 * Count of how many windows this view has been attached to. 2588 */ 2589 int mWindowAttachCount; 2590 2591 /** 2592 * The layout parameters associated with this view and used by the parent 2593 * {@link android.view.ViewGroup} to determine how this view should be 2594 * laid out. 2595 * {@hide} 2596 */ 2597 protected ViewGroup.LayoutParams mLayoutParams; 2598 2599 /** 2600 * The view flags hold various views states. 2601 * {@hide} 2602 */ 2603 @ViewDebug.ExportedProperty 2604 int mViewFlags; 2605 2606 static class TransformationInfo { 2607 /** 2608 * The transform matrix for the View. This transform is calculated internally 2609 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2610 * is used by default. Do *not* use this variable directly; instead call 2611 * getMatrix(), which will automatically recalculate the matrix if necessary 2612 * to get the correct matrix based on the latest rotation and scale properties. 2613 */ 2614 private final Matrix mMatrix = new Matrix(); 2615 2616 /** 2617 * The transform matrix for the View. This transform is calculated internally 2618 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2619 * is used by default. Do *not* use this variable directly; instead call 2620 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2621 * to get the correct matrix based on the latest rotation and scale properties. 2622 */ 2623 private Matrix mInverseMatrix; 2624 2625 /** 2626 * An internal variable that tracks whether we need to recalculate the 2627 * transform matrix, based on whether the rotation or scaleX/Y properties 2628 * have changed since the matrix was last calculated. 2629 */ 2630 boolean mMatrixDirty = false; 2631 2632 /** 2633 * An internal variable that tracks whether we need to recalculate the 2634 * transform matrix, based on whether the rotation or scaleX/Y properties 2635 * have changed since the matrix was last calculated. 2636 */ 2637 private boolean mInverseMatrixDirty = true; 2638 2639 /** 2640 * A variable that tracks whether we need to recalculate the 2641 * transform matrix, based on whether the rotation or scaleX/Y properties 2642 * have changed since the matrix was last calculated. This variable 2643 * is only valid after a call to updateMatrix() or to a function that 2644 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2645 */ 2646 private boolean mMatrixIsIdentity = true; 2647 2648 /** 2649 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2650 */ 2651 private Camera mCamera = null; 2652 2653 /** 2654 * This matrix is used when computing the matrix for 3D rotations. 2655 */ 2656 private Matrix matrix3D = null; 2657 2658 /** 2659 * These prev values are used to recalculate a centered pivot point when necessary. The 2660 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2661 * set), so thes values are only used then as well. 2662 */ 2663 private int mPrevWidth = -1; 2664 private int mPrevHeight = -1; 2665 2666 /** 2667 * The degrees rotation around the vertical axis through the pivot point. 2668 */ 2669 @ViewDebug.ExportedProperty 2670 float mRotationY = 0f; 2671 2672 /** 2673 * The degrees rotation around the horizontal axis through the pivot point. 2674 */ 2675 @ViewDebug.ExportedProperty 2676 float mRotationX = 0f; 2677 2678 /** 2679 * The degrees rotation around the pivot point. 2680 */ 2681 @ViewDebug.ExportedProperty 2682 float mRotation = 0f; 2683 2684 /** 2685 * The amount of translation of the object away from its left property (post-layout). 2686 */ 2687 @ViewDebug.ExportedProperty 2688 float mTranslationX = 0f; 2689 2690 /** 2691 * The amount of translation of the object away from its top property (post-layout). 2692 */ 2693 @ViewDebug.ExportedProperty 2694 float mTranslationY = 0f; 2695 2696 /** 2697 * The amount of scale in the x direction around the pivot point. A 2698 * value of 1 means no scaling is applied. 2699 */ 2700 @ViewDebug.ExportedProperty 2701 float mScaleX = 1f; 2702 2703 /** 2704 * The amount of scale in the y direction around the pivot point. A 2705 * value of 1 means no scaling is applied. 2706 */ 2707 @ViewDebug.ExportedProperty 2708 float mScaleY = 1f; 2709 2710 /** 2711 * The x location of the point around which the view is rotated and scaled. 2712 */ 2713 @ViewDebug.ExportedProperty 2714 float mPivotX = 0f; 2715 2716 /** 2717 * The y location of the point around which the view is rotated and scaled. 2718 */ 2719 @ViewDebug.ExportedProperty 2720 float mPivotY = 0f; 2721 2722 /** 2723 * The opacity of the View. This is a value from 0 to 1, where 0 means 2724 * completely transparent and 1 means completely opaque. 2725 */ 2726 @ViewDebug.ExportedProperty 2727 float mAlpha = 1f; 2728 } 2729 2730 TransformationInfo mTransformationInfo; 2731 2732 private boolean mLastIsOpaque; 2733 2734 /** 2735 * Convenience value to check for float values that are close enough to zero to be considered 2736 * zero. 2737 */ 2738 private static final float NONZERO_EPSILON = .001f; 2739 2740 /** 2741 * The distance in pixels from the left edge of this view's parent 2742 * to the left edge of this view. 2743 * {@hide} 2744 */ 2745 @ViewDebug.ExportedProperty(category = "layout") 2746 protected int mLeft; 2747 /** 2748 * The distance in pixels from the left edge of this view's parent 2749 * to the right edge of this view. 2750 * {@hide} 2751 */ 2752 @ViewDebug.ExportedProperty(category = "layout") 2753 protected int mRight; 2754 /** 2755 * The distance in pixels from the top edge of this view's parent 2756 * to the top edge of this view. 2757 * {@hide} 2758 */ 2759 @ViewDebug.ExportedProperty(category = "layout") 2760 protected int mTop; 2761 /** 2762 * The distance in pixels from the top edge of this view's parent 2763 * to the bottom edge of this view. 2764 * {@hide} 2765 */ 2766 @ViewDebug.ExportedProperty(category = "layout") 2767 protected int mBottom; 2768 2769 /** 2770 * The offset, in pixels, by which the content of this view is scrolled 2771 * horizontally. 2772 * {@hide} 2773 */ 2774 @ViewDebug.ExportedProperty(category = "scrolling") 2775 protected int mScrollX; 2776 /** 2777 * The offset, in pixels, by which the content of this view is scrolled 2778 * vertically. 2779 * {@hide} 2780 */ 2781 @ViewDebug.ExportedProperty(category = "scrolling") 2782 protected int mScrollY; 2783 2784 /** 2785 * The left padding in pixels, that is the distance in pixels between the 2786 * left edge of this view and the left edge of its content. 2787 * {@hide} 2788 */ 2789 @ViewDebug.ExportedProperty(category = "padding") 2790 protected int mPaddingLeft = 0; 2791 /** 2792 * The right padding in pixels, that is the distance in pixels between the 2793 * right edge of this view and the right edge of its content. 2794 * {@hide} 2795 */ 2796 @ViewDebug.ExportedProperty(category = "padding") 2797 protected int mPaddingRight = 0; 2798 /** 2799 * The top padding in pixels, that is the distance in pixels between the 2800 * top edge of this view and the top edge of its content. 2801 * {@hide} 2802 */ 2803 @ViewDebug.ExportedProperty(category = "padding") 2804 protected int mPaddingTop; 2805 /** 2806 * The bottom padding in pixels, that is the distance in pixels between the 2807 * bottom edge of this view and the bottom edge of its content. 2808 * {@hide} 2809 */ 2810 @ViewDebug.ExportedProperty(category = "padding") 2811 protected int mPaddingBottom; 2812 2813 /** 2814 * The layout insets in pixels, that is the distance in pixels between the 2815 * visible edges of this view its bounds. 2816 */ 2817 private Insets mLayoutInsets; 2818 2819 /** 2820 * Briefly describes the view and is primarily used for accessibility support. 2821 */ 2822 private CharSequence mContentDescription; 2823 2824 /** 2825 * Specifies the id of a view for which this view serves as a label for 2826 * accessibility purposes. 2827 */ 2828 private int mLabelForId = View.NO_ID; 2829 2830 /** 2831 * Predicate for matching labeled view id with its label for 2832 * accessibility purposes. 2833 */ 2834 private MatchLabelForPredicate mMatchLabelForPredicate; 2835 2836 /** 2837 * Predicate for matching a view by its id. 2838 */ 2839 private MatchIdPredicate mMatchIdPredicate; 2840 2841 /** 2842 * Cache the paddingRight set by the user to append to the scrollbar's size. 2843 * 2844 * @hide 2845 */ 2846 @ViewDebug.ExportedProperty(category = "padding") 2847 protected int mUserPaddingRight; 2848 2849 /** 2850 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2851 * 2852 * @hide 2853 */ 2854 @ViewDebug.ExportedProperty(category = "padding") 2855 protected int mUserPaddingBottom; 2856 2857 /** 2858 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2859 * 2860 * @hide 2861 */ 2862 @ViewDebug.ExportedProperty(category = "padding") 2863 protected int mUserPaddingLeft; 2864 2865 /** 2866 * Cache the paddingStart set by the user to append to the scrollbar's size. 2867 * 2868 */ 2869 @ViewDebug.ExportedProperty(category = "padding") 2870 int mUserPaddingStart; 2871 2872 /** 2873 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2874 * 2875 */ 2876 @ViewDebug.ExportedProperty(category = "padding") 2877 int mUserPaddingEnd; 2878 2879 /** 2880 * Cache initial left padding. 2881 * 2882 * @hide 2883 */ 2884 int mUserPaddingLeftInitial = 0; 2885 2886 /** 2887 * Cache initial right padding. 2888 * 2889 * @hide 2890 */ 2891 int mUserPaddingRightInitial = 0; 2892 2893 /** 2894 * Default undefined padding 2895 */ 2896 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 2897 2898 /** 2899 * @hide 2900 */ 2901 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2902 /** 2903 * @hide 2904 */ 2905 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2906 2907 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 2908 private Drawable mBackground; 2909 2910 private int mBackgroundResource; 2911 private boolean mBackgroundSizeChanged; 2912 2913 static class ListenerInfo { 2914 /** 2915 * Listener used to dispatch focus change events. 2916 * This field should be made private, so it is hidden from the SDK. 2917 * {@hide} 2918 */ 2919 protected OnFocusChangeListener mOnFocusChangeListener; 2920 2921 /** 2922 * Listeners for layout change events. 2923 */ 2924 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2925 2926 /** 2927 * Listeners for attach events. 2928 */ 2929 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2930 2931 /** 2932 * Listener used to dispatch click events. 2933 * This field should be made private, so it is hidden from the SDK. 2934 * {@hide} 2935 */ 2936 public OnClickListener mOnClickListener; 2937 2938 /** 2939 * Listener used to dispatch long click events. 2940 * This field should be made private, so it is hidden from the SDK. 2941 * {@hide} 2942 */ 2943 protected OnLongClickListener mOnLongClickListener; 2944 2945 /** 2946 * Listener used to build the context menu. 2947 * This field should be made private, so it is hidden from the SDK. 2948 * {@hide} 2949 */ 2950 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2951 2952 private OnKeyListener mOnKeyListener; 2953 2954 private OnTouchListener mOnTouchListener; 2955 2956 private OnHoverListener mOnHoverListener; 2957 2958 private OnGenericMotionListener mOnGenericMotionListener; 2959 2960 private OnDragListener mOnDragListener; 2961 2962 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2963 } 2964 2965 ListenerInfo mListenerInfo; 2966 2967 /** 2968 * The application environment this view lives in. 2969 * This field should be made private, so it is hidden from the SDK. 2970 * {@hide} 2971 */ 2972 protected Context mContext; 2973 2974 private final Resources mResources; 2975 2976 private ScrollabilityCache mScrollCache; 2977 2978 private int[] mDrawableState = null; 2979 2980 /** 2981 * Set to true when drawing cache is enabled and cannot be created. 2982 * 2983 * @hide 2984 */ 2985 public boolean mCachingFailed; 2986 2987 private Bitmap mDrawingCache; 2988 private Bitmap mUnscaledDrawingCache; 2989 private HardwareLayer mHardwareLayer; 2990 DisplayList mDisplayList; 2991 2992 /** 2993 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2994 * the user may specify which view to go to next. 2995 */ 2996 private int mNextFocusLeftId = View.NO_ID; 2997 2998 /** 2999 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3000 * the user may specify which view to go to next. 3001 */ 3002 private int mNextFocusRightId = View.NO_ID; 3003 3004 /** 3005 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3006 * the user may specify which view to go to next. 3007 */ 3008 private int mNextFocusUpId = View.NO_ID; 3009 3010 /** 3011 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3012 * the user may specify which view to go to next. 3013 */ 3014 private int mNextFocusDownId = View.NO_ID; 3015 3016 /** 3017 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3018 * the user may specify which view to go to next. 3019 */ 3020 int mNextFocusForwardId = View.NO_ID; 3021 3022 private CheckForLongPress mPendingCheckForLongPress; 3023 private CheckForTap mPendingCheckForTap = null; 3024 private PerformClick mPerformClick; 3025 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3026 3027 private UnsetPressedState mUnsetPressedState; 3028 3029 /** 3030 * Whether the long press's action has been invoked. The tap's action is invoked on the 3031 * up event while a long press is invoked as soon as the long press duration is reached, so 3032 * a long press could be performed before the tap is checked, in which case the tap's action 3033 * should not be invoked. 3034 */ 3035 private boolean mHasPerformedLongPress; 3036 3037 /** 3038 * The minimum height of the view. We'll try our best to have the height 3039 * of this view to at least this amount. 3040 */ 3041 @ViewDebug.ExportedProperty(category = "measurement") 3042 private int mMinHeight; 3043 3044 /** 3045 * The minimum width of the view. We'll try our best to have the width 3046 * of this view to at least this amount. 3047 */ 3048 @ViewDebug.ExportedProperty(category = "measurement") 3049 private int mMinWidth; 3050 3051 /** 3052 * The delegate to handle touch events that are physically in this view 3053 * but should be handled by another view. 3054 */ 3055 private TouchDelegate mTouchDelegate = null; 3056 3057 /** 3058 * Solid color to use as a background when creating the drawing cache. Enables 3059 * the cache to use 16 bit bitmaps instead of 32 bit. 3060 */ 3061 private int mDrawingCacheBackgroundColor = 0; 3062 3063 /** 3064 * Special tree observer used when mAttachInfo is null. 3065 */ 3066 private ViewTreeObserver mFloatingTreeObserver; 3067 3068 /** 3069 * Cache the touch slop from the context that created the view. 3070 */ 3071 private int mTouchSlop; 3072 3073 /** 3074 * Object that handles automatic animation of view properties. 3075 */ 3076 private ViewPropertyAnimator mAnimator = null; 3077 3078 /** 3079 * Flag indicating that a drag can cross window boundaries. When 3080 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3081 * with this flag set, all visible applications will be able to participate 3082 * in the drag operation and receive the dragged content. 3083 * 3084 * @hide 3085 */ 3086 public static final int DRAG_FLAG_GLOBAL = 1; 3087 3088 /** 3089 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3090 */ 3091 private float mVerticalScrollFactor; 3092 3093 /** 3094 * Position of the vertical scroll bar. 3095 */ 3096 private int mVerticalScrollbarPosition; 3097 3098 /** 3099 * Position the scroll bar at the default position as determined by the system. 3100 */ 3101 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3102 3103 /** 3104 * Position the scroll bar along the left edge. 3105 */ 3106 public static final int SCROLLBAR_POSITION_LEFT = 1; 3107 3108 /** 3109 * Position the scroll bar along the right edge. 3110 */ 3111 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3112 3113 /** 3114 * Indicates that the view does not have a layer. 3115 * 3116 * @see #getLayerType() 3117 * @see #setLayerType(int, android.graphics.Paint) 3118 * @see #LAYER_TYPE_SOFTWARE 3119 * @see #LAYER_TYPE_HARDWARE 3120 */ 3121 public static final int LAYER_TYPE_NONE = 0; 3122 3123 /** 3124 * <p>Indicates that the view has a software layer. A software layer is backed 3125 * by a bitmap and causes the view to be rendered using Android's software 3126 * rendering pipeline, even if hardware acceleration is enabled.</p> 3127 * 3128 * <p>Software layers have various usages:</p> 3129 * <p>When the application is not using hardware acceleration, a software layer 3130 * is useful to apply a specific color filter and/or blending mode and/or 3131 * translucency to a view and all its children.</p> 3132 * <p>When the application is using hardware acceleration, a software layer 3133 * is useful to render drawing primitives not supported by the hardware 3134 * accelerated pipeline. It can also be used to cache a complex view tree 3135 * into a texture and reduce the complexity of drawing operations. For instance, 3136 * when animating a complex view tree with a translation, a software layer can 3137 * be used to render the view tree only once.</p> 3138 * <p>Software layers should be avoided when the affected view tree updates 3139 * often. Every update will require to re-render the software layer, which can 3140 * potentially be slow (particularly when hardware acceleration is turned on 3141 * since the layer will have to be uploaded into a hardware texture after every 3142 * update.)</p> 3143 * 3144 * @see #getLayerType() 3145 * @see #setLayerType(int, android.graphics.Paint) 3146 * @see #LAYER_TYPE_NONE 3147 * @see #LAYER_TYPE_HARDWARE 3148 */ 3149 public static final int LAYER_TYPE_SOFTWARE = 1; 3150 3151 /** 3152 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3153 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3154 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3155 * rendering pipeline, but only if hardware acceleration is turned on for the 3156 * view hierarchy. When hardware acceleration is turned off, hardware layers 3157 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3158 * 3159 * <p>A hardware layer is useful to apply a specific color filter and/or 3160 * blending mode and/or translucency to a view and all its children.</p> 3161 * <p>A hardware layer can be used to cache a complex view tree into a 3162 * texture and reduce the complexity of drawing operations. For instance, 3163 * when animating a complex view tree with a translation, a hardware layer can 3164 * be used to render the view tree only once.</p> 3165 * <p>A hardware layer can also be used to increase the rendering quality when 3166 * rotation transformations are applied on a view. It can also be used to 3167 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3168 * 3169 * @see #getLayerType() 3170 * @see #setLayerType(int, android.graphics.Paint) 3171 * @see #LAYER_TYPE_NONE 3172 * @see #LAYER_TYPE_SOFTWARE 3173 */ 3174 public static final int LAYER_TYPE_HARDWARE = 2; 3175 3176 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3177 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3178 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3179 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3180 }) 3181 int mLayerType = LAYER_TYPE_NONE; 3182 Paint mLayerPaint; 3183 Rect mLocalDirtyRect; 3184 3185 /** 3186 * Set to true when the view is sending hover accessibility events because it 3187 * is the innermost hovered view. 3188 */ 3189 private boolean mSendingHoverAccessibilityEvents; 3190 3191 /** 3192 * Delegate for injecting accessibility functionality. 3193 */ 3194 AccessibilityDelegate mAccessibilityDelegate; 3195 3196 /** 3197 * Consistency verifier for debugging purposes. 3198 * @hide 3199 */ 3200 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3201 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3202 new InputEventConsistencyVerifier(this, 0) : null; 3203 3204 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3205 3206 /** 3207 * Simple constructor to use when creating a view from code. 3208 * 3209 * @param context The Context the view is running in, through which it can 3210 * access the current theme, resources, etc. 3211 */ 3212 public View(Context context) { 3213 mContext = context; 3214 mResources = context != null ? context.getResources() : null; 3215 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3216 // Set layout and text direction defaults 3217 mPrivateFlags2 = 3218 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3219 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3220 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3221 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3222 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3223 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3224 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3225 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3226 mUserPaddingStart = UNDEFINED_PADDING; 3227 mUserPaddingEnd = UNDEFINED_PADDING; 3228 } 3229 3230 /** 3231 * Constructor that is called when inflating a view from XML. This is called 3232 * when a view is being constructed from an XML file, supplying attributes 3233 * that were specified in the XML file. This version uses a default style of 3234 * 0, so the only attribute values applied are those in the Context's Theme 3235 * and the given AttributeSet. 3236 * 3237 * <p> 3238 * The method onFinishInflate() will be called after all children have been 3239 * added. 3240 * 3241 * @param context The Context the view is running in, through which it can 3242 * access the current theme, resources, etc. 3243 * @param attrs The attributes of the XML tag that is inflating the view. 3244 * @see #View(Context, AttributeSet, int) 3245 */ 3246 public View(Context context, AttributeSet attrs) { 3247 this(context, attrs, 0); 3248 } 3249 3250 /** 3251 * Perform inflation from XML and apply a class-specific base style. This 3252 * constructor of View allows subclasses to use their own base style when 3253 * they are inflating. For example, a Button class's constructor would call 3254 * this version of the super class constructor and supply 3255 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 3256 * the theme's button style to modify all of the base view attributes (in 3257 * particular its background) as well as the Button class's attributes. 3258 * 3259 * @param context The Context the view is running in, through which it can 3260 * access the current theme, resources, etc. 3261 * @param attrs The attributes of the XML tag that is inflating the view. 3262 * @param defStyle The default style to apply to this view. If 0, no style 3263 * will be applied (beyond what is included in the theme). This may 3264 * either be an attribute resource, whose value will be retrieved 3265 * from the current theme, or an explicit style resource. 3266 * @see #View(Context, AttributeSet) 3267 */ 3268 public View(Context context, AttributeSet attrs, int defStyle) { 3269 this(context); 3270 3271 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 3272 defStyle, 0); 3273 3274 Drawable background = null; 3275 3276 int leftPadding = -1; 3277 int topPadding = -1; 3278 int rightPadding = -1; 3279 int bottomPadding = -1; 3280 int startPadding = UNDEFINED_PADDING; 3281 int endPadding = UNDEFINED_PADDING; 3282 3283 int padding = -1; 3284 3285 int viewFlagValues = 0; 3286 int viewFlagMasks = 0; 3287 3288 boolean setScrollContainer = false; 3289 3290 int x = 0; 3291 int y = 0; 3292 3293 float tx = 0; 3294 float ty = 0; 3295 float rotation = 0; 3296 float rotationX = 0; 3297 float rotationY = 0; 3298 float sx = 1f; 3299 float sy = 1f; 3300 boolean transformSet = false; 3301 3302 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3303 int overScrollMode = mOverScrollMode; 3304 boolean initializeScrollbars = false; 3305 3306 boolean leftPaddingDefined = false; 3307 boolean rightPaddingDefined = false; 3308 boolean startPaddingDefined = false; 3309 boolean endPaddingDefined = false; 3310 3311 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3312 3313 final int N = a.getIndexCount(); 3314 for (int i = 0; i < N; i++) { 3315 int attr = a.getIndex(i); 3316 switch (attr) { 3317 case com.android.internal.R.styleable.View_background: 3318 background = a.getDrawable(attr); 3319 break; 3320 case com.android.internal.R.styleable.View_padding: 3321 padding = a.getDimensionPixelSize(attr, -1); 3322 mUserPaddingLeftInitial = padding; 3323 mUserPaddingRightInitial = padding; 3324 leftPaddingDefined = true; 3325 rightPaddingDefined = true; 3326 break; 3327 case com.android.internal.R.styleable.View_paddingLeft: 3328 leftPadding = a.getDimensionPixelSize(attr, -1); 3329 mUserPaddingLeftInitial = leftPadding; 3330 leftPaddingDefined = true; 3331 break; 3332 case com.android.internal.R.styleable.View_paddingTop: 3333 topPadding = a.getDimensionPixelSize(attr, -1); 3334 break; 3335 case com.android.internal.R.styleable.View_paddingRight: 3336 rightPadding = a.getDimensionPixelSize(attr, -1); 3337 mUserPaddingRightInitial = rightPadding; 3338 rightPaddingDefined = true; 3339 break; 3340 case com.android.internal.R.styleable.View_paddingBottom: 3341 bottomPadding = a.getDimensionPixelSize(attr, -1); 3342 break; 3343 case com.android.internal.R.styleable.View_paddingStart: 3344 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3345 startPaddingDefined = true; 3346 break; 3347 case com.android.internal.R.styleable.View_paddingEnd: 3348 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3349 endPaddingDefined = true; 3350 break; 3351 case com.android.internal.R.styleable.View_scrollX: 3352 x = a.getDimensionPixelOffset(attr, 0); 3353 break; 3354 case com.android.internal.R.styleable.View_scrollY: 3355 y = a.getDimensionPixelOffset(attr, 0); 3356 break; 3357 case com.android.internal.R.styleable.View_alpha: 3358 setAlpha(a.getFloat(attr, 1f)); 3359 break; 3360 case com.android.internal.R.styleable.View_transformPivotX: 3361 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3362 break; 3363 case com.android.internal.R.styleable.View_transformPivotY: 3364 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3365 break; 3366 case com.android.internal.R.styleable.View_translationX: 3367 tx = a.getDimensionPixelOffset(attr, 0); 3368 transformSet = true; 3369 break; 3370 case com.android.internal.R.styleable.View_translationY: 3371 ty = a.getDimensionPixelOffset(attr, 0); 3372 transformSet = true; 3373 break; 3374 case com.android.internal.R.styleable.View_rotation: 3375 rotation = a.getFloat(attr, 0); 3376 transformSet = true; 3377 break; 3378 case com.android.internal.R.styleable.View_rotationX: 3379 rotationX = a.getFloat(attr, 0); 3380 transformSet = true; 3381 break; 3382 case com.android.internal.R.styleable.View_rotationY: 3383 rotationY = a.getFloat(attr, 0); 3384 transformSet = true; 3385 break; 3386 case com.android.internal.R.styleable.View_scaleX: 3387 sx = a.getFloat(attr, 1f); 3388 transformSet = true; 3389 break; 3390 case com.android.internal.R.styleable.View_scaleY: 3391 sy = a.getFloat(attr, 1f); 3392 transformSet = true; 3393 break; 3394 case com.android.internal.R.styleable.View_id: 3395 mID = a.getResourceId(attr, NO_ID); 3396 break; 3397 case com.android.internal.R.styleable.View_tag: 3398 mTag = a.getText(attr); 3399 break; 3400 case com.android.internal.R.styleable.View_fitsSystemWindows: 3401 if (a.getBoolean(attr, false)) { 3402 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3403 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3404 } 3405 break; 3406 case com.android.internal.R.styleable.View_focusable: 3407 if (a.getBoolean(attr, false)) { 3408 viewFlagValues |= FOCUSABLE; 3409 viewFlagMasks |= FOCUSABLE_MASK; 3410 } 3411 break; 3412 case com.android.internal.R.styleable.View_focusableInTouchMode: 3413 if (a.getBoolean(attr, false)) { 3414 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3415 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3416 } 3417 break; 3418 case com.android.internal.R.styleable.View_clickable: 3419 if (a.getBoolean(attr, false)) { 3420 viewFlagValues |= CLICKABLE; 3421 viewFlagMasks |= CLICKABLE; 3422 } 3423 break; 3424 case com.android.internal.R.styleable.View_longClickable: 3425 if (a.getBoolean(attr, false)) { 3426 viewFlagValues |= LONG_CLICKABLE; 3427 viewFlagMasks |= LONG_CLICKABLE; 3428 } 3429 break; 3430 case com.android.internal.R.styleable.View_saveEnabled: 3431 if (!a.getBoolean(attr, true)) { 3432 viewFlagValues |= SAVE_DISABLED; 3433 viewFlagMasks |= SAVE_DISABLED_MASK; 3434 } 3435 break; 3436 case com.android.internal.R.styleable.View_duplicateParentState: 3437 if (a.getBoolean(attr, false)) { 3438 viewFlagValues |= DUPLICATE_PARENT_STATE; 3439 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3440 } 3441 break; 3442 case com.android.internal.R.styleable.View_visibility: 3443 final int visibility = a.getInt(attr, 0); 3444 if (visibility != 0) { 3445 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3446 viewFlagMasks |= VISIBILITY_MASK; 3447 } 3448 break; 3449 case com.android.internal.R.styleable.View_layoutDirection: 3450 // Clear any layout direction flags (included resolved bits) already set 3451 mPrivateFlags2 &= 3452 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3453 // Set the layout direction flags depending on the value of the attribute 3454 final int layoutDirection = a.getInt(attr, -1); 3455 final int value = (layoutDirection != -1) ? 3456 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3457 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3458 break; 3459 case com.android.internal.R.styleable.View_drawingCacheQuality: 3460 final int cacheQuality = a.getInt(attr, 0); 3461 if (cacheQuality != 0) { 3462 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3463 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3464 } 3465 break; 3466 case com.android.internal.R.styleable.View_contentDescription: 3467 setContentDescription(a.getString(attr)); 3468 break; 3469 case com.android.internal.R.styleable.View_labelFor: 3470 setLabelFor(a.getResourceId(attr, NO_ID)); 3471 break; 3472 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3473 if (!a.getBoolean(attr, true)) { 3474 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3475 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3476 } 3477 break; 3478 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3479 if (!a.getBoolean(attr, true)) { 3480 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3481 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3482 } 3483 break; 3484 case R.styleable.View_scrollbars: 3485 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3486 if (scrollbars != SCROLLBARS_NONE) { 3487 viewFlagValues |= scrollbars; 3488 viewFlagMasks |= SCROLLBARS_MASK; 3489 initializeScrollbars = true; 3490 } 3491 break; 3492 //noinspection deprecation 3493 case R.styleable.View_fadingEdge: 3494 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3495 // Ignore the attribute starting with ICS 3496 break; 3497 } 3498 // With builds < ICS, fall through and apply fading edges 3499 case R.styleable.View_requiresFadingEdge: 3500 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3501 if (fadingEdge != FADING_EDGE_NONE) { 3502 viewFlagValues |= fadingEdge; 3503 viewFlagMasks |= FADING_EDGE_MASK; 3504 initializeFadingEdge(a); 3505 } 3506 break; 3507 case R.styleable.View_scrollbarStyle: 3508 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3509 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3510 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3511 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3512 } 3513 break; 3514 case R.styleable.View_isScrollContainer: 3515 setScrollContainer = true; 3516 if (a.getBoolean(attr, false)) { 3517 setScrollContainer(true); 3518 } 3519 break; 3520 case com.android.internal.R.styleable.View_keepScreenOn: 3521 if (a.getBoolean(attr, false)) { 3522 viewFlagValues |= KEEP_SCREEN_ON; 3523 viewFlagMasks |= KEEP_SCREEN_ON; 3524 } 3525 break; 3526 case R.styleable.View_filterTouchesWhenObscured: 3527 if (a.getBoolean(attr, false)) { 3528 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3529 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3530 } 3531 break; 3532 case R.styleable.View_nextFocusLeft: 3533 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3534 break; 3535 case R.styleable.View_nextFocusRight: 3536 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3537 break; 3538 case R.styleable.View_nextFocusUp: 3539 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3540 break; 3541 case R.styleable.View_nextFocusDown: 3542 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3543 break; 3544 case R.styleable.View_nextFocusForward: 3545 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3546 break; 3547 case R.styleable.View_minWidth: 3548 mMinWidth = a.getDimensionPixelSize(attr, 0); 3549 break; 3550 case R.styleable.View_minHeight: 3551 mMinHeight = a.getDimensionPixelSize(attr, 0); 3552 break; 3553 case R.styleable.View_onClick: 3554 if (context.isRestricted()) { 3555 throw new IllegalStateException("The android:onClick attribute cannot " 3556 + "be used within a restricted context"); 3557 } 3558 3559 final String handlerName = a.getString(attr); 3560 if (handlerName != null) { 3561 setOnClickListener(new OnClickListener() { 3562 private Method mHandler; 3563 3564 public void onClick(View v) { 3565 if (mHandler == null) { 3566 try { 3567 mHandler = getContext().getClass().getMethod(handlerName, 3568 View.class); 3569 } catch (NoSuchMethodException e) { 3570 int id = getId(); 3571 String idText = id == NO_ID ? "" : " with id '" 3572 + getContext().getResources().getResourceEntryName( 3573 id) + "'"; 3574 throw new IllegalStateException("Could not find a method " + 3575 handlerName + "(View) in the activity " 3576 + getContext().getClass() + " for onClick handler" 3577 + " on view " + View.this.getClass() + idText, e); 3578 } 3579 } 3580 3581 try { 3582 mHandler.invoke(getContext(), View.this); 3583 } catch (IllegalAccessException e) { 3584 throw new IllegalStateException("Could not execute non " 3585 + "public method of the activity", e); 3586 } catch (InvocationTargetException e) { 3587 throw new IllegalStateException("Could not execute " 3588 + "method of the activity", e); 3589 } 3590 } 3591 }); 3592 } 3593 break; 3594 case R.styleable.View_overScrollMode: 3595 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3596 break; 3597 case R.styleable.View_verticalScrollbarPosition: 3598 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3599 break; 3600 case R.styleable.View_layerType: 3601 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3602 break; 3603 case R.styleable.View_textDirection: 3604 // Clear any text direction flag already set 3605 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3606 // Set the text direction flags depending on the value of the attribute 3607 final int textDirection = a.getInt(attr, -1); 3608 if (textDirection != -1) { 3609 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3610 } 3611 break; 3612 case R.styleable.View_textAlignment: 3613 // Clear any text alignment flag already set 3614 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3615 // Set the text alignment flag depending on the value of the attribute 3616 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3617 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 3618 break; 3619 case R.styleable.View_importantForAccessibility: 3620 setImportantForAccessibility(a.getInt(attr, 3621 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 3622 break; 3623 } 3624 } 3625 3626 setOverScrollMode(overScrollMode); 3627 3628 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 3629 // the resolved layout direction). Those cached values will be used later during padding 3630 // resolution. 3631 mUserPaddingStart = startPadding; 3632 mUserPaddingEnd = endPadding; 3633 3634 if (background != null) { 3635 setBackground(background); 3636 } 3637 3638 if (padding >= 0) { 3639 leftPadding = padding; 3640 topPadding = padding; 3641 rightPadding = padding; 3642 bottomPadding = padding; 3643 mUserPaddingLeftInitial = padding; 3644 mUserPaddingRightInitial = padding; 3645 } 3646 3647 if (isRtlCompatibilityMode()) { 3648 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 3649 // left / right padding are used if defined (meaning here nothing to do). If they are not 3650 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 3651 // start / end and resolve them as left / right (layout direction is not taken into account). 3652 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3653 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3654 // defined. 3655 if (!leftPaddingDefined && startPaddingDefined) { 3656 leftPadding = startPadding; 3657 } 3658 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 3659 if (!rightPaddingDefined && endPaddingDefined) { 3660 rightPadding = endPadding; 3661 } 3662 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 3663 } else { 3664 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 3665 // values defined. Otherwise, left /right values are used. 3666 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3667 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3668 // defined. 3669 if (startPaddingDefined) { 3670 mUserPaddingLeftInitial = startPadding; 3671 } else if (leftPaddingDefined) { 3672 mUserPaddingLeftInitial = leftPadding; 3673 } 3674 if (endPaddingDefined) { 3675 mUserPaddingRightInitial = endPadding; 3676 } 3677 else if (rightPaddingDefined) { 3678 mUserPaddingRightInitial = rightPadding; 3679 } 3680 } 3681 3682 internalSetPadding( 3683 mUserPaddingLeftInitial, 3684 topPadding >= 0 ? topPadding : mPaddingTop, 3685 mUserPaddingRightInitial, 3686 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3687 3688 if (viewFlagMasks != 0) { 3689 setFlags(viewFlagValues, viewFlagMasks); 3690 } 3691 3692 if (initializeScrollbars) { 3693 initializeScrollbars(a); 3694 } 3695 3696 a.recycle(); 3697 3698 // Needs to be called after mViewFlags is set 3699 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3700 recomputePadding(); 3701 } 3702 3703 if (x != 0 || y != 0) { 3704 scrollTo(x, y); 3705 } 3706 3707 if (transformSet) { 3708 setTranslationX(tx); 3709 setTranslationY(ty); 3710 setRotation(rotation); 3711 setRotationX(rotationX); 3712 setRotationY(rotationY); 3713 setScaleX(sx); 3714 setScaleY(sy); 3715 } 3716 3717 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3718 setScrollContainer(true); 3719 } 3720 3721 computeOpaqueFlags(); 3722 } 3723 3724 /** 3725 * Non-public constructor for use in testing 3726 */ 3727 View() { 3728 mResources = null; 3729 } 3730 3731 public String toString() { 3732 StringBuilder out = new StringBuilder(128); 3733 out.append(getClass().getName()); 3734 out.append('{'); 3735 out.append(Integer.toHexString(System.identityHashCode(this))); 3736 out.append(' '); 3737 switch (mViewFlags&VISIBILITY_MASK) { 3738 case VISIBLE: out.append('V'); break; 3739 case INVISIBLE: out.append('I'); break; 3740 case GONE: out.append('G'); break; 3741 default: out.append('.'); break; 3742 } 3743 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 3744 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 3745 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 3746 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 3747 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 3748 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 3749 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 3750 out.append(' '); 3751 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 3752 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 3753 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 3754 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 3755 out.append('p'); 3756 } else { 3757 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 3758 } 3759 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 3760 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 3761 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 3762 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 3763 out.append(' '); 3764 out.append(mLeft); 3765 out.append(','); 3766 out.append(mTop); 3767 out.append('-'); 3768 out.append(mRight); 3769 out.append(','); 3770 out.append(mBottom); 3771 final int id = getId(); 3772 if (id != NO_ID) { 3773 out.append(" #"); 3774 out.append(Integer.toHexString(id)); 3775 final Resources r = mResources; 3776 if (id != 0 && r != null) { 3777 try { 3778 String pkgname; 3779 switch (id&0xff000000) { 3780 case 0x7f000000: 3781 pkgname="app"; 3782 break; 3783 case 0x01000000: 3784 pkgname="android"; 3785 break; 3786 default: 3787 pkgname = r.getResourcePackageName(id); 3788 break; 3789 } 3790 String typename = r.getResourceTypeName(id); 3791 String entryname = r.getResourceEntryName(id); 3792 out.append(" "); 3793 out.append(pkgname); 3794 out.append(":"); 3795 out.append(typename); 3796 out.append("/"); 3797 out.append(entryname); 3798 } catch (Resources.NotFoundException e) { 3799 } 3800 } 3801 } 3802 out.append("}"); 3803 return out.toString(); 3804 } 3805 3806 /** 3807 * <p> 3808 * Initializes the fading edges from a given set of styled attributes. This 3809 * method should be called by subclasses that need fading edges and when an 3810 * instance of these subclasses is created programmatically rather than 3811 * being inflated from XML. This method is automatically called when the XML 3812 * is inflated. 3813 * </p> 3814 * 3815 * @param a the styled attributes set to initialize the fading edges from 3816 */ 3817 protected void initializeFadingEdge(TypedArray a) { 3818 initScrollCache(); 3819 3820 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3821 R.styleable.View_fadingEdgeLength, 3822 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3823 } 3824 3825 /** 3826 * Returns the size of the vertical faded edges used to indicate that more 3827 * content in this view is visible. 3828 * 3829 * @return The size in pixels of the vertical faded edge or 0 if vertical 3830 * faded edges are not enabled for this view. 3831 * @attr ref android.R.styleable#View_fadingEdgeLength 3832 */ 3833 public int getVerticalFadingEdgeLength() { 3834 if (isVerticalFadingEdgeEnabled()) { 3835 ScrollabilityCache cache = mScrollCache; 3836 if (cache != null) { 3837 return cache.fadingEdgeLength; 3838 } 3839 } 3840 return 0; 3841 } 3842 3843 /** 3844 * Set the size of the faded edge used to indicate that more content in this 3845 * view is available. Will not change whether the fading edge is enabled; use 3846 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3847 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3848 * for the vertical or horizontal fading edges. 3849 * 3850 * @param length The size in pixels of the faded edge used to indicate that more 3851 * content in this view is visible. 3852 */ 3853 public void setFadingEdgeLength(int length) { 3854 initScrollCache(); 3855 mScrollCache.fadingEdgeLength = length; 3856 } 3857 3858 /** 3859 * Returns the size of the horizontal faded edges used to indicate that more 3860 * content in this view is visible. 3861 * 3862 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3863 * faded edges are not enabled for this view. 3864 * @attr ref android.R.styleable#View_fadingEdgeLength 3865 */ 3866 public int getHorizontalFadingEdgeLength() { 3867 if (isHorizontalFadingEdgeEnabled()) { 3868 ScrollabilityCache cache = mScrollCache; 3869 if (cache != null) { 3870 return cache.fadingEdgeLength; 3871 } 3872 } 3873 return 0; 3874 } 3875 3876 /** 3877 * Returns the width of the vertical scrollbar. 3878 * 3879 * @return The width in pixels of the vertical scrollbar or 0 if there 3880 * is no vertical scrollbar. 3881 */ 3882 public int getVerticalScrollbarWidth() { 3883 ScrollabilityCache cache = mScrollCache; 3884 if (cache != null) { 3885 ScrollBarDrawable scrollBar = cache.scrollBar; 3886 if (scrollBar != null) { 3887 int size = scrollBar.getSize(true); 3888 if (size <= 0) { 3889 size = cache.scrollBarSize; 3890 } 3891 return size; 3892 } 3893 return 0; 3894 } 3895 return 0; 3896 } 3897 3898 /** 3899 * Returns the height of the horizontal scrollbar. 3900 * 3901 * @return The height in pixels of the horizontal scrollbar or 0 if 3902 * there is no horizontal scrollbar. 3903 */ 3904 protected int getHorizontalScrollbarHeight() { 3905 ScrollabilityCache cache = mScrollCache; 3906 if (cache != null) { 3907 ScrollBarDrawable scrollBar = cache.scrollBar; 3908 if (scrollBar != null) { 3909 int size = scrollBar.getSize(false); 3910 if (size <= 0) { 3911 size = cache.scrollBarSize; 3912 } 3913 return size; 3914 } 3915 return 0; 3916 } 3917 return 0; 3918 } 3919 3920 /** 3921 * <p> 3922 * Initializes the scrollbars from a given set of styled attributes. This 3923 * method should be called by subclasses that need scrollbars and when an 3924 * instance of these subclasses is created programmatically rather than 3925 * being inflated from XML. This method is automatically called when the XML 3926 * is inflated. 3927 * </p> 3928 * 3929 * @param a the styled attributes set to initialize the scrollbars from 3930 */ 3931 protected void initializeScrollbars(TypedArray a) { 3932 initScrollCache(); 3933 3934 final ScrollabilityCache scrollabilityCache = mScrollCache; 3935 3936 if (scrollabilityCache.scrollBar == null) { 3937 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3938 } 3939 3940 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3941 3942 if (!fadeScrollbars) { 3943 scrollabilityCache.state = ScrollabilityCache.ON; 3944 } 3945 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3946 3947 3948 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3949 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3950 .getScrollBarFadeDuration()); 3951 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3952 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3953 ViewConfiguration.getScrollDefaultDelay()); 3954 3955 3956 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3957 com.android.internal.R.styleable.View_scrollbarSize, 3958 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3959 3960 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3961 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3962 3963 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3964 if (thumb != null) { 3965 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3966 } 3967 3968 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3969 false); 3970 if (alwaysDraw) { 3971 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3972 } 3973 3974 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3975 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3976 3977 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3978 if (thumb != null) { 3979 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3980 } 3981 3982 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3983 false); 3984 if (alwaysDraw) { 3985 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3986 } 3987 3988 // Apply layout direction to the new Drawables if needed 3989 final int layoutDirection = getLayoutDirection(); 3990 if (track != null) { 3991 track.setLayoutDirection(layoutDirection); 3992 } 3993 if (thumb != null) { 3994 thumb.setLayoutDirection(layoutDirection); 3995 } 3996 3997 // Re-apply user/background padding so that scrollbar(s) get added 3998 resolvePadding(); 3999 } 4000 4001 /** 4002 * <p> 4003 * Initalizes the scrollability cache if necessary. 4004 * </p> 4005 */ 4006 private void initScrollCache() { 4007 if (mScrollCache == null) { 4008 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4009 } 4010 } 4011 4012 private ScrollabilityCache getScrollCache() { 4013 initScrollCache(); 4014 return mScrollCache; 4015 } 4016 4017 /** 4018 * Set the position of the vertical scroll bar. Should be one of 4019 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4020 * {@link #SCROLLBAR_POSITION_RIGHT}. 4021 * 4022 * @param position Where the vertical scroll bar should be positioned. 4023 */ 4024 public void setVerticalScrollbarPosition(int position) { 4025 if (mVerticalScrollbarPosition != position) { 4026 mVerticalScrollbarPosition = position; 4027 computeOpaqueFlags(); 4028 resolvePadding(); 4029 } 4030 } 4031 4032 /** 4033 * @return The position where the vertical scroll bar will show, if applicable. 4034 * @see #setVerticalScrollbarPosition(int) 4035 */ 4036 public int getVerticalScrollbarPosition() { 4037 return mVerticalScrollbarPosition; 4038 } 4039 4040 ListenerInfo getListenerInfo() { 4041 if (mListenerInfo != null) { 4042 return mListenerInfo; 4043 } 4044 mListenerInfo = new ListenerInfo(); 4045 return mListenerInfo; 4046 } 4047 4048 /** 4049 * Register a callback to be invoked when focus of this view changed. 4050 * 4051 * @param l The callback that will run. 4052 */ 4053 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4054 getListenerInfo().mOnFocusChangeListener = l; 4055 } 4056 4057 /** 4058 * Add a listener that will be called when the bounds of the view change due to 4059 * layout processing. 4060 * 4061 * @param listener The listener that will be called when layout bounds change. 4062 */ 4063 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4064 ListenerInfo li = getListenerInfo(); 4065 if (li.mOnLayoutChangeListeners == null) { 4066 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4067 } 4068 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4069 li.mOnLayoutChangeListeners.add(listener); 4070 } 4071 } 4072 4073 /** 4074 * Remove a listener for layout changes. 4075 * 4076 * @param listener The listener for layout bounds change. 4077 */ 4078 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4079 ListenerInfo li = mListenerInfo; 4080 if (li == null || li.mOnLayoutChangeListeners == null) { 4081 return; 4082 } 4083 li.mOnLayoutChangeListeners.remove(listener); 4084 } 4085 4086 /** 4087 * Add a listener for attach state changes. 4088 * 4089 * This listener will be called whenever this view is attached or detached 4090 * from a window. Remove the listener using 4091 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4092 * 4093 * @param listener Listener to attach 4094 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4095 */ 4096 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4097 ListenerInfo li = getListenerInfo(); 4098 if (li.mOnAttachStateChangeListeners == null) { 4099 li.mOnAttachStateChangeListeners 4100 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4101 } 4102 li.mOnAttachStateChangeListeners.add(listener); 4103 } 4104 4105 /** 4106 * Remove a listener for attach state changes. The listener will receive no further 4107 * notification of window attach/detach events. 4108 * 4109 * @param listener Listener to remove 4110 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4111 */ 4112 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4113 ListenerInfo li = mListenerInfo; 4114 if (li == null || li.mOnAttachStateChangeListeners == null) { 4115 return; 4116 } 4117 li.mOnAttachStateChangeListeners.remove(listener); 4118 } 4119 4120 /** 4121 * Returns the focus-change callback registered for this view. 4122 * 4123 * @return The callback, or null if one is not registered. 4124 */ 4125 public OnFocusChangeListener getOnFocusChangeListener() { 4126 ListenerInfo li = mListenerInfo; 4127 return li != null ? li.mOnFocusChangeListener : null; 4128 } 4129 4130 /** 4131 * Register a callback to be invoked when this view is clicked. If this view is not 4132 * clickable, it becomes clickable. 4133 * 4134 * @param l The callback that will run 4135 * 4136 * @see #setClickable(boolean) 4137 */ 4138 public void setOnClickListener(OnClickListener l) { 4139 if (!isClickable()) { 4140 setClickable(true); 4141 } 4142 getListenerInfo().mOnClickListener = l; 4143 } 4144 4145 /** 4146 * Return whether this view has an attached OnClickListener. Returns 4147 * true if there is a listener, false if there is none. 4148 */ 4149 public boolean hasOnClickListeners() { 4150 ListenerInfo li = mListenerInfo; 4151 return (li != null && li.mOnClickListener != null); 4152 } 4153 4154 /** 4155 * Register a callback to be invoked when this view is clicked and held. If this view is not 4156 * long clickable, it becomes long clickable. 4157 * 4158 * @param l The callback that will run 4159 * 4160 * @see #setLongClickable(boolean) 4161 */ 4162 public void setOnLongClickListener(OnLongClickListener l) { 4163 if (!isLongClickable()) { 4164 setLongClickable(true); 4165 } 4166 getListenerInfo().mOnLongClickListener = l; 4167 } 4168 4169 /** 4170 * Register a callback to be invoked when the context menu for this view is 4171 * being built. If this view is not long clickable, it becomes long clickable. 4172 * 4173 * @param l The callback that will run 4174 * 4175 */ 4176 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4177 if (!isLongClickable()) { 4178 setLongClickable(true); 4179 } 4180 getListenerInfo().mOnCreateContextMenuListener = l; 4181 } 4182 4183 /** 4184 * Call this view's OnClickListener, if it is defined. Performs all normal 4185 * actions associated with clicking: reporting accessibility event, playing 4186 * a sound, etc. 4187 * 4188 * @return True there was an assigned OnClickListener that was called, false 4189 * otherwise is returned. 4190 */ 4191 public boolean performClick() { 4192 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4193 4194 ListenerInfo li = mListenerInfo; 4195 if (li != null && li.mOnClickListener != null) { 4196 playSoundEffect(SoundEffectConstants.CLICK); 4197 li.mOnClickListener.onClick(this); 4198 return true; 4199 } 4200 4201 return false; 4202 } 4203 4204 /** 4205 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4206 * this only calls the listener, and does not do any associated clicking 4207 * actions like reporting an accessibility event. 4208 * 4209 * @return True there was an assigned OnClickListener that was called, false 4210 * otherwise is returned. 4211 */ 4212 public boolean callOnClick() { 4213 ListenerInfo li = mListenerInfo; 4214 if (li != null && li.mOnClickListener != null) { 4215 li.mOnClickListener.onClick(this); 4216 return true; 4217 } 4218 return false; 4219 } 4220 4221 /** 4222 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4223 * OnLongClickListener did not consume the event. 4224 * 4225 * @return True if one of the above receivers consumed the event, false otherwise. 4226 */ 4227 public boolean performLongClick() { 4228 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4229 4230 boolean handled = false; 4231 ListenerInfo li = mListenerInfo; 4232 if (li != null && li.mOnLongClickListener != null) { 4233 handled = li.mOnLongClickListener.onLongClick(View.this); 4234 } 4235 if (!handled) { 4236 handled = showContextMenu(); 4237 } 4238 if (handled) { 4239 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4240 } 4241 return handled; 4242 } 4243 4244 /** 4245 * Performs button-related actions during a touch down event. 4246 * 4247 * @param event The event. 4248 * @return True if the down was consumed. 4249 * 4250 * @hide 4251 */ 4252 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4253 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4254 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4255 return true; 4256 } 4257 } 4258 return false; 4259 } 4260 4261 /** 4262 * Bring up the context menu for this view. 4263 * 4264 * @return Whether a context menu was displayed. 4265 */ 4266 public boolean showContextMenu() { 4267 return getParent().showContextMenuForChild(this); 4268 } 4269 4270 /** 4271 * Bring up the context menu for this view, referring to the item under the specified point. 4272 * 4273 * @param x The referenced x coordinate. 4274 * @param y The referenced y coordinate. 4275 * @param metaState The keyboard modifiers that were pressed. 4276 * @return Whether a context menu was displayed. 4277 * 4278 * @hide 4279 */ 4280 public boolean showContextMenu(float x, float y, int metaState) { 4281 return showContextMenu(); 4282 } 4283 4284 /** 4285 * Start an action mode. 4286 * 4287 * @param callback Callback that will control the lifecycle of the action mode 4288 * @return The new action mode if it is started, null otherwise 4289 * 4290 * @see ActionMode 4291 */ 4292 public ActionMode startActionMode(ActionMode.Callback callback) { 4293 ViewParent parent = getParent(); 4294 if (parent == null) return null; 4295 return parent.startActionModeForChild(this, callback); 4296 } 4297 4298 /** 4299 * Register a callback to be invoked when a hardware key is pressed in this view. 4300 * Key presses in software input methods will generally not trigger the methods of 4301 * this listener. 4302 * @param l the key listener to attach to this view 4303 */ 4304 public void setOnKeyListener(OnKeyListener l) { 4305 getListenerInfo().mOnKeyListener = l; 4306 } 4307 4308 /** 4309 * Register a callback to be invoked when a touch event is sent to this view. 4310 * @param l the touch listener to attach to this view 4311 */ 4312 public void setOnTouchListener(OnTouchListener l) { 4313 getListenerInfo().mOnTouchListener = l; 4314 } 4315 4316 /** 4317 * Register a callback to be invoked when a generic motion event is sent to this view. 4318 * @param l the generic motion listener to attach to this view 4319 */ 4320 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4321 getListenerInfo().mOnGenericMotionListener = l; 4322 } 4323 4324 /** 4325 * Register a callback to be invoked when a hover event is sent to this view. 4326 * @param l the hover listener to attach to this view 4327 */ 4328 public void setOnHoverListener(OnHoverListener l) { 4329 getListenerInfo().mOnHoverListener = l; 4330 } 4331 4332 /** 4333 * Register a drag event listener callback object for this View. The parameter is 4334 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4335 * View, the system calls the 4336 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4337 * @param l An implementation of {@link android.view.View.OnDragListener}. 4338 */ 4339 public void setOnDragListener(OnDragListener l) { 4340 getListenerInfo().mOnDragListener = l; 4341 } 4342 4343 /** 4344 * Give this view focus. This will cause 4345 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4346 * 4347 * Note: this does not check whether this {@link View} should get focus, it just 4348 * gives it focus no matter what. It should only be called internally by framework 4349 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4350 * 4351 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4352 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4353 * focus moved when requestFocus() is called. It may not always 4354 * apply, in which case use the default View.FOCUS_DOWN. 4355 * @param previouslyFocusedRect The rectangle of the view that had focus 4356 * prior in this View's coordinate system. 4357 */ 4358 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 4359 if (DBG) { 4360 System.out.println(this + " requestFocus()"); 4361 } 4362 4363 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4364 mPrivateFlags |= PFLAG_FOCUSED; 4365 4366 if (mParent != null) { 4367 mParent.requestChildFocus(this, this); 4368 } 4369 4370 onFocusChanged(true, direction, previouslyFocusedRect); 4371 refreshDrawableState(); 4372 4373 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4374 notifyAccessibilityStateChanged(); 4375 } 4376 } 4377 } 4378 4379 /** 4380 * Request that a rectangle of this view be visible on the screen, 4381 * scrolling if necessary just enough. 4382 * 4383 * <p>A View should call this if it maintains some notion of which part 4384 * of its content is interesting. For example, a text editing view 4385 * should call this when its cursor moves. 4386 * 4387 * @param rectangle The rectangle. 4388 * @return Whether any parent scrolled. 4389 */ 4390 public boolean requestRectangleOnScreen(Rect rectangle) { 4391 return requestRectangleOnScreen(rectangle, false); 4392 } 4393 4394 /** 4395 * Request that a rectangle of this view be visible on the screen, 4396 * scrolling if necessary just enough. 4397 * 4398 * <p>A View should call this if it maintains some notion of which part 4399 * of its content is interesting. For example, a text editing view 4400 * should call this when its cursor moves. 4401 * 4402 * <p>When <code>immediate</code> is set to true, scrolling will not be 4403 * animated. 4404 * 4405 * @param rectangle The rectangle. 4406 * @param immediate True to forbid animated scrolling, false otherwise 4407 * @return Whether any parent scrolled. 4408 */ 4409 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4410 if (mParent == null) { 4411 return false; 4412 } 4413 4414 View child = this; 4415 4416 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4417 position.set(rectangle); 4418 4419 ViewParent parent = mParent; 4420 boolean scrolled = false; 4421 while (parent != null) { 4422 rectangle.set((int) position.left, (int) position.top, 4423 (int) position.right, (int) position.bottom); 4424 4425 scrolled |= parent.requestChildRectangleOnScreen(child, 4426 rectangle, immediate); 4427 4428 if (!child.hasIdentityMatrix()) { 4429 child.getMatrix().mapRect(position); 4430 } 4431 4432 position.offset(child.mLeft, child.mTop); 4433 4434 if (!(parent instanceof View)) { 4435 break; 4436 } 4437 4438 View parentView = (View) parent; 4439 4440 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4441 4442 child = parentView; 4443 parent = child.getParent(); 4444 } 4445 4446 return scrolled; 4447 } 4448 4449 /** 4450 * Called when this view wants to give up focus. If focus is cleared 4451 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4452 * <p> 4453 * <strong>Note:</strong> When a View clears focus the framework is trying 4454 * to give focus to the first focusable View from the top. Hence, if this 4455 * View is the first from the top that can take focus, then all callbacks 4456 * related to clearing focus will be invoked after wich the framework will 4457 * give focus to this view. 4458 * </p> 4459 */ 4460 public void clearFocus() { 4461 if (DBG) { 4462 System.out.println(this + " clearFocus()"); 4463 } 4464 4465 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4466 mPrivateFlags &= ~PFLAG_FOCUSED; 4467 4468 if (mParent != null) { 4469 mParent.clearChildFocus(this); 4470 } 4471 4472 onFocusChanged(false, 0, null); 4473 4474 refreshDrawableState(); 4475 4476 ensureInputFocusOnFirstFocusable(); 4477 4478 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4479 notifyAccessibilityStateChanged(); 4480 } 4481 } 4482 } 4483 4484 void ensureInputFocusOnFirstFocusable() { 4485 View root = getRootView(); 4486 if (root != null) { 4487 root.requestFocus(); 4488 } 4489 } 4490 4491 /** 4492 * Called internally by the view system when a new view is getting focus. 4493 * This is what clears the old focus. 4494 */ 4495 void unFocus() { 4496 if (DBG) { 4497 System.out.println(this + " unFocus()"); 4498 } 4499 4500 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4501 mPrivateFlags &= ~PFLAG_FOCUSED; 4502 4503 onFocusChanged(false, 0, null); 4504 refreshDrawableState(); 4505 4506 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4507 notifyAccessibilityStateChanged(); 4508 } 4509 } 4510 } 4511 4512 /** 4513 * Returns true if this view has focus iteself, or is the ancestor of the 4514 * view that has focus. 4515 * 4516 * @return True if this view has or contains focus, false otherwise. 4517 */ 4518 @ViewDebug.ExportedProperty(category = "focus") 4519 public boolean hasFocus() { 4520 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4521 } 4522 4523 /** 4524 * Returns true if this view is focusable or if it contains a reachable View 4525 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4526 * is a View whose parents do not block descendants focus. 4527 * 4528 * Only {@link #VISIBLE} views are considered focusable. 4529 * 4530 * @return True if the view is focusable or if the view contains a focusable 4531 * View, false otherwise. 4532 * 4533 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4534 */ 4535 public boolean hasFocusable() { 4536 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4537 } 4538 4539 /** 4540 * Called by the view system when the focus state of this view changes. 4541 * When the focus change event is caused by directional navigation, direction 4542 * and previouslyFocusedRect provide insight into where the focus is coming from. 4543 * When overriding, be sure to call up through to the super class so that 4544 * the standard focus handling will occur. 4545 * 4546 * @param gainFocus True if the View has focus; false otherwise. 4547 * @param direction The direction focus has moved when requestFocus() 4548 * is called to give this view focus. Values are 4549 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4550 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4551 * It may not always apply, in which case use the default. 4552 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4553 * system, of the previously focused view. If applicable, this will be 4554 * passed in as finer grained information about where the focus is coming 4555 * from (in addition to direction). Will be <code>null</code> otherwise. 4556 */ 4557 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 4558 if (gainFocus) { 4559 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4560 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4561 } 4562 } 4563 4564 InputMethodManager imm = InputMethodManager.peekInstance(); 4565 if (!gainFocus) { 4566 if (isPressed()) { 4567 setPressed(false); 4568 } 4569 if (imm != null && mAttachInfo != null 4570 && mAttachInfo.mHasWindowFocus) { 4571 imm.focusOut(this); 4572 } 4573 onFocusLost(); 4574 } else if (imm != null && mAttachInfo != null 4575 && mAttachInfo.mHasWindowFocus) { 4576 imm.focusIn(this); 4577 } 4578 4579 invalidate(true); 4580 ListenerInfo li = mListenerInfo; 4581 if (li != null && li.mOnFocusChangeListener != null) { 4582 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 4583 } 4584 4585 if (mAttachInfo != null) { 4586 mAttachInfo.mKeyDispatchState.reset(this); 4587 } 4588 } 4589 4590 /** 4591 * Sends an accessibility event of the given type. If accessibility is 4592 * not enabled this method has no effect. The default implementation calls 4593 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 4594 * to populate information about the event source (this View), then calls 4595 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 4596 * populate the text content of the event source including its descendants, 4597 * and last calls 4598 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 4599 * on its parent to resuest sending of the event to interested parties. 4600 * <p> 4601 * If an {@link AccessibilityDelegate} has been specified via calling 4602 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4603 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 4604 * responsible for handling this call. 4605 * </p> 4606 * 4607 * @param eventType The type of the event to send, as defined by several types from 4608 * {@link android.view.accessibility.AccessibilityEvent}, such as 4609 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 4610 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 4611 * 4612 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4613 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4614 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 4615 * @see AccessibilityDelegate 4616 */ 4617 public void sendAccessibilityEvent(int eventType) { 4618 if (mAccessibilityDelegate != null) { 4619 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 4620 } else { 4621 sendAccessibilityEventInternal(eventType); 4622 } 4623 } 4624 4625 /** 4626 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 4627 * {@link AccessibilityEvent} to make an announcement which is related to some 4628 * sort of a context change for which none of the events representing UI transitions 4629 * is a good fit. For example, announcing a new page in a book. If accessibility 4630 * is not enabled this method does nothing. 4631 * 4632 * @param text The announcement text. 4633 */ 4634 public void announceForAccessibility(CharSequence text) { 4635 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 4636 AccessibilityEvent event = AccessibilityEvent.obtain( 4637 AccessibilityEvent.TYPE_ANNOUNCEMENT); 4638 onInitializeAccessibilityEvent(event); 4639 event.getText().add(text); 4640 event.setContentDescription(null); 4641 mParent.requestSendAccessibilityEvent(this, event); 4642 } 4643 } 4644 4645 /** 4646 * @see #sendAccessibilityEvent(int) 4647 * 4648 * Note: Called from the default {@link AccessibilityDelegate}. 4649 */ 4650 void sendAccessibilityEventInternal(int eventType) { 4651 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4652 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 4653 } 4654 } 4655 4656 /** 4657 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 4658 * takes as an argument an empty {@link AccessibilityEvent} and does not 4659 * perform a check whether accessibility is enabled. 4660 * <p> 4661 * If an {@link AccessibilityDelegate} has been specified via calling 4662 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4663 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 4664 * is responsible for handling this call. 4665 * </p> 4666 * 4667 * @param event The event to send. 4668 * 4669 * @see #sendAccessibilityEvent(int) 4670 */ 4671 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 4672 if (mAccessibilityDelegate != null) { 4673 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 4674 } else { 4675 sendAccessibilityEventUncheckedInternal(event); 4676 } 4677 } 4678 4679 /** 4680 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 4681 * 4682 * Note: Called from the default {@link AccessibilityDelegate}. 4683 */ 4684 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 4685 if (!isShown()) { 4686 return; 4687 } 4688 onInitializeAccessibilityEvent(event); 4689 // Only a subset of accessibility events populates text content. 4690 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4691 dispatchPopulateAccessibilityEvent(event); 4692 } 4693 // In the beginning we called #isShown(), so we know that getParent() is not null. 4694 getParent().requestSendAccessibilityEvent(this, event); 4695 } 4696 4697 /** 4698 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4699 * to its children for adding their text content to the event. Note that the 4700 * event text is populated in a separate dispatch path since we add to the 4701 * event not only the text of the source but also the text of all its descendants. 4702 * A typical implementation will call 4703 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4704 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4705 * on each child. Override this method if custom population of the event text 4706 * content is required. 4707 * <p> 4708 * If an {@link AccessibilityDelegate} has been specified via calling 4709 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4710 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4711 * is responsible for handling this call. 4712 * </p> 4713 * <p> 4714 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4715 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4716 * </p> 4717 * 4718 * @param event The event. 4719 * 4720 * @return True if the event population was completed. 4721 */ 4722 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4723 if (mAccessibilityDelegate != null) { 4724 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4725 } else { 4726 return dispatchPopulateAccessibilityEventInternal(event); 4727 } 4728 } 4729 4730 /** 4731 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4732 * 4733 * Note: Called from the default {@link AccessibilityDelegate}. 4734 */ 4735 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4736 onPopulateAccessibilityEvent(event); 4737 return false; 4738 } 4739 4740 /** 4741 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4742 * giving a chance to this View to populate the accessibility event with its 4743 * text content. While this method is free to modify event 4744 * attributes other than text content, doing so should normally be performed in 4745 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4746 * <p> 4747 * Example: Adding formatted date string to an accessibility event in addition 4748 * to the text added by the super implementation: 4749 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4750 * super.onPopulateAccessibilityEvent(event); 4751 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4752 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4753 * mCurrentDate.getTimeInMillis(), flags); 4754 * event.getText().add(selectedDateUtterance); 4755 * }</pre> 4756 * <p> 4757 * If an {@link AccessibilityDelegate} has been specified via calling 4758 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4759 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 4760 * is responsible for handling this call. 4761 * </p> 4762 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4763 * information to the event, in case the default implementation has basic information to add. 4764 * </p> 4765 * 4766 * @param event The accessibility event which to populate. 4767 * 4768 * @see #sendAccessibilityEvent(int) 4769 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4770 */ 4771 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4772 if (mAccessibilityDelegate != null) { 4773 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 4774 } else { 4775 onPopulateAccessibilityEventInternal(event); 4776 } 4777 } 4778 4779 /** 4780 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 4781 * 4782 * Note: Called from the default {@link AccessibilityDelegate}. 4783 */ 4784 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4785 4786 } 4787 4788 /** 4789 * Initializes an {@link AccessibilityEvent} with information about 4790 * this View which is the event source. In other words, the source of 4791 * an accessibility event is the view whose state change triggered firing 4792 * the event. 4793 * <p> 4794 * Example: Setting the password property of an event in addition 4795 * to properties set by the super implementation: 4796 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4797 * super.onInitializeAccessibilityEvent(event); 4798 * event.setPassword(true); 4799 * }</pre> 4800 * <p> 4801 * If an {@link AccessibilityDelegate} has been specified via calling 4802 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4803 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4804 * is responsible for handling this call. 4805 * </p> 4806 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4807 * information to the event, in case the default implementation has basic information to add. 4808 * </p> 4809 * @param event The event to initialize. 4810 * 4811 * @see #sendAccessibilityEvent(int) 4812 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4813 */ 4814 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4815 if (mAccessibilityDelegate != null) { 4816 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 4817 } else { 4818 onInitializeAccessibilityEventInternal(event); 4819 } 4820 } 4821 4822 /** 4823 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4824 * 4825 * Note: Called from the default {@link AccessibilityDelegate}. 4826 */ 4827 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 4828 event.setSource(this); 4829 event.setClassName(View.class.getName()); 4830 event.setPackageName(getContext().getPackageName()); 4831 event.setEnabled(isEnabled()); 4832 event.setContentDescription(mContentDescription); 4833 4834 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 4835 ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList; 4836 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 4837 FOCUSABLES_ALL); 4838 event.setItemCount(focusablesTempList.size()); 4839 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4840 focusablesTempList.clear(); 4841 } 4842 } 4843 4844 /** 4845 * Returns an {@link AccessibilityNodeInfo} representing this view from the 4846 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 4847 * This method is responsible for obtaining an accessibility node info from a 4848 * pool of reusable instances and calling 4849 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 4850 * initialize the former. 4851 * <p> 4852 * Note: The client is responsible for recycling the obtained instance by calling 4853 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4854 * </p> 4855 * 4856 * @return A populated {@link AccessibilityNodeInfo}. 4857 * 4858 * @see AccessibilityNodeInfo 4859 */ 4860 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4861 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 4862 if (provider != null) { 4863 return provider.createAccessibilityNodeInfo(View.NO_ID); 4864 } else { 4865 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4866 onInitializeAccessibilityNodeInfo(info); 4867 return info; 4868 } 4869 } 4870 4871 /** 4872 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4873 * The base implementation sets: 4874 * <ul> 4875 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4876 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4877 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4878 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4879 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4880 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4881 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4882 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4883 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4884 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4885 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4886 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4887 * </ul> 4888 * <p> 4889 * Subclasses should override this method, call the super implementation, 4890 * and set additional attributes. 4891 * </p> 4892 * <p> 4893 * If an {@link AccessibilityDelegate} has been specified via calling 4894 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4895 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 4896 * is responsible for handling this call. 4897 * </p> 4898 * 4899 * @param info The instance to initialize. 4900 */ 4901 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 4902 if (mAccessibilityDelegate != null) { 4903 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 4904 } else { 4905 onInitializeAccessibilityNodeInfoInternal(info); 4906 } 4907 } 4908 4909 /** 4910 * Gets the location of this view in screen coordintates. 4911 * 4912 * @param outRect The output location 4913 */ 4914 private void getBoundsOnScreen(Rect outRect) { 4915 if (mAttachInfo == null) { 4916 return; 4917 } 4918 4919 RectF position = mAttachInfo.mTmpTransformRect; 4920 position.set(0, 0, mRight - mLeft, mBottom - mTop); 4921 4922 if (!hasIdentityMatrix()) { 4923 getMatrix().mapRect(position); 4924 } 4925 4926 position.offset(mLeft, mTop); 4927 4928 ViewParent parent = mParent; 4929 while (parent instanceof View) { 4930 View parentView = (View) parent; 4931 4932 position.offset(-parentView.mScrollX, -parentView.mScrollY); 4933 4934 if (!parentView.hasIdentityMatrix()) { 4935 parentView.getMatrix().mapRect(position); 4936 } 4937 4938 position.offset(parentView.mLeft, parentView.mTop); 4939 4940 parent = parentView.mParent; 4941 } 4942 4943 if (parent instanceof ViewRootImpl) { 4944 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 4945 position.offset(0, -viewRootImpl.mCurScrollY); 4946 } 4947 4948 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 4949 4950 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 4951 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 4952 } 4953 4954 /** 4955 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 4956 * 4957 * Note: Called from the default {@link AccessibilityDelegate}. 4958 */ 4959 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 4960 Rect bounds = mAttachInfo.mTmpInvalRect; 4961 4962 getDrawingRect(bounds); 4963 info.setBoundsInParent(bounds); 4964 4965 getBoundsOnScreen(bounds); 4966 info.setBoundsInScreen(bounds); 4967 4968 ViewParent parent = getParentForAccessibility(); 4969 if (parent instanceof View) { 4970 info.setParent((View) parent); 4971 } 4972 4973 if (mID != View.NO_ID) { 4974 View rootView = getRootView(); 4975 if (rootView == null) { 4976 rootView = this; 4977 } 4978 View label = rootView.findLabelForView(this, mID); 4979 if (label != null) { 4980 info.setLabeledBy(label); 4981 } 4982 } 4983 4984 if (mLabelForId != View.NO_ID) { 4985 View rootView = getRootView(); 4986 if (rootView == null) { 4987 rootView = this; 4988 } 4989 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 4990 if (labeled != null) { 4991 info.setLabelFor(labeled); 4992 } 4993 } 4994 4995 info.setVisibleToUser(isVisibleToUser()); 4996 4997 info.setPackageName(mContext.getPackageName()); 4998 info.setClassName(View.class.getName()); 4999 info.setContentDescription(getContentDescription()); 5000 5001 info.setEnabled(isEnabled()); 5002 info.setClickable(isClickable()); 5003 info.setFocusable(isFocusable()); 5004 info.setFocused(isFocused()); 5005 info.setAccessibilityFocused(isAccessibilityFocused()); 5006 info.setSelected(isSelected()); 5007 info.setLongClickable(isLongClickable()); 5008 5009 // TODO: These make sense only if we are in an AdapterView but all 5010 // views can be selected. Maybe from accessibility perspective 5011 // we should report as selectable view in an AdapterView. 5012 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5013 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5014 5015 if (isFocusable()) { 5016 if (isFocused()) { 5017 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5018 } else { 5019 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5020 } 5021 } 5022 5023 if (!isAccessibilityFocused()) { 5024 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5025 } else { 5026 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5027 } 5028 5029 if (isClickable() && isEnabled()) { 5030 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5031 } 5032 5033 if (isLongClickable() && isEnabled()) { 5034 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5035 } 5036 5037 if (mContentDescription != null && mContentDescription.length() > 0) { 5038 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5039 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5040 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5041 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5042 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5043 } 5044 } 5045 5046 private View findLabelForView(View view, int labeledId) { 5047 if (mMatchLabelForPredicate == null) { 5048 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5049 } 5050 mMatchLabelForPredicate.mLabeledId = labeledId; 5051 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5052 } 5053 5054 /** 5055 * Computes whether this view is visible to the user. Such a view is 5056 * attached, visible, all its predecessors are visible, it is not clipped 5057 * entirely by its predecessors, and has an alpha greater than zero. 5058 * 5059 * @return Whether the view is visible on the screen. 5060 * 5061 * @hide 5062 */ 5063 protected boolean isVisibleToUser() { 5064 return isVisibleToUser(null); 5065 } 5066 5067 /** 5068 * Computes whether the given portion of this view is visible to the user. 5069 * Such a view is attached, visible, all its predecessors are visible, 5070 * has an alpha greater than zero, and the specified portion is not 5071 * clipped entirely by its predecessors. 5072 * 5073 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5074 * <code>null</code>, and the entire view will be tested in this case. 5075 * When <code>true</code> is returned by the function, the actual visible 5076 * region will be stored in this parameter; that is, if boundInView is fully 5077 * contained within the view, no modification will be made, otherwise regions 5078 * outside of the visible area of the view will be clipped. 5079 * 5080 * @return Whether the specified portion of the view is visible on the screen. 5081 * 5082 * @hide 5083 */ 5084 protected boolean isVisibleToUser(Rect boundInView) { 5085 if (mAttachInfo != null) { 5086 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5087 Point offset = mAttachInfo.mPoint; 5088 // The first two checks are made also made by isShown() which 5089 // however traverses the tree up to the parent to catch that. 5090 // Therefore, we do some fail fast check to minimize the up 5091 // tree traversal. 5092 boolean isVisible = mAttachInfo.mWindowVisibility == View.VISIBLE 5093 && getAlpha() > 0 5094 && isShown() 5095 && getGlobalVisibleRect(visibleRect, offset); 5096 if (isVisible && boundInView != null) { 5097 visibleRect.offset(-offset.x, -offset.y); 5098 // isVisible is always true here, use a simple assignment 5099 isVisible = boundInView.intersect(visibleRect); 5100 } 5101 return isVisible; 5102 } 5103 5104 return false; 5105 } 5106 5107 /** 5108 * Returns the delegate for implementing accessibility support via 5109 * composition. For more details see {@link AccessibilityDelegate}. 5110 * 5111 * @return The delegate, or null if none set. 5112 * 5113 * @hide 5114 */ 5115 public AccessibilityDelegate getAccessibilityDelegate() { 5116 return mAccessibilityDelegate; 5117 } 5118 5119 /** 5120 * Sets a delegate for implementing accessibility support via composition as 5121 * opposed to inheritance. The delegate's primary use is for implementing 5122 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5123 * 5124 * @param delegate The delegate instance. 5125 * 5126 * @see AccessibilityDelegate 5127 */ 5128 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5129 mAccessibilityDelegate = delegate; 5130 } 5131 5132 /** 5133 * Gets the provider for managing a virtual view hierarchy rooted at this View 5134 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5135 * that explore the window content. 5136 * <p> 5137 * If this method returns an instance, this instance is responsible for managing 5138 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5139 * View including the one representing the View itself. Similarly the returned 5140 * instance is responsible for performing accessibility actions on any virtual 5141 * view or the root view itself. 5142 * </p> 5143 * <p> 5144 * If an {@link AccessibilityDelegate} has been specified via calling 5145 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5146 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5147 * is responsible for handling this call. 5148 * </p> 5149 * 5150 * @return The provider. 5151 * 5152 * @see AccessibilityNodeProvider 5153 */ 5154 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5155 if (mAccessibilityDelegate != null) { 5156 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5157 } else { 5158 return null; 5159 } 5160 } 5161 5162 /** 5163 * Gets the unique identifier of this view on the screen for accessibility purposes. 5164 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5165 * 5166 * @return The view accessibility id. 5167 * 5168 * @hide 5169 */ 5170 public int getAccessibilityViewId() { 5171 if (mAccessibilityViewId == NO_ID) { 5172 mAccessibilityViewId = sNextAccessibilityViewId++; 5173 } 5174 return mAccessibilityViewId; 5175 } 5176 5177 /** 5178 * Gets the unique identifier of the window in which this View reseides. 5179 * 5180 * @return The window accessibility id. 5181 * 5182 * @hide 5183 */ 5184 public int getAccessibilityWindowId() { 5185 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 5186 } 5187 5188 /** 5189 * Gets the {@link View} description. It briefly describes the view and is 5190 * primarily used for accessibility support. Set this property to enable 5191 * better accessibility support for your application. This is especially 5192 * true for views that do not have textual representation (For example, 5193 * ImageButton). 5194 * 5195 * @return The content description. 5196 * 5197 * @attr ref android.R.styleable#View_contentDescription 5198 */ 5199 @ViewDebug.ExportedProperty(category = "accessibility") 5200 public CharSequence getContentDescription() { 5201 return mContentDescription; 5202 } 5203 5204 /** 5205 * Sets the {@link View} description. It briefly describes the view and is 5206 * primarily used for accessibility support. Set this property to enable 5207 * better accessibility support for your application. This is especially 5208 * true for views that do not have textual representation (For example, 5209 * ImageButton). 5210 * 5211 * @param contentDescription The content description. 5212 * 5213 * @attr ref android.R.styleable#View_contentDescription 5214 */ 5215 @RemotableViewMethod 5216 public void setContentDescription(CharSequence contentDescription) { 5217 mContentDescription = contentDescription; 5218 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5219 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5220 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5221 } 5222 } 5223 5224 /** 5225 * Gets the id of a view for which this view serves as a label for 5226 * accessibility purposes. 5227 * 5228 * @return The labeled view id. 5229 */ 5230 @ViewDebug.ExportedProperty(category = "accessibility") 5231 public int getLabelFor() { 5232 return mLabelForId; 5233 } 5234 5235 /** 5236 * Sets the id of a view for which this view serves as a label for 5237 * accessibility purposes. 5238 * 5239 * @param id The labeled view id. 5240 */ 5241 @RemotableViewMethod 5242 public void setLabelFor(int id) { 5243 mLabelForId = id; 5244 if (mLabelForId != View.NO_ID 5245 && mID == View.NO_ID) { 5246 mID = generateViewId(); 5247 } 5248 } 5249 5250 /** 5251 * Invoked whenever this view loses focus, either by losing window focus or by losing 5252 * focus within its window. This method can be used to clear any state tied to the 5253 * focus. For instance, if a button is held pressed with the trackball and the window 5254 * loses focus, this method can be used to cancel the press. 5255 * 5256 * Subclasses of View overriding this method should always call super.onFocusLost(). 5257 * 5258 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5259 * @see #onWindowFocusChanged(boolean) 5260 * 5261 * @hide pending API council approval 5262 */ 5263 protected void onFocusLost() { 5264 resetPressedState(); 5265 } 5266 5267 private void resetPressedState() { 5268 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5269 return; 5270 } 5271 5272 if (isPressed()) { 5273 setPressed(false); 5274 5275 if (!mHasPerformedLongPress) { 5276 removeLongPressCallback(); 5277 } 5278 } 5279 } 5280 5281 /** 5282 * Returns true if this view has focus 5283 * 5284 * @return True if this view has focus, false otherwise. 5285 */ 5286 @ViewDebug.ExportedProperty(category = "focus") 5287 public boolean isFocused() { 5288 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5289 } 5290 5291 /** 5292 * Find the view in the hierarchy rooted at this view that currently has 5293 * focus. 5294 * 5295 * @return The view that currently has focus, or null if no focused view can 5296 * be found. 5297 */ 5298 public View findFocus() { 5299 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5300 } 5301 5302 /** 5303 * Indicates whether this view is one of the set of scrollable containers in 5304 * its window. 5305 * 5306 * @return whether this view is one of the set of scrollable containers in 5307 * its window 5308 * 5309 * @attr ref android.R.styleable#View_isScrollContainer 5310 */ 5311 public boolean isScrollContainer() { 5312 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5313 } 5314 5315 /** 5316 * Change whether this view is one of the set of scrollable containers in 5317 * its window. This will be used to determine whether the window can 5318 * resize or must pan when a soft input area is open -- scrollable 5319 * containers allow the window to use resize mode since the container 5320 * will appropriately shrink. 5321 * 5322 * @attr ref android.R.styleable#View_isScrollContainer 5323 */ 5324 public void setScrollContainer(boolean isScrollContainer) { 5325 if (isScrollContainer) { 5326 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5327 mAttachInfo.mScrollContainers.add(this); 5328 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5329 } 5330 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5331 } else { 5332 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5333 mAttachInfo.mScrollContainers.remove(this); 5334 } 5335 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5336 } 5337 } 5338 5339 /** 5340 * Returns the quality of the drawing cache. 5341 * 5342 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5343 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5344 * 5345 * @see #setDrawingCacheQuality(int) 5346 * @see #setDrawingCacheEnabled(boolean) 5347 * @see #isDrawingCacheEnabled() 5348 * 5349 * @attr ref android.R.styleable#View_drawingCacheQuality 5350 */ 5351 public int getDrawingCacheQuality() { 5352 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5353 } 5354 5355 /** 5356 * Set the drawing cache quality of this view. This value is used only when the 5357 * drawing cache is enabled 5358 * 5359 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5360 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5361 * 5362 * @see #getDrawingCacheQuality() 5363 * @see #setDrawingCacheEnabled(boolean) 5364 * @see #isDrawingCacheEnabled() 5365 * 5366 * @attr ref android.R.styleable#View_drawingCacheQuality 5367 */ 5368 public void setDrawingCacheQuality(int quality) { 5369 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5370 } 5371 5372 /** 5373 * Returns whether the screen should remain on, corresponding to the current 5374 * value of {@link #KEEP_SCREEN_ON}. 5375 * 5376 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5377 * 5378 * @see #setKeepScreenOn(boolean) 5379 * 5380 * @attr ref android.R.styleable#View_keepScreenOn 5381 */ 5382 public boolean getKeepScreenOn() { 5383 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5384 } 5385 5386 /** 5387 * Controls whether the screen should remain on, modifying the 5388 * value of {@link #KEEP_SCREEN_ON}. 5389 * 5390 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5391 * 5392 * @see #getKeepScreenOn() 5393 * 5394 * @attr ref android.R.styleable#View_keepScreenOn 5395 */ 5396 public void setKeepScreenOn(boolean keepScreenOn) { 5397 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5398 } 5399 5400 /** 5401 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5402 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5403 * 5404 * @attr ref android.R.styleable#View_nextFocusLeft 5405 */ 5406 public int getNextFocusLeftId() { 5407 return mNextFocusLeftId; 5408 } 5409 5410 /** 5411 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5412 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5413 * decide automatically. 5414 * 5415 * @attr ref android.R.styleable#View_nextFocusLeft 5416 */ 5417 public void setNextFocusLeftId(int nextFocusLeftId) { 5418 mNextFocusLeftId = nextFocusLeftId; 5419 } 5420 5421 /** 5422 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5423 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5424 * 5425 * @attr ref android.R.styleable#View_nextFocusRight 5426 */ 5427 public int getNextFocusRightId() { 5428 return mNextFocusRightId; 5429 } 5430 5431 /** 5432 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5433 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5434 * decide automatically. 5435 * 5436 * @attr ref android.R.styleable#View_nextFocusRight 5437 */ 5438 public void setNextFocusRightId(int nextFocusRightId) { 5439 mNextFocusRightId = nextFocusRightId; 5440 } 5441 5442 /** 5443 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5444 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5445 * 5446 * @attr ref android.R.styleable#View_nextFocusUp 5447 */ 5448 public int getNextFocusUpId() { 5449 return mNextFocusUpId; 5450 } 5451 5452 /** 5453 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5454 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5455 * decide automatically. 5456 * 5457 * @attr ref android.R.styleable#View_nextFocusUp 5458 */ 5459 public void setNextFocusUpId(int nextFocusUpId) { 5460 mNextFocusUpId = nextFocusUpId; 5461 } 5462 5463 /** 5464 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5465 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5466 * 5467 * @attr ref android.R.styleable#View_nextFocusDown 5468 */ 5469 public int getNextFocusDownId() { 5470 return mNextFocusDownId; 5471 } 5472 5473 /** 5474 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5475 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5476 * decide automatically. 5477 * 5478 * @attr ref android.R.styleable#View_nextFocusDown 5479 */ 5480 public void setNextFocusDownId(int nextFocusDownId) { 5481 mNextFocusDownId = nextFocusDownId; 5482 } 5483 5484 /** 5485 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5486 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5487 * 5488 * @attr ref android.R.styleable#View_nextFocusForward 5489 */ 5490 public int getNextFocusForwardId() { 5491 return mNextFocusForwardId; 5492 } 5493 5494 /** 5495 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5496 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 5497 * decide automatically. 5498 * 5499 * @attr ref android.R.styleable#View_nextFocusForward 5500 */ 5501 public void setNextFocusForwardId(int nextFocusForwardId) { 5502 mNextFocusForwardId = nextFocusForwardId; 5503 } 5504 5505 /** 5506 * Returns the visibility of this view and all of its ancestors 5507 * 5508 * @return True if this view and all of its ancestors are {@link #VISIBLE} 5509 */ 5510 public boolean isShown() { 5511 View current = this; 5512 //noinspection ConstantConditions 5513 do { 5514 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5515 return false; 5516 } 5517 ViewParent parent = current.mParent; 5518 if (parent == null) { 5519 return false; // We are not attached to the view root 5520 } 5521 if (!(parent instanceof View)) { 5522 return true; 5523 } 5524 current = (View) parent; 5525 } while (current != null); 5526 5527 return false; 5528 } 5529 5530 /** 5531 * Called by the view hierarchy when the content insets for a window have 5532 * changed, to allow it to adjust its content to fit within those windows. 5533 * The content insets tell you the space that the status bar, input method, 5534 * and other system windows infringe on the application's window. 5535 * 5536 * <p>You do not normally need to deal with this function, since the default 5537 * window decoration given to applications takes care of applying it to the 5538 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 5539 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 5540 * and your content can be placed under those system elements. You can then 5541 * use this method within your view hierarchy if you have parts of your UI 5542 * which you would like to ensure are not being covered. 5543 * 5544 * <p>The default implementation of this method simply applies the content 5545 * inset's to the view's padding, consuming that content (modifying the 5546 * insets to be 0), and returning true. This behavior is off by default, but can 5547 * be enabled through {@link #setFitsSystemWindows(boolean)}. 5548 * 5549 * <p>This function's traversal down the hierarchy is depth-first. The same content 5550 * insets object is propagated down the hierarchy, so any changes made to it will 5551 * be seen by all following views (including potentially ones above in 5552 * the hierarchy since this is a depth-first traversal). The first view 5553 * that returns true will abort the entire traversal. 5554 * 5555 * <p>The default implementation works well for a situation where it is 5556 * used with a container that covers the entire window, allowing it to 5557 * apply the appropriate insets to its content on all edges. If you need 5558 * a more complicated layout (such as two different views fitting system 5559 * windows, one on the top of the window, and one on the bottom), 5560 * you can override the method and handle the insets however you would like. 5561 * Note that the insets provided by the framework are always relative to the 5562 * far edges of the window, not accounting for the location of the called view 5563 * within that window. (In fact when this method is called you do not yet know 5564 * where the layout will place the view, as it is done before layout happens.) 5565 * 5566 * <p>Note: unlike many View methods, there is no dispatch phase to this 5567 * call. If you are overriding it in a ViewGroup and want to allow the 5568 * call to continue to your children, you must be sure to call the super 5569 * implementation. 5570 * 5571 * <p>Here is a sample layout that makes use of fitting system windows 5572 * to have controls for a video view placed inside of the window decorations 5573 * that it hides and shows. This can be used with code like the second 5574 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 5575 * 5576 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 5577 * 5578 * @param insets Current content insets of the window. Prior to 5579 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 5580 * the insets or else you and Android will be unhappy. 5581 * 5582 * @return Return true if this view applied the insets and it should not 5583 * continue propagating further down the hierarchy, false otherwise. 5584 * @see #getFitsSystemWindows() 5585 * @see #setFitsSystemWindows(boolean) 5586 * @see #setSystemUiVisibility(int) 5587 */ 5588 protected boolean fitSystemWindows(Rect insets) { 5589 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 5590 mUserPaddingStart = UNDEFINED_PADDING; 5591 mUserPaddingEnd = UNDEFINED_PADDING; 5592 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 5593 || mAttachInfo == null 5594 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 5595 internalSetPadding(insets.left, insets.top, insets.right, insets.bottom); 5596 return true; 5597 } else { 5598 internalSetPadding(0, 0, 0, 0); 5599 return false; 5600 } 5601 } 5602 return false; 5603 } 5604 5605 /** 5606 * Sets whether or not this view should account for system screen decorations 5607 * such as the status bar and inset its content; that is, controlling whether 5608 * the default implementation of {@link #fitSystemWindows(Rect)} will be 5609 * executed. See that method for more details. 5610 * 5611 * <p>Note that if you are providing your own implementation of 5612 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 5613 * flag to true -- your implementation will be overriding the default 5614 * implementation that checks this flag. 5615 * 5616 * @param fitSystemWindows If true, then the default implementation of 5617 * {@link #fitSystemWindows(Rect)} will be executed. 5618 * 5619 * @attr ref android.R.styleable#View_fitsSystemWindows 5620 * @see #getFitsSystemWindows() 5621 * @see #fitSystemWindows(Rect) 5622 * @see #setSystemUiVisibility(int) 5623 */ 5624 public void setFitsSystemWindows(boolean fitSystemWindows) { 5625 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 5626 } 5627 5628 /** 5629 * Check for state of {@link #setFitsSystemWindows(boolean). If this method 5630 * returns true, the default implementation of {@link #fitSystemWindows(Rect)} 5631 * will be executed. 5632 * 5633 * @return Returns true if the default implementation of 5634 * {@link #fitSystemWindows(Rect)} will be executed. 5635 * 5636 * @attr ref android.R.styleable#View_fitsSystemWindows 5637 * @see #setFitsSystemWindows() 5638 * @see #fitSystemWindows(Rect) 5639 * @see #setSystemUiVisibility(int) 5640 */ 5641 public boolean getFitsSystemWindows() { 5642 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 5643 } 5644 5645 /** @hide */ 5646 public boolean fitsSystemWindows() { 5647 return getFitsSystemWindows(); 5648 } 5649 5650 /** 5651 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 5652 */ 5653 public void requestFitSystemWindows() { 5654 if (mParent != null) { 5655 mParent.requestFitSystemWindows(); 5656 } 5657 } 5658 5659 /** 5660 * For use by PhoneWindow to make its own system window fitting optional. 5661 * @hide 5662 */ 5663 public void makeOptionalFitsSystemWindows() { 5664 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 5665 } 5666 5667 /** 5668 * Returns the visibility status for this view. 5669 * 5670 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5671 * @attr ref android.R.styleable#View_visibility 5672 */ 5673 @ViewDebug.ExportedProperty(mapping = { 5674 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 5675 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 5676 @ViewDebug.IntToString(from = GONE, to = "GONE") 5677 }) 5678 public int getVisibility() { 5679 return mViewFlags & VISIBILITY_MASK; 5680 } 5681 5682 /** 5683 * Set the enabled state of this view. 5684 * 5685 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5686 * @attr ref android.R.styleable#View_visibility 5687 */ 5688 @RemotableViewMethod 5689 public void setVisibility(int visibility) { 5690 setFlags(visibility, VISIBILITY_MASK); 5691 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 5692 } 5693 5694 /** 5695 * Returns the enabled status for this view. The interpretation of the 5696 * enabled state varies by subclass. 5697 * 5698 * @return True if this view is enabled, false otherwise. 5699 */ 5700 @ViewDebug.ExportedProperty 5701 public boolean isEnabled() { 5702 return (mViewFlags & ENABLED_MASK) == ENABLED; 5703 } 5704 5705 /** 5706 * Set the enabled state of this view. The interpretation of the enabled 5707 * state varies by subclass. 5708 * 5709 * @param enabled True if this view is enabled, false otherwise. 5710 */ 5711 @RemotableViewMethod 5712 public void setEnabled(boolean enabled) { 5713 if (enabled == isEnabled()) return; 5714 5715 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 5716 5717 /* 5718 * The View most likely has to change its appearance, so refresh 5719 * the drawable state. 5720 */ 5721 refreshDrawableState(); 5722 5723 // Invalidate too, since the default behavior for views is to be 5724 // be drawn at 50% alpha rather than to change the drawable. 5725 invalidate(true); 5726 } 5727 5728 /** 5729 * Set whether this view can receive the focus. 5730 * 5731 * Setting this to false will also ensure that this view is not focusable 5732 * in touch mode. 5733 * 5734 * @param focusable If true, this view can receive the focus. 5735 * 5736 * @see #setFocusableInTouchMode(boolean) 5737 * @attr ref android.R.styleable#View_focusable 5738 */ 5739 public void setFocusable(boolean focusable) { 5740 if (!focusable) { 5741 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 5742 } 5743 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 5744 } 5745 5746 /** 5747 * Set whether this view can receive focus while in touch mode. 5748 * 5749 * Setting this to true will also ensure that this view is focusable. 5750 * 5751 * @param focusableInTouchMode If true, this view can receive the focus while 5752 * in touch mode. 5753 * 5754 * @see #setFocusable(boolean) 5755 * @attr ref android.R.styleable#View_focusableInTouchMode 5756 */ 5757 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 5758 // Focusable in touch mode should always be set before the focusable flag 5759 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 5760 // which, in touch mode, will not successfully request focus on this view 5761 // because the focusable in touch mode flag is not set 5762 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 5763 if (focusableInTouchMode) { 5764 setFlags(FOCUSABLE, FOCUSABLE_MASK); 5765 } 5766 } 5767 5768 /** 5769 * Set whether this view should have sound effects enabled for events such as 5770 * clicking and touching. 5771 * 5772 * <p>You may wish to disable sound effects for a view if you already play sounds, 5773 * for instance, a dial key that plays dtmf tones. 5774 * 5775 * @param soundEffectsEnabled whether sound effects are enabled for this view. 5776 * @see #isSoundEffectsEnabled() 5777 * @see #playSoundEffect(int) 5778 * @attr ref android.R.styleable#View_soundEffectsEnabled 5779 */ 5780 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 5781 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 5782 } 5783 5784 /** 5785 * @return whether this view should have sound effects enabled for events such as 5786 * clicking and touching. 5787 * 5788 * @see #setSoundEffectsEnabled(boolean) 5789 * @see #playSoundEffect(int) 5790 * @attr ref android.R.styleable#View_soundEffectsEnabled 5791 */ 5792 @ViewDebug.ExportedProperty 5793 public boolean isSoundEffectsEnabled() { 5794 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 5795 } 5796 5797 /** 5798 * Set whether this view should have haptic feedback for events such as 5799 * long presses. 5800 * 5801 * <p>You may wish to disable haptic feedback if your view already controls 5802 * its own haptic feedback. 5803 * 5804 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 5805 * @see #isHapticFeedbackEnabled() 5806 * @see #performHapticFeedback(int) 5807 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5808 */ 5809 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 5810 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 5811 } 5812 5813 /** 5814 * @return whether this view should have haptic feedback enabled for events 5815 * long presses. 5816 * 5817 * @see #setHapticFeedbackEnabled(boolean) 5818 * @see #performHapticFeedback(int) 5819 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5820 */ 5821 @ViewDebug.ExportedProperty 5822 public boolean isHapticFeedbackEnabled() { 5823 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 5824 } 5825 5826 /** 5827 * Returns the layout direction for this view. 5828 * 5829 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 5830 * {@link #LAYOUT_DIRECTION_RTL}, 5831 * {@link #LAYOUT_DIRECTION_INHERIT} or 5832 * {@link #LAYOUT_DIRECTION_LOCALE}. 5833 * @attr ref android.R.styleable#View_layoutDirection 5834 * 5835 * @hide 5836 */ 5837 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5838 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 5839 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 5840 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 5841 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 5842 }) 5843 public int getRawLayoutDirection() { 5844 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 5845 } 5846 5847 /** 5848 * Set the layout direction for this view. This will propagate a reset of layout direction 5849 * resolution to the view's children and resolve layout direction for this view. 5850 * 5851 * @param layoutDirection the layout direction to set. Should be one of: 5852 * 5853 * {@link #LAYOUT_DIRECTION_LTR}, 5854 * {@link #LAYOUT_DIRECTION_RTL}, 5855 * {@link #LAYOUT_DIRECTION_INHERIT}, 5856 * {@link #LAYOUT_DIRECTION_LOCALE}. 5857 * 5858 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 5859 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 5860 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 5861 * 5862 * @attr ref android.R.styleable#View_layoutDirection 5863 */ 5864 @RemotableViewMethod 5865 public void setLayoutDirection(int layoutDirection) { 5866 if (getRawLayoutDirection() != layoutDirection) { 5867 // Reset the current layout direction and the resolved one 5868 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 5869 resetRtlProperties(); 5870 // Set the new layout direction (filtered) 5871 mPrivateFlags2 |= 5872 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 5873 // We need to resolve all RTL properties as they all depend on layout direction 5874 resolveRtlPropertiesIfNeeded(); 5875 requestLayout(); 5876 invalidate(true); 5877 } 5878 } 5879 5880 /** 5881 * Returns the resolved layout direction for this view. 5882 * 5883 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 5884 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 5885 * 5886 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 5887 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 5888 */ 5889 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5890 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 5891 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 5892 }) 5893 public int getLayoutDirection() { 5894 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 5895 if (targetSdkVersion < JELLY_BEAN_MR1) { 5896 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 5897 return LAYOUT_DIRECTION_LTR; 5898 } 5899 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 5900 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 5901 } 5902 5903 /** 5904 * Indicates whether or not this view's layout is right-to-left. This is resolved from 5905 * layout attribute and/or the inherited value from the parent 5906 * 5907 * @return true if the layout is right-to-left. 5908 * 5909 * @hide 5910 */ 5911 @ViewDebug.ExportedProperty(category = "layout") 5912 public boolean isLayoutRtl() { 5913 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 5914 } 5915 5916 /** 5917 * Indicates whether the view is currently tracking transient state that the 5918 * app should not need to concern itself with saving and restoring, but that 5919 * the framework should take special note to preserve when possible. 5920 * 5921 * <p>A view with transient state cannot be trivially rebound from an external 5922 * data source, such as an adapter binding item views in a list. This may be 5923 * because the view is performing an animation, tracking user selection 5924 * of content, or similar.</p> 5925 * 5926 * @return true if the view has transient state 5927 */ 5928 @ViewDebug.ExportedProperty(category = "layout") 5929 public boolean hasTransientState() { 5930 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 5931 } 5932 5933 /** 5934 * Set whether this view is currently tracking transient state that the 5935 * framework should attempt to preserve when possible. This flag is reference counted, 5936 * so every call to setHasTransientState(true) should be paired with a later call 5937 * to setHasTransientState(false). 5938 * 5939 * <p>A view with transient state cannot be trivially rebound from an external 5940 * data source, such as an adapter binding item views in a list. This may be 5941 * because the view is performing an animation, tracking user selection 5942 * of content, or similar.</p> 5943 * 5944 * @param hasTransientState true if this view has transient state 5945 */ 5946 public void setHasTransientState(boolean hasTransientState) { 5947 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 5948 mTransientStateCount - 1; 5949 if (mTransientStateCount < 0) { 5950 mTransientStateCount = 0; 5951 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 5952 "unmatched pair of setHasTransientState calls"); 5953 } 5954 if ((hasTransientState && mTransientStateCount == 1) || 5955 (!hasTransientState && mTransientStateCount == 0)) { 5956 // update flag if we've just incremented up from 0 or decremented down to 0 5957 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 5958 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 5959 if (mParent != null) { 5960 try { 5961 mParent.childHasTransientStateChanged(this, hasTransientState); 5962 } catch (AbstractMethodError e) { 5963 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 5964 " does not fully implement ViewParent", e); 5965 } 5966 } 5967 } 5968 } 5969 5970 /** 5971 * If this view doesn't do any drawing on its own, set this flag to 5972 * allow further optimizations. By default, this flag is not set on 5973 * View, but could be set on some View subclasses such as ViewGroup. 5974 * 5975 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 5976 * you should clear this flag. 5977 * 5978 * @param willNotDraw whether or not this View draw on its own 5979 */ 5980 public void setWillNotDraw(boolean willNotDraw) { 5981 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 5982 } 5983 5984 /** 5985 * Returns whether or not this View draws on its own. 5986 * 5987 * @return true if this view has nothing to draw, false otherwise 5988 */ 5989 @ViewDebug.ExportedProperty(category = "drawing") 5990 public boolean willNotDraw() { 5991 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 5992 } 5993 5994 /** 5995 * When a View's drawing cache is enabled, drawing is redirected to an 5996 * offscreen bitmap. Some views, like an ImageView, must be able to 5997 * bypass this mechanism if they already draw a single bitmap, to avoid 5998 * unnecessary usage of the memory. 5999 * 6000 * @param willNotCacheDrawing true if this view does not cache its 6001 * drawing, false otherwise 6002 */ 6003 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6004 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6005 } 6006 6007 /** 6008 * Returns whether or not this View can cache its drawing or not. 6009 * 6010 * @return true if this view does not cache its drawing, false otherwise 6011 */ 6012 @ViewDebug.ExportedProperty(category = "drawing") 6013 public boolean willNotCacheDrawing() { 6014 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6015 } 6016 6017 /** 6018 * Indicates whether this view reacts to click events or not. 6019 * 6020 * @return true if the view is clickable, false otherwise 6021 * 6022 * @see #setClickable(boolean) 6023 * @attr ref android.R.styleable#View_clickable 6024 */ 6025 @ViewDebug.ExportedProperty 6026 public boolean isClickable() { 6027 return (mViewFlags & CLICKABLE) == CLICKABLE; 6028 } 6029 6030 /** 6031 * Enables or disables click events for this view. When a view 6032 * is clickable it will change its state to "pressed" on every click. 6033 * Subclasses should set the view clickable to visually react to 6034 * user's clicks. 6035 * 6036 * @param clickable true to make the view clickable, false otherwise 6037 * 6038 * @see #isClickable() 6039 * @attr ref android.R.styleable#View_clickable 6040 */ 6041 public void setClickable(boolean clickable) { 6042 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6043 } 6044 6045 /** 6046 * Indicates whether this view reacts to long click events or not. 6047 * 6048 * @return true if the view is long clickable, false otherwise 6049 * 6050 * @see #setLongClickable(boolean) 6051 * @attr ref android.R.styleable#View_longClickable 6052 */ 6053 public boolean isLongClickable() { 6054 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6055 } 6056 6057 /** 6058 * Enables or disables long click events for this view. When a view is long 6059 * clickable it reacts to the user holding down the button for a longer 6060 * duration than a tap. This event can either launch the listener or a 6061 * context menu. 6062 * 6063 * @param longClickable true to make the view long clickable, false otherwise 6064 * @see #isLongClickable() 6065 * @attr ref android.R.styleable#View_longClickable 6066 */ 6067 public void setLongClickable(boolean longClickable) { 6068 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6069 } 6070 6071 /** 6072 * Sets the pressed state for this view. 6073 * 6074 * @see #isClickable() 6075 * @see #setClickable(boolean) 6076 * 6077 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6078 * the View's internal state from a previously set "pressed" state. 6079 */ 6080 public void setPressed(boolean pressed) { 6081 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6082 6083 if (pressed) { 6084 mPrivateFlags |= PFLAG_PRESSED; 6085 } else { 6086 mPrivateFlags &= ~PFLAG_PRESSED; 6087 } 6088 6089 if (needsRefresh) { 6090 refreshDrawableState(); 6091 } 6092 dispatchSetPressed(pressed); 6093 } 6094 6095 /** 6096 * Dispatch setPressed to all of this View's children. 6097 * 6098 * @see #setPressed(boolean) 6099 * 6100 * @param pressed The new pressed state 6101 */ 6102 protected void dispatchSetPressed(boolean pressed) { 6103 } 6104 6105 /** 6106 * Indicates whether the view is currently in pressed state. Unless 6107 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6108 * the pressed state. 6109 * 6110 * @see #setPressed(boolean) 6111 * @see #isClickable() 6112 * @see #setClickable(boolean) 6113 * 6114 * @return true if the view is currently pressed, false otherwise 6115 */ 6116 public boolean isPressed() { 6117 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6118 } 6119 6120 /** 6121 * Indicates whether this view will save its state (that is, 6122 * whether its {@link #onSaveInstanceState} method will be called). 6123 * 6124 * @return Returns true if the view state saving is enabled, else false. 6125 * 6126 * @see #setSaveEnabled(boolean) 6127 * @attr ref android.R.styleable#View_saveEnabled 6128 */ 6129 public boolean isSaveEnabled() { 6130 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6131 } 6132 6133 /** 6134 * Controls whether the saving of this view's state is 6135 * enabled (that is, whether its {@link #onSaveInstanceState} method 6136 * will be called). Note that even if freezing is enabled, the 6137 * view still must have an id assigned to it (via {@link #setId(int)}) 6138 * for its state to be saved. This flag can only disable the 6139 * saving of this view; any child views may still have their state saved. 6140 * 6141 * @param enabled Set to false to <em>disable</em> state saving, or true 6142 * (the default) to allow it. 6143 * 6144 * @see #isSaveEnabled() 6145 * @see #setId(int) 6146 * @see #onSaveInstanceState() 6147 * @attr ref android.R.styleable#View_saveEnabled 6148 */ 6149 public void setSaveEnabled(boolean enabled) { 6150 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6151 } 6152 6153 /** 6154 * Gets whether the framework should discard touches when the view's 6155 * window is obscured by another visible window. 6156 * Refer to the {@link View} security documentation for more details. 6157 * 6158 * @return True if touch filtering is enabled. 6159 * 6160 * @see #setFilterTouchesWhenObscured(boolean) 6161 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6162 */ 6163 @ViewDebug.ExportedProperty 6164 public boolean getFilterTouchesWhenObscured() { 6165 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6166 } 6167 6168 /** 6169 * Sets whether the framework should discard touches when the view's 6170 * window is obscured by another visible window. 6171 * Refer to the {@link View} security documentation for more details. 6172 * 6173 * @param enabled True if touch filtering should be enabled. 6174 * 6175 * @see #getFilterTouchesWhenObscured 6176 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6177 */ 6178 public void setFilterTouchesWhenObscured(boolean enabled) { 6179 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 6180 FILTER_TOUCHES_WHEN_OBSCURED); 6181 } 6182 6183 /** 6184 * Indicates whether the entire hierarchy under this view will save its 6185 * state when a state saving traversal occurs from its parent. The default 6186 * is true; if false, these views will not be saved unless 6187 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6188 * 6189 * @return Returns true if the view state saving from parent is enabled, else false. 6190 * 6191 * @see #setSaveFromParentEnabled(boolean) 6192 */ 6193 public boolean isSaveFromParentEnabled() { 6194 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6195 } 6196 6197 /** 6198 * Controls whether the entire hierarchy under this view will save its 6199 * state when a state saving traversal occurs from its parent. The default 6200 * is true; if false, these views will not be saved unless 6201 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6202 * 6203 * @param enabled Set to false to <em>disable</em> state saving, or true 6204 * (the default) to allow it. 6205 * 6206 * @see #isSaveFromParentEnabled() 6207 * @see #setId(int) 6208 * @see #onSaveInstanceState() 6209 */ 6210 public void setSaveFromParentEnabled(boolean enabled) { 6211 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6212 } 6213 6214 6215 /** 6216 * Returns whether this View is able to take focus. 6217 * 6218 * @return True if this view can take focus, or false otherwise. 6219 * @attr ref android.R.styleable#View_focusable 6220 */ 6221 @ViewDebug.ExportedProperty(category = "focus") 6222 public final boolean isFocusable() { 6223 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6224 } 6225 6226 /** 6227 * When a view is focusable, it may not want to take focus when in touch mode. 6228 * For example, a button would like focus when the user is navigating via a D-pad 6229 * so that the user can click on it, but once the user starts touching the screen, 6230 * the button shouldn't take focus 6231 * @return Whether the view is focusable in touch mode. 6232 * @attr ref android.R.styleable#View_focusableInTouchMode 6233 */ 6234 @ViewDebug.ExportedProperty 6235 public final boolean isFocusableInTouchMode() { 6236 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6237 } 6238 6239 /** 6240 * Find the nearest view in the specified direction that can take focus. 6241 * This does not actually give focus to that view. 6242 * 6243 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6244 * 6245 * @return The nearest focusable in the specified direction, or null if none 6246 * can be found. 6247 */ 6248 public View focusSearch(int direction) { 6249 if (mParent != null) { 6250 return mParent.focusSearch(this, direction); 6251 } else { 6252 return null; 6253 } 6254 } 6255 6256 /** 6257 * This method is the last chance for the focused view and its ancestors to 6258 * respond to an arrow key. This is called when the focused view did not 6259 * consume the key internally, nor could the view system find a new view in 6260 * the requested direction to give focus to. 6261 * 6262 * @param focused The currently focused view. 6263 * @param direction The direction focus wants to move. One of FOCUS_UP, 6264 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6265 * @return True if the this view consumed this unhandled move. 6266 */ 6267 public boolean dispatchUnhandledMove(View focused, int direction) { 6268 return false; 6269 } 6270 6271 /** 6272 * If a user manually specified the next view id for a particular direction, 6273 * use the root to look up the view. 6274 * @param root The root view of the hierarchy containing this view. 6275 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6276 * or FOCUS_BACKWARD. 6277 * @return The user specified next view, or null if there is none. 6278 */ 6279 View findUserSetNextFocus(View root, int direction) { 6280 switch (direction) { 6281 case FOCUS_LEFT: 6282 if (mNextFocusLeftId == View.NO_ID) return null; 6283 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6284 case FOCUS_RIGHT: 6285 if (mNextFocusRightId == View.NO_ID) return null; 6286 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6287 case FOCUS_UP: 6288 if (mNextFocusUpId == View.NO_ID) return null; 6289 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6290 case FOCUS_DOWN: 6291 if (mNextFocusDownId == View.NO_ID) return null; 6292 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6293 case FOCUS_FORWARD: 6294 if (mNextFocusForwardId == View.NO_ID) return null; 6295 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6296 case FOCUS_BACKWARD: { 6297 if (mID == View.NO_ID) return null; 6298 final int id = mID; 6299 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6300 @Override 6301 public boolean apply(View t) { 6302 return t.mNextFocusForwardId == id; 6303 } 6304 }); 6305 } 6306 } 6307 return null; 6308 } 6309 6310 private View findViewInsideOutShouldExist(View root, int id) { 6311 if (mMatchIdPredicate == null) { 6312 mMatchIdPredicate = new MatchIdPredicate(); 6313 } 6314 mMatchIdPredicate.mId = id; 6315 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6316 if (result == null) { 6317 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6318 } 6319 return result; 6320 } 6321 6322 /** 6323 * Find and return all focusable views that are descendants of this view, 6324 * possibly including this view if it is focusable itself. 6325 * 6326 * @param direction The direction of the focus 6327 * @return A list of focusable views 6328 */ 6329 public ArrayList<View> getFocusables(int direction) { 6330 ArrayList<View> result = new ArrayList<View>(24); 6331 addFocusables(result, direction); 6332 return result; 6333 } 6334 6335 /** 6336 * Add any focusable views that are descendants of this view (possibly 6337 * including this view if it is focusable itself) to views. If we are in touch mode, 6338 * only add views that are also focusable in touch mode. 6339 * 6340 * @param views Focusable views found so far 6341 * @param direction The direction of the focus 6342 */ 6343 public void addFocusables(ArrayList<View> views, int direction) { 6344 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6345 } 6346 6347 /** 6348 * Adds any focusable views that are descendants of this view (possibly 6349 * including this view if it is focusable itself) to views. This method 6350 * adds all focusable views regardless if we are in touch mode or 6351 * only views focusable in touch mode if we are in touch mode or 6352 * only views that can take accessibility focus if accessibility is enabeld 6353 * depending on the focusable mode paramater. 6354 * 6355 * @param views Focusable views found so far or null if all we are interested is 6356 * the number of focusables. 6357 * @param direction The direction of the focus. 6358 * @param focusableMode The type of focusables to be added. 6359 * 6360 * @see #FOCUSABLES_ALL 6361 * @see #FOCUSABLES_TOUCH_MODE 6362 */ 6363 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 6364 if (views == null) { 6365 return; 6366 } 6367 if (!isFocusable()) { 6368 return; 6369 } 6370 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6371 && isInTouchMode() && !isFocusableInTouchMode()) { 6372 return; 6373 } 6374 views.add(this); 6375 } 6376 6377 /** 6378 * Finds the Views that contain given text. The containment is case insensitive. 6379 * The search is performed by either the text that the View renders or the content 6380 * description that describes the view for accessibility purposes and the view does 6381 * not render or both. Clients can specify how the search is to be performed via 6382 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 6383 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 6384 * 6385 * @param outViews The output list of matching Views. 6386 * @param searched The text to match against. 6387 * 6388 * @see #FIND_VIEWS_WITH_TEXT 6389 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 6390 * @see #setContentDescription(CharSequence) 6391 */ 6392 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 6393 if (getAccessibilityNodeProvider() != null) { 6394 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 6395 outViews.add(this); 6396 } 6397 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 6398 && (searched != null && searched.length() > 0) 6399 && (mContentDescription != null && mContentDescription.length() > 0)) { 6400 String searchedLowerCase = searched.toString().toLowerCase(); 6401 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 6402 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 6403 outViews.add(this); 6404 } 6405 } 6406 } 6407 6408 /** 6409 * Find and return all touchable views that are descendants of this view, 6410 * possibly including this view if it is touchable itself. 6411 * 6412 * @return A list of touchable views 6413 */ 6414 public ArrayList<View> getTouchables() { 6415 ArrayList<View> result = new ArrayList<View>(); 6416 addTouchables(result); 6417 return result; 6418 } 6419 6420 /** 6421 * Add any touchable views that are descendants of this view (possibly 6422 * including this view if it is touchable itself) to views. 6423 * 6424 * @param views Touchable views found so far 6425 */ 6426 public void addTouchables(ArrayList<View> views) { 6427 final int viewFlags = mViewFlags; 6428 6429 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 6430 && (viewFlags & ENABLED_MASK) == ENABLED) { 6431 views.add(this); 6432 } 6433 } 6434 6435 /** 6436 * Returns whether this View is accessibility focused. 6437 * 6438 * @return True if this View is accessibility focused. 6439 */ 6440 boolean isAccessibilityFocused() { 6441 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 6442 } 6443 6444 /** 6445 * Call this to try to give accessibility focus to this view. 6446 * 6447 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 6448 * returns false or the view is no visible or the view already has accessibility 6449 * focus. 6450 * 6451 * See also {@link #focusSearch(int)}, which is what you call to say that you 6452 * have focus, and you want your parent to look for the next one. 6453 * 6454 * @return Whether this view actually took accessibility focus. 6455 * 6456 * @hide 6457 */ 6458 public boolean requestAccessibilityFocus() { 6459 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 6460 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 6461 return false; 6462 } 6463 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6464 return false; 6465 } 6466 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 6467 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 6468 ViewRootImpl viewRootImpl = getViewRootImpl(); 6469 if (viewRootImpl != null) { 6470 viewRootImpl.setAccessibilityFocus(this, null); 6471 } 6472 invalidate(); 6473 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 6474 notifyAccessibilityStateChanged(); 6475 return true; 6476 } 6477 return false; 6478 } 6479 6480 /** 6481 * Call this to try to clear accessibility focus of this view. 6482 * 6483 * See also {@link #focusSearch(int)}, which is what you call to say that you 6484 * have focus, and you want your parent to look for the next one. 6485 * 6486 * @hide 6487 */ 6488 public void clearAccessibilityFocus() { 6489 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6490 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6491 invalidate(); 6492 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 6493 notifyAccessibilityStateChanged(); 6494 } 6495 // Clear the global reference of accessibility focus if this 6496 // view or any of its descendants had accessibility focus. 6497 ViewRootImpl viewRootImpl = getViewRootImpl(); 6498 if (viewRootImpl != null) { 6499 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 6500 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 6501 viewRootImpl.setAccessibilityFocus(null, null); 6502 } 6503 } 6504 } 6505 6506 private void sendAccessibilityHoverEvent(int eventType) { 6507 // Since we are not delivering to a client accessibility events from not 6508 // important views (unless the clinet request that) we need to fire the 6509 // event from the deepest view exposed to the client. As a consequence if 6510 // the user crosses a not exposed view the client will see enter and exit 6511 // of the exposed predecessor followed by and enter and exit of that same 6512 // predecessor when entering and exiting the not exposed descendant. This 6513 // is fine since the client has a clear idea which view is hovered at the 6514 // price of a couple more events being sent. This is a simple and 6515 // working solution. 6516 View source = this; 6517 while (true) { 6518 if (source.includeForAccessibility()) { 6519 source.sendAccessibilityEvent(eventType); 6520 return; 6521 } 6522 ViewParent parent = source.getParent(); 6523 if (parent instanceof View) { 6524 source = (View) parent; 6525 } else { 6526 return; 6527 } 6528 } 6529 } 6530 6531 /** 6532 * Clears accessibility focus without calling any callback methods 6533 * normally invoked in {@link #clearAccessibilityFocus()}. This method 6534 * is used for clearing accessibility focus when giving this focus to 6535 * another view. 6536 */ 6537 void clearAccessibilityFocusNoCallbacks() { 6538 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6539 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6540 invalidate(); 6541 } 6542 } 6543 6544 /** 6545 * Call this to try to give focus to a specific view or to one of its 6546 * descendants. 6547 * 6548 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6549 * false), or if it is focusable and it is not focusable in touch mode 6550 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6551 * 6552 * See also {@link #focusSearch(int)}, which is what you call to say that you 6553 * have focus, and you want your parent to look for the next one. 6554 * 6555 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 6556 * {@link #FOCUS_DOWN} and <code>null</code>. 6557 * 6558 * @return Whether this view or one of its descendants actually took focus. 6559 */ 6560 public final boolean requestFocus() { 6561 return requestFocus(View.FOCUS_DOWN); 6562 } 6563 6564 /** 6565 * Call this to try to give focus to a specific view or to one of its 6566 * descendants and give it a hint about what direction focus is heading. 6567 * 6568 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6569 * false), or if it is focusable and it is not focusable in touch mode 6570 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6571 * 6572 * See also {@link #focusSearch(int)}, which is what you call to say that you 6573 * have focus, and you want your parent to look for the next one. 6574 * 6575 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 6576 * <code>null</code> set for the previously focused rectangle. 6577 * 6578 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6579 * @return Whether this view or one of its descendants actually took focus. 6580 */ 6581 public final boolean requestFocus(int direction) { 6582 return requestFocus(direction, null); 6583 } 6584 6585 /** 6586 * Call this to try to give focus to a specific view or to one of its descendants 6587 * and give it hints about the direction and a specific rectangle that the focus 6588 * is coming from. The rectangle can help give larger views a finer grained hint 6589 * about where focus is coming from, and therefore, where to show selection, or 6590 * forward focus change internally. 6591 * 6592 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6593 * false), or if it is focusable and it is not focusable in touch mode 6594 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6595 * 6596 * A View will not take focus if it is not visible. 6597 * 6598 * A View will not take focus if one of its parents has 6599 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 6600 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 6601 * 6602 * See also {@link #focusSearch(int)}, which is what you call to say that you 6603 * have focus, and you want your parent to look for the next one. 6604 * 6605 * You may wish to override this method if your custom {@link View} has an internal 6606 * {@link View} that it wishes to forward the request to. 6607 * 6608 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6609 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 6610 * to give a finer grained hint about where focus is coming from. May be null 6611 * if there is no hint. 6612 * @return Whether this view or one of its descendants actually took focus. 6613 */ 6614 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 6615 return requestFocusNoSearch(direction, previouslyFocusedRect); 6616 } 6617 6618 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 6619 // need to be focusable 6620 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 6621 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6622 return false; 6623 } 6624 6625 // need to be focusable in touch mode if in touch mode 6626 if (isInTouchMode() && 6627 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 6628 return false; 6629 } 6630 6631 // need to not have any parents blocking us 6632 if (hasAncestorThatBlocksDescendantFocus()) { 6633 return false; 6634 } 6635 6636 handleFocusGainInternal(direction, previouslyFocusedRect); 6637 return true; 6638 } 6639 6640 /** 6641 * Call this to try to give focus to a specific view or to one of its descendants. This is a 6642 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 6643 * touch mode to request focus when they are touched. 6644 * 6645 * @return Whether this view or one of its descendants actually took focus. 6646 * 6647 * @see #isInTouchMode() 6648 * 6649 */ 6650 public final boolean requestFocusFromTouch() { 6651 // Leave touch mode if we need to 6652 if (isInTouchMode()) { 6653 ViewRootImpl viewRoot = getViewRootImpl(); 6654 if (viewRoot != null) { 6655 viewRoot.ensureTouchMode(false); 6656 } 6657 } 6658 return requestFocus(View.FOCUS_DOWN); 6659 } 6660 6661 /** 6662 * @return Whether any ancestor of this view blocks descendant focus. 6663 */ 6664 private boolean hasAncestorThatBlocksDescendantFocus() { 6665 ViewParent ancestor = mParent; 6666 while (ancestor instanceof ViewGroup) { 6667 final ViewGroup vgAncestor = (ViewGroup) ancestor; 6668 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 6669 return true; 6670 } else { 6671 ancestor = vgAncestor.getParent(); 6672 } 6673 } 6674 return false; 6675 } 6676 6677 /** 6678 * Gets the mode for determining whether this View is important for accessibility 6679 * which is if it fires accessibility events and if it is reported to 6680 * accessibility services that query the screen. 6681 * 6682 * @return The mode for determining whether a View is important for accessibility. 6683 * 6684 * @attr ref android.R.styleable#View_importantForAccessibility 6685 * 6686 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6687 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6688 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6689 */ 6690 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 6691 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 6692 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 6693 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no") 6694 }) 6695 public int getImportantForAccessibility() { 6696 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6697 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6698 } 6699 6700 /** 6701 * Sets how to determine whether this view is important for accessibility 6702 * which is if it fires accessibility events and if it is reported to 6703 * accessibility services that query the screen. 6704 * 6705 * @param mode How to determine whether this view is important for accessibility. 6706 * 6707 * @attr ref android.R.styleable#View_importantForAccessibility 6708 * 6709 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6710 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6711 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6712 */ 6713 public void setImportantForAccessibility(int mode) { 6714 if (mode != getImportantForAccessibility()) { 6715 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6716 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 6717 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6718 notifyAccessibilityStateChanged(); 6719 } 6720 } 6721 6722 /** 6723 * Gets whether this view should be exposed for accessibility. 6724 * 6725 * @return Whether the view is exposed for accessibility. 6726 * 6727 * @hide 6728 */ 6729 public boolean isImportantForAccessibility() { 6730 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6731 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6732 switch (mode) { 6733 case IMPORTANT_FOR_ACCESSIBILITY_YES: 6734 return true; 6735 case IMPORTANT_FOR_ACCESSIBILITY_NO: 6736 return false; 6737 case IMPORTANT_FOR_ACCESSIBILITY_AUTO: 6738 return isActionableForAccessibility() || hasListenersForAccessibility() 6739 || getAccessibilityNodeProvider() != null; 6740 default: 6741 throw new IllegalArgumentException("Unknow important for accessibility mode: " 6742 + mode); 6743 } 6744 } 6745 6746 /** 6747 * Gets the parent for accessibility purposes. Note that the parent for 6748 * accessibility is not necessary the immediate parent. It is the first 6749 * predecessor that is important for accessibility. 6750 * 6751 * @return The parent for accessibility purposes. 6752 */ 6753 public ViewParent getParentForAccessibility() { 6754 if (mParent instanceof View) { 6755 View parentView = (View) mParent; 6756 if (parentView.includeForAccessibility()) { 6757 return mParent; 6758 } else { 6759 return mParent.getParentForAccessibility(); 6760 } 6761 } 6762 return null; 6763 } 6764 6765 /** 6766 * Adds the children of a given View for accessibility. Since some Views are 6767 * not important for accessibility the children for accessibility are not 6768 * necessarily direct children of the riew, rather they are the first level of 6769 * descendants important for accessibility. 6770 * 6771 * @param children The list of children for accessibility. 6772 */ 6773 public void addChildrenForAccessibility(ArrayList<View> children) { 6774 if (includeForAccessibility()) { 6775 children.add(this); 6776 } 6777 } 6778 6779 /** 6780 * Whether to regard this view for accessibility. A view is regarded for 6781 * accessibility if it is important for accessibility or the querying 6782 * accessibility service has explicitly requested that view not 6783 * important for accessibility are regarded. 6784 * 6785 * @return Whether to regard the view for accessibility. 6786 * 6787 * @hide 6788 */ 6789 public boolean includeForAccessibility() { 6790 if (mAttachInfo != null) { 6791 return mAttachInfo.mIncludeNotImportantViews || isImportantForAccessibility(); 6792 } 6793 return false; 6794 } 6795 6796 /** 6797 * Returns whether the View is considered actionable from 6798 * accessibility perspective. Such view are important for 6799 * accessibility. 6800 * 6801 * @return True if the view is actionable for accessibility. 6802 * 6803 * @hide 6804 */ 6805 public boolean isActionableForAccessibility() { 6806 return (isClickable() || isLongClickable() || isFocusable()); 6807 } 6808 6809 /** 6810 * Returns whether the View has registered callbacks wich makes it 6811 * important for accessibility. 6812 * 6813 * @return True if the view is actionable for accessibility. 6814 */ 6815 private boolean hasListenersForAccessibility() { 6816 ListenerInfo info = getListenerInfo(); 6817 return mTouchDelegate != null || info.mOnKeyListener != null 6818 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 6819 || info.mOnHoverListener != null || info.mOnDragListener != null; 6820 } 6821 6822 /** 6823 * Notifies accessibility services that some view's important for 6824 * accessibility state has changed. Note that such notifications 6825 * are made at most once every 6826 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 6827 * to avoid unnecessary load to the system. Also once a view has 6828 * made a notifucation this method is a NOP until the notification has 6829 * been sent to clients. 6830 * 6831 * @hide 6832 * 6833 * TODO: Makse sure this method is called for any view state change 6834 * that is interesting for accessilility purposes. 6835 */ 6836 public void notifyAccessibilityStateChanged() { 6837 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 6838 return; 6839 } 6840 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) { 6841 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED; 6842 if (mParent != null) { 6843 mParent.childAccessibilityStateChanged(this); 6844 } 6845 } 6846 } 6847 6848 /** 6849 * Reset the state indicating the this view has requested clients 6850 * interested in its accessibility state to be notified. 6851 * 6852 * @hide 6853 */ 6854 public void resetAccessibilityStateChanged() { 6855 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED; 6856 } 6857 6858 /** 6859 * Performs the specified accessibility action on the view. For 6860 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 6861 * <p> 6862 * If an {@link AccessibilityDelegate} has been specified via calling 6863 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6864 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 6865 * is responsible for handling this call. 6866 * </p> 6867 * 6868 * @param action The action to perform. 6869 * @param arguments Optional action arguments. 6870 * @return Whether the action was performed. 6871 */ 6872 public boolean performAccessibilityAction(int action, Bundle arguments) { 6873 if (mAccessibilityDelegate != null) { 6874 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 6875 } else { 6876 return performAccessibilityActionInternal(action, arguments); 6877 } 6878 } 6879 6880 /** 6881 * @see #performAccessibilityAction(int, Bundle) 6882 * 6883 * Note: Called from the default {@link AccessibilityDelegate}. 6884 */ 6885 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 6886 switch (action) { 6887 case AccessibilityNodeInfo.ACTION_CLICK: { 6888 if (isClickable()) { 6889 performClick(); 6890 return true; 6891 } 6892 } break; 6893 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 6894 if (isLongClickable()) { 6895 performLongClick(); 6896 return true; 6897 } 6898 } break; 6899 case AccessibilityNodeInfo.ACTION_FOCUS: { 6900 if (!hasFocus()) { 6901 // Get out of touch mode since accessibility 6902 // wants to move focus around. 6903 getViewRootImpl().ensureTouchMode(false); 6904 return requestFocus(); 6905 } 6906 } break; 6907 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 6908 if (hasFocus()) { 6909 clearFocus(); 6910 return !isFocused(); 6911 } 6912 } break; 6913 case AccessibilityNodeInfo.ACTION_SELECT: { 6914 if (!isSelected()) { 6915 setSelected(true); 6916 return isSelected(); 6917 } 6918 } break; 6919 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 6920 if (isSelected()) { 6921 setSelected(false); 6922 return !isSelected(); 6923 } 6924 } break; 6925 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 6926 if (!isAccessibilityFocused()) { 6927 return requestAccessibilityFocus(); 6928 } 6929 } break; 6930 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 6931 if (isAccessibilityFocused()) { 6932 clearAccessibilityFocus(); 6933 return true; 6934 } 6935 } break; 6936 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 6937 if (arguments != null) { 6938 final int granularity = arguments.getInt( 6939 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 6940 return nextAtGranularity(granularity); 6941 } 6942 } break; 6943 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 6944 if (arguments != null) { 6945 final int granularity = arguments.getInt( 6946 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 6947 return previousAtGranularity(granularity); 6948 } 6949 } break; 6950 } 6951 return false; 6952 } 6953 6954 private boolean nextAtGranularity(int granularity) { 6955 CharSequence text = getIterableTextForAccessibility(); 6956 if (text == null || text.length() == 0) { 6957 return false; 6958 } 6959 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 6960 if (iterator == null) { 6961 return false; 6962 } 6963 final int current = getAccessibilityCursorPosition(); 6964 final int[] range = iterator.following(current); 6965 if (range == null) { 6966 return false; 6967 } 6968 final int start = range[0]; 6969 final int end = range[1]; 6970 setAccessibilityCursorPosition(end); 6971 sendViewTextTraversedAtGranularityEvent( 6972 AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, 6973 granularity, start, end); 6974 return true; 6975 } 6976 6977 private boolean previousAtGranularity(int granularity) { 6978 CharSequence text = getIterableTextForAccessibility(); 6979 if (text == null || text.length() == 0) { 6980 return false; 6981 } 6982 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 6983 if (iterator == null) { 6984 return false; 6985 } 6986 int current = getAccessibilityCursorPosition(); 6987 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 6988 current = text.length(); 6989 } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) { 6990 // When traversing by character we always put the cursor after the character 6991 // to ease edit and have to compensate before asking the for previous segment. 6992 current--; 6993 } 6994 final int[] range = iterator.preceding(current); 6995 if (range == null) { 6996 return false; 6997 } 6998 final int start = range[0]; 6999 final int end = range[1]; 7000 // Always put the cursor after the character to ease edit. 7001 if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) { 7002 setAccessibilityCursorPosition(end); 7003 } else { 7004 setAccessibilityCursorPosition(start); 7005 } 7006 sendViewTextTraversedAtGranularityEvent( 7007 AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, 7008 granularity, start, end); 7009 return true; 7010 } 7011 7012 /** 7013 * Gets the text reported for accessibility purposes. 7014 * 7015 * @return The accessibility text. 7016 * 7017 * @hide 7018 */ 7019 public CharSequence getIterableTextForAccessibility() { 7020 return getContentDescription(); 7021 } 7022 7023 /** 7024 * @hide 7025 */ 7026 public int getAccessibilityCursorPosition() { 7027 return mAccessibilityCursorPosition; 7028 } 7029 7030 /** 7031 * @hide 7032 */ 7033 public void setAccessibilityCursorPosition(int position) { 7034 mAccessibilityCursorPosition = position; 7035 } 7036 7037 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7038 int fromIndex, int toIndex) { 7039 if (mParent == null) { 7040 return; 7041 } 7042 AccessibilityEvent event = AccessibilityEvent.obtain( 7043 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7044 onInitializeAccessibilityEvent(event); 7045 onPopulateAccessibilityEvent(event); 7046 event.setFromIndex(fromIndex); 7047 event.setToIndex(toIndex); 7048 event.setAction(action); 7049 event.setMovementGranularity(granularity); 7050 mParent.requestSendAccessibilityEvent(this, event); 7051 } 7052 7053 /** 7054 * @hide 7055 */ 7056 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7057 switch (granularity) { 7058 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7059 CharSequence text = getIterableTextForAccessibility(); 7060 if (text != null && text.length() > 0) { 7061 CharacterTextSegmentIterator iterator = 7062 CharacterTextSegmentIterator.getInstance( 7063 mContext.getResources().getConfiguration().locale); 7064 iterator.initialize(text.toString()); 7065 return iterator; 7066 } 7067 } break; 7068 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7069 CharSequence text = getIterableTextForAccessibility(); 7070 if (text != null && text.length() > 0) { 7071 WordTextSegmentIterator iterator = 7072 WordTextSegmentIterator.getInstance( 7073 mContext.getResources().getConfiguration().locale); 7074 iterator.initialize(text.toString()); 7075 return iterator; 7076 } 7077 } break; 7078 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7079 CharSequence text = getIterableTextForAccessibility(); 7080 if (text != null && text.length() > 0) { 7081 ParagraphTextSegmentIterator iterator = 7082 ParagraphTextSegmentIterator.getInstance(); 7083 iterator.initialize(text.toString()); 7084 return iterator; 7085 } 7086 } break; 7087 } 7088 return null; 7089 } 7090 7091 /** 7092 * @hide 7093 */ 7094 public void dispatchStartTemporaryDetach() { 7095 clearAccessibilityFocus(); 7096 clearDisplayList(); 7097 7098 onStartTemporaryDetach(); 7099 } 7100 7101 /** 7102 * This is called when a container is going to temporarily detach a child, with 7103 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7104 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7105 * {@link #onDetachedFromWindow()} when the container is done. 7106 */ 7107 public void onStartTemporaryDetach() { 7108 removeUnsetPressCallback(); 7109 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7110 } 7111 7112 /** 7113 * @hide 7114 */ 7115 public void dispatchFinishTemporaryDetach() { 7116 onFinishTemporaryDetach(); 7117 } 7118 7119 /** 7120 * Called after {@link #onStartTemporaryDetach} when the container is done 7121 * changing the view. 7122 */ 7123 public void onFinishTemporaryDetach() { 7124 } 7125 7126 /** 7127 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7128 * for this view's window. Returns null if the view is not currently attached 7129 * to the window. Normally you will not need to use this directly, but 7130 * just use the standard high-level event callbacks like 7131 * {@link #onKeyDown(int, KeyEvent)}. 7132 */ 7133 public KeyEvent.DispatcherState getKeyDispatcherState() { 7134 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7135 } 7136 7137 /** 7138 * Dispatch a key event before it is processed by any input method 7139 * associated with the view hierarchy. This can be used to intercept 7140 * key events in special situations before the IME consumes them; a 7141 * typical example would be handling the BACK key to update the application's 7142 * UI instead of allowing the IME to see it and close itself. 7143 * 7144 * @param event The key event to be dispatched. 7145 * @return True if the event was handled, false otherwise. 7146 */ 7147 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7148 return onKeyPreIme(event.getKeyCode(), event); 7149 } 7150 7151 /** 7152 * Dispatch a key event to the next view on the focus path. This path runs 7153 * from the top of the view tree down to the currently focused view. If this 7154 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7155 * the next node down the focus path. This method also fires any key 7156 * listeners. 7157 * 7158 * @param event The key event to be dispatched. 7159 * @return True if the event was handled, false otherwise. 7160 */ 7161 public boolean dispatchKeyEvent(KeyEvent event) { 7162 if (mInputEventConsistencyVerifier != null) { 7163 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7164 } 7165 7166 // Give any attached key listener a first crack at the event. 7167 //noinspection SimplifiableIfStatement 7168 ListenerInfo li = mListenerInfo; 7169 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7170 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7171 return true; 7172 } 7173 7174 if (event.dispatch(this, mAttachInfo != null 7175 ? mAttachInfo.mKeyDispatchState : null, this)) { 7176 return true; 7177 } 7178 7179 if (mInputEventConsistencyVerifier != null) { 7180 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7181 } 7182 return false; 7183 } 7184 7185 /** 7186 * Dispatches a key shortcut event. 7187 * 7188 * @param event The key event to be dispatched. 7189 * @return True if the event was handled by the view, false otherwise. 7190 */ 7191 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 7192 return onKeyShortcut(event.getKeyCode(), event); 7193 } 7194 7195 /** 7196 * Pass the touch screen motion event down to the target view, or this 7197 * view if it is the target. 7198 * 7199 * @param event The motion event to be dispatched. 7200 * @return True if the event was handled by the view, false otherwise. 7201 */ 7202 public boolean dispatchTouchEvent(MotionEvent event) { 7203 if (mInputEventConsistencyVerifier != null) { 7204 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 7205 } 7206 7207 if (onFilterTouchEventForSecurity(event)) { 7208 //noinspection SimplifiableIfStatement 7209 ListenerInfo li = mListenerInfo; 7210 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7211 && li.mOnTouchListener.onTouch(this, event)) { 7212 return true; 7213 } 7214 7215 if (onTouchEvent(event)) { 7216 return true; 7217 } 7218 } 7219 7220 if (mInputEventConsistencyVerifier != null) { 7221 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7222 } 7223 return false; 7224 } 7225 7226 /** 7227 * Filter the touch event to apply security policies. 7228 * 7229 * @param event The motion event to be filtered. 7230 * @return True if the event should be dispatched, false if the event should be dropped. 7231 * 7232 * @see #getFilterTouchesWhenObscured 7233 */ 7234 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 7235 //noinspection RedundantIfStatement 7236 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 7237 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 7238 // Window is obscured, drop this touch. 7239 return false; 7240 } 7241 return true; 7242 } 7243 7244 /** 7245 * Pass a trackball motion event down to the focused view. 7246 * 7247 * @param event The motion event to be dispatched. 7248 * @return True if the event was handled by the view, false otherwise. 7249 */ 7250 public boolean dispatchTrackballEvent(MotionEvent event) { 7251 if (mInputEventConsistencyVerifier != null) { 7252 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 7253 } 7254 7255 return onTrackballEvent(event); 7256 } 7257 7258 /** 7259 * Dispatch a generic motion event. 7260 * <p> 7261 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7262 * are delivered to the view under the pointer. All other generic motion events are 7263 * delivered to the focused view. Hover events are handled specially and are delivered 7264 * to {@link #onHoverEvent(MotionEvent)}. 7265 * </p> 7266 * 7267 * @param event The motion event to be dispatched. 7268 * @return True if the event was handled by the view, false otherwise. 7269 */ 7270 public boolean dispatchGenericMotionEvent(MotionEvent event) { 7271 if (mInputEventConsistencyVerifier != null) { 7272 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 7273 } 7274 7275 final int source = event.getSource(); 7276 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7277 final int action = event.getAction(); 7278 if (action == MotionEvent.ACTION_HOVER_ENTER 7279 || action == MotionEvent.ACTION_HOVER_MOVE 7280 || action == MotionEvent.ACTION_HOVER_EXIT) { 7281 if (dispatchHoverEvent(event)) { 7282 return true; 7283 } 7284 } else if (dispatchGenericPointerEvent(event)) { 7285 return true; 7286 } 7287 } else if (dispatchGenericFocusedEvent(event)) { 7288 return true; 7289 } 7290 7291 if (dispatchGenericMotionEventInternal(event)) { 7292 return true; 7293 } 7294 7295 if (mInputEventConsistencyVerifier != null) { 7296 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7297 } 7298 return false; 7299 } 7300 7301 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 7302 //noinspection SimplifiableIfStatement 7303 ListenerInfo li = mListenerInfo; 7304 if (li != null && li.mOnGenericMotionListener != null 7305 && (mViewFlags & ENABLED_MASK) == ENABLED 7306 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 7307 return true; 7308 } 7309 7310 if (onGenericMotionEvent(event)) { 7311 return true; 7312 } 7313 7314 if (mInputEventConsistencyVerifier != null) { 7315 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7316 } 7317 return false; 7318 } 7319 7320 /** 7321 * Dispatch a hover event. 7322 * <p> 7323 * Do not call this method directly. 7324 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7325 * </p> 7326 * 7327 * @param event The motion event to be dispatched. 7328 * @return True if the event was handled by the view, false otherwise. 7329 */ 7330 protected boolean dispatchHoverEvent(MotionEvent event) { 7331 //noinspection SimplifiableIfStatement 7332 ListenerInfo li = mListenerInfo; 7333 if (li != null && li.mOnHoverListener != null 7334 && (mViewFlags & ENABLED_MASK) == ENABLED 7335 && li.mOnHoverListener.onHover(this, event)) { 7336 return true; 7337 } 7338 7339 return onHoverEvent(event); 7340 } 7341 7342 /** 7343 * Returns true if the view has a child to which it has recently sent 7344 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 7345 * it does not have a hovered child, then it must be the innermost hovered view. 7346 * @hide 7347 */ 7348 protected boolean hasHoveredChild() { 7349 return false; 7350 } 7351 7352 /** 7353 * Dispatch a generic motion event to the view under the first pointer. 7354 * <p> 7355 * Do not call this method directly. 7356 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7357 * </p> 7358 * 7359 * @param event The motion event to be dispatched. 7360 * @return True if the event was handled by the view, false otherwise. 7361 */ 7362 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 7363 return false; 7364 } 7365 7366 /** 7367 * Dispatch a generic motion event to the currently focused view. 7368 * <p> 7369 * Do not call this method directly. 7370 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7371 * </p> 7372 * 7373 * @param event The motion event to be dispatched. 7374 * @return True if the event was handled by the view, false otherwise. 7375 */ 7376 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 7377 return false; 7378 } 7379 7380 /** 7381 * Dispatch a pointer event. 7382 * <p> 7383 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 7384 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 7385 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 7386 * and should not be expected to handle other pointing device features. 7387 * </p> 7388 * 7389 * @param event The motion event to be dispatched. 7390 * @return True if the event was handled by the view, false otherwise. 7391 * @hide 7392 */ 7393 public final boolean dispatchPointerEvent(MotionEvent event) { 7394 if (event.isTouchEvent()) { 7395 return dispatchTouchEvent(event); 7396 } else { 7397 return dispatchGenericMotionEvent(event); 7398 } 7399 } 7400 7401 /** 7402 * Called when the window containing this view gains or loses window focus. 7403 * ViewGroups should override to route to their children. 7404 * 7405 * @param hasFocus True if the window containing this view now has focus, 7406 * false otherwise. 7407 */ 7408 public void dispatchWindowFocusChanged(boolean hasFocus) { 7409 onWindowFocusChanged(hasFocus); 7410 } 7411 7412 /** 7413 * Called when the window containing this view gains or loses focus. Note 7414 * that this is separate from view focus: to receive key events, both 7415 * your view and its window must have focus. If a window is displayed 7416 * on top of yours that takes input focus, then your own window will lose 7417 * focus but the view focus will remain unchanged. 7418 * 7419 * @param hasWindowFocus True if the window containing this view now has 7420 * focus, false otherwise. 7421 */ 7422 public void onWindowFocusChanged(boolean hasWindowFocus) { 7423 InputMethodManager imm = InputMethodManager.peekInstance(); 7424 if (!hasWindowFocus) { 7425 if (isPressed()) { 7426 setPressed(false); 7427 } 7428 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7429 imm.focusOut(this); 7430 } 7431 removeLongPressCallback(); 7432 removeTapCallback(); 7433 onFocusLost(); 7434 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7435 imm.focusIn(this); 7436 } 7437 refreshDrawableState(); 7438 } 7439 7440 /** 7441 * Returns true if this view is in a window that currently has window focus. 7442 * Note that this is not the same as the view itself having focus. 7443 * 7444 * @return True if this view is in a window that currently has window focus. 7445 */ 7446 public boolean hasWindowFocus() { 7447 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 7448 } 7449 7450 /** 7451 * Dispatch a view visibility change down the view hierarchy. 7452 * ViewGroups should override to route to their children. 7453 * @param changedView The view whose visibility changed. Could be 'this' or 7454 * an ancestor view. 7455 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7456 * {@link #INVISIBLE} or {@link #GONE}. 7457 */ 7458 protected void dispatchVisibilityChanged(View changedView, int visibility) { 7459 onVisibilityChanged(changedView, visibility); 7460 } 7461 7462 /** 7463 * Called when the visibility of the view or an ancestor of the view is changed. 7464 * @param changedView The view whose visibility changed. Could be 'this' or 7465 * an ancestor view. 7466 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7467 * {@link #INVISIBLE} or {@link #GONE}. 7468 */ 7469 protected void onVisibilityChanged(View changedView, int visibility) { 7470 if (visibility == VISIBLE) { 7471 if (mAttachInfo != null) { 7472 initialAwakenScrollBars(); 7473 } else { 7474 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 7475 } 7476 } 7477 } 7478 7479 /** 7480 * Dispatch a hint about whether this view is displayed. For instance, when 7481 * a View moves out of the screen, it might receives a display hint indicating 7482 * the view is not displayed. Applications should not <em>rely</em> on this hint 7483 * as there is no guarantee that they will receive one. 7484 * 7485 * @param hint A hint about whether or not this view is displayed: 7486 * {@link #VISIBLE} or {@link #INVISIBLE}. 7487 */ 7488 public void dispatchDisplayHint(int hint) { 7489 onDisplayHint(hint); 7490 } 7491 7492 /** 7493 * Gives this view a hint about whether is displayed or not. For instance, when 7494 * a View moves out of the screen, it might receives a display hint indicating 7495 * the view is not displayed. Applications should not <em>rely</em> on this hint 7496 * as there is no guarantee that they will receive one. 7497 * 7498 * @param hint A hint about whether or not this view is displayed: 7499 * {@link #VISIBLE} or {@link #INVISIBLE}. 7500 */ 7501 protected void onDisplayHint(int hint) { 7502 } 7503 7504 /** 7505 * Dispatch a window visibility change down the view hierarchy. 7506 * ViewGroups should override to route to their children. 7507 * 7508 * @param visibility The new visibility of the window. 7509 * 7510 * @see #onWindowVisibilityChanged(int) 7511 */ 7512 public void dispatchWindowVisibilityChanged(int visibility) { 7513 onWindowVisibilityChanged(visibility); 7514 } 7515 7516 /** 7517 * Called when the window containing has change its visibility 7518 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 7519 * that this tells you whether or not your window is being made visible 7520 * to the window manager; this does <em>not</em> tell you whether or not 7521 * your window is obscured by other windows on the screen, even if it 7522 * is itself visible. 7523 * 7524 * @param visibility The new visibility of the window. 7525 */ 7526 protected void onWindowVisibilityChanged(int visibility) { 7527 if (visibility == VISIBLE) { 7528 initialAwakenScrollBars(); 7529 } 7530 } 7531 7532 /** 7533 * Returns the current visibility of the window this view is attached to 7534 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 7535 * 7536 * @return Returns the current visibility of the view's window. 7537 */ 7538 public int getWindowVisibility() { 7539 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 7540 } 7541 7542 /** 7543 * Retrieve the overall visible display size in which the window this view is 7544 * attached to has been positioned in. This takes into account screen 7545 * decorations above the window, for both cases where the window itself 7546 * is being position inside of them or the window is being placed under 7547 * then and covered insets are used for the window to position its content 7548 * inside. In effect, this tells you the available area where content can 7549 * be placed and remain visible to users. 7550 * 7551 * <p>This function requires an IPC back to the window manager to retrieve 7552 * the requested information, so should not be used in performance critical 7553 * code like drawing. 7554 * 7555 * @param outRect Filled in with the visible display frame. If the view 7556 * is not attached to a window, this is simply the raw display size. 7557 */ 7558 public void getWindowVisibleDisplayFrame(Rect outRect) { 7559 if (mAttachInfo != null) { 7560 try { 7561 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 7562 } catch (RemoteException e) { 7563 return; 7564 } 7565 // XXX This is really broken, and probably all needs to be done 7566 // in the window manager, and we need to know more about whether 7567 // we want the area behind or in front of the IME. 7568 final Rect insets = mAttachInfo.mVisibleInsets; 7569 outRect.left += insets.left; 7570 outRect.top += insets.top; 7571 outRect.right -= insets.right; 7572 outRect.bottom -= insets.bottom; 7573 return; 7574 } 7575 // The view is not attached to a display so we don't have a context. 7576 // Make a best guess about the display size. 7577 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 7578 d.getRectSize(outRect); 7579 } 7580 7581 /** 7582 * Dispatch a notification about a resource configuration change down 7583 * the view hierarchy. 7584 * ViewGroups should override to route to their children. 7585 * 7586 * @param newConfig The new resource configuration. 7587 * 7588 * @see #onConfigurationChanged(android.content.res.Configuration) 7589 */ 7590 public void dispatchConfigurationChanged(Configuration newConfig) { 7591 onConfigurationChanged(newConfig); 7592 } 7593 7594 /** 7595 * Called when the current configuration of the resources being used 7596 * by the application have changed. You can use this to decide when 7597 * to reload resources that can changed based on orientation and other 7598 * configuration characterstics. You only need to use this if you are 7599 * not relying on the normal {@link android.app.Activity} mechanism of 7600 * recreating the activity instance upon a configuration change. 7601 * 7602 * @param newConfig The new resource configuration. 7603 */ 7604 protected void onConfigurationChanged(Configuration newConfig) { 7605 } 7606 7607 /** 7608 * Private function to aggregate all per-view attributes in to the view 7609 * root. 7610 */ 7611 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7612 performCollectViewAttributes(attachInfo, visibility); 7613 } 7614 7615 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7616 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 7617 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 7618 attachInfo.mKeepScreenOn = true; 7619 } 7620 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 7621 ListenerInfo li = mListenerInfo; 7622 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 7623 attachInfo.mHasSystemUiListeners = true; 7624 } 7625 } 7626 } 7627 7628 void needGlobalAttributesUpdate(boolean force) { 7629 final AttachInfo ai = mAttachInfo; 7630 if (ai != null && !ai.mRecomputeGlobalAttributes) { 7631 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 7632 || ai.mHasSystemUiListeners) { 7633 ai.mRecomputeGlobalAttributes = true; 7634 } 7635 } 7636 } 7637 7638 /** 7639 * Returns whether the device is currently in touch mode. Touch mode is entered 7640 * once the user begins interacting with the device by touch, and affects various 7641 * things like whether focus is always visible to the user. 7642 * 7643 * @return Whether the device is in touch mode. 7644 */ 7645 @ViewDebug.ExportedProperty 7646 public boolean isInTouchMode() { 7647 if (mAttachInfo != null) { 7648 return mAttachInfo.mInTouchMode; 7649 } else { 7650 return ViewRootImpl.isInTouchMode(); 7651 } 7652 } 7653 7654 /** 7655 * Returns the context the view is running in, through which it can 7656 * access the current theme, resources, etc. 7657 * 7658 * @return The view's Context. 7659 */ 7660 @ViewDebug.CapturedViewProperty 7661 public final Context getContext() { 7662 return mContext; 7663 } 7664 7665 /** 7666 * Handle a key event before it is processed by any input method 7667 * associated with the view hierarchy. This can be used to intercept 7668 * key events in special situations before the IME consumes them; a 7669 * typical example would be handling the BACK key to update the application's 7670 * UI instead of allowing the IME to see it and close itself. 7671 * 7672 * @param keyCode The value in event.getKeyCode(). 7673 * @param event Description of the key event. 7674 * @return If you handled the event, return true. If you want to allow the 7675 * event to be handled by the next receiver, return false. 7676 */ 7677 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 7678 return false; 7679 } 7680 7681 /** 7682 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 7683 * KeyEvent.Callback.onKeyDown()}: perform press of the view 7684 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 7685 * is released, if the view is enabled and clickable. 7686 * 7687 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7688 * although some may elect to do so in some situations. Do not rely on this to 7689 * catch software key presses. 7690 * 7691 * @param keyCode A key code that represents the button pressed, from 7692 * {@link android.view.KeyEvent}. 7693 * @param event The KeyEvent object that defines the button action. 7694 */ 7695 public boolean onKeyDown(int keyCode, KeyEvent event) { 7696 boolean result = false; 7697 7698 switch (keyCode) { 7699 case KeyEvent.KEYCODE_DPAD_CENTER: 7700 case KeyEvent.KEYCODE_ENTER: { 7701 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7702 return true; 7703 } 7704 // Long clickable items don't necessarily have to be clickable 7705 if (((mViewFlags & CLICKABLE) == CLICKABLE || 7706 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 7707 (event.getRepeatCount() == 0)) { 7708 setPressed(true); 7709 checkForLongClick(0); 7710 return true; 7711 } 7712 break; 7713 } 7714 } 7715 return result; 7716 } 7717 7718 /** 7719 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 7720 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 7721 * the event). 7722 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7723 * although some may elect to do so in some situations. Do not rely on this to 7724 * catch software key presses. 7725 */ 7726 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 7727 return false; 7728 } 7729 7730 /** 7731 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 7732 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 7733 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 7734 * {@link KeyEvent#KEYCODE_ENTER} is released. 7735 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7736 * although some may elect to do so in some situations. Do not rely on this to 7737 * catch software key presses. 7738 * 7739 * @param keyCode A key code that represents the button pressed, from 7740 * {@link android.view.KeyEvent}. 7741 * @param event The KeyEvent object that defines the button action. 7742 */ 7743 public boolean onKeyUp(int keyCode, KeyEvent event) { 7744 boolean result = false; 7745 7746 switch (keyCode) { 7747 case KeyEvent.KEYCODE_DPAD_CENTER: 7748 case KeyEvent.KEYCODE_ENTER: { 7749 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7750 return true; 7751 } 7752 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 7753 setPressed(false); 7754 7755 if (!mHasPerformedLongPress) { 7756 // This is a tap, so remove the longpress check 7757 removeLongPressCallback(); 7758 7759 result = performClick(); 7760 } 7761 } 7762 break; 7763 } 7764 } 7765 return result; 7766 } 7767 7768 /** 7769 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 7770 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 7771 * the event). 7772 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7773 * although some may elect to do so in some situations. Do not rely on this to 7774 * catch software key presses. 7775 * 7776 * @param keyCode A key code that represents the button pressed, from 7777 * {@link android.view.KeyEvent}. 7778 * @param repeatCount The number of times the action was made. 7779 * @param event The KeyEvent object that defines the button action. 7780 */ 7781 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 7782 return false; 7783 } 7784 7785 /** 7786 * Called on the focused view when a key shortcut event is not handled. 7787 * Override this method to implement local key shortcuts for the View. 7788 * Key shortcuts can also be implemented by setting the 7789 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 7790 * 7791 * @param keyCode The value in event.getKeyCode(). 7792 * @param event Description of the key event. 7793 * @return If you handled the event, return true. If you want to allow the 7794 * event to be handled by the next receiver, return false. 7795 */ 7796 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 7797 return false; 7798 } 7799 7800 /** 7801 * Check whether the called view is a text editor, in which case it 7802 * would make sense to automatically display a soft input window for 7803 * it. Subclasses should override this if they implement 7804 * {@link #onCreateInputConnection(EditorInfo)} to return true if 7805 * a call on that method would return a non-null InputConnection, and 7806 * they are really a first-class editor that the user would normally 7807 * start typing on when the go into a window containing your view. 7808 * 7809 * <p>The default implementation always returns false. This does 7810 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 7811 * will not be called or the user can not otherwise perform edits on your 7812 * view; it is just a hint to the system that this is not the primary 7813 * purpose of this view. 7814 * 7815 * @return Returns true if this view is a text editor, else false. 7816 */ 7817 public boolean onCheckIsTextEditor() { 7818 return false; 7819 } 7820 7821 /** 7822 * Create a new InputConnection for an InputMethod to interact 7823 * with the view. The default implementation returns null, since it doesn't 7824 * support input methods. You can override this to implement such support. 7825 * This is only needed for views that take focus and text input. 7826 * 7827 * <p>When implementing this, you probably also want to implement 7828 * {@link #onCheckIsTextEditor()} to indicate you will return a 7829 * non-null InputConnection. 7830 * 7831 * @param outAttrs Fill in with attribute information about the connection. 7832 */ 7833 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 7834 return null; 7835 } 7836 7837 /** 7838 * Called by the {@link android.view.inputmethod.InputMethodManager} 7839 * when a view who is not the current 7840 * input connection target is trying to make a call on the manager. The 7841 * default implementation returns false; you can override this to return 7842 * true for certain views if you are performing InputConnection proxying 7843 * to them. 7844 * @param view The View that is making the InputMethodManager call. 7845 * @return Return true to allow the call, false to reject. 7846 */ 7847 public boolean checkInputConnectionProxy(View view) { 7848 return false; 7849 } 7850 7851 /** 7852 * Show the context menu for this view. It is not safe to hold on to the 7853 * menu after returning from this method. 7854 * 7855 * You should normally not overload this method. Overload 7856 * {@link #onCreateContextMenu(ContextMenu)} or define an 7857 * {@link OnCreateContextMenuListener} to add items to the context menu. 7858 * 7859 * @param menu The context menu to populate 7860 */ 7861 public void createContextMenu(ContextMenu menu) { 7862 ContextMenuInfo menuInfo = getContextMenuInfo(); 7863 7864 // Sets the current menu info so all items added to menu will have 7865 // my extra info set. 7866 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 7867 7868 onCreateContextMenu(menu); 7869 ListenerInfo li = mListenerInfo; 7870 if (li != null && li.mOnCreateContextMenuListener != null) { 7871 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 7872 } 7873 7874 // Clear the extra information so subsequent items that aren't mine don't 7875 // have my extra info. 7876 ((MenuBuilder)menu).setCurrentMenuInfo(null); 7877 7878 if (mParent != null) { 7879 mParent.createContextMenu(menu); 7880 } 7881 } 7882 7883 /** 7884 * Views should implement this if they have extra information to associate 7885 * with the context menu. The return result is supplied as a parameter to 7886 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 7887 * callback. 7888 * 7889 * @return Extra information about the item for which the context menu 7890 * should be shown. This information will vary across different 7891 * subclasses of View. 7892 */ 7893 protected ContextMenuInfo getContextMenuInfo() { 7894 return null; 7895 } 7896 7897 /** 7898 * Views should implement this if the view itself is going to add items to 7899 * the context menu. 7900 * 7901 * @param menu the context menu to populate 7902 */ 7903 protected void onCreateContextMenu(ContextMenu menu) { 7904 } 7905 7906 /** 7907 * Implement this method to handle trackball motion events. The 7908 * <em>relative</em> movement of the trackball since the last event 7909 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 7910 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 7911 * that a movement of 1 corresponds to the user pressing one DPAD key (so 7912 * they will often be fractional values, representing the more fine-grained 7913 * movement information available from a trackball). 7914 * 7915 * @param event The motion event. 7916 * @return True if the event was handled, false otherwise. 7917 */ 7918 public boolean onTrackballEvent(MotionEvent event) { 7919 return false; 7920 } 7921 7922 /** 7923 * Implement this method to handle generic motion events. 7924 * <p> 7925 * Generic motion events describe joystick movements, mouse hovers, track pad 7926 * touches, scroll wheel movements and other input events. The 7927 * {@link MotionEvent#getSource() source} of the motion event specifies 7928 * the class of input that was received. Implementations of this method 7929 * must examine the bits in the source before processing the event. 7930 * The following code example shows how this is done. 7931 * </p><p> 7932 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7933 * are delivered to the view under the pointer. All other generic motion events are 7934 * delivered to the focused view. 7935 * </p> 7936 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 7937 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 7938 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 7939 * // process the joystick movement... 7940 * return true; 7941 * } 7942 * } 7943 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7944 * switch (event.getAction()) { 7945 * case MotionEvent.ACTION_HOVER_MOVE: 7946 * // process the mouse hover movement... 7947 * return true; 7948 * case MotionEvent.ACTION_SCROLL: 7949 * // process the scroll wheel movement... 7950 * return true; 7951 * } 7952 * } 7953 * return super.onGenericMotionEvent(event); 7954 * }</pre> 7955 * 7956 * @param event The generic motion event being processed. 7957 * @return True if the event was handled, false otherwise. 7958 */ 7959 public boolean onGenericMotionEvent(MotionEvent event) { 7960 return false; 7961 } 7962 7963 /** 7964 * Implement this method to handle hover events. 7965 * <p> 7966 * This method is called whenever a pointer is hovering into, over, or out of the 7967 * bounds of a view and the view is not currently being touched. 7968 * Hover events are represented as pointer events with action 7969 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 7970 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 7971 * </p> 7972 * <ul> 7973 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 7974 * when the pointer enters the bounds of the view.</li> 7975 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 7976 * when the pointer has already entered the bounds of the view and has moved.</li> 7977 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 7978 * when the pointer has exited the bounds of the view or when the pointer is 7979 * about to go down due to a button click, tap, or similar user action that 7980 * causes the view to be touched.</li> 7981 * </ul> 7982 * <p> 7983 * The view should implement this method to return true to indicate that it is 7984 * handling the hover event, such as by changing its drawable state. 7985 * </p><p> 7986 * The default implementation calls {@link #setHovered} to update the hovered state 7987 * of the view when a hover enter or hover exit event is received, if the view 7988 * is enabled and is clickable. The default implementation also sends hover 7989 * accessibility events. 7990 * </p> 7991 * 7992 * @param event The motion event that describes the hover. 7993 * @return True if the view handled the hover event. 7994 * 7995 * @see #isHovered 7996 * @see #setHovered 7997 * @see #onHoverChanged 7998 */ 7999 public boolean onHoverEvent(MotionEvent event) { 8000 // The root view may receive hover (or touch) events that are outside the bounds of 8001 // the window. This code ensures that we only send accessibility events for 8002 // hovers that are actually within the bounds of the root view. 8003 final int action = event.getActionMasked(); 8004 if (!mSendingHoverAccessibilityEvents) { 8005 if ((action == MotionEvent.ACTION_HOVER_ENTER 8006 || action == MotionEvent.ACTION_HOVER_MOVE) 8007 && !hasHoveredChild() 8008 && pointInView(event.getX(), event.getY())) { 8009 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8010 mSendingHoverAccessibilityEvents = true; 8011 } 8012 } else { 8013 if (action == MotionEvent.ACTION_HOVER_EXIT 8014 || (action == MotionEvent.ACTION_MOVE 8015 && !pointInView(event.getX(), event.getY()))) { 8016 mSendingHoverAccessibilityEvents = false; 8017 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8018 // If the window does not have input focus we take away accessibility 8019 // focus as soon as the user stop hovering over the view. 8020 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 8021 getViewRootImpl().setAccessibilityFocus(null, null); 8022 } 8023 } 8024 } 8025 8026 if (isHoverable()) { 8027 switch (action) { 8028 case MotionEvent.ACTION_HOVER_ENTER: 8029 setHovered(true); 8030 break; 8031 case MotionEvent.ACTION_HOVER_EXIT: 8032 setHovered(false); 8033 break; 8034 } 8035 8036 // Dispatch the event to onGenericMotionEvent before returning true. 8037 // This is to provide compatibility with existing applications that 8038 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8039 // break because of the new default handling for hoverable views 8040 // in onHoverEvent. 8041 // Note that onGenericMotionEvent will be called by default when 8042 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8043 dispatchGenericMotionEventInternal(event); 8044 return true; 8045 } 8046 8047 return false; 8048 } 8049 8050 /** 8051 * Returns true if the view should handle {@link #onHoverEvent} 8052 * by calling {@link #setHovered} to change its hovered state. 8053 * 8054 * @return True if the view is hoverable. 8055 */ 8056 private boolean isHoverable() { 8057 final int viewFlags = mViewFlags; 8058 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8059 return false; 8060 } 8061 8062 return (viewFlags & CLICKABLE) == CLICKABLE 8063 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8064 } 8065 8066 /** 8067 * Returns true if the view is currently hovered. 8068 * 8069 * @return True if the view is currently hovered. 8070 * 8071 * @see #setHovered 8072 * @see #onHoverChanged 8073 */ 8074 @ViewDebug.ExportedProperty 8075 public boolean isHovered() { 8076 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8077 } 8078 8079 /** 8080 * Sets whether the view is currently hovered. 8081 * <p> 8082 * Calling this method also changes the drawable state of the view. This 8083 * enables the view to react to hover by using different drawable resources 8084 * to change its appearance. 8085 * </p><p> 8086 * The {@link #onHoverChanged} method is called when the hovered state changes. 8087 * </p> 8088 * 8089 * @param hovered True if the view is hovered. 8090 * 8091 * @see #isHovered 8092 * @see #onHoverChanged 8093 */ 8094 public void setHovered(boolean hovered) { 8095 if (hovered) { 8096 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8097 mPrivateFlags |= PFLAG_HOVERED; 8098 refreshDrawableState(); 8099 onHoverChanged(true); 8100 } 8101 } else { 8102 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8103 mPrivateFlags &= ~PFLAG_HOVERED; 8104 refreshDrawableState(); 8105 onHoverChanged(false); 8106 } 8107 } 8108 } 8109 8110 /** 8111 * Implement this method to handle hover state changes. 8112 * <p> 8113 * This method is called whenever the hover state changes as a result of a 8114 * call to {@link #setHovered}. 8115 * </p> 8116 * 8117 * @param hovered The current hover state, as returned by {@link #isHovered}. 8118 * 8119 * @see #isHovered 8120 * @see #setHovered 8121 */ 8122 public void onHoverChanged(boolean hovered) { 8123 } 8124 8125 /** 8126 * Implement this method to handle touch screen motion events. 8127 * 8128 * @param event The motion event. 8129 * @return True if the event was handled, false otherwise. 8130 */ 8131 public boolean onTouchEvent(MotionEvent event) { 8132 final int viewFlags = mViewFlags; 8133 8134 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8135 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8136 setPressed(false); 8137 } 8138 // A disabled view that is clickable still consumes the touch 8139 // events, it just doesn't respond to them. 8140 return (((viewFlags & CLICKABLE) == CLICKABLE || 8141 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8142 } 8143 8144 if (mTouchDelegate != null) { 8145 if (mTouchDelegate.onTouchEvent(event)) { 8146 return true; 8147 } 8148 } 8149 8150 if (((viewFlags & CLICKABLE) == CLICKABLE || 8151 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8152 switch (event.getAction()) { 8153 case MotionEvent.ACTION_UP: 8154 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8155 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8156 // take focus if we don't have it already and we should in 8157 // touch mode. 8158 boolean focusTaken = false; 8159 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8160 focusTaken = requestFocus(); 8161 } 8162 8163 if (prepressed) { 8164 // The button is being released before we actually 8165 // showed it as pressed. Make it show the pressed 8166 // state now (before scheduling the click) to ensure 8167 // the user sees it. 8168 setPressed(true); 8169 } 8170 8171 if (!mHasPerformedLongPress) { 8172 // This is a tap, so remove the longpress check 8173 removeLongPressCallback(); 8174 8175 // Only perform take click actions if we were in the pressed state 8176 if (!focusTaken) { 8177 // Use a Runnable and post this rather than calling 8178 // performClick directly. This lets other visual state 8179 // of the view update before click actions start. 8180 if (mPerformClick == null) { 8181 mPerformClick = new PerformClick(); 8182 } 8183 if (!post(mPerformClick)) { 8184 performClick(); 8185 } 8186 } 8187 } 8188 8189 if (mUnsetPressedState == null) { 8190 mUnsetPressedState = new UnsetPressedState(); 8191 } 8192 8193 if (prepressed) { 8194 postDelayed(mUnsetPressedState, 8195 ViewConfiguration.getPressedStateDuration()); 8196 } else if (!post(mUnsetPressedState)) { 8197 // If the post failed, unpress right now 8198 mUnsetPressedState.run(); 8199 } 8200 removeTapCallback(); 8201 } 8202 break; 8203 8204 case MotionEvent.ACTION_DOWN: 8205 mHasPerformedLongPress = false; 8206 8207 if (performButtonActionOnTouchDown(event)) { 8208 break; 8209 } 8210 8211 // Walk up the hierarchy to determine if we're inside a scrolling container. 8212 boolean isInScrollingContainer = isInScrollingContainer(); 8213 8214 // For views inside a scrolling container, delay the pressed feedback for 8215 // a short period in case this is a scroll. 8216 if (isInScrollingContainer) { 8217 mPrivateFlags |= PFLAG_PREPRESSED; 8218 if (mPendingCheckForTap == null) { 8219 mPendingCheckForTap = new CheckForTap(); 8220 } 8221 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 8222 } else { 8223 // Not inside a scrolling container, so show the feedback right away 8224 setPressed(true); 8225 checkForLongClick(0); 8226 } 8227 break; 8228 8229 case MotionEvent.ACTION_CANCEL: 8230 setPressed(false); 8231 removeTapCallback(); 8232 break; 8233 8234 case MotionEvent.ACTION_MOVE: 8235 final int x = (int) event.getX(); 8236 final int y = (int) event.getY(); 8237 8238 // Be lenient about moving outside of buttons 8239 if (!pointInView(x, y, mTouchSlop)) { 8240 // Outside button 8241 removeTapCallback(); 8242 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 8243 // Remove any future long press/tap checks 8244 removeLongPressCallback(); 8245 8246 setPressed(false); 8247 } 8248 } 8249 break; 8250 } 8251 return true; 8252 } 8253 8254 return false; 8255 } 8256 8257 /** 8258 * @hide 8259 */ 8260 public boolean isInScrollingContainer() { 8261 ViewParent p = getParent(); 8262 while (p != null && p instanceof ViewGroup) { 8263 if (((ViewGroup) p).shouldDelayChildPressedState()) { 8264 return true; 8265 } 8266 p = p.getParent(); 8267 } 8268 return false; 8269 } 8270 8271 /** 8272 * Remove the longpress detection timer. 8273 */ 8274 private void removeLongPressCallback() { 8275 if (mPendingCheckForLongPress != null) { 8276 removeCallbacks(mPendingCheckForLongPress); 8277 } 8278 } 8279 8280 /** 8281 * Remove the pending click action 8282 */ 8283 private void removePerformClickCallback() { 8284 if (mPerformClick != null) { 8285 removeCallbacks(mPerformClick); 8286 } 8287 } 8288 8289 /** 8290 * Remove the prepress detection timer. 8291 */ 8292 private void removeUnsetPressCallback() { 8293 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 8294 setPressed(false); 8295 removeCallbacks(mUnsetPressedState); 8296 } 8297 } 8298 8299 /** 8300 * Remove the tap detection timer. 8301 */ 8302 private void removeTapCallback() { 8303 if (mPendingCheckForTap != null) { 8304 mPrivateFlags &= ~PFLAG_PREPRESSED; 8305 removeCallbacks(mPendingCheckForTap); 8306 } 8307 } 8308 8309 /** 8310 * Cancels a pending long press. Your subclass can use this if you 8311 * want the context menu to come up if the user presses and holds 8312 * at the same place, but you don't want it to come up if they press 8313 * and then move around enough to cause scrolling. 8314 */ 8315 public void cancelLongPress() { 8316 removeLongPressCallback(); 8317 8318 /* 8319 * The prepressed state handled by the tap callback is a display 8320 * construct, but the tap callback will post a long press callback 8321 * less its own timeout. Remove it here. 8322 */ 8323 removeTapCallback(); 8324 } 8325 8326 /** 8327 * Remove the pending callback for sending a 8328 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 8329 */ 8330 private void removeSendViewScrolledAccessibilityEventCallback() { 8331 if (mSendViewScrolledAccessibilityEvent != null) { 8332 removeCallbacks(mSendViewScrolledAccessibilityEvent); 8333 mSendViewScrolledAccessibilityEvent.mIsPending = false; 8334 } 8335 } 8336 8337 /** 8338 * Sets the TouchDelegate for this View. 8339 */ 8340 public void setTouchDelegate(TouchDelegate delegate) { 8341 mTouchDelegate = delegate; 8342 } 8343 8344 /** 8345 * Gets the TouchDelegate for this View. 8346 */ 8347 public TouchDelegate getTouchDelegate() { 8348 return mTouchDelegate; 8349 } 8350 8351 /** 8352 * Set flags controlling behavior of this view. 8353 * 8354 * @param flags Constant indicating the value which should be set 8355 * @param mask Constant indicating the bit range that should be changed 8356 */ 8357 void setFlags(int flags, int mask) { 8358 int old = mViewFlags; 8359 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 8360 8361 int changed = mViewFlags ^ old; 8362 if (changed == 0) { 8363 return; 8364 } 8365 int privateFlags = mPrivateFlags; 8366 8367 /* Check if the FOCUSABLE bit has changed */ 8368 if (((changed & FOCUSABLE_MASK) != 0) && 8369 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 8370 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 8371 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 8372 /* Give up focus if we are no longer focusable */ 8373 clearFocus(); 8374 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 8375 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 8376 /* 8377 * Tell the view system that we are now available to take focus 8378 * if no one else already has it. 8379 */ 8380 if (mParent != null) mParent.focusableViewAvailable(this); 8381 } 8382 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8383 notifyAccessibilityStateChanged(); 8384 } 8385 } 8386 8387 if ((flags & VISIBILITY_MASK) == VISIBLE) { 8388 if ((changed & VISIBILITY_MASK) != 0) { 8389 /* 8390 * If this view is becoming visible, invalidate it in case it changed while 8391 * it was not visible. Marking it drawn ensures that the invalidation will 8392 * go through. 8393 */ 8394 mPrivateFlags |= PFLAG_DRAWN; 8395 invalidate(true); 8396 8397 needGlobalAttributesUpdate(true); 8398 8399 // a view becoming visible is worth notifying the parent 8400 // about in case nothing has focus. even if this specific view 8401 // isn't focusable, it may contain something that is, so let 8402 // the root view try to give this focus if nothing else does. 8403 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 8404 mParent.focusableViewAvailable(this); 8405 } 8406 } 8407 } 8408 8409 /* Check if the GONE bit has changed */ 8410 if ((changed & GONE) != 0) { 8411 needGlobalAttributesUpdate(false); 8412 requestLayout(); 8413 8414 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 8415 if (hasFocus()) clearFocus(); 8416 clearAccessibilityFocus(); 8417 destroyDrawingCache(); 8418 if (mParent instanceof View) { 8419 // GONE views noop invalidation, so invalidate the parent 8420 ((View) mParent).invalidate(true); 8421 } 8422 // Mark the view drawn to ensure that it gets invalidated properly the next 8423 // time it is visible and gets invalidated 8424 mPrivateFlags |= PFLAG_DRAWN; 8425 } 8426 if (mAttachInfo != null) { 8427 mAttachInfo.mViewVisibilityChanged = true; 8428 } 8429 } 8430 8431 /* Check if the VISIBLE bit has changed */ 8432 if ((changed & INVISIBLE) != 0) { 8433 needGlobalAttributesUpdate(false); 8434 /* 8435 * If this view is becoming invisible, set the DRAWN flag so that 8436 * the next invalidate() will not be skipped. 8437 */ 8438 mPrivateFlags |= PFLAG_DRAWN; 8439 8440 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 8441 // root view becoming invisible shouldn't clear focus and accessibility focus 8442 if (getRootView() != this) { 8443 clearFocus(); 8444 clearAccessibilityFocus(); 8445 } 8446 } 8447 if (mAttachInfo != null) { 8448 mAttachInfo.mViewVisibilityChanged = true; 8449 } 8450 } 8451 8452 if ((changed & VISIBILITY_MASK) != 0) { 8453 if (mParent instanceof ViewGroup) { 8454 ((ViewGroup) mParent).onChildVisibilityChanged(this, 8455 (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK)); 8456 ((View) mParent).invalidate(true); 8457 } else if (mParent != null) { 8458 mParent.invalidateChild(this, null); 8459 } 8460 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 8461 } 8462 8463 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 8464 destroyDrawingCache(); 8465 } 8466 8467 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 8468 destroyDrawingCache(); 8469 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8470 invalidateParentCaches(); 8471 } 8472 8473 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 8474 destroyDrawingCache(); 8475 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8476 } 8477 8478 if ((changed & DRAW_MASK) != 0) { 8479 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 8480 if (mBackground != null) { 8481 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8482 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 8483 } else { 8484 mPrivateFlags |= PFLAG_SKIP_DRAW; 8485 } 8486 } else { 8487 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8488 } 8489 requestLayout(); 8490 invalidate(true); 8491 } 8492 8493 if ((changed & KEEP_SCREEN_ON) != 0) { 8494 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 8495 mParent.recomputeViewAttributes(this); 8496 } 8497 } 8498 8499 if (AccessibilityManager.getInstance(mContext).isEnabled() 8500 && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0 8501 || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) { 8502 notifyAccessibilityStateChanged(); 8503 } 8504 } 8505 8506 /** 8507 * Change the view's z order in the tree, so it's on top of other sibling 8508 * views 8509 */ 8510 public void bringToFront() { 8511 if (mParent != null) { 8512 mParent.bringChildToFront(this); 8513 } 8514 } 8515 8516 /** 8517 * This is called in response to an internal scroll in this view (i.e., the 8518 * view scrolled its own contents). This is typically as a result of 8519 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 8520 * called. 8521 * 8522 * @param l Current horizontal scroll origin. 8523 * @param t Current vertical scroll origin. 8524 * @param oldl Previous horizontal scroll origin. 8525 * @param oldt Previous vertical scroll origin. 8526 */ 8527 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 8528 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8529 postSendViewScrolledAccessibilityEventCallback(); 8530 } 8531 8532 mBackgroundSizeChanged = true; 8533 8534 final AttachInfo ai = mAttachInfo; 8535 if (ai != null) { 8536 ai.mViewScrollChanged = true; 8537 } 8538 } 8539 8540 /** 8541 * Interface definition for a callback to be invoked when the layout bounds of a view 8542 * changes due to layout processing. 8543 */ 8544 public interface OnLayoutChangeListener { 8545 /** 8546 * Called when the focus state of a view has changed. 8547 * 8548 * @param v The view whose state has changed. 8549 * @param left The new value of the view's left property. 8550 * @param top The new value of the view's top property. 8551 * @param right The new value of the view's right property. 8552 * @param bottom The new value of the view's bottom property. 8553 * @param oldLeft The previous value of the view's left property. 8554 * @param oldTop The previous value of the view's top property. 8555 * @param oldRight The previous value of the view's right property. 8556 * @param oldBottom The previous value of the view's bottom property. 8557 */ 8558 void onLayoutChange(View v, int left, int top, int right, int bottom, 8559 int oldLeft, int oldTop, int oldRight, int oldBottom); 8560 } 8561 8562 /** 8563 * This is called during layout when the size of this view has changed. If 8564 * you were just added to the view hierarchy, you're called with the old 8565 * values of 0. 8566 * 8567 * @param w Current width of this view. 8568 * @param h Current height of this view. 8569 * @param oldw Old width of this view. 8570 * @param oldh Old height of this view. 8571 */ 8572 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 8573 } 8574 8575 /** 8576 * Called by draw to draw the child views. This may be overridden 8577 * by derived classes to gain control just before its children are drawn 8578 * (but after its own view has been drawn). 8579 * @param canvas the canvas on which to draw the view 8580 */ 8581 protected void dispatchDraw(Canvas canvas) { 8582 8583 } 8584 8585 /** 8586 * Gets the parent of this view. Note that the parent is a 8587 * ViewParent and not necessarily a View. 8588 * 8589 * @return Parent of this view. 8590 */ 8591 public final ViewParent getParent() { 8592 return mParent; 8593 } 8594 8595 /** 8596 * Set the horizontal scrolled position of your view. This will cause a call to 8597 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8598 * invalidated. 8599 * @param value the x position to scroll to 8600 */ 8601 public void setScrollX(int value) { 8602 scrollTo(value, mScrollY); 8603 } 8604 8605 /** 8606 * Set the vertical scrolled position of your view. This will cause a call to 8607 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8608 * invalidated. 8609 * @param value the y position to scroll to 8610 */ 8611 public void setScrollY(int value) { 8612 scrollTo(mScrollX, value); 8613 } 8614 8615 /** 8616 * Return the scrolled left position of this view. This is the left edge of 8617 * the displayed part of your view. You do not need to draw any pixels 8618 * farther left, since those are outside of the frame of your view on 8619 * screen. 8620 * 8621 * @return The left edge of the displayed part of your view, in pixels. 8622 */ 8623 public final int getScrollX() { 8624 return mScrollX; 8625 } 8626 8627 /** 8628 * Return the scrolled top position of this view. This is the top edge of 8629 * the displayed part of your view. You do not need to draw any pixels above 8630 * it, since those are outside of the frame of your view on screen. 8631 * 8632 * @return The top edge of the displayed part of your view, in pixels. 8633 */ 8634 public final int getScrollY() { 8635 return mScrollY; 8636 } 8637 8638 /** 8639 * Return the width of the your view. 8640 * 8641 * @return The width of your view, in pixels. 8642 */ 8643 @ViewDebug.ExportedProperty(category = "layout") 8644 public final int getWidth() { 8645 return mRight - mLeft; 8646 } 8647 8648 /** 8649 * Return the height of your view. 8650 * 8651 * @return The height of your view, in pixels. 8652 */ 8653 @ViewDebug.ExportedProperty(category = "layout") 8654 public final int getHeight() { 8655 return mBottom - mTop; 8656 } 8657 8658 /** 8659 * Return the visible drawing bounds of your view. Fills in the output 8660 * rectangle with the values from getScrollX(), getScrollY(), 8661 * getWidth(), and getHeight(). 8662 * 8663 * @param outRect The (scrolled) drawing bounds of the view. 8664 */ 8665 public void getDrawingRect(Rect outRect) { 8666 outRect.left = mScrollX; 8667 outRect.top = mScrollY; 8668 outRect.right = mScrollX + (mRight - mLeft); 8669 outRect.bottom = mScrollY + (mBottom - mTop); 8670 } 8671 8672 /** 8673 * Like {@link #getMeasuredWidthAndState()}, but only returns the 8674 * raw width component (that is the result is masked by 8675 * {@link #MEASURED_SIZE_MASK}). 8676 * 8677 * @return The raw measured width of this view. 8678 */ 8679 public final int getMeasuredWidth() { 8680 return mMeasuredWidth & MEASURED_SIZE_MASK; 8681 } 8682 8683 /** 8684 * Return the full width measurement information for this view as computed 8685 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8686 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8687 * This should be used during measurement and layout calculations only. Use 8688 * {@link #getWidth()} to see how wide a view is after layout. 8689 * 8690 * @return The measured width of this view as a bit mask. 8691 */ 8692 public final int getMeasuredWidthAndState() { 8693 return mMeasuredWidth; 8694 } 8695 8696 /** 8697 * Like {@link #getMeasuredHeightAndState()}, but only returns the 8698 * raw width component (that is the result is masked by 8699 * {@link #MEASURED_SIZE_MASK}). 8700 * 8701 * @return The raw measured height of this view. 8702 */ 8703 public final int getMeasuredHeight() { 8704 return mMeasuredHeight & MEASURED_SIZE_MASK; 8705 } 8706 8707 /** 8708 * Return the full height measurement information for this view as computed 8709 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8710 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8711 * This should be used during measurement and layout calculations only. Use 8712 * {@link #getHeight()} to see how wide a view is after layout. 8713 * 8714 * @return The measured width of this view as a bit mask. 8715 */ 8716 public final int getMeasuredHeightAndState() { 8717 return mMeasuredHeight; 8718 } 8719 8720 /** 8721 * Return only the state bits of {@link #getMeasuredWidthAndState()} 8722 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 8723 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 8724 * and the height component is at the shifted bits 8725 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 8726 */ 8727 public final int getMeasuredState() { 8728 return (mMeasuredWidth&MEASURED_STATE_MASK) 8729 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 8730 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 8731 } 8732 8733 /** 8734 * The transform matrix of this view, which is calculated based on the current 8735 * roation, scale, and pivot properties. 8736 * 8737 * @see #getRotation() 8738 * @see #getScaleX() 8739 * @see #getScaleY() 8740 * @see #getPivotX() 8741 * @see #getPivotY() 8742 * @return The current transform matrix for the view 8743 */ 8744 public Matrix getMatrix() { 8745 if (mTransformationInfo != null) { 8746 updateMatrix(); 8747 return mTransformationInfo.mMatrix; 8748 } 8749 return Matrix.IDENTITY_MATRIX; 8750 } 8751 8752 /** 8753 * Utility function to determine if the value is far enough away from zero to be 8754 * considered non-zero. 8755 * @param value A floating point value to check for zero-ness 8756 * @return whether the passed-in value is far enough away from zero to be considered non-zero 8757 */ 8758 private static boolean nonzero(float value) { 8759 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 8760 } 8761 8762 /** 8763 * Returns true if the transform matrix is the identity matrix. 8764 * Recomputes the matrix if necessary. 8765 * 8766 * @return True if the transform matrix is the identity matrix, false otherwise. 8767 */ 8768 final boolean hasIdentityMatrix() { 8769 if (mTransformationInfo != null) { 8770 updateMatrix(); 8771 return mTransformationInfo.mMatrixIsIdentity; 8772 } 8773 return true; 8774 } 8775 8776 void ensureTransformationInfo() { 8777 if (mTransformationInfo == null) { 8778 mTransformationInfo = new TransformationInfo(); 8779 } 8780 } 8781 8782 /** 8783 * Recomputes the transform matrix if necessary. 8784 */ 8785 private void updateMatrix() { 8786 final TransformationInfo info = mTransformationInfo; 8787 if (info == null) { 8788 return; 8789 } 8790 if (info.mMatrixDirty) { 8791 // transform-related properties have changed since the last time someone 8792 // asked for the matrix; recalculate it with the current values 8793 8794 // Figure out if we need to update the pivot point 8795 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 8796 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 8797 info.mPrevWidth = mRight - mLeft; 8798 info.mPrevHeight = mBottom - mTop; 8799 info.mPivotX = info.mPrevWidth / 2f; 8800 info.mPivotY = info.mPrevHeight / 2f; 8801 } 8802 } 8803 info.mMatrix.reset(); 8804 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 8805 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 8806 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 8807 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 8808 } else { 8809 if (info.mCamera == null) { 8810 info.mCamera = new Camera(); 8811 info.matrix3D = new Matrix(); 8812 } 8813 info.mCamera.save(); 8814 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 8815 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 8816 info.mCamera.getMatrix(info.matrix3D); 8817 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 8818 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 8819 info.mPivotY + info.mTranslationY); 8820 info.mMatrix.postConcat(info.matrix3D); 8821 info.mCamera.restore(); 8822 } 8823 info.mMatrixDirty = false; 8824 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 8825 info.mInverseMatrixDirty = true; 8826 } 8827 } 8828 8829 /** 8830 * Utility method to retrieve the inverse of the current mMatrix property. 8831 * We cache the matrix to avoid recalculating it when transform properties 8832 * have not changed. 8833 * 8834 * @return The inverse of the current matrix of this view. 8835 */ 8836 final Matrix getInverseMatrix() { 8837 final TransformationInfo info = mTransformationInfo; 8838 if (info != null) { 8839 updateMatrix(); 8840 if (info.mInverseMatrixDirty) { 8841 if (info.mInverseMatrix == null) { 8842 info.mInverseMatrix = new Matrix(); 8843 } 8844 info.mMatrix.invert(info.mInverseMatrix); 8845 info.mInverseMatrixDirty = false; 8846 } 8847 return info.mInverseMatrix; 8848 } 8849 return Matrix.IDENTITY_MATRIX; 8850 } 8851 8852 /** 8853 * Gets the distance along the Z axis from the camera to this view. 8854 * 8855 * @see #setCameraDistance(float) 8856 * 8857 * @return The distance along the Z axis. 8858 */ 8859 public float getCameraDistance() { 8860 ensureTransformationInfo(); 8861 final float dpi = mResources.getDisplayMetrics().densityDpi; 8862 final TransformationInfo info = mTransformationInfo; 8863 if (info.mCamera == null) { 8864 info.mCamera = new Camera(); 8865 info.matrix3D = new Matrix(); 8866 } 8867 return -(info.mCamera.getLocationZ() * dpi); 8868 } 8869 8870 /** 8871 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 8872 * views are drawn) from the camera to this view. The camera's distance 8873 * affects 3D transformations, for instance rotations around the X and Y 8874 * axis. If the rotationX or rotationY properties are changed and this view is 8875 * large (more than half the size of the screen), it is recommended to always 8876 * use a camera distance that's greater than the height (X axis rotation) or 8877 * the width (Y axis rotation) of this view.</p> 8878 * 8879 * <p>The distance of the camera from the view plane can have an affect on the 8880 * perspective distortion of the view when it is rotated around the x or y axis. 8881 * For example, a large distance will result in a large viewing angle, and there 8882 * will not be much perspective distortion of the view as it rotates. A short 8883 * distance may cause much more perspective distortion upon rotation, and can 8884 * also result in some drawing artifacts if the rotated view ends up partially 8885 * behind the camera (which is why the recommendation is to use a distance at 8886 * least as far as the size of the view, if the view is to be rotated.)</p> 8887 * 8888 * <p>The distance is expressed in "depth pixels." The default distance depends 8889 * on the screen density. For instance, on a medium density display, the 8890 * default distance is 1280. On a high density display, the default distance 8891 * is 1920.</p> 8892 * 8893 * <p>If you want to specify a distance that leads to visually consistent 8894 * results across various densities, use the following formula:</p> 8895 * <pre> 8896 * float scale = context.getResources().getDisplayMetrics().density; 8897 * view.setCameraDistance(distance * scale); 8898 * </pre> 8899 * 8900 * <p>The density scale factor of a high density display is 1.5, 8901 * and 1920 = 1280 * 1.5.</p> 8902 * 8903 * @param distance The distance in "depth pixels", if negative the opposite 8904 * value is used 8905 * 8906 * @see #setRotationX(float) 8907 * @see #setRotationY(float) 8908 */ 8909 public void setCameraDistance(float distance) { 8910 invalidateViewProperty(true, false); 8911 8912 ensureTransformationInfo(); 8913 final float dpi = mResources.getDisplayMetrics().densityDpi; 8914 final TransformationInfo info = mTransformationInfo; 8915 if (info.mCamera == null) { 8916 info.mCamera = new Camera(); 8917 info.matrix3D = new Matrix(); 8918 } 8919 8920 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 8921 info.mMatrixDirty = true; 8922 8923 invalidateViewProperty(false, false); 8924 if (mDisplayList != null) { 8925 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 8926 } 8927 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 8928 // View was rejected last time it was drawn by its parent; this may have changed 8929 invalidateParentIfNeeded(); 8930 } 8931 } 8932 8933 /** 8934 * The degrees that the view is rotated around the pivot point. 8935 * 8936 * @see #setRotation(float) 8937 * @see #getPivotX() 8938 * @see #getPivotY() 8939 * 8940 * @return The degrees of rotation. 8941 */ 8942 @ViewDebug.ExportedProperty(category = "drawing") 8943 public float getRotation() { 8944 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 8945 } 8946 8947 /** 8948 * Sets the degrees that the view is rotated around the pivot point. Increasing values 8949 * result in clockwise rotation. 8950 * 8951 * @param rotation The degrees of rotation. 8952 * 8953 * @see #getRotation() 8954 * @see #getPivotX() 8955 * @see #getPivotY() 8956 * @see #setRotationX(float) 8957 * @see #setRotationY(float) 8958 * 8959 * @attr ref android.R.styleable#View_rotation 8960 */ 8961 public void setRotation(float rotation) { 8962 ensureTransformationInfo(); 8963 final TransformationInfo info = mTransformationInfo; 8964 if (info.mRotation != rotation) { 8965 // Double-invalidation is necessary to capture view's old and new areas 8966 invalidateViewProperty(true, false); 8967 info.mRotation = rotation; 8968 info.mMatrixDirty = true; 8969 invalidateViewProperty(false, true); 8970 if (mDisplayList != null) { 8971 mDisplayList.setRotation(rotation); 8972 } 8973 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 8974 // View was rejected last time it was drawn by its parent; this may have changed 8975 invalidateParentIfNeeded(); 8976 } 8977 } 8978 } 8979 8980 /** 8981 * The degrees that the view is rotated around the vertical axis through the pivot point. 8982 * 8983 * @see #getPivotX() 8984 * @see #getPivotY() 8985 * @see #setRotationY(float) 8986 * 8987 * @return The degrees of Y rotation. 8988 */ 8989 @ViewDebug.ExportedProperty(category = "drawing") 8990 public float getRotationY() { 8991 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 8992 } 8993 8994 /** 8995 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 8996 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 8997 * down the y axis. 8998 * 8999 * When rotating large views, it is recommended to adjust the camera distance 9000 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9001 * 9002 * @param rotationY The degrees of Y rotation. 9003 * 9004 * @see #getRotationY() 9005 * @see #getPivotX() 9006 * @see #getPivotY() 9007 * @see #setRotation(float) 9008 * @see #setRotationX(float) 9009 * @see #setCameraDistance(float) 9010 * 9011 * @attr ref android.R.styleable#View_rotationY 9012 */ 9013 public void setRotationY(float rotationY) { 9014 ensureTransformationInfo(); 9015 final TransformationInfo info = mTransformationInfo; 9016 if (info.mRotationY != rotationY) { 9017 invalidateViewProperty(true, false); 9018 info.mRotationY = rotationY; 9019 info.mMatrixDirty = true; 9020 invalidateViewProperty(false, true); 9021 if (mDisplayList != null) { 9022 mDisplayList.setRotationY(rotationY); 9023 } 9024 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9025 // View was rejected last time it was drawn by its parent; this may have changed 9026 invalidateParentIfNeeded(); 9027 } 9028 } 9029 } 9030 9031 /** 9032 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9033 * 9034 * @see #getPivotX() 9035 * @see #getPivotY() 9036 * @see #setRotationX(float) 9037 * 9038 * @return The degrees of X rotation. 9039 */ 9040 @ViewDebug.ExportedProperty(category = "drawing") 9041 public float getRotationX() { 9042 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 9043 } 9044 9045 /** 9046 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9047 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9048 * x axis. 9049 * 9050 * When rotating large views, it is recommended to adjust the camera distance 9051 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9052 * 9053 * @param rotationX The degrees of X rotation. 9054 * 9055 * @see #getRotationX() 9056 * @see #getPivotX() 9057 * @see #getPivotY() 9058 * @see #setRotation(float) 9059 * @see #setRotationY(float) 9060 * @see #setCameraDistance(float) 9061 * 9062 * @attr ref android.R.styleable#View_rotationX 9063 */ 9064 public void setRotationX(float rotationX) { 9065 ensureTransformationInfo(); 9066 final TransformationInfo info = mTransformationInfo; 9067 if (info.mRotationX != rotationX) { 9068 invalidateViewProperty(true, false); 9069 info.mRotationX = rotationX; 9070 info.mMatrixDirty = true; 9071 invalidateViewProperty(false, true); 9072 if (mDisplayList != null) { 9073 mDisplayList.setRotationX(rotationX); 9074 } 9075 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9076 // View was rejected last time it was drawn by its parent; this may have changed 9077 invalidateParentIfNeeded(); 9078 } 9079 } 9080 } 9081 9082 /** 9083 * The amount that the view is scaled in x around the pivot point, as a proportion of 9084 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9085 * 9086 * <p>By default, this is 1.0f. 9087 * 9088 * @see #getPivotX() 9089 * @see #getPivotY() 9090 * @return The scaling factor. 9091 */ 9092 @ViewDebug.ExportedProperty(category = "drawing") 9093 public float getScaleX() { 9094 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 9095 } 9096 9097 /** 9098 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9099 * the view's unscaled width. A value of 1 means that no scaling is applied. 9100 * 9101 * @param scaleX The scaling factor. 9102 * @see #getPivotX() 9103 * @see #getPivotY() 9104 * 9105 * @attr ref android.R.styleable#View_scaleX 9106 */ 9107 public void setScaleX(float scaleX) { 9108 ensureTransformationInfo(); 9109 final TransformationInfo info = mTransformationInfo; 9110 if (info.mScaleX != scaleX) { 9111 invalidateViewProperty(true, false); 9112 info.mScaleX = scaleX; 9113 info.mMatrixDirty = true; 9114 invalidateViewProperty(false, true); 9115 if (mDisplayList != null) { 9116 mDisplayList.setScaleX(scaleX); 9117 } 9118 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9119 // View was rejected last time it was drawn by its parent; this may have changed 9120 invalidateParentIfNeeded(); 9121 } 9122 } 9123 } 9124 9125 /** 9126 * The amount that the view is scaled in y around the pivot point, as a proportion of 9127 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9128 * 9129 * <p>By default, this is 1.0f. 9130 * 9131 * @see #getPivotX() 9132 * @see #getPivotY() 9133 * @return The scaling factor. 9134 */ 9135 @ViewDebug.ExportedProperty(category = "drawing") 9136 public float getScaleY() { 9137 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 9138 } 9139 9140 /** 9141 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9142 * the view's unscaled width. A value of 1 means that no scaling is applied. 9143 * 9144 * @param scaleY The scaling factor. 9145 * @see #getPivotX() 9146 * @see #getPivotY() 9147 * 9148 * @attr ref android.R.styleable#View_scaleY 9149 */ 9150 public void setScaleY(float scaleY) { 9151 ensureTransformationInfo(); 9152 final TransformationInfo info = mTransformationInfo; 9153 if (info.mScaleY != scaleY) { 9154 invalidateViewProperty(true, false); 9155 info.mScaleY = scaleY; 9156 info.mMatrixDirty = true; 9157 invalidateViewProperty(false, true); 9158 if (mDisplayList != null) { 9159 mDisplayList.setScaleY(scaleY); 9160 } 9161 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9162 // View was rejected last time it was drawn by its parent; this may have changed 9163 invalidateParentIfNeeded(); 9164 } 9165 } 9166 } 9167 9168 /** 9169 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9170 * and {@link #setScaleX(float) scaled}. 9171 * 9172 * @see #getRotation() 9173 * @see #getScaleX() 9174 * @see #getScaleY() 9175 * @see #getPivotY() 9176 * @return The x location of the pivot point. 9177 * 9178 * @attr ref android.R.styleable#View_transformPivotX 9179 */ 9180 @ViewDebug.ExportedProperty(category = "drawing") 9181 public float getPivotX() { 9182 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 9183 } 9184 9185 /** 9186 * Sets the x location of the point around which the view is 9187 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9188 * By default, the pivot point is centered on the object. 9189 * Setting this property disables this behavior and causes the view to use only the 9190 * explicitly set pivotX and pivotY values. 9191 * 9192 * @param pivotX The x location of the pivot point. 9193 * @see #getRotation() 9194 * @see #getScaleX() 9195 * @see #getScaleY() 9196 * @see #getPivotY() 9197 * 9198 * @attr ref android.R.styleable#View_transformPivotX 9199 */ 9200 public void setPivotX(float pivotX) { 9201 ensureTransformationInfo(); 9202 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9203 final TransformationInfo info = mTransformationInfo; 9204 if (info.mPivotX != pivotX) { 9205 invalidateViewProperty(true, false); 9206 info.mPivotX = pivotX; 9207 info.mMatrixDirty = true; 9208 invalidateViewProperty(false, true); 9209 if (mDisplayList != null) { 9210 mDisplayList.setPivotX(pivotX); 9211 } 9212 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9213 // View was rejected last time it was drawn by its parent; this may have changed 9214 invalidateParentIfNeeded(); 9215 } 9216 } 9217 } 9218 9219 /** 9220 * The y location of the point around which the view is {@link #setRotation(float) rotated} 9221 * and {@link #setScaleY(float) scaled}. 9222 * 9223 * @see #getRotation() 9224 * @see #getScaleX() 9225 * @see #getScaleY() 9226 * @see #getPivotY() 9227 * @return The y location of the pivot point. 9228 * 9229 * @attr ref android.R.styleable#View_transformPivotY 9230 */ 9231 @ViewDebug.ExportedProperty(category = "drawing") 9232 public float getPivotY() { 9233 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 9234 } 9235 9236 /** 9237 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 9238 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 9239 * Setting this property disables this behavior and causes the view to use only the 9240 * explicitly set pivotX and pivotY values. 9241 * 9242 * @param pivotY The y location of the pivot point. 9243 * @see #getRotation() 9244 * @see #getScaleX() 9245 * @see #getScaleY() 9246 * @see #getPivotY() 9247 * 9248 * @attr ref android.R.styleable#View_transformPivotY 9249 */ 9250 public void setPivotY(float pivotY) { 9251 ensureTransformationInfo(); 9252 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9253 final TransformationInfo info = mTransformationInfo; 9254 if (info.mPivotY != pivotY) { 9255 invalidateViewProperty(true, false); 9256 info.mPivotY = pivotY; 9257 info.mMatrixDirty = true; 9258 invalidateViewProperty(false, true); 9259 if (mDisplayList != null) { 9260 mDisplayList.setPivotY(pivotY); 9261 } 9262 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9263 // View was rejected last time it was drawn by its parent; this may have changed 9264 invalidateParentIfNeeded(); 9265 } 9266 } 9267 } 9268 9269 /** 9270 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 9271 * completely transparent and 1 means the view is completely opaque. 9272 * 9273 * <p>By default this is 1.0f. 9274 * @return The opacity of the view. 9275 */ 9276 @ViewDebug.ExportedProperty(category = "drawing") 9277 public float getAlpha() { 9278 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 9279 } 9280 9281 /** 9282 * Returns whether this View has content which overlaps. This function, intended to be 9283 * overridden by specific View types, is an optimization when alpha is set on a view. If 9284 * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer 9285 * and then composited it into place, which can be expensive. If the view has no overlapping 9286 * rendering, the view can draw each primitive with the appropriate alpha value directly. 9287 * An example of overlapping rendering is a TextView with a background image, such as a 9288 * Button. An example of non-overlapping rendering is a TextView with no background, or 9289 * an ImageView with only the foreground image. The default implementation returns true; 9290 * subclasses should override if they have cases which can be optimized. 9291 * 9292 * @return true if the content in this view might overlap, false otherwise. 9293 */ 9294 public boolean hasOverlappingRendering() { 9295 return true; 9296 } 9297 9298 /** 9299 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 9300 * completely transparent and 1 means the view is completely opaque.</p> 9301 * 9302 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 9303 * responsible for applying the opacity itself. Otherwise, calling this method is 9304 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 9305 * setting a hardware layer.</p> 9306 * 9307 * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have 9308 * performance implications. It is generally best to use the alpha property sparingly and 9309 * transiently, as in the case of fading animations.</p> 9310 * 9311 * @param alpha The opacity of the view. 9312 * 9313 * @see #setLayerType(int, android.graphics.Paint) 9314 * 9315 * @attr ref android.R.styleable#View_alpha 9316 */ 9317 public void setAlpha(float alpha) { 9318 ensureTransformationInfo(); 9319 if (mTransformationInfo.mAlpha != alpha) { 9320 mTransformationInfo.mAlpha = alpha; 9321 if (onSetAlpha((int) (alpha * 255))) { 9322 mPrivateFlags |= PFLAG_ALPHA_SET; 9323 // subclass is handling alpha - don't optimize rendering cache invalidation 9324 invalidateParentCaches(); 9325 invalidate(true); 9326 } else { 9327 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9328 invalidateViewProperty(true, false); 9329 if (mDisplayList != null) { 9330 mDisplayList.setAlpha(alpha); 9331 } 9332 } 9333 } 9334 } 9335 9336 /** 9337 * Faster version of setAlpha() which performs the same steps except there are 9338 * no calls to invalidate(). The caller of this function should perform proper invalidation 9339 * on the parent and this object. The return value indicates whether the subclass handles 9340 * alpha (the return value for onSetAlpha()). 9341 * 9342 * @param alpha The new value for the alpha property 9343 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 9344 * the new value for the alpha property is different from the old value 9345 */ 9346 boolean setAlphaNoInvalidation(float alpha) { 9347 ensureTransformationInfo(); 9348 if (mTransformationInfo.mAlpha != alpha) { 9349 mTransformationInfo.mAlpha = alpha; 9350 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 9351 if (subclassHandlesAlpha) { 9352 mPrivateFlags |= PFLAG_ALPHA_SET; 9353 return true; 9354 } else { 9355 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9356 if (mDisplayList != null) { 9357 mDisplayList.setAlpha(alpha); 9358 } 9359 } 9360 } 9361 return false; 9362 } 9363 9364 /** 9365 * Top position of this view relative to its parent. 9366 * 9367 * @return The top of this view, in pixels. 9368 */ 9369 @ViewDebug.CapturedViewProperty 9370 public final int getTop() { 9371 return mTop; 9372 } 9373 9374 /** 9375 * Sets the top position of this view relative to its parent. This method is meant to be called 9376 * by the layout system and should not generally be called otherwise, because the property 9377 * may be changed at any time by the layout. 9378 * 9379 * @param top The top of this view, in pixels. 9380 */ 9381 public final void setTop(int top) { 9382 if (top != mTop) { 9383 updateMatrix(); 9384 final boolean matrixIsIdentity = mTransformationInfo == null 9385 || mTransformationInfo.mMatrixIsIdentity; 9386 if (matrixIsIdentity) { 9387 if (mAttachInfo != null) { 9388 int minTop; 9389 int yLoc; 9390 if (top < mTop) { 9391 minTop = top; 9392 yLoc = top - mTop; 9393 } else { 9394 minTop = mTop; 9395 yLoc = 0; 9396 } 9397 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 9398 } 9399 } else { 9400 // Double-invalidation is necessary to capture view's old and new areas 9401 invalidate(true); 9402 } 9403 9404 int width = mRight - mLeft; 9405 int oldHeight = mBottom - mTop; 9406 9407 mTop = top; 9408 if (mDisplayList != null) { 9409 mDisplayList.setTop(mTop); 9410 } 9411 9412 onSizeChanged(width, mBottom - mTop, width, oldHeight); 9413 9414 if (!matrixIsIdentity) { 9415 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9416 // A change in dimension means an auto-centered pivot point changes, too 9417 mTransformationInfo.mMatrixDirty = true; 9418 } 9419 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9420 invalidate(true); 9421 } 9422 mBackgroundSizeChanged = true; 9423 invalidateParentIfNeeded(); 9424 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9425 // View was rejected last time it was drawn by its parent; this may have changed 9426 invalidateParentIfNeeded(); 9427 } 9428 } 9429 } 9430 9431 /** 9432 * Bottom position of this view relative to its parent. 9433 * 9434 * @return The bottom of this view, in pixels. 9435 */ 9436 @ViewDebug.CapturedViewProperty 9437 public final int getBottom() { 9438 return mBottom; 9439 } 9440 9441 /** 9442 * True if this view has changed since the last time being drawn. 9443 * 9444 * @return The dirty state of this view. 9445 */ 9446 public boolean isDirty() { 9447 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 9448 } 9449 9450 /** 9451 * Sets the bottom position of this view relative to its parent. This method is meant to be 9452 * called by the layout system and should not generally be called otherwise, because the 9453 * property may be changed at any time by the layout. 9454 * 9455 * @param bottom The bottom of this view, in pixels. 9456 */ 9457 public final void setBottom(int bottom) { 9458 if (bottom != mBottom) { 9459 updateMatrix(); 9460 final boolean matrixIsIdentity = mTransformationInfo == null 9461 || mTransformationInfo.mMatrixIsIdentity; 9462 if (matrixIsIdentity) { 9463 if (mAttachInfo != null) { 9464 int maxBottom; 9465 if (bottom < mBottom) { 9466 maxBottom = mBottom; 9467 } else { 9468 maxBottom = bottom; 9469 } 9470 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 9471 } 9472 } else { 9473 // Double-invalidation is necessary to capture view's old and new areas 9474 invalidate(true); 9475 } 9476 9477 int width = mRight - mLeft; 9478 int oldHeight = mBottom - mTop; 9479 9480 mBottom = bottom; 9481 if (mDisplayList != null) { 9482 mDisplayList.setBottom(mBottom); 9483 } 9484 9485 onSizeChanged(width, mBottom - mTop, width, oldHeight); 9486 9487 if (!matrixIsIdentity) { 9488 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9489 // A change in dimension means an auto-centered pivot point changes, too 9490 mTransformationInfo.mMatrixDirty = true; 9491 } 9492 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9493 invalidate(true); 9494 } 9495 mBackgroundSizeChanged = true; 9496 invalidateParentIfNeeded(); 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 * Left position of this view relative to its parent. 9506 * 9507 * @return The left edge of this view, in pixels. 9508 */ 9509 @ViewDebug.CapturedViewProperty 9510 public final int getLeft() { 9511 return mLeft; 9512 } 9513 9514 /** 9515 * Sets the left position of this view relative to its parent. This method is meant to be called 9516 * by the layout system and should not generally be called otherwise, because the property 9517 * may be changed at any time by the layout. 9518 * 9519 * @param left The bottom of this view, in pixels. 9520 */ 9521 public final void setLeft(int left) { 9522 if (left != mLeft) { 9523 updateMatrix(); 9524 final boolean matrixIsIdentity = mTransformationInfo == null 9525 || mTransformationInfo.mMatrixIsIdentity; 9526 if (matrixIsIdentity) { 9527 if (mAttachInfo != null) { 9528 int minLeft; 9529 int xLoc; 9530 if (left < mLeft) { 9531 minLeft = left; 9532 xLoc = left - mLeft; 9533 } else { 9534 minLeft = mLeft; 9535 xLoc = 0; 9536 } 9537 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 9538 } 9539 } else { 9540 // Double-invalidation is necessary to capture view's old and new areas 9541 invalidate(true); 9542 } 9543 9544 int oldWidth = mRight - mLeft; 9545 int height = mBottom - mTop; 9546 9547 mLeft = left; 9548 if (mDisplayList != null) { 9549 mDisplayList.setLeft(left); 9550 } 9551 9552 onSizeChanged(mRight - mLeft, height, oldWidth, height); 9553 9554 if (!matrixIsIdentity) { 9555 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9556 // A change in dimension means an auto-centered pivot point changes, too 9557 mTransformationInfo.mMatrixDirty = true; 9558 } 9559 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9560 invalidate(true); 9561 } 9562 mBackgroundSizeChanged = true; 9563 invalidateParentIfNeeded(); 9564 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9565 // View was rejected last time it was drawn by its parent; this may have changed 9566 invalidateParentIfNeeded(); 9567 } 9568 } 9569 } 9570 9571 /** 9572 * Right position of this view relative to its parent. 9573 * 9574 * @return The right edge of this view, in pixels. 9575 */ 9576 @ViewDebug.CapturedViewProperty 9577 public final int getRight() { 9578 return mRight; 9579 } 9580 9581 /** 9582 * Sets the right position of this view relative to its parent. This method is meant to be called 9583 * by the layout system and should not generally be called otherwise, because the property 9584 * may be changed at any time by the layout. 9585 * 9586 * @param right The bottom of this view, in pixels. 9587 */ 9588 public final void setRight(int right) { 9589 if (right != mRight) { 9590 updateMatrix(); 9591 final boolean matrixIsIdentity = mTransformationInfo == null 9592 || mTransformationInfo.mMatrixIsIdentity; 9593 if (matrixIsIdentity) { 9594 if (mAttachInfo != null) { 9595 int maxRight; 9596 if (right < mRight) { 9597 maxRight = mRight; 9598 } else { 9599 maxRight = right; 9600 } 9601 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 9602 } 9603 } else { 9604 // Double-invalidation is necessary to capture view's old and new areas 9605 invalidate(true); 9606 } 9607 9608 int oldWidth = mRight - mLeft; 9609 int height = mBottom - mTop; 9610 9611 mRight = right; 9612 if (mDisplayList != null) { 9613 mDisplayList.setRight(mRight); 9614 } 9615 9616 onSizeChanged(mRight - mLeft, height, oldWidth, height); 9617 9618 if (!matrixIsIdentity) { 9619 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9620 // A change in dimension means an auto-centered pivot point changes, too 9621 mTransformationInfo.mMatrixDirty = true; 9622 } 9623 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9624 invalidate(true); 9625 } 9626 mBackgroundSizeChanged = true; 9627 invalidateParentIfNeeded(); 9628 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9629 // View was rejected last time it was drawn by its parent; this may have changed 9630 invalidateParentIfNeeded(); 9631 } 9632 } 9633 } 9634 9635 /** 9636 * The visual x position of this view, in pixels. This is equivalent to the 9637 * {@link #setTranslationX(float) translationX} property plus the current 9638 * {@link #getLeft() left} property. 9639 * 9640 * @return The visual x position of this view, in pixels. 9641 */ 9642 @ViewDebug.ExportedProperty(category = "drawing") 9643 public float getX() { 9644 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 9645 } 9646 9647 /** 9648 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 9649 * {@link #setTranslationX(float) translationX} property to be the difference between 9650 * the x value passed in and the current {@link #getLeft() left} property. 9651 * 9652 * @param x The visual x position of this view, in pixels. 9653 */ 9654 public void setX(float x) { 9655 setTranslationX(x - mLeft); 9656 } 9657 9658 /** 9659 * The visual y position of this view, in pixels. This is equivalent to the 9660 * {@link #setTranslationY(float) translationY} property plus the current 9661 * {@link #getTop() top} property. 9662 * 9663 * @return The visual y position of this view, in pixels. 9664 */ 9665 @ViewDebug.ExportedProperty(category = "drawing") 9666 public float getY() { 9667 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 9668 } 9669 9670 /** 9671 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 9672 * {@link #setTranslationY(float) translationY} property to be the difference between 9673 * the y value passed in and the current {@link #getTop() top} property. 9674 * 9675 * @param y The visual y position of this view, in pixels. 9676 */ 9677 public void setY(float y) { 9678 setTranslationY(y - mTop); 9679 } 9680 9681 9682 /** 9683 * The horizontal location of this view relative to its {@link #getLeft() left} position. 9684 * This position is post-layout, in addition to wherever the object's 9685 * layout placed it. 9686 * 9687 * @return The horizontal position of this view relative to its left position, in pixels. 9688 */ 9689 @ViewDebug.ExportedProperty(category = "drawing") 9690 public float getTranslationX() { 9691 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 9692 } 9693 9694 /** 9695 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 9696 * This effectively positions the object post-layout, in addition to wherever the object's 9697 * layout placed it. 9698 * 9699 * @param translationX The horizontal position of this view relative to its left position, 9700 * in pixels. 9701 * 9702 * @attr ref android.R.styleable#View_translationX 9703 */ 9704 public void setTranslationX(float translationX) { 9705 ensureTransformationInfo(); 9706 final TransformationInfo info = mTransformationInfo; 9707 if (info.mTranslationX != translationX) { 9708 // Double-invalidation is necessary to capture view's old and new areas 9709 invalidateViewProperty(true, false); 9710 info.mTranslationX = translationX; 9711 info.mMatrixDirty = true; 9712 invalidateViewProperty(false, true); 9713 if (mDisplayList != null) { 9714 mDisplayList.setTranslationX(translationX); 9715 } 9716 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9717 // View was rejected last time it was drawn by its parent; this may have changed 9718 invalidateParentIfNeeded(); 9719 } 9720 } 9721 } 9722 9723 /** 9724 * The horizontal location of this view relative to its {@link #getTop() top} position. 9725 * This position is post-layout, in addition to wherever the object's 9726 * layout placed it. 9727 * 9728 * @return The vertical position of this view relative to its top position, 9729 * in pixels. 9730 */ 9731 @ViewDebug.ExportedProperty(category = "drawing") 9732 public float getTranslationY() { 9733 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 9734 } 9735 9736 /** 9737 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 9738 * This effectively positions the object post-layout, in addition to wherever the object's 9739 * layout placed it. 9740 * 9741 * @param translationY The vertical position of this view relative to its top position, 9742 * in pixels. 9743 * 9744 * @attr ref android.R.styleable#View_translationY 9745 */ 9746 public void setTranslationY(float translationY) { 9747 ensureTransformationInfo(); 9748 final TransformationInfo info = mTransformationInfo; 9749 if (info.mTranslationY != translationY) { 9750 invalidateViewProperty(true, false); 9751 info.mTranslationY = translationY; 9752 info.mMatrixDirty = true; 9753 invalidateViewProperty(false, true); 9754 if (mDisplayList != null) { 9755 mDisplayList.setTranslationY(translationY); 9756 } 9757 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9758 // View was rejected last time it was drawn by its parent; this may have changed 9759 invalidateParentIfNeeded(); 9760 } 9761 } 9762 } 9763 9764 /** 9765 * Hit rectangle in parent's coordinates 9766 * 9767 * @param outRect The hit rectangle of the view. 9768 */ 9769 public void getHitRect(Rect outRect) { 9770 updateMatrix(); 9771 final TransformationInfo info = mTransformationInfo; 9772 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 9773 outRect.set(mLeft, mTop, mRight, mBottom); 9774 } else { 9775 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 9776 tmpRect.set(-info.mPivotX, -info.mPivotY, 9777 getWidth() - info.mPivotX, getHeight() - info.mPivotY); 9778 info.mMatrix.mapRect(tmpRect); 9779 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 9780 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 9781 } 9782 } 9783 9784 /** 9785 * Determines whether the given point, in local coordinates is inside the view. 9786 */ 9787 /*package*/ final boolean pointInView(float localX, float localY) { 9788 return localX >= 0 && localX < (mRight - mLeft) 9789 && localY >= 0 && localY < (mBottom - mTop); 9790 } 9791 9792 /** 9793 * Utility method to determine whether the given point, in local coordinates, 9794 * is inside the view, where the area of the view is expanded by the slop factor. 9795 * This method is called while processing touch-move events to determine if the event 9796 * is still within the view. 9797 */ 9798 private boolean pointInView(float localX, float localY, float slop) { 9799 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 9800 localY < ((mBottom - mTop) + slop); 9801 } 9802 9803 /** 9804 * When a view has focus and the user navigates away from it, the next view is searched for 9805 * starting from the rectangle filled in by this method. 9806 * 9807 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 9808 * of the view. However, if your view maintains some idea of internal selection, 9809 * such as a cursor, or a selected row or column, you should override this method and 9810 * fill in a more specific rectangle. 9811 * 9812 * @param r The rectangle to fill in, in this view's coordinates. 9813 */ 9814 public void getFocusedRect(Rect r) { 9815 getDrawingRect(r); 9816 } 9817 9818 /** 9819 * If some part of this view is not clipped by any of its parents, then 9820 * return that area in r in global (root) coordinates. To convert r to local 9821 * coordinates (without taking possible View rotations into account), offset 9822 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 9823 * If the view is completely clipped or translated out, return false. 9824 * 9825 * @param r If true is returned, r holds the global coordinates of the 9826 * visible portion of this view. 9827 * @param globalOffset If true is returned, globalOffset holds the dx,dy 9828 * between this view and its root. globalOffet may be null. 9829 * @return true if r is non-empty (i.e. part of the view is visible at the 9830 * root level. 9831 */ 9832 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 9833 int width = mRight - mLeft; 9834 int height = mBottom - mTop; 9835 if (width > 0 && height > 0) { 9836 r.set(0, 0, width, height); 9837 if (globalOffset != null) { 9838 globalOffset.set(-mScrollX, -mScrollY); 9839 } 9840 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 9841 } 9842 return false; 9843 } 9844 9845 public final boolean getGlobalVisibleRect(Rect r) { 9846 return getGlobalVisibleRect(r, null); 9847 } 9848 9849 public final boolean getLocalVisibleRect(Rect r) { 9850 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 9851 if (getGlobalVisibleRect(r, offset)) { 9852 r.offset(-offset.x, -offset.y); // make r local 9853 return true; 9854 } 9855 return false; 9856 } 9857 9858 /** 9859 * Offset this view's vertical location by the specified number of pixels. 9860 * 9861 * @param offset the number of pixels to offset the view by 9862 */ 9863 public void offsetTopAndBottom(int offset) { 9864 if (offset != 0) { 9865 updateMatrix(); 9866 final boolean matrixIsIdentity = mTransformationInfo == null 9867 || mTransformationInfo.mMatrixIsIdentity; 9868 if (matrixIsIdentity) { 9869 if (mDisplayList != null) { 9870 invalidateViewProperty(false, false); 9871 } else { 9872 final ViewParent p = mParent; 9873 if (p != null && mAttachInfo != null) { 9874 final Rect r = mAttachInfo.mTmpInvalRect; 9875 int minTop; 9876 int maxBottom; 9877 int yLoc; 9878 if (offset < 0) { 9879 minTop = mTop + offset; 9880 maxBottom = mBottom; 9881 yLoc = offset; 9882 } else { 9883 minTop = mTop; 9884 maxBottom = mBottom + offset; 9885 yLoc = 0; 9886 } 9887 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 9888 p.invalidateChild(this, r); 9889 } 9890 } 9891 } else { 9892 invalidateViewProperty(false, false); 9893 } 9894 9895 mTop += offset; 9896 mBottom += offset; 9897 if (mDisplayList != null) { 9898 mDisplayList.offsetTopBottom(offset); 9899 invalidateViewProperty(false, false); 9900 } else { 9901 if (!matrixIsIdentity) { 9902 invalidateViewProperty(false, true); 9903 } 9904 invalidateParentIfNeeded(); 9905 } 9906 } 9907 } 9908 9909 /** 9910 * Offset this view's horizontal location by the specified amount of pixels. 9911 * 9912 * @param offset the numer of pixels to offset the view by 9913 */ 9914 public void offsetLeftAndRight(int offset) { 9915 if (offset != 0) { 9916 updateMatrix(); 9917 final boolean matrixIsIdentity = mTransformationInfo == null 9918 || mTransformationInfo.mMatrixIsIdentity; 9919 if (matrixIsIdentity) { 9920 if (mDisplayList != null) { 9921 invalidateViewProperty(false, false); 9922 } else { 9923 final ViewParent p = mParent; 9924 if (p != null && mAttachInfo != null) { 9925 final Rect r = mAttachInfo.mTmpInvalRect; 9926 int minLeft; 9927 int maxRight; 9928 if (offset < 0) { 9929 minLeft = mLeft + offset; 9930 maxRight = mRight; 9931 } else { 9932 minLeft = mLeft; 9933 maxRight = mRight + offset; 9934 } 9935 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 9936 p.invalidateChild(this, r); 9937 } 9938 } 9939 } else { 9940 invalidateViewProperty(false, false); 9941 } 9942 9943 mLeft += offset; 9944 mRight += offset; 9945 if (mDisplayList != null) { 9946 mDisplayList.offsetLeftRight(offset); 9947 invalidateViewProperty(false, false); 9948 } else { 9949 if (!matrixIsIdentity) { 9950 invalidateViewProperty(false, true); 9951 } 9952 invalidateParentIfNeeded(); 9953 } 9954 } 9955 } 9956 9957 /** 9958 * Get the LayoutParams associated with this view. All views should have 9959 * layout parameters. These supply parameters to the <i>parent</i> of this 9960 * view specifying how it should be arranged. There are many subclasses of 9961 * ViewGroup.LayoutParams, and these correspond to the different subclasses 9962 * of ViewGroup that are responsible for arranging their children. 9963 * 9964 * This method may return null if this View is not attached to a parent 9965 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 9966 * was not invoked successfully. When a View is attached to a parent 9967 * ViewGroup, this method must not return null. 9968 * 9969 * @return The LayoutParams associated with this view, or null if no 9970 * parameters have been set yet 9971 */ 9972 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 9973 public ViewGroup.LayoutParams getLayoutParams() { 9974 return mLayoutParams; 9975 } 9976 9977 /** 9978 * Set the layout parameters associated with this view. These supply 9979 * parameters to the <i>parent</i> of this view specifying how it should be 9980 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 9981 * correspond to the different subclasses of ViewGroup that are responsible 9982 * for arranging their children. 9983 * 9984 * @param params The layout parameters for this view, cannot be null 9985 */ 9986 public void setLayoutParams(ViewGroup.LayoutParams params) { 9987 if (params == null) { 9988 throw new NullPointerException("Layout parameters cannot be null"); 9989 } 9990 mLayoutParams = params; 9991 resolveLayoutParams(); 9992 if (mParent instanceof ViewGroup) { 9993 ((ViewGroup) mParent).onSetLayoutParams(this, params); 9994 } 9995 requestLayout(); 9996 } 9997 9998 /** 9999 * Resolve the layout parameters depending on the resolved layout direction 10000 */ 10001 private void resolveLayoutParams() { 10002 if (mLayoutParams != null) { 10003 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 10004 } 10005 } 10006 10007 /** 10008 * Set the scrolled position of your view. This will cause a call to 10009 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10010 * invalidated. 10011 * @param x the x position to scroll to 10012 * @param y the y position to scroll to 10013 */ 10014 public void scrollTo(int x, int y) { 10015 if (mScrollX != x || mScrollY != y) { 10016 int oldX = mScrollX; 10017 int oldY = mScrollY; 10018 mScrollX = x; 10019 mScrollY = y; 10020 invalidateParentCaches(); 10021 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 10022 if (!awakenScrollBars()) { 10023 postInvalidateOnAnimation(); 10024 } 10025 } 10026 } 10027 10028 /** 10029 * Move the scrolled position of your view. This will cause a call to 10030 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10031 * invalidated. 10032 * @param x the amount of pixels to scroll by horizontally 10033 * @param y the amount of pixels to scroll by vertically 10034 */ 10035 public void scrollBy(int x, int y) { 10036 scrollTo(mScrollX + x, mScrollY + y); 10037 } 10038 10039 /** 10040 * <p>Trigger the scrollbars to draw. When invoked this method starts an 10041 * animation to fade the scrollbars out after a default delay. If a subclass 10042 * provides animated scrolling, the start delay should equal the duration 10043 * of the scrolling animation.</p> 10044 * 10045 * <p>The animation starts only if at least one of the scrollbars is 10046 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 10047 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10048 * this method returns true, and false otherwise. If the animation is 10049 * started, this method calls {@link #invalidate()}; in that case the 10050 * caller should not call {@link #invalidate()}.</p> 10051 * 10052 * <p>This method should be invoked every time a subclass directly updates 10053 * the scroll parameters.</p> 10054 * 10055 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 10056 * and {@link #scrollTo(int, int)}.</p> 10057 * 10058 * @return true if the animation is played, false otherwise 10059 * 10060 * @see #awakenScrollBars(int) 10061 * @see #scrollBy(int, int) 10062 * @see #scrollTo(int, int) 10063 * @see #isHorizontalScrollBarEnabled() 10064 * @see #isVerticalScrollBarEnabled() 10065 * @see #setHorizontalScrollBarEnabled(boolean) 10066 * @see #setVerticalScrollBarEnabled(boolean) 10067 */ 10068 protected boolean awakenScrollBars() { 10069 return mScrollCache != null && 10070 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 10071 } 10072 10073 /** 10074 * Trigger the scrollbars to draw. 10075 * This method differs from awakenScrollBars() only in its default duration. 10076 * initialAwakenScrollBars() will show the scroll bars for longer than 10077 * usual to give the user more of a chance to notice them. 10078 * 10079 * @return true if the animation is played, false otherwise. 10080 */ 10081 private boolean initialAwakenScrollBars() { 10082 return mScrollCache != null && 10083 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 10084 } 10085 10086 /** 10087 * <p> 10088 * Trigger the scrollbars to draw. When invoked this method starts an 10089 * animation to fade the scrollbars out after a fixed delay. If a subclass 10090 * provides animated scrolling, the start delay should equal the duration of 10091 * the scrolling animation. 10092 * </p> 10093 * 10094 * <p> 10095 * The animation starts only if at least one of the scrollbars is enabled, 10096 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10097 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10098 * this method returns true, and false otherwise. If the animation is 10099 * started, this method calls {@link #invalidate()}; in that case the caller 10100 * should not call {@link #invalidate()}. 10101 * </p> 10102 * 10103 * <p> 10104 * This method should be invoked everytime a subclass directly updates the 10105 * scroll parameters. 10106 * </p> 10107 * 10108 * @param startDelay the delay, in milliseconds, after which the animation 10109 * should start; when the delay is 0, the animation starts 10110 * immediately 10111 * @return true if the animation is played, false otherwise 10112 * 10113 * @see #scrollBy(int, int) 10114 * @see #scrollTo(int, int) 10115 * @see #isHorizontalScrollBarEnabled() 10116 * @see #isVerticalScrollBarEnabled() 10117 * @see #setHorizontalScrollBarEnabled(boolean) 10118 * @see #setVerticalScrollBarEnabled(boolean) 10119 */ 10120 protected boolean awakenScrollBars(int startDelay) { 10121 return awakenScrollBars(startDelay, true); 10122 } 10123 10124 /** 10125 * <p> 10126 * Trigger the scrollbars to draw. When invoked this method starts an 10127 * animation to fade the scrollbars out after a fixed delay. If a subclass 10128 * provides animated scrolling, the start delay should equal the duration of 10129 * the scrolling animation. 10130 * </p> 10131 * 10132 * <p> 10133 * The animation starts only if at least one of the scrollbars is enabled, 10134 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10135 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10136 * this method returns true, and false otherwise. If the animation is 10137 * started, this method calls {@link #invalidate()} if the invalidate parameter 10138 * is set to true; in that case the caller 10139 * should not call {@link #invalidate()}. 10140 * </p> 10141 * 10142 * <p> 10143 * This method should be invoked everytime a subclass directly updates the 10144 * scroll parameters. 10145 * </p> 10146 * 10147 * @param startDelay the delay, in milliseconds, after which the animation 10148 * should start; when the delay is 0, the animation starts 10149 * immediately 10150 * 10151 * @param invalidate Wheter this method should call invalidate 10152 * 10153 * @return true if the animation is played, false otherwise 10154 * 10155 * @see #scrollBy(int, int) 10156 * @see #scrollTo(int, int) 10157 * @see #isHorizontalScrollBarEnabled() 10158 * @see #isVerticalScrollBarEnabled() 10159 * @see #setHorizontalScrollBarEnabled(boolean) 10160 * @see #setVerticalScrollBarEnabled(boolean) 10161 */ 10162 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 10163 final ScrollabilityCache scrollCache = mScrollCache; 10164 10165 if (scrollCache == null || !scrollCache.fadeScrollBars) { 10166 return false; 10167 } 10168 10169 if (scrollCache.scrollBar == null) { 10170 scrollCache.scrollBar = new ScrollBarDrawable(); 10171 } 10172 10173 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 10174 10175 if (invalidate) { 10176 // Invalidate to show the scrollbars 10177 postInvalidateOnAnimation(); 10178 } 10179 10180 if (scrollCache.state == ScrollabilityCache.OFF) { 10181 // FIXME: this is copied from WindowManagerService. 10182 // We should get this value from the system when it 10183 // is possible to do so. 10184 final int KEY_REPEAT_FIRST_DELAY = 750; 10185 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 10186 } 10187 10188 // Tell mScrollCache when we should start fading. This may 10189 // extend the fade start time if one was already scheduled 10190 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 10191 scrollCache.fadeStartTime = fadeStartTime; 10192 scrollCache.state = ScrollabilityCache.ON; 10193 10194 // Schedule our fader to run, unscheduling any old ones first 10195 if (mAttachInfo != null) { 10196 mAttachInfo.mHandler.removeCallbacks(scrollCache); 10197 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 10198 } 10199 10200 return true; 10201 } 10202 10203 return false; 10204 } 10205 10206 /** 10207 * Do not invalidate views which are not visible and which are not running an animation. They 10208 * will not get drawn and they should not set dirty flags as if they will be drawn 10209 */ 10210 private boolean skipInvalidate() { 10211 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 10212 (!(mParent instanceof ViewGroup) || 10213 !((ViewGroup) mParent).isViewTransitioning(this)); 10214 } 10215 /** 10216 * Mark the area defined by dirty as needing to be drawn. If the view is 10217 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 10218 * in the future. This must be called from a UI thread. To call from a non-UI 10219 * thread, call {@link #postInvalidate()}. 10220 * 10221 * WARNING: This method is destructive to dirty. 10222 * @param dirty the rectangle representing the bounds of the dirty region 10223 */ 10224 public void invalidate(Rect dirty) { 10225 if (skipInvalidate()) { 10226 return; 10227 } 10228 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10229 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10230 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10231 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10232 mPrivateFlags |= PFLAG_INVALIDATED; 10233 mPrivateFlags |= PFLAG_DIRTY; 10234 final ViewParent p = mParent; 10235 final AttachInfo ai = mAttachInfo; 10236 //noinspection PointlessBooleanExpression,ConstantConditions 10237 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10238 if (p != null && ai != null && ai.mHardwareAccelerated) { 10239 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10240 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10241 p.invalidateChild(this, null); 10242 return; 10243 } 10244 } 10245 if (p != null && ai != null) { 10246 final int scrollX = mScrollX; 10247 final int scrollY = mScrollY; 10248 final Rect r = ai.mTmpInvalRect; 10249 r.set(dirty.left - scrollX, dirty.top - scrollY, 10250 dirty.right - scrollX, dirty.bottom - scrollY); 10251 mParent.invalidateChild(this, r); 10252 } 10253 } 10254 } 10255 10256 /** 10257 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 10258 * The coordinates of the dirty rect are relative to the view. 10259 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 10260 * will be called at some point in the future. This must be called from 10261 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 10262 * @param l the left position of the dirty region 10263 * @param t the top position of the dirty region 10264 * @param r the right position of the dirty region 10265 * @param b the bottom position of the dirty region 10266 */ 10267 public void invalidate(int l, int t, int r, int b) { 10268 if (skipInvalidate()) { 10269 return; 10270 } 10271 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10272 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10273 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10274 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10275 mPrivateFlags |= PFLAG_INVALIDATED; 10276 mPrivateFlags |= PFLAG_DIRTY; 10277 final ViewParent p = mParent; 10278 final AttachInfo ai = mAttachInfo; 10279 //noinspection PointlessBooleanExpression,ConstantConditions 10280 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10281 if (p != null && ai != null && ai.mHardwareAccelerated) { 10282 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10283 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10284 p.invalidateChild(this, null); 10285 return; 10286 } 10287 } 10288 if (p != null && ai != null && l < r && t < b) { 10289 final int scrollX = mScrollX; 10290 final int scrollY = mScrollY; 10291 final Rect tmpr = ai.mTmpInvalRect; 10292 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 10293 p.invalidateChild(this, tmpr); 10294 } 10295 } 10296 } 10297 10298 /** 10299 * Invalidate the whole view. If the view is visible, 10300 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 10301 * the future. This must be called from a UI thread. To call from a non-UI thread, 10302 * call {@link #postInvalidate()}. 10303 */ 10304 public void invalidate() { 10305 invalidate(true); 10306 } 10307 10308 /** 10309 * This is where the invalidate() work actually happens. A full invalidate() 10310 * causes the drawing cache to be invalidated, but this function can be called with 10311 * invalidateCache set to false to skip that invalidation step for cases that do not 10312 * need it (for example, a component that remains at the same dimensions with the same 10313 * content). 10314 * 10315 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 10316 * well. This is usually true for a full invalidate, but may be set to false if the 10317 * View's contents or dimensions have not changed. 10318 */ 10319 void invalidate(boolean invalidateCache) { 10320 if (skipInvalidate()) { 10321 return; 10322 } 10323 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10324 (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) || 10325 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) { 10326 mLastIsOpaque = isOpaque(); 10327 mPrivateFlags &= ~PFLAG_DRAWN; 10328 mPrivateFlags |= PFLAG_DIRTY; 10329 if (invalidateCache) { 10330 mPrivateFlags |= PFLAG_INVALIDATED; 10331 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10332 } 10333 final AttachInfo ai = mAttachInfo; 10334 final ViewParent p = mParent; 10335 //noinspection PointlessBooleanExpression,ConstantConditions 10336 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10337 if (p != null && ai != null && ai.mHardwareAccelerated) { 10338 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10339 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10340 p.invalidateChild(this, null); 10341 return; 10342 } 10343 } 10344 10345 if (p != null && ai != null) { 10346 final Rect r = ai.mTmpInvalRect; 10347 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10348 // Don't call invalidate -- we don't want to internally scroll 10349 // our own bounds 10350 p.invalidateChild(this, r); 10351 } 10352 } 10353 } 10354 10355 /** 10356 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 10357 * set any flags or handle all of the cases handled by the default invalidation methods. 10358 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 10359 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 10360 * walk up the hierarchy, transforming the dirty rect as necessary. 10361 * 10362 * The method also handles normal invalidation logic if display list properties are not 10363 * being used in this view. The invalidateParent and forceRedraw flags are used by that 10364 * backup approach, to handle these cases used in the various property-setting methods. 10365 * 10366 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 10367 * are not being used in this view 10368 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 10369 * list properties are not being used in this view 10370 */ 10371 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 10372 if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) { 10373 if (invalidateParent) { 10374 invalidateParentCaches(); 10375 } 10376 if (forceRedraw) { 10377 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10378 } 10379 invalidate(false); 10380 } else { 10381 final AttachInfo ai = mAttachInfo; 10382 final ViewParent p = mParent; 10383 if (p != null && ai != null) { 10384 final Rect r = ai.mTmpInvalRect; 10385 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10386 if (mParent instanceof ViewGroup) { 10387 ((ViewGroup) mParent).invalidateChildFast(this, r); 10388 } else { 10389 mParent.invalidateChild(this, r); 10390 } 10391 } 10392 } 10393 } 10394 10395 /** 10396 * Utility method to transform a given Rect by the current matrix of this view. 10397 */ 10398 void transformRect(final Rect rect) { 10399 if (!getMatrix().isIdentity()) { 10400 RectF boundingRect = mAttachInfo.mTmpTransformRect; 10401 boundingRect.set(rect); 10402 getMatrix().mapRect(boundingRect); 10403 rect.set((int) (boundingRect.left - 0.5f), 10404 (int) (boundingRect.top - 0.5f), 10405 (int) (boundingRect.right + 0.5f), 10406 (int) (boundingRect.bottom + 0.5f)); 10407 } 10408 } 10409 10410 /** 10411 * Used to indicate that the parent of this view should clear its caches. This functionality 10412 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10413 * which is necessary when various parent-managed properties of the view change, such as 10414 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 10415 * clears the parent caches and does not causes an invalidate event. 10416 * 10417 * @hide 10418 */ 10419 protected void invalidateParentCaches() { 10420 if (mParent instanceof View) { 10421 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 10422 } 10423 } 10424 10425 /** 10426 * Used to indicate that the parent of this view should be invalidated. This functionality 10427 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10428 * which is necessary when various parent-managed properties of the view change, such as 10429 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 10430 * an invalidation event to the parent. 10431 * 10432 * @hide 10433 */ 10434 protected void invalidateParentIfNeeded() { 10435 if (isHardwareAccelerated() && mParent instanceof View) { 10436 ((View) mParent).invalidate(true); 10437 } 10438 } 10439 10440 /** 10441 * Indicates whether this View is opaque. An opaque View guarantees that it will 10442 * draw all the pixels overlapping its bounds using a fully opaque color. 10443 * 10444 * Subclasses of View should override this method whenever possible to indicate 10445 * whether an instance is opaque. Opaque Views are treated in a special way by 10446 * the View hierarchy, possibly allowing it to perform optimizations during 10447 * invalidate/draw passes. 10448 * 10449 * @return True if this View is guaranteed to be fully opaque, false otherwise. 10450 */ 10451 @ViewDebug.ExportedProperty(category = "drawing") 10452 public boolean isOpaque() { 10453 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 10454 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f); 10455 } 10456 10457 /** 10458 * @hide 10459 */ 10460 protected void computeOpaqueFlags() { 10461 // Opaque if: 10462 // - Has a background 10463 // - Background is opaque 10464 // - Doesn't have scrollbars or scrollbars are inside overlay 10465 10466 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 10467 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 10468 } else { 10469 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 10470 } 10471 10472 final int flags = mViewFlags; 10473 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 10474 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 10475 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 10476 } else { 10477 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 10478 } 10479 } 10480 10481 /** 10482 * @hide 10483 */ 10484 protected boolean hasOpaqueScrollbars() { 10485 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 10486 } 10487 10488 /** 10489 * @return A handler associated with the thread running the View. This 10490 * handler can be used to pump events in the UI events queue. 10491 */ 10492 public Handler getHandler() { 10493 if (mAttachInfo != null) { 10494 return mAttachInfo.mHandler; 10495 } 10496 return null; 10497 } 10498 10499 /** 10500 * Gets the view root associated with the View. 10501 * @return The view root, or null if none. 10502 * @hide 10503 */ 10504 public ViewRootImpl getViewRootImpl() { 10505 if (mAttachInfo != null) { 10506 return mAttachInfo.mViewRootImpl; 10507 } 10508 return null; 10509 } 10510 10511 /** 10512 * <p>Causes the Runnable to be added to the message queue. 10513 * The runnable will be run on the user interface thread.</p> 10514 * 10515 * <p>This method can be invoked from outside of the UI thread 10516 * only when this View is attached to a window.</p> 10517 * 10518 * @param action The Runnable that will be executed. 10519 * 10520 * @return Returns true if the Runnable was successfully placed in to the 10521 * message queue. Returns false on failure, usually because the 10522 * looper processing the message queue is exiting. 10523 * 10524 * @see #postDelayed 10525 * @see #removeCallbacks 10526 */ 10527 public boolean post(Runnable action) { 10528 final AttachInfo attachInfo = mAttachInfo; 10529 if (attachInfo != null) { 10530 return attachInfo.mHandler.post(action); 10531 } 10532 // Assume that post will succeed later 10533 ViewRootImpl.getRunQueue().post(action); 10534 return true; 10535 } 10536 10537 /** 10538 * <p>Causes the Runnable to be added to the message queue, to be run 10539 * after the specified amount of time elapses. 10540 * The runnable will be run on the user interface thread.</p> 10541 * 10542 * <p>This method can be invoked from outside of the UI thread 10543 * only when this View is attached to a window.</p> 10544 * 10545 * @param action The Runnable that will be executed. 10546 * @param delayMillis The delay (in milliseconds) until the Runnable 10547 * will be executed. 10548 * 10549 * @return true if the Runnable was successfully placed in to the 10550 * message queue. Returns false on failure, usually because the 10551 * looper processing the message queue is exiting. Note that a 10552 * result of true does not mean the Runnable will be processed -- 10553 * if the looper is quit before the delivery time of the message 10554 * occurs then the message will be dropped. 10555 * 10556 * @see #post 10557 * @see #removeCallbacks 10558 */ 10559 public boolean postDelayed(Runnable action, long delayMillis) { 10560 final AttachInfo attachInfo = mAttachInfo; 10561 if (attachInfo != null) { 10562 return attachInfo.mHandler.postDelayed(action, delayMillis); 10563 } 10564 // Assume that post will succeed later 10565 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10566 return true; 10567 } 10568 10569 /** 10570 * <p>Causes the Runnable to execute on the next animation time step. 10571 * The runnable will be run on the user interface thread.</p> 10572 * 10573 * <p>This method can be invoked from outside of the UI thread 10574 * only when this View is attached to a window.</p> 10575 * 10576 * @param action The Runnable that will be executed. 10577 * 10578 * @see #postOnAnimationDelayed 10579 * @see #removeCallbacks 10580 */ 10581 public void postOnAnimation(Runnable action) { 10582 final AttachInfo attachInfo = mAttachInfo; 10583 if (attachInfo != null) { 10584 attachInfo.mViewRootImpl.mChoreographer.postCallback( 10585 Choreographer.CALLBACK_ANIMATION, action, null); 10586 } else { 10587 // Assume that post will succeed later 10588 ViewRootImpl.getRunQueue().post(action); 10589 } 10590 } 10591 10592 /** 10593 * <p>Causes the Runnable to execute on the next animation time step, 10594 * after the specified amount of time elapses. 10595 * The runnable will be run on the user interface thread.</p> 10596 * 10597 * <p>This method can be invoked from outside of the UI thread 10598 * only when this View is attached to a window.</p> 10599 * 10600 * @param action The Runnable that will be executed. 10601 * @param delayMillis The delay (in milliseconds) until the Runnable 10602 * will be executed. 10603 * 10604 * @see #postOnAnimation 10605 * @see #removeCallbacks 10606 */ 10607 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 10608 final AttachInfo attachInfo = mAttachInfo; 10609 if (attachInfo != null) { 10610 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 10611 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 10612 } else { 10613 // Assume that post will succeed later 10614 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10615 } 10616 } 10617 10618 /** 10619 * <p>Removes the specified Runnable from the message queue.</p> 10620 * 10621 * <p>This method can be invoked from outside of the UI thread 10622 * only when this View is attached to a window.</p> 10623 * 10624 * @param action The Runnable to remove from the message handling queue 10625 * 10626 * @return true if this view could ask the Handler to remove the Runnable, 10627 * false otherwise. When the returned value is true, the Runnable 10628 * may or may not have been actually removed from the message queue 10629 * (for instance, if the Runnable was not in the queue already.) 10630 * 10631 * @see #post 10632 * @see #postDelayed 10633 * @see #postOnAnimation 10634 * @see #postOnAnimationDelayed 10635 */ 10636 public boolean removeCallbacks(Runnable action) { 10637 if (action != null) { 10638 final AttachInfo attachInfo = mAttachInfo; 10639 if (attachInfo != null) { 10640 attachInfo.mHandler.removeCallbacks(action); 10641 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 10642 Choreographer.CALLBACK_ANIMATION, action, null); 10643 } else { 10644 // Assume that post will succeed later 10645 ViewRootImpl.getRunQueue().removeCallbacks(action); 10646 } 10647 } 10648 return true; 10649 } 10650 10651 /** 10652 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 10653 * Use this to invalidate the View from a non-UI thread.</p> 10654 * 10655 * <p>This method can be invoked from outside of the UI thread 10656 * only when this View is attached to a window.</p> 10657 * 10658 * @see #invalidate() 10659 * @see #postInvalidateDelayed(long) 10660 */ 10661 public void postInvalidate() { 10662 postInvalidateDelayed(0); 10663 } 10664 10665 /** 10666 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10667 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 10668 * 10669 * <p>This method can be invoked from outside of the UI thread 10670 * only when this View is attached to a window.</p> 10671 * 10672 * @param left The left coordinate of the rectangle to invalidate. 10673 * @param top The top coordinate of the rectangle to invalidate. 10674 * @param right The right coordinate of the rectangle to invalidate. 10675 * @param bottom The bottom coordinate of the rectangle to invalidate. 10676 * 10677 * @see #invalidate(int, int, int, int) 10678 * @see #invalidate(Rect) 10679 * @see #postInvalidateDelayed(long, int, int, int, int) 10680 */ 10681 public void postInvalidate(int left, int top, int right, int bottom) { 10682 postInvalidateDelayed(0, left, top, right, bottom); 10683 } 10684 10685 /** 10686 * <p>Cause an invalidate to happen on a subsequent cycle through the event 10687 * loop. Waits for the specified amount of time.</p> 10688 * 10689 * <p>This method can be invoked from outside of the UI thread 10690 * only when this View is attached to a window.</p> 10691 * 10692 * @param delayMilliseconds the duration in milliseconds to delay the 10693 * invalidation by 10694 * 10695 * @see #invalidate() 10696 * @see #postInvalidate() 10697 */ 10698 public void postInvalidateDelayed(long delayMilliseconds) { 10699 // We try only with the AttachInfo because there's no point in invalidating 10700 // if we are not attached to our window 10701 final AttachInfo attachInfo = mAttachInfo; 10702 if (attachInfo != null) { 10703 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 10704 } 10705 } 10706 10707 /** 10708 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10709 * through the event loop. Waits for the specified amount of time.</p> 10710 * 10711 * <p>This method can be invoked from outside of the UI thread 10712 * only when this View is attached to a window.</p> 10713 * 10714 * @param delayMilliseconds the duration in milliseconds to delay the 10715 * invalidation by 10716 * @param left The left coordinate of the rectangle to invalidate. 10717 * @param top The top coordinate of the rectangle to invalidate. 10718 * @param right The right coordinate of the rectangle to invalidate. 10719 * @param bottom The bottom coordinate of the rectangle to invalidate. 10720 * 10721 * @see #invalidate(int, int, int, int) 10722 * @see #invalidate(Rect) 10723 * @see #postInvalidate(int, int, int, int) 10724 */ 10725 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 10726 int right, int bottom) { 10727 10728 // We try only with the AttachInfo because there's no point in invalidating 10729 // if we are not attached to our window 10730 final AttachInfo attachInfo = mAttachInfo; 10731 if (attachInfo != null) { 10732 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 10733 info.target = this; 10734 info.left = left; 10735 info.top = top; 10736 info.right = right; 10737 info.bottom = bottom; 10738 10739 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 10740 } 10741 } 10742 10743 /** 10744 * <p>Cause an invalidate to happen on the next animation time step, typically the 10745 * next display frame.</p> 10746 * 10747 * <p>This method can be invoked from outside of the UI thread 10748 * only when this View is attached to a window.</p> 10749 * 10750 * @see #invalidate() 10751 */ 10752 public void postInvalidateOnAnimation() { 10753 // We try only with the AttachInfo because there's no point in invalidating 10754 // if we are not attached to our window 10755 final AttachInfo attachInfo = mAttachInfo; 10756 if (attachInfo != null) { 10757 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 10758 } 10759 } 10760 10761 /** 10762 * <p>Cause an invalidate of the specified area to happen on the next animation 10763 * time step, typically the next display frame.</p> 10764 * 10765 * <p>This method can be invoked from outside of the UI thread 10766 * only when this View is attached to a window.</p> 10767 * 10768 * @param left The left coordinate of the rectangle to invalidate. 10769 * @param top The top coordinate of the rectangle to invalidate. 10770 * @param right The right coordinate of the rectangle to invalidate. 10771 * @param bottom The bottom coordinate of the rectangle to invalidate. 10772 * 10773 * @see #invalidate(int, int, int, int) 10774 * @see #invalidate(Rect) 10775 */ 10776 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 10777 // We try only with the AttachInfo because there's no point in invalidating 10778 // if we are not attached to our window 10779 final AttachInfo attachInfo = mAttachInfo; 10780 if (attachInfo != null) { 10781 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 10782 info.target = this; 10783 info.left = left; 10784 info.top = top; 10785 info.right = right; 10786 info.bottom = bottom; 10787 10788 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 10789 } 10790 } 10791 10792 /** 10793 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 10794 * This event is sent at most once every 10795 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 10796 */ 10797 private void postSendViewScrolledAccessibilityEventCallback() { 10798 if (mSendViewScrolledAccessibilityEvent == null) { 10799 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 10800 } 10801 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 10802 mSendViewScrolledAccessibilityEvent.mIsPending = true; 10803 postDelayed(mSendViewScrolledAccessibilityEvent, 10804 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 10805 } 10806 } 10807 10808 /** 10809 * Called by a parent to request that a child update its values for mScrollX 10810 * and mScrollY if necessary. This will typically be done if the child is 10811 * animating a scroll using a {@link android.widget.Scroller Scroller} 10812 * object. 10813 */ 10814 public void computeScroll() { 10815 } 10816 10817 /** 10818 * <p>Indicate whether the horizontal edges are faded when the view is 10819 * scrolled horizontally.</p> 10820 * 10821 * @return true if the horizontal edges should are faded on scroll, false 10822 * otherwise 10823 * 10824 * @see #setHorizontalFadingEdgeEnabled(boolean) 10825 * 10826 * @attr ref android.R.styleable#View_requiresFadingEdge 10827 */ 10828 public boolean isHorizontalFadingEdgeEnabled() { 10829 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 10830 } 10831 10832 /** 10833 * <p>Define whether the horizontal edges should be faded when this view 10834 * is scrolled horizontally.</p> 10835 * 10836 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 10837 * be faded when the view is scrolled 10838 * horizontally 10839 * 10840 * @see #isHorizontalFadingEdgeEnabled() 10841 * 10842 * @attr ref android.R.styleable#View_requiresFadingEdge 10843 */ 10844 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 10845 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 10846 if (horizontalFadingEdgeEnabled) { 10847 initScrollCache(); 10848 } 10849 10850 mViewFlags ^= FADING_EDGE_HORIZONTAL; 10851 } 10852 } 10853 10854 /** 10855 * <p>Indicate whether the vertical edges are faded when the view is 10856 * scrolled horizontally.</p> 10857 * 10858 * @return true if the vertical edges should are faded on scroll, false 10859 * otherwise 10860 * 10861 * @see #setVerticalFadingEdgeEnabled(boolean) 10862 * 10863 * @attr ref android.R.styleable#View_requiresFadingEdge 10864 */ 10865 public boolean isVerticalFadingEdgeEnabled() { 10866 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 10867 } 10868 10869 /** 10870 * <p>Define whether the vertical edges should be faded when this view 10871 * is scrolled vertically.</p> 10872 * 10873 * @param verticalFadingEdgeEnabled true if the vertical edges should 10874 * be faded when the view is scrolled 10875 * vertically 10876 * 10877 * @see #isVerticalFadingEdgeEnabled() 10878 * 10879 * @attr ref android.R.styleable#View_requiresFadingEdge 10880 */ 10881 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 10882 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 10883 if (verticalFadingEdgeEnabled) { 10884 initScrollCache(); 10885 } 10886 10887 mViewFlags ^= FADING_EDGE_VERTICAL; 10888 } 10889 } 10890 10891 /** 10892 * Returns the strength, or intensity, of the top faded edge. The strength is 10893 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10894 * returns 0.0 or 1.0 but no value in between. 10895 * 10896 * Subclasses should override this method to provide a smoother fade transition 10897 * when scrolling occurs. 10898 * 10899 * @return the intensity of the top fade as a float between 0.0f and 1.0f 10900 */ 10901 protected float getTopFadingEdgeStrength() { 10902 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 10903 } 10904 10905 /** 10906 * Returns the strength, or intensity, of the bottom faded edge. The strength is 10907 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10908 * returns 0.0 or 1.0 but no value in between. 10909 * 10910 * Subclasses should override this method to provide a smoother fade transition 10911 * when scrolling occurs. 10912 * 10913 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 10914 */ 10915 protected float getBottomFadingEdgeStrength() { 10916 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 10917 computeVerticalScrollRange() ? 1.0f : 0.0f; 10918 } 10919 10920 /** 10921 * Returns the strength, or intensity, of the left faded edge. The strength is 10922 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10923 * returns 0.0 or 1.0 but no value in between. 10924 * 10925 * Subclasses should override this method to provide a smoother fade transition 10926 * when scrolling occurs. 10927 * 10928 * @return the intensity of the left fade as a float between 0.0f and 1.0f 10929 */ 10930 protected float getLeftFadingEdgeStrength() { 10931 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 10932 } 10933 10934 /** 10935 * Returns the strength, or intensity, of the right faded edge. The strength is 10936 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10937 * returns 0.0 or 1.0 but no value in between. 10938 * 10939 * Subclasses should override this method to provide a smoother fade transition 10940 * when scrolling occurs. 10941 * 10942 * @return the intensity of the right fade as a float between 0.0f and 1.0f 10943 */ 10944 protected float getRightFadingEdgeStrength() { 10945 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 10946 computeHorizontalScrollRange() ? 1.0f : 0.0f; 10947 } 10948 10949 /** 10950 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 10951 * scrollbar is not drawn by default.</p> 10952 * 10953 * @return true if the horizontal scrollbar should be painted, false 10954 * otherwise 10955 * 10956 * @see #setHorizontalScrollBarEnabled(boolean) 10957 */ 10958 public boolean isHorizontalScrollBarEnabled() { 10959 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 10960 } 10961 10962 /** 10963 * <p>Define whether the horizontal scrollbar should be drawn or not. The 10964 * scrollbar is not drawn by default.</p> 10965 * 10966 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 10967 * be painted 10968 * 10969 * @see #isHorizontalScrollBarEnabled() 10970 */ 10971 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 10972 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 10973 mViewFlags ^= SCROLLBARS_HORIZONTAL; 10974 computeOpaqueFlags(); 10975 resolvePadding(); 10976 } 10977 } 10978 10979 /** 10980 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 10981 * scrollbar is not drawn by default.</p> 10982 * 10983 * @return true if the vertical scrollbar should be painted, false 10984 * otherwise 10985 * 10986 * @see #setVerticalScrollBarEnabled(boolean) 10987 */ 10988 public boolean isVerticalScrollBarEnabled() { 10989 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 10990 } 10991 10992 /** 10993 * <p>Define whether the vertical scrollbar should be drawn or not. The 10994 * scrollbar is not drawn by default.</p> 10995 * 10996 * @param verticalScrollBarEnabled true if the vertical scrollbar should 10997 * be painted 10998 * 10999 * @see #isVerticalScrollBarEnabled() 11000 */ 11001 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 11002 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 11003 mViewFlags ^= SCROLLBARS_VERTICAL; 11004 computeOpaqueFlags(); 11005 resolvePadding(); 11006 } 11007 } 11008 11009 /** 11010 * @hide 11011 */ 11012 protected void recomputePadding() { 11013 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 11014 } 11015 11016 /** 11017 * Define whether scrollbars will fade when the view is not scrolling. 11018 * 11019 * @param fadeScrollbars wheter to enable fading 11020 * 11021 * @attr ref android.R.styleable#View_fadeScrollbars 11022 */ 11023 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 11024 initScrollCache(); 11025 final ScrollabilityCache scrollabilityCache = mScrollCache; 11026 scrollabilityCache.fadeScrollBars = fadeScrollbars; 11027 if (fadeScrollbars) { 11028 scrollabilityCache.state = ScrollabilityCache.OFF; 11029 } else { 11030 scrollabilityCache.state = ScrollabilityCache.ON; 11031 } 11032 } 11033 11034 /** 11035 * 11036 * Returns true if scrollbars will fade when this view is not scrolling 11037 * 11038 * @return true if scrollbar fading is enabled 11039 * 11040 * @attr ref android.R.styleable#View_fadeScrollbars 11041 */ 11042 public boolean isScrollbarFadingEnabled() { 11043 return mScrollCache != null && mScrollCache.fadeScrollBars; 11044 } 11045 11046 /** 11047 * 11048 * Returns the delay before scrollbars fade. 11049 * 11050 * @return the delay before scrollbars fade 11051 * 11052 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11053 */ 11054 public int getScrollBarDefaultDelayBeforeFade() { 11055 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 11056 mScrollCache.scrollBarDefaultDelayBeforeFade; 11057 } 11058 11059 /** 11060 * Define the delay before scrollbars fade. 11061 * 11062 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 11063 * 11064 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11065 */ 11066 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 11067 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 11068 } 11069 11070 /** 11071 * 11072 * Returns the scrollbar fade duration. 11073 * 11074 * @return the scrollbar fade duration 11075 * 11076 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11077 */ 11078 public int getScrollBarFadeDuration() { 11079 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 11080 mScrollCache.scrollBarFadeDuration; 11081 } 11082 11083 /** 11084 * Define the scrollbar fade duration. 11085 * 11086 * @param scrollBarFadeDuration - the scrollbar fade duration 11087 * 11088 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11089 */ 11090 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 11091 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 11092 } 11093 11094 /** 11095 * 11096 * Returns the scrollbar size. 11097 * 11098 * @return the scrollbar size 11099 * 11100 * @attr ref android.R.styleable#View_scrollbarSize 11101 */ 11102 public int getScrollBarSize() { 11103 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 11104 mScrollCache.scrollBarSize; 11105 } 11106 11107 /** 11108 * Define the scrollbar size. 11109 * 11110 * @param scrollBarSize - the scrollbar size 11111 * 11112 * @attr ref android.R.styleable#View_scrollbarSize 11113 */ 11114 public void setScrollBarSize(int scrollBarSize) { 11115 getScrollCache().scrollBarSize = scrollBarSize; 11116 } 11117 11118 /** 11119 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 11120 * inset. When inset, they add to the padding of the view. And the scrollbars 11121 * can be drawn inside the padding area or on the edge of the view. For example, 11122 * if a view has a background drawable and you want to draw the scrollbars 11123 * inside the padding specified by the drawable, you can use 11124 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 11125 * appear at the edge of the view, ignoring the padding, then you can use 11126 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 11127 * @param style the style of the scrollbars. Should be one of 11128 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 11129 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 11130 * @see #SCROLLBARS_INSIDE_OVERLAY 11131 * @see #SCROLLBARS_INSIDE_INSET 11132 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11133 * @see #SCROLLBARS_OUTSIDE_INSET 11134 * 11135 * @attr ref android.R.styleable#View_scrollbarStyle 11136 */ 11137 public void setScrollBarStyle(int style) { 11138 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 11139 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 11140 computeOpaqueFlags(); 11141 resolvePadding(); 11142 } 11143 } 11144 11145 /** 11146 * <p>Returns the current scrollbar style.</p> 11147 * @return the current scrollbar style 11148 * @see #SCROLLBARS_INSIDE_OVERLAY 11149 * @see #SCROLLBARS_INSIDE_INSET 11150 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11151 * @see #SCROLLBARS_OUTSIDE_INSET 11152 * 11153 * @attr ref android.R.styleable#View_scrollbarStyle 11154 */ 11155 @ViewDebug.ExportedProperty(mapping = { 11156 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 11157 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 11158 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 11159 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 11160 }) 11161 public int getScrollBarStyle() { 11162 return mViewFlags & SCROLLBARS_STYLE_MASK; 11163 } 11164 11165 /** 11166 * <p>Compute the horizontal range that the horizontal scrollbar 11167 * represents.</p> 11168 * 11169 * <p>The range is expressed in arbitrary units that must be the same as the 11170 * units used by {@link #computeHorizontalScrollExtent()} and 11171 * {@link #computeHorizontalScrollOffset()}.</p> 11172 * 11173 * <p>The default range is the drawing width of this view.</p> 11174 * 11175 * @return the total horizontal range represented by the horizontal 11176 * scrollbar 11177 * 11178 * @see #computeHorizontalScrollExtent() 11179 * @see #computeHorizontalScrollOffset() 11180 * @see android.widget.ScrollBarDrawable 11181 */ 11182 protected int computeHorizontalScrollRange() { 11183 return getWidth(); 11184 } 11185 11186 /** 11187 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 11188 * within the horizontal range. This value is used to compute the position 11189 * of the thumb within the scrollbar's track.</p> 11190 * 11191 * <p>The range is expressed in arbitrary units that must be the same as the 11192 * units used by {@link #computeHorizontalScrollRange()} and 11193 * {@link #computeHorizontalScrollExtent()}.</p> 11194 * 11195 * <p>The default offset is the scroll offset of this view.</p> 11196 * 11197 * @return the horizontal offset of the scrollbar's thumb 11198 * 11199 * @see #computeHorizontalScrollRange() 11200 * @see #computeHorizontalScrollExtent() 11201 * @see android.widget.ScrollBarDrawable 11202 */ 11203 protected int computeHorizontalScrollOffset() { 11204 return mScrollX; 11205 } 11206 11207 /** 11208 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 11209 * within the horizontal range. This value is used to compute the length 11210 * of the thumb within the scrollbar's track.</p> 11211 * 11212 * <p>The range is expressed in arbitrary units that must be the same as the 11213 * units used by {@link #computeHorizontalScrollRange()} and 11214 * {@link #computeHorizontalScrollOffset()}.</p> 11215 * 11216 * <p>The default extent is the drawing width of this view.</p> 11217 * 11218 * @return the horizontal extent of the scrollbar's thumb 11219 * 11220 * @see #computeHorizontalScrollRange() 11221 * @see #computeHorizontalScrollOffset() 11222 * @see android.widget.ScrollBarDrawable 11223 */ 11224 protected int computeHorizontalScrollExtent() { 11225 return getWidth(); 11226 } 11227 11228 /** 11229 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 11230 * 11231 * <p>The range is expressed in arbitrary units that must be the same as the 11232 * units used by {@link #computeVerticalScrollExtent()} and 11233 * {@link #computeVerticalScrollOffset()}.</p> 11234 * 11235 * @return the total vertical range represented by the vertical scrollbar 11236 * 11237 * <p>The default range is the drawing height of this view.</p> 11238 * 11239 * @see #computeVerticalScrollExtent() 11240 * @see #computeVerticalScrollOffset() 11241 * @see android.widget.ScrollBarDrawable 11242 */ 11243 protected int computeVerticalScrollRange() { 11244 return getHeight(); 11245 } 11246 11247 /** 11248 * <p>Compute the vertical offset of the vertical scrollbar's thumb 11249 * within the horizontal range. This value is used to compute the position 11250 * of the thumb within the scrollbar's track.</p> 11251 * 11252 * <p>The range is expressed in arbitrary units that must be the same as the 11253 * units used by {@link #computeVerticalScrollRange()} and 11254 * {@link #computeVerticalScrollExtent()}.</p> 11255 * 11256 * <p>The default offset is the scroll offset of this view.</p> 11257 * 11258 * @return the vertical offset of the scrollbar's thumb 11259 * 11260 * @see #computeVerticalScrollRange() 11261 * @see #computeVerticalScrollExtent() 11262 * @see android.widget.ScrollBarDrawable 11263 */ 11264 protected int computeVerticalScrollOffset() { 11265 return mScrollY; 11266 } 11267 11268 /** 11269 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 11270 * within the vertical range. This value is used to compute the length 11271 * of the thumb within the scrollbar's track.</p> 11272 * 11273 * <p>The range is expressed in arbitrary units that must be the same as the 11274 * units used by {@link #computeVerticalScrollRange()} and 11275 * {@link #computeVerticalScrollOffset()}.</p> 11276 * 11277 * <p>The default extent is the drawing height of this view.</p> 11278 * 11279 * @return the vertical extent of the scrollbar's thumb 11280 * 11281 * @see #computeVerticalScrollRange() 11282 * @see #computeVerticalScrollOffset() 11283 * @see android.widget.ScrollBarDrawable 11284 */ 11285 protected int computeVerticalScrollExtent() { 11286 return getHeight(); 11287 } 11288 11289 /** 11290 * Check if this view can be scrolled horizontally in a certain direction. 11291 * 11292 * @param direction Negative to check scrolling left, positive to check scrolling right. 11293 * @return true if this view can be scrolled in the specified direction, false otherwise. 11294 */ 11295 public boolean canScrollHorizontally(int direction) { 11296 final int offset = computeHorizontalScrollOffset(); 11297 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 11298 if (range == 0) return false; 11299 if (direction < 0) { 11300 return offset > 0; 11301 } else { 11302 return offset < range - 1; 11303 } 11304 } 11305 11306 /** 11307 * Check if this view can be scrolled vertically in a certain direction. 11308 * 11309 * @param direction Negative to check scrolling up, positive to check scrolling down. 11310 * @return true if this view can be scrolled in the specified direction, false otherwise. 11311 */ 11312 public boolean canScrollVertically(int direction) { 11313 final int offset = computeVerticalScrollOffset(); 11314 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 11315 if (range == 0) return false; 11316 if (direction < 0) { 11317 return offset > 0; 11318 } else { 11319 return offset < range - 1; 11320 } 11321 } 11322 11323 /** 11324 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 11325 * scrollbars are painted only if they have been awakened first.</p> 11326 * 11327 * @param canvas the canvas on which to draw the scrollbars 11328 * 11329 * @see #awakenScrollBars(int) 11330 */ 11331 protected final void onDrawScrollBars(Canvas canvas) { 11332 // scrollbars are drawn only when the animation is running 11333 final ScrollabilityCache cache = mScrollCache; 11334 if (cache != null) { 11335 11336 int state = cache.state; 11337 11338 if (state == ScrollabilityCache.OFF) { 11339 return; 11340 } 11341 11342 boolean invalidate = false; 11343 11344 if (state == ScrollabilityCache.FADING) { 11345 // We're fading -- get our fade interpolation 11346 if (cache.interpolatorValues == null) { 11347 cache.interpolatorValues = new float[1]; 11348 } 11349 11350 float[] values = cache.interpolatorValues; 11351 11352 // Stops the animation if we're done 11353 if (cache.scrollBarInterpolator.timeToValues(values) == 11354 Interpolator.Result.FREEZE_END) { 11355 cache.state = ScrollabilityCache.OFF; 11356 } else { 11357 cache.scrollBar.setAlpha(Math.round(values[0])); 11358 } 11359 11360 // This will make the scroll bars inval themselves after 11361 // drawing. We only want this when we're fading so that 11362 // we prevent excessive redraws 11363 invalidate = true; 11364 } else { 11365 // We're just on -- but we may have been fading before so 11366 // reset alpha 11367 cache.scrollBar.setAlpha(255); 11368 } 11369 11370 11371 final int viewFlags = mViewFlags; 11372 11373 final boolean drawHorizontalScrollBar = 11374 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11375 final boolean drawVerticalScrollBar = 11376 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 11377 && !isVerticalScrollBarHidden(); 11378 11379 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 11380 final int width = mRight - mLeft; 11381 final int height = mBottom - mTop; 11382 11383 final ScrollBarDrawable scrollBar = cache.scrollBar; 11384 11385 final int scrollX = mScrollX; 11386 final int scrollY = mScrollY; 11387 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 11388 11389 int left, top, right, bottom; 11390 11391 if (drawHorizontalScrollBar) { 11392 int size = scrollBar.getSize(false); 11393 if (size <= 0) { 11394 size = cache.scrollBarSize; 11395 } 11396 11397 scrollBar.setParameters(computeHorizontalScrollRange(), 11398 computeHorizontalScrollOffset(), 11399 computeHorizontalScrollExtent(), false); 11400 final int verticalScrollBarGap = drawVerticalScrollBar ? 11401 getVerticalScrollbarWidth() : 0; 11402 top = scrollY + height - size - (mUserPaddingBottom & inside); 11403 left = scrollX + (mPaddingLeft & inside); 11404 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 11405 bottom = top + size; 11406 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 11407 if (invalidate) { 11408 invalidate(left, top, right, bottom); 11409 } 11410 } 11411 11412 if (drawVerticalScrollBar) { 11413 int size = scrollBar.getSize(true); 11414 if (size <= 0) { 11415 size = cache.scrollBarSize; 11416 } 11417 11418 scrollBar.setParameters(computeVerticalScrollRange(), 11419 computeVerticalScrollOffset(), 11420 computeVerticalScrollExtent(), true); 11421 int verticalScrollbarPosition = mVerticalScrollbarPosition; 11422 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 11423 verticalScrollbarPosition = isLayoutRtl() ? 11424 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 11425 } 11426 switch (verticalScrollbarPosition) { 11427 default: 11428 case SCROLLBAR_POSITION_RIGHT: 11429 left = scrollX + width - size - (mUserPaddingRight & inside); 11430 break; 11431 case SCROLLBAR_POSITION_LEFT: 11432 left = scrollX + (mUserPaddingLeft & inside); 11433 break; 11434 } 11435 top = scrollY + (mPaddingTop & inside); 11436 right = left + size; 11437 bottom = scrollY + height - (mUserPaddingBottom & inside); 11438 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 11439 if (invalidate) { 11440 invalidate(left, top, right, bottom); 11441 } 11442 } 11443 } 11444 } 11445 } 11446 11447 /** 11448 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 11449 * FastScroller is visible. 11450 * @return whether to temporarily hide the vertical scrollbar 11451 * @hide 11452 */ 11453 protected boolean isVerticalScrollBarHidden() { 11454 return false; 11455 } 11456 11457 /** 11458 * <p>Draw the horizontal scrollbar if 11459 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 11460 * 11461 * @param canvas the canvas on which to draw the scrollbar 11462 * @param scrollBar the scrollbar's drawable 11463 * 11464 * @see #isHorizontalScrollBarEnabled() 11465 * @see #computeHorizontalScrollRange() 11466 * @see #computeHorizontalScrollExtent() 11467 * @see #computeHorizontalScrollOffset() 11468 * @see android.widget.ScrollBarDrawable 11469 * @hide 11470 */ 11471 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 11472 int l, int t, int r, int b) { 11473 scrollBar.setBounds(l, t, r, b); 11474 scrollBar.draw(canvas); 11475 } 11476 11477 /** 11478 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 11479 * returns true.</p> 11480 * 11481 * @param canvas the canvas on which to draw the scrollbar 11482 * @param scrollBar the scrollbar's drawable 11483 * 11484 * @see #isVerticalScrollBarEnabled() 11485 * @see #computeVerticalScrollRange() 11486 * @see #computeVerticalScrollExtent() 11487 * @see #computeVerticalScrollOffset() 11488 * @see android.widget.ScrollBarDrawable 11489 * @hide 11490 */ 11491 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 11492 int l, int t, int r, int b) { 11493 scrollBar.setBounds(l, t, r, b); 11494 scrollBar.draw(canvas); 11495 } 11496 11497 /** 11498 * Implement this to do your drawing. 11499 * 11500 * @param canvas the canvas on which the background will be drawn 11501 */ 11502 protected void onDraw(Canvas canvas) { 11503 } 11504 11505 /* 11506 * Caller is responsible for calling requestLayout if necessary. 11507 * (This allows addViewInLayout to not request a new layout.) 11508 */ 11509 void assignParent(ViewParent parent) { 11510 if (mParent == null) { 11511 mParent = parent; 11512 } else if (parent == null) { 11513 mParent = null; 11514 } else { 11515 throw new RuntimeException("view " + this + " being added, but" 11516 + " it already has a parent"); 11517 } 11518 } 11519 11520 /** 11521 * This is called when the view is attached to a window. At this point it 11522 * has a Surface and will start drawing. Note that this function is 11523 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 11524 * however it may be called any time before the first onDraw -- including 11525 * before or after {@link #onMeasure(int, int)}. 11526 * 11527 * @see #onDetachedFromWindow() 11528 */ 11529 protected void onAttachedToWindow() { 11530 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 11531 mParent.requestTransparentRegion(this); 11532 } 11533 11534 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 11535 initialAwakenScrollBars(); 11536 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 11537 } 11538 11539 jumpDrawablesToCurrentState(); 11540 11541 clearAccessibilityFocus(); 11542 if (isFocused()) { 11543 InputMethodManager imm = InputMethodManager.peekInstance(); 11544 imm.focusIn(this); 11545 } 11546 11547 if (mAttachInfo != null && mDisplayList != null) { 11548 mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList); 11549 } 11550 } 11551 11552 /** 11553 * Resolve all RTL related properties. 11554 */ 11555 void resolveRtlPropertiesIfNeeded() { 11556 if (!needRtlPropertiesResolution()) return; 11557 11558 // Order is important here: LayoutDirection MUST be resolved first 11559 if (!isLayoutDirectionResolved()) { 11560 resolveLayoutDirection(); 11561 resolveLayoutParams(); 11562 } 11563 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 11564 if (!isTextDirectionResolved()) { 11565 resolveTextDirection(); 11566 } 11567 if (!isTextAlignmentResolved()) { 11568 resolveTextAlignment(); 11569 } 11570 if (!isPaddingResolved()) { 11571 resolvePadding(); 11572 } 11573 if (!isDrawablesResolved()) { 11574 resolveDrawables(); 11575 } 11576 onRtlPropertiesChanged(getLayoutDirection()); 11577 } 11578 11579 // Reset resolution of all RTL related properties. 11580 void resetRtlProperties() { 11581 resetResolvedLayoutDirection(); 11582 resetResolvedTextDirection(); 11583 resetResolvedTextAlignment(); 11584 resetResolvedPadding(); 11585 resetResolvedDrawables(); 11586 } 11587 11588 /** 11589 * @see #onScreenStateChanged(int) 11590 */ 11591 void dispatchScreenStateChanged(int screenState) { 11592 onScreenStateChanged(screenState); 11593 } 11594 11595 /** 11596 * This method is called whenever the state of the screen this view is 11597 * attached to changes. A state change will usually occurs when the screen 11598 * turns on or off (whether it happens automatically or the user does it 11599 * manually.) 11600 * 11601 * @param screenState The new state of the screen. Can be either 11602 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 11603 */ 11604 public void onScreenStateChanged(int screenState) { 11605 } 11606 11607 /** 11608 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 11609 */ 11610 private boolean hasRtlSupport() { 11611 return mContext.getApplicationInfo().hasRtlSupport(); 11612 } 11613 11614 /** 11615 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 11616 * RTL not supported) 11617 */ 11618 private boolean isRtlCompatibilityMode() { 11619 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 11620 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 11621 } 11622 11623 /** 11624 * @return true if RTL properties need resolution. 11625 */ 11626 private boolean needRtlPropertiesResolution() { 11627 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 11628 } 11629 11630 /** 11631 * Called when any RTL property (layout direction or text direction or text alignment) has 11632 * been changed. 11633 * 11634 * Subclasses need to override this method to take care of cached information that depends on the 11635 * resolved layout direction, or to inform child views that inherit their layout direction. 11636 * 11637 * The default implementation does nothing. 11638 * 11639 * @param layoutDirection the direction of the layout 11640 * 11641 * @see #LAYOUT_DIRECTION_LTR 11642 * @see #LAYOUT_DIRECTION_RTL 11643 */ 11644 public void onRtlPropertiesChanged(int layoutDirection) { 11645 } 11646 11647 /** 11648 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 11649 * that the parent directionality can and will be resolved before its children. 11650 * 11651 * @return true if resolution has been done, false otherwise. 11652 * 11653 * @hide 11654 */ 11655 public boolean resolveLayoutDirection() { 11656 // Clear any previous layout direction resolution 11657 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 11658 11659 if (hasRtlSupport()) { 11660 // Set resolved depending on layout direction 11661 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 11662 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 11663 case LAYOUT_DIRECTION_INHERIT: 11664 // We cannot resolve yet. LTR is by default and let the resolution happen again 11665 // later to get the correct resolved value 11666 if (!canResolveLayoutDirection()) return false; 11667 11668 View parent = ((View) mParent); 11669 // Parent has not yet resolved, LTR is still the default 11670 if (!parent.isLayoutDirectionResolved()) return false; 11671 11672 if (parent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11673 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11674 } 11675 break; 11676 case LAYOUT_DIRECTION_RTL: 11677 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11678 break; 11679 case LAYOUT_DIRECTION_LOCALE: 11680 if((LAYOUT_DIRECTION_RTL == 11681 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 11682 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11683 } 11684 break; 11685 default: 11686 // Nothing to do, LTR by default 11687 } 11688 } 11689 11690 // Set to resolved 11691 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 11692 return true; 11693 } 11694 11695 /** 11696 * Check if layout direction resolution can be done. 11697 * 11698 * @return true if layout direction resolution can be done otherwise return false. 11699 * 11700 * @hide 11701 */ 11702 public boolean canResolveLayoutDirection() { 11703 switch (getRawLayoutDirection()) { 11704 case LAYOUT_DIRECTION_INHERIT: 11705 return (mParent != null) && (mParent instanceof ViewGroup) && 11706 ((ViewGroup) mParent).canResolveLayoutDirection(); 11707 default: 11708 return true; 11709 } 11710 } 11711 11712 /** 11713 * Reset the resolved layout direction. Layout direction will be resolved during a call to 11714 * {@link #onMeasure(int, int)}. 11715 * 11716 * @hide 11717 */ 11718 public void resetResolvedLayoutDirection() { 11719 // Reset the current resolved bits 11720 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 11721 } 11722 11723 /** 11724 * @return true if the layout direction is inherited. 11725 * 11726 * @hide 11727 */ 11728 public boolean isLayoutDirectionInherited() { 11729 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 11730 } 11731 11732 /** 11733 * @return true if layout direction has been resolved. 11734 */ 11735 private boolean isLayoutDirectionResolved() { 11736 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 11737 } 11738 11739 /** 11740 * Return if padding has been resolved 11741 * 11742 * @hide 11743 */ 11744 boolean isPaddingResolved() { 11745 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 11746 } 11747 11748 /** 11749 * Resolve padding depending on layout direction. 11750 * 11751 * @hide 11752 */ 11753 public void resolvePadding() { 11754 if (!isRtlCompatibilityMode()) { 11755 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 11756 // If start / end padding are defined, they will be resolved (hence overriding) to 11757 // left / right or right / left depending on the resolved layout direction. 11758 // If start / end padding are not defined, use the left / right ones. 11759 int resolvedLayoutDirection = getLayoutDirection(); 11760 // Set user padding to initial values ... 11761 mUserPaddingLeft = mUserPaddingLeftInitial; 11762 mUserPaddingRight = mUserPaddingRightInitial; 11763 // ... then resolve it. 11764 switch (resolvedLayoutDirection) { 11765 case LAYOUT_DIRECTION_RTL: 11766 if (mUserPaddingStart != UNDEFINED_PADDING) { 11767 mUserPaddingRight = mUserPaddingStart; 11768 } 11769 if (mUserPaddingEnd != UNDEFINED_PADDING) { 11770 mUserPaddingLeft = mUserPaddingEnd; 11771 } 11772 break; 11773 case LAYOUT_DIRECTION_LTR: 11774 default: 11775 if (mUserPaddingStart != UNDEFINED_PADDING) { 11776 mUserPaddingLeft = mUserPaddingStart; 11777 } 11778 if (mUserPaddingEnd != UNDEFINED_PADDING) { 11779 mUserPaddingRight = mUserPaddingEnd; 11780 } 11781 } 11782 11783 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 11784 11785 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, 11786 mUserPaddingBottom); 11787 onRtlPropertiesChanged(resolvedLayoutDirection); 11788 } 11789 11790 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 11791 } 11792 11793 /** 11794 * Reset the resolved layout direction. 11795 * 11796 * @hide 11797 */ 11798 public void resetResolvedPadding() { 11799 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 11800 } 11801 11802 /** 11803 * This is called when the view is detached from a window. At this point it 11804 * no longer has a surface for drawing. 11805 * 11806 * @see #onAttachedToWindow() 11807 */ 11808 protected void onDetachedFromWindow() { 11809 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 11810 11811 removeUnsetPressCallback(); 11812 removeLongPressCallback(); 11813 removePerformClickCallback(); 11814 removeSendViewScrolledAccessibilityEventCallback(); 11815 11816 destroyDrawingCache(); 11817 11818 destroyLayer(false); 11819 11820 if (mAttachInfo != null) { 11821 if (mDisplayList != null) { 11822 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList); 11823 } 11824 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 11825 } else { 11826 // Should never happen 11827 clearDisplayList(); 11828 } 11829 11830 mCurrentAnimation = null; 11831 11832 resetRtlProperties(); 11833 onRtlPropertiesChanged(LAYOUT_DIRECTION_DEFAULT); 11834 resetAccessibilityStateChanged(); 11835 } 11836 11837 /** 11838 * @return The number of times this view has been attached to a window 11839 */ 11840 protected int getWindowAttachCount() { 11841 return mWindowAttachCount; 11842 } 11843 11844 /** 11845 * Retrieve a unique token identifying the window this view is attached to. 11846 * @return Return the window's token for use in 11847 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 11848 */ 11849 public IBinder getWindowToken() { 11850 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 11851 } 11852 11853 /** 11854 * Retrieve a unique token identifying the top-level "real" window of 11855 * the window that this view is attached to. That is, this is like 11856 * {@link #getWindowToken}, except if the window this view in is a panel 11857 * window (attached to another containing window), then the token of 11858 * the containing window is returned instead. 11859 * 11860 * @return Returns the associated window token, either 11861 * {@link #getWindowToken()} or the containing window's token. 11862 */ 11863 public IBinder getApplicationWindowToken() { 11864 AttachInfo ai = mAttachInfo; 11865 if (ai != null) { 11866 IBinder appWindowToken = ai.mPanelParentWindowToken; 11867 if (appWindowToken == null) { 11868 appWindowToken = ai.mWindowToken; 11869 } 11870 return appWindowToken; 11871 } 11872 return null; 11873 } 11874 11875 /** 11876 * Gets the logical display to which the view's window has been attached. 11877 * 11878 * @return The logical display, or null if the view is not currently attached to a window. 11879 */ 11880 public Display getDisplay() { 11881 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 11882 } 11883 11884 /** 11885 * Retrieve private session object this view hierarchy is using to 11886 * communicate with the window manager. 11887 * @return the session object to communicate with the window manager 11888 */ 11889 /*package*/ IWindowSession getWindowSession() { 11890 return mAttachInfo != null ? mAttachInfo.mSession : null; 11891 } 11892 11893 /** 11894 * @param info the {@link android.view.View.AttachInfo} to associated with 11895 * this view 11896 */ 11897 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 11898 //System.out.println("Attached! " + this); 11899 mAttachInfo = info; 11900 mWindowAttachCount++; 11901 // We will need to evaluate the drawable state at least once. 11902 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 11903 if (mFloatingTreeObserver != null) { 11904 info.mTreeObserver.merge(mFloatingTreeObserver); 11905 mFloatingTreeObserver = null; 11906 } 11907 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 11908 mAttachInfo.mScrollContainers.add(this); 11909 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 11910 } 11911 performCollectViewAttributes(mAttachInfo, visibility); 11912 onAttachedToWindow(); 11913 11914 ListenerInfo li = mListenerInfo; 11915 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 11916 li != null ? li.mOnAttachStateChangeListeners : null; 11917 if (listeners != null && listeners.size() > 0) { 11918 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 11919 // perform the dispatching. The iterator is a safe guard against listeners that 11920 // could mutate the list by calling the various add/remove methods. This prevents 11921 // the array from being modified while we iterate it. 11922 for (OnAttachStateChangeListener listener : listeners) { 11923 listener.onViewAttachedToWindow(this); 11924 } 11925 } 11926 11927 int vis = info.mWindowVisibility; 11928 if (vis != GONE) { 11929 onWindowVisibilityChanged(vis); 11930 } 11931 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 11932 // If nobody has evaluated the drawable state yet, then do it now. 11933 refreshDrawableState(); 11934 } 11935 needGlobalAttributesUpdate(false); 11936 } 11937 11938 void dispatchDetachedFromWindow() { 11939 AttachInfo info = mAttachInfo; 11940 if (info != null) { 11941 int vis = info.mWindowVisibility; 11942 if (vis != GONE) { 11943 onWindowVisibilityChanged(GONE); 11944 } 11945 } 11946 11947 onDetachedFromWindow(); 11948 11949 ListenerInfo li = mListenerInfo; 11950 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 11951 li != null ? li.mOnAttachStateChangeListeners : null; 11952 if (listeners != null && listeners.size() > 0) { 11953 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 11954 // perform the dispatching. The iterator is a safe guard against listeners that 11955 // could mutate the list by calling the various add/remove methods. This prevents 11956 // the array from being modified while we iterate it. 11957 for (OnAttachStateChangeListener listener : listeners) { 11958 listener.onViewDetachedFromWindow(this); 11959 } 11960 } 11961 11962 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 11963 mAttachInfo.mScrollContainers.remove(this); 11964 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 11965 } 11966 11967 mAttachInfo = null; 11968 } 11969 11970 /** 11971 * Store this view hierarchy's frozen state into the given container. 11972 * 11973 * @param container The SparseArray in which to save the view's state. 11974 * 11975 * @see #restoreHierarchyState(android.util.SparseArray) 11976 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11977 * @see #onSaveInstanceState() 11978 */ 11979 public void saveHierarchyState(SparseArray<Parcelable> container) { 11980 dispatchSaveInstanceState(container); 11981 } 11982 11983 /** 11984 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 11985 * this view and its children. May be overridden to modify how freezing happens to a 11986 * view's children; for example, some views may want to not store state for their children. 11987 * 11988 * @param container The SparseArray in which to save the view's state. 11989 * 11990 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 11991 * @see #saveHierarchyState(android.util.SparseArray) 11992 * @see #onSaveInstanceState() 11993 */ 11994 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 11995 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 11996 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 11997 Parcelable state = onSaveInstanceState(); 11998 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 11999 throw new IllegalStateException( 12000 "Derived class did not call super.onSaveInstanceState()"); 12001 } 12002 if (state != null) { 12003 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 12004 // + ": " + state); 12005 container.put(mID, state); 12006 } 12007 } 12008 } 12009 12010 /** 12011 * Hook allowing a view to generate a representation of its internal state 12012 * that can later be used to create a new instance with that same state. 12013 * This state should only contain information that is not persistent or can 12014 * not be reconstructed later. For example, you will never store your 12015 * current position on screen because that will be computed again when a 12016 * new instance of the view is placed in its view hierarchy. 12017 * <p> 12018 * Some examples of things you may store here: the current cursor position 12019 * in a text view (but usually not the text itself since that is stored in a 12020 * content provider or other persistent storage), the currently selected 12021 * item in a list view. 12022 * 12023 * @return Returns a Parcelable object containing the view's current dynamic 12024 * state, or null if there is nothing interesting to save. The 12025 * default implementation returns null. 12026 * @see #onRestoreInstanceState(android.os.Parcelable) 12027 * @see #saveHierarchyState(android.util.SparseArray) 12028 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12029 * @see #setSaveEnabled(boolean) 12030 */ 12031 protected Parcelable onSaveInstanceState() { 12032 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12033 return BaseSavedState.EMPTY_STATE; 12034 } 12035 12036 /** 12037 * Restore this view hierarchy's frozen state from the given container. 12038 * 12039 * @param container The SparseArray which holds previously frozen states. 12040 * 12041 * @see #saveHierarchyState(android.util.SparseArray) 12042 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12043 * @see #onRestoreInstanceState(android.os.Parcelable) 12044 */ 12045 public void restoreHierarchyState(SparseArray<Parcelable> container) { 12046 dispatchRestoreInstanceState(container); 12047 } 12048 12049 /** 12050 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 12051 * state for this view and its children. May be overridden to modify how restoring 12052 * happens to a view's children; for example, some views may want to not store state 12053 * for their children. 12054 * 12055 * @param container The SparseArray which holds previously saved state. 12056 * 12057 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12058 * @see #restoreHierarchyState(android.util.SparseArray) 12059 * @see #onRestoreInstanceState(android.os.Parcelable) 12060 */ 12061 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 12062 if (mID != NO_ID) { 12063 Parcelable state = container.get(mID); 12064 if (state != null) { 12065 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 12066 // + ": " + state); 12067 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 12068 onRestoreInstanceState(state); 12069 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 12070 throw new IllegalStateException( 12071 "Derived class did not call super.onRestoreInstanceState()"); 12072 } 12073 } 12074 } 12075 } 12076 12077 /** 12078 * Hook allowing a view to re-apply a representation of its internal state that had previously 12079 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 12080 * null state. 12081 * 12082 * @param state The frozen state that had previously been returned by 12083 * {@link #onSaveInstanceState}. 12084 * 12085 * @see #onSaveInstanceState() 12086 * @see #restoreHierarchyState(android.util.SparseArray) 12087 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12088 */ 12089 protected void onRestoreInstanceState(Parcelable state) { 12090 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12091 if (state != BaseSavedState.EMPTY_STATE && state != null) { 12092 throw new IllegalArgumentException("Wrong state class, expecting View State but " 12093 + "received " + state.getClass().toString() + " instead. This usually happens " 12094 + "when two views of different type have the same id in the same hierarchy. " 12095 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 12096 + "other views do not use the same id."); 12097 } 12098 } 12099 12100 /** 12101 * <p>Return the time at which the drawing of the view hierarchy started.</p> 12102 * 12103 * @return the drawing start time in milliseconds 12104 */ 12105 public long getDrawingTime() { 12106 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 12107 } 12108 12109 /** 12110 * <p>Enables or disables the duplication of the parent's state into this view. When 12111 * duplication is enabled, this view gets its drawable state from its parent rather 12112 * than from its own internal properties.</p> 12113 * 12114 * <p>Note: in the current implementation, setting this property to true after the 12115 * view was added to a ViewGroup might have no effect at all. This property should 12116 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 12117 * 12118 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 12119 * property is enabled, an exception will be thrown.</p> 12120 * 12121 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 12122 * parent, these states should not be affected by this method.</p> 12123 * 12124 * @param enabled True to enable duplication of the parent's drawable state, false 12125 * to disable it. 12126 * 12127 * @see #getDrawableState() 12128 * @see #isDuplicateParentStateEnabled() 12129 */ 12130 public void setDuplicateParentStateEnabled(boolean enabled) { 12131 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 12132 } 12133 12134 /** 12135 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 12136 * 12137 * @return True if this view's drawable state is duplicated from the parent, 12138 * false otherwise 12139 * 12140 * @see #getDrawableState() 12141 * @see #setDuplicateParentStateEnabled(boolean) 12142 */ 12143 public boolean isDuplicateParentStateEnabled() { 12144 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 12145 } 12146 12147 /** 12148 * <p>Specifies the type of layer backing this view. The layer can be 12149 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 12150 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 12151 * 12152 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12153 * instance that controls how the layer is composed on screen. The following 12154 * properties of the paint are taken into account when composing the layer:</p> 12155 * <ul> 12156 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12157 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12158 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12159 * </ul> 12160 * 12161 * <p>If this view has an alpha value set to < 1.0 by calling 12162 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 12163 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 12164 * equivalent to setting a hardware layer on this view and providing a paint with 12165 * the desired alpha value.</p> 12166 * 12167 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 12168 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 12169 * for more information on when and how to use layers.</p> 12170 * 12171 * @param layerType The type of layer to use with this view, must be one of 12172 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12173 * {@link #LAYER_TYPE_HARDWARE} 12174 * @param paint The paint used to compose the layer. This argument is optional 12175 * and can be null. It is ignored when the layer type is 12176 * {@link #LAYER_TYPE_NONE} 12177 * 12178 * @see #getLayerType() 12179 * @see #LAYER_TYPE_NONE 12180 * @see #LAYER_TYPE_SOFTWARE 12181 * @see #LAYER_TYPE_HARDWARE 12182 * @see #setAlpha(float) 12183 * 12184 * @attr ref android.R.styleable#View_layerType 12185 */ 12186 public void setLayerType(int layerType, Paint paint) { 12187 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 12188 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 12189 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 12190 } 12191 12192 if (layerType == mLayerType) { 12193 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 12194 mLayerPaint = paint == null ? new Paint() : paint; 12195 invalidateParentCaches(); 12196 invalidate(true); 12197 } 12198 return; 12199 } 12200 12201 // Destroy any previous software drawing cache if needed 12202 switch (mLayerType) { 12203 case LAYER_TYPE_HARDWARE: 12204 destroyLayer(false); 12205 // fall through - non-accelerated views may use software layer mechanism instead 12206 case LAYER_TYPE_SOFTWARE: 12207 destroyDrawingCache(); 12208 break; 12209 default: 12210 break; 12211 } 12212 12213 mLayerType = layerType; 12214 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 12215 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 12216 mLocalDirtyRect = layerDisabled ? null : new Rect(); 12217 12218 invalidateParentCaches(); 12219 invalidate(true); 12220 } 12221 12222 /** 12223 * Updates the {@link Paint} object used with the current layer (used only if the current 12224 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 12225 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 12226 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 12227 * ensure that the view gets redrawn immediately. 12228 * 12229 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12230 * instance that controls how the layer is composed on screen. The following 12231 * properties of the paint are taken into account when composing the layer:</p> 12232 * <ul> 12233 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12234 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12235 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12236 * </ul> 12237 * 12238 * <p>If this view has an alpha value set to < 1.0 by calling 12239 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 12240 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 12241 * equivalent to setting a hardware layer on this view and providing a paint with 12242 * the desired alpha value.</p> 12243 * 12244 * @param paint The paint used to compose the layer. This argument is optional 12245 * and can be null. It is ignored when the layer type is 12246 * {@link #LAYER_TYPE_NONE} 12247 * 12248 * @see #setLayerType(int, android.graphics.Paint) 12249 */ 12250 public void setLayerPaint(Paint paint) { 12251 int layerType = getLayerType(); 12252 if (layerType != LAYER_TYPE_NONE) { 12253 mLayerPaint = paint == null ? new Paint() : paint; 12254 if (layerType == LAYER_TYPE_HARDWARE) { 12255 HardwareLayer layer = getHardwareLayer(); 12256 if (layer != null) { 12257 layer.setLayerPaint(paint); 12258 } 12259 invalidateViewProperty(false, false); 12260 } else { 12261 invalidate(); 12262 } 12263 } 12264 } 12265 12266 /** 12267 * Indicates whether this view has a static layer. A view with layer type 12268 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 12269 * dynamic. 12270 */ 12271 boolean hasStaticLayer() { 12272 return true; 12273 } 12274 12275 /** 12276 * Indicates what type of layer is currently associated with this view. By default 12277 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 12278 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 12279 * for more information on the different types of layers. 12280 * 12281 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12282 * {@link #LAYER_TYPE_HARDWARE} 12283 * 12284 * @see #setLayerType(int, android.graphics.Paint) 12285 * @see #buildLayer() 12286 * @see #LAYER_TYPE_NONE 12287 * @see #LAYER_TYPE_SOFTWARE 12288 * @see #LAYER_TYPE_HARDWARE 12289 */ 12290 public int getLayerType() { 12291 return mLayerType; 12292 } 12293 12294 /** 12295 * Forces this view's layer to be created and this view to be rendered 12296 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 12297 * invoking this method will have no effect. 12298 * 12299 * This method can for instance be used to render a view into its layer before 12300 * starting an animation. If this view is complex, rendering into the layer 12301 * before starting the animation will avoid skipping frames. 12302 * 12303 * @throws IllegalStateException If this view is not attached to a window 12304 * 12305 * @see #setLayerType(int, android.graphics.Paint) 12306 */ 12307 public void buildLayer() { 12308 if (mLayerType == LAYER_TYPE_NONE) return; 12309 12310 if (mAttachInfo == null) { 12311 throw new IllegalStateException("This view must be attached to a window first"); 12312 } 12313 12314 switch (mLayerType) { 12315 case LAYER_TYPE_HARDWARE: 12316 if (mAttachInfo.mHardwareRenderer != null && 12317 mAttachInfo.mHardwareRenderer.isEnabled() && 12318 mAttachInfo.mHardwareRenderer.validate()) { 12319 getHardwareLayer(); 12320 } 12321 break; 12322 case LAYER_TYPE_SOFTWARE: 12323 buildDrawingCache(true); 12324 break; 12325 } 12326 } 12327 12328 /** 12329 * <p>Returns a hardware layer that can be used to draw this view again 12330 * without executing its draw method.</p> 12331 * 12332 * @return A HardwareLayer ready to render, or null if an error occurred. 12333 */ 12334 HardwareLayer getHardwareLayer() { 12335 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 12336 !mAttachInfo.mHardwareRenderer.isEnabled()) { 12337 return null; 12338 } 12339 12340 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 12341 12342 final int width = mRight - mLeft; 12343 final int height = mBottom - mTop; 12344 12345 if (width == 0 || height == 0) { 12346 return null; 12347 } 12348 12349 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 12350 if (mHardwareLayer == null) { 12351 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 12352 width, height, isOpaque()); 12353 mLocalDirtyRect.set(0, 0, width, height); 12354 } else { 12355 if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 12356 if (mHardwareLayer.resize(width, height)) { 12357 mLocalDirtyRect.set(0, 0, width, height); 12358 } 12359 } 12360 12361 // This should not be necessary but applications that change 12362 // the parameters of their background drawable without calling 12363 // this.setBackground(Drawable) can leave the view in a bad state 12364 // (for instance isOpaque() returns true, but the background is 12365 // not opaque.) 12366 computeOpaqueFlags(); 12367 12368 final boolean opaque = isOpaque(); 12369 if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) { 12370 mHardwareLayer.setOpaque(opaque); 12371 mLocalDirtyRect.set(0, 0, width, height); 12372 } 12373 } 12374 12375 // The layer is not valid if the underlying GPU resources cannot be allocated 12376 if (!mHardwareLayer.isValid()) { 12377 return null; 12378 } 12379 12380 mHardwareLayer.setLayerPaint(mLayerPaint); 12381 mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 12382 ViewRootImpl viewRoot = getViewRootImpl(); 12383 if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer); 12384 12385 mLocalDirtyRect.setEmpty(); 12386 } 12387 12388 return mHardwareLayer; 12389 } 12390 12391 /** 12392 * Destroys this View's hardware layer if possible. 12393 * 12394 * @return True if the layer was destroyed, false otherwise. 12395 * 12396 * @see #setLayerType(int, android.graphics.Paint) 12397 * @see #LAYER_TYPE_HARDWARE 12398 */ 12399 boolean destroyLayer(boolean valid) { 12400 if (mHardwareLayer != null) { 12401 AttachInfo info = mAttachInfo; 12402 if (info != null && info.mHardwareRenderer != null && 12403 info.mHardwareRenderer.isEnabled() && 12404 (valid || info.mHardwareRenderer.validate())) { 12405 mHardwareLayer.destroy(); 12406 mHardwareLayer = null; 12407 12408 if (mDisplayList != null) { 12409 mDisplayList.reset(); 12410 } 12411 invalidate(true); 12412 invalidateParentCaches(); 12413 } 12414 return true; 12415 } 12416 return false; 12417 } 12418 12419 /** 12420 * Destroys all hardware rendering resources. This method is invoked 12421 * when the system needs to reclaim resources. Upon execution of this 12422 * method, you should free any OpenGL resources created by the view. 12423 * 12424 * Note: you <strong>must</strong> call 12425 * <code>super.destroyHardwareResources()</code> when overriding 12426 * this method. 12427 * 12428 * @hide 12429 */ 12430 protected void destroyHardwareResources() { 12431 destroyLayer(true); 12432 } 12433 12434 /** 12435 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 12436 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 12437 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 12438 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 12439 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 12440 * null.</p> 12441 * 12442 * <p>Enabling the drawing cache is similar to 12443 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 12444 * acceleration is turned off. When hardware acceleration is turned on, enabling the 12445 * drawing cache has no effect on rendering because the system uses a different mechanism 12446 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 12447 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 12448 * for information on how to enable software and hardware layers.</p> 12449 * 12450 * <p>This API can be used to manually generate 12451 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 12452 * {@link #getDrawingCache()}.</p> 12453 * 12454 * @param enabled true to enable the drawing cache, false otherwise 12455 * 12456 * @see #isDrawingCacheEnabled() 12457 * @see #getDrawingCache() 12458 * @see #buildDrawingCache() 12459 * @see #setLayerType(int, android.graphics.Paint) 12460 */ 12461 public void setDrawingCacheEnabled(boolean enabled) { 12462 mCachingFailed = false; 12463 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 12464 } 12465 12466 /** 12467 * <p>Indicates whether the drawing cache is enabled for this view.</p> 12468 * 12469 * @return true if the drawing cache is enabled 12470 * 12471 * @see #setDrawingCacheEnabled(boolean) 12472 * @see #getDrawingCache() 12473 */ 12474 @ViewDebug.ExportedProperty(category = "drawing") 12475 public boolean isDrawingCacheEnabled() { 12476 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 12477 } 12478 12479 /** 12480 * Debugging utility which recursively outputs the dirty state of a view and its 12481 * descendants. 12482 * 12483 * @hide 12484 */ 12485 @SuppressWarnings({"UnusedDeclaration"}) 12486 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 12487 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 12488 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 12489 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 12490 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 12491 if (clear) { 12492 mPrivateFlags &= clearMask; 12493 } 12494 if (this instanceof ViewGroup) { 12495 ViewGroup parent = (ViewGroup) this; 12496 final int count = parent.getChildCount(); 12497 for (int i = 0; i < count; i++) { 12498 final View child = parent.getChildAt(i); 12499 child.outputDirtyFlags(indent + " ", clear, clearMask); 12500 } 12501 } 12502 } 12503 12504 /** 12505 * This method is used by ViewGroup to cause its children to restore or recreate their 12506 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 12507 * to recreate its own display list, which would happen if it went through the normal 12508 * draw/dispatchDraw mechanisms. 12509 * 12510 * @hide 12511 */ 12512 protected void dispatchGetDisplayList() {} 12513 12514 /** 12515 * A view that is not attached or hardware accelerated cannot create a display list. 12516 * This method checks these conditions and returns the appropriate result. 12517 * 12518 * @return true if view has the ability to create a display list, false otherwise. 12519 * 12520 * @hide 12521 */ 12522 public boolean canHaveDisplayList() { 12523 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 12524 } 12525 12526 /** 12527 * @return The HardwareRenderer associated with that view or null if hardware rendering 12528 * is not supported or this this has not been attached to a window. 12529 * 12530 * @hide 12531 */ 12532 public HardwareRenderer getHardwareRenderer() { 12533 if (mAttachInfo != null) { 12534 return mAttachInfo.mHardwareRenderer; 12535 } 12536 return null; 12537 } 12538 12539 /** 12540 * Returns a DisplayList. If the incoming displayList is null, one will be created. 12541 * Otherwise, the same display list will be returned (after having been rendered into 12542 * along the way, depending on the invalidation state of the view). 12543 * 12544 * @param displayList The previous version of this displayList, could be null. 12545 * @param isLayer Whether the requester of the display list is a layer. If so, 12546 * the view will avoid creating a layer inside the resulting display list. 12547 * @return A new or reused DisplayList object. 12548 */ 12549 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 12550 if (!canHaveDisplayList()) { 12551 return null; 12552 } 12553 12554 if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || 12555 displayList == null || !displayList.isValid() || 12556 (!isLayer && mRecreateDisplayList))) { 12557 // Don't need to recreate the display list, just need to tell our 12558 // children to restore/recreate theirs 12559 if (displayList != null && displayList.isValid() && 12560 !isLayer && !mRecreateDisplayList) { 12561 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12562 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12563 dispatchGetDisplayList(); 12564 12565 return displayList; 12566 } 12567 12568 if (!isLayer) { 12569 // If we got here, we're recreating it. Mark it as such to ensure that 12570 // we copy in child display lists into ours in drawChild() 12571 mRecreateDisplayList = true; 12572 } 12573 if (displayList == null) { 12574 final String name = getClass().getSimpleName(); 12575 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name); 12576 // If we're creating a new display list, make sure our parent gets invalidated 12577 // since they will need to recreate their display list to account for this 12578 // new child display list. 12579 invalidateParentCaches(); 12580 } 12581 12582 boolean caching = false; 12583 final HardwareCanvas canvas = displayList.start(); 12584 int width = mRight - mLeft; 12585 int height = mBottom - mTop; 12586 12587 try { 12588 canvas.setViewport(width, height); 12589 // The dirty rect should always be null for a display list 12590 canvas.onPreDraw(null); 12591 int layerType = getLayerType(); 12592 if (!isLayer && layerType != LAYER_TYPE_NONE) { 12593 if (layerType == LAYER_TYPE_HARDWARE) { 12594 final HardwareLayer layer = getHardwareLayer(); 12595 if (layer != null && layer.isValid()) { 12596 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 12597 } else { 12598 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 12599 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 12600 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 12601 } 12602 caching = true; 12603 } else { 12604 buildDrawingCache(true); 12605 Bitmap cache = getDrawingCache(true); 12606 if (cache != null) { 12607 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 12608 caching = true; 12609 } 12610 } 12611 } else { 12612 12613 computeScroll(); 12614 12615 canvas.translate(-mScrollX, -mScrollY); 12616 if (!isLayer) { 12617 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12618 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12619 } 12620 12621 // Fast path for layouts with no backgrounds 12622 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12623 dispatchDraw(canvas); 12624 } else { 12625 draw(canvas); 12626 } 12627 } 12628 } finally { 12629 canvas.onPostDraw(); 12630 12631 displayList.end(); 12632 displayList.setCaching(caching); 12633 if (isLayer) { 12634 displayList.setLeftTopRightBottom(0, 0, width, height); 12635 } else { 12636 setDisplayListProperties(displayList); 12637 } 12638 } 12639 } else if (!isLayer) { 12640 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12641 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12642 } 12643 12644 return displayList; 12645 } 12646 12647 /** 12648 * Get the DisplayList for the HardwareLayer 12649 * 12650 * @param layer The HardwareLayer whose DisplayList we want 12651 * @return A DisplayList fopr the specified HardwareLayer 12652 */ 12653 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 12654 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 12655 layer.setDisplayList(displayList); 12656 return displayList; 12657 } 12658 12659 12660 /** 12661 * <p>Returns a display list that can be used to draw this view again 12662 * without executing its draw method.</p> 12663 * 12664 * @return A DisplayList ready to replay, or null if caching is not enabled. 12665 * 12666 * @hide 12667 */ 12668 public DisplayList getDisplayList() { 12669 mDisplayList = getDisplayList(mDisplayList, false); 12670 return mDisplayList; 12671 } 12672 12673 private void clearDisplayList() { 12674 if (mDisplayList != null) { 12675 mDisplayList.invalidate(); 12676 mDisplayList.clear(); 12677 } 12678 } 12679 12680 /** 12681 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 12682 * 12683 * @return A non-scaled bitmap representing this view or null if cache is disabled. 12684 * 12685 * @see #getDrawingCache(boolean) 12686 */ 12687 public Bitmap getDrawingCache() { 12688 return getDrawingCache(false); 12689 } 12690 12691 /** 12692 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 12693 * is null when caching is disabled. If caching is enabled and the cache is not ready, 12694 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 12695 * draw from the cache when the cache is enabled. To benefit from the cache, you must 12696 * request the drawing cache by calling this method and draw it on screen if the 12697 * returned bitmap is not null.</p> 12698 * 12699 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 12700 * this method will create a bitmap of the same size as this view. Because this bitmap 12701 * will be drawn scaled by the parent ViewGroup, the result on screen might show 12702 * scaling artifacts. To avoid such artifacts, you should call this method by setting 12703 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 12704 * size than the view. This implies that your application must be able to handle this 12705 * size.</p> 12706 * 12707 * @param autoScale Indicates whether the generated bitmap should be scaled based on 12708 * the current density of the screen when the application is in compatibility 12709 * mode. 12710 * 12711 * @return A bitmap representing this view or null if cache is disabled. 12712 * 12713 * @see #setDrawingCacheEnabled(boolean) 12714 * @see #isDrawingCacheEnabled() 12715 * @see #buildDrawingCache(boolean) 12716 * @see #destroyDrawingCache() 12717 */ 12718 public Bitmap getDrawingCache(boolean autoScale) { 12719 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 12720 return null; 12721 } 12722 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 12723 buildDrawingCache(autoScale); 12724 } 12725 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 12726 } 12727 12728 /** 12729 * <p>Frees the resources used by the drawing cache. If you call 12730 * {@link #buildDrawingCache()} manually without calling 12731 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 12732 * should cleanup the cache with this method afterwards.</p> 12733 * 12734 * @see #setDrawingCacheEnabled(boolean) 12735 * @see #buildDrawingCache() 12736 * @see #getDrawingCache() 12737 */ 12738 public void destroyDrawingCache() { 12739 if (mDrawingCache != null) { 12740 mDrawingCache.recycle(); 12741 mDrawingCache = null; 12742 } 12743 if (mUnscaledDrawingCache != null) { 12744 mUnscaledDrawingCache.recycle(); 12745 mUnscaledDrawingCache = null; 12746 } 12747 } 12748 12749 /** 12750 * Setting a solid background color for the drawing cache's bitmaps will improve 12751 * performance and memory usage. Note, though that this should only be used if this 12752 * view will always be drawn on top of a solid color. 12753 * 12754 * @param color The background color to use for the drawing cache's bitmap 12755 * 12756 * @see #setDrawingCacheEnabled(boolean) 12757 * @see #buildDrawingCache() 12758 * @see #getDrawingCache() 12759 */ 12760 public void setDrawingCacheBackgroundColor(int color) { 12761 if (color != mDrawingCacheBackgroundColor) { 12762 mDrawingCacheBackgroundColor = color; 12763 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 12764 } 12765 } 12766 12767 /** 12768 * @see #setDrawingCacheBackgroundColor(int) 12769 * 12770 * @return The background color to used for the drawing cache's bitmap 12771 */ 12772 public int getDrawingCacheBackgroundColor() { 12773 return mDrawingCacheBackgroundColor; 12774 } 12775 12776 /** 12777 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 12778 * 12779 * @see #buildDrawingCache(boolean) 12780 */ 12781 public void buildDrawingCache() { 12782 buildDrawingCache(false); 12783 } 12784 12785 /** 12786 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 12787 * 12788 * <p>If you call {@link #buildDrawingCache()} manually without calling 12789 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 12790 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 12791 * 12792 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 12793 * this method will create a bitmap of the same size as this view. Because this bitmap 12794 * will be drawn scaled by the parent ViewGroup, the result on screen might show 12795 * scaling artifacts. To avoid such artifacts, you should call this method by setting 12796 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 12797 * size than the view. This implies that your application must be able to handle this 12798 * size.</p> 12799 * 12800 * <p>You should avoid calling this method when hardware acceleration is enabled. If 12801 * you do not need the drawing cache bitmap, calling this method will increase memory 12802 * usage and cause the view to be rendered in software once, thus negatively impacting 12803 * performance.</p> 12804 * 12805 * @see #getDrawingCache() 12806 * @see #destroyDrawingCache() 12807 */ 12808 public void buildDrawingCache(boolean autoScale) { 12809 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 12810 mDrawingCache == null : mUnscaledDrawingCache == null)) { 12811 mCachingFailed = false; 12812 12813 int width = mRight - mLeft; 12814 int height = mBottom - mTop; 12815 12816 final AttachInfo attachInfo = mAttachInfo; 12817 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 12818 12819 if (autoScale && scalingRequired) { 12820 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 12821 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 12822 } 12823 12824 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 12825 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 12826 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 12827 12828 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 12829 final long drawingCacheSize = 12830 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 12831 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 12832 if (width > 0 && height > 0) { 12833 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 12834 + projectedBitmapSize + " bytes, only " 12835 + drawingCacheSize + " available"); 12836 } 12837 destroyDrawingCache(); 12838 mCachingFailed = true; 12839 return; 12840 } 12841 12842 boolean clear = true; 12843 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 12844 12845 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 12846 Bitmap.Config quality; 12847 if (!opaque) { 12848 // Never pick ARGB_4444 because it looks awful 12849 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 12850 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 12851 case DRAWING_CACHE_QUALITY_AUTO: 12852 quality = Bitmap.Config.ARGB_8888; 12853 break; 12854 case DRAWING_CACHE_QUALITY_LOW: 12855 quality = Bitmap.Config.ARGB_8888; 12856 break; 12857 case DRAWING_CACHE_QUALITY_HIGH: 12858 quality = Bitmap.Config.ARGB_8888; 12859 break; 12860 default: 12861 quality = Bitmap.Config.ARGB_8888; 12862 break; 12863 } 12864 } else { 12865 // Optimization for translucent windows 12866 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 12867 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 12868 } 12869 12870 // Try to cleanup memory 12871 if (bitmap != null) bitmap.recycle(); 12872 12873 try { 12874 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 12875 width, height, quality); 12876 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 12877 if (autoScale) { 12878 mDrawingCache = bitmap; 12879 } else { 12880 mUnscaledDrawingCache = bitmap; 12881 } 12882 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 12883 } catch (OutOfMemoryError e) { 12884 // If there is not enough memory to create the bitmap cache, just 12885 // ignore the issue as bitmap caches are not required to draw the 12886 // view hierarchy 12887 if (autoScale) { 12888 mDrawingCache = null; 12889 } else { 12890 mUnscaledDrawingCache = null; 12891 } 12892 mCachingFailed = true; 12893 return; 12894 } 12895 12896 clear = drawingCacheBackgroundColor != 0; 12897 } 12898 12899 Canvas canvas; 12900 if (attachInfo != null) { 12901 canvas = attachInfo.mCanvas; 12902 if (canvas == null) { 12903 canvas = new Canvas(); 12904 } 12905 canvas.setBitmap(bitmap); 12906 // Temporarily clobber the cached Canvas in case one of our children 12907 // is also using a drawing cache. Without this, the children would 12908 // steal the canvas by attaching their own bitmap to it and bad, bad 12909 // thing would happen (invisible views, corrupted drawings, etc.) 12910 attachInfo.mCanvas = null; 12911 } else { 12912 // This case should hopefully never or seldom happen 12913 canvas = new Canvas(bitmap); 12914 } 12915 12916 if (clear) { 12917 bitmap.eraseColor(drawingCacheBackgroundColor); 12918 } 12919 12920 computeScroll(); 12921 final int restoreCount = canvas.save(); 12922 12923 if (autoScale && scalingRequired) { 12924 final float scale = attachInfo.mApplicationScale; 12925 canvas.scale(scale, scale); 12926 } 12927 12928 canvas.translate(-mScrollX, -mScrollY); 12929 12930 mPrivateFlags |= PFLAG_DRAWN; 12931 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 12932 mLayerType != LAYER_TYPE_NONE) { 12933 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 12934 } 12935 12936 // Fast path for layouts with no backgrounds 12937 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12938 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12939 dispatchDraw(canvas); 12940 } else { 12941 draw(canvas); 12942 } 12943 12944 canvas.restoreToCount(restoreCount); 12945 canvas.setBitmap(null); 12946 12947 if (attachInfo != null) { 12948 // Restore the cached Canvas for our siblings 12949 attachInfo.mCanvas = canvas; 12950 } 12951 } 12952 } 12953 12954 /** 12955 * Create a snapshot of the view into a bitmap. We should probably make 12956 * some form of this public, but should think about the API. 12957 */ 12958 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 12959 int width = mRight - mLeft; 12960 int height = mBottom - mTop; 12961 12962 final AttachInfo attachInfo = mAttachInfo; 12963 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 12964 width = (int) ((width * scale) + 0.5f); 12965 height = (int) ((height * scale) + 0.5f); 12966 12967 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 12968 width > 0 ? width : 1, height > 0 ? height : 1, quality); 12969 if (bitmap == null) { 12970 throw new OutOfMemoryError(); 12971 } 12972 12973 Resources resources = getResources(); 12974 if (resources != null) { 12975 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 12976 } 12977 12978 Canvas canvas; 12979 if (attachInfo != null) { 12980 canvas = attachInfo.mCanvas; 12981 if (canvas == null) { 12982 canvas = new Canvas(); 12983 } 12984 canvas.setBitmap(bitmap); 12985 // Temporarily clobber the cached Canvas in case one of our children 12986 // is also using a drawing cache. Without this, the children would 12987 // steal the canvas by attaching their own bitmap to it and bad, bad 12988 // things would happen (invisible views, corrupted drawings, etc.) 12989 attachInfo.mCanvas = null; 12990 } else { 12991 // This case should hopefully never or seldom happen 12992 canvas = new Canvas(bitmap); 12993 } 12994 12995 if ((backgroundColor & 0xff000000) != 0) { 12996 bitmap.eraseColor(backgroundColor); 12997 } 12998 12999 computeScroll(); 13000 final int restoreCount = canvas.save(); 13001 canvas.scale(scale, scale); 13002 canvas.translate(-mScrollX, -mScrollY); 13003 13004 // Temporarily remove the dirty mask 13005 int flags = mPrivateFlags; 13006 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13007 13008 // Fast path for layouts with no backgrounds 13009 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13010 dispatchDraw(canvas); 13011 } else { 13012 draw(canvas); 13013 } 13014 13015 mPrivateFlags = flags; 13016 13017 canvas.restoreToCount(restoreCount); 13018 canvas.setBitmap(null); 13019 13020 if (attachInfo != null) { 13021 // Restore the cached Canvas for our siblings 13022 attachInfo.mCanvas = canvas; 13023 } 13024 13025 return bitmap; 13026 } 13027 13028 /** 13029 * Indicates whether this View is currently in edit mode. A View is usually 13030 * in edit mode when displayed within a developer tool. For instance, if 13031 * this View is being drawn by a visual user interface builder, this method 13032 * should return true. 13033 * 13034 * Subclasses should check the return value of this method to provide 13035 * different behaviors if their normal behavior might interfere with the 13036 * host environment. For instance: the class spawns a thread in its 13037 * constructor, the drawing code relies on device-specific features, etc. 13038 * 13039 * This method is usually checked in the drawing code of custom widgets. 13040 * 13041 * @return True if this View is in edit mode, false otherwise. 13042 */ 13043 public boolean isInEditMode() { 13044 return false; 13045 } 13046 13047 /** 13048 * If the View draws content inside its padding and enables fading edges, 13049 * it needs to support padding offsets. Padding offsets are added to the 13050 * fading edges to extend the length of the fade so that it covers pixels 13051 * drawn inside the padding. 13052 * 13053 * Subclasses of this class should override this method if they need 13054 * to draw content inside the padding. 13055 * 13056 * @return True if padding offset must be applied, false otherwise. 13057 * 13058 * @see #getLeftPaddingOffset() 13059 * @see #getRightPaddingOffset() 13060 * @see #getTopPaddingOffset() 13061 * @see #getBottomPaddingOffset() 13062 * 13063 * @since CURRENT 13064 */ 13065 protected boolean isPaddingOffsetRequired() { 13066 return false; 13067 } 13068 13069 /** 13070 * Amount by which to extend the left fading region. Called only when 13071 * {@link #isPaddingOffsetRequired()} returns true. 13072 * 13073 * @return The left padding offset in pixels. 13074 * 13075 * @see #isPaddingOffsetRequired() 13076 * 13077 * @since CURRENT 13078 */ 13079 protected int getLeftPaddingOffset() { 13080 return 0; 13081 } 13082 13083 /** 13084 * Amount by which to extend the right fading region. Called only when 13085 * {@link #isPaddingOffsetRequired()} returns true. 13086 * 13087 * @return The right padding offset in pixels. 13088 * 13089 * @see #isPaddingOffsetRequired() 13090 * 13091 * @since CURRENT 13092 */ 13093 protected int getRightPaddingOffset() { 13094 return 0; 13095 } 13096 13097 /** 13098 * Amount by which to extend the top fading region. Called only when 13099 * {@link #isPaddingOffsetRequired()} returns true. 13100 * 13101 * @return The top padding offset in pixels. 13102 * 13103 * @see #isPaddingOffsetRequired() 13104 * 13105 * @since CURRENT 13106 */ 13107 protected int getTopPaddingOffset() { 13108 return 0; 13109 } 13110 13111 /** 13112 * Amount by which to extend the bottom fading region. Called only when 13113 * {@link #isPaddingOffsetRequired()} returns true. 13114 * 13115 * @return The bottom padding offset in pixels. 13116 * 13117 * @see #isPaddingOffsetRequired() 13118 * 13119 * @since CURRENT 13120 */ 13121 protected int getBottomPaddingOffset() { 13122 return 0; 13123 } 13124 13125 /** 13126 * @hide 13127 * @param offsetRequired 13128 */ 13129 protected int getFadeTop(boolean offsetRequired) { 13130 int top = mPaddingTop; 13131 if (offsetRequired) top += getTopPaddingOffset(); 13132 return top; 13133 } 13134 13135 /** 13136 * @hide 13137 * @param offsetRequired 13138 */ 13139 protected int getFadeHeight(boolean offsetRequired) { 13140 int padding = mPaddingTop; 13141 if (offsetRequired) padding += getTopPaddingOffset(); 13142 return mBottom - mTop - mPaddingBottom - padding; 13143 } 13144 13145 /** 13146 * <p>Indicates whether this view is attached to a hardware accelerated 13147 * window or not.</p> 13148 * 13149 * <p>Even if this method returns true, it does not mean that every call 13150 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 13151 * accelerated {@link android.graphics.Canvas}. For instance, if this view 13152 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 13153 * window is hardware accelerated, 13154 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 13155 * return false, and this method will return true.</p> 13156 * 13157 * @return True if the view is attached to a window and the window is 13158 * hardware accelerated; false in any other case. 13159 */ 13160 public boolean isHardwareAccelerated() { 13161 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13162 } 13163 13164 /** 13165 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 13166 * case of an active Animation being run on the view. 13167 */ 13168 private boolean drawAnimation(ViewGroup parent, long drawingTime, 13169 Animation a, boolean scalingRequired) { 13170 Transformation invalidationTransform; 13171 final int flags = parent.mGroupFlags; 13172 final boolean initialized = a.isInitialized(); 13173 if (!initialized) { 13174 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 13175 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 13176 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 13177 onAnimationStart(); 13178 } 13179 13180 boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f); 13181 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 13182 if (parent.mInvalidationTransformation == null) { 13183 parent.mInvalidationTransformation = new Transformation(); 13184 } 13185 invalidationTransform = parent.mInvalidationTransformation; 13186 a.getTransformation(drawingTime, invalidationTransform, 1f); 13187 } else { 13188 invalidationTransform = parent.mChildTransformation; 13189 } 13190 13191 if (more) { 13192 if (!a.willChangeBounds()) { 13193 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 13194 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 13195 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 13196 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 13197 // The child need to draw an animation, potentially offscreen, so 13198 // make sure we do not cancel invalidate requests 13199 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13200 parent.invalidate(mLeft, mTop, mRight, mBottom); 13201 } 13202 } else { 13203 if (parent.mInvalidateRegion == null) { 13204 parent.mInvalidateRegion = new RectF(); 13205 } 13206 final RectF region = parent.mInvalidateRegion; 13207 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 13208 invalidationTransform); 13209 13210 // The child need to draw an animation, potentially offscreen, so 13211 // make sure we do not cancel invalidate requests 13212 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13213 13214 final int left = mLeft + (int) region.left; 13215 final int top = mTop + (int) region.top; 13216 parent.invalidate(left, top, left + (int) (region.width() + .5f), 13217 top + (int) (region.height() + .5f)); 13218 } 13219 } 13220 return more; 13221 } 13222 13223 /** 13224 * This method is called by getDisplayList() when a display list is created or re-rendered. 13225 * It sets or resets the current value of all properties on that display list (resetting is 13226 * necessary when a display list is being re-created, because we need to make sure that 13227 * previously-set transform values 13228 */ 13229 void setDisplayListProperties(DisplayList displayList) { 13230 if (displayList != null) { 13231 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 13232 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 13233 if (mParent instanceof ViewGroup) { 13234 displayList.setClipChildren( 13235 (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 13236 } 13237 float alpha = 1; 13238 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 13239 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13240 ViewGroup parentVG = (ViewGroup) mParent; 13241 final boolean hasTransform = 13242 parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation); 13243 if (hasTransform) { 13244 Transformation transform = parentVG.mChildTransformation; 13245 final int transformType = parentVG.mChildTransformation.getTransformationType(); 13246 if (transformType != Transformation.TYPE_IDENTITY) { 13247 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 13248 alpha = transform.getAlpha(); 13249 } 13250 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 13251 displayList.setStaticMatrix(transform.getMatrix()); 13252 } 13253 } 13254 } 13255 } 13256 if (mTransformationInfo != null) { 13257 alpha *= mTransformationInfo.mAlpha; 13258 if (alpha < 1) { 13259 final int multipliedAlpha = (int) (255 * alpha); 13260 if (onSetAlpha(multipliedAlpha)) { 13261 alpha = 1; 13262 } 13263 } 13264 displayList.setTransformationInfo(alpha, 13265 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 13266 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 13267 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 13268 mTransformationInfo.mScaleY); 13269 if (mTransformationInfo.mCamera == null) { 13270 mTransformationInfo.mCamera = new Camera(); 13271 mTransformationInfo.matrix3D = new Matrix(); 13272 } 13273 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 13274 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) { 13275 displayList.setPivotX(getPivotX()); 13276 displayList.setPivotY(getPivotY()); 13277 } 13278 } else if (alpha < 1) { 13279 displayList.setAlpha(alpha); 13280 } 13281 } 13282 } 13283 13284 /** 13285 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 13286 * This draw() method is an implementation detail and is not intended to be overridden or 13287 * to be called from anywhere else other than ViewGroup.drawChild(). 13288 */ 13289 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 13290 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13291 boolean more = false; 13292 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 13293 final int flags = parent.mGroupFlags; 13294 13295 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 13296 parent.mChildTransformation.clear(); 13297 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13298 } 13299 13300 Transformation transformToApply = null; 13301 boolean concatMatrix = false; 13302 13303 boolean scalingRequired = false; 13304 boolean caching; 13305 int layerType = getLayerType(); 13306 13307 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 13308 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 13309 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 13310 caching = true; 13311 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 13312 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 13313 } else { 13314 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 13315 } 13316 13317 final Animation a = getAnimation(); 13318 if (a != null) { 13319 more = drawAnimation(parent, drawingTime, a, scalingRequired); 13320 concatMatrix = a.willChangeTransformationMatrix(); 13321 if (concatMatrix) { 13322 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13323 } 13324 transformToApply = parent.mChildTransformation; 13325 } else { 13326 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && 13327 mDisplayList != null) { 13328 // No longer animating: clear out old animation matrix 13329 mDisplayList.setAnimationMatrix(null); 13330 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13331 } 13332 if (!useDisplayListProperties && 13333 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13334 final boolean hasTransform = 13335 parent.getChildStaticTransformation(this, parent.mChildTransformation); 13336 if (hasTransform) { 13337 final int transformType = parent.mChildTransformation.getTransformationType(); 13338 transformToApply = transformType != Transformation.TYPE_IDENTITY ? 13339 parent.mChildTransformation : null; 13340 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 13341 } 13342 } 13343 } 13344 13345 concatMatrix |= !childHasIdentityMatrix; 13346 13347 // Sets the flag as early as possible to allow draw() implementations 13348 // to call invalidate() successfully when doing animations 13349 mPrivateFlags |= PFLAG_DRAWN; 13350 13351 if (!concatMatrix && 13352 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 13353 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 13354 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 13355 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 13356 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 13357 return more; 13358 } 13359 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 13360 13361 if (hardwareAccelerated) { 13362 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 13363 // retain the flag's value temporarily in the mRecreateDisplayList flag 13364 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 13365 mPrivateFlags &= ~PFLAG_INVALIDATED; 13366 } 13367 13368 DisplayList displayList = null; 13369 Bitmap cache = null; 13370 boolean hasDisplayList = false; 13371 if (caching) { 13372 if (!hardwareAccelerated) { 13373 if (layerType != LAYER_TYPE_NONE) { 13374 layerType = LAYER_TYPE_SOFTWARE; 13375 buildDrawingCache(true); 13376 } 13377 cache = getDrawingCache(true); 13378 } else { 13379 switch (layerType) { 13380 case LAYER_TYPE_SOFTWARE: 13381 if (useDisplayListProperties) { 13382 hasDisplayList = canHaveDisplayList(); 13383 } else { 13384 buildDrawingCache(true); 13385 cache = getDrawingCache(true); 13386 } 13387 break; 13388 case LAYER_TYPE_HARDWARE: 13389 if (useDisplayListProperties) { 13390 hasDisplayList = canHaveDisplayList(); 13391 } 13392 break; 13393 case LAYER_TYPE_NONE: 13394 // Delay getting the display list until animation-driven alpha values are 13395 // set up and possibly passed on to the view 13396 hasDisplayList = canHaveDisplayList(); 13397 break; 13398 } 13399 } 13400 } 13401 useDisplayListProperties &= hasDisplayList; 13402 if (useDisplayListProperties) { 13403 displayList = getDisplayList(); 13404 if (!displayList.isValid()) { 13405 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13406 // to getDisplayList(), the display list will be marked invalid and we should not 13407 // try to use it again. 13408 displayList = null; 13409 hasDisplayList = false; 13410 useDisplayListProperties = false; 13411 } 13412 } 13413 13414 int sx = 0; 13415 int sy = 0; 13416 if (!hasDisplayList) { 13417 computeScroll(); 13418 sx = mScrollX; 13419 sy = mScrollY; 13420 } 13421 13422 final boolean hasNoCache = cache == null || hasDisplayList; 13423 final boolean offsetForScroll = cache == null && !hasDisplayList && 13424 layerType != LAYER_TYPE_HARDWARE; 13425 13426 int restoreTo = -1; 13427 if (!useDisplayListProperties || transformToApply != null) { 13428 restoreTo = canvas.save(); 13429 } 13430 if (offsetForScroll) { 13431 canvas.translate(mLeft - sx, mTop - sy); 13432 } else { 13433 if (!useDisplayListProperties) { 13434 canvas.translate(mLeft, mTop); 13435 } 13436 if (scalingRequired) { 13437 if (useDisplayListProperties) { 13438 // TODO: Might not need this if we put everything inside the DL 13439 restoreTo = canvas.save(); 13440 } 13441 // mAttachInfo cannot be null, otherwise scalingRequired == false 13442 final float scale = 1.0f / mAttachInfo.mApplicationScale; 13443 canvas.scale(scale, scale); 13444 } 13445 } 13446 13447 float alpha = useDisplayListProperties ? 1 : getAlpha(); 13448 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 13449 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13450 if (transformToApply != null || !childHasIdentityMatrix) { 13451 int transX = 0; 13452 int transY = 0; 13453 13454 if (offsetForScroll) { 13455 transX = -sx; 13456 transY = -sy; 13457 } 13458 13459 if (transformToApply != null) { 13460 if (concatMatrix) { 13461 if (useDisplayListProperties) { 13462 displayList.setAnimationMatrix(transformToApply.getMatrix()); 13463 } else { 13464 // Undo the scroll translation, apply the transformation matrix, 13465 // then redo the scroll translate to get the correct result. 13466 canvas.translate(-transX, -transY); 13467 canvas.concat(transformToApply.getMatrix()); 13468 canvas.translate(transX, transY); 13469 } 13470 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13471 } 13472 13473 float transformAlpha = transformToApply.getAlpha(); 13474 if (transformAlpha < 1) { 13475 alpha *= transformAlpha; 13476 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13477 } 13478 } 13479 13480 if (!childHasIdentityMatrix && !useDisplayListProperties) { 13481 canvas.translate(-transX, -transY); 13482 canvas.concat(getMatrix()); 13483 canvas.translate(transX, transY); 13484 } 13485 } 13486 13487 // Deal with alpha if it is or used to be <1 13488 if (alpha < 1 || 13489 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13490 if (alpha < 1) { 13491 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13492 } else { 13493 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13494 } 13495 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13496 if (hasNoCache) { 13497 final int multipliedAlpha = (int) (255 * alpha); 13498 if (!onSetAlpha(multipliedAlpha)) { 13499 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13500 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 13501 layerType != LAYER_TYPE_NONE) { 13502 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 13503 } 13504 if (useDisplayListProperties) { 13505 displayList.setAlpha(alpha * getAlpha()); 13506 } else if (layerType == LAYER_TYPE_NONE) { 13507 final int scrollX = hasDisplayList ? 0 : sx; 13508 final int scrollY = hasDisplayList ? 0 : sy; 13509 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 13510 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 13511 } 13512 } else { 13513 // Alpha is handled by the child directly, clobber the layer's alpha 13514 mPrivateFlags |= PFLAG_ALPHA_SET; 13515 } 13516 } 13517 } 13518 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 13519 onSetAlpha(255); 13520 mPrivateFlags &= ~PFLAG_ALPHA_SET; 13521 } 13522 13523 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 13524 !useDisplayListProperties) { 13525 if (offsetForScroll) { 13526 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 13527 } else { 13528 if (!scalingRequired || cache == null) { 13529 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 13530 } else { 13531 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 13532 } 13533 } 13534 } 13535 13536 if (!useDisplayListProperties && hasDisplayList) { 13537 displayList = getDisplayList(); 13538 if (!displayList.isValid()) { 13539 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13540 // to getDisplayList(), the display list will be marked invalid and we should not 13541 // try to use it again. 13542 displayList = null; 13543 hasDisplayList = false; 13544 } 13545 } 13546 13547 if (hasNoCache) { 13548 boolean layerRendered = false; 13549 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 13550 final HardwareLayer layer = getHardwareLayer(); 13551 if (layer != null && layer.isValid()) { 13552 mLayerPaint.setAlpha((int) (alpha * 255)); 13553 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 13554 layerRendered = true; 13555 } else { 13556 final int scrollX = hasDisplayList ? 0 : sx; 13557 final int scrollY = hasDisplayList ? 0 : sy; 13558 canvas.saveLayer(scrollX, scrollY, 13559 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 13560 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13561 } 13562 } 13563 13564 if (!layerRendered) { 13565 if (!hasDisplayList) { 13566 // Fast path for layouts with no backgrounds 13567 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13568 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13569 dispatchDraw(canvas); 13570 } else { 13571 draw(canvas); 13572 } 13573 } else { 13574 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13575 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 13576 } 13577 } 13578 } else if (cache != null) { 13579 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13580 Paint cachePaint; 13581 13582 if (layerType == LAYER_TYPE_NONE) { 13583 cachePaint = parent.mCachePaint; 13584 if (cachePaint == null) { 13585 cachePaint = new Paint(); 13586 cachePaint.setDither(false); 13587 parent.mCachePaint = cachePaint; 13588 } 13589 if (alpha < 1) { 13590 cachePaint.setAlpha((int) (alpha * 255)); 13591 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13592 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 13593 cachePaint.setAlpha(255); 13594 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13595 } 13596 } else { 13597 cachePaint = mLayerPaint; 13598 cachePaint.setAlpha((int) (alpha * 255)); 13599 } 13600 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 13601 } 13602 13603 if (restoreTo >= 0) { 13604 canvas.restoreToCount(restoreTo); 13605 } 13606 13607 if (a != null && !more) { 13608 if (!hardwareAccelerated && !a.getFillAfter()) { 13609 onSetAlpha(255); 13610 } 13611 parent.finishAnimatingView(this, a); 13612 } 13613 13614 if (more && hardwareAccelerated) { 13615 // invalidation is the trigger to recreate display lists, so if we're using 13616 // display lists to render, force an invalidate to allow the animation to 13617 // continue drawing another frame 13618 parent.invalidate(true); 13619 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 13620 // alpha animations should cause the child to recreate its display list 13621 invalidate(true); 13622 } 13623 } 13624 13625 mRecreateDisplayList = false; 13626 13627 return more; 13628 } 13629 13630 /** 13631 * Manually render this view (and all of its children) to the given Canvas. 13632 * The view must have already done a full layout before this function is 13633 * called. When implementing a view, implement 13634 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 13635 * If you do need to override this method, call the superclass version. 13636 * 13637 * @param canvas The Canvas to which the View is rendered. 13638 */ 13639 public void draw(Canvas canvas) { 13640 final int privateFlags = mPrivateFlags; 13641 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 13642 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 13643 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 13644 13645 /* 13646 * Draw traversal performs several drawing steps which must be executed 13647 * in the appropriate order: 13648 * 13649 * 1. Draw the background 13650 * 2. If necessary, save the canvas' layers to prepare for fading 13651 * 3. Draw view's content 13652 * 4. Draw children 13653 * 5. If necessary, draw the fading edges and restore layers 13654 * 6. Draw decorations (scrollbars for instance) 13655 */ 13656 13657 // Step 1, draw the background, if needed 13658 int saveCount; 13659 13660 if (!dirtyOpaque) { 13661 final Drawable background = mBackground; 13662 if (background != null) { 13663 final int scrollX = mScrollX; 13664 final int scrollY = mScrollY; 13665 13666 if (mBackgroundSizeChanged) { 13667 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 13668 mBackgroundSizeChanged = false; 13669 } 13670 13671 if ((scrollX | scrollY) == 0) { 13672 background.draw(canvas); 13673 } else { 13674 canvas.translate(scrollX, scrollY); 13675 background.draw(canvas); 13676 canvas.translate(-scrollX, -scrollY); 13677 } 13678 } 13679 } 13680 13681 // skip step 2 & 5 if possible (common case) 13682 final int viewFlags = mViewFlags; 13683 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 13684 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 13685 if (!verticalEdges && !horizontalEdges) { 13686 // Step 3, draw the content 13687 if (!dirtyOpaque) onDraw(canvas); 13688 13689 // Step 4, draw the children 13690 dispatchDraw(canvas); 13691 13692 // Step 6, draw decorations (scrollbars) 13693 onDrawScrollBars(canvas); 13694 13695 // we're done... 13696 return; 13697 } 13698 13699 /* 13700 * Here we do the full fledged routine... 13701 * (this is an uncommon case where speed matters less, 13702 * this is why we repeat some of the tests that have been 13703 * done above) 13704 */ 13705 13706 boolean drawTop = false; 13707 boolean drawBottom = false; 13708 boolean drawLeft = false; 13709 boolean drawRight = false; 13710 13711 float topFadeStrength = 0.0f; 13712 float bottomFadeStrength = 0.0f; 13713 float leftFadeStrength = 0.0f; 13714 float rightFadeStrength = 0.0f; 13715 13716 // Step 2, save the canvas' layers 13717 int paddingLeft = mPaddingLeft; 13718 13719 final boolean offsetRequired = isPaddingOffsetRequired(); 13720 if (offsetRequired) { 13721 paddingLeft += getLeftPaddingOffset(); 13722 } 13723 13724 int left = mScrollX + paddingLeft; 13725 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 13726 int top = mScrollY + getFadeTop(offsetRequired); 13727 int bottom = top + getFadeHeight(offsetRequired); 13728 13729 if (offsetRequired) { 13730 right += getRightPaddingOffset(); 13731 bottom += getBottomPaddingOffset(); 13732 } 13733 13734 final ScrollabilityCache scrollabilityCache = mScrollCache; 13735 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 13736 int length = (int) fadeHeight; 13737 13738 // clip the fade length if top and bottom fades overlap 13739 // overlapping fades produce odd-looking artifacts 13740 if (verticalEdges && (top + length > bottom - length)) { 13741 length = (bottom - top) / 2; 13742 } 13743 13744 // also clip horizontal fades if necessary 13745 if (horizontalEdges && (left + length > right - length)) { 13746 length = (right - left) / 2; 13747 } 13748 13749 if (verticalEdges) { 13750 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 13751 drawTop = topFadeStrength * fadeHeight > 1.0f; 13752 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 13753 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 13754 } 13755 13756 if (horizontalEdges) { 13757 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 13758 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 13759 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 13760 drawRight = rightFadeStrength * fadeHeight > 1.0f; 13761 } 13762 13763 saveCount = canvas.getSaveCount(); 13764 13765 int solidColor = getSolidColor(); 13766 if (solidColor == 0) { 13767 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13768 13769 if (drawTop) { 13770 canvas.saveLayer(left, top, right, top + length, null, flags); 13771 } 13772 13773 if (drawBottom) { 13774 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 13775 } 13776 13777 if (drawLeft) { 13778 canvas.saveLayer(left, top, left + length, bottom, null, flags); 13779 } 13780 13781 if (drawRight) { 13782 canvas.saveLayer(right - length, top, right, bottom, null, flags); 13783 } 13784 } else { 13785 scrollabilityCache.setFadeColor(solidColor); 13786 } 13787 13788 // Step 3, draw the content 13789 if (!dirtyOpaque) onDraw(canvas); 13790 13791 // Step 4, draw the children 13792 dispatchDraw(canvas); 13793 13794 // Step 5, draw the fade effect and restore layers 13795 final Paint p = scrollabilityCache.paint; 13796 final Matrix matrix = scrollabilityCache.matrix; 13797 final Shader fade = scrollabilityCache.shader; 13798 13799 if (drawTop) { 13800 matrix.setScale(1, fadeHeight * topFadeStrength); 13801 matrix.postTranslate(left, top); 13802 fade.setLocalMatrix(matrix); 13803 canvas.drawRect(left, top, right, top + length, p); 13804 } 13805 13806 if (drawBottom) { 13807 matrix.setScale(1, fadeHeight * bottomFadeStrength); 13808 matrix.postRotate(180); 13809 matrix.postTranslate(left, bottom); 13810 fade.setLocalMatrix(matrix); 13811 canvas.drawRect(left, bottom - length, right, bottom, p); 13812 } 13813 13814 if (drawLeft) { 13815 matrix.setScale(1, fadeHeight * leftFadeStrength); 13816 matrix.postRotate(-90); 13817 matrix.postTranslate(left, top); 13818 fade.setLocalMatrix(matrix); 13819 canvas.drawRect(left, top, left + length, bottom, p); 13820 } 13821 13822 if (drawRight) { 13823 matrix.setScale(1, fadeHeight * rightFadeStrength); 13824 matrix.postRotate(90); 13825 matrix.postTranslate(right, top); 13826 fade.setLocalMatrix(matrix); 13827 canvas.drawRect(right - length, top, right, bottom, p); 13828 } 13829 13830 canvas.restoreToCount(saveCount); 13831 13832 // Step 6, draw decorations (scrollbars) 13833 onDrawScrollBars(canvas); 13834 } 13835 13836 /** 13837 * Override this if your view is known to always be drawn on top of a solid color background, 13838 * and needs to draw fading edges. Returning a non-zero color enables the view system to 13839 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 13840 * should be set to 0xFF. 13841 * 13842 * @see #setVerticalFadingEdgeEnabled(boolean) 13843 * @see #setHorizontalFadingEdgeEnabled(boolean) 13844 * 13845 * @return The known solid color background for this view, or 0 if the color may vary 13846 */ 13847 @ViewDebug.ExportedProperty(category = "drawing") 13848 public int getSolidColor() { 13849 return 0; 13850 } 13851 13852 /** 13853 * Build a human readable string representation of the specified view flags. 13854 * 13855 * @param flags the view flags to convert to a string 13856 * @return a String representing the supplied flags 13857 */ 13858 private static String printFlags(int flags) { 13859 String output = ""; 13860 int numFlags = 0; 13861 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 13862 output += "TAKES_FOCUS"; 13863 numFlags++; 13864 } 13865 13866 switch (flags & VISIBILITY_MASK) { 13867 case INVISIBLE: 13868 if (numFlags > 0) { 13869 output += " "; 13870 } 13871 output += "INVISIBLE"; 13872 // USELESS HERE numFlags++; 13873 break; 13874 case GONE: 13875 if (numFlags > 0) { 13876 output += " "; 13877 } 13878 output += "GONE"; 13879 // USELESS HERE numFlags++; 13880 break; 13881 default: 13882 break; 13883 } 13884 return output; 13885 } 13886 13887 /** 13888 * Build a human readable string representation of the specified private 13889 * view flags. 13890 * 13891 * @param privateFlags the private view flags to convert to a string 13892 * @return a String representing the supplied flags 13893 */ 13894 private static String printPrivateFlags(int privateFlags) { 13895 String output = ""; 13896 int numFlags = 0; 13897 13898 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 13899 output += "WANTS_FOCUS"; 13900 numFlags++; 13901 } 13902 13903 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 13904 if (numFlags > 0) { 13905 output += " "; 13906 } 13907 output += "FOCUSED"; 13908 numFlags++; 13909 } 13910 13911 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 13912 if (numFlags > 0) { 13913 output += " "; 13914 } 13915 output += "SELECTED"; 13916 numFlags++; 13917 } 13918 13919 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 13920 if (numFlags > 0) { 13921 output += " "; 13922 } 13923 output += "IS_ROOT_NAMESPACE"; 13924 numFlags++; 13925 } 13926 13927 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 13928 if (numFlags > 0) { 13929 output += " "; 13930 } 13931 output += "HAS_BOUNDS"; 13932 numFlags++; 13933 } 13934 13935 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 13936 if (numFlags > 0) { 13937 output += " "; 13938 } 13939 output += "DRAWN"; 13940 // USELESS HERE numFlags++; 13941 } 13942 return output; 13943 } 13944 13945 /** 13946 * <p>Indicates whether or not this view's layout will be requested during 13947 * the next hierarchy layout pass.</p> 13948 * 13949 * @return true if the layout will be forced during next layout pass 13950 */ 13951 public boolean isLayoutRequested() { 13952 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 13953 } 13954 13955 /** 13956 * Assign a size and position to a view and all of its 13957 * descendants 13958 * 13959 * <p>This is the second phase of the layout mechanism. 13960 * (The first is measuring). In this phase, each parent calls 13961 * layout on all of its children to position them. 13962 * This is typically done using the child measurements 13963 * that were stored in the measure pass().</p> 13964 * 13965 * <p>Derived classes should not override this method. 13966 * Derived classes with children should override 13967 * onLayout. In that method, they should 13968 * call layout on each of their children.</p> 13969 * 13970 * @param l Left position, relative to parent 13971 * @param t Top position, relative to parent 13972 * @param r Right position, relative to parent 13973 * @param b Bottom position, relative to parent 13974 */ 13975 @SuppressWarnings({"unchecked"}) 13976 public void layout(int l, int t, int r, int b) { 13977 int oldL = mLeft; 13978 int oldT = mTop; 13979 int oldB = mBottom; 13980 int oldR = mRight; 13981 boolean changed = setFrame(l, t, r, b); 13982 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 13983 onLayout(changed, l, t, r, b); 13984 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 13985 13986 ListenerInfo li = mListenerInfo; 13987 if (li != null && li.mOnLayoutChangeListeners != null) { 13988 ArrayList<OnLayoutChangeListener> listenersCopy = 13989 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 13990 int numListeners = listenersCopy.size(); 13991 for (int i = 0; i < numListeners; ++i) { 13992 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 13993 } 13994 } 13995 } 13996 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 13997 } 13998 13999 /** 14000 * Called from layout when this view should 14001 * assign a size and position to each of its children. 14002 * 14003 * Derived classes with children should override 14004 * this method and call layout on each of 14005 * their children. 14006 * @param changed This is a new size or position for this view 14007 * @param left Left position, relative to parent 14008 * @param top Top position, relative to parent 14009 * @param right Right position, relative to parent 14010 * @param bottom Bottom position, relative to parent 14011 */ 14012 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 14013 } 14014 14015 /** 14016 * Assign a size and position to this view. 14017 * 14018 * This is called from layout. 14019 * 14020 * @param left Left position, relative to parent 14021 * @param top Top position, relative to parent 14022 * @param right Right position, relative to parent 14023 * @param bottom Bottom position, relative to parent 14024 * @return true if the new size and position are different than the 14025 * previous ones 14026 * {@hide} 14027 */ 14028 protected boolean setFrame(int left, int top, int right, int bottom) { 14029 boolean changed = false; 14030 14031 if (DBG) { 14032 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 14033 + right + "," + bottom + ")"); 14034 } 14035 14036 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 14037 changed = true; 14038 14039 // Remember our drawn bit 14040 int drawn = mPrivateFlags & PFLAG_DRAWN; 14041 14042 int oldWidth = mRight - mLeft; 14043 int oldHeight = mBottom - mTop; 14044 int newWidth = right - left; 14045 int newHeight = bottom - top; 14046 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 14047 14048 // Invalidate our old position 14049 invalidate(sizeChanged); 14050 14051 mLeft = left; 14052 mTop = top; 14053 mRight = right; 14054 mBottom = bottom; 14055 if (mDisplayList != null) { 14056 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 14057 } 14058 14059 mPrivateFlags |= PFLAG_HAS_BOUNDS; 14060 14061 14062 if (sizeChanged) { 14063 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 14064 // A change in dimension means an auto-centered pivot point changes, too 14065 if (mTransformationInfo != null) { 14066 mTransformationInfo.mMatrixDirty = true; 14067 } 14068 } 14069 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 14070 } 14071 14072 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 14073 // If we are visible, force the DRAWN bit to on so that 14074 // this invalidate will go through (at least to our parent). 14075 // This is because someone may have invalidated this view 14076 // before this call to setFrame came in, thereby clearing 14077 // the DRAWN bit. 14078 mPrivateFlags |= PFLAG_DRAWN; 14079 invalidate(sizeChanged); 14080 // parent display list may need to be recreated based on a change in the bounds 14081 // of any child 14082 invalidateParentCaches(); 14083 } 14084 14085 // Reset drawn bit to original value (invalidate turns it off) 14086 mPrivateFlags |= drawn; 14087 14088 mBackgroundSizeChanged = true; 14089 } 14090 return changed; 14091 } 14092 14093 /** 14094 * Finalize inflating a view from XML. This is called as the last phase 14095 * of inflation, after all child views have been added. 14096 * 14097 * <p>Even if the subclass overrides onFinishInflate, they should always be 14098 * sure to call the super method, so that we get called. 14099 */ 14100 protected void onFinishInflate() { 14101 } 14102 14103 /** 14104 * Returns the resources associated with this view. 14105 * 14106 * @return Resources object. 14107 */ 14108 public Resources getResources() { 14109 return mResources; 14110 } 14111 14112 /** 14113 * Invalidates the specified Drawable. 14114 * 14115 * @param drawable the drawable to invalidate 14116 */ 14117 public void invalidateDrawable(Drawable drawable) { 14118 if (verifyDrawable(drawable)) { 14119 final Rect dirty = drawable.getBounds(); 14120 final int scrollX = mScrollX; 14121 final int scrollY = mScrollY; 14122 14123 invalidate(dirty.left + scrollX, dirty.top + scrollY, 14124 dirty.right + scrollX, dirty.bottom + scrollY); 14125 } 14126 } 14127 14128 /** 14129 * Schedules an action on a drawable to occur at a specified time. 14130 * 14131 * @param who the recipient of the action 14132 * @param what the action to run on the drawable 14133 * @param when the time at which the action must occur. Uses the 14134 * {@link SystemClock#uptimeMillis} timebase. 14135 */ 14136 public void scheduleDrawable(Drawable who, Runnable what, long when) { 14137 if (verifyDrawable(who) && what != null) { 14138 final long delay = when - SystemClock.uptimeMillis(); 14139 if (mAttachInfo != null) { 14140 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 14141 Choreographer.CALLBACK_ANIMATION, what, who, 14142 Choreographer.subtractFrameDelay(delay)); 14143 } else { 14144 ViewRootImpl.getRunQueue().postDelayed(what, delay); 14145 } 14146 } 14147 } 14148 14149 /** 14150 * Cancels a scheduled action on a drawable. 14151 * 14152 * @param who the recipient of the action 14153 * @param what the action to cancel 14154 */ 14155 public void unscheduleDrawable(Drawable who, Runnable what) { 14156 if (verifyDrawable(who) && what != null) { 14157 if (mAttachInfo != null) { 14158 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14159 Choreographer.CALLBACK_ANIMATION, what, who); 14160 } else { 14161 ViewRootImpl.getRunQueue().removeCallbacks(what); 14162 } 14163 } 14164 } 14165 14166 /** 14167 * Unschedule any events associated with the given Drawable. This can be 14168 * used when selecting a new Drawable into a view, so that the previous 14169 * one is completely unscheduled. 14170 * 14171 * @param who The Drawable to unschedule. 14172 * 14173 * @see #drawableStateChanged 14174 */ 14175 public void unscheduleDrawable(Drawable who) { 14176 if (mAttachInfo != null && who != null) { 14177 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14178 Choreographer.CALLBACK_ANIMATION, null, who); 14179 } 14180 } 14181 14182 /** 14183 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 14184 * that the View directionality can and will be resolved before its Drawables. 14185 * 14186 * Will call {@link View#onResolveDrawables} when resolution is done. 14187 * 14188 * @hide 14189 */ 14190 public void resolveDrawables() { 14191 if (mBackground != null) { 14192 mBackground.setLayoutDirection(getLayoutDirection()); 14193 } 14194 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 14195 onResolveDrawables(getLayoutDirection()); 14196 } 14197 14198 /** 14199 * Called when layout direction has been resolved. 14200 * 14201 * The default implementation does nothing. 14202 * 14203 * @param layoutDirection The resolved layout direction. 14204 * 14205 * @see #LAYOUT_DIRECTION_LTR 14206 * @see #LAYOUT_DIRECTION_RTL 14207 * 14208 * @hide 14209 */ 14210 public void onResolveDrawables(int layoutDirection) { 14211 } 14212 14213 private void resetResolvedDrawables() { 14214 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 14215 } 14216 14217 private boolean isDrawablesResolved() { 14218 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 14219 } 14220 14221 /** 14222 * If your view subclass is displaying its own Drawable objects, it should 14223 * override this function and return true for any Drawable it is 14224 * displaying. This allows animations for those drawables to be 14225 * scheduled. 14226 * 14227 * <p>Be sure to call through to the super class when overriding this 14228 * function. 14229 * 14230 * @param who The Drawable to verify. Return true if it is one you are 14231 * displaying, else return the result of calling through to the 14232 * super class. 14233 * 14234 * @return boolean If true than the Drawable is being displayed in the 14235 * view; else false and it is not allowed to animate. 14236 * 14237 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 14238 * @see #drawableStateChanged() 14239 */ 14240 protected boolean verifyDrawable(Drawable who) { 14241 return who == mBackground; 14242 } 14243 14244 /** 14245 * This function is called whenever the state of the view changes in such 14246 * a way that it impacts the state of drawables being shown. 14247 * 14248 * <p>Be sure to call through to the superclass when overriding this 14249 * function. 14250 * 14251 * @see Drawable#setState(int[]) 14252 */ 14253 protected void drawableStateChanged() { 14254 Drawable d = mBackground; 14255 if (d != null && d.isStateful()) { 14256 d.setState(getDrawableState()); 14257 } 14258 } 14259 14260 /** 14261 * Call this to force a view to update its drawable state. This will cause 14262 * drawableStateChanged to be called on this view. Views that are interested 14263 * in the new state should call getDrawableState. 14264 * 14265 * @see #drawableStateChanged 14266 * @see #getDrawableState 14267 */ 14268 public void refreshDrawableState() { 14269 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 14270 drawableStateChanged(); 14271 14272 ViewParent parent = mParent; 14273 if (parent != null) { 14274 parent.childDrawableStateChanged(this); 14275 } 14276 } 14277 14278 /** 14279 * Return an array of resource IDs of the drawable states representing the 14280 * current state of the view. 14281 * 14282 * @return The current drawable state 14283 * 14284 * @see Drawable#setState(int[]) 14285 * @see #drawableStateChanged() 14286 * @see #onCreateDrawableState(int) 14287 */ 14288 public final int[] getDrawableState() { 14289 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 14290 return mDrawableState; 14291 } else { 14292 mDrawableState = onCreateDrawableState(0); 14293 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 14294 return mDrawableState; 14295 } 14296 } 14297 14298 /** 14299 * Generate the new {@link android.graphics.drawable.Drawable} state for 14300 * this view. This is called by the view 14301 * system when the cached Drawable state is determined to be invalid. To 14302 * retrieve the current state, you should use {@link #getDrawableState}. 14303 * 14304 * @param extraSpace if non-zero, this is the number of extra entries you 14305 * would like in the returned array in which you can place your own 14306 * states. 14307 * 14308 * @return Returns an array holding the current {@link Drawable} state of 14309 * the view. 14310 * 14311 * @see #mergeDrawableStates(int[], int[]) 14312 */ 14313 protected int[] onCreateDrawableState(int extraSpace) { 14314 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 14315 mParent instanceof View) { 14316 return ((View) mParent).onCreateDrawableState(extraSpace); 14317 } 14318 14319 int[] drawableState; 14320 14321 int privateFlags = mPrivateFlags; 14322 14323 int viewStateIndex = 0; 14324 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 14325 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 14326 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 14327 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 14328 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 14329 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 14330 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 14331 HardwareRenderer.isAvailable()) { 14332 // This is set if HW acceleration is requested, even if the current 14333 // process doesn't allow it. This is just to allow app preview 14334 // windows to better match their app. 14335 viewStateIndex |= VIEW_STATE_ACCELERATED; 14336 } 14337 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 14338 14339 final int privateFlags2 = mPrivateFlags2; 14340 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 14341 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 14342 14343 drawableState = VIEW_STATE_SETS[viewStateIndex]; 14344 14345 //noinspection ConstantIfStatement 14346 if (false) { 14347 Log.i("View", "drawableStateIndex=" + viewStateIndex); 14348 Log.i("View", toString() 14349 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 14350 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 14351 + " fo=" + hasFocus() 14352 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 14353 + " wf=" + hasWindowFocus() 14354 + ": " + Arrays.toString(drawableState)); 14355 } 14356 14357 if (extraSpace == 0) { 14358 return drawableState; 14359 } 14360 14361 final int[] fullState; 14362 if (drawableState != null) { 14363 fullState = new int[drawableState.length + extraSpace]; 14364 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 14365 } else { 14366 fullState = new int[extraSpace]; 14367 } 14368 14369 return fullState; 14370 } 14371 14372 /** 14373 * Merge your own state values in <var>additionalState</var> into the base 14374 * state values <var>baseState</var> that were returned by 14375 * {@link #onCreateDrawableState(int)}. 14376 * 14377 * @param baseState The base state values returned by 14378 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 14379 * own additional state values. 14380 * 14381 * @param additionalState The additional state values you would like 14382 * added to <var>baseState</var>; this array is not modified. 14383 * 14384 * @return As a convenience, the <var>baseState</var> array you originally 14385 * passed into the function is returned. 14386 * 14387 * @see #onCreateDrawableState(int) 14388 */ 14389 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 14390 final int N = baseState.length; 14391 int i = N - 1; 14392 while (i >= 0 && baseState[i] == 0) { 14393 i--; 14394 } 14395 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 14396 return baseState; 14397 } 14398 14399 /** 14400 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 14401 * on all Drawable objects associated with this view. 14402 */ 14403 public void jumpDrawablesToCurrentState() { 14404 if (mBackground != null) { 14405 mBackground.jumpToCurrentState(); 14406 } 14407 } 14408 14409 /** 14410 * Sets the background color for this view. 14411 * @param color the color of the background 14412 */ 14413 @RemotableViewMethod 14414 public void setBackgroundColor(int color) { 14415 if (mBackground instanceof ColorDrawable) { 14416 ((ColorDrawable) mBackground.mutate()).setColor(color); 14417 computeOpaqueFlags(); 14418 } else { 14419 setBackground(new ColorDrawable(color)); 14420 } 14421 } 14422 14423 /** 14424 * Set the background to a given resource. The resource should refer to 14425 * a Drawable object or 0 to remove the background. 14426 * @param resid The identifier of the resource. 14427 * 14428 * @attr ref android.R.styleable#View_background 14429 */ 14430 @RemotableViewMethod 14431 public void setBackgroundResource(int resid) { 14432 if (resid != 0 && resid == mBackgroundResource) { 14433 return; 14434 } 14435 14436 Drawable d= null; 14437 if (resid != 0) { 14438 d = mResources.getDrawable(resid); 14439 } 14440 setBackground(d); 14441 14442 mBackgroundResource = resid; 14443 } 14444 14445 /** 14446 * Set the background to a given Drawable, or remove the background. If the 14447 * background has padding, this View's padding is set to the background's 14448 * padding. However, when a background is removed, this View's padding isn't 14449 * touched. If setting the padding is desired, please use 14450 * {@link #setPadding(int, int, int, int)}. 14451 * 14452 * @param background The Drawable to use as the background, or null to remove the 14453 * background 14454 */ 14455 public void setBackground(Drawable background) { 14456 //noinspection deprecation 14457 setBackgroundDrawable(background); 14458 } 14459 14460 /** 14461 * @deprecated use {@link #setBackground(Drawable)} instead 14462 */ 14463 @Deprecated 14464 public void setBackgroundDrawable(Drawable background) { 14465 computeOpaqueFlags(); 14466 14467 if (background == mBackground) { 14468 return; 14469 } 14470 14471 boolean requestLayout = false; 14472 14473 mBackgroundResource = 0; 14474 14475 /* 14476 * Regardless of whether we're setting a new background or not, we want 14477 * to clear the previous drawable. 14478 */ 14479 if (mBackground != null) { 14480 mBackground.setCallback(null); 14481 unscheduleDrawable(mBackground); 14482 } 14483 14484 if (background != null) { 14485 Rect padding = sThreadLocal.get(); 14486 if (padding == null) { 14487 padding = new Rect(); 14488 sThreadLocal.set(padding); 14489 } 14490 resetResolvedDrawables(); 14491 background.setLayoutDirection(getLayoutDirection()); 14492 if (background.getPadding(padding)) { 14493 resetResolvedPadding(); 14494 switch (background.getLayoutDirection()) { 14495 case LAYOUT_DIRECTION_RTL: 14496 mUserPaddingLeftInitial = padding.right; 14497 mUserPaddingRightInitial = padding.left; 14498 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 14499 break; 14500 case LAYOUT_DIRECTION_LTR: 14501 default: 14502 mUserPaddingLeftInitial = padding.left; 14503 mUserPaddingRightInitial = padding.right; 14504 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 14505 } 14506 } 14507 14508 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 14509 // if it has a different minimum size, we should layout again 14510 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 14511 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 14512 requestLayout = true; 14513 } 14514 14515 background.setCallback(this); 14516 if (background.isStateful()) { 14517 background.setState(getDrawableState()); 14518 } 14519 background.setVisible(getVisibility() == VISIBLE, false); 14520 mBackground = background; 14521 14522 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 14523 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 14524 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 14525 requestLayout = true; 14526 } 14527 } else { 14528 /* Remove the background */ 14529 mBackground = null; 14530 14531 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 14532 /* 14533 * This view ONLY drew the background before and we're removing 14534 * the background, so now it won't draw anything 14535 * (hence we SKIP_DRAW) 14536 */ 14537 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 14538 mPrivateFlags |= PFLAG_SKIP_DRAW; 14539 } 14540 14541 /* 14542 * When the background is set, we try to apply its padding to this 14543 * View. When the background is removed, we don't touch this View's 14544 * padding. This is noted in the Javadocs. Hence, we don't need to 14545 * requestLayout(), the invalidate() below is sufficient. 14546 */ 14547 14548 // The old background's minimum size could have affected this 14549 // View's layout, so let's requestLayout 14550 requestLayout = true; 14551 } 14552 14553 computeOpaqueFlags(); 14554 14555 if (requestLayout) { 14556 requestLayout(); 14557 } 14558 14559 mBackgroundSizeChanged = true; 14560 invalidate(true); 14561 } 14562 14563 /** 14564 * Gets the background drawable 14565 * 14566 * @return The drawable used as the background for this view, if any. 14567 * 14568 * @see #setBackground(Drawable) 14569 * 14570 * @attr ref android.R.styleable#View_background 14571 */ 14572 public Drawable getBackground() { 14573 return mBackground; 14574 } 14575 14576 /** 14577 * Sets the padding. The view may add on the space required to display 14578 * the scrollbars, depending on the style and visibility of the scrollbars. 14579 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 14580 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 14581 * from the values set in this call. 14582 * 14583 * @attr ref android.R.styleable#View_padding 14584 * @attr ref android.R.styleable#View_paddingBottom 14585 * @attr ref android.R.styleable#View_paddingLeft 14586 * @attr ref android.R.styleable#View_paddingRight 14587 * @attr ref android.R.styleable#View_paddingTop 14588 * @param left the left padding in pixels 14589 * @param top the top padding in pixels 14590 * @param right the right padding in pixels 14591 * @param bottom the bottom padding in pixels 14592 */ 14593 public void setPadding(int left, int top, int right, int bottom) { 14594 resetResolvedPadding(); 14595 14596 mUserPaddingStart = UNDEFINED_PADDING; 14597 mUserPaddingEnd = UNDEFINED_PADDING; 14598 14599 mUserPaddingLeftInitial = left; 14600 mUserPaddingRightInitial = right; 14601 14602 internalSetPadding(left, top, right, bottom); 14603 } 14604 14605 /** 14606 * @hide 14607 */ 14608 protected void internalSetPadding(int left, int top, int right, int bottom) { 14609 mUserPaddingLeft = left; 14610 mUserPaddingRight = right; 14611 mUserPaddingBottom = bottom; 14612 14613 final int viewFlags = mViewFlags; 14614 boolean changed = false; 14615 14616 // Common case is there are no scroll bars. 14617 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 14618 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 14619 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 14620 ? 0 : getVerticalScrollbarWidth(); 14621 switch (mVerticalScrollbarPosition) { 14622 case SCROLLBAR_POSITION_DEFAULT: 14623 if (isLayoutRtl()) { 14624 left += offset; 14625 } else { 14626 right += offset; 14627 } 14628 break; 14629 case SCROLLBAR_POSITION_RIGHT: 14630 right += offset; 14631 break; 14632 case SCROLLBAR_POSITION_LEFT: 14633 left += offset; 14634 break; 14635 } 14636 } 14637 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 14638 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 14639 ? 0 : getHorizontalScrollbarHeight(); 14640 } 14641 } 14642 14643 if (mPaddingLeft != left) { 14644 changed = true; 14645 mPaddingLeft = left; 14646 } 14647 if (mPaddingTop != top) { 14648 changed = true; 14649 mPaddingTop = top; 14650 } 14651 if (mPaddingRight != right) { 14652 changed = true; 14653 mPaddingRight = right; 14654 } 14655 if (mPaddingBottom != bottom) { 14656 changed = true; 14657 mPaddingBottom = bottom; 14658 } 14659 14660 if (changed) { 14661 requestLayout(); 14662 } 14663 } 14664 14665 /** 14666 * Sets the relative padding. The view may add on the space required to display 14667 * the scrollbars, depending on the style and visibility of the scrollbars. 14668 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 14669 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 14670 * from the values set in this call. 14671 * 14672 * @attr ref android.R.styleable#View_padding 14673 * @attr ref android.R.styleable#View_paddingBottom 14674 * @attr ref android.R.styleable#View_paddingStart 14675 * @attr ref android.R.styleable#View_paddingEnd 14676 * @attr ref android.R.styleable#View_paddingTop 14677 * @param start the start padding in pixels 14678 * @param top the top padding in pixels 14679 * @param end the end padding in pixels 14680 * @param bottom the bottom padding in pixels 14681 */ 14682 public void setPaddingRelative(int start, int top, int end, int bottom) { 14683 resetResolvedPadding(); 14684 14685 mUserPaddingStart = start; 14686 mUserPaddingEnd = end; 14687 14688 switch(getLayoutDirection()) { 14689 case LAYOUT_DIRECTION_RTL: 14690 mUserPaddingLeftInitial = end; 14691 mUserPaddingRightInitial = start; 14692 internalSetPadding(end, top, start, bottom); 14693 break; 14694 case LAYOUT_DIRECTION_LTR: 14695 default: 14696 mUserPaddingLeftInitial = start; 14697 mUserPaddingRightInitial = end; 14698 internalSetPadding(start, top, end, bottom); 14699 } 14700 } 14701 14702 /** 14703 * Returns the top padding of this view. 14704 * 14705 * @return the top padding in pixels 14706 */ 14707 public int getPaddingTop() { 14708 return mPaddingTop; 14709 } 14710 14711 /** 14712 * Returns the bottom padding of this view. If there are inset and enabled 14713 * scrollbars, this value may include the space required to display the 14714 * scrollbars as well. 14715 * 14716 * @return the bottom padding in pixels 14717 */ 14718 public int getPaddingBottom() { 14719 return mPaddingBottom; 14720 } 14721 14722 /** 14723 * Returns the left padding of this view. If there are inset and enabled 14724 * scrollbars, this value may include the space required to display the 14725 * scrollbars as well. 14726 * 14727 * @return the left padding in pixels 14728 */ 14729 public int getPaddingLeft() { 14730 if (!isPaddingResolved()) { 14731 resolvePadding(); 14732 } 14733 return mPaddingLeft; 14734 } 14735 14736 /** 14737 * Returns the start padding of this view depending on its resolved layout direction. 14738 * If there are inset and enabled scrollbars, this value may include the space 14739 * required to display the scrollbars as well. 14740 * 14741 * @return the start padding in pixels 14742 */ 14743 public int getPaddingStart() { 14744 if (!isPaddingResolved()) { 14745 resolvePadding(); 14746 } 14747 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 14748 mPaddingRight : mPaddingLeft; 14749 } 14750 14751 /** 14752 * Returns the right padding of this view. If there are inset and enabled 14753 * scrollbars, this value may include the space required to display the 14754 * scrollbars as well. 14755 * 14756 * @return the right padding in pixels 14757 */ 14758 public int getPaddingRight() { 14759 if (!isPaddingResolved()) { 14760 resolvePadding(); 14761 } 14762 return mPaddingRight; 14763 } 14764 14765 /** 14766 * Returns the end padding of this view depending on its resolved layout direction. 14767 * If there are inset and enabled scrollbars, this value may include the space 14768 * required to display the scrollbars as well. 14769 * 14770 * @return the end padding in pixels 14771 */ 14772 public int getPaddingEnd() { 14773 if (!isPaddingResolved()) { 14774 resolvePadding(); 14775 } 14776 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 14777 mPaddingLeft : mPaddingRight; 14778 } 14779 14780 /** 14781 * Return if the padding as been set thru relative values 14782 * {@link #setPaddingRelative(int, int, int, int)} or thru 14783 * @attr ref android.R.styleable#View_paddingStart or 14784 * @attr ref android.R.styleable#View_paddingEnd 14785 * 14786 * @return true if the padding is relative or false if it is not. 14787 */ 14788 public boolean isPaddingRelative() { 14789 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 14790 } 14791 14792 /** 14793 * @hide 14794 */ 14795 public void resetPaddingToInitialValues() { 14796 if (isRtlCompatibilityMode()) { 14797 mPaddingLeft = mUserPaddingLeftInitial; 14798 mPaddingRight = mUserPaddingRightInitial; 14799 } else { 14800 if (isLayoutRtl()) { 14801 mPaddingLeft = mUserPaddingRightInitial; 14802 mPaddingRight = mUserPaddingLeftInitial; 14803 } else { 14804 mPaddingLeft = mUserPaddingLeftInitial; 14805 mPaddingRight = mUserPaddingRightInitial; 14806 } 14807 } 14808 } 14809 14810 /** 14811 * @hide 14812 */ 14813 public Insets getOpticalInsets() { 14814 if (mLayoutInsets == null) { 14815 mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets(); 14816 } 14817 return mLayoutInsets; 14818 } 14819 14820 /** 14821 * @hide 14822 */ 14823 public void setLayoutInsets(Insets layoutInsets) { 14824 mLayoutInsets = layoutInsets; 14825 } 14826 14827 /** 14828 * Changes the selection state of this view. A view can be selected or not. 14829 * Note that selection is not the same as focus. Views are typically 14830 * selected in the context of an AdapterView like ListView or GridView; 14831 * the selected view is the view that is highlighted. 14832 * 14833 * @param selected true if the view must be selected, false otherwise 14834 */ 14835 public void setSelected(boolean selected) { 14836 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 14837 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 14838 if (!selected) resetPressedState(); 14839 invalidate(true); 14840 refreshDrawableState(); 14841 dispatchSetSelected(selected); 14842 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 14843 notifyAccessibilityStateChanged(); 14844 } 14845 } 14846 } 14847 14848 /** 14849 * Dispatch setSelected to all of this View's children. 14850 * 14851 * @see #setSelected(boolean) 14852 * 14853 * @param selected The new selected state 14854 */ 14855 protected void dispatchSetSelected(boolean selected) { 14856 } 14857 14858 /** 14859 * Indicates the selection state of this view. 14860 * 14861 * @return true if the view is selected, false otherwise 14862 */ 14863 @ViewDebug.ExportedProperty 14864 public boolean isSelected() { 14865 return (mPrivateFlags & PFLAG_SELECTED) != 0; 14866 } 14867 14868 /** 14869 * Changes the activated state of this view. A view can be activated or not. 14870 * Note that activation is not the same as selection. Selection is 14871 * a transient property, representing the view (hierarchy) the user is 14872 * currently interacting with. Activation is a longer-term state that the 14873 * user can move views in and out of. For example, in a list view with 14874 * single or multiple selection enabled, the views in the current selection 14875 * set are activated. (Um, yeah, we are deeply sorry about the terminology 14876 * here.) The activated state is propagated down to children of the view it 14877 * is set on. 14878 * 14879 * @param activated true if the view must be activated, false otherwise 14880 */ 14881 public void setActivated(boolean activated) { 14882 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 14883 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 14884 invalidate(true); 14885 refreshDrawableState(); 14886 dispatchSetActivated(activated); 14887 } 14888 } 14889 14890 /** 14891 * Dispatch setActivated to all of this View's children. 14892 * 14893 * @see #setActivated(boolean) 14894 * 14895 * @param activated The new activated state 14896 */ 14897 protected void dispatchSetActivated(boolean activated) { 14898 } 14899 14900 /** 14901 * Indicates the activation state of this view. 14902 * 14903 * @return true if the view is activated, false otherwise 14904 */ 14905 @ViewDebug.ExportedProperty 14906 public boolean isActivated() { 14907 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 14908 } 14909 14910 /** 14911 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 14912 * observer can be used to get notifications when global events, like 14913 * layout, happen. 14914 * 14915 * The returned ViewTreeObserver observer is not guaranteed to remain 14916 * valid for the lifetime of this View. If the caller of this method keeps 14917 * a long-lived reference to ViewTreeObserver, it should always check for 14918 * the return value of {@link ViewTreeObserver#isAlive()}. 14919 * 14920 * @return The ViewTreeObserver for this view's hierarchy. 14921 */ 14922 public ViewTreeObserver getViewTreeObserver() { 14923 if (mAttachInfo != null) { 14924 return mAttachInfo.mTreeObserver; 14925 } 14926 if (mFloatingTreeObserver == null) { 14927 mFloatingTreeObserver = new ViewTreeObserver(); 14928 } 14929 return mFloatingTreeObserver; 14930 } 14931 14932 /** 14933 * <p>Finds the topmost view in the current view hierarchy.</p> 14934 * 14935 * @return the topmost view containing this view 14936 */ 14937 public View getRootView() { 14938 if (mAttachInfo != null) { 14939 final View v = mAttachInfo.mRootView; 14940 if (v != null) { 14941 return v; 14942 } 14943 } 14944 14945 View parent = this; 14946 14947 while (parent.mParent != null && parent.mParent instanceof View) { 14948 parent = (View) parent.mParent; 14949 } 14950 14951 return parent; 14952 } 14953 14954 /** 14955 * <p>Computes the coordinates of this view on the screen. The argument 14956 * must be an array of two integers. After the method returns, the array 14957 * contains the x and y location in that order.</p> 14958 * 14959 * @param location an array of two integers in which to hold the coordinates 14960 */ 14961 public void getLocationOnScreen(int[] location) { 14962 getLocationInWindow(location); 14963 14964 final AttachInfo info = mAttachInfo; 14965 if (info != null) { 14966 location[0] += info.mWindowLeft; 14967 location[1] += info.mWindowTop; 14968 } 14969 } 14970 14971 /** 14972 * <p>Computes the coordinates of this view in its window. The argument 14973 * must be an array of two integers. After the method returns, the array 14974 * contains the x and y location in that order.</p> 14975 * 14976 * @param location an array of two integers in which to hold the coordinates 14977 */ 14978 public void getLocationInWindow(int[] location) { 14979 if (location == null || location.length < 2) { 14980 throw new IllegalArgumentException("location must be an array of two integers"); 14981 } 14982 14983 if (mAttachInfo == null) { 14984 // When the view is not attached to a window, this method does not make sense 14985 location[0] = location[1] = 0; 14986 return; 14987 } 14988 14989 float[] position = mAttachInfo.mTmpTransformLocation; 14990 position[0] = position[1] = 0.0f; 14991 14992 if (!hasIdentityMatrix()) { 14993 getMatrix().mapPoints(position); 14994 } 14995 14996 position[0] += mLeft; 14997 position[1] += mTop; 14998 14999 ViewParent viewParent = mParent; 15000 while (viewParent instanceof View) { 15001 final View view = (View) viewParent; 15002 15003 position[0] -= view.mScrollX; 15004 position[1] -= view.mScrollY; 15005 15006 if (!view.hasIdentityMatrix()) { 15007 view.getMatrix().mapPoints(position); 15008 } 15009 15010 position[0] += view.mLeft; 15011 position[1] += view.mTop; 15012 15013 viewParent = view.mParent; 15014 } 15015 15016 if (viewParent instanceof ViewRootImpl) { 15017 // *cough* 15018 final ViewRootImpl vr = (ViewRootImpl) viewParent; 15019 position[1] -= vr.mCurScrollY; 15020 } 15021 15022 location[0] = (int) (position[0] + 0.5f); 15023 location[1] = (int) (position[1] + 0.5f); 15024 } 15025 15026 /** 15027 * {@hide} 15028 * @param id the id of the view to be found 15029 * @return the view of the specified id, null if cannot be found 15030 */ 15031 protected View findViewTraversal(int id) { 15032 if (id == mID) { 15033 return this; 15034 } 15035 return null; 15036 } 15037 15038 /** 15039 * {@hide} 15040 * @param tag the tag of the view to be found 15041 * @return the view of specified tag, null if cannot be found 15042 */ 15043 protected View findViewWithTagTraversal(Object tag) { 15044 if (tag != null && tag.equals(mTag)) { 15045 return this; 15046 } 15047 return null; 15048 } 15049 15050 /** 15051 * {@hide} 15052 * @param predicate The predicate to evaluate. 15053 * @param childToSkip If not null, ignores this child during the recursive traversal. 15054 * @return The first view that matches the predicate or null. 15055 */ 15056 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 15057 if (predicate.apply(this)) { 15058 return this; 15059 } 15060 return null; 15061 } 15062 15063 /** 15064 * Look for a child view with the given id. If this view has the given 15065 * id, return this view. 15066 * 15067 * @param id The id to search for. 15068 * @return The view that has the given id in the hierarchy or null 15069 */ 15070 public final View findViewById(int id) { 15071 if (id < 0) { 15072 return null; 15073 } 15074 return findViewTraversal(id); 15075 } 15076 15077 /** 15078 * Finds a view by its unuque and stable accessibility id. 15079 * 15080 * @param accessibilityId The searched accessibility id. 15081 * @return The found view. 15082 */ 15083 final View findViewByAccessibilityId(int accessibilityId) { 15084 if (accessibilityId < 0) { 15085 return null; 15086 } 15087 return findViewByAccessibilityIdTraversal(accessibilityId); 15088 } 15089 15090 /** 15091 * Performs the traversal to find a view by its unuque and stable accessibility id. 15092 * 15093 * <strong>Note:</strong>This method does not stop at the root namespace 15094 * boundary since the user can touch the screen at an arbitrary location 15095 * potentially crossing the root namespace bounday which will send an 15096 * accessibility event to accessibility services and they should be able 15097 * to obtain the event source. Also accessibility ids are guaranteed to be 15098 * unique in the window. 15099 * 15100 * @param accessibilityId The accessibility id. 15101 * @return The found view. 15102 */ 15103 View findViewByAccessibilityIdTraversal(int accessibilityId) { 15104 if (getAccessibilityViewId() == accessibilityId) { 15105 return this; 15106 } 15107 return null; 15108 } 15109 15110 /** 15111 * Look for a child view with the given tag. If this view has the given 15112 * tag, return this view. 15113 * 15114 * @param tag The tag to search for, using "tag.equals(getTag())". 15115 * @return The View that has the given tag in the hierarchy or null 15116 */ 15117 public final View findViewWithTag(Object tag) { 15118 if (tag == null) { 15119 return null; 15120 } 15121 return findViewWithTagTraversal(tag); 15122 } 15123 15124 /** 15125 * {@hide} 15126 * Look for a child view that matches the specified predicate. 15127 * If this view matches the predicate, return this view. 15128 * 15129 * @param predicate The predicate to evaluate. 15130 * @return The first view that matches the predicate or null. 15131 */ 15132 public final View findViewByPredicate(Predicate<View> predicate) { 15133 return findViewByPredicateTraversal(predicate, null); 15134 } 15135 15136 /** 15137 * {@hide} 15138 * Look for a child view that matches the specified predicate, 15139 * starting with the specified view and its descendents and then 15140 * recusively searching the ancestors and siblings of that view 15141 * until this view is reached. 15142 * 15143 * This method is useful in cases where the predicate does not match 15144 * a single unique view (perhaps multiple views use the same id) 15145 * and we are trying to find the view that is "closest" in scope to the 15146 * starting view. 15147 * 15148 * @param start The view to start from. 15149 * @param predicate The predicate to evaluate. 15150 * @return The first view that matches the predicate or null. 15151 */ 15152 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 15153 View childToSkip = null; 15154 for (;;) { 15155 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 15156 if (view != null || start == this) { 15157 return view; 15158 } 15159 15160 ViewParent parent = start.getParent(); 15161 if (parent == null || !(parent instanceof View)) { 15162 return null; 15163 } 15164 15165 childToSkip = start; 15166 start = (View) parent; 15167 } 15168 } 15169 15170 /** 15171 * Sets the identifier for this view. The identifier does not have to be 15172 * unique in this view's hierarchy. The identifier should be a positive 15173 * number. 15174 * 15175 * @see #NO_ID 15176 * @see #getId() 15177 * @see #findViewById(int) 15178 * 15179 * @param id a number used to identify the view 15180 * 15181 * @attr ref android.R.styleable#View_id 15182 */ 15183 public void setId(int id) { 15184 mID = id; 15185 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 15186 mID = generateViewId(); 15187 } 15188 } 15189 15190 /** 15191 * {@hide} 15192 * 15193 * @param isRoot true if the view belongs to the root namespace, false 15194 * otherwise 15195 */ 15196 public void setIsRootNamespace(boolean isRoot) { 15197 if (isRoot) { 15198 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 15199 } else { 15200 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 15201 } 15202 } 15203 15204 /** 15205 * {@hide} 15206 * 15207 * @return true if the view belongs to the root namespace, false otherwise 15208 */ 15209 public boolean isRootNamespace() { 15210 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 15211 } 15212 15213 /** 15214 * Returns this view's identifier. 15215 * 15216 * @return a positive integer used to identify the view or {@link #NO_ID} 15217 * if the view has no ID 15218 * 15219 * @see #setId(int) 15220 * @see #findViewById(int) 15221 * @attr ref android.R.styleable#View_id 15222 */ 15223 @ViewDebug.CapturedViewProperty 15224 public int getId() { 15225 return mID; 15226 } 15227 15228 /** 15229 * Returns this view's tag. 15230 * 15231 * @return the Object stored in this view as a tag 15232 * 15233 * @see #setTag(Object) 15234 * @see #getTag(int) 15235 */ 15236 @ViewDebug.ExportedProperty 15237 public Object getTag() { 15238 return mTag; 15239 } 15240 15241 /** 15242 * Sets the tag associated with this view. A tag can be used to mark 15243 * a view in its hierarchy and does not have to be unique within the 15244 * hierarchy. Tags can also be used to store data within a view without 15245 * resorting to another data structure. 15246 * 15247 * @param tag an Object to tag the view with 15248 * 15249 * @see #getTag() 15250 * @see #setTag(int, Object) 15251 */ 15252 public void setTag(final Object tag) { 15253 mTag = tag; 15254 } 15255 15256 /** 15257 * Returns the tag associated with this view and the specified key. 15258 * 15259 * @param key The key identifying the tag 15260 * 15261 * @return the Object stored in this view as a tag 15262 * 15263 * @see #setTag(int, Object) 15264 * @see #getTag() 15265 */ 15266 public Object getTag(int key) { 15267 if (mKeyedTags != null) return mKeyedTags.get(key); 15268 return null; 15269 } 15270 15271 /** 15272 * Sets a tag associated with this view and a key. A tag can be used 15273 * to mark a view in its hierarchy and does not have to be unique within 15274 * the hierarchy. Tags can also be used to store data within a view 15275 * without resorting to another data structure. 15276 * 15277 * The specified key should be an id declared in the resources of the 15278 * application to ensure it is unique (see the <a 15279 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 15280 * Keys identified as belonging to 15281 * the Android framework or not associated with any package will cause 15282 * an {@link IllegalArgumentException} to be thrown. 15283 * 15284 * @param key The key identifying the tag 15285 * @param tag An Object to tag the view with 15286 * 15287 * @throws IllegalArgumentException If they specified key is not valid 15288 * 15289 * @see #setTag(Object) 15290 * @see #getTag(int) 15291 */ 15292 public void setTag(int key, final Object tag) { 15293 // If the package id is 0x00 or 0x01, it's either an undefined package 15294 // or a framework id 15295 if ((key >>> 24) < 2) { 15296 throw new IllegalArgumentException("The key must be an application-specific " 15297 + "resource id."); 15298 } 15299 15300 setKeyedTag(key, tag); 15301 } 15302 15303 /** 15304 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 15305 * framework id. 15306 * 15307 * @hide 15308 */ 15309 public void setTagInternal(int key, Object tag) { 15310 if ((key >>> 24) != 0x1) { 15311 throw new IllegalArgumentException("The key must be a framework-specific " 15312 + "resource id."); 15313 } 15314 15315 setKeyedTag(key, tag); 15316 } 15317 15318 private void setKeyedTag(int key, Object tag) { 15319 if (mKeyedTags == null) { 15320 mKeyedTags = new SparseArray<Object>(); 15321 } 15322 15323 mKeyedTags.put(key, tag); 15324 } 15325 15326 /** 15327 * Prints information about this view in the log output, with the tag 15328 * {@link #VIEW_LOG_TAG}. 15329 * 15330 * @hide 15331 */ 15332 public void debug() { 15333 debug(0); 15334 } 15335 15336 /** 15337 * Prints information about this view in the log output, with the tag 15338 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 15339 * indentation defined by the <code>depth</code>. 15340 * 15341 * @param depth the indentation level 15342 * 15343 * @hide 15344 */ 15345 protected void debug(int depth) { 15346 String output = debugIndent(depth - 1); 15347 15348 output += "+ " + this; 15349 int id = getId(); 15350 if (id != -1) { 15351 output += " (id=" + id + ")"; 15352 } 15353 Object tag = getTag(); 15354 if (tag != null) { 15355 output += " (tag=" + tag + ")"; 15356 } 15357 Log.d(VIEW_LOG_TAG, output); 15358 15359 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 15360 output = debugIndent(depth) + " FOCUSED"; 15361 Log.d(VIEW_LOG_TAG, output); 15362 } 15363 15364 output = debugIndent(depth); 15365 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 15366 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 15367 + "} "; 15368 Log.d(VIEW_LOG_TAG, output); 15369 15370 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 15371 || mPaddingBottom != 0) { 15372 output = debugIndent(depth); 15373 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 15374 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 15375 Log.d(VIEW_LOG_TAG, output); 15376 } 15377 15378 output = debugIndent(depth); 15379 output += "mMeasureWidth=" + mMeasuredWidth + 15380 " mMeasureHeight=" + mMeasuredHeight; 15381 Log.d(VIEW_LOG_TAG, output); 15382 15383 output = debugIndent(depth); 15384 if (mLayoutParams == null) { 15385 output += "BAD! no layout params"; 15386 } else { 15387 output = mLayoutParams.debug(output); 15388 } 15389 Log.d(VIEW_LOG_TAG, output); 15390 15391 output = debugIndent(depth); 15392 output += "flags={"; 15393 output += View.printFlags(mViewFlags); 15394 output += "}"; 15395 Log.d(VIEW_LOG_TAG, output); 15396 15397 output = debugIndent(depth); 15398 output += "privateFlags={"; 15399 output += View.printPrivateFlags(mPrivateFlags); 15400 output += "}"; 15401 Log.d(VIEW_LOG_TAG, output); 15402 } 15403 15404 /** 15405 * Creates a string of whitespaces used for indentation. 15406 * 15407 * @param depth the indentation level 15408 * @return a String containing (depth * 2 + 3) * 2 white spaces 15409 * 15410 * @hide 15411 */ 15412 protected static String debugIndent(int depth) { 15413 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 15414 for (int i = 0; i < (depth * 2) + 3; i++) { 15415 spaces.append(' ').append(' '); 15416 } 15417 return spaces.toString(); 15418 } 15419 15420 /** 15421 * <p>Return the offset of the widget's text baseline from the widget's top 15422 * boundary. If this widget does not support baseline alignment, this 15423 * method returns -1. </p> 15424 * 15425 * @return the offset of the baseline within the widget's bounds or -1 15426 * if baseline alignment is not supported 15427 */ 15428 @ViewDebug.ExportedProperty(category = "layout") 15429 public int getBaseline() { 15430 return -1; 15431 } 15432 15433 /** 15434 * Call this when something has changed which has invalidated the 15435 * layout of this view. This will schedule a layout pass of the view 15436 * tree. 15437 */ 15438 public void requestLayout() { 15439 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 15440 mPrivateFlags |= PFLAG_INVALIDATED; 15441 15442 if (mParent != null && !mParent.isLayoutRequested()) { 15443 mParent.requestLayout(); 15444 } 15445 } 15446 15447 /** 15448 * Forces this view to be laid out during the next layout pass. 15449 * This method does not call requestLayout() or forceLayout() 15450 * on the parent. 15451 */ 15452 public void forceLayout() { 15453 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 15454 mPrivateFlags |= PFLAG_INVALIDATED; 15455 } 15456 15457 /** 15458 * <p> 15459 * This is called to find out how big a view should be. The parent 15460 * supplies constraint information in the width and height parameters. 15461 * </p> 15462 * 15463 * <p> 15464 * The actual measurement work of a view is performed in 15465 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 15466 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 15467 * </p> 15468 * 15469 * 15470 * @param widthMeasureSpec Horizontal space requirements as imposed by the 15471 * parent 15472 * @param heightMeasureSpec Vertical space requirements as imposed by the 15473 * parent 15474 * 15475 * @see #onMeasure(int, int) 15476 */ 15477 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 15478 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 15479 widthMeasureSpec != mOldWidthMeasureSpec || 15480 heightMeasureSpec != mOldHeightMeasureSpec) { 15481 15482 // first clears the measured dimension flag 15483 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 15484 15485 resolveRtlPropertiesIfNeeded(); 15486 15487 // measure ourselves, this should set the measured dimension flag back 15488 onMeasure(widthMeasureSpec, heightMeasureSpec); 15489 15490 // flag not set, setMeasuredDimension() was not invoked, we raise 15491 // an exception to warn the developer 15492 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 15493 throw new IllegalStateException("onMeasure() did not set the" 15494 + " measured dimension by calling" 15495 + " setMeasuredDimension()"); 15496 } 15497 15498 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 15499 } 15500 15501 mOldWidthMeasureSpec = widthMeasureSpec; 15502 mOldHeightMeasureSpec = heightMeasureSpec; 15503 } 15504 15505 /** 15506 * <p> 15507 * Measure the view and its content to determine the measured width and the 15508 * measured height. This method is invoked by {@link #measure(int, int)} and 15509 * should be overriden by subclasses to provide accurate and efficient 15510 * measurement of their contents. 15511 * </p> 15512 * 15513 * <p> 15514 * <strong>CONTRACT:</strong> When overriding this method, you 15515 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 15516 * measured width and height of this view. Failure to do so will trigger an 15517 * <code>IllegalStateException</code>, thrown by 15518 * {@link #measure(int, int)}. Calling the superclass' 15519 * {@link #onMeasure(int, int)} is a valid use. 15520 * </p> 15521 * 15522 * <p> 15523 * The base class implementation of measure defaults to the background size, 15524 * unless a larger size is allowed by the MeasureSpec. Subclasses should 15525 * override {@link #onMeasure(int, int)} to provide better measurements of 15526 * their content. 15527 * </p> 15528 * 15529 * <p> 15530 * If this method is overridden, it is the subclass's responsibility to make 15531 * sure the measured height and width are at least the view's minimum height 15532 * and width ({@link #getSuggestedMinimumHeight()} and 15533 * {@link #getSuggestedMinimumWidth()}). 15534 * </p> 15535 * 15536 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 15537 * The requirements are encoded with 15538 * {@link android.view.View.MeasureSpec}. 15539 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 15540 * The requirements are encoded with 15541 * {@link android.view.View.MeasureSpec}. 15542 * 15543 * @see #getMeasuredWidth() 15544 * @see #getMeasuredHeight() 15545 * @see #setMeasuredDimension(int, int) 15546 * @see #getSuggestedMinimumHeight() 15547 * @see #getSuggestedMinimumWidth() 15548 * @see android.view.View.MeasureSpec#getMode(int) 15549 * @see android.view.View.MeasureSpec#getSize(int) 15550 */ 15551 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 15552 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 15553 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 15554 } 15555 15556 /** 15557 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 15558 * measured width and measured height. Failing to do so will trigger an 15559 * exception at measurement time.</p> 15560 * 15561 * @param measuredWidth The measured width of this view. May be a complex 15562 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 15563 * {@link #MEASURED_STATE_TOO_SMALL}. 15564 * @param measuredHeight The measured height of this view. May be a complex 15565 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 15566 * {@link #MEASURED_STATE_TOO_SMALL}. 15567 */ 15568 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 15569 mMeasuredWidth = measuredWidth; 15570 mMeasuredHeight = measuredHeight; 15571 15572 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 15573 } 15574 15575 /** 15576 * Merge two states as returned by {@link #getMeasuredState()}. 15577 * @param curState The current state as returned from a view or the result 15578 * of combining multiple views. 15579 * @param newState The new view state to combine. 15580 * @return Returns a new integer reflecting the combination of the two 15581 * states. 15582 */ 15583 public static int combineMeasuredStates(int curState, int newState) { 15584 return curState | newState; 15585 } 15586 15587 /** 15588 * Version of {@link #resolveSizeAndState(int, int, int)} 15589 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 15590 */ 15591 public static int resolveSize(int size, int measureSpec) { 15592 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 15593 } 15594 15595 /** 15596 * Utility to reconcile a desired size and state, with constraints imposed 15597 * by a MeasureSpec. Will take the desired size, unless a different size 15598 * is imposed by the constraints. The returned value is a compound integer, 15599 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 15600 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 15601 * size is smaller than the size the view wants to be. 15602 * 15603 * @param size How big the view wants to be 15604 * @param measureSpec Constraints imposed by the parent 15605 * @return Size information bit mask as defined by 15606 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 15607 */ 15608 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 15609 int result = size; 15610 int specMode = MeasureSpec.getMode(measureSpec); 15611 int specSize = MeasureSpec.getSize(measureSpec); 15612 switch (specMode) { 15613 case MeasureSpec.UNSPECIFIED: 15614 result = size; 15615 break; 15616 case MeasureSpec.AT_MOST: 15617 if (specSize < size) { 15618 result = specSize | MEASURED_STATE_TOO_SMALL; 15619 } else { 15620 result = size; 15621 } 15622 break; 15623 case MeasureSpec.EXACTLY: 15624 result = specSize; 15625 break; 15626 } 15627 return result | (childMeasuredState&MEASURED_STATE_MASK); 15628 } 15629 15630 /** 15631 * Utility to return a default size. Uses the supplied size if the 15632 * MeasureSpec imposed no constraints. Will get larger if allowed 15633 * by the MeasureSpec. 15634 * 15635 * @param size Default size for this view 15636 * @param measureSpec Constraints imposed by the parent 15637 * @return The size this view should be. 15638 */ 15639 public static int getDefaultSize(int size, int measureSpec) { 15640 int result = size; 15641 int specMode = MeasureSpec.getMode(measureSpec); 15642 int specSize = MeasureSpec.getSize(measureSpec); 15643 15644 switch (specMode) { 15645 case MeasureSpec.UNSPECIFIED: 15646 result = size; 15647 break; 15648 case MeasureSpec.AT_MOST: 15649 case MeasureSpec.EXACTLY: 15650 result = specSize; 15651 break; 15652 } 15653 return result; 15654 } 15655 15656 /** 15657 * Returns the suggested minimum height that the view should use. This 15658 * returns the maximum of the view's minimum height 15659 * and the background's minimum height 15660 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 15661 * <p> 15662 * When being used in {@link #onMeasure(int, int)}, the caller should still 15663 * ensure the returned height is within the requirements of the parent. 15664 * 15665 * @return The suggested minimum height of the view. 15666 */ 15667 protected int getSuggestedMinimumHeight() { 15668 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 15669 15670 } 15671 15672 /** 15673 * Returns the suggested minimum width that the view should use. This 15674 * returns the maximum of the view's minimum width) 15675 * and the background's minimum width 15676 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 15677 * <p> 15678 * When being used in {@link #onMeasure(int, int)}, the caller should still 15679 * ensure the returned width is within the requirements of the parent. 15680 * 15681 * @return The suggested minimum width of the view. 15682 */ 15683 protected int getSuggestedMinimumWidth() { 15684 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 15685 } 15686 15687 /** 15688 * Returns the minimum height of the view. 15689 * 15690 * @return the minimum height the view will try to be. 15691 * 15692 * @see #setMinimumHeight(int) 15693 * 15694 * @attr ref android.R.styleable#View_minHeight 15695 */ 15696 public int getMinimumHeight() { 15697 return mMinHeight; 15698 } 15699 15700 /** 15701 * Sets the minimum height of the view. It is not guaranteed the view will 15702 * be able to achieve this minimum height (for example, if its parent layout 15703 * constrains it with less available height). 15704 * 15705 * @param minHeight The minimum height the view will try to be. 15706 * 15707 * @see #getMinimumHeight() 15708 * 15709 * @attr ref android.R.styleable#View_minHeight 15710 */ 15711 public void setMinimumHeight(int minHeight) { 15712 mMinHeight = minHeight; 15713 requestLayout(); 15714 } 15715 15716 /** 15717 * Returns the minimum width of the view. 15718 * 15719 * @return the minimum width the view will try to be. 15720 * 15721 * @see #setMinimumWidth(int) 15722 * 15723 * @attr ref android.R.styleable#View_minWidth 15724 */ 15725 public int getMinimumWidth() { 15726 return mMinWidth; 15727 } 15728 15729 /** 15730 * Sets the minimum width of the view. It is not guaranteed the view will 15731 * be able to achieve this minimum width (for example, if its parent layout 15732 * constrains it with less available width). 15733 * 15734 * @param minWidth The minimum width the view will try to be. 15735 * 15736 * @see #getMinimumWidth() 15737 * 15738 * @attr ref android.R.styleable#View_minWidth 15739 */ 15740 public void setMinimumWidth(int minWidth) { 15741 mMinWidth = minWidth; 15742 requestLayout(); 15743 15744 } 15745 15746 /** 15747 * Get the animation currently associated with this view. 15748 * 15749 * @return The animation that is currently playing or 15750 * scheduled to play for this view. 15751 */ 15752 public Animation getAnimation() { 15753 return mCurrentAnimation; 15754 } 15755 15756 /** 15757 * Start the specified animation now. 15758 * 15759 * @param animation the animation to start now 15760 */ 15761 public void startAnimation(Animation animation) { 15762 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 15763 setAnimation(animation); 15764 invalidateParentCaches(); 15765 invalidate(true); 15766 } 15767 15768 /** 15769 * Cancels any animations for this view. 15770 */ 15771 public void clearAnimation() { 15772 if (mCurrentAnimation != null) { 15773 mCurrentAnimation.detach(); 15774 } 15775 mCurrentAnimation = null; 15776 invalidateParentIfNeeded(); 15777 } 15778 15779 /** 15780 * Sets the next animation to play for this view. 15781 * If you want the animation to play immediately, use 15782 * {@link #startAnimation(android.view.animation.Animation)} instead. 15783 * This method provides allows fine-grained 15784 * control over the start time and invalidation, but you 15785 * must make sure that 1) the animation has a start time set, and 15786 * 2) the view's parent (which controls animations on its children) 15787 * will be invalidated when the animation is supposed to 15788 * start. 15789 * 15790 * @param animation The next animation, or null. 15791 */ 15792 public void setAnimation(Animation animation) { 15793 mCurrentAnimation = animation; 15794 15795 if (animation != null) { 15796 // If the screen is off assume the animation start time is now instead of 15797 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 15798 // would cause the animation to start when the screen turns back on 15799 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 15800 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 15801 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 15802 } 15803 animation.reset(); 15804 } 15805 } 15806 15807 /** 15808 * Invoked by a parent ViewGroup to notify the start of the animation 15809 * currently associated with this view. If you override this method, 15810 * always call super.onAnimationStart(); 15811 * 15812 * @see #setAnimation(android.view.animation.Animation) 15813 * @see #getAnimation() 15814 */ 15815 protected void onAnimationStart() { 15816 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 15817 } 15818 15819 /** 15820 * Invoked by a parent ViewGroup to notify the end of the animation 15821 * currently associated with this view. If you override this method, 15822 * always call super.onAnimationEnd(); 15823 * 15824 * @see #setAnimation(android.view.animation.Animation) 15825 * @see #getAnimation() 15826 */ 15827 protected void onAnimationEnd() { 15828 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 15829 } 15830 15831 /** 15832 * Invoked if there is a Transform that involves alpha. Subclass that can 15833 * draw themselves with the specified alpha should return true, and then 15834 * respect that alpha when their onDraw() is called. If this returns false 15835 * then the view may be redirected to draw into an offscreen buffer to 15836 * fulfill the request, which will look fine, but may be slower than if the 15837 * subclass handles it internally. The default implementation returns false. 15838 * 15839 * @param alpha The alpha (0..255) to apply to the view's drawing 15840 * @return true if the view can draw with the specified alpha. 15841 */ 15842 protected boolean onSetAlpha(int alpha) { 15843 return false; 15844 } 15845 15846 /** 15847 * This is used by the RootView to perform an optimization when 15848 * the view hierarchy contains one or several SurfaceView. 15849 * SurfaceView is always considered transparent, but its children are not, 15850 * therefore all View objects remove themselves from the global transparent 15851 * region (passed as a parameter to this function). 15852 * 15853 * @param region The transparent region for this ViewAncestor (window). 15854 * 15855 * @return Returns true if the effective visibility of the view at this 15856 * point is opaque, regardless of the transparent region; returns false 15857 * if it is possible for underlying windows to be seen behind the view. 15858 * 15859 * {@hide} 15860 */ 15861 public boolean gatherTransparentRegion(Region region) { 15862 final AttachInfo attachInfo = mAttachInfo; 15863 if (region != null && attachInfo != null) { 15864 final int pflags = mPrivateFlags; 15865 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 15866 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 15867 // remove it from the transparent region. 15868 final int[] location = attachInfo.mTransparentLocation; 15869 getLocationInWindow(location); 15870 region.op(location[0], location[1], location[0] + mRight - mLeft, 15871 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 15872 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 15873 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 15874 // exists, so we remove the background drawable's non-transparent 15875 // parts from this transparent region. 15876 applyDrawableToTransparentRegion(mBackground, region); 15877 } 15878 } 15879 return true; 15880 } 15881 15882 /** 15883 * Play a sound effect for this view. 15884 * 15885 * <p>The framework will play sound effects for some built in actions, such as 15886 * clicking, but you may wish to play these effects in your widget, 15887 * for instance, for internal navigation. 15888 * 15889 * <p>The sound effect will only be played if sound effects are enabled by the user, and 15890 * {@link #isSoundEffectsEnabled()} is true. 15891 * 15892 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 15893 */ 15894 public void playSoundEffect(int soundConstant) { 15895 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 15896 return; 15897 } 15898 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 15899 } 15900 15901 /** 15902 * BZZZTT!!1! 15903 * 15904 * <p>Provide haptic feedback to the user for this view. 15905 * 15906 * <p>The framework will provide haptic feedback for some built in actions, 15907 * such as long presses, but you may wish to provide feedback for your 15908 * own widget. 15909 * 15910 * <p>The feedback will only be performed if 15911 * {@link #isHapticFeedbackEnabled()} is true. 15912 * 15913 * @param feedbackConstant One of the constants defined in 15914 * {@link HapticFeedbackConstants} 15915 */ 15916 public boolean performHapticFeedback(int feedbackConstant) { 15917 return performHapticFeedback(feedbackConstant, 0); 15918 } 15919 15920 /** 15921 * BZZZTT!!1! 15922 * 15923 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 15924 * 15925 * @param feedbackConstant One of the constants defined in 15926 * {@link HapticFeedbackConstants} 15927 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 15928 */ 15929 public boolean performHapticFeedback(int feedbackConstant, int flags) { 15930 if (mAttachInfo == null) { 15931 return false; 15932 } 15933 //noinspection SimplifiableIfStatement 15934 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 15935 && !isHapticFeedbackEnabled()) { 15936 return false; 15937 } 15938 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 15939 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 15940 } 15941 15942 /** 15943 * Request that the visibility of the status bar or other screen/window 15944 * decorations be changed. 15945 * 15946 * <p>This method is used to put the over device UI into temporary modes 15947 * where the user's attention is focused more on the application content, 15948 * by dimming or hiding surrounding system affordances. This is typically 15949 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 15950 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 15951 * to be placed behind the action bar (and with these flags other system 15952 * affordances) so that smooth transitions between hiding and showing them 15953 * can be done. 15954 * 15955 * <p>Two representative examples of the use of system UI visibility is 15956 * implementing a content browsing application (like a magazine reader) 15957 * and a video playing application. 15958 * 15959 * <p>The first code shows a typical implementation of a View in a content 15960 * browsing application. In this implementation, the application goes 15961 * into a content-oriented mode by hiding the status bar and action bar, 15962 * and putting the navigation elements into lights out mode. The user can 15963 * then interact with content while in this mode. Such an application should 15964 * provide an easy way for the user to toggle out of the mode (such as to 15965 * check information in the status bar or access notifications). In the 15966 * implementation here, this is done simply by tapping on the content. 15967 * 15968 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 15969 * content} 15970 * 15971 * <p>This second code sample shows a typical implementation of a View 15972 * in a video playing application. In this situation, while the video is 15973 * playing the application would like to go into a complete full-screen mode, 15974 * to use as much of the display as possible for the video. When in this state 15975 * the user can not interact with the application; the system intercepts 15976 * touching on the screen to pop the UI out of full screen mode. See 15977 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 15978 * 15979 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 15980 * content} 15981 * 15982 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 15983 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 15984 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 15985 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 15986 */ 15987 public void setSystemUiVisibility(int visibility) { 15988 if (visibility != mSystemUiVisibility) { 15989 mSystemUiVisibility = visibility; 15990 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 15991 mParent.recomputeViewAttributes(this); 15992 } 15993 } 15994 } 15995 15996 /** 15997 * Returns the last {@link #setSystemUiVisibility(int) that this view has requested. 15998 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 15999 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 16000 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 16001 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 16002 */ 16003 public int getSystemUiVisibility() { 16004 return mSystemUiVisibility; 16005 } 16006 16007 /** 16008 * Returns the current system UI visibility that is currently set for 16009 * the entire window. This is the combination of the 16010 * {@link #setSystemUiVisibility(int)} values supplied by all of the 16011 * views in the window. 16012 */ 16013 public int getWindowSystemUiVisibility() { 16014 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 16015 } 16016 16017 /** 16018 * Override to find out when the window's requested system UI visibility 16019 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 16020 * This is different from the callbacks recieved through 16021 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 16022 * in that this is only telling you about the local request of the window, 16023 * not the actual values applied by the system. 16024 */ 16025 public void onWindowSystemUiVisibilityChanged(int visible) { 16026 } 16027 16028 /** 16029 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 16030 * the view hierarchy. 16031 */ 16032 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 16033 onWindowSystemUiVisibilityChanged(visible); 16034 } 16035 16036 /** 16037 * Set a listener to receive callbacks when the visibility of the system bar changes. 16038 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 16039 */ 16040 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 16041 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 16042 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 16043 mParent.recomputeViewAttributes(this); 16044 } 16045 } 16046 16047 /** 16048 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 16049 * the view hierarchy. 16050 */ 16051 public void dispatchSystemUiVisibilityChanged(int visibility) { 16052 ListenerInfo li = mListenerInfo; 16053 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 16054 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 16055 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 16056 } 16057 } 16058 16059 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 16060 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 16061 if (val != mSystemUiVisibility) { 16062 setSystemUiVisibility(val); 16063 return true; 16064 } 16065 return false; 16066 } 16067 16068 /** @hide */ 16069 public void setDisabledSystemUiVisibility(int flags) { 16070 if (mAttachInfo != null) { 16071 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 16072 mAttachInfo.mDisabledSystemUiVisibility = flags; 16073 if (mParent != null) { 16074 mParent.recomputeViewAttributes(this); 16075 } 16076 } 16077 } 16078 } 16079 16080 /** 16081 * Creates an image that the system displays during the drag and drop 16082 * operation. This is called a "drag shadow". The default implementation 16083 * for a DragShadowBuilder based on a View returns an image that has exactly the same 16084 * appearance as the given View. The default also positions the center of the drag shadow 16085 * directly under the touch point. If no View is provided (the constructor with no parameters 16086 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 16087 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 16088 * default is an invisible drag shadow. 16089 * <p> 16090 * You are not required to use the View you provide to the constructor as the basis of the 16091 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 16092 * anything you want as the drag shadow. 16093 * </p> 16094 * <p> 16095 * You pass a DragShadowBuilder object to the system when you start the drag. The system 16096 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 16097 * size and position of the drag shadow. It uses this data to construct a 16098 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 16099 * so that your application can draw the shadow image in the Canvas. 16100 * </p> 16101 * 16102 * <div class="special reference"> 16103 * <h3>Developer Guides</h3> 16104 * <p>For a guide to implementing drag and drop features, read the 16105 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 16106 * </div> 16107 */ 16108 public static class DragShadowBuilder { 16109 private final WeakReference<View> mView; 16110 16111 /** 16112 * Constructs a shadow image builder based on a View. By default, the resulting drag 16113 * shadow will have the same appearance and dimensions as the View, with the touch point 16114 * over the center of the View. 16115 * @param view A View. Any View in scope can be used. 16116 */ 16117 public DragShadowBuilder(View view) { 16118 mView = new WeakReference<View>(view); 16119 } 16120 16121 /** 16122 * Construct a shadow builder object with no associated View. This 16123 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 16124 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 16125 * to supply the drag shadow's dimensions and appearance without 16126 * reference to any View object. If they are not overridden, then the result is an 16127 * invisible drag shadow. 16128 */ 16129 public DragShadowBuilder() { 16130 mView = new WeakReference<View>(null); 16131 } 16132 16133 /** 16134 * Returns the View object that had been passed to the 16135 * {@link #View.DragShadowBuilder(View)} 16136 * constructor. If that View parameter was {@code null} or if the 16137 * {@link #View.DragShadowBuilder()} 16138 * constructor was used to instantiate the builder object, this method will return 16139 * null. 16140 * 16141 * @return The View object associate with this builder object. 16142 */ 16143 @SuppressWarnings({"JavadocReference"}) 16144 final public View getView() { 16145 return mView.get(); 16146 } 16147 16148 /** 16149 * Provides the metrics for the shadow image. These include the dimensions of 16150 * the shadow image, and the point within that shadow that should 16151 * be centered under the touch location while dragging. 16152 * <p> 16153 * The default implementation sets the dimensions of the shadow to be the 16154 * same as the dimensions of the View itself and centers the shadow under 16155 * the touch point. 16156 * </p> 16157 * 16158 * @param shadowSize A {@link android.graphics.Point} containing the width and height 16159 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 16160 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 16161 * image. 16162 * 16163 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 16164 * shadow image that should be underneath the touch point during the drag and drop 16165 * operation. Your application must set {@link android.graphics.Point#x} to the 16166 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 16167 */ 16168 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 16169 final View view = mView.get(); 16170 if (view != null) { 16171 shadowSize.set(view.getWidth(), view.getHeight()); 16172 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 16173 } else { 16174 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 16175 } 16176 } 16177 16178 /** 16179 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 16180 * based on the dimensions it received from the 16181 * {@link #onProvideShadowMetrics(Point, Point)} callback. 16182 * 16183 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 16184 */ 16185 public void onDrawShadow(Canvas canvas) { 16186 final View view = mView.get(); 16187 if (view != null) { 16188 view.draw(canvas); 16189 } else { 16190 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 16191 } 16192 } 16193 } 16194 16195 /** 16196 * Starts a drag and drop operation. When your application calls this method, it passes a 16197 * {@link android.view.View.DragShadowBuilder} object to the system. The 16198 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 16199 * to get metrics for the drag shadow, and then calls the object's 16200 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 16201 * <p> 16202 * Once the system has the drag shadow, it begins the drag and drop operation by sending 16203 * drag events to all the View objects in your application that are currently visible. It does 16204 * this either by calling the View object's drag listener (an implementation of 16205 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 16206 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 16207 * Both are passed a {@link android.view.DragEvent} object that has a 16208 * {@link android.view.DragEvent#getAction()} value of 16209 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 16210 * </p> 16211 * <p> 16212 * Your application can invoke startDrag() on any attached View object. The View object does not 16213 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 16214 * be related to the View the user selected for dragging. 16215 * </p> 16216 * @param data A {@link android.content.ClipData} object pointing to the data to be 16217 * transferred by the drag and drop operation. 16218 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 16219 * drag shadow. 16220 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 16221 * drop operation. This Object is put into every DragEvent object sent by the system during the 16222 * current drag. 16223 * <p> 16224 * myLocalState is a lightweight mechanism for the sending information from the dragged View 16225 * to the target Views. For example, it can contain flags that differentiate between a 16226 * a copy operation and a move operation. 16227 * </p> 16228 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 16229 * so the parameter should be set to 0. 16230 * @return {@code true} if the method completes successfully, or 16231 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 16232 * do a drag, and so no drag operation is in progress. 16233 */ 16234 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 16235 Object myLocalState, int flags) { 16236 if (ViewDebug.DEBUG_DRAG) { 16237 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 16238 } 16239 boolean okay = false; 16240 16241 Point shadowSize = new Point(); 16242 Point shadowTouchPoint = new Point(); 16243 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 16244 16245 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 16246 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 16247 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 16248 } 16249 16250 if (ViewDebug.DEBUG_DRAG) { 16251 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 16252 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 16253 } 16254 Surface surface = new Surface(); 16255 try { 16256 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 16257 flags, shadowSize.x, shadowSize.y, surface); 16258 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 16259 + " surface=" + surface); 16260 if (token != null) { 16261 Canvas canvas = surface.lockCanvas(null); 16262 try { 16263 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 16264 shadowBuilder.onDrawShadow(canvas); 16265 } finally { 16266 surface.unlockCanvasAndPost(canvas); 16267 } 16268 16269 final ViewRootImpl root = getViewRootImpl(); 16270 16271 // Cache the local state object for delivery with DragEvents 16272 root.setLocalDragState(myLocalState); 16273 16274 // repurpose 'shadowSize' for the last touch point 16275 root.getLastTouchPoint(shadowSize); 16276 16277 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 16278 shadowSize.x, shadowSize.y, 16279 shadowTouchPoint.x, shadowTouchPoint.y, data); 16280 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 16281 16282 // Off and running! Release our local surface instance; the drag 16283 // shadow surface is now managed by the system process. 16284 surface.release(); 16285 } 16286 } catch (Exception e) { 16287 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 16288 surface.destroy(); 16289 } 16290 16291 return okay; 16292 } 16293 16294 /** 16295 * Handles drag events sent by the system following a call to 16296 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 16297 *<p> 16298 * When the system calls this method, it passes a 16299 * {@link android.view.DragEvent} object. A call to 16300 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 16301 * in DragEvent. The method uses these to determine what is happening in the drag and drop 16302 * operation. 16303 * @param event The {@link android.view.DragEvent} sent by the system. 16304 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 16305 * in DragEvent, indicating the type of drag event represented by this object. 16306 * @return {@code true} if the method was successful, otherwise {@code false}. 16307 * <p> 16308 * The method should return {@code true} in response to an action type of 16309 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 16310 * operation. 16311 * </p> 16312 * <p> 16313 * The method should also return {@code true} in response to an action type of 16314 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 16315 * {@code false} if it didn't. 16316 * </p> 16317 */ 16318 public boolean onDragEvent(DragEvent event) { 16319 return false; 16320 } 16321 16322 /** 16323 * Detects if this View is enabled and has a drag event listener. 16324 * If both are true, then it calls the drag event listener with the 16325 * {@link android.view.DragEvent} it received. If the drag event listener returns 16326 * {@code true}, then dispatchDragEvent() returns {@code true}. 16327 * <p> 16328 * For all other cases, the method calls the 16329 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 16330 * method and returns its result. 16331 * </p> 16332 * <p> 16333 * This ensures that a drag event is always consumed, even if the View does not have a drag 16334 * event listener. However, if the View has a listener and the listener returns true, then 16335 * onDragEvent() is not called. 16336 * </p> 16337 */ 16338 public boolean dispatchDragEvent(DragEvent event) { 16339 //noinspection SimplifiableIfStatement 16340 ListenerInfo li = mListenerInfo; 16341 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 16342 && li.mOnDragListener.onDrag(this, event)) { 16343 return true; 16344 } 16345 return onDragEvent(event); 16346 } 16347 16348 boolean canAcceptDrag() { 16349 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 16350 } 16351 16352 /** 16353 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 16354 * it is ever exposed at all. 16355 * @hide 16356 */ 16357 public void onCloseSystemDialogs(String reason) { 16358 } 16359 16360 /** 16361 * Given a Drawable whose bounds have been set to draw into this view, 16362 * update a Region being computed for 16363 * {@link #gatherTransparentRegion(android.graphics.Region)} so 16364 * that any non-transparent parts of the Drawable are removed from the 16365 * given transparent region. 16366 * 16367 * @param dr The Drawable whose transparency is to be applied to the region. 16368 * @param region A Region holding the current transparency information, 16369 * where any parts of the region that are set are considered to be 16370 * transparent. On return, this region will be modified to have the 16371 * transparency information reduced by the corresponding parts of the 16372 * Drawable that are not transparent. 16373 * {@hide} 16374 */ 16375 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 16376 if (DBG) { 16377 Log.i("View", "Getting transparent region for: " + this); 16378 } 16379 final Region r = dr.getTransparentRegion(); 16380 final Rect db = dr.getBounds(); 16381 final AttachInfo attachInfo = mAttachInfo; 16382 if (r != null && attachInfo != null) { 16383 final int w = getRight()-getLeft(); 16384 final int h = getBottom()-getTop(); 16385 if (db.left > 0) { 16386 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 16387 r.op(0, 0, db.left, h, Region.Op.UNION); 16388 } 16389 if (db.right < w) { 16390 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 16391 r.op(db.right, 0, w, h, Region.Op.UNION); 16392 } 16393 if (db.top > 0) { 16394 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 16395 r.op(0, 0, w, db.top, Region.Op.UNION); 16396 } 16397 if (db.bottom < h) { 16398 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 16399 r.op(0, db.bottom, w, h, Region.Op.UNION); 16400 } 16401 final int[] location = attachInfo.mTransparentLocation; 16402 getLocationInWindow(location); 16403 r.translate(location[0], location[1]); 16404 region.op(r, Region.Op.INTERSECT); 16405 } else { 16406 region.op(db, Region.Op.DIFFERENCE); 16407 } 16408 } 16409 16410 private void checkForLongClick(int delayOffset) { 16411 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 16412 mHasPerformedLongPress = false; 16413 16414 if (mPendingCheckForLongPress == null) { 16415 mPendingCheckForLongPress = new CheckForLongPress(); 16416 } 16417 mPendingCheckForLongPress.rememberWindowAttachCount(); 16418 postDelayed(mPendingCheckForLongPress, 16419 ViewConfiguration.getLongPressTimeout() - delayOffset); 16420 } 16421 } 16422 16423 /** 16424 * Inflate a view from an XML resource. This convenience method wraps the {@link 16425 * LayoutInflater} class, which provides a full range of options for view inflation. 16426 * 16427 * @param context The Context object for your activity or application. 16428 * @param resource The resource ID to inflate 16429 * @param root A view group that will be the parent. Used to properly inflate the 16430 * layout_* parameters. 16431 * @see LayoutInflater 16432 */ 16433 public static View inflate(Context context, int resource, ViewGroup root) { 16434 LayoutInflater factory = LayoutInflater.from(context); 16435 return factory.inflate(resource, root); 16436 } 16437 16438 /** 16439 * Scroll the view with standard behavior for scrolling beyond the normal 16440 * content boundaries. Views that call this method should override 16441 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 16442 * results of an over-scroll operation. 16443 * 16444 * Views can use this method to handle any touch or fling-based scrolling. 16445 * 16446 * @param deltaX Change in X in pixels 16447 * @param deltaY Change in Y in pixels 16448 * @param scrollX Current X scroll value in pixels before applying deltaX 16449 * @param scrollY Current Y scroll value in pixels before applying deltaY 16450 * @param scrollRangeX Maximum content scroll range along the X axis 16451 * @param scrollRangeY Maximum content scroll range along the Y axis 16452 * @param maxOverScrollX Number of pixels to overscroll by in either direction 16453 * along the X axis. 16454 * @param maxOverScrollY Number of pixels to overscroll by in either direction 16455 * along the Y axis. 16456 * @param isTouchEvent true if this scroll operation is the result of a touch event. 16457 * @return true if scrolling was clamped to an over-scroll boundary along either 16458 * axis, false otherwise. 16459 */ 16460 @SuppressWarnings({"UnusedParameters"}) 16461 protected boolean overScrollBy(int deltaX, int deltaY, 16462 int scrollX, int scrollY, 16463 int scrollRangeX, int scrollRangeY, 16464 int maxOverScrollX, int maxOverScrollY, 16465 boolean isTouchEvent) { 16466 final int overScrollMode = mOverScrollMode; 16467 final boolean canScrollHorizontal = 16468 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 16469 final boolean canScrollVertical = 16470 computeVerticalScrollRange() > computeVerticalScrollExtent(); 16471 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 16472 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 16473 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 16474 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 16475 16476 int newScrollX = scrollX + deltaX; 16477 if (!overScrollHorizontal) { 16478 maxOverScrollX = 0; 16479 } 16480 16481 int newScrollY = scrollY + deltaY; 16482 if (!overScrollVertical) { 16483 maxOverScrollY = 0; 16484 } 16485 16486 // Clamp values if at the limits and record 16487 final int left = -maxOverScrollX; 16488 final int right = maxOverScrollX + scrollRangeX; 16489 final int top = -maxOverScrollY; 16490 final int bottom = maxOverScrollY + scrollRangeY; 16491 16492 boolean clampedX = false; 16493 if (newScrollX > right) { 16494 newScrollX = right; 16495 clampedX = true; 16496 } else if (newScrollX < left) { 16497 newScrollX = left; 16498 clampedX = true; 16499 } 16500 16501 boolean clampedY = false; 16502 if (newScrollY > bottom) { 16503 newScrollY = bottom; 16504 clampedY = true; 16505 } else if (newScrollY < top) { 16506 newScrollY = top; 16507 clampedY = true; 16508 } 16509 16510 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 16511 16512 return clampedX || clampedY; 16513 } 16514 16515 /** 16516 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 16517 * respond to the results of an over-scroll operation. 16518 * 16519 * @param scrollX New X scroll value in pixels 16520 * @param scrollY New Y scroll value in pixels 16521 * @param clampedX True if scrollX was clamped to an over-scroll boundary 16522 * @param clampedY True if scrollY was clamped to an over-scroll boundary 16523 */ 16524 protected void onOverScrolled(int scrollX, int scrollY, 16525 boolean clampedX, boolean clampedY) { 16526 // Intentionally empty. 16527 } 16528 16529 /** 16530 * Returns the over-scroll mode for this view. The result will be 16531 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16532 * (allow over-scrolling only if the view content is larger than the container), 16533 * or {@link #OVER_SCROLL_NEVER}. 16534 * 16535 * @return This view's over-scroll mode. 16536 */ 16537 public int getOverScrollMode() { 16538 return mOverScrollMode; 16539 } 16540 16541 /** 16542 * Set the over-scroll mode for this view. Valid over-scroll modes are 16543 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16544 * (allow over-scrolling only if the view content is larger than the container), 16545 * or {@link #OVER_SCROLL_NEVER}. 16546 * 16547 * Setting the over-scroll mode of a view will have an effect only if the 16548 * view is capable of scrolling. 16549 * 16550 * @param overScrollMode The new over-scroll mode for this view. 16551 */ 16552 public void setOverScrollMode(int overScrollMode) { 16553 if (overScrollMode != OVER_SCROLL_ALWAYS && 16554 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 16555 overScrollMode != OVER_SCROLL_NEVER) { 16556 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 16557 } 16558 mOverScrollMode = overScrollMode; 16559 } 16560 16561 /** 16562 * Gets a scale factor that determines the distance the view should scroll 16563 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 16564 * @return The vertical scroll scale factor. 16565 * @hide 16566 */ 16567 protected float getVerticalScrollFactor() { 16568 if (mVerticalScrollFactor == 0) { 16569 TypedValue outValue = new TypedValue(); 16570 if (!mContext.getTheme().resolveAttribute( 16571 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 16572 throw new IllegalStateException( 16573 "Expected theme to define listPreferredItemHeight."); 16574 } 16575 mVerticalScrollFactor = outValue.getDimension( 16576 mContext.getResources().getDisplayMetrics()); 16577 } 16578 return mVerticalScrollFactor; 16579 } 16580 16581 /** 16582 * Gets a scale factor that determines the distance the view should scroll 16583 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 16584 * @return The horizontal scroll scale factor. 16585 * @hide 16586 */ 16587 protected float getHorizontalScrollFactor() { 16588 // TODO: Should use something else. 16589 return getVerticalScrollFactor(); 16590 } 16591 16592 /** 16593 * Return the value specifying the text direction or policy that was set with 16594 * {@link #setTextDirection(int)}. 16595 * 16596 * @return the defined text direction. It can be one of: 16597 * 16598 * {@link #TEXT_DIRECTION_INHERIT}, 16599 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16600 * {@link #TEXT_DIRECTION_ANY_RTL}, 16601 * {@link #TEXT_DIRECTION_LTR}, 16602 * {@link #TEXT_DIRECTION_RTL}, 16603 * {@link #TEXT_DIRECTION_LOCALE} 16604 * 16605 * @hide 16606 */ 16607 @ViewDebug.ExportedProperty(category = "text", mapping = { 16608 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 16609 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 16610 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 16611 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 16612 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 16613 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 16614 }) 16615 public int getRawTextDirection() { 16616 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 16617 } 16618 16619 /** 16620 * Set the text direction. 16621 * 16622 * @param textDirection the direction to set. Should be one of: 16623 * 16624 * {@link #TEXT_DIRECTION_INHERIT}, 16625 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16626 * {@link #TEXT_DIRECTION_ANY_RTL}, 16627 * {@link #TEXT_DIRECTION_LTR}, 16628 * {@link #TEXT_DIRECTION_RTL}, 16629 * {@link #TEXT_DIRECTION_LOCALE} 16630 * 16631 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 16632 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 16633 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 16634 */ 16635 public void setTextDirection(int textDirection) { 16636 if (getRawTextDirection() != textDirection) { 16637 // Reset the current text direction and the resolved one 16638 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 16639 resetResolvedTextDirection(); 16640 // Set the new text direction 16641 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 16642 // Do resolution 16643 resolveTextDirection(); 16644 // Notify change 16645 onRtlPropertiesChanged(getLayoutDirection()); 16646 // Refresh 16647 requestLayout(); 16648 invalidate(true); 16649 } 16650 } 16651 16652 /** 16653 * Return the resolved text direction. 16654 * 16655 * @return the resolved text direction. Returns one of: 16656 * 16657 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16658 * {@link #TEXT_DIRECTION_ANY_RTL}, 16659 * {@link #TEXT_DIRECTION_LTR}, 16660 * {@link #TEXT_DIRECTION_RTL}, 16661 * {@link #TEXT_DIRECTION_LOCALE} 16662 */ 16663 public int getTextDirection() { 16664 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 16665 } 16666 16667 /** 16668 * Resolve the text direction. 16669 * 16670 * @return true if resolution has been done, false otherwise. 16671 * 16672 * @hide 16673 */ 16674 public boolean resolveTextDirection() { 16675 // Reset any previous text direction resolution 16676 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 16677 16678 if (hasRtlSupport()) { 16679 // Set resolved text direction flag depending on text direction flag 16680 final int textDirection = getRawTextDirection(); 16681 switch(textDirection) { 16682 case TEXT_DIRECTION_INHERIT: 16683 if (!canResolveTextDirection()) { 16684 // We cannot do the resolution if there is no parent, so use the default one 16685 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16686 // Resolution will need to happen again later 16687 return false; 16688 } 16689 16690 View parent = ((View) mParent); 16691 // Parent has not yet resolved, so we still return the default 16692 if (!parent.isTextDirectionResolved()) { 16693 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16694 // Resolution will need to happen again later 16695 return false; 16696 } 16697 16698 // Set current resolved direction to the same value as the parent's one 16699 final int parentResolvedDirection = parent.getTextDirection(); 16700 switch (parentResolvedDirection) { 16701 case TEXT_DIRECTION_FIRST_STRONG: 16702 case TEXT_DIRECTION_ANY_RTL: 16703 case TEXT_DIRECTION_LTR: 16704 case TEXT_DIRECTION_RTL: 16705 case TEXT_DIRECTION_LOCALE: 16706 mPrivateFlags2 |= 16707 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 16708 break; 16709 default: 16710 // Default resolved direction is "first strong" heuristic 16711 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16712 } 16713 break; 16714 case TEXT_DIRECTION_FIRST_STRONG: 16715 case TEXT_DIRECTION_ANY_RTL: 16716 case TEXT_DIRECTION_LTR: 16717 case TEXT_DIRECTION_RTL: 16718 case TEXT_DIRECTION_LOCALE: 16719 // Resolved direction is the same as text direction 16720 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 16721 break; 16722 default: 16723 // Default resolved direction is "first strong" heuristic 16724 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16725 } 16726 } else { 16727 // Default resolved direction is "first strong" heuristic 16728 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16729 } 16730 16731 // Set to resolved 16732 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 16733 return true; 16734 } 16735 16736 /** 16737 * Check if text direction resolution can be done. 16738 * 16739 * @return true if text direction resolution can be done otherwise return false. 16740 */ 16741 private boolean canResolveTextDirection() { 16742 switch (getRawTextDirection()) { 16743 case TEXT_DIRECTION_INHERIT: 16744 return (mParent != null) && (mParent instanceof View) && 16745 ((View) mParent).canResolveTextDirection(); 16746 default: 16747 return true; 16748 } 16749 } 16750 16751 /** 16752 * Reset resolved text direction. Text direction will be resolved during a call to 16753 * {@link #onMeasure(int, int)}. 16754 * 16755 * @hide 16756 */ 16757 public void resetResolvedTextDirection() { 16758 // Reset any previous text direction resolution 16759 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 16760 // Set to default value 16761 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16762 } 16763 16764 /** 16765 * @return true if text direction is inherited. 16766 * 16767 * @hide 16768 */ 16769 public boolean isTextDirectionInherited() { 16770 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 16771 } 16772 16773 /** 16774 * @return true if text direction is resolved. 16775 */ 16776 private boolean isTextDirectionResolved() { 16777 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 16778 } 16779 16780 /** 16781 * Return the value specifying the text alignment or policy that was set with 16782 * {@link #setTextAlignment(int)}. 16783 * 16784 * @return the defined text alignment. It can be one of: 16785 * 16786 * {@link #TEXT_ALIGNMENT_INHERIT}, 16787 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16788 * {@link #TEXT_ALIGNMENT_CENTER}, 16789 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16790 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16791 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16792 * {@link #TEXT_ALIGNMENT_VIEW_END} 16793 * 16794 * @hide 16795 */ 16796 @ViewDebug.ExportedProperty(category = "text", mapping = { 16797 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 16798 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 16799 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 16800 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 16801 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 16802 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 16803 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 16804 }) 16805 public int getRawTextAlignment() { 16806 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 16807 } 16808 16809 /** 16810 * Set the text alignment. 16811 * 16812 * @param textAlignment The text alignment to set. Should be one of 16813 * 16814 * {@link #TEXT_ALIGNMENT_INHERIT}, 16815 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16816 * {@link #TEXT_ALIGNMENT_CENTER}, 16817 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16818 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16819 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16820 * {@link #TEXT_ALIGNMENT_VIEW_END} 16821 * 16822 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 16823 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 16824 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 16825 * 16826 * @attr ref android.R.styleable#View_textAlignment 16827 */ 16828 public void setTextAlignment(int textAlignment) { 16829 if (textAlignment != getRawTextAlignment()) { 16830 // Reset the current and resolved text alignment 16831 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 16832 resetResolvedTextAlignment(); 16833 // Set the new text alignment 16834 mPrivateFlags2 |= 16835 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 16836 // Do resolution 16837 resolveTextAlignment(); 16838 // Notify change 16839 onRtlPropertiesChanged(getLayoutDirection()); 16840 // Refresh 16841 requestLayout(); 16842 invalidate(true); 16843 } 16844 } 16845 16846 /** 16847 * Return the resolved text alignment. 16848 * 16849 * @return the resolved text alignment. Returns one of: 16850 * 16851 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16852 * {@link #TEXT_ALIGNMENT_CENTER}, 16853 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16854 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16855 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16856 * {@link #TEXT_ALIGNMENT_VIEW_END} 16857 */ 16858 @ViewDebug.ExportedProperty(category = "text", mapping = { 16859 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 16860 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 16861 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 16862 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 16863 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 16864 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 16865 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 16866 }) 16867 public int getTextAlignment() { 16868 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 16869 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 16870 } 16871 16872 /** 16873 * Resolve the text alignment. 16874 * 16875 * @return true if resolution has been done, false otherwise. 16876 * 16877 * @hide 16878 */ 16879 public boolean resolveTextAlignment() { 16880 // Reset any previous text alignment resolution 16881 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 16882 16883 if (hasRtlSupport()) { 16884 // Set resolved text alignment flag depending on text alignment flag 16885 final int textAlignment = getRawTextAlignment(); 16886 switch (textAlignment) { 16887 case TEXT_ALIGNMENT_INHERIT: 16888 // Check if we can resolve the text alignment 16889 if (!canResolveTextAlignment()) { 16890 // We cannot do the resolution if there is no parent so use the default 16891 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16892 // Resolution will need to happen again later 16893 return false; 16894 } 16895 View parent = (View) mParent; 16896 16897 // Parent has not yet resolved, so we still return the default 16898 if (!parent.isTextAlignmentResolved()) { 16899 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16900 // Resolution will need to happen again later 16901 return false; 16902 } 16903 16904 final int parentResolvedTextAlignment = parent.getTextAlignment(); 16905 switch (parentResolvedTextAlignment) { 16906 case TEXT_ALIGNMENT_GRAVITY: 16907 case TEXT_ALIGNMENT_TEXT_START: 16908 case TEXT_ALIGNMENT_TEXT_END: 16909 case TEXT_ALIGNMENT_CENTER: 16910 case TEXT_ALIGNMENT_VIEW_START: 16911 case TEXT_ALIGNMENT_VIEW_END: 16912 // Resolved text alignment is the same as the parent resolved 16913 // text alignment 16914 mPrivateFlags2 |= 16915 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 16916 break; 16917 default: 16918 // Use default resolved text alignment 16919 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16920 } 16921 break; 16922 case TEXT_ALIGNMENT_GRAVITY: 16923 case TEXT_ALIGNMENT_TEXT_START: 16924 case TEXT_ALIGNMENT_TEXT_END: 16925 case TEXT_ALIGNMENT_CENTER: 16926 case TEXT_ALIGNMENT_VIEW_START: 16927 case TEXT_ALIGNMENT_VIEW_END: 16928 // Resolved text alignment is the same as text alignment 16929 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 16930 break; 16931 default: 16932 // Use default resolved text alignment 16933 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16934 } 16935 } else { 16936 // Use default resolved text alignment 16937 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16938 } 16939 16940 // Set the resolved 16941 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 16942 return true; 16943 } 16944 16945 /** 16946 * Check if text alignment resolution can be done. 16947 * 16948 * @return true if text alignment resolution can be done otherwise return false. 16949 */ 16950 private boolean canResolveTextAlignment() { 16951 switch (getRawTextAlignment()) { 16952 case TEXT_DIRECTION_INHERIT: 16953 return (mParent != null) && (mParent instanceof View) && 16954 ((View) mParent).canResolveTextAlignment(); 16955 default: 16956 return true; 16957 } 16958 } 16959 16960 /** 16961 * Reset resolved text alignment. Text alignment will be resolved during a call to 16962 * {@link #onMeasure(int, int)}. 16963 * 16964 * @hide 16965 */ 16966 public void resetResolvedTextAlignment() { 16967 // Reset any previous text alignment resolution 16968 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 16969 // Set to default 16970 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16971 } 16972 16973 /** 16974 * @return true if text alignment is inherited. 16975 * 16976 * @hide 16977 */ 16978 public boolean isTextAlignmentInherited() { 16979 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 16980 } 16981 16982 /** 16983 * @return true if text alignment is resolved. 16984 */ 16985 private boolean isTextAlignmentResolved() { 16986 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 16987 } 16988 16989 /** 16990 * Generate a value suitable for use in {@link #setId(int)}. 16991 * This value will not collide with ID values generated at build time by aapt for R.id. 16992 * 16993 * @return a generated ID value 16994 */ 16995 public static int generateViewId() { 16996 for (;;) { 16997 final int result = sNextGeneratedId.get(); 16998 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 16999 int newValue = result + 1; 17000 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 17001 if (sNextGeneratedId.compareAndSet(result, newValue)) { 17002 return result; 17003 } 17004 } 17005 } 17006 17007 // 17008 // Properties 17009 // 17010 /** 17011 * A Property wrapper around the <code>alpha</code> functionality handled by the 17012 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 17013 */ 17014 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 17015 @Override 17016 public void setValue(View object, float value) { 17017 object.setAlpha(value); 17018 } 17019 17020 @Override 17021 public Float get(View object) { 17022 return object.getAlpha(); 17023 } 17024 }; 17025 17026 /** 17027 * A Property wrapper around the <code>translationX</code> functionality handled by the 17028 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 17029 */ 17030 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 17031 @Override 17032 public void setValue(View object, float value) { 17033 object.setTranslationX(value); 17034 } 17035 17036 @Override 17037 public Float get(View object) { 17038 return object.getTranslationX(); 17039 } 17040 }; 17041 17042 /** 17043 * A Property wrapper around the <code>translationY</code> functionality handled by the 17044 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 17045 */ 17046 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 17047 @Override 17048 public void setValue(View object, float value) { 17049 object.setTranslationY(value); 17050 } 17051 17052 @Override 17053 public Float get(View object) { 17054 return object.getTranslationY(); 17055 } 17056 }; 17057 17058 /** 17059 * A Property wrapper around the <code>x</code> functionality handled by the 17060 * {@link View#setX(float)} and {@link View#getX()} methods. 17061 */ 17062 public static final Property<View, Float> X = new FloatProperty<View>("x") { 17063 @Override 17064 public void setValue(View object, float value) { 17065 object.setX(value); 17066 } 17067 17068 @Override 17069 public Float get(View object) { 17070 return object.getX(); 17071 } 17072 }; 17073 17074 /** 17075 * A Property wrapper around the <code>y</code> functionality handled by the 17076 * {@link View#setY(float)} and {@link View#getY()} methods. 17077 */ 17078 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 17079 @Override 17080 public void setValue(View object, float value) { 17081 object.setY(value); 17082 } 17083 17084 @Override 17085 public Float get(View object) { 17086 return object.getY(); 17087 } 17088 }; 17089 17090 /** 17091 * A Property wrapper around the <code>rotation</code> functionality handled by the 17092 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 17093 */ 17094 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 17095 @Override 17096 public void setValue(View object, float value) { 17097 object.setRotation(value); 17098 } 17099 17100 @Override 17101 public Float get(View object) { 17102 return object.getRotation(); 17103 } 17104 }; 17105 17106 /** 17107 * A Property wrapper around the <code>rotationX</code> functionality handled by the 17108 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 17109 */ 17110 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 17111 @Override 17112 public void setValue(View object, float value) { 17113 object.setRotationX(value); 17114 } 17115 17116 @Override 17117 public Float get(View object) { 17118 return object.getRotationX(); 17119 } 17120 }; 17121 17122 /** 17123 * A Property wrapper around the <code>rotationY</code> functionality handled by the 17124 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 17125 */ 17126 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 17127 @Override 17128 public void setValue(View object, float value) { 17129 object.setRotationY(value); 17130 } 17131 17132 @Override 17133 public Float get(View object) { 17134 return object.getRotationY(); 17135 } 17136 }; 17137 17138 /** 17139 * A Property wrapper around the <code>scaleX</code> functionality handled by the 17140 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 17141 */ 17142 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 17143 @Override 17144 public void setValue(View object, float value) { 17145 object.setScaleX(value); 17146 } 17147 17148 @Override 17149 public Float get(View object) { 17150 return object.getScaleX(); 17151 } 17152 }; 17153 17154 /** 17155 * A Property wrapper around the <code>scaleY</code> functionality handled by the 17156 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 17157 */ 17158 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 17159 @Override 17160 public void setValue(View object, float value) { 17161 object.setScaleY(value); 17162 } 17163 17164 @Override 17165 public Float get(View object) { 17166 return object.getScaleY(); 17167 } 17168 }; 17169 17170 /** 17171 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 17172 * Each MeasureSpec represents a requirement for either the width or the height. 17173 * A MeasureSpec is comprised of a size and a mode. There are three possible 17174 * modes: 17175 * <dl> 17176 * <dt>UNSPECIFIED</dt> 17177 * <dd> 17178 * The parent has not imposed any constraint on the child. It can be whatever size 17179 * it wants. 17180 * </dd> 17181 * 17182 * <dt>EXACTLY</dt> 17183 * <dd> 17184 * The parent has determined an exact size for the child. The child is going to be 17185 * given those bounds regardless of how big it wants to be. 17186 * </dd> 17187 * 17188 * <dt>AT_MOST</dt> 17189 * <dd> 17190 * The child can be as large as it wants up to the specified size. 17191 * </dd> 17192 * </dl> 17193 * 17194 * MeasureSpecs are implemented as ints to reduce object allocation. This class 17195 * is provided to pack and unpack the <size, mode> tuple into the int. 17196 */ 17197 public static class MeasureSpec { 17198 private static final int MODE_SHIFT = 30; 17199 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 17200 17201 /** 17202 * Measure specification mode: The parent has not imposed any constraint 17203 * on the child. It can be whatever size it wants. 17204 */ 17205 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 17206 17207 /** 17208 * Measure specification mode: The parent has determined an exact size 17209 * for the child. The child is going to be given those bounds regardless 17210 * of how big it wants to be. 17211 */ 17212 public static final int EXACTLY = 1 << MODE_SHIFT; 17213 17214 /** 17215 * Measure specification mode: The child can be as large as it wants up 17216 * to the specified size. 17217 */ 17218 public static final int AT_MOST = 2 << MODE_SHIFT; 17219 17220 /** 17221 * Creates a measure specification based on the supplied size and mode. 17222 * 17223 * The mode must always be one of the following: 17224 * <ul> 17225 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 17226 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 17227 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 17228 * </ul> 17229 * 17230 * @param size the size of the measure specification 17231 * @param mode the mode of the measure specification 17232 * @return the measure specification based on size and mode 17233 */ 17234 public static int makeMeasureSpec(int size, int mode) { 17235 return size + mode; 17236 } 17237 17238 /** 17239 * Extracts the mode from the supplied measure specification. 17240 * 17241 * @param measureSpec the measure specification to extract the mode from 17242 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 17243 * {@link android.view.View.MeasureSpec#AT_MOST} or 17244 * {@link android.view.View.MeasureSpec#EXACTLY} 17245 */ 17246 public static int getMode(int measureSpec) { 17247 return (measureSpec & MODE_MASK); 17248 } 17249 17250 /** 17251 * Extracts the size from the supplied measure specification. 17252 * 17253 * @param measureSpec the measure specification to extract the size from 17254 * @return the size in pixels defined in the supplied measure specification 17255 */ 17256 public static int getSize(int measureSpec) { 17257 return (measureSpec & ~MODE_MASK); 17258 } 17259 17260 /** 17261 * Returns a String representation of the specified measure 17262 * specification. 17263 * 17264 * @param measureSpec the measure specification to convert to a String 17265 * @return a String with the following format: "MeasureSpec: MODE SIZE" 17266 */ 17267 public static String toString(int measureSpec) { 17268 int mode = getMode(measureSpec); 17269 int size = getSize(measureSpec); 17270 17271 StringBuilder sb = new StringBuilder("MeasureSpec: "); 17272 17273 if (mode == UNSPECIFIED) 17274 sb.append("UNSPECIFIED "); 17275 else if (mode == EXACTLY) 17276 sb.append("EXACTLY "); 17277 else if (mode == AT_MOST) 17278 sb.append("AT_MOST "); 17279 else 17280 sb.append(mode).append(" "); 17281 17282 sb.append(size); 17283 return sb.toString(); 17284 } 17285 } 17286 17287 class CheckForLongPress implements Runnable { 17288 17289 private int mOriginalWindowAttachCount; 17290 17291 public void run() { 17292 if (isPressed() && (mParent != null) 17293 && mOriginalWindowAttachCount == mWindowAttachCount) { 17294 if (performLongClick()) { 17295 mHasPerformedLongPress = true; 17296 } 17297 } 17298 } 17299 17300 public void rememberWindowAttachCount() { 17301 mOriginalWindowAttachCount = mWindowAttachCount; 17302 } 17303 } 17304 17305 private final class CheckForTap implements Runnable { 17306 public void run() { 17307 mPrivateFlags &= ~PFLAG_PREPRESSED; 17308 setPressed(true); 17309 checkForLongClick(ViewConfiguration.getTapTimeout()); 17310 } 17311 } 17312 17313 private final class PerformClick implements Runnable { 17314 public void run() { 17315 performClick(); 17316 } 17317 } 17318 17319 /** @hide */ 17320 public void hackTurnOffWindowResizeAnim(boolean off) { 17321 mAttachInfo.mTurnOffWindowResizeAnim = off; 17322 } 17323 17324 /** 17325 * This method returns a ViewPropertyAnimator object, which can be used to animate 17326 * specific properties on this View. 17327 * 17328 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 17329 */ 17330 public ViewPropertyAnimator animate() { 17331 if (mAnimator == null) { 17332 mAnimator = new ViewPropertyAnimator(this); 17333 } 17334 return mAnimator; 17335 } 17336 17337 /** 17338 * Interface definition for a callback to be invoked when a hardware key event is 17339 * dispatched to this view. The callback will be invoked before the key event is 17340 * given to the view. This is only useful for hardware keyboards; a software input 17341 * method has no obligation to trigger this listener. 17342 */ 17343 public interface OnKeyListener { 17344 /** 17345 * Called when a hardware key is dispatched to a view. This allows listeners to 17346 * get a chance to respond before the target view. 17347 * <p>Key presses in software keyboards will generally NOT trigger this method, 17348 * although some may elect to do so in some situations. Do not assume a 17349 * software input method has to be key-based; even if it is, it may use key presses 17350 * in a different way than you expect, so there is no way to reliably catch soft 17351 * input key presses. 17352 * 17353 * @param v The view the key has been dispatched to. 17354 * @param keyCode The code for the physical key that was pressed 17355 * @param event The KeyEvent object containing full information about 17356 * the event. 17357 * @return True if the listener has consumed the event, false otherwise. 17358 */ 17359 boolean onKey(View v, int keyCode, KeyEvent event); 17360 } 17361 17362 /** 17363 * Interface definition for a callback to be invoked when a touch event is 17364 * dispatched to this view. The callback will be invoked before the touch 17365 * event is given to the view. 17366 */ 17367 public interface OnTouchListener { 17368 /** 17369 * Called when a touch event is dispatched to a view. This allows listeners to 17370 * get a chance to respond before the target view. 17371 * 17372 * @param v The view the touch event has been dispatched to. 17373 * @param event The MotionEvent object containing full information about 17374 * the event. 17375 * @return True if the listener has consumed the event, false otherwise. 17376 */ 17377 boolean onTouch(View v, MotionEvent event); 17378 } 17379 17380 /** 17381 * Interface definition for a callback to be invoked when a hover event is 17382 * dispatched to this view. The callback will be invoked before the hover 17383 * event is given to the view. 17384 */ 17385 public interface OnHoverListener { 17386 /** 17387 * Called when a hover event is dispatched to a view. This allows listeners to 17388 * get a chance to respond before the target view. 17389 * 17390 * @param v The view the hover event has been dispatched to. 17391 * @param event The MotionEvent object containing full information about 17392 * the event. 17393 * @return True if the listener has consumed the event, false otherwise. 17394 */ 17395 boolean onHover(View v, MotionEvent event); 17396 } 17397 17398 /** 17399 * Interface definition for a callback to be invoked when a generic motion event is 17400 * dispatched to this view. The callback will be invoked before the generic motion 17401 * event is given to the view. 17402 */ 17403 public interface OnGenericMotionListener { 17404 /** 17405 * Called when a generic motion event is dispatched to a view. This allows listeners to 17406 * get a chance to respond before the target view. 17407 * 17408 * @param v The view the generic motion event has been dispatched to. 17409 * @param event The MotionEvent object containing full information about 17410 * the event. 17411 * @return True if the listener has consumed the event, false otherwise. 17412 */ 17413 boolean onGenericMotion(View v, MotionEvent event); 17414 } 17415 17416 /** 17417 * Interface definition for a callback to be invoked when a view has been clicked and held. 17418 */ 17419 public interface OnLongClickListener { 17420 /** 17421 * Called when a view has been clicked and held. 17422 * 17423 * @param v The view that was clicked and held. 17424 * 17425 * @return true if the callback consumed the long click, false otherwise. 17426 */ 17427 boolean onLongClick(View v); 17428 } 17429 17430 /** 17431 * Interface definition for a callback to be invoked when a drag is being dispatched 17432 * to this view. The callback will be invoked before the hosting view's own 17433 * onDrag(event) method. If the listener wants to fall back to the hosting view's 17434 * onDrag(event) behavior, it should return 'false' from this callback. 17435 * 17436 * <div class="special reference"> 17437 * <h3>Developer Guides</h3> 17438 * <p>For a guide to implementing drag and drop features, read the 17439 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17440 * </div> 17441 */ 17442 public interface OnDragListener { 17443 /** 17444 * Called when a drag event is dispatched to a view. This allows listeners 17445 * to get a chance to override base View behavior. 17446 * 17447 * @param v The View that received the drag event. 17448 * @param event The {@link android.view.DragEvent} object for the drag event. 17449 * @return {@code true} if the drag event was handled successfully, or {@code false} 17450 * if the drag event was not handled. Note that {@code false} will trigger the View 17451 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 17452 */ 17453 boolean onDrag(View v, DragEvent event); 17454 } 17455 17456 /** 17457 * Interface definition for a callback to be invoked when the focus state of 17458 * a view changed. 17459 */ 17460 public interface OnFocusChangeListener { 17461 /** 17462 * Called when the focus state of a view has changed. 17463 * 17464 * @param v The view whose state has changed. 17465 * @param hasFocus The new focus state of v. 17466 */ 17467 void onFocusChange(View v, boolean hasFocus); 17468 } 17469 17470 /** 17471 * Interface definition for a callback to be invoked when a view is clicked. 17472 */ 17473 public interface OnClickListener { 17474 /** 17475 * Called when a view has been clicked. 17476 * 17477 * @param v The view that was clicked. 17478 */ 17479 void onClick(View v); 17480 } 17481 17482 /** 17483 * Interface definition for a callback to be invoked when the context menu 17484 * for this view is being built. 17485 */ 17486 public interface OnCreateContextMenuListener { 17487 /** 17488 * Called when the context menu for this view is being built. It is not 17489 * safe to hold onto the menu after this method returns. 17490 * 17491 * @param menu The context menu that is being built 17492 * @param v The view for which the context menu is being built 17493 * @param menuInfo Extra information about the item for which the 17494 * context menu should be shown. This information will vary 17495 * depending on the class of v. 17496 */ 17497 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 17498 } 17499 17500 /** 17501 * Interface definition for a callback to be invoked when the status bar changes 17502 * visibility. This reports <strong>global</strong> changes to the system UI 17503 * state, not what the application is requesting. 17504 * 17505 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 17506 */ 17507 public interface OnSystemUiVisibilityChangeListener { 17508 /** 17509 * Called when the status bar changes visibility because of a call to 17510 * {@link View#setSystemUiVisibility(int)}. 17511 * 17512 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17513 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 17514 * This tells you the <strong>global</strong> state of these UI visibility 17515 * flags, not what your app is currently applying. 17516 */ 17517 public void onSystemUiVisibilityChange(int visibility); 17518 } 17519 17520 /** 17521 * Interface definition for a callback to be invoked when this view is attached 17522 * or detached from its window. 17523 */ 17524 public interface OnAttachStateChangeListener { 17525 /** 17526 * Called when the view is attached to a window. 17527 * @param v The view that was attached 17528 */ 17529 public void onViewAttachedToWindow(View v); 17530 /** 17531 * Called when the view is detached from a window. 17532 * @param v The view that was detached 17533 */ 17534 public void onViewDetachedFromWindow(View v); 17535 } 17536 17537 private final class UnsetPressedState implements Runnable { 17538 public void run() { 17539 setPressed(false); 17540 } 17541 } 17542 17543 /** 17544 * Base class for derived classes that want to save and restore their own 17545 * state in {@link android.view.View#onSaveInstanceState()}. 17546 */ 17547 public static class BaseSavedState extends AbsSavedState { 17548 /** 17549 * Constructor used when reading from a parcel. Reads the state of the superclass. 17550 * 17551 * @param source 17552 */ 17553 public BaseSavedState(Parcel source) { 17554 super(source); 17555 } 17556 17557 /** 17558 * Constructor called by derived classes when creating their SavedState objects 17559 * 17560 * @param superState The state of the superclass of this view 17561 */ 17562 public BaseSavedState(Parcelable superState) { 17563 super(superState); 17564 } 17565 17566 public static final Parcelable.Creator<BaseSavedState> CREATOR = 17567 new Parcelable.Creator<BaseSavedState>() { 17568 public BaseSavedState createFromParcel(Parcel in) { 17569 return new BaseSavedState(in); 17570 } 17571 17572 public BaseSavedState[] newArray(int size) { 17573 return new BaseSavedState[size]; 17574 } 17575 }; 17576 } 17577 17578 /** 17579 * A set of information given to a view when it is attached to its parent 17580 * window. 17581 */ 17582 static class AttachInfo { 17583 interface Callbacks { 17584 void playSoundEffect(int effectId); 17585 boolean performHapticFeedback(int effectId, boolean always); 17586 } 17587 17588 /** 17589 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 17590 * to a Handler. This class contains the target (View) to invalidate and 17591 * the coordinates of the dirty rectangle. 17592 * 17593 * For performance purposes, this class also implements a pool of up to 17594 * POOL_LIMIT objects that get reused. This reduces memory allocations 17595 * whenever possible. 17596 */ 17597 static class InvalidateInfo implements Poolable<InvalidateInfo> { 17598 private static final int POOL_LIMIT = 10; 17599 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 17600 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 17601 public InvalidateInfo newInstance() { 17602 return new InvalidateInfo(); 17603 } 17604 17605 public void onAcquired(InvalidateInfo element) { 17606 } 17607 17608 public void onReleased(InvalidateInfo element) { 17609 element.target = null; 17610 } 17611 }, POOL_LIMIT) 17612 ); 17613 17614 private InvalidateInfo mNext; 17615 private boolean mIsPooled; 17616 17617 View target; 17618 17619 int left; 17620 int top; 17621 int right; 17622 int bottom; 17623 17624 public void setNextPoolable(InvalidateInfo element) { 17625 mNext = element; 17626 } 17627 17628 public InvalidateInfo getNextPoolable() { 17629 return mNext; 17630 } 17631 17632 static InvalidateInfo acquire() { 17633 return sPool.acquire(); 17634 } 17635 17636 void release() { 17637 sPool.release(this); 17638 } 17639 17640 public boolean isPooled() { 17641 return mIsPooled; 17642 } 17643 17644 public void setPooled(boolean isPooled) { 17645 mIsPooled = isPooled; 17646 } 17647 } 17648 17649 final IWindowSession mSession; 17650 17651 final IWindow mWindow; 17652 17653 final IBinder mWindowToken; 17654 17655 final Display mDisplay; 17656 17657 final Callbacks mRootCallbacks; 17658 17659 HardwareCanvas mHardwareCanvas; 17660 17661 /** 17662 * The top view of the hierarchy. 17663 */ 17664 View mRootView; 17665 17666 IBinder mPanelParentWindowToken; 17667 Surface mSurface; 17668 17669 boolean mHardwareAccelerated; 17670 boolean mHardwareAccelerationRequested; 17671 HardwareRenderer mHardwareRenderer; 17672 17673 boolean mScreenOn; 17674 17675 /** 17676 * Scale factor used by the compatibility mode 17677 */ 17678 float mApplicationScale; 17679 17680 /** 17681 * Indicates whether the application is in compatibility mode 17682 */ 17683 boolean mScalingRequired; 17684 17685 /** 17686 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 17687 */ 17688 boolean mTurnOffWindowResizeAnim; 17689 17690 /** 17691 * Left position of this view's window 17692 */ 17693 int mWindowLeft; 17694 17695 /** 17696 * Top position of this view's window 17697 */ 17698 int mWindowTop; 17699 17700 /** 17701 * Indicates whether views need to use 32-bit drawing caches 17702 */ 17703 boolean mUse32BitDrawingCache; 17704 17705 /** 17706 * For windows that are full-screen but using insets to layout inside 17707 * of the screen decorations, these are the current insets for the 17708 * content of the window. 17709 */ 17710 final Rect mContentInsets = new Rect(); 17711 17712 /** 17713 * For windows that are full-screen but using insets to layout inside 17714 * of the screen decorations, these are the current insets for the 17715 * actual visible parts of the window. 17716 */ 17717 final Rect mVisibleInsets = new Rect(); 17718 17719 /** 17720 * The internal insets given by this window. This value is 17721 * supplied by the client (through 17722 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 17723 * be given to the window manager when changed to be used in laying 17724 * out windows behind it. 17725 */ 17726 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 17727 = new ViewTreeObserver.InternalInsetsInfo(); 17728 17729 /** 17730 * All views in the window's hierarchy that serve as scroll containers, 17731 * used to determine if the window can be resized or must be panned 17732 * to adjust for a soft input area. 17733 */ 17734 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 17735 17736 final KeyEvent.DispatcherState mKeyDispatchState 17737 = new KeyEvent.DispatcherState(); 17738 17739 /** 17740 * Indicates whether the view's window currently has the focus. 17741 */ 17742 boolean mHasWindowFocus; 17743 17744 /** 17745 * The current visibility of the window. 17746 */ 17747 int mWindowVisibility; 17748 17749 /** 17750 * Indicates the time at which drawing started to occur. 17751 */ 17752 long mDrawingTime; 17753 17754 /** 17755 * Indicates whether or not ignoring the DIRTY_MASK flags. 17756 */ 17757 boolean mIgnoreDirtyState; 17758 17759 /** 17760 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 17761 * to avoid clearing that flag prematurely. 17762 */ 17763 boolean mSetIgnoreDirtyState = false; 17764 17765 /** 17766 * Indicates whether the view's window is currently in touch mode. 17767 */ 17768 boolean mInTouchMode; 17769 17770 /** 17771 * Indicates that ViewAncestor should trigger a global layout change 17772 * the next time it performs a traversal 17773 */ 17774 boolean mRecomputeGlobalAttributes; 17775 17776 /** 17777 * Always report new attributes at next traversal. 17778 */ 17779 boolean mForceReportNewAttributes; 17780 17781 /** 17782 * Set during a traveral if any views want to keep the screen on. 17783 */ 17784 boolean mKeepScreenOn; 17785 17786 /** 17787 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 17788 */ 17789 int mSystemUiVisibility; 17790 17791 /** 17792 * Hack to force certain system UI visibility flags to be cleared. 17793 */ 17794 int mDisabledSystemUiVisibility; 17795 17796 /** 17797 * Last global system UI visibility reported by the window manager. 17798 */ 17799 int mGlobalSystemUiVisibility; 17800 17801 /** 17802 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 17803 * attached. 17804 */ 17805 boolean mHasSystemUiListeners; 17806 17807 /** 17808 * Set if the visibility of any views has changed. 17809 */ 17810 boolean mViewVisibilityChanged; 17811 17812 /** 17813 * Set to true if a view has been scrolled. 17814 */ 17815 boolean mViewScrollChanged; 17816 17817 /** 17818 * Global to the view hierarchy used as a temporary for dealing with 17819 * x/y points in the transparent region computations. 17820 */ 17821 final int[] mTransparentLocation = new int[2]; 17822 17823 /** 17824 * Global to the view hierarchy used as a temporary for dealing with 17825 * x/y points in the ViewGroup.invalidateChild implementation. 17826 */ 17827 final int[] mInvalidateChildLocation = new int[2]; 17828 17829 17830 /** 17831 * Global to the view hierarchy used as a temporary for dealing with 17832 * x/y location when view is transformed. 17833 */ 17834 final float[] mTmpTransformLocation = new float[2]; 17835 17836 /** 17837 * The view tree observer used to dispatch global events like 17838 * layout, pre-draw, touch mode change, etc. 17839 */ 17840 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 17841 17842 /** 17843 * A Canvas used by the view hierarchy to perform bitmap caching. 17844 */ 17845 Canvas mCanvas; 17846 17847 /** 17848 * The view root impl. 17849 */ 17850 final ViewRootImpl mViewRootImpl; 17851 17852 /** 17853 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 17854 * handler can be used to pump events in the UI events queue. 17855 */ 17856 final Handler mHandler; 17857 17858 /** 17859 * Temporary for use in computing invalidate rectangles while 17860 * calling up the hierarchy. 17861 */ 17862 final Rect mTmpInvalRect = new Rect(); 17863 17864 /** 17865 * Temporary for use in computing hit areas with transformed views 17866 */ 17867 final RectF mTmpTransformRect = new RectF(); 17868 17869 /** 17870 * Temporary for use in transforming invalidation rect 17871 */ 17872 final Matrix mTmpMatrix = new Matrix(); 17873 17874 /** 17875 * Temporary for use in transforming invalidation rect 17876 */ 17877 final Transformation mTmpTransformation = new Transformation(); 17878 17879 /** 17880 * Temporary list for use in collecting focusable descendents of a view. 17881 */ 17882 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 17883 17884 /** 17885 * The id of the window for accessibility purposes. 17886 */ 17887 int mAccessibilityWindowId = View.NO_ID; 17888 17889 /** 17890 * Whether to ingore not exposed for accessibility Views when 17891 * reporting the view tree to accessibility services. 17892 */ 17893 boolean mIncludeNotImportantViews; 17894 17895 /** 17896 * The drawable for highlighting accessibility focus. 17897 */ 17898 Drawable mAccessibilityFocusDrawable; 17899 17900 /** 17901 * Show where the margins, bounds and layout bounds are for each view. 17902 */ 17903 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 17904 17905 /** 17906 * Point used to compute visible regions. 17907 */ 17908 final Point mPoint = new Point(); 17909 17910 /** 17911 * Creates a new set of attachment information with the specified 17912 * events handler and thread. 17913 * 17914 * @param handler the events handler the view must use 17915 */ 17916 AttachInfo(IWindowSession session, IWindow window, Display display, 17917 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 17918 mSession = session; 17919 mWindow = window; 17920 mWindowToken = window.asBinder(); 17921 mDisplay = display; 17922 mViewRootImpl = viewRootImpl; 17923 mHandler = handler; 17924 mRootCallbacks = effectPlayer; 17925 } 17926 } 17927 17928 /** 17929 * <p>ScrollabilityCache holds various fields used by a View when scrolling 17930 * is supported. This avoids keeping too many unused fields in most 17931 * instances of View.</p> 17932 */ 17933 private static class ScrollabilityCache implements Runnable { 17934 17935 /** 17936 * Scrollbars are not visible 17937 */ 17938 public static final int OFF = 0; 17939 17940 /** 17941 * Scrollbars are visible 17942 */ 17943 public static final int ON = 1; 17944 17945 /** 17946 * Scrollbars are fading away 17947 */ 17948 public static final int FADING = 2; 17949 17950 public boolean fadeScrollBars; 17951 17952 public int fadingEdgeLength; 17953 public int scrollBarDefaultDelayBeforeFade; 17954 public int scrollBarFadeDuration; 17955 17956 public int scrollBarSize; 17957 public ScrollBarDrawable scrollBar; 17958 public float[] interpolatorValues; 17959 public View host; 17960 17961 public final Paint paint; 17962 public final Matrix matrix; 17963 public Shader shader; 17964 17965 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 17966 17967 private static final float[] OPAQUE = { 255 }; 17968 private static final float[] TRANSPARENT = { 0.0f }; 17969 17970 /** 17971 * When fading should start. This time moves into the future every time 17972 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 17973 */ 17974 public long fadeStartTime; 17975 17976 17977 /** 17978 * The current state of the scrollbars: ON, OFF, or FADING 17979 */ 17980 public int state = OFF; 17981 17982 private int mLastColor; 17983 17984 public ScrollabilityCache(ViewConfiguration configuration, View host) { 17985 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 17986 scrollBarSize = configuration.getScaledScrollBarSize(); 17987 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 17988 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 17989 17990 paint = new Paint(); 17991 matrix = new Matrix(); 17992 // use use a height of 1, and then wack the matrix each time we 17993 // actually use it. 17994 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 17995 paint.setShader(shader); 17996 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 17997 17998 this.host = host; 17999 } 18000 18001 public void setFadeColor(int color) { 18002 if (color != mLastColor) { 18003 mLastColor = color; 18004 18005 if (color != 0) { 18006 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 18007 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 18008 paint.setShader(shader); 18009 // Restore the default transfer mode (src_over) 18010 paint.setXfermode(null); 18011 } else { 18012 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 18013 paint.setShader(shader); 18014 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 18015 } 18016 } 18017 } 18018 18019 public void run() { 18020 long now = AnimationUtils.currentAnimationTimeMillis(); 18021 if (now >= fadeStartTime) { 18022 18023 // the animation fades the scrollbars out by changing 18024 // the opacity (alpha) from fully opaque to fully 18025 // transparent 18026 int nextFrame = (int) now; 18027 int framesCount = 0; 18028 18029 Interpolator interpolator = scrollBarInterpolator; 18030 18031 // Start opaque 18032 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 18033 18034 // End transparent 18035 nextFrame += scrollBarFadeDuration; 18036 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 18037 18038 state = FADING; 18039 18040 // Kick off the fade animation 18041 host.invalidate(true); 18042 } 18043 } 18044 } 18045 18046 /** 18047 * Resuable callback for sending 18048 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 18049 */ 18050 private class SendViewScrolledAccessibilityEvent implements Runnable { 18051 public volatile boolean mIsPending; 18052 18053 public void run() { 18054 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 18055 mIsPending = false; 18056 } 18057 } 18058 18059 /** 18060 * <p> 18061 * This class represents a delegate that can be registered in a {@link View} 18062 * to enhance accessibility support via composition rather via inheritance. 18063 * It is specifically targeted to widget developers that extend basic View 18064 * classes i.e. classes in package android.view, that would like their 18065 * applications to be backwards compatible. 18066 * </p> 18067 * <div class="special reference"> 18068 * <h3>Developer Guides</h3> 18069 * <p>For more information about making applications accessible, read the 18070 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 18071 * developer guide.</p> 18072 * </div> 18073 * <p> 18074 * A scenario in which a developer would like to use an accessibility delegate 18075 * is overriding a method introduced in a later API version then the minimal API 18076 * version supported by the application. For example, the method 18077 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 18078 * in API version 4 when the accessibility APIs were first introduced. If a 18079 * developer would like his application to run on API version 4 devices (assuming 18080 * all other APIs used by the application are version 4 or lower) and take advantage 18081 * of this method, instead of overriding the method which would break the application's 18082 * backwards compatibility, he can override the corresponding method in this 18083 * delegate and register the delegate in the target View if the API version of 18084 * the system is high enough i.e. the API version is same or higher to the API 18085 * version that introduced 18086 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 18087 * </p> 18088 * <p> 18089 * Here is an example implementation: 18090 * </p> 18091 * <code><pre><p> 18092 * if (Build.VERSION.SDK_INT >= 14) { 18093 * // If the API version is equal of higher than the version in 18094 * // which onInitializeAccessibilityNodeInfo was introduced we 18095 * // register a delegate with a customized implementation. 18096 * View view = findViewById(R.id.view_id); 18097 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 18098 * public void onInitializeAccessibilityNodeInfo(View host, 18099 * AccessibilityNodeInfo info) { 18100 * // Let the default implementation populate the info. 18101 * super.onInitializeAccessibilityNodeInfo(host, info); 18102 * // Set some other information. 18103 * info.setEnabled(host.isEnabled()); 18104 * } 18105 * }); 18106 * } 18107 * </code></pre></p> 18108 * <p> 18109 * This delegate contains methods that correspond to the accessibility methods 18110 * in View. If a delegate has been specified the implementation in View hands 18111 * off handling to the corresponding method in this delegate. The default 18112 * implementation the delegate methods behaves exactly as the corresponding 18113 * method in View for the case of no accessibility delegate been set. Hence, 18114 * to customize the behavior of a View method, clients can override only the 18115 * corresponding delegate method without altering the behavior of the rest 18116 * accessibility related methods of the host view. 18117 * </p> 18118 */ 18119 public static class AccessibilityDelegate { 18120 18121 /** 18122 * Sends an accessibility event of the given type. If accessibility is not 18123 * enabled this method has no effect. 18124 * <p> 18125 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 18126 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 18127 * been set. 18128 * </p> 18129 * 18130 * @param host The View hosting the delegate. 18131 * @param eventType The type of the event to send. 18132 * 18133 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 18134 */ 18135 public void sendAccessibilityEvent(View host, int eventType) { 18136 host.sendAccessibilityEventInternal(eventType); 18137 } 18138 18139 /** 18140 * Performs the specified accessibility action on the view. For 18141 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 18142 * <p> 18143 * The default implementation behaves as 18144 * {@link View#performAccessibilityAction(int, Bundle) 18145 * View#performAccessibilityAction(int, Bundle)} for the case of 18146 * no accessibility delegate been set. 18147 * </p> 18148 * 18149 * @param action The action to perform. 18150 * @return Whether the action was performed. 18151 * 18152 * @see View#performAccessibilityAction(int, Bundle) 18153 * View#performAccessibilityAction(int, Bundle) 18154 */ 18155 public boolean performAccessibilityAction(View host, int action, Bundle args) { 18156 return host.performAccessibilityActionInternal(action, args); 18157 } 18158 18159 /** 18160 * Sends an accessibility event. This method behaves exactly as 18161 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 18162 * empty {@link AccessibilityEvent} and does not perform a check whether 18163 * accessibility is enabled. 18164 * <p> 18165 * The default implementation behaves as 18166 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18167 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 18168 * the case of no accessibility delegate been set. 18169 * </p> 18170 * 18171 * @param host The View hosting the delegate. 18172 * @param event The event to send. 18173 * 18174 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18175 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18176 */ 18177 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 18178 host.sendAccessibilityEventUncheckedInternal(event); 18179 } 18180 18181 /** 18182 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 18183 * to its children for adding their text content to the event. 18184 * <p> 18185 * The default implementation behaves as 18186 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18187 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 18188 * the case of no accessibility delegate been set. 18189 * </p> 18190 * 18191 * @param host The View hosting the delegate. 18192 * @param event The event. 18193 * @return True if the event population was completed. 18194 * 18195 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18196 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18197 */ 18198 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18199 return host.dispatchPopulateAccessibilityEventInternal(event); 18200 } 18201 18202 /** 18203 * Gives a chance to the host View to populate the accessibility event with its 18204 * text content. 18205 * <p> 18206 * The default implementation behaves as 18207 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 18208 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 18209 * the case of no accessibility delegate been set. 18210 * </p> 18211 * 18212 * @param host The View hosting the delegate. 18213 * @param event The accessibility event which to populate. 18214 * 18215 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 18216 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 18217 */ 18218 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18219 host.onPopulateAccessibilityEventInternal(event); 18220 } 18221 18222 /** 18223 * Initializes an {@link AccessibilityEvent} with information about the 18224 * the host View which is the event source. 18225 * <p> 18226 * The default implementation behaves as 18227 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 18228 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 18229 * the case of no accessibility delegate been set. 18230 * </p> 18231 * 18232 * @param host The View hosting the delegate. 18233 * @param event The event to initialize. 18234 * 18235 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 18236 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 18237 */ 18238 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 18239 host.onInitializeAccessibilityEventInternal(event); 18240 } 18241 18242 /** 18243 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 18244 * <p> 18245 * The default implementation behaves as 18246 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18247 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 18248 * the case of no accessibility delegate been set. 18249 * </p> 18250 * 18251 * @param host The View hosting the delegate. 18252 * @param info The instance to initialize. 18253 * 18254 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18255 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18256 */ 18257 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 18258 host.onInitializeAccessibilityNodeInfoInternal(info); 18259 } 18260 18261 /** 18262 * Called when a child of the host View has requested sending an 18263 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 18264 * to augment the event. 18265 * <p> 18266 * The default implementation behaves as 18267 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18268 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 18269 * the case of no accessibility delegate been set. 18270 * </p> 18271 * 18272 * @param host The View hosting the delegate. 18273 * @param child The child which requests sending the event. 18274 * @param event The event to be sent. 18275 * @return True if the event should be sent 18276 * 18277 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18278 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18279 */ 18280 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 18281 AccessibilityEvent event) { 18282 return host.onRequestSendAccessibilityEventInternal(child, event); 18283 } 18284 18285 /** 18286 * Gets the provider for managing a virtual view hierarchy rooted at this View 18287 * and reported to {@link android.accessibilityservice.AccessibilityService}s 18288 * that explore the window content. 18289 * <p> 18290 * The default implementation behaves as 18291 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 18292 * the case of no accessibility delegate been set. 18293 * </p> 18294 * 18295 * @return The provider. 18296 * 18297 * @see AccessibilityNodeProvider 18298 */ 18299 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 18300 return null; 18301 } 18302 } 18303 18304 private class MatchIdPredicate implements Predicate<View> { 18305 public int mId; 18306 18307 @Override 18308 public boolean apply(View view) { 18309 return (view.mID == mId); 18310 } 18311 } 18312 18313 private class MatchLabelForPredicate implements Predicate<View> { 18314 private int mLabeledId; 18315 18316 @Override 18317 public boolean apply(View view) { 18318 return (view.mLabelForId == mLabeledId); 18319 } 18320 } 18321 18322 /** 18323 * Dump all private flags in readable format, useful for documentation and 18324 * sanity checking. 18325 */ 18326 private static void dumpFlags() { 18327 final HashMap<String, String> found = Maps.newHashMap(); 18328 try { 18329 for (Field field : View.class.getDeclaredFields()) { 18330 final int modifiers = field.getModifiers(); 18331 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 18332 if (field.getType().equals(int.class)) { 18333 final int value = field.getInt(null); 18334 dumpFlag(found, field.getName(), value); 18335 } else if (field.getType().equals(int[].class)) { 18336 final int[] values = (int[]) field.get(null); 18337 for (int i = 0; i < values.length; i++) { 18338 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 18339 } 18340 } 18341 } 18342 } 18343 } catch (IllegalAccessException e) { 18344 throw new RuntimeException(e); 18345 } 18346 18347 final ArrayList<String> keys = Lists.newArrayList(); 18348 keys.addAll(found.keySet()); 18349 Collections.sort(keys); 18350 for (String key : keys) { 18351 Log.d(VIEW_LOG_TAG, found.get(key)); 18352 } 18353 } 18354 18355 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 18356 // Sort flags by prefix, then by bits, always keeping unique keys 18357 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 18358 final int prefix = name.indexOf('_'); 18359 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 18360 final String output = bits + " " + name; 18361 found.put(key, output); 18362 } 18363} 18364