View.java revision 7e5b586a26603e3f59881789bf7dfd8e8a76b92c
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 // There are a couple of flags left in mPrivateFlags2 2145 2146 /* End of masks for mPrivateFlags2 */ 2147 2148 /* Masks for mPrivateFlags3 */ 2149 2150 /** 2151 * Flag indicating that view has a transform animation set on it. This is used to track whether 2152 * an animation is cleared between successive frames, in order to tell the associated 2153 * DisplayList to clear its animation matrix. 2154 */ 2155 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2156 2157 /** 2158 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2159 * animation is cleared between successive frames, in order to tell the associated 2160 * DisplayList to restore its alpha value. 2161 */ 2162 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2163 2164 2165 /* End of masks for mPrivateFlags3 */ 2166 2167 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2168 2169 /** 2170 * Always allow a user to over-scroll this view, provided it is a 2171 * view that can scroll. 2172 * 2173 * @see #getOverScrollMode() 2174 * @see #setOverScrollMode(int) 2175 */ 2176 public static final int OVER_SCROLL_ALWAYS = 0; 2177 2178 /** 2179 * Allow a user to over-scroll this view only if the content is large 2180 * enough to meaningfully scroll, provided it is a view that can scroll. 2181 * 2182 * @see #getOverScrollMode() 2183 * @see #setOverScrollMode(int) 2184 */ 2185 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2186 2187 /** 2188 * Never allow a user to over-scroll this view. 2189 * 2190 * @see #getOverScrollMode() 2191 * @see #setOverScrollMode(int) 2192 */ 2193 public static final int OVER_SCROLL_NEVER = 2; 2194 2195 /** 2196 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2197 * requested the system UI (status bar) to be visible (the default). 2198 * 2199 * @see #setSystemUiVisibility(int) 2200 */ 2201 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2202 2203 /** 2204 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2205 * system UI to enter an unobtrusive "low profile" mode. 2206 * 2207 * <p>This is for use in games, book readers, video players, or any other 2208 * "immersive" application where the usual system chrome is deemed too distracting. 2209 * 2210 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2211 * 2212 * @see #setSystemUiVisibility(int) 2213 */ 2214 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2215 2216 /** 2217 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2218 * system navigation be temporarily hidden. 2219 * 2220 * <p>This is an even less obtrusive state than that called for by 2221 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2222 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2223 * those to disappear. This is useful (in conjunction with the 2224 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2225 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2226 * window flags) for displaying content using every last pixel on the display. 2227 * 2228 * <p>There is a limitation: because navigation controls are so important, the least user 2229 * interaction will cause them to reappear immediately. When this happens, both 2230 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2231 * so that both elements reappear at the same time. 2232 * 2233 * @see #setSystemUiVisibility(int) 2234 */ 2235 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2236 2237 /** 2238 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2239 * into the normal fullscreen mode so that its content can take over the screen 2240 * while still allowing the user to interact with the application. 2241 * 2242 * <p>This has the same visual effect as 2243 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2244 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2245 * meaning that non-critical screen decorations (such as the status bar) will be 2246 * hidden while the user is in the View's window, focusing the experience on 2247 * that content. Unlike the window flag, if you are using ActionBar in 2248 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2249 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2250 * hide the action bar. 2251 * 2252 * <p>This approach to going fullscreen is best used over the window flag when 2253 * it is a transient state -- that is, the application does this at certain 2254 * points in its user interaction where it wants to allow the user to focus 2255 * on content, but not as a continuous state. For situations where the application 2256 * would like to simply stay full screen the entire time (such as a game that 2257 * wants to take over the screen), the 2258 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2259 * is usually a better approach. The state set here will be removed by the system 2260 * in various situations (such as the user moving to another application) like 2261 * the other system UI states. 2262 * 2263 * <p>When using this flag, the application should provide some easy facility 2264 * for the user to go out of it. A common example would be in an e-book 2265 * reader, where tapping on the screen brings back whatever screen and UI 2266 * decorations that had been hidden while the user was immersed in reading 2267 * the book. 2268 * 2269 * @see #setSystemUiVisibility(int) 2270 */ 2271 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2272 2273 /** 2274 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2275 * flags, we would like a stable view of the content insets given to 2276 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2277 * will always represent the worst case that the application can expect 2278 * as a continuous state. In the stock Android UI this is the space for 2279 * the system bar, nav bar, and status bar, but not more transient elements 2280 * such as an input method. 2281 * 2282 * The stable layout your UI sees is based on the system UI modes you can 2283 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2284 * then you will get a stable layout for changes of the 2285 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2286 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2287 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2288 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2289 * with a stable layout. (Note that you should avoid using 2290 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2291 * 2292 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2293 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2294 * then a hidden status bar will be considered a "stable" state for purposes 2295 * here. This allows your UI to continually hide the status bar, while still 2296 * using the system UI flags to hide the action bar while still retaining 2297 * a stable layout. Note that changing the window fullscreen flag will never 2298 * provide a stable layout for a clean transition. 2299 * 2300 * <p>If you are using ActionBar in 2301 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2302 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2303 * insets it adds to those given to the application. 2304 */ 2305 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2306 2307 /** 2308 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2309 * to be layed out as if it has requested 2310 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2311 * allows it to avoid artifacts when switching in and out of that mode, at 2312 * the expense that some of its user interface may be covered by screen 2313 * decorations when they are shown. You can perform layout of your inner 2314 * UI elements to account for the navagation system UI through the 2315 * {@link #fitSystemWindows(Rect)} method. 2316 */ 2317 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2318 2319 /** 2320 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2321 * to be layed out as if it has requested 2322 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2323 * allows it to avoid artifacts when switching in and out of that mode, at 2324 * the expense that some of its user interface may be covered by screen 2325 * decorations when they are shown. You can perform layout of your inner 2326 * UI elements to account for non-fullscreen system UI through the 2327 * {@link #fitSystemWindows(Rect)} method. 2328 */ 2329 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2330 2331 /** 2332 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2333 */ 2334 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2335 2336 /** 2337 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2338 */ 2339 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2340 2341 /** 2342 * @hide 2343 * 2344 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2345 * out of the public fields to keep the undefined bits out of the developer's way. 2346 * 2347 * Flag to make the status bar not expandable. Unless you also 2348 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2349 */ 2350 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2351 2352 /** 2353 * @hide 2354 * 2355 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2356 * out of the public fields to keep the undefined bits out of the developer's way. 2357 * 2358 * Flag to hide notification icons and scrolling ticker text. 2359 */ 2360 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2361 2362 /** 2363 * @hide 2364 * 2365 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2366 * out of the public fields to keep the undefined bits out of the developer's way. 2367 * 2368 * Flag to disable incoming notification alerts. This will not block 2369 * icons, but it will block sound, vibrating and other visual or aural notifications. 2370 */ 2371 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2372 2373 /** 2374 * @hide 2375 * 2376 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2377 * out of the public fields to keep the undefined bits out of the developer's way. 2378 * 2379 * Flag to hide only the scrolling ticker. Note that 2380 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2381 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2382 */ 2383 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2384 2385 /** 2386 * @hide 2387 * 2388 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2389 * out of the public fields to keep the undefined bits out of the developer's way. 2390 * 2391 * Flag to hide the center system info area. 2392 */ 2393 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2394 2395 /** 2396 * @hide 2397 * 2398 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2399 * out of the public fields to keep the undefined bits out of the developer's way. 2400 * 2401 * Flag to hide only the home button. Don't use this 2402 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2403 */ 2404 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2405 2406 /** 2407 * @hide 2408 * 2409 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2410 * out of the public fields to keep the undefined bits out of the developer's way. 2411 * 2412 * Flag to hide only the back button. Don't use this 2413 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2414 */ 2415 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2416 2417 /** 2418 * @hide 2419 * 2420 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2421 * out of the public fields to keep the undefined bits out of the developer's way. 2422 * 2423 * Flag to hide only the clock. You might use this if your activity has 2424 * its own clock making the status bar's clock redundant. 2425 */ 2426 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2427 2428 /** 2429 * @hide 2430 * 2431 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2432 * out of the public fields to keep the undefined bits out of the developer's way. 2433 * 2434 * Flag to hide only the recent apps button. Don't use this 2435 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2436 */ 2437 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2438 2439 /** 2440 * @hide 2441 */ 2442 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2443 2444 /** 2445 * These are the system UI flags that can be cleared by events outside 2446 * of an application. Currently this is just the ability to tap on the 2447 * screen while hiding the navigation bar to have it return. 2448 * @hide 2449 */ 2450 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2451 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2452 | SYSTEM_UI_FLAG_FULLSCREEN; 2453 2454 /** 2455 * Flags that can impact the layout in relation to system UI. 2456 */ 2457 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2458 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2459 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2460 2461 /** 2462 * Find views that render the specified text. 2463 * 2464 * @see #findViewsWithText(ArrayList, CharSequence, int) 2465 */ 2466 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2467 2468 /** 2469 * Find find views that contain the specified content description. 2470 * 2471 * @see #findViewsWithText(ArrayList, CharSequence, int) 2472 */ 2473 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2474 2475 /** 2476 * Find views that contain {@link AccessibilityNodeProvider}. Such 2477 * a View is a root of virtual view hierarchy and may contain the searched 2478 * text. If this flag is set Views with providers are automatically 2479 * added and it is a responsibility of the client to call the APIs of 2480 * the provider to determine whether the virtual tree rooted at this View 2481 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2482 * represeting the virtual views with this text. 2483 * 2484 * @see #findViewsWithText(ArrayList, CharSequence, int) 2485 * 2486 * @hide 2487 */ 2488 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2489 2490 /** 2491 * The undefined cursor position. 2492 */ 2493 private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2494 2495 /** 2496 * Indicates that the screen has changed state and is now off. 2497 * 2498 * @see #onScreenStateChanged(int) 2499 */ 2500 public static final int SCREEN_STATE_OFF = 0x0; 2501 2502 /** 2503 * Indicates that the screen has changed state and is now on. 2504 * 2505 * @see #onScreenStateChanged(int) 2506 */ 2507 public static final int SCREEN_STATE_ON = 0x1; 2508 2509 /** 2510 * Controls the over-scroll mode for this view. 2511 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2512 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2513 * and {@link #OVER_SCROLL_NEVER}. 2514 */ 2515 private int mOverScrollMode; 2516 2517 /** 2518 * The parent this view is attached to. 2519 * {@hide} 2520 * 2521 * @see #getParent() 2522 */ 2523 protected ViewParent mParent; 2524 2525 /** 2526 * {@hide} 2527 */ 2528 AttachInfo mAttachInfo; 2529 2530 /** 2531 * {@hide} 2532 */ 2533 @ViewDebug.ExportedProperty(flagMapping = { 2534 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2535 name = "FORCE_LAYOUT"), 2536 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2537 name = "LAYOUT_REQUIRED"), 2538 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2539 name = "DRAWING_CACHE_INVALID", outputIf = false), 2540 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2541 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2542 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2543 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2544 }) 2545 int mPrivateFlags; 2546 int mPrivateFlags2; 2547 int mPrivateFlags3; 2548 2549 /** 2550 * This view's request for the visibility of the status bar. 2551 * @hide 2552 */ 2553 @ViewDebug.ExportedProperty(flagMapping = { 2554 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2555 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2556 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2557 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2558 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2559 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2560 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2561 equals = SYSTEM_UI_FLAG_VISIBLE, 2562 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2563 }) 2564 int mSystemUiVisibility; 2565 2566 /** 2567 * Reference count for transient state. 2568 * @see #setHasTransientState(boolean) 2569 */ 2570 int mTransientStateCount = 0; 2571 2572 /** 2573 * Count of how many windows this view has been attached to. 2574 */ 2575 int mWindowAttachCount; 2576 2577 /** 2578 * The layout parameters associated with this view and used by the parent 2579 * {@link android.view.ViewGroup} to determine how this view should be 2580 * laid out. 2581 * {@hide} 2582 */ 2583 protected ViewGroup.LayoutParams mLayoutParams; 2584 2585 /** 2586 * The view flags hold various views states. 2587 * {@hide} 2588 */ 2589 @ViewDebug.ExportedProperty 2590 int mViewFlags; 2591 2592 static class TransformationInfo { 2593 /** 2594 * The transform matrix for the View. This transform is calculated internally 2595 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2596 * is used by default. Do *not* use this variable directly; instead call 2597 * getMatrix(), which will automatically recalculate the matrix if necessary 2598 * to get the correct matrix based on the latest rotation and scale properties. 2599 */ 2600 private final Matrix mMatrix = new Matrix(); 2601 2602 /** 2603 * The transform matrix for the View. This transform is calculated internally 2604 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2605 * is used by default. Do *not* use this variable directly; instead call 2606 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2607 * to get the correct matrix based on the latest rotation and scale properties. 2608 */ 2609 private Matrix mInverseMatrix; 2610 2611 /** 2612 * An internal variable that tracks whether we need to recalculate the 2613 * transform matrix, based on whether the rotation or scaleX/Y properties 2614 * have changed since the matrix was last calculated. 2615 */ 2616 boolean mMatrixDirty = false; 2617 2618 /** 2619 * An internal variable that tracks whether we need to recalculate the 2620 * transform matrix, based on whether the rotation or scaleX/Y properties 2621 * have changed since the matrix was last calculated. 2622 */ 2623 private boolean mInverseMatrixDirty = true; 2624 2625 /** 2626 * A 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. This variable 2629 * is only valid after a call to updateMatrix() or to a function that 2630 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2631 */ 2632 private boolean mMatrixIsIdentity = true; 2633 2634 /** 2635 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2636 */ 2637 private Camera mCamera = null; 2638 2639 /** 2640 * This matrix is used when computing the matrix for 3D rotations. 2641 */ 2642 private Matrix matrix3D = null; 2643 2644 /** 2645 * These prev values are used to recalculate a centered pivot point when necessary. The 2646 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2647 * set), so thes values are only used then as well. 2648 */ 2649 private int mPrevWidth = -1; 2650 private int mPrevHeight = -1; 2651 2652 /** 2653 * The degrees rotation around the vertical axis through the pivot point. 2654 */ 2655 @ViewDebug.ExportedProperty 2656 float mRotationY = 0f; 2657 2658 /** 2659 * The degrees rotation around the horizontal axis through the pivot point. 2660 */ 2661 @ViewDebug.ExportedProperty 2662 float mRotationX = 0f; 2663 2664 /** 2665 * The degrees rotation around the pivot point. 2666 */ 2667 @ViewDebug.ExportedProperty 2668 float mRotation = 0f; 2669 2670 /** 2671 * The amount of translation of the object away from its left property (post-layout). 2672 */ 2673 @ViewDebug.ExportedProperty 2674 float mTranslationX = 0f; 2675 2676 /** 2677 * The amount of translation of the object away from its top property (post-layout). 2678 */ 2679 @ViewDebug.ExportedProperty 2680 float mTranslationY = 0f; 2681 2682 /** 2683 * The amount of scale in the x direction around the pivot point. A 2684 * value of 1 means no scaling is applied. 2685 */ 2686 @ViewDebug.ExportedProperty 2687 float mScaleX = 1f; 2688 2689 /** 2690 * The amount of scale in the y direction around the pivot point. A 2691 * value of 1 means no scaling is applied. 2692 */ 2693 @ViewDebug.ExportedProperty 2694 float mScaleY = 1f; 2695 2696 /** 2697 * The x location of the point around which the view is rotated and scaled. 2698 */ 2699 @ViewDebug.ExportedProperty 2700 float mPivotX = 0f; 2701 2702 /** 2703 * The y location of the point around which the view is rotated and scaled. 2704 */ 2705 @ViewDebug.ExportedProperty 2706 float mPivotY = 0f; 2707 2708 /** 2709 * The opacity of the View. This is a value from 0 to 1, where 0 means 2710 * completely transparent and 1 means completely opaque. 2711 */ 2712 @ViewDebug.ExportedProperty 2713 float mAlpha = 1f; 2714 } 2715 2716 TransformationInfo mTransformationInfo; 2717 2718 private boolean mLastIsOpaque; 2719 2720 /** 2721 * Convenience value to check for float values that are close enough to zero to be considered 2722 * zero. 2723 */ 2724 private static final float NONZERO_EPSILON = .001f; 2725 2726 /** 2727 * The distance in pixels from the left edge of this view's parent 2728 * to the left edge of this view. 2729 * {@hide} 2730 */ 2731 @ViewDebug.ExportedProperty(category = "layout") 2732 protected int mLeft; 2733 /** 2734 * The distance in pixels from the left edge of this view's parent 2735 * to the right edge of this view. 2736 * {@hide} 2737 */ 2738 @ViewDebug.ExportedProperty(category = "layout") 2739 protected int mRight; 2740 /** 2741 * The distance in pixels from the top edge of this view's parent 2742 * to the top edge of this view. 2743 * {@hide} 2744 */ 2745 @ViewDebug.ExportedProperty(category = "layout") 2746 protected int mTop; 2747 /** 2748 * The distance in pixels from the top edge of this view's parent 2749 * to the bottom edge of this view. 2750 * {@hide} 2751 */ 2752 @ViewDebug.ExportedProperty(category = "layout") 2753 protected int mBottom; 2754 2755 /** 2756 * The offset, in pixels, by which the content of this view is scrolled 2757 * horizontally. 2758 * {@hide} 2759 */ 2760 @ViewDebug.ExportedProperty(category = "scrolling") 2761 protected int mScrollX; 2762 /** 2763 * The offset, in pixels, by which the content of this view is scrolled 2764 * vertically. 2765 * {@hide} 2766 */ 2767 @ViewDebug.ExportedProperty(category = "scrolling") 2768 protected int mScrollY; 2769 2770 /** 2771 * The left padding in pixels, that is the distance in pixels between the 2772 * left edge of this view and the left edge of its content. 2773 * {@hide} 2774 */ 2775 @ViewDebug.ExportedProperty(category = "padding") 2776 protected int mPaddingLeft; 2777 /** 2778 * The right padding in pixels, that is the distance in pixels between the 2779 * right edge of this view and the right edge of its content. 2780 * {@hide} 2781 */ 2782 @ViewDebug.ExportedProperty(category = "padding") 2783 protected int mPaddingRight; 2784 /** 2785 * The top padding in pixels, that is the distance in pixels between the 2786 * top edge of this view and the top edge of its content. 2787 * {@hide} 2788 */ 2789 @ViewDebug.ExportedProperty(category = "padding") 2790 protected int mPaddingTop; 2791 /** 2792 * The bottom padding in pixels, that is the distance in pixels between the 2793 * bottom edge of this view and the bottom edge of its content. 2794 * {@hide} 2795 */ 2796 @ViewDebug.ExportedProperty(category = "padding") 2797 protected int mPaddingBottom; 2798 2799 /** 2800 * The layout insets in pixels, that is the distance in pixels between the 2801 * visible edges of this view its bounds. 2802 */ 2803 private Insets mLayoutInsets; 2804 2805 /** 2806 * Briefly describes the view and is primarily used for accessibility support. 2807 */ 2808 private CharSequence mContentDescription; 2809 2810 /** 2811 * Specifies the id of a view for which this view serves as a label for 2812 * accessibility purposes. 2813 */ 2814 private int mLabelForId = View.NO_ID; 2815 2816 /** 2817 * Predicate for matching labeled view id with its label for 2818 * accessibility purposes. 2819 */ 2820 private MatchLabelForPredicate mMatchLabelForPredicate; 2821 2822 /** 2823 * Predicate for matching a view by its id. 2824 */ 2825 private MatchIdPredicate mMatchIdPredicate; 2826 2827 /** 2828 * Cache the paddingRight set by the user to append to the scrollbar's size. 2829 * 2830 * @hide 2831 */ 2832 @ViewDebug.ExportedProperty(category = "padding") 2833 protected int mUserPaddingRight; 2834 2835 /** 2836 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2837 * 2838 * @hide 2839 */ 2840 @ViewDebug.ExportedProperty(category = "padding") 2841 protected int mUserPaddingBottom; 2842 2843 /** 2844 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2845 * 2846 * @hide 2847 */ 2848 @ViewDebug.ExportedProperty(category = "padding") 2849 protected int mUserPaddingLeft; 2850 2851 /** 2852 * Cache the paddingStart set by the user to append to the scrollbar's size. 2853 * 2854 */ 2855 @ViewDebug.ExportedProperty(category = "padding") 2856 int mUserPaddingStart; 2857 2858 /** 2859 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2860 * 2861 */ 2862 @ViewDebug.ExportedProperty(category = "padding") 2863 int mUserPaddingEnd; 2864 2865 /** 2866 * Cache initial left padding. 2867 * 2868 * @hide 2869 */ 2870 int mUserPaddingLeftInitial = UNDEFINED_PADDING; 2871 2872 /** 2873 * Cache initial right padding. 2874 * 2875 * @hide 2876 */ 2877 int mUserPaddingRightInitial = UNDEFINED_PADDING; 2878 2879 /** 2880 * Default undefined padding 2881 */ 2882 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 2883 2884 /** 2885 * @hide 2886 */ 2887 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2888 /** 2889 * @hide 2890 */ 2891 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2892 2893 private Drawable mBackground; 2894 2895 private int mBackgroundResource; 2896 private boolean mBackgroundSizeChanged; 2897 2898 static class ListenerInfo { 2899 /** 2900 * Listener used to dispatch focus change events. 2901 * This field should be made private, so it is hidden from the SDK. 2902 * {@hide} 2903 */ 2904 protected OnFocusChangeListener mOnFocusChangeListener; 2905 2906 /** 2907 * Listeners for layout change events. 2908 */ 2909 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2910 2911 /** 2912 * Listeners for attach events. 2913 */ 2914 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2915 2916 /** 2917 * Listener used to dispatch click events. 2918 * This field should be made private, so it is hidden from the SDK. 2919 * {@hide} 2920 */ 2921 public OnClickListener mOnClickListener; 2922 2923 /** 2924 * Listener used to dispatch long click events. 2925 * This field should be made private, so it is hidden from the SDK. 2926 * {@hide} 2927 */ 2928 protected OnLongClickListener mOnLongClickListener; 2929 2930 /** 2931 * Listener used to build the context menu. 2932 * This field should be made private, so it is hidden from the SDK. 2933 * {@hide} 2934 */ 2935 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2936 2937 private OnKeyListener mOnKeyListener; 2938 2939 private OnTouchListener mOnTouchListener; 2940 2941 private OnHoverListener mOnHoverListener; 2942 2943 private OnGenericMotionListener mOnGenericMotionListener; 2944 2945 private OnDragListener mOnDragListener; 2946 2947 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2948 } 2949 2950 ListenerInfo mListenerInfo; 2951 2952 /** 2953 * The application environment this view lives in. 2954 * This field should be made private, so it is hidden from the SDK. 2955 * {@hide} 2956 */ 2957 protected Context mContext; 2958 2959 private final Resources mResources; 2960 2961 private ScrollabilityCache mScrollCache; 2962 2963 private int[] mDrawableState = null; 2964 2965 /** 2966 * Set to true when drawing cache is enabled and cannot be created. 2967 * 2968 * @hide 2969 */ 2970 public boolean mCachingFailed; 2971 2972 private Bitmap mDrawingCache; 2973 private Bitmap mUnscaledDrawingCache; 2974 private HardwareLayer mHardwareLayer; 2975 DisplayList mDisplayList; 2976 2977 /** 2978 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2979 * the user may specify which view to go to next. 2980 */ 2981 private int mNextFocusLeftId = View.NO_ID; 2982 2983 /** 2984 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2985 * the user may specify which view to go to next. 2986 */ 2987 private int mNextFocusRightId = View.NO_ID; 2988 2989 /** 2990 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2991 * the user may specify which view to go to next. 2992 */ 2993 private int mNextFocusUpId = View.NO_ID; 2994 2995 /** 2996 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2997 * the user may specify which view to go to next. 2998 */ 2999 private int mNextFocusDownId = View.NO_ID; 3000 3001 /** 3002 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3003 * the user may specify which view to go to next. 3004 */ 3005 int mNextFocusForwardId = View.NO_ID; 3006 3007 private CheckForLongPress mPendingCheckForLongPress; 3008 private CheckForTap mPendingCheckForTap = null; 3009 private PerformClick mPerformClick; 3010 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3011 3012 private UnsetPressedState mUnsetPressedState; 3013 3014 /** 3015 * Whether the long press's action has been invoked. The tap's action is invoked on the 3016 * up event while a long press is invoked as soon as the long press duration is reached, so 3017 * a long press could be performed before the tap is checked, in which case the tap's action 3018 * should not be invoked. 3019 */ 3020 private boolean mHasPerformedLongPress; 3021 3022 /** 3023 * The minimum height of the view. We'll try our best to have the height 3024 * of this view to at least this amount. 3025 */ 3026 @ViewDebug.ExportedProperty(category = "measurement") 3027 private int mMinHeight; 3028 3029 /** 3030 * The minimum width of the view. We'll try our best to have the width 3031 * of this view to at least this amount. 3032 */ 3033 @ViewDebug.ExportedProperty(category = "measurement") 3034 private int mMinWidth; 3035 3036 /** 3037 * The delegate to handle touch events that are physically in this view 3038 * but should be handled by another view. 3039 */ 3040 private TouchDelegate mTouchDelegate = null; 3041 3042 /** 3043 * Solid color to use as a background when creating the drawing cache. Enables 3044 * the cache to use 16 bit bitmaps instead of 32 bit. 3045 */ 3046 private int mDrawingCacheBackgroundColor = 0; 3047 3048 /** 3049 * Special tree observer used when mAttachInfo is null. 3050 */ 3051 private ViewTreeObserver mFloatingTreeObserver; 3052 3053 /** 3054 * Cache the touch slop from the context that created the view. 3055 */ 3056 private int mTouchSlop; 3057 3058 /** 3059 * Object that handles automatic animation of view properties. 3060 */ 3061 private ViewPropertyAnimator mAnimator = null; 3062 3063 /** 3064 * Flag indicating that a drag can cross window boundaries. When 3065 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3066 * with this flag set, all visible applications will be able to participate 3067 * in the drag operation and receive the dragged content. 3068 * 3069 * @hide 3070 */ 3071 public static final int DRAG_FLAG_GLOBAL = 1; 3072 3073 /** 3074 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3075 */ 3076 private float mVerticalScrollFactor; 3077 3078 /** 3079 * Position of the vertical scroll bar. 3080 */ 3081 private int mVerticalScrollbarPosition; 3082 3083 /** 3084 * Position the scroll bar at the default position as determined by the system. 3085 */ 3086 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3087 3088 /** 3089 * Position the scroll bar along the left edge. 3090 */ 3091 public static final int SCROLLBAR_POSITION_LEFT = 1; 3092 3093 /** 3094 * Position the scroll bar along the right edge. 3095 */ 3096 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3097 3098 /** 3099 * Indicates that the view does not have a layer. 3100 * 3101 * @see #getLayerType() 3102 * @see #setLayerType(int, android.graphics.Paint) 3103 * @see #LAYER_TYPE_SOFTWARE 3104 * @see #LAYER_TYPE_HARDWARE 3105 */ 3106 public static final int LAYER_TYPE_NONE = 0; 3107 3108 /** 3109 * <p>Indicates that the view has a software layer. A software layer is backed 3110 * by a bitmap and causes the view to be rendered using Android's software 3111 * rendering pipeline, even if hardware acceleration is enabled.</p> 3112 * 3113 * <p>Software layers have various usages:</p> 3114 * <p>When the application is not using hardware acceleration, a software layer 3115 * is useful to apply a specific color filter and/or blending mode and/or 3116 * translucency to a view and all its children.</p> 3117 * <p>When the application is using hardware acceleration, a software layer 3118 * is useful to render drawing primitives not supported by the hardware 3119 * accelerated pipeline. It can also be used to cache a complex view tree 3120 * into a texture and reduce the complexity of drawing operations. For instance, 3121 * when animating a complex view tree with a translation, a software layer can 3122 * be used to render the view tree only once.</p> 3123 * <p>Software layers should be avoided when the affected view tree updates 3124 * often. Every update will require to re-render the software layer, which can 3125 * potentially be slow (particularly when hardware acceleration is turned on 3126 * since the layer will have to be uploaded into a hardware texture after every 3127 * update.)</p> 3128 * 3129 * @see #getLayerType() 3130 * @see #setLayerType(int, android.graphics.Paint) 3131 * @see #LAYER_TYPE_NONE 3132 * @see #LAYER_TYPE_HARDWARE 3133 */ 3134 public static final int LAYER_TYPE_SOFTWARE = 1; 3135 3136 /** 3137 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3138 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3139 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3140 * rendering pipeline, but only if hardware acceleration is turned on for the 3141 * view hierarchy. When hardware acceleration is turned off, hardware layers 3142 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3143 * 3144 * <p>A hardware layer is useful to apply a specific color filter and/or 3145 * blending mode and/or translucency to a view and all its children.</p> 3146 * <p>A hardware layer can be used to cache a complex view tree into a 3147 * texture and reduce the complexity of drawing operations. For instance, 3148 * when animating a complex view tree with a translation, a hardware layer can 3149 * be used to render the view tree only once.</p> 3150 * <p>A hardware layer can also be used to increase the rendering quality when 3151 * rotation transformations are applied on a view. It can also be used to 3152 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3153 * 3154 * @see #getLayerType() 3155 * @see #setLayerType(int, android.graphics.Paint) 3156 * @see #LAYER_TYPE_NONE 3157 * @see #LAYER_TYPE_SOFTWARE 3158 */ 3159 public static final int LAYER_TYPE_HARDWARE = 2; 3160 3161 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3162 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3163 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3164 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3165 }) 3166 int mLayerType = LAYER_TYPE_NONE; 3167 Paint mLayerPaint; 3168 Rect mLocalDirtyRect; 3169 3170 /** 3171 * Set to true when the view is sending hover accessibility events because it 3172 * is the innermost hovered view. 3173 */ 3174 private boolean mSendingHoverAccessibilityEvents; 3175 3176 /** 3177 * Delegate for injecting accessibility functionality. 3178 */ 3179 AccessibilityDelegate mAccessibilityDelegate; 3180 3181 /** 3182 * Consistency verifier for debugging purposes. 3183 * @hide 3184 */ 3185 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3186 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3187 new InputEventConsistencyVerifier(this, 0) : null; 3188 3189 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3190 3191 /** 3192 * Simple constructor to use when creating a view from code. 3193 * 3194 * @param context The Context the view is running in, through which it can 3195 * access the current theme, resources, etc. 3196 */ 3197 public View(Context context) { 3198 mContext = context; 3199 mResources = context != null ? context.getResources() : null; 3200 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3201 // Set layout and text direction defaults 3202 mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3203 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3204 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3205 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3206 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3207 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3208 mUserPaddingStart = UNDEFINED_PADDING; 3209 mUserPaddingEnd = UNDEFINED_PADDING; 3210 } 3211 3212 /** 3213 * Constructor that is called when inflating a view from XML. This is called 3214 * when a view is being constructed from an XML file, supplying attributes 3215 * that were specified in the XML file. This version uses a default style of 3216 * 0, so the only attribute values applied are those in the Context's Theme 3217 * and the given AttributeSet. 3218 * 3219 * <p> 3220 * The method onFinishInflate() will be called after all children have been 3221 * added. 3222 * 3223 * @param context The Context the view is running in, through which it can 3224 * access the current theme, resources, etc. 3225 * @param attrs The attributes of the XML tag that is inflating the view. 3226 * @see #View(Context, AttributeSet, int) 3227 */ 3228 public View(Context context, AttributeSet attrs) { 3229 this(context, attrs, 0); 3230 } 3231 3232 /** 3233 * Perform inflation from XML and apply a class-specific base style. This 3234 * constructor of View allows subclasses to use their own base style when 3235 * they are inflating. For example, a Button class's constructor would call 3236 * this version of the super class constructor and supply 3237 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 3238 * the theme's button style to modify all of the base view attributes (in 3239 * particular its background) as well as the Button class's attributes. 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 * @param defStyle The default style to apply to this view. If 0, no style 3245 * will be applied (beyond what is included in the theme). This may 3246 * either be an attribute resource, whose value will be retrieved 3247 * from the current theme, or an explicit style resource. 3248 * @see #View(Context, AttributeSet) 3249 */ 3250 public View(Context context, AttributeSet attrs, int defStyle) { 3251 this(context); 3252 3253 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 3254 defStyle, 0); 3255 3256 Drawable background = null; 3257 3258 int leftPadding = -1; 3259 int topPadding = -1; 3260 int rightPadding = -1; 3261 int bottomPadding = -1; 3262 int startPadding = UNDEFINED_PADDING; 3263 int endPadding = UNDEFINED_PADDING; 3264 3265 int padding = -1; 3266 3267 int viewFlagValues = 0; 3268 int viewFlagMasks = 0; 3269 3270 boolean setScrollContainer = false; 3271 3272 int x = 0; 3273 int y = 0; 3274 3275 float tx = 0; 3276 float ty = 0; 3277 float rotation = 0; 3278 float rotationX = 0; 3279 float rotationY = 0; 3280 float sx = 1f; 3281 float sy = 1f; 3282 boolean transformSet = false; 3283 3284 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3285 int overScrollMode = mOverScrollMode; 3286 boolean initializeScrollbars = false; 3287 3288 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3289 3290 final int N = a.getIndexCount(); 3291 for (int i = 0; i < N; i++) { 3292 int attr = a.getIndex(i); 3293 switch (attr) { 3294 case com.android.internal.R.styleable.View_background: 3295 background = a.getDrawable(attr); 3296 break; 3297 case com.android.internal.R.styleable.View_padding: 3298 padding = a.getDimensionPixelSize(attr, -1); 3299 mUserPaddingLeftInitial = padding; 3300 mUserPaddingRightInitial = padding; 3301 break; 3302 case com.android.internal.R.styleable.View_paddingLeft: 3303 leftPadding = a.getDimensionPixelSize(attr, -1); 3304 mUserPaddingLeftInitial = leftPadding; 3305 break; 3306 case com.android.internal.R.styleable.View_paddingTop: 3307 topPadding = a.getDimensionPixelSize(attr, -1); 3308 break; 3309 case com.android.internal.R.styleable.View_paddingRight: 3310 rightPadding = a.getDimensionPixelSize(attr, -1); 3311 mUserPaddingRightInitial = rightPadding; 3312 break; 3313 case com.android.internal.R.styleable.View_paddingBottom: 3314 bottomPadding = a.getDimensionPixelSize(attr, -1); 3315 break; 3316 case com.android.internal.R.styleable.View_paddingStart: 3317 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3318 break; 3319 case com.android.internal.R.styleable.View_paddingEnd: 3320 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3321 break; 3322 case com.android.internal.R.styleable.View_scrollX: 3323 x = a.getDimensionPixelOffset(attr, 0); 3324 break; 3325 case com.android.internal.R.styleable.View_scrollY: 3326 y = a.getDimensionPixelOffset(attr, 0); 3327 break; 3328 case com.android.internal.R.styleable.View_alpha: 3329 setAlpha(a.getFloat(attr, 1f)); 3330 break; 3331 case com.android.internal.R.styleable.View_transformPivotX: 3332 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3333 break; 3334 case com.android.internal.R.styleable.View_transformPivotY: 3335 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3336 break; 3337 case com.android.internal.R.styleable.View_translationX: 3338 tx = a.getDimensionPixelOffset(attr, 0); 3339 transformSet = true; 3340 break; 3341 case com.android.internal.R.styleable.View_translationY: 3342 ty = a.getDimensionPixelOffset(attr, 0); 3343 transformSet = true; 3344 break; 3345 case com.android.internal.R.styleable.View_rotation: 3346 rotation = a.getFloat(attr, 0); 3347 transformSet = true; 3348 break; 3349 case com.android.internal.R.styleable.View_rotationX: 3350 rotationX = a.getFloat(attr, 0); 3351 transformSet = true; 3352 break; 3353 case com.android.internal.R.styleable.View_rotationY: 3354 rotationY = a.getFloat(attr, 0); 3355 transformSet = true; 3356 break; 3357 case com.android.internal.R.styleable.View_scaleX: 3358 sx = a.getFloat(attr, 1f); 3359 transformSet = true; 3360 break; 3361 case com.android.internal.R.styleable.View_scaleY: 3362 sy = a.getFloat(attr, 1f); 3363 transformSet = true; 3364 break; 3365 case com.android.internal.R.styleable.View_id: 3366 mID = a.getResourceId(attr, NO_ID); 3367 break; 3368 case com.android.internal.R.styleable.View_tag: 3369 mTag = a.getText(attr); 3370 break; 3371 case com.android.internal.R.styleable.View_fitsSystemWindows: 3372 if (a.getBoolean(attr, false)) { 3373 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3374 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3375 } 3376 break; 3377 case com.android.internal.R.styleable.View_focusable: 3378 if (a.getBoolean(attr, false)) { 3379 viewFlagValues |= FOCUSABLE; 3380 viewFlagMasks |= FOCUSABLE_MASK; 3381 } 3382 break; 3383 case com.android.internal.R.styleable.View_focusableInTouchMode: 3384 if (a.getBoolean(attr, false)) { 3385 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3386 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3387 } 3388 break; 3389 case com.android.internal.R.styleable.View_clickable: 3390 if (a.getBoolean(attr, false)) { 3391 viewFlagValues |= CLICKABLE; 3392 viewFlagMasks |= CLICKABLE; 3393 } 3394 break; 3395 case com.android.internal.R.styleable.View_longClickable: 3396 if (a.getBoolean(attr, false)) { 3397 viewFlagValues |= LONG_CLICKABLE; 3398 viewFlagMasks |= LONG_CLICKABLE; 3399 } 3400 break; 3401 case com.android.internal.R.styleable.View_saveEnabled: 3402 if (!a.getBoolean(attr, true)) { 3403 viewFlagValues |= SAVE_DISABLED; 3404 viewFlagMasks |= SAVE_DISABLED_MASK; 3405 } 3406 break; 3407 case com.android.internal.R.styleable.View_duplicateParentState: 3408 if (a.getBoolean(attr, false)) { 3409 viewFlagValues |= DUPLICATE_PARENT_STATE; 3410 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3411 } 3412 break; 3413 case com.android.internal.R.styleable.View_visibility: 3414 final int visibility = a.getInt(attr, 0); 3415 if (visibility != 0) { 3416 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3417 viewFlagMasks |= VISIBILITY_MASK; 3418 } 3419 break; 3420 case com.android.internal.R.styleable.View_layoutDirection: 3421 // Clear any layout direction flags (included resolved bits) already set 3422 mPrivateFlags2 &= ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3423 // Set the layout direction flags depending on the value of the attribute 3424 final int layoutDirection = a.getInt(attr, -1); 3425 final int value = (layoutDirection != -1) ? 3426 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3427 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3428 break; 3429 case com.android.internal.R.styleable.View_drawingCacheQuality: 3430 final int cacheQuality = a.getInt(attr, 0); 3431 if (cacheQuality != 0) { 3432 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3433 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3434 } 3435 break; 3436 case com.android.internal.R.styleable.View_contentDescription: 3437 setContentDescription(a.getString(attr)); 3438 break; 3439 case com.android.internal.R.styleable.View_labelFor: 3440 setLabelFor(a.getResourceId(attr, NO_ID)); 3441 break; 3442 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3443 if (!a.getBoolean(attr, true)) { 3444 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3445 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3446 } 3447 break; 3448 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3449 if (!a.getBoolean(attr, true)) { 3450 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3451 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3452 } 3453 break; 3454 case R.styleable.View_scrollbars: 3455 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3456 if (scrollbars != SCROLLBARS_NONE) { 3457 viewFlagValues |= scrollbars; 3458 viewFlagMasks |= SCROLLBARS_MASK; 3459 initializeScrollbars = true; 3460 } 3461 break; 3462 //noinspection deprecation 3463 case R.styleable.View_fadingEdge: 3464 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3465 // Ignore the attribute starting with ICS 3466 break; 3467 } 3468 // With builds < ICS, fall through and apply fading edges 3469 case R.styleable.View_requiresFadingEdge: 3470 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3471 if (fadingEdge != FADING_EDGE_NONE) { 3472 viewFlagValues |= fadingEdge; 3473 viewFlagMasks |= FADING_EDGE_MASK; 3474 initializeFadingEdge(a); 3475 } 3476 break; 3477 case R.styleable.View_scrollbarStyle: 3478 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3479 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3480 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3481 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3482 } 3483 break; 3484 case R.styleable.View_isScrollContainer: 3485 setScrollContainer = true; 3486 if (a.getBoolean(attr, false)) { 3487 setScrollContainer(true); 3488 } 3489 break; 3490 case com.android.internal.R.styleable.View_keepScreenOn: 3491 if (a.getBoolean(attr, false)) { 3492 viewFlagValues |= KEEP_SCREEN_ON; 3493 viewFlagMasks |= KEEP_SCREEN_ON; 3494 } 3495 break; 3496 case R.styleable.View_filterTouchesWhenObscured: 3497 if (a.getBoolean(attr, false)) { 3498 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3499 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3500 } 3501 break; 3502 case R.styleable.View_nextFocusLeft: 3503 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3504 break; 3505 case R.styleable.View_nextFocusRight: 3506 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3507 break; 3508 case R.styleable.View_nextFocusUp: 3509 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3510 break; 3511 case R.styleable.View_nextFocusDown: 3512 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3513 break; 3514 case R.styleable.View_nextFocusForward: 3515 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3516 break; 3517 case R.styleable.View_minWidth: 3518 mMinWidth = a.getDimensionPixelSize(attr, 0); 3519 break; 3520 case R.styleable.View_minHeight: 3521 mMinHeight = a.getDimensionPixelSize(attr, 0); 3522 break; 3523 case R.styleable.View_onClick: 3524 if (context.isRestricted()) { 3525 throw new IllegalStateException("The android:onClick attribute cannot " 3526 + "be used within a restricted context"); 3527 } 3528 3529 final String handlerName = a.getString(attr); 3530 if (handlerName != null) { 3531 setOnClickListener(new OnClickListener() { 3532 private Method mHandler; 3533 3534 public void onClick(View v) { 3535 if (mHandler == null) { 3536 try { 3537 mHandler = getContext().getClass().getMethod(handlerName, 3538 View.class); 3539 } catch (NoSuchMethodException e) { 3540 int id = getId(); 3541 String idText = id == NO_ID ? "" : " with id '" 3542 + getContext().getResources().getResourceEntryName( 3543 id) + "'"; 3544 throw new IllegalStateException("Could not find a method " + 3545 handlerName + "(View) in the activity " 3546 + getContext().getClass() + " for onClick handler" 3547 + " on view " + View.this.getClass() + idText, e); 3548 } 3549 } 3550 3551 try { 3552 mHandler.invoke(getContext(), View.this); 3553 } catch (IllegalAccessException e) { 3554 throw new IllegalStateException("Could not execute non " 3555 + "public method of the activity", e); 3556 } catch (InvocationTargetException e) { 3557 throw new IllegalStateException("Could not execute " 3558 + "method of the activity", e); 3559 } 3560 } 3561 }); 3562 } 3563 break; 3564 case R.styleable.View_overScrollMode: 3565 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3566 break; 3567 case R.styleable.View_verticalScrollbarPosition: 3568 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3569 break; 3570 case R.styleable.View_layerType: 3571 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3572 break; 3573 case R.styleable.View_textDirection: 3574 // Clear any text direction flag already set 3575 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3576 // Set the text direction flags depending on the value of the attribute 3577 final int textDirection = a.getInt(attr, -1); 3578 if (textDirection != -1) { 3579 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3580 } 3581 break; 3582 case R.styleable.View_textAlignment: 3583 // Clear any text alignment flag already set 3584 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3585 // Set the text alignment flag depending on the value of the attribute 3586 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3587 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 3588 break; 3589 case R.styleable.View_importantForAccessibility: 3590 setImportantForAccessibility(a.getInt(attr, 3591 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 3592 break; 3593 } 3594 } 3595 3596 setOverScrollMode(overScrollMode); 3597 3598 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 3599 // the resolved layout direction). Those cached values will be used later during padding 3600 // resolution. 3601 mUserPaddingStart = startPadding; 3602 mUserPaddingEnd = endPadding; 3603 3604 if (background != null) { 3605 setBackground(background); 3606 } 3607 3608 if (padding >= 0) { 3609 leftPadding = padding; 3610 topPadding = padding; 3611 rightPadding = padding; 3612 bottomPadding = padding; 3613 mUserPaddingLeftInitial = padding; 3614 mUserPaddingRightInitial = padding; 3615 } 3616 3617 // If the user specified the padding (either with android:padding or 3618 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 3619 // use the default padding or the padding from the background drawable 3620 // (stored at this point in mPadding*) 3621 mUserPaddingLeftInitial = leftPadding >= 0 ? leftPadding : mPaddingLeft; 3622 mUserPaddingRightInitial = rightPadding >= 0 ? rightPadding : mPaddingRight; 3623 internalSetPadding(mUserPaddingLeftInitial, 3624 topPadding >= 0 ? topPadding : mPaddingTop, 3625 mUserPaddingRightInitial, 3626 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3627 3628 if (viewFlagMasks != 0) { 3629 setFlags(viewFlagValues, viewFlagMasks); 3630 } 3631 3632 if (initializeScrollbars) { 3633 initializeScrollbars(a); 3634 } 3635 3636 a.recycle(); 3637 3638 // Needs to be called after mViewFlags is set 3639 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3640 recomputePadding(); 3641 } 3642 3643 if (x != 0 || y != 0) { 3644 scrollTo(x, y); 3645 } 3646 3647 if (transformSet) { 3648 setTranslationX(tx); 3649 setTranslationY(ty); 3650 setRotation(rotation); 3651 setRotationX(rotationX); 3652 setRotationY(rotationY); 3653 setScaleX(sx); 3654 setScaleY(sy); 3655 } 3656 3657 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3658 setScrollContainer(true); 3659 } 3660 3661 computeOpaqueFlags(); 3662 } 3663 3664 /** 3665 * Non-public constructor for use in testing 3666 */ 3667 View() { 3668 mResources = null; 3669 } 3670 3671 public String toString() { 3672 StringBuilder out = new StringBuilder(128); 3673 out.append(getClass().getName()); 3674 out.append('{'); 3675 out.append(Integer.toHexString(System.identityHashCode(this))); 3676 out.append(' '); 3677 switch (mViewFlags&VISIBILITY_MASK) { 3678 case VISIBLE: out.append('V'); break; 3679 case INVISIBLE: out.append('I'); break; 3680 case GONE: out.append('G'); break; 3681 default: out.append('.'); break; 3682 } 3683 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 3684 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 3685 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 3686 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 3687 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 3688 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 3689 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 3690 out.append(' '); 3691 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 3692 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 3693 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 3694 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 3695 out.append('p'); 3696 } else { 3697 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 3698 } 3699 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 3700 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 3701 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 3702 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 3703 out.append(' '); 3704 out.append(mLeft); 3705 out.append(','); 3706 out.append(mTop); 3707 out.append('-'); 3708 out.append(mRight); 3709 out.append(','); 3710 out.append(mBottom); 3711 final int id = getId(); 3712 if (id != NO_ID) { 3713 out.append(" #"); 3714 out.append(Integer.toHexString(id)); 3715 final Resources r = mResources; 3716 if (id != 0 && r != null) { 3717 try { 3718 String pkgname; 3719 switch (id&0xff000000) { 3720 case 0x7f000000: 3721 pkgname="app"; 3722 break; 3723 case 0x01000000: 3724 pkgname="android"; 3725 break; 3726 default: 3727 pkgname = r.getResourcePackageName(id); 3728 break; 3729 } 3730 String typename = r.getResourceTypeName(id); 3731 String entryname = r.getResourceEntryName(id); 3732 out.append(" "); 3733 out.append(pkgname); 3734 out.append(":"); 3735 out.append(typename); 3736 out.append("/"); 3737 out.append(entryname); 3738 } catch (Resources.NotFoundException e) { 3739 } 3740 } 3741 } 3742 out.append("}"); 3743 return out.toString(); 3744 } 3745 3746 /** 3747 * <p> 3748 * Initializes the fading edges from a given set of styled attributes. This 3749 * method should be called by subclasses that need fading edges and when an 3750 * instance of these subclasses is created programmatically rather than 3751 * being inflated from XML. This method is automatically called when the XML 3752 * is inflated. 3753 * </p> 3754 * 3755 * @param a the styled attributes set to initialize the fading edges from 3756 */ 3757 protected void initializeFadingEdge(TypedArray a) { 3758 initScrollCache(); 3759 3760 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3761 R.styleable.View_fadingEdgeLength, 3762 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3763 } 3764 3765 /** 3766 * Returns the size of the vertical faded edges used to indicate that more 3767 * content in this view is visible. 3768 * 3769 * @return The size in pixels of the vertical faded edge or 0 if vertical 3770 * faded edges are not enabled for this view. 3771 * @attr ref android.R.styleable#View_fadingEdgeLength 3772 */ 3773 public int getVerticalFadingEdgeLength() { 3774 if (isVerticalFadingEdgeEnabled()) { 3775 ScrollabilityCache cache = mScrollCache; 3776 if (cache != null) { 3777 return cache.fadingEdgeLength; 3778 } 3779 } 3780 return 0; 3781 } 3782 3783 /** 3784 * Set the size of the faded edge used to indicate that more content in this 3785 * view is available. Will not change whether the fading edge is enabled; use 3786 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3787 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3788 * for the vertical or horizontal fading edges. 3789 * 3790 * @param length The size in pixels of the faded edge used to indicate that more 3791 * content in this view is visible. 3792 */ 3793 public void setFadingEdgeLength(int length) { 3794 initScrollCache(); 3795 mScrollCache.fadingEdgeLength = length; 3796 } 3797 3798 /** 3799 * Returns the size of the horizontal faded edges used to indicate that more 3800 * content in this view is visible. 3801 * 3802 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3803 * faded edges are not enabled for this view. 3804 * @attr ref android.R.styleable#View_fadingEdgeLength 3805 */ 3806 public int getHorizontalFadingEdgeLength() { 3807 if (isHorizontalFadingEdgeEnabled()) { 3808 ScrollabilityCache cache = mScrollCache; 3809 if (cache != null) { 3810 return cache.fadingEdgeLength; 3811 } 3812 } 3813 return 0; 3814 } 3815 3816 /** 3817 * Returns the width of the vertical scrollbar. 3818 * 3819 * @return The width in pixels of the vertical scrollbar or 0 if there 3820 * is no vertical scrollbar. 3821 */ 3822 public int getVerticalScrollbarWidth() { 3823 ScrollabilityCache cache = mScrollCache; 3824 if (cache != null) { 3825 ScrollBarDrawable scrollBar = cache.scrollBar; 3826 if (scrollBar != null) { 3827 int size = scrollBar.getSize(true); 3828 if (size <= 0) { 3829 size = cache.scrollBarSize; 3830 } 3831 return size; 3832 } 3833 return 0; 3834 } 3835 return 0; 3836 } 3837 3838 /** 3839 * Returns the height of the horizontal scrollbar. 3840 * 3841 * @return The height in pixels of the horizontal scrollbar or 0 if 3842 * there is no horizontal scrollbar. 3843 */ 3844 protected int getHorizontalScrollbarHeight() { 3845 ScrollabilityCache cache = mScrollCache; 3846 if (cache != null) { 3847 ScrollBarDrawable scrollBar = cache.scrollBar; 3848 if (scrollBar != null) { 3849 int size = scrollBar.getSize(false); 3850 if (size <= 0) { 3851 size = cache.scrollBarSize; 3852 } 3853 return size; 3854 } 3855 return 0; 3856 } 3857 return 0; 3858 } 3859 3860 /** 3861 * <p> 3862 * Initializes the scrollbars from a given set of styled attributes. This 3863 * method should be called by subclasses that need scrollbars and when an 3864 * instance of these subclasses is created programmatically rather than 3865 * being inflated from XML. This method is automatically called when the XML 3866 * is inflated. 3867 * </p> 3868 * 3869 * @param a the styled attributes set to initialize the scrollbars from 3870 */ 3871 protected void initializeScrollbars(TypedArray a) { 3872 initScrollCache(); 3873 3874 final ScrollabilityCache scrollabilityCache = mScrollCache; 3875 3876 if (scrollabilityCache.scrollBar == null) { 3877 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3878 } 3879 3880 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3881 3882 if (!fadeScrollbars) { 3883 scrollabilityCache.state = ScrollabilityCache.ON; 3884 } 3885 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3886 3887 3888 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3889 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3890 .getScrollBarFadeDuration()); 3891 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3892 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3893 ViewConfiguration.getScrollDefaultDelay()); 3894 3895 3896 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3897 com.android.internal.R.styleable.View_scrollbarSize, 3898 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3899 3900 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3901 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3902 3903 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3904 if (thumb != null) { 3905 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3906 } 3907 3908 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3909 false); 3910 if (alwaysDraw) { 3911 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3912 } 3913 3914 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3915 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3916 3917 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3918 if (thumb != null) { 3919 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3920 } 3921 3922 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3923 false); 3924 if (alwaysDraw) { 3925 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3926 } 3927 3928 // Apply layout direction to the new Drawables if needed 3929 final int layoutDirection = getResolvedLayoutDirection(); 3930 if (track != null) { 3931 track.setLayoutDirection(layoutDirection); 3932 } 3933 if (thumb != null) { 3934 thumb.setLayoutDirection(layoutDirection); 3935 } 3936 3937 // Re-apply user/background padding so that scrollbar(s) get added 3938 resolvePadding(); 3939 } 3940 3941 /** 3942 * <p> 3943 * Initalizes the scrollability cache if necessary. 3944 * </p> 3945 */ 3946 private void initScrollCache() { 3947 if (mScrollCache == null) { 3948 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3949 } 3950 } 3951 3952 private ScrollabilityCache getScrollCache() { 3953 initScrollCache(); 3954 return mScrollCache; 3955 } 3956 3957 /** 3958 * Set the position of the vertical scroll bar. Should be one of 3959 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3960 * {@link #SCROLLBAR_POSITION_RIGHT}. 3961 * 3962 * @param position Where the vertical scroll bar should be positioned. 3963 */ 3964 public void setVerticalScrollbarPosition(int position) { 3965 if (mVerticalScrollbarPosition != position) { 3966 mVerticalScrollbarPosition = position; 3967 computeOpaqueFlags(); 3968 resolvePadding(); 3969 } 3970 } 3971 3972 /** 3973 * @return The position where the vertical scroll bar will show, if applicable. 3974 * @see #setVerticalScrollbarPosition(int) 3975 */ 3976 public int getVerticalScrollbarPosition() { 3977 return mVerticalScrollbarPosition; 3978 } 3979 3980 ListenerInfo getListenerInfo() { 3981 if (mListenerInfo != null) { 3982 return mListenerInfo; 3983 } 3984 mListenerInfo = new ListenerInfo(); 3985 return mListenerInfo; 3986 } 3987 3988 /** 3989 * Register a callback to be invoked when focus of this view changed. 3990 * 3991 * @param l The callback that will run. 3992 */ 3993 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3994 getListenerInfo().mOnFocusChangeListener = l; 3995 } 3996 3997 /** 3998 * Add a listener that will be called when the bounds of the view change due to 3999 * layout processing. 4000 * 4001 * @param listener The listener that will be called when layout bounds change. 4002 */ 4003 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4004 ListenerInfo li = getListenerInfo(); 4005 if (li.mOnLayoutChangeListeners == null) { 4006 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4007 } 4008 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4009 li.mOnLayoutChangeListeners.add(listener); 4010 } 4011 } 4012 4013 /** 4014 * Remove a listener for layout changes. 4015 * 4016 * @param listener The listener for layout bounds change. 4017 */ 4018 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4019 ListenerInfo li = mListenerInfo; 4020 if (li == null || li.mOnLayoutChangeListeners == null) { 4021 return; 4022 } 4023 li.mOnLayoutChangeListeners.remove(listener); 4024 } 4025 4026 /** 4027 * Add a listener for attach state changes. 4028 * 4029 * This listener will be called whenever this view is attached or detached 4030 * from a window. Remove the listener using 4031 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4032 * 4033 * @param listener Listener to attach 4034 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4035 */ 4036 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4037 ListenerInfo li = getListenerInfo(); 4038 if (li.mOnAttachStateChangeListeners == null) { 4039 li.mOnAttachStateChangeListeners 4040 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4041 } 4042 li.mOnAttachStateChangeListeners.add(listener); 4043 } 4044 4045 /** 4046 * Remove a listener for attach state changes. The listener will receive no further 4047 * notification of window attach/detach events. 4048 * 4049 * @param listener Listener to remove 4050 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4051 */ 4052 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4053 ListenerInfo li = mListenerInfo; 4054 if (li == null || li.mOnAttachStateChangeListeners == null) { 4055 return; 4056 } 4057 li.mOnAttachStateChangeListeners.remove(listener); 4058 } 4059 4060 /** 4061 * Returns the focus-change callback registered for this view. 4062 * 4063 * @return The callback, or null if one is not registered. 4064 */ 4065 public OnFocusChangeListener getOnFocusChangeListener() { 4066 ListenerInfo li = mListenerInfo; 4067 return li != null ? li.mOnFocusChangeListener : null; 4068 } 4069 4070 /** 4071 * Register a callback to be invoked when this view is clicked. If this view is not 4072 * clickable, it becomes clickable. 4073 * 4074 * @param l The callback that will run 4075 * 4076 * @see #setClickable(boolean) 4077 */ 4078 public void setOnClickListener(OnClickListener l) { 4079 if (!isClickable()) { 4080 setClickable(true); 4081 } 4082 getListenerInfo().mOnClickListener = l; 4083 } 4084 4085 /** 4086 * Return whether this view has an attached OnClickListener. Returns 4087 * true if there is a listener, false if there is none. 4088 */ 4089 public boolean hasOnClickListeners() { 4090 ListenerInfo li = mListenerInfo; 4091 return (li != null && li.mOnClickListener != null); 4092 } 4093 4094 /** 4095 * Register a callback to be invoked when this view is clicked and held. If this view is not 4096 * long clickable, it becomes long clickable. 4097 * 4098 * @param l The callback that will run 4099 * 4100 * @see #setLongClickable(boolean) 4101 */ 4102 public void setOnLongClickListener(OnLongClickListener l) { 4103 if (!isLongClickable()) { 4104 setLongClickable(true); 4105 } 4106 getListenerInfo().mOnLongClickListener = l; 4107 } 4108 4109 /** 4110 * Register a callback to be invoked when the context menu for this view is 4111 * being built. If this view is not long clickable, it becomes long clickable. 4112 * 4113 * @param l The callback that will run 4114 * 4115 */ 4116 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4117 if (!isLongClickable()) { 4118 setLongClickable(true); 4119 } 4120 getListenerInfo().mOnCreateContextMenuListener = l; 4121 } 4122 4123 /** 4124 * Call this view's OnClickListener, if it is defined. Performs all normal 4125 * actions associated with clicking: reporting accessibility event, playing 4126 * a sound, etc. 4127 * 4128 * @return True there was an assigned OnClickListener that was called, false 4129 * otherwise is returned. 4130 */ 4131 public boolean performClick() { 4132 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4133 4134 ListenerInfo li = mListenerInfo; 4135 if (li != null && li.mOnClickListener != null) { 4136 playSoundEffect(SoundEffectConstants.CLICK); 4137 li.mOnClickListener.onClick(this); 4138 return true; 4139 } 4140 4141 return false; 4142 } 4143 4144 /** 4145 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4146 * this only calls the listener, and does not do any associated clicking 4147 * actions like reporting an accessibility event. 4148 * 4149 * @return True there was an assigned OnClickListener that was called, false 4150 * otherwise is returned. 4151 */ 4152 public boolean callOnClick() { 4153 ListenerInfo li = mListenerInfo; 4154 if (li != null && li.mOnClickListener != null) { 4155 li.mOnClickListener.onClick(this); 4156 return true; 4157 } 4158 return false; 4159 } 4160 4161 /** 4162 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4163 * OnLongClickListener did not consume the event. 4164 * 4165 * @return True if one of the above receivers consumed the event, false otherwise. 4166 */ 4167 public boolean performLongClick() { 4168 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4169 4170 boolean handled = false; 4171 ListenerInfo li = mListenerInfo; 4172 if (li != null && li.mOnLongClickListener != null) { 4173 handled = li.mOnLongClickListener.onLongClick(View.this); 4174 } 4175 if (!handled) { 4176 handled = showContextMenu(); 4177 } 4178 if (handled) { 4179 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4180 } 4181 return handled; 4182 } 4183 4184 /** 4185 * Performs button-related actions during a touch down event. 4186 * 4187 * @param event The event. 4188 * @return True if the down was consumed. 4189 * 4190 * @hide 4191 */ 4192 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4193 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4194 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4195 return true; 4196 } 4197 } 4198 return false; 4199 } 4200 4201 /** 4202 * Bring up the context menu for this view. 4203 * 4204 * @return Whether a context menu was displayed. 4205 */ 4206 public boolean showContextMenu() { 4207 return getParent().showContextMenuForChild(this); 4208 } 4209 4210 /** 4211 * Bring up the context menu for this view, referring to the item under the specified point. 4212 * 4213 * @param x The referenced x coordinate. 4214 * @param y The referenced y coordinate. 4215 * @param metaState The keyboard modifiers that were pressed. 4216 * @return Whether a context menu was displayed. 4217 * 4218 * @hide 4219 */ 4220 public boolean showContextMenu(float x, float y, int metaState) { 4221 return showContextMenu(); 4222 } 4223 4224 /** 4225 * Start an action mode. 4226 * 4227 * @param callback Callback that will control the lifecycle of the action mode 4228 * @return The new action mode if it is started, null otherwise 4229 * 4230 * @see ActionMode 4231 */ 4232 public ActionMode startActionMode(ActionMode.Callback callback) { 4233 ViewParent parent = getParent(); 4234 if (parent == null) return null; 4235 return parent.startActionModeForChild(this, callback); 4236 } 4237 4238 /** 4239 * Register a callback to be invoked when a hardware key is pressed in this view. 4240 * Key presses in software input methods will generally not trigger the methods of 4241 * this listener. 4242 * @param l the key listener to attach to this view 4243 */ 4244 public void setOnKeyListener(OnKeyListener l) { 4245 getListenerInfo().mOnKeyListener = l; 4246 } 4247 4248 /** 4249 * Register a callback to be invoked when a touch event is sent to this view. 4250 * @param l the touch listener to attach to this view 4251 */ 4252 public void setOnTouchListener(OnTouchListener l) { 4253 getListenerInfo().mOnTouchListener = l; 4254 } 4255 4256 /** 4257 * Register a callback to be invoked when a generic motion event is sent to this view. 4258 * @param l the generic motion listener to attach to this view 4259 */ 4260 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4261 getListenerInfo().mOnGenericMotionListener = l; 4262 } 4263 4264 /** 4265 * Register a callback to be invoked when a hover event is sent to this view. 4266 * @param l the hover listener to attach to this view 4267 */ 4268 public void setOnHoverListener(OnHoverListener l) { 4269 getListenerInfo().mOnHoverListener = l; 4270 } 4271 4272 /** 4273 * Register a drag event listener callback object for this View. The parameter is 4274 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4275 * View, the system calls the 4276 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4277 * @param l An implementation of {@link android.view.View.OnDragListener}. 4278 */ 4279 public void setOnDragListener(OnDragListener l) { 4280 getListenerInfo().mOnDragListener = l; 4281 } 4282 4283 /** 4284 * Give this view focus. This will cause 4285 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4286 * 4287 * Note: this does not check whether this {@link View} should get focus, it just 4288 * gives it focus no matter what. It should only be called internally by framework 4289 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4290 * 4291 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4292 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4293 * focus moved when requestFocus() is called. It may not always 4294 * apply, in which case use the default View.FOCUS_DOWN. 4295 * @param previouslyFocusedRect The rectangle of the view that had focus 4296 * prior in this View's coordinate system. 4297 */ 4298 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 4299 if (DBG) { 4300 System.out.println(this + " requestFocus()"); 4301 } 4302 4303 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4304 mPrivateFlags |= PFLAG_FOCUSED; 4305 4306 if (mParent != null) { 4307 mParent.requestChildFocus(this, this); 4308 } 4309 4310 onFocusChanged(true, direction, previouslyFocusedRect); 4311 refreshDrawableState(); 4312 4313 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4314 notifyAccessibilityStateChanged(); 4315 } 4316 } 4317 } 4318 4319 /** 4320 * Request that a rectangle of this view be visible on the screen, 4321 * scrolling if necessary just enough. 4322 * 4323 * <p>A View should call this if it maintains some notion of which part 4324 * of its content is interesting. For example, a text editing view 4325 * should call this when its cursor moves. 4326 * 4327 * @param rectangle The rectangle. 4328 * @return Whether any parent scrolled. 4329 */ 4330 public boolean requestRectangleOnScreen(Rect rectangle) { 4331 return requestRectangleOnScreen(rectangle, false); 4332 } 4333 4334 /** 4335 * Request that a rectangle of this view be visible on the screen, 4336 * scrolling if necessary just enough. 4337 * 4338 * <p>A View should call this if it maintains some notion of which part 4339 * of its content is interesting. For example, a text editing view 4340 * should call this when its cursor moves. 4341 * 4342 * <p>When <code>immediate</code> is set to true, scrolling will not be 4343 * animated. 4344 * 4345 * @param rectangle The rectangle. 4346 * @param immediate True to forbid animated scrolling, false otherwise 4347 * @return Whether any parent scrolled. 4348 */ 4349 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4350 if (mAttachInfo == null) { 4351 return false; 4352 } 4353 4354 View child = this; 4355 4356 RectF position = mAttachInfo.mTmpTransformRect; 4357 position.set(rectangle); 4358 4359 ViewParent parent = mParent; 4360 boolean scrolled = false; 4361 while (parent != null) { 4362 rectangle.set((int) position.left, (int) position.top, 4363 (int) position.right, (int) position.bottom); 4364 4365 scrolled |= parent.requestChildRectangleOnScreen(child, 4366 rectangle, immediate); 4367 4368 if (!child.hasIdentityMatrix()) { 4369 child.getMatrix().mapRect(position); 4370 } 4371 4372 position.offset(child.mLeft, child.mTop); 4373 4374 if (!(parent instanceof View)) { 4375 break; 4376 } 4377 4378 View parentView = (View) parent; 4379 4380 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4381 4382 child = parentView; 4383 parent = child.getParent(); 4384 } 4385 4386 return scrolled; 4387 } 4388 4389 /** 4390 * Called when this view wants to give up focus. If focus is cleared 4391 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4392 * <p> 4393 * <strong>Note:</strong> When a View clears focus the framework is trying 4394 * to give focus to the first focusable View from the top. Hence, if this 4395 * View is the first from the top that can take focus, then all callbacks 4396 * related to clearing focus will be invoked after wich the framework will 4397 * give focus to this view. 4398 * </p> 4399 */ 4400 public void clearFocus() { 4401 if (DBG) { 4402 System.out.println(this + " clearFocus()"); 4403 } 4404 4405 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4406 mPrivateFlags &= ~PFLAG_FOCUSED; 4407 4408 if (mParent != null) { 4409 mParent.clearChildFocus(this); 4410 } 4411 4412 onFocusChanged(false, 0, null); 4413 4414 refreshDrawableState(); 4415 4416 ensureInputFocusOnFirstFocusable(); 4417 4418 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4419 notifyAccessibilityStateChanged(); 4420 } 4421 } 4422 } 4423 4424 void ensureInputFocusOnFirstFocusable() { 4425 View root = getRootView(); 4426 if (root != null) { 4427 root.requestFocus(); 4428 } 4429 } 4430 4431 /** 4432 * Called internally by the view system when a new view is getting focus. 4433 * This is what clears the old focus. 4434 */ 4435 void unFocus() { 4436 if (DBG) { 4437 System.out.println(this + " unFocus()"); 4438 } 4439 4440 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4441 mPrivateFlags &= ~PFLAG_FOCUSED; 4442 4443 onFocusChanged(false, 0, null); 4444 refreshDrawableState(); 4445 4446 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4447 notifyAccessibilityStateChanged(); 4448 } 4449 } 4450 } 4451 4452 /** 4453 * Returns true if this view has focus iteself, or is the ancestor of the 4454 * view that has focus. 4455 * 4456 * @return True if this view has or contains focus, false otherwise. 4457 */ 4458 @ViewDebug.ExportedProperty(category = "focus") 4459 public boolean hasFocus() { 4460 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4461 } 4462 4463 /** 4464 * Returns true if this view is focusable or if it contains a reachable View 4465 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4466 * is a View whose parents do not block descendants focus. 4467 * 4468 * Only {@link #VISIBLE} views are considered focusable. 4469 * 4470 * @return True if the view is focusable or if the view contains a focusable 4471 * View, false otherwise. 4472 * 4473 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4474 */ 4475 public boolean hasFocusable() { 4476 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4477 } 4478 4479 /** 4480 * Called by the view system when the focus state of this view changes. 4481 * When the focus change event is caused by directional navigation, direction 4482 * and previouslyFocusedRect provide insight into where the focus is coming from. 4483 * When overriding, be sure to call up through to the super class so that 4484 * the standard focus handling will occur. 4485 * 4486 * @param gainFocus True if the View has focus; false otherwise. 4487 * @param direction The direction focus has moved when requestFocus() 4488 * is called to give this view focus. Values are 4489 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4490 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4491 * It may not always apply, in which case use the default. 4492 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4493 * system, of the previously focused view. If applicable, this will be 4494 * passed in as finer grained information about where the focus is coming 4495 * from (in addition to direction). Will be <code>null</code> otherwise. 4496 */ 4497 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 4498 if (gainFocus) { 4499 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4500 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4501 } 4502 } 4503 4504 InputMethodManager imm = InputMethodManager.peekInstance(); 4505 if (!gainFocus) { 4506 if (isPressed()) { 4507 setPressed(false); 4508 } 4509 if (imm != null && mAttachInfo != null 4510 && mAttachInfo.mHasWindowFocus) { 4511 imm.focusOut(this); 4512 } 4513 onFocusLost(); 4514 } else if (imm != null && mAttachInfo != null 4515 && mAttachInfo.mHasWindowFocus) { 4516 imm.focusIn(this); 4517 } 4518 4519 invalidate(true); 4520 ListenerInfo li = mListenerInfo; 4521 if (li != null && li.mOnFocusChangeListener != null) { 4522 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 4523 } 4524 4525 if (mAttachInfo != null) { 4526 mAttachInfo.mKeyDispatchState.reset(this); 4527 } 4528 } 4529 4530 /** 4531 * Sends an accessibility event of the given type. If accessibility is 4532 * not enabled this method has no effect. The default implementation calls 4533 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 4534 * to populate information about the event source (this View), then calls 4535 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 4536 * populate the text content of the event source including its descendants, 4537 * and last calls 4538 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 4539 * on its parent to resuest sending of the event to interested parties. 4540 * <p> 4541 * If an {@link AccessibilityDelegate} has been specified via calling 4542 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4543 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 4544 * responsible for handling this call. 4545 * </p> 4546 * 4547 * @param eventType The type of the event to send, as defined by several types from 4548 * {@link android.view.accessibility.AccessibilityEvent}, such as 4549 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 4550 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 4551 * 4552 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4553 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4554 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 4555 * @see AccessibilityDelegate 4556 */ 4557 public void sendAccessibilityEvent(int eventType) { 4558 if (mAccessibilityDelegate != null) { 4559 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 4560 } else { 4561 sendAccessibilityEventInternal(eventType); 4562 } 4563 } 4564 4565 /** 4566 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 4567 * {@link AccessibilityEvent} to make an announcement which is related to some 4568 * sort of a context change for which none of the events representing UI transitions 4569 * is a good fit. For example, announcing a new page in a book. If accessibility 4570 * is not enabled this method does nothing. 4571 * 4572 * @param text The announcement text. 4573 */ 4574 public void announceForAccessibility(CharSequence text) { 4575 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 4576 AccessibilityEvent event = AccessibilityEvent.obtain( 4577 AccessibilityEvent.TYPE_ANNOUNCEMENT); 4578 onInitializeAccessibilityEvent(event); 4579 event.getText().add(text); 4580 event.setContentDescription(null); 4581 mParent.requestSendAccessibilityEvent(this, event); 4582 } 4583 } 4584 4585 /** 4586 * @see #sendAccessibilityEvent(int) 4587 * 4588 * Note: Called from the default {@link AccessibilityDelegate}. 4589 */ 4590 void sendAccessibilityEventInternal(int eventType) { 4591 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4592 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 4593 } 4594 } 4595 4596 /** 4597 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 4598 * takes as an argument an empty {@link AccessibilityEvent} and does not 4599 * perform a check whether accessibility is enabled. 4600 * <p> 4601 * If an {@link AccessibilityDelegate} has been specified via calling 4602 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4603 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 4604 * is responsible for handling this call. 4605 * </p> 4606 * 4607 * @param event The event to send. 4608 * 4609 * @see #sendAccessibilityEvent(int) 4610 */ 4611 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 4612 if (mAccessibilityDelegate != null) { 4613 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 4614 } else { 4615 sendAccessibilityEventUncheckedInternal(event); 4616 } 4617 } 4618 4619 /** 4620 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 4621 * 4622 * Note: Called from the default {@link AccessibilityDelegate}. 4623 */ 4624 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 4625 if (!isShown()) { 4626 return; 4627 } 4628 onInitializeAccessibilityEvent(event); 4629 // Only a subset of accessibility events populates text content. 4630 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4631 dispatchPopulateAccessibilityEvent(event); 4632 } 4633 // In the beginning we called #isShown(), so we know that getParent() is not null. 4634 getParent().requestSendAccessibilityEvent(this, event); 4635 } 4636 4637 /** 4638 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4639 * to its children for adding their text content to the event. Note that the 4640 * event text is populated in a separate dispatch path since we add to the 4641 * event not only the text of the source but also the text of all its descendants. 4642 * A typical implementation will call 4643 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4644 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4645 * on each child. Override this method if custom population of the event text 4646 * content is required. 4647 * <p> 4648 * If an {@link AccessibilityDelegate} has been specified via calling 4649 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4650 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4651 * is responsible for handling this call. 4652 * </p> 4653 * <p> 4654 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4655 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4656 * </p> 4657 * 4658 * @param event The event. 4659 * 4660 * @return True if the event population was completed. 4661 */ 4662 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4663 if (mAccessibilityDelegate != null) { 4664 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4665 } else { 4666 return dispatchPopulateAccessibilityEventInternal(event); 4667 } 4668 } 4669 4670 /** 4671 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4672 * 4673 * Note: Called from the default {@link AccessibilityDelegate}. 4674 */ 4675 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4676 onPopulateAccessibilityEvent(event); 4677 return false; 4678 } 4679 4680 /** 4681 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4682 * giving a chance to this View to populate the accessibility event with its 4683 * text content. While this method is free to modify event 4684 * attributes other than text content, doing so should normally be performed in 4685 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4686 * <p> 4687 * Example: Adding formatted date string to an accessibility event in addition 4688 * to the text added by the super implementation: 4689 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4690 * super.onPopulateAccessibilityEvent(event); 4691 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4692 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4693 * mCurrentDate.getTimeInMillis(), flags); 4694 * event.getText().add(selectedDateUtterance); 4695 * }</pre> 4696 * <p> 4697 * If an {@link AccessibilityDelegate} has been specified via calling 4698 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4699 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 4700 * is responsible for handling this call. 4701 * </p> 4702 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4703 * information to the event, in case the default implementation has basic information to add. 4704 * </p> 4705 * 4706 * @param event The accessibility event which to populate. 4707 * 4708 * @see #sendAccessibilityEvent(int) 4709 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4710 */ 4711 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4712 if (mAccessibilityDelegate != null) { 4713 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 4714 } else { 4715 onPopulateAccessibilityEventInternal(event); 4716 } 4717 } 4718 4719 /** 4720 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 4721 * 4722 * Note: Called from the default {@link AccessibilityDelegate}. 4723 */ 4724 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4725 4726 } 4727 4728 /** 4729 * Initializes an {@link AccessibilityEvent} with information about 4730 * this View which is the event source. In other words, the source of 4731 * an accessibility event is the view whose state change triggered firing 4732 * the event. 4733 * <p> 4734 * Example: Setting the password property of an event in addition 4735 * to properties set by the super implementation: 4736 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4737 * super.onInitializeAccessibilityEvent(event); 4738 * event.setPassword(true); 4739 * }</pre> 4740 * <p> 4741 * If an {@link AccessibilityDelegate} has been specified via calling 4742 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4743 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4744 * is responsible for handling this call. 4745 * </p> 4746 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4747 * information to the event, in case the default implementation has basic information to add. 4748 * </p> 4749 * @param event The event to initialize. 4750 * 4751 * @see #sendAccessibilityEvent(int) 4752 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4753 */ 4754 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4755 if (mAccessibilityDelegate != null) { 4756 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 4757 } else { 4758 onInitializeAccessibilityEventInternal(event); 4759 } 4760 } 4761 4762 /** 4763 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4764 * 4765 * Note: Called from the default {@link AccessibilityDelegate}. 4766 */ 4767 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 4768 event.setSource(this); 4769 event.setClassName(View.class.getName()); 4770 event.setPackageName(getContext().getPackageName()); 4771 event.setEnabled(isEnabled()); 4772 event.setContentDescription(mContentDescription); 4773 4774 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 4775 ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList; 4776 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 4777 FOCUSABLES_ALL); 4778 event.setItemCount(focusablesTempList.size()); 4779 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4780 focusablesTempList.clear(); 4781 } 4782 } 4783 4784 /** 4785 * Returns an {@link AccessibilityNodeInfo} representing this view from the 4786 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 4787 * This method is responsible for obtaining an accessibility node info from a 4788 * pool of reusable instances and calling 4789 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 4790 * initialize the former. 4791 * <p> 4792 * Note: The client is responsible for recycling the obtained instance by calling 4793 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4794 * </p> 4795 * 4796 * @return A populated {@link AccessibilityNodeInfo}. 4797 * 4798 * @see AccessibilityNodeInfo 4799 */ 4800 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4801 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 4802 if (provider != null) { 4803 return provider.createAccessibilityNodeInfo(View.NO_ID); 4804 } else { 4805 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4806 onInitializeAccessibilityNodeInfo(info); 4807 return info; 4808 } 4809 } 4810 4811 /** 4812 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4813 * The base implementation sets: 4814 * <ul> 4815 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4816 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4817 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4818 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4819 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4820 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4821 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4822 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4823 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4824 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4825 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4826 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4827 * </ul> 4828 * <p> 4829 * Subclasses should override this method, call the super implementation, 4830 * and set additional attributes. 4831 * </p> 4832 * <p> 4833 * If an {@link AccessibilityDelegate} has been specified via calling 4834 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4835 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 4836 * is responsible for handling this call. 4837 * </p> 4838 * 4839 * @param info The instance to initialize. 4840 */ 4841 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 4842 if (mAccessibilityDelegate != null) { 4843 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 4844 } else { 4845 onInitializeAccessibilityNodeInfoInternal(info); 4846 } 4847 } 4848 4849 /** 4850 * Gets the location of this view in screen coordintates. 4851 * 4852 * @param outRect The output location 4853 */ 4854 private void getBoundsOnScreen(Rect outRect) { 4855 if (mAttachInfo == null) { 4856 return; 4857 } 4858 4859 RectF position = mAttachInfo.mTmpTransformRect; 4860 position.set(0, 0, mRight - mLeft, mBottom - mTop); 4861 4862 if (!hasIdentityMatrix()) { 4863 getMatrix().mapRect(position); 4864 } 4865 4866 position.offset(mLeft, mTop); 4867 4868 ViewParent parent = mParent; 4869 while (parent instanceof View) { 4870 View parentView = (View) parent; 4871 4872 position.offset(-parentView.mScrollX, -parentView.mScrollY); 4873 4874 if (!parentView.hasIdentityMatrix()) { 4875 parentView.getMatrix().mapRect(position); 4876 } 4877 4878 position.offset(parentView.mLeft, parentView.mTop); 4879 4880 parent = parentView.mParent; 4881 } 4882 4883 if (parent instanceof ViewRootImpl) { 4884 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 4885 position.offset(0, -viewRootImpl.mCurScrollY); 4886 } 4887 4888 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 4889 4890 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 4891 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 4892 } 4893 4894 /** 4895 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 4896 * 4897 * Note: Called from the default {@link AccessibilityDelegate}. 4898 */ 4899 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 4900 Rect bounds = mAttachInfo.mTmpInvalRect; 4901 4902 getDrawingRect(bounds); 4903 info.setBoundsInParent(bounds); 4904 4905 getBoundsOnScreen(bounds); 4906 info.setBoundsInScreen(bounds); 4907 4908 ViewParent parent = getParentForAccessibility(); 4909 if (parent instanceof View) { 4910 info.setParent((View) parent); 4911 } 4912 4913 if (mID != View.NO_ID) { 4914 View rootView = getRootView(); 4915 if (rootView == null) { 4916 rootView = this; 4917 } 4918 View label = rootView.findLabelForView(this, mID); 4919 if (label != null) { 4920 info.setLabeledBy(label); 4921 } 4922 } 4923 4924 if (mLabelForId != View.NO_ID) { 4925 View rootView = getRootView(); 4926 if (rootView == null) { 4927 rootView = this; 4928 } 4929 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 4930 if (labeled != null) { 4931 info.setLabelFor(labeled); 4932 } 4933 } 4934 4935 info.setVisibleToUser(isVisibleToUser()); 4936 4937 info.setPackageName(mContext.getPackageName()); 4938 info.setClassName(View.class.getName()); 4939 info.setContentDescription(getContentDescription()); 4940 4941 info.setEnabled(isEnabled()); 4942 info.setClickable(isClickable()); 4943 info.setFocusable(isFocusable()); 4944 info.setFocused(isFocused()); 4945 info.setAccessibilityFocused(isAccessibilityFocused()); 4946 info.setSelected(isSelected()); 4947 info.setLongClickable(isLongClickable()); 4948 4949 // TODO: These make sense only if we are in an AdapterView but all 4950 // views can be selected. Maybe from accessibility perspective 4951 // we should report as selectable view in an AdapterView. 4952 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 4953 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 4954 4955 if (isFocusable()) { 4956 if (isFocused()) { 4957 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 4958 } else { 4959 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 4960 } 4961 } 4962 4963 if (!isAccessibilityFocused()) { 4964 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 4965 } else { 4966 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 4967 } 4968 4969 if (isClickable() && isEnabled()) { 4970 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 4971 } 4972 4973 if (isLongClickable() && isEnabled()) { 4974 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 4975 } 4976 4977 if (mContentDescription != null && mContentDescription.length() > 0) { 4978 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 4979 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 4980 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 4981 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 4982 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 4983 } 4984 } 4985 4986 private View findLabelForView(View view, int labeledId) { 4987 if (mMatchLabelForPredicate == null) { 4988 mMatchLabelForPredicate = new MatchLabelForPredicate(); 4989 } 4990 mMatchLabelForPredicate.mLabeledId = labeledId; 4991 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 4992 } 4993 4994 /** 4995 * Computes whether this view is visible to the user. Such a view is 4996 * attached, visible, all its predecessors are visible, it is not clipped 4997 * entirely by its predecessors, and has an alpha greater than zero. 4998 * 4999 * @return Whether the view is visible on the screen. 5000 * 5001 * @hide 5002 */ 5003 protected boolean isVisibleToUser() { 5004 return isVisibleToUser(null); 5005 } 5006 5007 /** 5008 * Computes whether the given portion of this view is visible to the user. 5009 * Such a view is attached, visible, all its predecessors are visible, 5010 * has an alpha greater than zero, and the specified portion is not 5011 * clipped entirely by its predecessors. 5012 * 5013 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5014 * <code>null</code>, and the entire view will be tested in this case. 5015 * When <code>true</code> is returned by the function, the actual visible 5016 * region will be stored in this parameter; that is, if boundInView is fully 5017 * contained within the view, no modification will be made, otherwise regions 5018 * outside of the visible area of the view will be clipped. 5019 * 5020 * @return Whether the specified portion of the view is visible on the screen. 5021 * 5022 * @hide 5023 */ 5024 protected boolean isVisibleToUser(Rect boundInView) { 5025 if (mAttachInfo != null) { 5026 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5027 Point offset = mAttachInfo.mPoint; 5028 // The first two checks are made also made by isShown() which 5029 // however traverses the tree up to the parent to catch that. 5030 // Therefore, we do some fail fast check to minimize the up 5031 // tree traversal. 5032 boolean isVisible = mAttachInfo.mWindowVisibility == View.VISIBLE 5033 && getAlpha() > 0 5034 && isShown() 5035 && getGlobalVisibleRect(visibleRect, offset); 5036 if (isVisible && boundInView != null) { 5037 visibleRect.offset(-offset.x, -offset.y); 5038 // isVisible is always true here, use a simple assignment 5039 isVisible = boundInView.intersect(visibleRect); 5040 } 5041 return isVisible; 5042 } 5043 5044 return false; 5045 } 5046 5047 /** 5048 * Returns the delegate for implementing accessibility support via 5049 * composition. For more details see {@link AccessibilityDelegate}. 5050 * 5051 * @return The delegate, or null if none set. 5052 * 5053 * @hide 5054 */ 5055 public AccessibilityDelegate getAccessibilityDelegate() { 5056 return mAccessibilityDelegate; 5057 } 5058 5059 /** 5060 * Sets a delegate for implementing accessibility support via composition as 5061 * opposed to inheritance. The delegate's primary use is for implementing 5062 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5063 * 5064 * @param delegate The delegate instance. 5065 * 5066 * @see AccessibilityDelegate 5067 */ 5068 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5069 mAccessibilityDelegate = delegate; 5070 } 5071 5072 /** 5073 * Gets the provider for managing a virtual view hierarchy rooted at this View 5074 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5075 * that explore the window content. 5076 * <p> 5077 * If this method returns an instance, this instance is responsible for managing 5078 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5079 * View including the one representing the View itself. Similarly the returned 5080 * instance is responsible for performing accessibility actions on any virtual 5081 * view or the root view itself. 5082 * </p> 5083 * <p> 5084 * If an {@link AccessibilityDelegate} has been specified via calling 5085 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5086 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5087 * is responsible for handling this call. 5088 * </p> 5089 * 5090 * @return The provider. 5091 * 5092 * @see AccessibilityNodeProvider 5093 */ 5094 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5095 if (mAccessibilityDelegate != null) { 5096 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5097 } else { 5098 return null; 5099 } 5100 } 5101 5102 /** 5103 * Gets the unique identifier of this view on the screen for accessibility purposes. 5104 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5105 * 5106 * @return The view accessibility id. 5107 * 5108 * @hide 5109 */ 5110 public int getAccessibilityViewId() { 5111 if (mAccessibilityViewId == NO_ID) { 5112 mAccessibilityViewId = sNextAccessibilityViewId++; 5113 } 5114 return mAccessibilityViewId; 5115 } 5116 5117 /** 5118 * Gets the unique identifier of the window in which this View reseides. 5119 * 5120 * @return The window accessibility id. 5121 * 5122 * @hide 5123 */ 5124 public int getAccessibilityWindowId() { 5125 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 5126 } 5127 5128 /** 5129 * Gets the {@link View} description. It briefly describes the view and is 5130 * primarily used for accessibility support. Set this property to enable 5131 * better accessibility support for your application. This is especially 5132 * true for views that do not have textual representation (For example, 5133 * ImageButton). 5134 * 5135 * @return The content description. 5136 * 5137 * @attr ref android.R.styleable#View_contentDescription 5138 */ 5139 @ViewDebug.ExportedProperty(category = "accessibility") 5140 public CharSequence getContentDescription() { 5141 return mContentDescription; 5142 } 5143 5144 /** 5145 * Sets the {@link View} description. It briefly describes the view and is 5146 * primarily used for accessibility support. Set this property to enable 5147 * better accessibility support for your application. This is especially 5148 * true for views that do not have textual representation (For example, 5149 * ImageButton). 5150 * 5151 * @param contentDescription The content description. 5152 * 5153 * @attr ref android.R.styleable#View_contentDescription 5154 */ 5155 @RemotableViewMethod 5156 public void setContentDescription(CharSequence contentDescription) { 5157 mContentDescription = contentDescription; 5158 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5159 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5160 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5161 } 5162 } 5163 5164 /** 5165 * Gets the id of a view for which this view serves as a label for 5166 * accessibility purposes. 5167 * 5168 * @return The labeled view id. 5169 */ 5170 @ViewDebug.ExportedProperty(category = "accessibility") 5171 public int getLabelFor() { 5172 return mLabelForId; 5173 } 5174 5175 /** 5176 * Sets the id of a view for which this view serves as a label for 5177 * accessibility purposes. 5178 * 5179 * @param id The labeled view id. 5180 */ 5181 @RemotableViewMethod 5182 public void setLabelFor(int id) { 5183 mLabelForId = id; 5184 if (mLabelForId != View.NO_ID 5185 && mID == View.NO_ID) { 5186 mID = generateViewId(); 5187 } 5188 } 5189 5190 /** 5191 * Invoked whenever this view loses focus, either by losing window focus or by losing 5192 * focus within its window. This method can be used to clear any state tied to the 5193 * focus. For instance, if a button is held pressed with the trackball and the window 5194 * loses focus, this method can be used to cancel the press. 5195 * 5196 * Subclasses of View overriding this method should always call super.onFocusLost(). 5197 * 5198 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5199 * @see #onWindowFocusChanged(boolean) 5200 * 5201 * @hide pending API council approval 5202 */ 5203 protected void onFocusLost() { 5204 resetPressedState(); 5205 } 5206 5207 private void resetPressedState() { 5208 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5209 return; 5210 } 5211 5212 if (isPressed()) { 5213 setPressed(false); 5214 5215 if (!mHasPerformedLongPress) { 5216 removeLongPressCallback(); 5217 } 5218 } 5219 } 5220 5221 /** 5222 * Returns true if this view has focus 5223 * 5224 * @return True if this view has focus, false otherwise. 5225 */ 5226 @ViewDebug.ExportedProperty(category = "focus") 5227 public boolean isFocused() { 5228 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5229 } 5230 5231 /** 5232 * Find the view in the hierarchy rooted at this view that currently has 5233 * focus. 5234 * 5235 * @return The view that currently has focus, or null if no focused view can 5236 * be found. 5237 */ 5238 public View findFocus() { 5239 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5240 } 5241 5242 /** 5243 * Indicates whether this view is one of the set of scrollable containers in 5244 * its window. 5245 * 5246 * @return whether this view is one of the set of scrollable containers in 5247 * its window 5248 * 5249 * @attr ref android.R.styleable#View_isScrollContainer 5250 */ 5251 public boolean isScrollContainer() { 5252 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5253 } 5254 5255 /** 5256 * Change whether this view is one of the set of scrollable containers in 5257 * its window. This will be used to determine whether the window can 5258 * resize or must pan when a soft input area is open -- scrollable 5259 * containers allow the window to use resize mode since the container 5260 * will appropriately shrink. 5261 * 5262 * @attr ref android.R.styleable#View_isScrollContainer 5263 */ 5264 public void setScrollContainer(boolean isScrollContainer) { 5265 if (isScrollContainer) { 5266 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5267 mAttachInfo.mScrollContainers.add(this); 5268 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5269 } 5270 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5271 } else { 5272 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5273 mAttachInfo.mScrollContainers.remove(this); 5274 } 5275 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5276 } 5277 } 5278 5279 /** 5280 * Returns the quality of the drawing cache. 5281 * 5282 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5283 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5284 * 5285 * @see #setDrawingCacheQuality(int) 5286 * @see #setDrawingCacheEnabled(boolean) 5287 * @see #isDrawingCacheEnabled() 5288 * 5289 * @attr ref android.R.styleable#View_drawingCacheQuality 5290 */ 5291 public int getDrawingCacheQuality() { 5292 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5293 } 5294 5295 /** 5296 * Set the drawing cache quality of this view. This value is used only when the 5297 * drawing cache is enabled 5298 * 5299 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5300 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5301 * 5302 * @see #getDrawingCacheQuality() 5303 * @see #setDrawingCacheEnabled(boolean) 5304 * @see #isDrawingCacheEnabled() 5305 * 5306 * @attr ref android.R.styleable#View_drawingCacheQuality 5307 */ 5308 public void setDrawingCacheQuality(int quality) { 5309 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5310 } 5311 5312 /** 5313 * Returns whether the screen should remain on, corresponding to the current 5314 * value of {@link #KEEP_SCREEN_ON}. 5315 * 5316 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5317 * 5318 * @see #setKeepScreenOn(boolean) 5319 * 5320 * @attr ref android.R.styleable#View_keepScreenOn 5321 */ 5322 public boolean getKeepScreenOn() { 5323 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5324 } 5325 5326 /** 5327 * Controls whether the screen should remain on, modifying the 5328 * value of {@link #KEEP_SCREEN_ON}. 5329 * 5330 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5331 * 5332 * @see #getKeepScreenOn() 5333 * 5334 * @attr ref android.R.styleable#View_keepScreenOn 5335 */ 5336 public void setKeepScreenOn(boolean keepScreenOn) { 5337 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5338 } 5339 5340 /** 5341 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5342 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5343 * 5344 * @attr ref android.R.styleable#View_nextFocusLeft 5345 */ 5346 public int getNextFocusLeftId() { 5347 return mNextFocusLeftId; 5348 } 5349 5350 /** 5351 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5352 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5353 * decide automatically. 5354 * 5355 * @attr ref android.R.styleable#View_nextFocusLeft 5356 */ 5357 public void setNextFocusLeftId(int nextFocusLeftId) { 5358 mNextFocusLeftId = nextFocusLeftId; 5359 } 5360 5361 /** 5362 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5363 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5364 * 5365 * @attr ref android.R.styleable#View_nextFocusRight 5366 */ 5367 public int getNextFocusRightId() { 5368 return mNextFocusRightId; 5369 } 5370 5371 /** 5372 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5373 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5374 * decide automatically. 5375 * 5376 * @attr ref android.R.styleable#View_nextFocusRight 5377 */ 5378 public void setNextFocusRightId(int nextFocusRightId) { 5379 mNextFocusRightId = nextFocusRightId; 5380 } 5381 5382 /** 5383 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5384 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5385 * 5386 * @attr ref android.R.styleable#View_nextFocusUp 5387 */ 5388 public int getNextFocusUpId() { 5389 return mNextFocusUpId; 5390 } 5391 5392 /** 5393 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5394 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5395 * decide automatically. 5396 * 5397 * @attr ref android.R.styleable#View_nextFocusUp 5398 */ 5399 public void setNextFocusUpId(int nextFocusUpId) { 5400 mNextFocusUpId = nextFocusUpId; 5401 } 5402 5403 /** 5404 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5405 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5406 * 5407 * @attr ref android.R.styleable#View_nextFocusDown 5408 */ 5409 public int getNextFocusDownId() { 5410 return mNextFocusDownId; 5411 } 5412 5413 /** 5414 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5415 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5416 * decide automatically. 5417 * 5418 * @attr ref android.R.styleable#View_nextFocusDown 5419 */ 5420 public void setNextFocusDownId(int nextFocusDownId) { 5421 mNextFocusDownId = nextFocusDownId; 5422 } 5423 5424 /** 5425 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5426 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5427 * 5428 * @attr ref android.R.styleable#View_nextFocusForward 5429 */ 5430 public int getNextFocusForwardId() { 5431 return mNextFocusForwardId; 5432 } 5433 5434 /** 5435 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5436 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 5437 * decide automatically. 5438 * 5439 * @attr ref android.R.styleable#View_nextFocusForward 5440 */ 5441 public void setNextFocusForwardId(int nextFocusForwardId) { 5442 mNextFocusForwardId = nextFocusForwardId; 5443 } 5444 5445 /** 5446 * Returns the visibility of this view and all of its ancestors 5447 * 5448 * @return True if this view and all of its ancestors are {@link #VISIBLE} 5449 */ 5450 public boolean isShown() { 5451 View current = this; 5452 //noinspection ConstantConditions 5453 do { 5454 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5455 return false; 5456 } 5457 ViewParent parent = current.mParent; 5458 if (parent == null) { 5459 return false; // We are not attached to the view root 5460 } 5461 if (!(parent instanceof View)) { 5462 return true; 5463 } 5464 current = (View) parent; 5465 } while (current != null); 5466 5467 return false; 5468 } 5469 5470 /** 5471 * Called by the view hierarchy when the content insets for a window have 5472 * changed, to allow it to adjust its content to fit within those windows. 5473 * The content insets tell you the space that the status bar, input method, 5474 * and other system windows infringe on the application's window. 5475 * 5476 * <p>You do not normally need to deal with this function, since the default 5477 * window decoration given to applications takes care of applying it to the 5478 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 5479 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 5480 * and your content can be placed under those system elements. You can then 5481 * use this method within your view hierarchy if you have parts of your UI 5482 * which you would like to ensure are not being covered. 5483 * 5484 * <p>The default implementation of this method simply applies the content 5485 * inset's to the view's padding, consuming that content (modifying the 5486 * insets to be 0), and returning true. This behavior is off by default, but can 5487 * be enabled through {@link #setFitsSystemWindows(boolean)}. 5488 * 5489 * <p>This function's traversal down the hierarchy is depth-first. The same content 5490 * insets object is propagated down the hierarchy, so any changes made to it will 5491 * be seen by all following views (including potentially ones above in 5492 * the hierarchy since this is a depth-first traversal). The first view 5493 * that returns true will abort the entire traversal. 5494 * 5495 * <p>The default implementation works well for a situation where it is 5496 * used with a container that covers the entire window, allowing it to 5497 * apply the appropriate insets to its content on all edges. If you need 5498 * a more complicated layout (such as two different views fitting system 5499 * windows, one on the top of the window, and one on the bottom), 5500 * you can override the method and handle the insets however you would like. 5501 * Note that the insets provided by the framework are always relative to the 5502 * far edges of the window, not accounting for the location of the called view 5503 * within that window. (In fact when this method is called you do not yet know 5504 * where the layout will place the view, as it is done before layout happens.) 5505 * 5506 * <p>Note: unlike many View methods, there is no dispatch phase to this 5507 * call. If you are overriding it in a ViewGroup and want to allow the 5508 * call to continue to your children, you must be sure to call the super 5509 * implementation. 5510 * 5511 * <p>Here is a sample layout that makes use of fitting system windows 5512 * to have controls for a video view placed inside of the window decorations 5513 * that it hides and shows. This can be used with code like the second 5514 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 5515 * 5516 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 5517 * 5518 * @param insets Current content insets of the window. Prior to 5519 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 5520 * the insets or else you and Android will be unhappy. 5521 * 5522 * @return Return true if this view applied the insets and it should not 5523 * continue propagating further down the hierarchy, false otherwise. 5524 * @see #getFitsSystemWindows() 5525 * @see #setFitsSystemWindows(boolean) 5526 * @see #setSystemUiVisibility(int) 5527 */ 5528 protected boolean fitSystemWindows(Rect insets) { 5529 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 5530 mUserPaddingStart = UNDEFINED_PADDING; 5531 mUserPaddingEnd = UNDEFINED_PADDING; 5532 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 5533 || mAttachInfo == null 5534 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 5535 internalSetPadding(insets.left, insets.top, insets.right, insets.bottom); 5536 return true; 5537 } else { 5538 internalSetPadding(0, 0, 0, 0); 5539 return false; 5540 } 5541 } 5542 return false; 5543 } 5544 5545 /** 5546 * Sets whether or not this view should account for system screen decorations 5547 * such as the status bar and inset its content; that is, controlling whether 5548 * the default implementation of {@link #fitSystemWindows(Rect)} will be 5549 * executed. See that method for more details. 5550 * 5551 * <p>Note that if you are providing your own implementation of 5552 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 5553 * flag to true -- your implementation will be overriding the default 5554 * implementation that checks this flag. 5555 * 5556 * @param fitSystemWindows If true, then the default implementation of 5557 * {@link #fitSystemWindows(Rect)} will be executed. 5558 * 5559 * @attr ref android.R.styleable#View_fitsSystemWindows 5560 * @see #getFitsSystemWindows() 5561 * @see #fitSystemWindows(Rect) 5562 * @see #setSystemUiVisibility(int) 5563 */ 5564 public void setFitsSystemWindows(boolean fitSystemWindows) { 5565 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 5566 } 5567 5568 /** 5569 * Check for state of {@link #setFitsSystemWindows(boolean). If this method 5570 * returns true, the default implementation of {@link #fitSystemWindows(Rect)} 5571 * will be executed. 5572 * 5573 * @return Returns true if the default implementation of 5574 * {@link #fitSystemWindows(Rect)} will be executed. 5575 * 5576 * @attr ref android.R.styleable#View_fitsSystemWindows 5577 * @see #setFitsSystemWindows() 5578 * @see #fitSystemWindows(Rect) 5579 * @see #setSystemUiVisibility(int) 5580 */ 5581 public boolean getFitsSystemWindows() { 5582 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 5583 } 5584 5585 /** @hide */ 5586 public boolean fitsSystemWindows() { 5587 return getFitsSystemWindows(); 5588 } 5589 5590 /** 5591 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 5592 */ 5593 public void requestFitSystemWindows() { 5594 if (mParent != null) { 5595 mParent.requestFitSystemWindows(); 5596 } 5597 } 5598 5599 /** 5600 * For use by PhoneWindow to make its own system window fitting optional. 5601 * @hide 5602 */ 5603 public void makeOptionalFitsSystemWindows() { 5604 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 5605 } 5606 5607 /** 5608 * Returns the visibility status for this view. 5609 * 5610 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5611 * @attr ref android.R.styleable#View_visibility 5612 */ 5613 @ViewDebug.ExportedProperty(mapping = { 5614 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 5615 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 5616 @ViewDebug.IntToString(from = GONE, to = "GONE") 5617 }) 5618 public int getVisibility() { 5619 return mViewFlags & VISIBILITY_MASK; 5620 } 5621 5622 /** 5623 * Set the enabled state of this view. 5624 * 5625 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5626 * @attr ref android.R.styleable#View_visibility 5627 */ 5628 @RemotableViewMethod 5629 public void setVisibility(int visibility) { 5630 setFlags(visibility, VISIBILITY_MASK); 5631 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 5632 } 5633 5634 /** 5635 * Returns the enabled status for this view. The interpretation of the 5636 * enabled state varies by subclass. 5637 * 5638 * @return True if this view is enabled, false otherwise. 5639 */ 5640 @ViewDebug.ExportedProperty 5641 public boolean isEnabled() { 5642 return (mViewFlags & ENABLED_MASK) == ENABLED; 5643 } 5644 5645 /** 5646 * Set the enabled state of this view. The interpretation of the enabled 5647 * state varies by subclass. 5648 * 5649 * @param enabled True if this view is enabled, false otherwise. 5650 */ 5651 @RemotableViewMethod 5652 public void setEnabled(boolean enabled) { 5653 if (enabled == isEnabled()) return; 5654 5655 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 5656 5657 /* 5658 * The View most likely has to change its appearance, so refresh 5659 * the drawable state. 5660 */ 5661 refreshDrawableState(); 5662 5663 // Invalidate too, since the default behavior for views is to be 5664 // be drawn at 50% alpha rather than to change the drawable. 5665 invalidate(true); 5666 } 5667 5668 /** 5669 * Set whether this view can receive the focus. 5670 * 5671 * Setting this to false will also ensure that this view is not focusable 5672 * in touch mode. 5673 * 5674 * @param focusable If true, this view can receive the focus. 5675 * 5676 * @see #setFocusableInTouchMode(boolean) 5677 * @attr ref android.R.styleable#View_focusable 5678 */ 5679 public void setFocusable(boolean focusable) { 5680 if (!focusable) { 5681 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 5682 } 5683 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 5684 } 5685 5686 /** 5687 * Set whether this view can receive focus while in touch mode. 5688 * 5689 * Setting this to true will also ensure that this view is focusable. 5690 * 5691 * @param focusableInTouchMode If true, this view can receive the focus while 5692 * in touch mode. 5693 * 5694 * @see #setFocusable(boolean) 5695 * @attr ref android.R.styleable#View_focusableInTouchMode 5696 */ 5697 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 5698 // Focusable in touch mode should always be set before the focusable flag 5699 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 5700 // which, in touch mode, will not successfully request focus on this view 5701 // because the focusable in touch mode flag is not set 5702 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 5703 if (focusableInTouchMode) { 5704 setFlags(FOCUSABLE, FOCUSABLE_MASK); 5705 } 5706 } 5707 5708 /** 5709 * Set whether this view should have sound effects enabled for events such as 5710 * clicking and touching. 5711 * 5712 * <p>You may wish to disable sound effects for a view if you already play sounds, 5713 * for instance, a dial key that plays dtmf tones. 5714 * 5715 * @param soundEffectsEnabled whether sound effects are enabled for this view. 5716 * @see #isSoundEffectsEnabled() 5717 * @see #playSoundEffect(int) 5718 * @attr ref android.R.styleable#View_soundEffectsEnabled 5719 */ 5720 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 5721 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 5722 } 5723 5724 /** 5725 * @return whether this view should have sound effects enabled for events such as 5726 * clicking and touching. 5727 * 5728 * @see #setSoundEffectsEnabled(boolean) 5729 * @see #playSoundEffect(int) 5730 * @attr ref android.R.styleable#View_soundEffectsEnabled 5731 */ 5732 @ViewDebug.ExportedProperty 5733 public boolean isSoundEffectsEnabled() { 5734 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 5735 } 5736 5737 /** 5738 * Set whether this view should have haptic feedback for events such as 5739 * long presses. 5740 * 5741 * <p>You may wish to disable haptic feedback if your view already controls 5742 * its own haptic feedback. 5743 * 5744 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 5745 * @see #isHapticFeedbackEnabled() 5746 * @see #performHapticFeedback(int) 5747 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5748 */ 5749 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 5750 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 5751 } 5752 5753 /** 5754 * @return whether this view should have haptic feedback enabled for events 5755 * long presses. 5756 * 5757 * @see #setHapticFeedbackEnabled(boolean) 5758 * @see #performHapticFeedback(int) 5759 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5760 */ 5761 @ViewDebug.ExportedProperty 5762 public boolean isHapticFeedbackEnabled() { 5763 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 5764 } 5765 5766 /** 5767 * Returns the layout direction for this view. 5768 * 5769 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 5770 * {@link #LAYOUT_DIRECTION_RTL}, 5771 * {@link #LAYOUT_DIRECTION_INHERIT} or 5772 * {@link #LAYOUT_DIRECTION_LOCALE}. 5773 * @attr ref android.R.styleable#View_layoutDirection 5774 */ 5775 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5776 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 5777 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 5778 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 5779 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 5780 }) 5781 public int getLayoutDirection() { 5782 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 5783 } 5784 5785 /** 5786 * Set the layout direction for this view. This will propagate a reset of layout direction 5787 * resolution to the view's children and resolve layout direction for this view. 5788 * 5789 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 5790 * {@link #LAYOUT_DIRECTION_RTL}, 5791 * {@link #LAYOUT_DIRECTION_INHERIT} or 5792 * {@link #LAYOUT_DIRECTION_LOCALE}. 5793 * 5794 * @attr ref android.R.styleable#View_layoutDirection 5795 */ 5796 @RemotableViewMethod 5797 public void setLayoutDirection(int layoutDirection) { 5798 if (getLayoutDirection() != layoutDirection) { 5799 // Reset the current layout direction and the resolved one 5800 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 5801 resetResolvedLayoutDirection(); 5802 // Reset padding resolution 5803 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 5804 // Set the new layout direction (filtered) 5805 mPrivateFlags2 |= 5806 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 5807 resolveRtlProperties(); 5808 // ... and ask for a layout pass 5809 requestLayout(); 5810 } 5811 } 5812 5813 /** 5814 * Returns the resolved layout direction for this view. 5815 * 5816 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 5817 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 5818 */ 5819 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5820 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 5821 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 5822 }) 5823 public int getResolvedLayoutDirection() { 5824 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 5825 if (targetSdkVersion < JELLY_BEAN_MR1) { 5826 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 5827 return LAYOUT_DIRECTION_LTR; 5828 } 5829 // The layout direction will be resolved only if needed 5830 if ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) != PFLAG2_LAYOUT_DIRECTION_RESOLVED) { 5831 resolveLayoutDirection(); 5832 } 5833 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? 5834 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 5835 } 5836 5837 /** 5838 * Indicates whether or not this view's layout is right-to-left. This is resolved from 5839 * layout attribute and/or the inherited value from the parent 5840 * 5841 * @return true if the layout is right-to-left. 5842 */ 5843 @ViewDebug.ExportedProperty(category = "layout") 5844 public boolean isLayoutRtl() { 5845 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 5846 } 5847 5848 /** 5849 * Indicates whether the view is currently tracking transient state that the 5850 * app should not need to concern itself with saving and restoring, but that 5851 * the framework should take special note to preserve when possible. 5852 * 5853 * <p>A view with transient state cannot be trivially rebound from an external 5854 * data source, such as an adapter binding item views in a list. This may be 5855 * because the view is performing an animation, tracking user selection 5856 * of content, or similar.</p> 5857 * 5858 * @return true if the view has transient state 5859 */ 5860 @ViewDebug.ExportedProperty(category = "layout") 5861 public boolean hasTransientState() { 5862 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 5863 } 5864 5865 /** 5866 * Set whether this view is currently tracking transient state that the 5867 * framework should attempt to preserve when possible. This flag is reference counted, 5868 * so every call to setHasTransientState(true) should be paired with a later call 5869 * to setHasTransientState(false). 5870 * 5871 * <p>A view with transient state cannot be trivially rebound from an external 5872 * data source, such as an adapter binding item views in a list. This may be 5873 * because the view is performing an animation, tracking user selection 5874 * of content, or similar.</p> 5875 * 5876 * @param hasTransientState true if this view has transient state 5877 */ 5878 public void setHasTransientState(boolean hasTransientState) { 5879 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 5880 mTransientStateCount - 1; 5881 if (mTransientStateCount < 0) { 5882 mTransientStateCount = 0; 5883 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 5884 "unmatched pair of setHasTransientState calls"); 5885 } 5886 if ((hasTransientState && mTransientStateCount == 1) || 5887 (!hasTransientState && mTransientStateCount == 0)) { 5888 // update flag if we've just incremented up from 0 or decremented down to 0 5889 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 5890 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 5891 if (mParent != null) { 5892 try { 5893 mParent.childHasTransientStateChanged(this, hasTransientState); 5894 } catch (AbstractMethodError e) { 5895 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 5896 " does not fully implement ViewParent", e); 5897 } 5898 } 5899 } 5900 } 5901 5902 /** 5903 * If this view doesn't do any drawing on its own, set this flag to 5904 * allow further optimizations. By default, this flag is not set on 5905 * View, but could be set on some View subclasses such as ViewGroup. 5906 * 5907 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 5908 * you should clear this flag. 5909 * 5910 * @param willNotDraw whether or not this View draw on its own 5911 */ 5912 public void setWillNotDraw(boolean willNotDraw) { 5913 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 5914 } 5915 5916 /** 5917 * Returns whether or not this View draws on its own. 5918 * 5919 * @return true if this view has nothing to draw, false otherwise 5920 */ 5921 @ViewDebug.ExportedProperty(category = "drawing") 5922 public boolean willNotDraw() { 5923 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 5924 } 5925 5926 /** 5927 * When a View's drawing cache is enabled, drawing is redirected to an 5928 * offscreen bitmap. Some views, like an ImageView, must be able to 5929 * bypass this mechanism if they already draw a single bitmap, to avoid 5930 * unnecessary usage of the memory. 5931 * 5932 * @param willNotCacheDrawing true if this view does not cache its 5933 * drawing, false otherwise 5934 */ 5935 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 5936 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 5937 } 5938 5939 /** 5940 * Returns whether or not this View can cache its drawing or not. 5941 * 5942 * @return true if this view does not cache its drawing, false otherwise 5943 */ 5944 @ViewDebug.ExportedProperty(category = "drawing") 5945 public boolean willNotCacheDrawing() { 5946 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 5947 } 5948 5949 /** 5950 * Indicates whether this view reacts to click events or not. 5951 * 5952 * @return true if the view is clickable, false otherwise 5953 * 5954 * @see #setClickable(boolean) 5955 * @attr ref android.R.styleable#View_clickable 5956 */ 5957 @ViewDebug.ExportedProperty 5958 public boolean isClickable() { 5959 return (mViewFlags & CLICKABLE) == CLICKABLE; 5960 } 5961 5962 /** 5963 * Enables or disables click events for this view. When a view 5964 * is clickable it will change its state to "pressed" on every click. 5965 * Subclasses should set the view clickable to visually react to 5966 * user's clicks. 5967 * 5968 * @param clickable true to make the view clickable, false otherwise 5969 * 5970 * @see #isClickable() 5971 * @attr ref android.R.styleable#View_clickable 5972 */ 5973 public void setClickable(boolean clickable) { 5974 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 5975 } 5976 5977 /** 5978 * Indicates whether this view reacts to long click events or not. 5979 * 5980 * @return true if the view is long clickable, false otherwise 5981 * 5982 * @see #setLongClickable(boolean) 5983 * @attr ref android.R.styleable#View_longClickable 5984 */ 5985 public boolean isLongClickable() { 5986 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 5987 } 5988 5989 /** 5990 * Enables or disables long click events for this view. When a view is long 5991 * clickable it reacts to the user holding down the button for a longer 5992 * duration than a tap. This event can either launch the listener or a 5993 * context menu. 5994 * 5995 * @param longClickable true to make the view long clickable, false otherwise 5996 * @see #isLongClickable() 5997 * @attr ref android.R.styleable#View_longClickable 5998 */ 5999 public void setLongClickable(boolean longClickable) { 6000 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6001 } 6002 6003 /** 6004 * Sets the pressed state for this view. 6005 * 6006 * @see #isClickable() 6007 * @see #setClickable(boolean) 6008 * 6009 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6010 * the View's internal state from a previously set "pressed" state. 6011 */ 6012 public void setPressed(boolean pressed) { 6013 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6014 6015 if (pressed) { 6016 mPrivateFlags |= PFLAG_PRESSED; 6017 } else { 6018 mPrivateFlags &= ~PFLAG_PRESSED; 6019 } 6020 6021 if (needsRefresh) { 6022 refreshDrawableState(); 6023 } 6024 dispatchSetPressed(pressed); 6025 } 6026 6027 /** 6028 * Dispatch setPressed to all of this View's children. 6029 * 6030 * @see #setPressed(boolean) 6031 * 6032 * @param pressed The new pressed state 6033 */ 6034 protected void dispatchSetPressed(boolean pressed) { 6035 } 6036 6037 /** 6038 * Indicates whether the view is currently in pressed state. Unless 6039 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6040 * the pressed state. 6041 * 6042 * @see #setPressed(boolean) 6043 * @see #isClickable() 6044 * @see #setClickable(boolean) 6045 * 6046 * @return true if the view is currently pressed, false otherwise 6047 */ 6048 public boolean isPressed() { 6049 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6050 } 6051 6052 /** 6053 * Indicates whether this view will save its state (that is, 6054 * whether its {@link #onSaveInstanceState} method will be called). 6055 * 6056 * @return Returns true if the view state saving is enabled, else false. 6057 * 6058 * @see #setSaveEnabled(boolean) 6059 * @attr ref android.R.styleable#View_saveEnabled 6060 */ 6061 public boolean isSaveEnabled() { 6062 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6063 } 6064 6065 /** 6066 * Controls whether the saving of this view's state is 6067 * enabled (that is, whether its {@link #onSaveInstanceState} method 6068 * will be called). Note that even if freezing is enabled, the 6069 * view still must have an id assigned to it (via {@link #setId(int)}) 6070 * for its state to be saved. This flag can only disable the 6071 * saving of this view; any child views may still have their state saved. 6072 * 6073 * @param enabled Set to false to <em>disable</em> state saving, or true 6074 * (the default) to allow it. 6075 * 6076 * @see #isSaveEnabled() 6077 * @see #setId(int) 6078 * @see #onSaveInstanceState() 6079 * @attr ref android.R.styleable#View_saveEnabled 6080 */ 6081 public void setSaveEnabled(boolean enabled) { 6082 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6083 } 6084 6085 /** 6086 * Gets whether the framework should discard touches when the view's 6087 * window is obscured by another visible window. 6088 * Refer to the {@link View} security documentation for more details. 6089 * 6090 * @return True if touch filtering is enabled. 6091 * 6092 * @see #setFilterTouchesWhenObscured(boolean) 6093 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6094 */ 6095 @ViewDebug.ExportedProperty 6096 public boolean getFilterTouchesWhenObscured() { 6097 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6098 } 6099 6100 /** 6101 * Sets whether the framework should discard touches when the view's 6102 * window is obscured by another visible window. 6103 * Refer to the {@link View} security documentation for more details. 6104 * 6105 * @param enabled True if touch filtering should be enabled. 6106 * 6107 * @see #getFilterTouchesWhenObscured 6108 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6109 */ 6110 public void setFilterTouchesWhenObscured(boolean enabled) { 6111 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 6112 FILTER_TOUCHES_WHEN_OBSCURED); 6113 } 6114 6115 /** 6116 * Indicates whether the entire hierarchy under this view will save its 6117 * state when a state saving traversal occurs from its parent. The default 6118 * is true; if false, these views will not be saved unless 6119 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6120 * 6121 * @return Returns true if the view state saving from parent is enabled, else false. 6122 * 6123 * @see #setSaveFromParentEnabled(boolean) 6124 */ 6125 public boolean isSaveFromParentEnabled() { 6126 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6127 } 6128 6129 /** 6130 * Controls whether the entire hierarchy under this view will save its 6131 * state when a state saving traversal occurs from its parent. The default 6132 * is true; if false, these views will not be saved unless 6133 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6134 * 6135 * @param enabled Set to false to <em>disable</em> state saving, or true 6136 * (the default) to allow it. 6137 * 6138 * @see #isSaveFromParentEnabled() 6139 * @see #setId(int) 6140 * @see #onSaveInstanceState() 6141 */ 6142 public void setSaveFromParentEnabled(boolean enabled) { 6143 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6144 } 6145 6146 6147 /** 6148 * Returns whether this View is able to take focus. 6149 * 6150 * @return True if this view can take focus, or false otherwise. 6151 * @attr ref android.R.styleable#View_focusable 6152 */ 6153 @ViewDebug.ExportedProperty(category = "focus") 6154 public final boolean isFocusable() { 6155 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6156 } 6157 6158 /** 6159 * When a view is focusable, it may not want to take focus when in touch mode. 6160 * For example, a button would like focus when the user is navigating via a D-pad 6161 * so that the user can click on it, but once the user starts touching the screen, 6162 * the button shouldn't take focus 6163 * @return Whether the view is focusable in touch mode. 6164 * @attr ref android.R.styleable#View_focusableInTouchMode 6165 */ 6166 @ViewDebug.ExportedProperty 6167 public final boolean isFocusableInTouchMode() { 6168 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6169 } 6170 6171 /** 6172 * Find the nearest view in the specified direction that can take focus. 6173 * This does not actually give focus to that view. 6174 * 6175 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6176 * 6177 * @return The nearest focusable in the specified direction, or null if none 6178 * can be found. 6179 */ 6180 public View focusSearch(int direction) { 6181 if (mParent != null) { 6182 return mParent.focusSearch(this, direction); 6183 } else { 6184 return null; 6185 } 6186 } 6187 6188 /** 6189 * This method is the last chance for the focused view and its ancestors to 6190 * respond to an arrow key. This is called when the focused view did not 6191 * consume the key internally, nor could the view system find a new view in 6192 * the requested direction to give focus to. 6193 * 6194 * @param focused The currently focused view. 6195 * @param direction The direction focus wants to move. One of FOCUS_UP, 6196 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6197 * @return True if the this view consumed this unhandled move. 6198 */ 6199 public boolean dispatchUnhandledMove(View focused, int direction) { 6200 return false; 6201 } 6202 6203 /** 6204 * If a user manually specified the next view id for a particular direction, 6205 * use the root to look up the view. 6206 * @param root The root view of the hierarchy containing this view. 6207 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6208 * or FOCUS_BACKWARD. 6209 * @return The user specified next view, or null if there is none. 6210 */ 6211 View findUserSetNextFocus(View root, int direction) { 6212 switch (direction) { 6213 case FOCUS_LEFT: 6214 if (mNextFocusLeftId == View.NO_ID) return null; 6215 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6216 case FOCUS_RIGHT: 6217 if (mNextFocusRightId == View.NO_ID) return null; 6218 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6219 case FOCUS_UP: 6220 if (mNextFocusUpId == View.NO_ID) return null; 6221 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6222 case FOCUS_DOWN: 6223 if (mNextFocusDownId == View.NO_ID) return null; 6224 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6225 case FOCUS_FORWARD: 6226 if (mNextFocusForwardId == View.NO_ID) return null; 6227 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6228 case FOCUS_BACKWARD: { 6229 if (mID == View.NO_ID) return null; 6230 final int id = mID; 6231 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6232 @Override 6233 public boolean apply(View t) { 6234 return t.mNextFocusForwardId == id; 6235 } 6236 }); 6237 } 6238 } 6239 return null; 6240 } 6241 6242 private View findViewInsideOutShouldExist(View root, int id) { 6243 if (mMatchIdPredicate == null) { 6244 mMatchIdPredicate = new MatchIdPredicate(); 6245 } 6246 mMatchIdPredicate.mId = id; 6247 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6248 if (result == null) { 6249 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6250 } 6251 return result; 6252 } 6253 6254 /** 6255 * Find and return all focusable views that are descendants of this view, 6256 * possibly including this view if it is focusable itself. 6257 * 6258 * @param direction The direction of the focus 6259 * @return A list of focusable views 6260 */ 6261 public ArrayList<View> getFocusables(int direction) { 6262 ArrayList<View> result = new ArrayList<View>(24); 6263 addFocusables(result, direction); 6264 return result; 6265 } 6266 6267 /** 6268 * Add any focusable views that are descendants of this view (possibly 6269 * including this view if it is focusable itself) to views. If we are in touch mode, 6270 * only add views that are also focusable in touch mode. 6271 * 6272 * @param views Focusable views found so far 6273 * @param direction The direction of the focus 6274 */ 6275 public void addFocusables(ArrayList<View> views, int direction) { 6276 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6277 } 6278 6279 /** 6280 * Adds any focusable views that are descendants of this view (possibly 6281 * including this view if it is focusable itself) to views. This method 6282 * adds all focusable views regardless if we are in touch mode or 6283 * only views focusable in touch mode if we are in touch mode or 6284 * only views that can take accessibility focus if accessibility is enabeld 6285 * depending on the focusable mode paramater. 6286 * 6287 * @param views Focusable views found so far or null if all we are interested is 6288 * the number of focusables. 6289 * @param direction The direction of the focus. 6290 * @param focusableMode The type of focusables to be added. 6291 * 6292 * @see #FOCUSABLES_ALL 6293 * @see #FOCUSABLES_TOUCH_MODE 6294 */ 6295 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 6296 if (views == null) { 6297 return; 6298 } 6299 if (!isFocusable()) { 6300 return; 6301 } 6302 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6303 && isInTouchMode() && !isFocusableInTouchMode()) { 6304 return; 6305 } 6306 views.add(this); 6307 } 6308 6309 /** 6310 * Finds the Views that contain given text. The containment is case insensitive. 6311 * The search is performed by either the text that the View renders or the content 6312 * description that describes the view for accessibility purposes and the view does 6313 * not render or both. Clients can specify how the search is to be performed via 6314 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 6315 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 6316 * 6317 * @param outViews The output list of matching Views. 6318 * @param searched The text to match against. 6319 * 6320 * @see #FIND_VIEWS_WITH_TEXT 6321 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 6322 * @see #setContentDescription(CharSequence) 6323 */ 6324 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 6325 if (getAccessibilityNodeProvider() != null) { 6326 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 6327 outViews.add(this); 6328 } 6329 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 6330 && (searched != null && searched.length() > 0) 6331 && (mContentDescription != null && mContentDescription.length() > 0)) { 6332 String searchedLowerCase = searched.toString().toLowerCase(); 6333 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 6334 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 6335 outViews.add(this); 6336 } 6337 } 6338 } 6339 6340 /** 6341 * Find and return all touchable views that are descendants of this view, 6342 * possibly including this view if it is touchable itself. 6343 * 6344 * @return A list of touchable views 6345 */ 6346 public ArrayList<View> getTouchables() { 6347 ArrayList<View> result = new ArrayList<View>(); 6348 addTouchables(result); 6349 return result; 6350 } 6351 6352 /** 6353 * Add any touchable views that are descendants of this view (possibly 6354 * including this view if it is touchable itself) to views. 6355 * 6356 * @param views Touchable views found so far 6357 */ 6358 public void addTouchables(ArrayList<View> views) { 6359 final int viewFlags = mViewFlags; 6360 6361 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 6362 && (viewFlags & ENABLED_MASK) == ENABLED) { 6363 views.add(this); 6364 } 6365 } 6366 6367 /** 6368 * Returns whether this View is accessibility focused. 6369 * 6370 * @return True if this View is accessibility focused. 6371 */ 6372 boolean isAccessibilityFocused() { 6373 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 6374 } 6375 6376 /** 6377 * Call this to try to give accessibility focus to this view. 6378 * 6379 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 6380 * returns false or the view is no visible or the view already has accessibility 6381 * focus. 6382 * 6383 * See also {@link #focusSearch(int)}, which is what you call to say that you 6384 * have focus, and you want your parent to look for the next one. 6385 * 6386 * @return Whether this view actually took accessibility focus. 6387 * 6388 * @hide 6389 */ 6390 public boolean requestAccessibilityFocus() { 6391 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 6392 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 6393 return false; 6394 } 6395 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6396 return false; 6397 } 6398 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 6399 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 6400 ViewRootImpl viewRootImpl = getViewRootImpl(); 6401 if (viewRootImpl != null) { 6402 viewRootImpl.setAccessibilityFocus(this, null); 6403 } 6404 if (mAttachInfo != null) { 6405 Rect rectangle = mAttachInfo.mTmpInvalRect; 6406 getDrawingRect(rectangle); 6407 requestRectangleOnScreen(rectangle); 6408 } 6409 invalidate(); 6410 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 6411 notifyAccessibilityStateChanged(); 6412 return true; 6413 } 6414 return false; 6415 } 6416 6417 /** 6418 * Call this to try to clear accessibility focus of this view. 6419 * 6420 * See also {@link #focusSearch(int)}, which is what you call to say that you 6421 * have focus, and you want your parent to look for the next one. 6422 * 6423 * @hide 6424 */ 6425 public void clearAccessibilityFocus() { 6426 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6427 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6428 invalidate(); 6429 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 6430 notifyAccessibilityStateChanged(); 6431 } 6432 // Clear the global reference of accessibility focus if this 6433 // view or any of its descendants had accessibility focus. 6434 ViewRootImpl viewRootImpl = getViewRootImpl(); 6435 if (viewRootImpl != null) { 6436 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 6437 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 6438 viewRootImpl.setAccessibilityFocus(null, null); 6439 } 6440 } 6441 } 6442 6443 private void sendAccessibilityHoverEvent(int eventType) { 6444 // Since we are not delivering to a client accessibility events from not 6445 // important views (unless the clinet request that) we need to fire the 6446 // event from the deepest view exposed to the client. As a consequence if 6447 // the user crosses a not exposed view the client will see enter and exit 6448 // of the exposed predecessor followed by and enter and exit of that same 6449 // predecessor when entering and exiting the not exposed descendant. This 6450 // is fine since the client has a clear idea which view is hovered at the 6451 // price of a couple more events being sent. This is a simple and 6452 // working solution. 6453 View source = this; 6454 while (true) { 6455 if (source.includeForAccessibility()) { 6456 source.sendAccessibilityEvent(eventType); 6457 return; 6458 } 6459 ViewParent parent = source.getParent(); 6460 if (parent instanceof View) { 6461 source = (View) parent; 6462 } else { 6463 return; 6464 } 6465 } 6466 } 6467 6468 /** 6469 * Clears accessibility focus without calling any callback methods 6470 * normally invoked in {@link #clearAccessibilityFocus()}. This method 6471 * is used for clearing accessibility focus when giving this focus to 6472 * another view. 6473 */ 6474 void clearAccessibilityFocusNoCallbacks() { 6475 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6476 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6477 invalidate(); 6478 } 6479 } 6480 6481 /** 6482 * Call this to try to give focus to a specific view or to one of its 6483 * descendants. 6484 * 6485 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6486 * false), or if it is focusable and it is not focusable in touch mode 6487 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6488 * 6489 * See also {@link #focusSearch(int)}, which is what you call to say that you 6490 * have focus, and you want your parent to look for the next one. 6491 * 6492 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 6493 * {@link #FOCUS_DOWN} and <code>null</code>. 6494 * 6495 * @return Whether this view or one of its descendants actually took focus. 6496 */ 6497 public final boolean requestFocus() { 6498 return requestFocus(View.FOCUS_DOWN); 6499 } 6500 6501 /** 6502 * Call this to try to give focus to a specific view or to one of its 6503 * descendants and give it a hint about what direction focus is heading. 6504 * 6505 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6506 * false), or if it is focusable and it is not focusable in touch mode 6507 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6508 * 6509 * See also {@link #focusSearch(int)}, which is what you call to say that you 6510 * have focus, and you want your parent to look for the next one. 6511 * 6512 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 6513 * <code>null</code> set for the previously focused rectangle. 6514 * 6515 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6516 * @return Whether this view or one of its descendants actually took focus. 6517 */ 6518 public final boolean requestFocus(int direction) { 6519 return requestFocus(direction, null); 6520 } 6521 6522 /** 6523 * Call this to try to give focus to a specific view or to one of its descendants 6524 * and give it hints about the direction and a specific rectangle that the focus 6525 * is coming from. The rectangle can help give larger views a finer grained hint 6526 * about where focus is coming from, and therefore, where to show selection, or 6527 * forward focus change internally. 6528 * 6529 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6530 * false), or if it is focusable and it is not focusable in touch mode 6531 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6532 * 6533 * A View will not take focus if it is not visible. 6534 * 6535 * A View will not take focus if one of its parents has 6536 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 6537 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 6538 * 6539 * See also {@link #focusSearch(int)}, which is what you call to say that you 6540 * have focus, and you want your parent to look for the next one. 6541 * 6542 * You may wish to override this method if your custom {@link View} has an internal 6543 * {@link View} that it wishes to forward the request to. 6544 * 6545 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6546 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 6547 * to give a finer grained hint about where focus is coming from. May be null 6548 * if there is no hint. 6549 * @return Whether this view or one of its descendants actually took focus. 6550 */ 6551 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 6552 return requestFocusNoSearch(direction, previouslyFocusedRect); 6553 } 6554 6555 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 6556 // need to be focusable 6557 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 6558 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6559 return false; 6560 } 6561 6562 // need to be focusable in touch mode if in touch mode 6563 if (isInTouchMode() && 6564 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 6565 return false; 6566 } 6567 6568 // need to not have any parents blocking us 6569 if (hasAncestorThatBlocksDescendantFocus()) { 6570 return false; 6571 } 6572 6573 handleFocusGainInternal(direction, previouslyFocusedRect); 6574 return true; 6575 } 6576 6577 /** 6578 * Call this to try to give focus to a specific view or to one of its descendants. This is a 6579 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 6580 * touch mode to request focus when they are touched. 6581 * 6582 * @return Whether this view or one of its descendants actually took focus. 6583 * 6584 * @see #isInTouchMode() 6585 * 6586 */ 6587 public final boolean requestFocusFromTouch() { 6588 // Leave touch mode if we need to 6589 if (isInTouchMode()) { 6590 ViewRootImpl viewRoot = getViewRootImpl(); 6591 if (viewRoot != null) { 6592 viewRoot.ensureTouchMode(false); 6593 } 6594 } 6595 return requestFocus(View.FOCUS_DOWN); 6596 } 6597 6598 /** 6599 * @return Whether any ancestor of this view blocks descendant focus. 6600 */ 6601 private boolean hasAncestorThatBlocksDescendantFocus() { 6602 ViewParent ancestor = mParent; 6603 while (ancestor instanceof ViewGroup) { 6604 final ViewGroup vgAncestor = (ViewGroup) ancestor; 6605 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 6606 return true; 6607 } else { 6608 ancestor = vgAncestor.getParent(); 6609 } 6610 } 6611 return false; 6612 } 6613 6614 /** 6615 * Gets the mode for determining whether this View is important for accessibility 6616 * which is if it fires accessibility events and if it is reported to 6617 * accessibility services that query the screen. 6618 * 6619 * @return The mode for determining whether a View is important for accessibility. 6620 * 6621 * @attr ref android.R.styleable#View_importantForAccessibility 6622 * 6623 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6624 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6625 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6626 */ 6627 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 6628 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 6629 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 6630 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no") 6631 }) 6632 public int getImportantForAccessibility() { 6633 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6634 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6635 } 6636 6637 /** 6638 * Sets how to determine whether this view is important for accessibility 6639 * which is if it fires accessibility events and if it is reported to 6640 * accessibility services that query the screen. 6641 * 6642 * @param mode How to determine whether this view is important for accessibility. 6643 * 6644 * @attr ref android.R.styleable#View_importantForAccessibility 6645 * 6646 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6647 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6648 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6649 */ 6650 public void setImportantForAccessibility(int mode) { 6651 if (mode != getImportantForAccessibility()) { 6652 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6653 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 6654 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6655 notifyAccessibilityStateChanged(); 6656 } 6657 } 6658 6659 /** 6660 * Gets whether this view should be exposed for accessibility. 6661 * 6662 * @return Whether the view is exposed for accessibility. 6663 * 6664 * @hide 6665 */ 6666 public boolean isImportantForAccessibility() { 6667 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6668 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6669 switch (mode) { 6670 case IMPORTANT_FOR_ACCESSIBILITY_YES: 6671 return true; 6672 case IMPORTANT_FOR_ACCESSIBILITY_NO: 6673 return false; 6674 case IMPORTANT_FOR_ACCESSIBILITY_AUTO: 6675 return isActionableForAccessibility() || hasListenersForAccessibility() 6676 || getAccessibilityNodeProvider() != null; 6677 default: 6678 throw new IllegalArgumentException("Unknow important for accessibility mode: " 6679 + mode); 6680 } 6681 } 6682 6683 /** 6684 * Gets the parent for accessibility purposes. Note that the parent for 6685 * accessibility is not necessary the immediate parent. It is the first 6686 * predecessor that is important for accessibility. 6687 * 6688 * @return The parent for accessibility purposes. 6689 */ 6690 public ViewParent getParentForAccessibility() { 6691 if (mParent instanceof View) { 6692 View parentView = (View) mParent; 6693 if (parentView.includeForAccessibility()) { 6694 return mParent; 6695 } else { 6696 return mParent.getParentForAccessibility(); 6697 } 6698 } 6699 return null; 6700 } 6701 6702 /** 6703 * Adds the children of a given View for accessibility. Since some Views are 6704 * not important for accessibility the children for accessibility are not 6705 * necessarily direct children of the riew, rather they are the first level of 6706 * descendants important for accessibility. 6707 * 6708 * @param children The list of children for accessibility. 6709 */ 6710 public void addChildrenForAccessibility(ArrayList<View> children) { 6711 if (includeForAccessibility()) { 6712 children.add(this); 6713 } 6714 } 6715 6716 /** 6717 * Whether to regard this view for accessibility. A view is regarded for 6718 * accessibility if it is important for accessibility or the querying 6719 * accessibility service has explicitly requested that view not 6720 * important for accessibility are regarded. 6721 * 6722 * @return Whether to regard the view for accessibility. 6723 * 6724 * @hide 6725 */ 6726 public boolean includeForAccessibility() { 6727 if (mAttachInfo != null) { 6728 return mAttachInfo.mIncludeNotImportantViews || isImportantForAccessibility(); 6729 } 6730 return false; 6731 } 6732 6733 /** 6734 * Returns whether the View is considered actionable from 6735 * accessibility perspective. Such view are important for 6736 * accessibility. 6737 * 6738 * @return True if the view is actionable for accessibility. 6739 * 6740 * @hide 6741 */ 6742 public boolean isActionableForAccessibility() { 6743 return (isClickable() || isLongClickable() || isFocusable()); 6744 } 6745 6746 /** 6747 * Returns whether the View has registered callbacks wich makes it 6748 * important for accessibility. 6749 * 6750 * @return True if the view is actionable for accessibility. 6751 */ 6752 private boolean hasListenersForAccessibility() { 6753 ListenerInfo info = getListenerInfo(); 6754 return mTouchDelegate != null || info.mOnKeyListener != null 6755 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 6756 || info.mOnHoverListener != null || info.mOnDragListener != null; 6757 } 6758 6759 /** 6760 * Notifies accessibility services that some view's important for 6761 * accessibility state has changed. Note that such notifications 6762 * are made at most once every 6763 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 6764 * to avoid unnecessary load to the system. Also once a view has 6765 * made a notifucation this method is a NOP until the notification has 6766 * been sent to clients. 6767 * 6768 * @hide 6769 * 6770 * TODO: Makse sure this method is called for any view state change 6771 * that is interesting for accessilility purposes. 6772 */ 6773 public void notifyAccessibilityStateChanged() { 6774 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 6775 return; 6776 } 6777 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) { 6778 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED; 6779 if (mParent != null) { 6780 mParent.childAccessibilityStateChanged(this); 6781 } 6782 } 6783 } 6784 6785 /** 6786 * Reset the state indicating the this view has requested clients 6787 * interested in its accessibility state to be notified. 6788 * 6789 * @hide 6790 */ 6791 public void resetAccessibilityStateChanged() { 6792 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED; 6793 } 6794 6795 /** 6796 * Performs the specified accessibility action on the view. For 6797 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 6798 * <p> 6799 * If an {@link AccessibilityDelegate} has been specified via calling 6800 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6801 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 6802 * is responsible for handling this call. 6803 * </p> 6804 * 6805 * @param action The action to perform. 6806 * @param arguments Optional action arguments. 6807 * @return Whether the action was performed. 6808 */ 6809 public boolean performAccessibilityAction(int action, Bundle arguments) { 6810 if (mAccessibilityDelegate != null) { 6811 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 6812 } else { 6813 return performAccessibilityActionInternal(action, arguments); 6814 } 6815 } 6816 6817 /** 6818 * @see #performAccessibilityAction(int, Bundle) 6819 * 6820 * Note: Called from the default {@link AccessibilityDelegate}. 6821 */ 6822 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 6823 switch (action) { 6824 case AccessibilityNodeInfo.ACTION_CLICK: { 6825 if (isClickable()) { 6826 return performClick(); 6827 } 6828 } break; 6829 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 6830 if (isLongClickable()) { 6831 return performLongClick(); 6832 } 6833 } break; 6834 case AccessibilityNodeInfo.ACTION_FOCUS: { 6835 if (!hasFocus()) { 6836 // Get out of touch mode since accessibility 6837 // wants to move focus around. 6838 getViewRootImpl().ensureTouchMode(false); 6839 return requestFocus(); 6840 } 6841 } break; 6842 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 6843 if (hasFocus()) { 6844 clearFocus(); 6845 return !isFocused(); 6846 } 6847 } break; 6848 case AccessibilityNodeInfo.ACTION_SELECT: { 6849 if (!isSelected()) { 6850 setSelected(true); 6851 return isSelected(); 6852 } 6853 } break; 6854 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 6855 if (isSelected()) { 6856 setSelected(false); 6857 return !isSelected(); 6858 } 6859 } break; 6860 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 6861 if (!isAccessibilityFocused()) { 6862 return requestAccessibilityFocus(); 6863 } 6864 } break; 6865 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 6866 if (isAccessibilityFocused()) { 6867 clearAccessibilityFocus(); 6868 return true; 6869 } 6870 } break; 6871 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 6872 if (arguments != null) { 6873 final int granularity = arguments.getInt( 6874 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 6875 return nextAtGranularity(granularity); 6876 } 6877 } break; 6878 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 6879 if (arguments != null) { 6880 final int granularity = arguments.getInt( 6881 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 6882 return previousAtGranularity(granularity); 6883 } 6884 } break; 6885 } 6886 return false; 6887 } 6888 6889 private boolean nextAtGranularity(int granularity) { 6890 CharSequence text = getIterableTextForAccessibility(); 6891 if (text == null || text.length() == 0) { 6892 return false; 6893 } 6894 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 6895 if (iterator == null) { 6896 return false; 6897 } 6898 final int current = getAccessibilityCursorPosition(); 6899 final int[] range = iterator.following(current); 6900 if (range == null) { 6901 return false; 6902 } 6903 final int start = range[0]; 6904 final int end = range[1]; 6905 setAccessibilityCursorPosition(end); 6906 sendViewTextTraversedAtGranularityEvent( 6907 AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, 6908 granularity, start, end); 6909 return true; 6910 } 6911 6912 private boolean previousAtGranularity(int granularity) { 6913 CharSequence text = getIterableTextForAccessibility(); 6914 if (text == null || text.length() == 0) { 6915 return false; 6916 } 6917 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 6918 if (iterator == null) { 6919 return false; 6920 } 6921 int current = getAccessibilityCursorPosition(); 6922 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 6923 current = text.length(); 6924 } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) { 6925 // When traversing by character we always put the cursor after the character 6926 // to ease edit and have to compensate before asking the for previous segment. 6927 current--; 6928 } 6929 final int[] range = iterator.preceding(current); 6930 if (range == null) { 6931 return false; 6932 } 6933 final int start = range[0]; 6934 final int end = range[1]; 6935 // Always put the cursor after the character to ease edit. 6936 if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) { 6937 setAccessibilityCursorPosition(end); 6938 } else { 6939 setAccessibilityCursorPosition(start); 6940 } 6941 sendViewTextTraversedAtGranularityEvent( 6942 AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, 6943 granularity, start, end); 6944 return true; 6945 } 6946 6947 /** 6948 * Gets the text reported for accessibility purposes. 6949 * 6950 * @return The accessibility text. 6951 * 6952 * @hide 6953 */ 6954 public CharSequence getIterableTextForAccessibility() { 6955 return getContentDescription(); 6956 } 6957 6958 /** 6959 * @hide 6960 */ 6961 public int getAccessibilityCursorPosition() { 6962 return mAccessibilityCursorPosition; 6963 } 6964 6965 /** 6966 * @hide 6967 */ 6968 public void setAccessibilityCursorPosition(int position) { 6969 mAccessibilityCursorPosition = position; 6970 } 6971 6972 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 6973 int fromIndex, int toIndex) { 6974 if (mParent == null) { 6975 return; 6976 } 6977 AccessibilityEvent event = AccessibilityEvent.obtain( 6978 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 6979 onInitializeAccessibilityEvent(event); 6980 onPopulateAccessibilityEvent(event); 6981 event.setFromIndex(fromIndex); 6982 event.setToIndex(toIndex); 6983 event.setAction(action); 6984 event.setMovementGranularity(granularity); 6985 mParent.requestSendAccessibilityEvent(this, event); 6986 } 6987 6988 /** 6989 * @hide 6990 */ 6991 public TextSegmentIterator getIteratorForGranularity(int granularity) { 6992 switch (granularity) { 6993 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 6994 CharSequence text = getIterableTextForAccessibility(); 6995 if (text != null && text.length() > 0) { 6996 CharacterTextSegmentIterator iterator = 6997 CharacterTextSegmentIterator.getInstance( 6998 mContext.getResources().getConfiguration().locale); 6999 iterator.initialize(text.toString()); 7000 return iterator; 7001 } 7002 } break; 7003 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7004 CharSequence text = getIterableTextForAccessibility(); 7005 if (text != null && text.length() > 0) { 7006 WordTextSegmentIterator iterator = 7007 WordTextSegmentIterator.getInstance( 7008 mContext.getResources().getConfiguration().locale); 7009 iterator.initialize(text.toString()); 7010 return iterator; 7011 } 7012 } break; 7013 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7014 CharSequence text = getIterableTextForAccessibility(); 7015 if (text != null && text.length() > 0) { 7016 ParagraphTextSegmentIterator iterator = 7017 ParagraphTextSegmentIterator.getInstance(); 7018 iterator.initialize(text.toString()); 7019 return iterator; 7020 } 7021 } break; 7022 } 7023 return null; 7024 } 7025 7026 /** 7027 * @hide 7028 */ 7029 public void dispatchStartTemporaryDetach() { 7030 clearAccessibilityFocus(); 7031 clearDisplayList(); 7032 7033 onStartTemporaryDetach(); 7034 } 7035 7036 /** 7037 * This is called when a container is going to temporarily detach a child, with 7038 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7039 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7040 * {@link #onDetachedFromWindow()} when the container is done. 7041 */ 7042 public void onStartTemporaryDetach() { 7043 removeUnsetPressCallback(); 7044 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7045 } 7046 7047 /** 7048 * @hide 7049 */ 7050 public void dispatchFinishTemporaryDetach() { 7051 onFinishTemporaryDetach(); 7052 } 7053 7054 /** 7055 * Called after {@link #onStartTemporaryDetach} when the container is done 7056 * changing the view. 7057 */ 7058 public void onFinishTemporaryDetach() { 7059 } 7060 7061 /** 7062 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7063 * for this view's window. Returns null if the view is not currently attached 7064 * to the window. Normally you will not need to use this directly, but 7065 * just use the standard high-level event callbacks like 7066 * {@link #onKeyDown(int, KeyEvent)}. 7067 */ 7068 public KeyEvent.DispatcherState getKeyDispatcherState() { 7069 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7070 } 7071 7072 /** 7073 * Dispatch a key event before it is processed by any input method 7074 * associated with the view hierarchy. This can be used to intercept 7075 * key events in special situations before the IME consumes them; a 7076 * typical example would be handling the BACK key to update the application's 7077 * UI instead of allowing the IME to see it and close itself. 7078 * 7079 * @param event The key event to be dispatched. 7080 * @return True if the event was handled, false otherwise. 7081 */ 7082 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7083 return onKeyPreIme(event.getKeyCode(), event); 7084 } 7085 7086 /** 7087 * Dispatch a key event to the next view on the focus path. This path runs 7088 * from the top of the view tree down to the currently focused view. If this 7089 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7090 * the next node down the focus path. This method also fires any key 7091 * listeners. 7092 * 7093 * @param event The key event to be dispatched. 7094 * @return True if the event was handled, false otherwise. 7095 */ 7096 public boolean dispatchKeyEvent(KeyEvent event) { 7097 if (mInputEventConsistencyVerifier != null) { 7098 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7099 } 7100 7101 // Give any attached key listener a first crack at the event. 7102 //noinspection SimplifiableIfStatement 7103 ListenerInfo li = mListenerInfo; 7104 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7105 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7106 return true; 7107 } 7108 7109 if (event.dispatch(this, mAttachInfo != null 7110 ? mAttachInfo.mKeyDispatchState : null, this)) { 7111 return true; 7112 } 7113 7114 if (mInputEventConsistencyVerifier != null) { 7115 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7116 } 7117 return false; 7118 } 7119 7120 /** 7121 * Dispatches a key shortcut event. 7122 * 7123 * @param event The key event to be dispatched. 7124 * @return True if the event was handled by the view, false otherwise. 7125 */ 7126 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 7127 return onKeyShortcut(event.getKeyCode(), event); 7128 } 7129 7130 /** 7131 * Pass the touch screen motion event down to the target view, or this 7132 * view if it is the target. 7133 * 7134 * @param event The motion event to be dispatched. 7135 * @return True if the event was handled by the view, false otherwise. 7136 */ 7137 public boolean dispatchTouchEvent(MotionEvent event) { 7138 if (mInputEventConsistencyVerifier != null) { 7139 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 7140 } 7141 7142 if (onFilterTouchEventForSecurity(event)) { 7143 //noinspection SimplifiableIfStatement 7144 ListenerInfo li = mListenerInfo; 7145 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7146 && li.mOnTouchListener.onTouch(this, event)) { 7147 return true; 7148 } 7149 7150 if (onTouchEvent(event)) { 7151 return true; 7152 } 7153 } 7154 7155 if (mInputEventConsistencyVerifier != null) { 7156 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7157 } 7158 return false; 7159 } 7160 7161 /** 7162 * Filter the touch event to apply security policies. 7163 * 7164 * @param event The motion event to be filtered. 7165 * @return True if the event should be dispatched, false if the event should be dropped. 7166 * 7167 * @see #getFilterTouchesWhenObscured 7168 */ 7169 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 7170 //noinspection RedundantIfStatement 7171 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 7172 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 7173 // Window is obscured, drop this touch. 7174 return false; 7175 } 7176 return true; 7177 } 7178 7179 /** 7180 * Pass a trackball motion event down to the focused view. 7181 * 7182 * @param event The motion event to be dispatched. 7183 * @return True if the event was handled by the view, false otherwise. 7184 */ 7185 public boolean dispatchTrackballEvent(MotionEvent event) { 7186 if (mInputEventConsistencyVerifier != null) { 7187 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 7188 } 7189 7190 return onTrackballEvent(event); 7191 } 7192 7193 /** 7194 * Dispatch a generic motion event. 7195 * <p> 7196 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7197 * are delivered to the view under the pointer. All other generic motion events are 7198 * delivered to the focused view. Hover events are handled specially and are delivered 7199 * to {@link #onHoverEvent(MotionEvent)}. 7200 * </p> 7201 * 7202 * @param event The motion event to be dispatched. 7203 * @return True if the event was handled by the view, false otherwise. 7204 */ 7205 public boolean dispatchGenericMotionEvent(MotionEvent event) { 7206 if (mInputEventConsistencyVerifier != null) { 7207 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 7208 } 7209 7210 final int source = event.getSource(); 7211 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7212 final int action = event.getAction(); 7213 if (action == MotionEvent.ACTION_HOVER_ENTER 7214 || action == MotionEvent.ACTION_HOVER_MOVE 7215 || action == MotionEvent.ACTION_HOVER_EXIT) { 7216 if (dispatchHoverEvent(event)) { 7217 return true; 7218 } 7219 } else if (dispatchGenericPointerEvent(event)) { 7220 return true; 7221 } 7222 } else if (dispatchGenericFocusedEvent(event)) { 7223 return true; 7224 } 7225 7226 if (dispatchGenericMotionEventInternal(event)) { 7227 return true; 7228 } 7229 7230 if (mInputEventConsistencyVerifier != null) { 7231 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7232 } 7233 return false; 7234 } 7235 7236 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 7237 //noinspection SimplifiableIfStatement 7238 ListenerInfo li = mListenerInfo; 7239 if (li != null && li.mOnGenericMotionListener != null 7240 && (mViewFlags & ENABLED_MASK) == ENABLED 7241 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 7242 return true; 7243 } 7244 7245 if (onGenericMotionEvent(event)) { 7246 return true; 7247 } 7248 7249 if (mInputEventConsistencyVerifier != null) { 7250 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7251 } 7252 return false; 7253 } 7254 7255 /** 7256 * Dispatch a hover event. 7257 * <p> 7258 * Do not call this method directly. 7259 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7260 * </p> 7261 * 7262 * @param event The motion event to be dispatched. 7263 * @return True if the event was handled by the view, false otherwise. 7264 */ 7265 protected boolean dispatchHoverEvent(MotionEvent event) { 7266 //noinspection SimplifiableIfStatement 7267 ListenerInfo li = mListenerInfo; 7268 if (li != null && li.mOnHoverListener != null 7269 && (mViewFlags & ENABLED_MASK) == ENABLED 7270 && li.mOnHoverListener.onHover(this, event)) { 7271 return true; 7272 } 7273 7274 return onHoverEvent(event); 7275 } 7276 7277 /** 7278 * Returns true if the view has a child to which it has recently sent 7279 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 7280 * it does not have a hovered child, then it must be the innermost hovered view. 7281 * @hide 7282 */ 7283 protected boolean hasHoveredChild() { 7284 return false; 7285 } 7286 7287 /** 7288 * Dispatch a generic motion event to the view under the first pointer. 7289 * <p> 7290 * Do not call this method directly. 7291 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7292 * </p> 7293 * 7294 * @param event The motion event to be dispatched. 7295 * @return True if the event was handled by the view, false otherwise. 7296 */ 7297 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 7298 return false; 7299 } 7300 7301 /** 7302 * Dispatch a generic motion event to the currently focused view. 7303 * <p> 7304 * Do not call this method directly. 7305 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7306 * </p> 7307 * 7308 * @param event The motion event to be dispatched. 7309 * @return True if the event was handled by the view, false otherwise. 7310 */ 7311 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 7312 return false; 7313 } 7314 7315 /** 7316 * Dispatch a pointer event. 7317 * <p> 7318 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 7319 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 7320 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 7321 * and should not be expected to handle other pointing device features. 7322 * </p> 7323 * 7324 * @param event The motion event to be dispatched. 7325 * @return True if the event was handled by the view, false otherwise. 7326 * @hide 7327 */ 7328 public final boolean dispatchPointerEvent(MotionEvent event) { 7329 if (event.isTouchEvent()) { 7330 return dispatchTouchEvent(event); 7331 } else { 7332 return dispatchGenericMotionEvent(event); 7333 } 7334 } 7335 7336 /** 7337 * Called when the window containing this view gains or loses window focus. 7338 * ViewGroups should override to route to their children. 7339 * 7340 * @param hasFocus True if the window containing this view now has focus, 7341 * false otherwise. 7342 */ 7343 public void dispatchWindowFocusChanged(boolean hasFocus) { 7344 onWindowFocusChanged(hasFocus); 7345 } 7346 7347 /** 7348 * Called when the window containing this view gains or loses focus. Note 7349 * that this is separate from view focus: to receive key events, both 7350 * your view and its window must have focus. If a window is displayed 7351 * on top of yours that takes input focus, then your own window will lose 7352 * focus but the view focus will remain unchanged. 7353 * 7354 * @param hasWindowFocus True if the window containing this view now has 7355 * focus, false otherwise. 7356 */ 7357 public void onWindowFocusChanged(boolean hasWindowFocus) { 7358 InputMethodManager imm = InputMethodManager.peekInstance(); 7359 if (!hasWindowFocus) { 7360 if (isPressed()) { 7361 setPressed(false); 7362 } 7363 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7364 imm.focusOut(this); 7365 } 7366 removeLongPressCallback(); 7367 removeTapCallback(); 7368 onFocusLost(); 7369 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7370 imm.focusIn(this); 7371 } 7372 refreshDrawableState(); 7373 } 7374 7375 /** 7376 * Returns true if this view is in a window that currently has window focus. 7377 * Note that this is not the same as the view itself having focus. 7378 * 7379 * @return True if this view is in a window that currently has window focus. 7380 */ 7381 public boolean hasWindowFocus() { 7382 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 7383 } 7384 7385 /** 7386 * Dispatch a view visibility change down the view hierarchy. 7387 * ViewGroups should override to route to their children. 7388 * @param changedView The view whose visibility changed. Could be 'this' or 7389 * an ancestor view. 7390 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7391 * {@link #INVISIBLE} or {@link #GONE}. 7392 */ 7393 protected void dispatchVisibilityChanged(View changedView, int visibility) { 7394 onVisibilityChanged(changedView, visibility); 7395 } 7396 7397 /** 7398 * Called when the visibility of the view or an ancestor of the view is changed. 7399 * @param changedView The view whose visibility changed. Could be 'this' or 7400 * an ancestor view. 7401 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7402 * {@link #INVISIBLE} or {@link #GONE}. 7403 */ 7404 protected void onVisibilityChanged(View changedView, int visibility) { 7405 if (visibility == VISIBLE) { 7406 if (mAttachInfo != null) { 7407 initialAwakenScrollBars(); 7408 } else { 7409 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 7410 } 7411 } 7412 } 7413 7414 /** 7415 * Dispatch a hint about whether this view is displayed. For instance, when 7416 * a View moves out of the screen, it might receives a display hint indicating 7417 * the view is not displayed. Applications should not <em>rely</em> on this hint 7418 * as there is no guarantee that they will receive one. 7419 * 7420 * @param hint A hint about whether or not this view is displayed: 7421 * {@link #VISIBLE} or {@link #INVISIBLE}. 7422 */ 7423 public void dispatchDisplayHint(int hint) { 7424 onDisplayHint(hint); 7425 } 7426 7427 /** 7428 * Gives this view a hint about whether is displayed or not. For instance, when 7429 * a View moves out of the screen, it might receives a display hint indicating 7430 * the view is not displayed. Applications should not <em>rely</em> on this hint 7431 * as there is no guarantee that they will receive one. 7432 * 7433 * @param hint A hint about whether or not this view is displayed: 7434 * {@link #VISIBLE} or {@link #INVISIBLE}. 7435 */ 7436 protected void onDisplayHint(int hint) { 7437 } 7438 7439 /** 7440 * Dispatch a window visibility change down the view hierarchy. 7441 * ViewGroups should override to route to their children. 7442 * 7443 * @param visibility The new visibility of the window. 7444 * 7445 * @see #onWindowVisibilityChanged(int) 7446 */ 7447 public void dispatchWindowVisibilityChanged(int visibility) { 7448 onWindowVisibilityChanged(visibility); 7449 } 7450 7451 /** 7452 * Called when the window containing has change its visibility 7453 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 7454 * that this tells you whether or not your window is being made visible 7455 * to the window manager; this does <em>not</em> tell you whether or not 7456 * your window is obscured by other windows on the screen, even if it 7457 * is itself visible. 7458 * 7459 * @param visibility The new visibility of the window. 7460 */ 7461 protected void onWindowVisibilityChanged(int visibility) { 7462 if (visibility == VISIBLE) { 7463 initialAwakenScrollBars(); 7464 } 7465 } 7466 7467 /** 7468 * Returns the current visibility of the window this view is attached to 7469 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 7470 * 7471 * @return Returns the current visibility of the view's window. 7472 */ 7473 public int getWindowVisibility() { 7474 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 7475 } 7476 7477 /** 7478 * Retrieve the overall visible display size in which the window this view is 7479 * attached to has been positioned in. This takes into account screen 7480 * decorations above the window, for both cases where the window itself 7481 * is being position inside of them or the window is being placed under 7482 * then and covered insets are used for the window to position its content 7483 * inside. In effect, this tells you the available area where content can 7484 * be placed and remain visible to users. 7485 * 7486 * <p>This function requires an IPC back to the window manager to retrieve 7487 * the requested information, so should not be used in performance critical 7488 * code like drawing. 7489 * 7490 * @param outRect Filled in with the visible display frame. If the view 7491 * is not attached to a window, this is simply the raw display size. 7492 */ 7493 public void getWindowVisibleDisplayFrame(Rect outRect) { 7494 if (mAttachInfo != null) { 7495 try { 7496 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 7497 } catch (RemoteException e) { 7498 return; 7499 } 7500 // XXX This is really broken, and probably all needs to be done 7501 // in the window manager, and we need to know more about whether 7502 // we want the area behind or in front of the IME. 7503 final Rect insets = mAttachInfo.mVisibleInsets; 7504 outRect.left += insets.left; 7505 outRect.top += insets.top; 7506 outRect.right -= insets.right; 7507 outRect.bottom -= insets.bottom; 7508 return; 7509 } 7510 // The view is not attached to a display so we don't have a context. 7511 // Make a best guess about the display size. 7512 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 7513 d.getRectSize(outRect); 7514 } 7515 7516 /** 7517 * Dispatch a notification about a resource configuration change down 7518 * the view hierarchy. 7519 * ViewGroups should override to route to their children. 7520 * 7521 * @param newConfig The new resource configuration. 7522 * 7523 * @see #onConfigurationChanged(android.content.res.Configuration) 7524 */ 7525 public void dispatchConfigurationChanged(Configuration newConfig) { 7526 onConfigurationChanged(newConfig); 7527 } 7528 7529 /** 7530 * Called when the current configuration of the resources being used 7531 * by the application have changed. You can use this to decide when 7532 * to reload resources that can changed based on orientation and other 7533 * configuration characterstics. You only need to use this if you are 7534 * not relying on the normal {@link android.app.Activity} mechanism of 7535 * recreating the activity instance upon a configuration change. 7536 * 7537 * @param newConfig The new resource configuration. 7538 */ 7539 protected void onConfigurationChanged(Configuration newConfig) { 7540 } 7541 7542 /** 7543 * Private function to aggregate all per-view attributes in to the view 7544 * root. 7545 */ 7546 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7547 performCollectViewAttributes(attachInfo, visibility); 7548 } 7549 7550 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7551 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 7552 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 7553 attachInfo.mKeepScreenOn = true; 7554 } 7555 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 7556 ListenerInfo li = mListenerInfo; 7557 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 7558 attachInfo.mHasSystemUiListeners = true; 7559 } 7560 } 7561 } 7562 7563 void needGlobalAttributesUpdate(boolean force) { 7564 final AttachInfo ai = mAttachInfo; 7565 if (ai != null && !ai.mRecomputeGlobalAttributes) { 7566 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 7567 || ai.mHasSystemUiListeners) { 7568 ai.mRecomputeGlobalAttributes = true; 7569 } 7570 } 7571 } 7572 7573 /** 7574 * Returns whether the device is currently in touch mode. Touch mode is entered 7575 * once the user begins interacting with the device by touch, and affects various 7576 * things like whether focus is always visible to the user. 7577 * 7578 * @return Whether the device is in touch mode. 7579 */ 7580 @ViewDebug.ExportedProperty 7581 public boolean isInTouchMode() { 7582 if (mAttachInfo != null) { 7583 return mAttachInfo.mInTouchMode; 7584 } else { 7585 return ViewRootImpl.isInTouchMode(); 7586 } 7587 } 7588 7589 /** 7590 * Returns the context the view is running in, through which it can 7591 * access the current theme, resources, etc. 7592 * 7593 * @return The view's Context. 7594 */ 7595 @ViewDebug.CapturedViewProperty 7596 public final Context getContext() { 7597 return mContext; 7598 } 7599 7600 /** 7601 * Handle a key event before it is processed by any input method 7602 * associated with the view hierarchy. This can be used to intercept 7603 * key events in special situations before the IME consumes them; a 7604 * typical example would be handling the BACK key to update the application's 7605 * UI instead of allowing the IME to see it and close itself. 7606 * 7607 * @param keyCode The value in event.getKeyCode(). 7608 * @param event Description of the key event. 7609 * @return If you handled the event, return true. If you want to allow the 7610 * event to be handled by the next receiver, return false. 7611 */ 7612 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 7613 return false; 7614 } 7615 7616 /** 7617 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 7618 * KeyEvent.Callback.onKeyDown()}: perform press of the view 7619 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 7620 * is released, if the view is enabled and clickable. 7621 * 7622 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7623 * although some may elect to do so in some situations. Do not rely on this to 7624 * catch software key presses. 7625 * 7626 * @param keyCode A key code that represents the button pressed, from 7627 * {@link android.view.KeyEvent}. 7628 * @param event The KeyEvent object that defines the button action. 7629 */ 7630 public boolean onKeyDown(int keyCode, KeyEvent event) { 7631 boolean result = false; 7632 7633 switch (keyCode) { 7634 case KeyEvent.KEYCODE_DPAD_CENTER: 7635 case KeyEvent.KEYCODE_ENTER: { 7636 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7637 return true; 7638 } 7639 // Long clickable items don't necessarily have to be clickable 7640 if (((mViewFlags & CLICKABLE) == CLICKABLE || 7641 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 7642 (event.getRepeatCount() == 0)) { 7643 setPressed(true); 7644 checkForLongClick(0); 7645 return true; 7646 } 7647 break; 7648 } 7649 } 7650 return result; 7651 } 7652 7653 /** 7654 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 7655 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 7656 * the event). 7657 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7658 * although some may elect to do so in some situations. Do not rely on this to 7659 * catch software key presses. 7660 */ 7661 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 7662 return false; 7663 } 7664 7665 /** 7666 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 7667 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 7668 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 7669 * {@link KeyEvent#KEYCODE_ENTER} is released. 7670 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7671 * although some may elect to do so in some situations. Do not rely on this to 7672 * catch software key presses. 7673 * 7674 * @param keyCode A key code that represents the button pressed, from 7675 * {@link android.view.KeyEvent}. 7676 * @param event The KeyEvent object that defines the button action. 7677 */ 7678 public boolean onKeyUp(int keyCode, KeyEvent event) { 7679 boolean result = false; 7680 7681 switch (keyCode) { 7682 case KeyEvent.KEYCODE_DPAD_CENTER: 7683 case KeyEvent.KEYCODE_ENTER: { 7684 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7685 return true; 7686 } 7687 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 7688 setPressed(false); 7689 7690 if (!mHasPerformedLongPress) { 7691 // This is a tap, so remove the longpress check 7692 removeLongPressCallback(); 7693 7694 result = performClick(); 7695 } 7696 } 7697 break; 7698 } 7699 } 7700 return result; 7701 } 7702 7703 /** 7704 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 7705 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 7706 * the event). 7707 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7708 * although some may elect to do so in some situations. Do not rely on this to 7709 * catch software key presses. 7710 * 7711 * @param keyCode A key code that represents the button pressed, from 7712 * {@link android.view.KeyEvent}. 7713 * @param repeatCount The number of times the action was made. 7714 * @param event The KeyEvent object that defines the button action. 7715 */ 7716 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 7717 return false; 7718 } 7719 7720 /** 7721 * Called on the focused view when a key shortcut event is not handled. 7722 * Override this method to implement local key shortcuts for the View. 7723 * Key shortcuts can also be implemented by setting the 7724 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 7725 * 7726 * @param keyCode The value in event.getKeyCode(). 7727 * @param event Description of the key event. 7728 * @return If you handled the event, return true. If you want to allow the 7729 * event to be handled by the next receiver, return false. 7730 */ 7731 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 7732 return false; 7733 } 7734 7735 /** 7736 * Check whether the called view is a text editor, in which case it 7737 * would make sense to automatically display a soft input window for 7738 * it. Subclasses should override this if they implement 7739 * {@link #onCreateInputConnection(EditorInfo)} to return true if 7740 * a call on that method would return a non-null InputConnection, and 7741 * they are really a first-class editor that the user would normally 7742 * start typing on when the go into a window containing your view. 7743 * 7744 * <p>The default implementation always returns false. This does 7745 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 7746 * will not be called or the user can not otherwise perform edits on your 7747 * view; it is just a hint to the system that this is not the primary 7748 * purpose of this view. 7749 * 7750 * @return Returns true if this view is a text editor, else false. 7751 */ 7752 public boolean onCheckIsTextEditor() { 7753 return false; 7754 } 7755 7756 /** 7757 * Create a new InputConnection for an InputMethod to interact 7758 * with the view. The default implementation returns null, since it doesn't 7759 * support input methods. You can override this to implement such support. 7760 * This is only needed for views that take focus and text input. 7761 * 7762 * <p>When implementing this, you probably also want to implement 7763 * {@link #onCheckIsTextEditor()} to indicate you will return a 7764 * non-null InputConnection. 7765 * 7766 * @param outAttrs Fill in with attribute information about the connection. 7767 */ 7768 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 7769 return null; 7770 } 7771 7772 /** 7773 * Called by the {@link android.view.inputmethod.InputMethodManager} 7774 * when a view who is not the current 7775 * input connection target is trying to make a call on the manager. The 7776 * default implementation returns false; you can override this to return 7777 * true for certain views if you are performing InputConnection proxying 7778 * to them. 7779 * @param view The View that is making the InputMethodManager call. 7780 * @return Return true to allow the call, false to reject. 7781 */ 7782 public boolean checkInputConnectionProxy(View view) { 7783 return false; 7784 } 7785 7786 /** 7787 * Show the context menu for this view. It is not safe to hold on to the 7788 * menu after returning from this method. 7789 * 7790 * You should normally not overload this method. Overload 7791 * {@link #onCreateContextMenu(ContextMenu)} or define an 7792 * {@link OnCreateContextMenuListener} to add items to the context menu. 7793 * 7794 * @param menu The context menu to populate 7795 */ 7796 public void createContextMenu(ContextMenu menu) { 7797 ContextMenuInfo menuInfo = getContextMenuInfo(); 7798 7799 // Sets the current menu info so all items added to menu will have 7800 // my extra info set. 7801 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 7802 7803 onCreateContextMenu(menu); 7804 ListenerInfo li = mListenerInfo; 7805 if (li != null && li.mOnCreateContextMenuListener != null) { 7806 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 7807 } 7808 7809 // Clear the extra information so subsequent items that aren't mine don't 7810 // have my extra info. 7811 ((MenuBuilder)menu).setCurrentMenuInfo(null); 7812 7813 if (mParent != null) { 7814 mParent.createContextMenu(menu); 7815 } 7816 } 7817 7818 /** 7819 * Views should implement this if they have extra information to associate 7820 * with the context menu. The return result is supplied as a parameter to 7821 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 7822 * callback. 7823 * 7824 * @return Extra information about the item for which the context menu 7825 * should be shown. This information will vary across different 7826 * subclasses of View. 7827 */ 7828 protected ContextMenuInfo getContextMenuInfo() { 7829 return null; 7830 } 7831 7832 /** 7833 * Views should implement this if the view itself is going to add items to 7834 * the context menu. 7835 * 7836 * @param menu the context menu to populate 7837 */ 7838 protected void onCreateContextMenu(ContextMenu menu) { 7839 } 7840 7841 /** 7842 * Implement this method to handle trackball motion events. The 7843 * <em>relative</em> movement of the trackball since the last event 7844 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 7845 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 7846 * that a movement of 1 corresponds to the user pressing one DPAD key (so 7847 * they will often be fractional values, representing the more fine-grained 7848 * movement information available from a trackball). 7849 * 7850 * @param event The motion event. 7851 * @return True if the event was handled, false otherwise. 7852 */ 7853 public boolean onTrackballEvent(MotionEvent event) { 7854 return false; 7855 } 7856 7857 /** 7858 * Implement this method to handle generic motion events. 7859 * <p> 7860 * Generic motion events describe joystick movements, mouse hovers, track pad 7861 * touches, scroll wheel movements and other input events. The 7862 * {@link MotionEvent#getSource() source} of the motion event specifies 7863 * the class of input that was received. Implementations of this method 7864 * must examine the bits in the source before processing the event. 7865 * The following code example shows how this is done. 7866 * </p><p> 7867 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7868 * are delivered to the view under the pointer. All other generic motion events are 7869 * delivered to the focused view. 7870 * </p> 7871 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 7872 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 7873 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 7874 * // process the joystick movement... 7875 * return true; 7876 * } 7877 * } 7878 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7879 * switch (event.getAction()) { 7880 * case MotionEvent.ACTION_HOVER_MOVE: 7881 * // process the mouse hover movement... 7882 * return true; 7883 * case MotionEvent.ACTION_SCROLL: 7884 * // process the scroll wheel movement... 7885 * return true; 7886 * } 7887 * } 7888 * return super.onGenericMotionEvent(event); 7889 * }</pre> 7890 * 7891 * @param event The generic motion event being processed. 7892 * @return True if the event was handled, false otherwise. 7893 */ 7894 public boolean onGenericMotionEvent(MotionEvent event) { 7895 return false; 7896 } 7897 7898 /** 7899 * Implement this method to handle hover events. 7900 * <p> 7901 * This method is called whenever a pointer is hovering into, over, or out of the 7902 * bounds of a view and the view is not currently being touched. 7903 * Hover events are represented as pointer events with action 7904 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 7905 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 7906 * </p> 7907 * <ul> 7908 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 7909 * when the pointer enters the bounds of the view.</li> 7910 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 7911 * when the pointer has already entered the bounds of the view and has moved.</li> 7912 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 7913 * when the pointer has exited the bounds of the view or when the pointer is 7914 * about to go down due to a button click, tap, or similar user action that 7915 * causes the view to be touched.</li> 7916 * </ul> 7917 * <p> 7918 * The view should implement this method to return true to indicate that it is 7919 * handling the hover event, such as by changing its drawable state. 7920 * </p><p> 7921 * The default implementation calls {@link #setHovered} to update the hovered state 7922 * of the view when a hover enter or hover exit event is received, if the view 7923 * is enabled and is clickable. The default implementation also sends hover 7924 * accessibility events. 7925 * </p> 7926 * 7927 * @param event The motion event that describes the hover. 7928 * @return True if the view handled the hover event. 7929 * 7930 * @see #isHovered 7931 * @see #setHovered 7932 * @see #onHoverChanged 7933 */ 7934 public boolean onHoverEvent(MotionEvent event) { 7935 // The root view may receive hover (or touch) events that are outside the bounds of 7936 // the window. This code ensures that we only send accessibility events for 7937 // hovers that are actually within the bounds of the root view. 7938 final int action = event.getActionMasked(); 7939 if (!mSendingHoverAccessibilityEvents) { 7940 if ((action == MotionEvent.ACTION_HOVER_ENTER 7941 || action == MotionEvent.ACTION_HOVER_MOVE) 7942 && !hasHoveredChild() 7943 && pointInView(event.getX(), event.getY())) { 7944 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 7945 mSendingHoverAccessibilityEvents = true; 7946 } 7947 } else { 7948 if (action == MotionEvent.ACTION_HOVER_EXIT 7949 || (action == MotionEvent.ACTION_MOVE 7950 && !pointInView(event.getX(), event.getY()))) { 7951 mSendingHoverAccessibilityEvents = false; 7952 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 7953 // If the window does not have input focus we take away accessibility 7954 // focus as soon as the user stop hovering over the view. 7955 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 7956 getViewRootImpl().setAccessibilityFocus(null, null); 7957 } 7958 } 7959 } 7960 7961 if (isHoverable()) { 7962 switch (action) { 7963 case MotionEvent.ACTION_HOVER_ENTER: 7964 setHovered(true); 7965 break; 7966 case MotionEvent.ACTION_HOVER_EXIT: 7967 setHovered(false); 7968 break; 7969 } 7970 7971 // Dispatch the event to onGenericMotionEvent before returning true. 7972 // This is to provide compatibility with existing applications that 7973 // handled HOVER_MOVE events in onGenericMotionEvent and that would 7974 // break because of the new default handling for hoverable views 7975 // in onHoverEvent. 7976 // Note that onGenericMotionEvent will be called by default when 7977 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 7978 dispatchGenericMotionEventInternal(event); 7979 return true; 7980 } 7981 7982 return false; 7983 } 7984 7985 /** 7986 * Returns true if the view should handle {@link #onHoverEvent} 7987 * by calling {@link #setHovered} to change its hovered state. 7988 * 7989 * @return True if the view is hoverable. 7990 */ 7991 private boolean isHoverable() { 7992 final int viewFlags = mViewFlags; 7993 if ((viewFlags & ENABLED_MASK) == DISABLED) { 7994 return false; 7995 } 7996 7997 return (viewFlags & CLICKABLE) == CLICKABLE 7998 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 7999 } 8000 8001 /** 8002 * Returns true if the view is currently hovered. 8003 * 8004 * @return True if the view is currently hovered. 8005 * 8006 * @see #setHovered 8007 * @see #onHoverChanged 8008 */ 8009 @ViewDebug.ExportedProperty 8010 public boolean isHovered() { 8011 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8012 } 8013 8014 /** 8015 * Sets whether the view is currently hovered. 8016 * <p> 8017 * Calling this method also changes the drawable state of the view. This 8018 * enables the view to react to hover by using different drawable resources 8019 * to change its appearance. 8020 * </p><p> 8021 * The {@link #onHoverChanged} method is called when the hovered state changes. 8022 * </p> 8023 * 8024 * @param hovered True if the view is hovered. 8025 * 8026 * @see #isHovered 8027 * @see #onHoverChanged 8028 */ 8029 public void setHovered(boolean hovered) { 8030 if (hovered) { 8031 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8032 mPrivateFlags |= PFLAG_HOVERED; 8033 refreshDrawableState(); 8034 onHoverChanged(true); 8035 } 8036 } else { 8037 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8038 mPrivateFlags &= ~PFLAG_HOVERED; 8039 refreshDrawableState(); 8040 onHoverChanged(false); 8041 } 8042 } 8043 } 8044 8045 /** 8046 * Implement this method to handle hover state changes. 8047 * <p> 8048 * This method is called whenever the hover state changes as a result of a 8049 * call to {@link #setHovered}. 8050 * </p> 8051 * 8052 * @param hovered The current hover state, as returned by {@link #isHovered}. 8053 * 8054 * @see #isHovered 8055 * @see #setHovered 8056 */ 8057 public void onHoverChanged(boolean hovered) { 8058 } 8059 8060 /** 8061 * Implement this method to handle touch screen motion events. 8062 * 8063 * @param event The motion event. 8064 * @return True if the event was handled, false otherwise. 8065 */ 8066 public boolean onTouchEvent(MotionEvent event) { 8067 final int viewFlags = mViewFlags; 8068 8069 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8070 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8071 setPressed(false); 8072 } 8073 // A disabled view that is clickable still consumes the touch 8074 // events, it just doesn't respond to them. 8075 return (((viewFlags & CLICKABLE) == CLICKABLE || 8076 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8077 } 8078 8079 if (mTouchDelegate != null) { 8080 if (mTouchDelegate.onTouchEvent(event)) { 8081 return true; 8082 } 8083 } 8084 8085 if (((viewFlags & CLICKABLE) == CLICKABLE || 8086 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8087 switch (event.getAction()) { 8088 case MotionEvent.ACTION_UP: 8089 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8090 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8091 // take focus if we don't have it already and we should in 8092 // touch mode. 8093 boolean focusTaken = false; 8094 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8095 focusTaken = requestFocus(); 8096 } 8097 8098 if (prepressed) { 8099 // The button is being released before we actually 8100 // showed it as pressed. Make it show the pressed 8101 // state now (before scheduling the click) to ensure 8102 // the user sees it. 8103 setPressed(true); 8104 } 8105 8106 if (!mHasPerformedLongPress) { 8107 // This is a tap, so remove the longpress check 8108 removeLongPressCallback(); 8109 8110 // Only perform take click actions if we were in the pressed state 8111 if (!focusTaken) { 8112 // Use a Runnable and post this rather than calling 8113 // performClick directly. This lets other visual state 8114 // of the view update before click actions start. 8115 if (mPerformClick == null) { 8116 mPerformClick = new PerformClick(); 8117 } 8118 if (!post(mPerformClick)) { 8119 performClick(); 8120 } 8121 } 8122 } 8123 8124 if (mUnsetPressedState == null) { 8125 mUnsetPressedState = new UnsetPressedState(); 8126 } 8127 8128 if (prepressed) { 8129 postDelayed(mUnsetPressedState, 8130 ViewConfiguration.getPressedStateDuration()); 8131 } else if (!post(mUnsetPressedState)) { 8132 // If the post failed, unpress right now 8133 mUnsetPressedState.run(); 8134 } 8135 removeTapCallback(); 8136 } 8137 break; 8138 8139 case MotionEvent.ACTION_DOWN: 8140 mHasPerformedLongPress = false; 8141 8142 if (performButtonActionOnTouchDown(event)) { 8143 break; 8144 } 8145 8146 // Walk up the hierarchy to determine if we're inside a scrolling container. 8147 boolean isInScrollingContainer = isInScrollingContainer(); 8148 8149 // For views inside a scrolling container, delay the pressed feedback for 8150 // a short period in case this is a scroll. 8151 if (isInScrollingContainer) { 8152 mPrivateFlags |= PFLAG_PREPRESSED; 8153 if (mPendingCheckForTap == null) { 8154 mPendingCheckForTap = new CheckForTap(); 8155 } 8156 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 8157 } else { 8158 // Not inside a scrolling container, so show the feedback right away 8159 setPressed(true); 8160 checkForLongClick(0); 8161 } 8162 break; 8163 8164 case MotionEvent.ACTION_CANCEL: 8165 setPressed(false); 8166 removeTapCallback(); 8167 break; 8168 8169 case MotionEvent.ACTION_MOVE: 8170 final int x = (int) event.getX(); 8171 final int y = (int) event.getY(); 8172 8173 // Be lenient about moving outside of buttons 8174 if (!pointInView(x, y, mTouchSlop)) { 8175 // Outside button 8176 removeTapCallback(); 8177 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 8178 // Remove any future long press/tap checks 8179 removeLongPressCallback(); 8180 8181 setPressed(false); 8182 } 8183 } 8184 break; 8185 } 8186 return true; 8187 } 8188 8189 return false; 8190 } 8191 8192 /** 8193 * @hide 8194 */ 8195 public boolean isInScrollingContainer() { 8196 ViewParent p = getParent(); 8197 while (p != null && p instanceof ViewGroup) { 8198 if (((ViewGroup) p).shouldDelayChildPressedState()) { 8199 return true; 8200 } 8201 p = p.getParent(); 8202 } 8203 return false; 8204 } 8205 8206 /** 8207 * Remove the longpress detection timer. 8208 */ 8209 private void removeLongPressCallback() { 8210 if (mPendingCheckForLongPress != null) { 8211 removeCallbacks(mPendingCheckForLongPress); 8212 } 8213 } 8214 8215 /** 8216 * Remove the pending click action 8217 */ 8218 private void removePerformClickCallback() { 8219 if (mPerformClick != null) { 8220 removeCallbacks(mPerformClick); 8221 } 8222 } 8223 8224 /** 8225 * Remove the prepress detection timer. 8226 */ 8227 private void removeUnsetPressCallback() { 8228 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 8229 setPressed(false); 8230 removeCallbacks(mUnsetPressedState); 8231 } 8232 } 8233 8234 /** 8235 * Remove the tap detection timer. 8236 */ 8237 private void removeTapCallback() { 8238 if (mPendingCheckForTap != null) { 8239 mPrivateFlags &= ~PFLAG_PREPRESSED; 8240 removeCallbacks(mPendingCheckForTap); 8241 } 8242 } 8243 8244 /** 8245 * Cancels a pending long press. Your subclass can use this if you 8246 * want the context menu to come up if the user presses and holds 8247 * at the same place, but you don't want it to come up if they press 8248 * and then move around enough to cause scrolling. 8249 */ 8250 public void cancelLongPress() { 8251 removeLongPressCallback(); 8252 8253 /* 8254 * The prepressed state handled by the tap callback is a display 8255 * construct, but the tap callback will post a long press callback 8256 * less its own timeout. Remove it here. 8257 */ 8258 removeTapCallback(); 8259 } 8260 8261 /** 8262 * Remove the pending callback for sending a 8263 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 8264 */ 8265 private void removeSendViewScrolledAccessibilityEventCallback() { 8266 if (mSendViewScrolledAccessibilityEvent != null) { 8267 removeCallbacks(mSendViewScrolledAccessibilityEvent); 8268 mSendViewScrolledAccessibilityEvent.mIsPending = false; 8269 } 8270 } 8271 8272 /** 8273 * Sets the TouchDelegate for this View. 8274 */ 8275 public void setTouchDelegate(TouchDelegate delegate) { 8276 mTouchDelegate = delegate; 8277 } 8278 8279 /** 8280 * Gets the TouchDelegate for this View. 8281 */ 8282 public TouchDelegate getTouchDelegate() { 8283 return mTouchDelegate; 8284 } 8285 8286 /** 8287 * Set flags controlling behavior of this view. 8288 * 8289 * @param flags Constant indicating the value which should be set 8290 * @param mask Constant indicating the bit range that should be changed 8291 */ 8292 void setFlags(int flags, int mask) { 8293 int old = mViewFlags; 8294 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 8295 8296 int changed = mViewFlags ^ old; 8297 if (changed == 0) { 8298 return; 8299 } 8300 int privateFlags = mPrivateFlags; 8301 8302 /* Check if the FOCUSABLE bit has changed */ 8303 if (((changed & FOCUSABLE_MASK) != 0) && 8304 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 8305 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 8306 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 8307 /* Give up focus if we are no longer focusable */ 8308 clearFocus(); 8309 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 8310 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 8311 /* 8312 * Tell the view system that we are now available to take focus 8313 * if no one else already has it. 8314 */ 8315 if (mParent != null) mParent.focusableViewAvailable(this); 8316 } 8317 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8318 notifyAccessibilityStateChanged(); 8319 } 8320 } 8321 8322 if ((flags & VISIBILITY_MASK) == VISIBLE) { 8323 if ((changed & VISIBILITY_MASK) != 0) { 8324 /* 8325 * If this view is becoming visible, invalidate it in case it changed while 8326 * it was not visible. Marking it drawn ensures that the invalidation will 8327 * go through. 8328 */ 8329 mPrivateFlags |= PFLAG_DRAWN; 8330 invalidate(true); 8331 8332 needGlobalAttributesUpdate(true); 8333 8334 // a view becoming visible is worth notifying the parent 8335 // about in case nothing has focus. even if this specific view 8336 // isn't focusable, it may contain something that is, so let 8337 // the root view try to give this focus if nothing else does. 8338 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 8339 mParent.focusableViewAvailable(this); 8340 } 8341 } 8342 } 8343 8344 /* Check if the GONE bit has changed */ 8345 if ((changed & GONE) != 0) { 8346 needGlobalAttributesUpdate(false); 8347 requestLayout(); 8348 8349 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 8350 if (hasFocus()) clearFocus(); 8351 clearAccessibilityFocus(); 8352 destroyDrawingCache(); 8353 if (mParent instanceof View) { 8354 // GONE views noop invalidation, so invalidate the parent 8355 ((View) mParent).invalidate(true); 8356 } 8357 // Mark the view drawn to ensure that it gets invalidated properly the next 8358 // time it is visible and gets invalidated 8359 mPrivateFlags |= PFLAG_DRAWN; 8360 } 8361 if (mAttachInfo != null) { 8362 mAttachInfo.mViewVisibilityChanged = true; 8363 } 8364 } 8365 8366 /* Check if the VISIBLE bit has changed */ 8367 if ((changed & INVISIBLE) != 0) { 8368 needGlobalAttributesUpdate(false); 8369 /* 8370 * If this view is becoming invisible, set the DRAWN flag so that 8371 * the next invalidate() will not be skipped. 8372 */ 8373 mPrivateFlags |= PFLAG_DRAWN; 8374 8375 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 8376 // root view becoming invisible shouldn't clear focus and accessibility focus 8377 if (getRootView() != this) { 8378 clearFocus(); 8379 clearAccessibilityFocus(); 8380 } 8381 } 8382 if (mAttachInfo != null) { 8383 mAttachInfo.mViewVisibilityChanged = true; 8384 } 8385 } 8386 8387 if ((changed & VISIBILITY_MASK) != 0) { 8388 if (mParent instanceof ViewGroup) { 8389 ((ViewGroup) mParent).onChildVisibilityChanged(this, 8390 (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK)); 8391 ((View) mParent).invalidate(true); 8392 } else if (mParent != null) { 8393 mParent.invalidateChild(this, null); 8394 } 8395 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 8396 } 8397 8398 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 8399 destroyDrawingCache(); 8400 } 8401 8402 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 8403 destroyDrawingCache(); 8404 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8405 invalidateParentCaches(); 8406 } 8407 8408 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 8409 destroyDrawingCache(); 8410 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8411 } 8412 8413 if ((changed & DRAW_MASK) != 0) { 8414 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 8415 if (mBackground != null) { 8416 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8417 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 8418 } else { 8419 mPrivateFlags |= PFLAG_SKIP_DRAW; 8420 } 8421 } else { 8422 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8423 } 8424 requestLayout(); 8425 invalidate(true); 8426 } 8427 8428 if ((changed & KEEP_SCREEN_ON) != 0) { 8429 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 8430 mParent.recomputeViewAttributes(this); 8431 } 8432 } 8433 8434 if (AccessibilityManager.getInstance(mContext).isEnabled() 8435 && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0 8436 || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) { 8437 notifyAccessibilityStateChanged(); 8438 } 8439 } 8440 8441 /** 8442 * Change the view's z order in the tree, so it's on top of other sibling 8443 * views 8444 */ 8445 public void bringToFront() { 8446 if (mParent != null) { 8447 mParent.bringChildToFront(this); 8448 } 8449 } 8450 8451 /** 8452 * This is called in response to an internal scroll in this view (i.e., the 8453 * view scrolled its own contents). This is typically as a result of 8454 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 8455 * called. 8456 * 8457 * @param l Current horizontal scroll origin. 8458 * @param t Current vertical scroll origin. 8459 * @param oldl Previous horizontal scroll origin. 8460 * @param oldt Previous vertical scroll origin. 8461 */ 8462 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 8463 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8464 postSendViewScrolledAccessibilityEventCallback(); 8465 } 8466 8467 mBackgroundSizeChanged = true; 8468 8469 final AttachInfo ai = mAttachInfo; 8470 if (ai != null) { 8471 ai.mViewScrollChanged = true; 8472 } 8473 } 8474 8475 /** 8476 * Interface definition for a callback to be invoked when the layout bounds of a view 8477 * changes due to layout processing. 8478 */ 8479 public interface OnLayoutChangeListener { 8480 /** 8481 * Called when the focus state of a view has changed. 8482 * 8483 * @param v The view whose state has changed. 8484 * @param left The new value of the view's left property. 8485 * @param top The new value of the view's top property. 8486 * @param right The new value of the view's right property. 8487 * @param bottom The new value of the view's bottom property. 8488 * @param oldLeft The previous value of the view's left property. 8489 * @param oldTop The previous value of the view's top property. 8490 * @param oldRight The previous value of the view's right property. 8491 * @param oldBottom The previous value of the view's bottom property. 8492 */ 8493 void onLayoutChange(View v, int left, int top, int right, int bottom, 8494 int oldLeft, int oldTop, int oldRight, int oldBottom); 8495 } 8496 8497 /** 8498 * This is called during layout when the size of this view has changed. If 8499 * you were just added to the view hierarchy, you're called with the old 8500 * values of 0. 8501 * 8502 * @param w Current width of this view. 8503 * @param h Current height of this view. 8504 * @param oldw Old width of this view. 8505 * @param oldh Old height of this view. 8506 */ 8507 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 8508 } 8509 8510 /** 8511 * Called by draw to draw the child views. This may be overridden 8512 * by derived classes to gain control just before its children are drawn 8513 * (but after its own view has been drawn). 8514 * @param canvas the canvas on which to draw the view 8515 */ 8516 protected void dispatchDraw(Canvas canvas) { 8517 8518 } 8519 8520 /** 8521 * Gets the parent of this view. Note that the parent is a 8522 * ViewParent and not necessarily a View. 8523 * 8524 * @return Parent of this view. 8525 */ 8526 public final ViewParent getParent() { 8527 return mParent; 8528 } 8529 8530 /** 8531 * Set the horizontal scrolled position of your view. This will cause a call to 8532 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8533 * invalidated. 8534 * @param value the x position to scroll to 8535 */ 8536 public void setScrollX(int value) { 8537 scrollTo(value, mScrollY); 8538 } 8539 8540 /** 8541 * Set the vertical scrolled position of your view. This will cause a call to 8542 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8543 * invalidated. 8544 * @param value the y position to scroll to 8545 */ 8546 public void setScrollY(int value) { 8547 scrollTo(mScrollX, value); 8548 } 8549 8550 /** 8551 * Return the scrolled left position of this view. This is the left edge of 8552 * the displayed part of your view. You do not need to draw any pixels 8553 * farther left, since those are outside of the frame of your view on 8554 * screen. 8555 * 8556 * @return The left edge of the displayed part of your view, in pixels. 8557 */ 8558 public final int getScrollX() { 8559 return mScrollX; 8560 } 8561 8562 /** 8563 * Return the scrolled top position of this view. This is the top edge of 8564 * the displayed part of your view. You do not need to draw any pixels above 8565 * it, since those are outside of the frame of your view on screen. 8566 * 8567 * @return The top edge of the displayed part of your view, in pixels. 8568 */ 8569 public final int getScrollY() { 8570 return mScrollY; 8571 } 8572 8573 /** 8574 * Return the width of the your view. 8575 * 8576 * @return The width of your view, in pixels. 8577 */ 8578 @ViewDebug.ExportedProperty(category = "layout") 8579 public final int getWidth() { 8580 return mRight - mLeft; 8581 } 8582 8583 /** 8584 * Return the height of your view. 8585 * 8586 * @return The height of your view, in pixels. 8587 */ 8588 @ViewDebug.ExportedProperty(category = "layout") 8589 public final int getHeight() { 8590 return mBottom - mTop; 8591 } 8592 8593 /** 8594 * Return the visible drawing bounds of your view. Fills in the output 8595 * rectangle with the values from getScrollX(), getScrollY(), 8596 * getWidth(), and getHeight(). 8597 * 8598 * @param outRect The (scrolled) drawing bounds of the view. 8599 */ 8600 public void getDrawingRect(Rect outRect) { 8601 outRect.left = mScrollX; 8602 outRect.top = mScrollY; 8603 outRect.right = mScrollX + (mRight - mLeft); 8604 outRect.bottom = mScrollY + (mBottom - mTop); 8605 } 8606 8607 /** 8608 * Like {@link #getMeasuredWidthAndState()}, but only returns the 8609 * raw width component (that is the result is masked by 8610 * {@link #MEASURED_SIZE_MASK}). 8611 * 8612 * @return The raw measured width of this view. 8613 */ 8614 public final int getMeasuredWidth() { 8615 return mMeasuredWidth & MEASURED_SIZE_MASK; 8616 } 8617 8618 /** 8619 * Return the full width measurement information for this view as computed 8620 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8621 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8622 * This should be used during measurement and layout calculations only. Use 8623 * {@link #getWidth()} to see how wide a view is after layout. 8624 * 8625 * @return The measured width of this view as a bit mask. 8626 */ 8627 public final int getMeasuredWidthAndState() { 8628 return mMeasuredWidth; 8629 } 8630 8631 /** 8632 * Like {@link #getMeasuredHeightAndState()}, but only returns the 8633 * raw width component (that is the result is masked by 8634 * {@link #MEASURED_SIZE_MASK}). 8635 * 8636 * @return The raw measured height of this view. 8637 */ 8638 public final int getMeasuredHeight() { 8639 return mMeasuredHeight & MEASURED_SIZE_MASK; 8640 } 8641 8642 /** 8643 * Return the full height measurement information for this view as computed 8644 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8645 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8646 * This should be used during measurement and layout calculations only. Use 8647 * {@link #getHeight()} to see how wide a view is after layout. 8648 * 8649 * @return The measured width of this view as a bit mask. 8650 */ 8651 public final int getMeasuredHeightAndState() { 8652 return mMeasuredHeight; 8653 } 8654 8655 /** 8656 * Return only the state bits of {@link #getMeasuredWidthAndState()} 8657 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 8658 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 8659 * and the height component is at the shifted bits 8660 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 8661 */ 8662 public final int getMeasuredState() { 8663 return (mMeasuredWidth&MEASURED_STATE_MASK) 8664 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 8665 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 8666 } 8667 8668 /** 8669 * The transform matrix of this view, which is calculated based on the current 8670 * roation, scale, and pivot properties. 8671 * 8672 * @see #getRotation() 8673 * @see #getScaleX() 8674 * @see #getScaleY() 8675 * @see #getPivotX() 8676 * @see #getPivotY() 8677 * @return The current transform matrix for the view 8678 */ 8679 public Matrix getMatrix() { 8680 if (mTransformationInfo != null) { 8681 updateMatrix(); 8682 return mTransformationInfo.mMatrix; 8683 } 8684 return Matrix.IDENTITY_MATRIX; 8685 } 8686 8687 /** 8688 * Utility function to determine if the value is far enough away from zero to be 8689 * considered non-zero. 8690 * @param value A floating point value to check for zero-ness 8691 * @return whether the passed-in value is far enough away from zero to be considered non-zero 8692 */ 8693 private static boolean nonzero(float value) { 8694 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 8695 } 8696 8697 /** 8698 * Returns true if the transform matrix is the identity matrix. 8699 * Recomputes the matrix if necessary. 8700 * 8701 * @return True if the transform matrix is the identity matrix, false otherwise. 8702 */ 8703 final boolean hasIdentityMatrix() { 8704 if (mTransformationInfo != null) { 8705 updateMatrix(); 8706 return mTransformationInfo.mMatrixIsIdentity; 8707 } 8708 return true; 8709 } 8710 8711 void ensureTransformationInfo() { 8712 if (mTransformationInfo == null) { 8713 mTransformationInfo = new TransformationInfo(); 8714 } 8715 } 8716 8717 /** 8718 * Recomputes the transform matrix if necessary. 8719 */ 8720 private void updateMatrix() { 8721 final TransformationInfo info = mTransformationInfo; 8722 if (info == null) { 8723 return; 8724 } 8725 if (info.mMatrixDirty) { 8726 // transform-related properties have changed since the last time someone 8727 // asked for the matrix; recalculate it with the current values 8728 8729 // Figure out if we need to update the pivot point 8730 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 8731 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 8732 info.mPrevWidth = mRight - mLeft; 8733 info.mPrevHeight = mBottom - mTop; 8734 info.mPivotX = info.mPrevWidth / 2f; 8735 info.mPivotY = info.mPrevHeight / 2f; 8736 } 8737 } 8738 info.mMatrix.reset(); 8739 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 8740 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 8741 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 8742 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 8743 } else { 8744 if (info.mCamera == null) { 8745 info.mCamera = new Camera(); 8746 info.matrix3D = new Matrix(); 8747 } 8748 info.mCamera.save(); 8749 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 8750 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 8751 info.mCamera.getMatrix(info.matrix3D); 8752 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 8753 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 8754 info.mPivotY + info.mTranslationY); 8755 info.mMatrix.postConcat(info.matrix3D); 8756 info.mCamera.restore(); 8757 } 8758 info.mMatrixDirty = false; 8759 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 8760 info.mInverseMatrixDirty = true; 8761 } 8762 } 8763 8764 /** 8765 * Utility method to retrieve the inverse of the current mMatrix property. 8766 * We cache the matrix to avoid recalculating it when transform properties 8767 * have not changed. 8768 * 8769 * @return The inverse of the current matrix of this view. 8770 */ 8771 final Matrix getInverseMatrix() { 8772 final TransformationInfo info = mTransformationInfo; 8773 if (info != null) { 8774 updateMatrix(); 8775 if (info.mInverseMatrixDirty) { 8776 if (info.mInverseMatrix == null) { 8777 info.mInverseMatrix = new Matrix(); 8778 } 8779 info.mMatrix.invert(info.mInverseMatrix); 8780 info.mInverseMatrixDirty = false; 8781 } 8782 return info.mInverseMatrix; 8783 } 8784 return Matrix.IDENTITY_MATRIX; 8785 } 8786 8787 /** 8788 * Gets the distance along the Z axis from the camera to this view. 8789 * 8790 * @see #setCameraDistance(float) 8791 * 8792 * @return The distance along the Z axis. 8793 */ 8794 public float getCameraDistance() { 8795 ensureTransformationInfo(); 8796 final float dpi = mResources.getDisplayMetrics().densityDpi; 8797 final TransformationInfo info = mTransformationInfo; 8798 if (info.mCamera == null) { 8799 info.mCamera = new Camera(); 8800 info.matrix3D = new Matrix(); 8801 } 8802 return -(info.mCamera.getLocationZ() * dpi); 8803 } 8804 8805 /** 8806 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 8807 * views are drawn) from the camera to this view. The camera's distance 8808 * affects 3D transformations, for instance rotations around the X and Y 8809 * axis. If the rotationX or rotationY properties are changed and this view is 8810 * large (more than half the size of the screen), it is recommended to always 8811 * use a camera distance that's greater than the height (X axis rotation) or 8812 * the width (Y axis rotation) of this view.</p> 8813 * 8814 * <p>The distance of the camera from the view plane can have an affect on the 8815 * perspective distortion of the view when it is rotated around the x or y axis. 8816 * For example, a large distance will result in a large viewing angle, and there 8817 * will not be much perspective distortion of the view as it rotates. A short 8818 * distance may cause much more perspective distortion upon rotation, and can 8819 * also result in some drawing artifacts if the rotated view ends up partially 8820 * behind the camera (which is why the recommendation is to use a distance at 8821 * least as far as the size of the view, if the view is to be rotated.)</p> 8822 * 8823 * <p>The distance is expressed in "depth pixels." The default distance depends 8824 * on the screen density. For instance, on a medium density display, the 8825 * default distance is 1280. On a high density display, the default distance 8826 * is 1920.</p> 8827 * 8828 * <p>If you want to specify a distance that leads to visually consistent 8829 * results across various densities, use the following formula:</p> 8830 * <pre> 8831 * float scale = context.getResources().getDisplayMetrics().density; 8832 * view.setCameraDistance(distance * scale); 8833 * </pre> 8834 * 8835 * <p>The density scale factor of a high density display is 1.5, 8836 * and 1920 = 1280 * 1.5.</p> 8837 * 8838 * @param distance The distance in "depth pixels", if negative the opposite 8839 * value is used 8840 * 8841 * @see #setRotationX(float) 8842 * @see #setRotationY(float) 8843 */ 8844 public void setCameraDistance(float distance) { 8845 invalidateViewProperty(true, false); 8846 8847 ensureTransformationInfo(); 8848 final float dpi = mResources.getDisplayMetrics().densityDpi; 8849 final TransformationInfo info = mTransformationInfo; 8850 if (info.mCamera == null) { 8851 info.mCamera = new Camera(); 8852 info.matrix3D = new Matrix(); 8853 } 8854 8855 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 8856 info.mMatrixDirty = true; 8857 8858 invalidateViewProperty(false, false); 8859 if (mDisplayList != null) { 8860 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 8861 } 8862 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 8863 // View was rejected last time it was drawn by its parent; this may have changed 8864 invalidateParentIfNeeded(); 8865 } 8866 } 8867 8868 /** 8869 * The degrees that the view is rotated around the pivot point. 8870 * 8871 * @see #setRotation(float) 8872 * @see #getPivotX() 8873 * @see #getPivotY() 8874 * 8875 * @return The degrees of rotation. 8876 */ 8877 @ViewDebug.ExportedProperty(category = "drawing") 8878 public float getRotation() { 8879 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 8880 } 8881 8882 /** 8883 * Sets the degrees that the view is rotated around the pivot point. Increasing values 8884 * result in clockwise rotation. 8885 * 8886 * @param rotation The degrees of rotation. 8887 * 8888 * @see #getRotation() 8889 * @see #getPivotX() 8890 * @see #getPivotY() 8891 * @see #setRotationX(float) 8892 * @see #setRotationY(float) 8893 * 8894 * @attr ref android.R.styleable#View_rotation 8895 */ 8896 public void setRotation(float rotation) { 8897 ensureTransformationInfo(); 8898 final TransformationInfo info = mTransformationInfo; 8899 if (info.mRotation != rotation) { 8900 // Double-invalidation is necessary to capture view's old and new areas 8901 invalidateViewProperty(true, false); 8902 info.mRotation = rotation; 8903 info.mMatrixDirty = true; 8904 invalidateViewProperty(false, true); 8905 if (mDisplayList != null) { 8906 mDisplayList.setRotation(rotation); 8907 } 8908 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 8909 // View was rejected last time it was drawn by its parent; this may have changed 8910 invalidateParentIfNeeded(); 8911 } 8912 } 8913 } 8914 8915 /** 8916 * The degrees that the view is rotated around the vertical axis through the pivot point. 8917 * 8918 * @see #getPivotX() 8919 * @see #getPivotY() 8920 * @see #setRotationY(float) 8921 * 8922 * @return The degrees of Y rotation. 8923 */ 8924 @ViewDebug.ExportedProperty(category = "drawing") 8925 public float getRotationY() { 8926 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 8927 } 8928 8929 /** 8930 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 8931 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 8932 * down the y axis. 8933 * 8934 * When rotating large views, it is recommended to adjust the camera distance 8935 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 8936 * 8937 * @param rotationY The degrees of Y rotation. 8938 * 8939 * @see #getRotationY() 8940 * @see #getPivotX() 8941 * @see #getPivotY() 8942 * @see #setRotation(float) 8943 * @see #setRotationX(float) 8944 * @see #setCameraDistance(float) 8945 * 8946 * @attr ref android.R.styleable#View_rotationY 8947 */ 8948 public void setRotationY(float rotationY) { 8949 ensureTransformationInfo(); 8950 final TransformationInfo info = mTransformationInfo; 8951 if (info.mRotationY != rotationY) { 8952 invalidateViewProperty(true, false); 8953 info.mRotationY = rotationY; 8954 info.mMatrixDirty = true; 8955 invalidateViewProperty(false, true); 8956 if (mDisplayList != null) { 8957 mDisplayList.setRotationY(rotationY); 8958 } 8959 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 8960 // View was rejected last time it was drawn by its parent; this may have changed 8961 invalidateParentIfNeeded(); 8962 } 8963 } 8964 } 8965 8966 /** 8967 * The degrees that the view is rotated around the horizontal axis through the pivot point. 8968 * 8969 * @see #getPivotX() 8970 * @see #getPivotY() 8971 * @see #setRotationX(float) 8972 * 8973 * @return The degrees of X rotation. 8974 */ 8975 @ViewDebug.ExportedProperty(category = "drawing") 8976 public float getRotationX() { 8977 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 8978 } 8979 8980 /** 8981 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 8982 * Increasing values result in clockwise rotation from the viewpoint of looking down the 8983 * x axis. 8984 * 8985 * When rotating large views, it is recommended to adjust the camera distance 8986 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 8987 * 8988 * @param rotationX The degrees of X rotation. 8989 * 8990 * @see #getRotationX() 8991 * @see #getPivotX() 8992 * @see #getPivotY() 8993 * @see #setRotation(float) 8994 * @see #setRotationY(float) 8995 * @see #setCameraDistance(float) 8996 * 8997 * @attr ref android.R.styleable#View_rotationX 8998 */ 8999 public void setRotationX(float rotationX) { 9000 ensureTransformationInfo(); 9001 final TransformationInfo info = mTransformationInfo; 9002 if (info.mRotationX != rotationX) { 9003 invalidateViewProperty(true, false); 9004 info.mRotationX = rotationX; 9005 info.mMatrixDirty = true; 9006 invalidateViewProperty(false, true); 9007 if (mDisplayList != null) { 9008 mDisplayList.setRotationX(rotationX); 9009 } 9010 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9011 // View was rejected last time it was drawn by its parent; this may have changed 9012 invalidateParentIfNeeded(); 9013 } 9014 } 9015 } 9016 9017 /** 9018 * The amount that the view is scaled in x around the pivot point, as a proportion of 9019 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9020 * 9021 * <p>By default, this is 1.0f. 9022 * 9023 * @see #getPivotX() 9024 * @see #getPivotY() 9025 * @return The scaling factor. 9026 */ 9027 @ViewDebug.ExportedProperty(category = "drawing") 9028 public float getScaleX() { 9029 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 9030 } 9031 9032 /** 9033 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9034 * the view's unscaled width. A value of 1 means that no scaling is applied. 9035 * 9036 * @param scaleX The scaling factor. 9037 * @see #getPivotX() 9038 * @see #getPivotY() 9039 * 9040 * @attr ref android.R.styleable#View_scaleX 9041 */ 9042 public void setScaleX(float scaleX) { 9043 ensureTransformationInfo(); 9044 final TransformationInfo info = mTransformationInfo; 9045 if (info.mScaleX != scaleX) { 9046 invalidateViewProperty(true, false); 9047 info.mScaleX = scaleX; 9048 info.mMatrixDirty = true; 9049 invalidateViewProperty(false, true); 9050 if (mDisplayList != null) { 9051 mDisplayList.setScaleX(scaleX); 9052 } 9053 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9054 // View was rejected last time it was drawn by its parent; this may have changed 9055 invalidateParentIfNeeded(); 9056 } 9057 } 9058 } 9059 9060 /** 9061 * The amount that the view is scaled in y around the pivot point, as a proportion of 9062 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9063 * 9064 * <p>By default, this is 1.0f. 9065 * 9066 * @see #getPivotX() 9067 * @see #getPivotY() 9068 * @return The scaling factor. 9069 */ 9070 @ViewDebug.ExportedProperty(category = "drawing") 9071 public float getScaleY() { 9072 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 9073 } 9074 9075 /** 9076 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9077 * the view's unscaled width. A value of 1 means that no scaling is applied. 9078 * 9079 * @param scaleY The scaling factor. 9080 * @see #getPivotX() 9081 * @see #getPivotY() 9082 * 9083 * @attr ref android.R.styleable#View_scaleY 9084 */ 9085 public void setScaleY(float scaleY) { 9086 ensureTransformationInfo(); 9087 final TransformationInfo info = mTransformationInfo; 9088 if (info.mScaleY != scaleY) { 9089 invalidateViewProperty(true, false); 9090 info.mScaleY = scaleY; 9091 info.mMatrixDirty = true; 9092 invalidateViewProperty(false, true); 9093 if (mDisplayList != null) { 9094 mDisplayList.setScaleY(scaleY); 9095 } 9096 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9097 // View was rejected last time it was drawn by its parent; this may have changed 9098 invalidateParentIfNeeded(); 9099 } 9100 } 9101 } 9102 9103 /** 9104 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9105 * and {@link #setScaleX(float) scaled}. 9106 * 9107 * @see #getRotation() 9108 * @see #getScaleX() 9109 * @see #getScaleY() 9110 * @see #getPivotY() 9111 * @return The x location of the pivot point. 9112 * 9113 * @attr ref android.R.styleable#View_transformPivotX 9114 */ 9115 @ViewDebug.ExportedProperty(category = "drawing") 9116 public float getPivotX() { 9117 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 9118 } 9119 9120 /** 9121 * Sets the x location of the point around which the view is 9122 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9123 * By default, the pivot point is centered on the object. 9124 * Setting this property disables this behavior and causes the view to use only the 9125 * explicitly set pivotX and pivotY values. 9126 * 9127 * @param pivotX The x location of the pivot point. 9128 * @see #getRotation() 9129 * @see #getScaleX() 9130 * @see #getScaleY() 9131 * @see #getPivotY() 9132 * 9133 * @attr ref android.R.styleable#View_transformPivotX 9134 */ 9135 public void setPivotX(float pivotX) { 9136 ensureTransformationInfo(); 9137 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9138 final TransformationInfo info = mTransformationInfo; 9139 if (info.mPivotX != pivotX) { 9140 invalidateViewProperty(true, false); 9141 info.mPivotX = pivotX; 9142 info.mMatrixDirty = true; 9143 invalidateViewProperty(false, true); 9144 if (mDisplayList != null) { 9145 mDisplayList.setPivotX(pivotX); 9146 } 9147 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9148 // View was rejected last time it was drawn by its parent; this may have changed 9149 invalidateParentIfNeeded(); 9150 } 9151 } 9152 } 9153 9154 /** 9155 * The y location of the point around which the view is {@link #setRotation(float) rotated} 9156 * and {@link #setScaleY(float) scaled}. 9157 * 9158 * @see #getRotation() 9159 * @see #getScaleX() 9160 * @see #getScaleY() 9161 * @see #getPivotY() 9162 * @return The y location of the pivot point. 9163 * 9164 * @attr ref android.R.styleable#View_transformPivotY 9165 */ 9166 @ViewDebug.ExportedProperty(category = "drawing") 9167 public float getPivotY() { 9168 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 9169 } 9170 9171 /** 9172 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 9173 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 9174 * Setting this property disables this behavior and causes the view to use only the 9175 * explicitly set pivotX and pivotY values. 9176 * 9177 * @param pivotY The y location of the pivot point. 9178 * @see #getRotation() 9179 * @see #getScaleX() 9180 * @see #getScaleY() 9181 * @see #getPivotY() 9182 * 9183 * @attr ref android.R.styleable#View_transformPivotY 9184 */ 9185 public void setPivotY(float pivotY) { 9186 ensureTransformationInfo(); 9187 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9188 final TransformationInfo info = mTransformationInfo; 9189 if (info.mPivotY != pivotY) { 9190 invalidateViewProperty(true, false); 9191 info.mPivotY = pivotY; 9192 info.mMatrixDirty = true; 9193 invalidateViewProperty(false, true); 9194 if (mDisplayList != null) { 9195 mDisplayList.setPivotY(pivotY); 9196 } 9197 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9198 // View was rejected last time it was drawn by its parent; this may have changed 9199 invalidateParentIfNeeded(); 9200 } 9201 } 9202 } 9203 9204 /** 9205 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 9206 * completely transparent and 1 means the view is completely opaque. 9207 * 9208 * <p>By default this is 1.0f. 9209 * @return The opacity of the view. 9210 */ 9211 @ViewDebug.ExportedProperty(category = "drawing") 9212 public float getAlpha() { 9213 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 9214 } 9215 9216 /** 9217 * Returns whether this View has content which overlaps. This function, intended to be 9218 * overridden by specific View types, is an optimization when alpha is set on a view. If 9219 * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer 9220 * and then composited it into place, which can be expensive. If the view has no overlapping 9221 * rendering, the view can draw each primitive with the appropriate alpha value directly. 9222 * An example of overlapping rendering is a TextView with a background image, such as a 9223 * Button. An example of non-overlapping rendering is a TextView with no background, or 9224 * an ImageView with only the foreground image. The default implementation returns true; 9225 * subclasses should override if they have cases which can be optimized. 9226 * 9227 * @return true if the content in this view might overlap, false otherwise. 9228 */ 9229 public boolean hasOverlappingRendering() { 9230 return true; 9231 } 9232 9233 /** 9234 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 9235 * completely transparent and 1 means the view is completely opaque.</p> 9236 * 9237 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 9238 * responsible for applying the opacity itself. Otherwise, calling this method is 9239 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 9240 * setting a hardware layer.</p> 9241 * 9242 * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have 9243 * performance implications. It is generally best to use the alpha property sparingly and 9244 * transiently, as in the case of fading animations.</p> 9245 * 9246 * @param alpha The opacity of the view. 9247 * 9248 * @see #setLayerType(int, android.graphics.Paint) 9249 * 9250 * @attr ref android.R.styleable#View_alpha 9251 */ 9252 public void setAlpha(float alpha) { 9253 ensureTransformationInfo(); 9254 if (mTransformationInfo.mAlpha != alpha) { 9255 mTransformationInfo.mAlpha = alpha; 9256 if (onSetAlpha((int) (alpha * 255))) { 9257 mPrivateFlags |= PFLAG_ALPHA_SET; 9258 // subclass is handling alpha - don't optimize rendering cache invalidation 9259 invalidateParentCaches(); 9260 invalidate(true); 9261 } else { 9262 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9263 invalidateViewProperty(true, false); 9264 if (mDisplayList != null) { 9265 mDisplayList.setAlpha(alpha); 9266 } 9267 } 9268 } 9269 } 9270 9271 /** 9272 * Faster version of setAlpha() which performs the same steps except there are 9273 * no calls to invalidate(). The caller of this function should perform proper invalidation 9274 * on the parent and this object. The return value indicates whether the subclass handles 9275 * alpha (the return value for onSetAlpha()). 9276 * 9277 * @param alpha The new value for the alpha property 9278 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 9279 * the new value for the alpha property is different from the old value 9280 */ 9281 boolean setAlphaNoInvalidation(float alpha) { 9282 ensureTransformationInfo(); 9283 if (mTransformationInfo.mAlpha != alpha) { 9284 mTransformationInfo.mAlpha = alpha; 9285 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 9286 if (subclassHandlesAlpha) { 9287 mPrivateFlags |= PFLAG_ALPHA_SET; 9288 return true; 9289 } else { 9290 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9291 if (mDisplayList != null) { 9292 mDisplayList.setAlpha(alpha); 9293 } 9294 } 9295 } 9296 return false; 9297 } 9298 9299 /** 9300 * Top position of this view relative to its parent. 9301 * 9302 * @return The top of this view, in pixels. 9303 */ 9304 @ViewDebug.CapturedViewProperty 9305 public final int getTop() { 9306 return mTop; 9307 } 9308 9309 /** 9310 * Sets the top position of this view relative to its parent. This method is meant to be called 9311 * by the layout system and should not generally be called otherwise, because the property 9312 * may be changed at any time by the layout. 9313 * 9314 * @param top The top of this view, in pixels. 9315 */ 9316 public final void setTop(int top) { 9317 if (top != mTop) { 9318 updateMatrix(); 9319 final boolean matrixIsIdentity = mTransformationInfo == null 9320 || mTransformationInfo.mMatrixIsIdentity; 9321 if (matrixIsIdentity) { 9322 if (mAttachInfo != null) { 9323 int minTop; 9324 int yLoc; 9325 if (top < mTop) { 9326 minTop = top; 9327 yLoc = top - mTop; 9328 } else { 9329 minTop = mTop; 9330 yLoc = 0; 9331 } 9332 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 9333 } 9334 } else { 9335 // Double-invalidation is necessary to capture view's old and new areas 9336 invalidate(true); 9337 } 9338 9339 int width = mRight - mLeft; 9340 int oldHeight = mBottom - mTop; 9341 9342 mTop = top; 9343 if (mDisplayList != null) { 9344 mDisplayList.setTop(mTop); 9345 } 9346 9347 onSizeChanged(width, mBottom - mTop, width, oldHeight); 9348 9349 if (!matrixIsIdentity) { 9350 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9351 // A change in dimension means an auto-centered pivot point changes, too 9352 mTransformationInfo.mMatrixDirty = true; 9353 } 9354 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9355 invalidate(true); 9356 } 9357 mBackgroundSizeChanged = true; 9358 invalidateParentIfNeeded(); 9359 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9360 // View was rejected last time it was drawn by its parent; this may have changed 9361 invalidateParentIfNeeded(); 9362 } 9363 } 9364 } 9365 9366 /** 9367 * Bottom position of this view relative to its parent. 9368 * 9369 * @return The bottom of this view, in pixels. 9370 */ 9371 @ViewDebug.CapturedViewProperty 9372 public final int getBottom() { 9373 return mBottom; 9374 } 9375 9376 /** 9377 * True if this view has changed since the last time being drawn. 9378 * 9379 * @return The dirty state of this view. 9380 */ 9381 public boolean isDirty() { 9382 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 9383 } 9384 9385 /** 9386 * Sets the bottom position of this view relative to its parent. This method is meant to be 9387 * called by the layout system and should not generally be called otherwise, because the 9388 * property may be changed at any time by the layout. 9389 * 9390 * @param bottom The bottom of this view, in pixels. 9391 */ 9392 public final void setBottom(int bottom) { 9393 if (bottom != mBottom) { 9394 updateMatrix(); 9395 final boolean matrixIsIdentity = mTransformationInfo == null 9396 || mTransformationInfo.mMatrixIsIdentity; 9397 if (matrixIsIdentity) { 9398 if (mAttachInfo != null) { 9399 int maxBottom; 9400 if (bottom < mBottom) { 9401 maxBottom = mBottom; 9402 } else { 9403 maxBottom = bottom; 9404 } 9405 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 9406 } 9407 } else { 9408 // Double-invalidation is necessary to capture view's old and new areas 9409 invalidate(true); 9410 } 9411 9412 int width = mRight - mLeft; 9413 int oldHeight = mBottom - mTop; 9414 9415 mBottom = bottom; 9416 if (mDisplayList != null) { 9417 mDisplayList.setBottom(mBottom); 9418 } 9419 9420 onSizeChanged(width, mBottom - mTop, width, oldHeight); 9421 9422 if (!matrixIsIdentity) { 9423 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9424 // A change in dimension means an auto-centered pivot point changes, too 9425 mTransformationInfo.mMatrixDirty = true; 9426 } 9427 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9428 invalidate(true); 9429 } 9430 mBackgroundSizeChanged = true; 9431 invalidateParentIfNeeded(); 9432 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9433 // View was rejected last time it was drawn by its parent; this may have changed 9434 invalidateParentIfNeeded(); 9435 } 9436 } 9437 } 9438 9439 /** 9440 * Left position of this view relative to its parent. 9441 * 9442 * @return The left edge of this view, in pixels. 9443 */ 9444 @ViewDebug.CapturedViewProperty 9445 public final int getLeft() { 9446 return mLeft; 9447 } 9448 9449 /** 9450 * Sets the left position of this view relative to its parent. This method is meant to be called 9451 * by the layout system and should not generally be called otherwise, because the property 9452 * may be changed at any time by the layout. 9453 * 9454 * @param left The bottom of this view, in pixels. 9455 */ 9456 public final void setLeft(int left) { 9457 if (left != mLeft) { 9458 updateMatrix(); 9459 final boolean matrixIsIdentity = mTransformationInfo == null 9460 || mTransformationInfo.mMatrixIsIdentity; 9461 if (matrixIsIdentity) { 9462 if (mAttachInfo != null) { 9463 int minLeft; 9464 int xLoc; 9465 if (left < mLeft) { 9466 minLeft = left; 9467 xLoc = left - mLeft; 9468 } else { 9469 minLeft = mLeft; 9470 xLoc = 0; 9471 } 9472 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 9473 } 9474 } else { 9475 // Double-invalidation is necessary to capture view's old and new areas 9476 invalidate(true); 9477 } 9478 9479 int oldWidth = mRight - mLeft; 9480 int height = mBottom - mTop; 9481 9482 mLeft = left; 9483 if (mDisplayList != null) { 9484 mDisplayList.setLeft(left); 9485 } 9486 9487 onSizeChanged(mRight - mLeft, height, oldWidth, height); 9488 9489 if (!matrixIsIdentity) { 9490 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9491 // A change in dimension means an auto-centered pivot point changes, too 9492 mTransformationInfo.mMatrixDirty = true; 9493 } 9494 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9495 invalidate(true); 9496 } 9497 mBackgroundSizeChanged = true; 9498 invalidateParentIfNeeded(); 9499 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9500 // View was rejected last time it was drawn by its parent; this may have changed 9501 invalidateParentIfNeeded(); 9502 } 9503 } 9504 } 9505 9506 /** 9507 * Right position of this view relative to its parent. 9508 * 9509 * @return The right edge of this view, in pixels. 9510 */ 9511 @ViewDebug.CapturedViewProperty 9512 public final int getRight() { 9513 return mRight; 9514 } 9515 9516 /** 9517 * Sets the right position of this view relative to its parent. This method is meant to be called 9518 * by the layout system and should not generally be called otherwise, because the property 9519 * may be changed at any time by the layout. 9520 * 9521 * @param right The bottom of this view, in pixels. 9522 */ 9523 public final void setRight(int right) { 9524 if (right != mRight) { 9525 updateMatrix(); 9526 final boolean matrixIsIdentity = mTransformationInfo == null 9527 || mTransformationInfo.mMatrixIsIdentity; 9528 if (matrixIsIdentity) { 9529 if (mAttachInfo != null) { 9530 int maxRight; 9531 if (right < mRight) { 9532 maxRight = mRight; 9533 } else { 9534 maxRight = right; 9535 } 9536 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 9537 } 9538 } else { 9539 // Double-invalidation is necessary to capture view's old and new areas 9540 invalidate(true); 9541 } 9542 9543 int oldWidth = mRight - mLeft; 9544 int height = mBottom - mTop; 9545 9546 mRight = right; 9547 if (mDisplayList != null) { 9548 mDisplayList.setRight(mRight); 9549 } 9550 9551 onSizeChanged(mRight - mLeft, height, oldWidth, height); 9552 9553 if (!matrixIsIdentity) { 9554 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9555 // A change in dimension means an auto-centered pivot point changes, too 9556 mTransformationInfo.mMatrixDirty = true; 9557 } 9558 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9559 invalidate(true); 9560 } 9561 mBackgroundSizeChanged = true; 9562 invalidateParentIfNeeded(); 9563 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9564 // View was rejected last time it was drawn by its parent; this may have changed 9565 invalidateParentIfNeeded(); 9566 } 9567 } 9568 } 9569 9570 /** 9571 * The visual x position of this view, in pixels. This is equivalent to the 9572 * {@link #setTranslationX(float) translationX} property plus the current 9573 * {@link #getLeft() left} property. 9574 * 9575 * @return The visual x position of this view, in pixels. 9576 */ 9577 @ViewDebug.ExportedProperty(category = "drawing") 9578 public float getX() { 9579 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 9580 } 9581 9582 /** 9583 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 9584 * {@link #setTranslationX(float) translationX} property to be the difference between 9585 * the x value passed in and the current {@link #getLeft() left} property. 9586 * 9587 * @param x The visual x position of this view, in pixels. 9588 */ 9589 public void setX(float x) { 9590 setTranslationX(x - mLeft); 9591 } 9592 9593 /** 9594 * The visual y position of this view, in pixels. This is equivalent to the 9595 * {@link #setTranslationY(float) translationY} property plus the current 9596 * {@link #getTop() top} property. 9597 * 9598 * @return The visual y position of this view, in pixels. 9599 */ 9600 @ViewDebug.ExportedProperty(category = "drawing") 9601 public float getY() { 9602 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 9603 } 9604 9605 /** 9606 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 9607 * {@link #setTranslationY(float) translationY} property to be the difference between 9608 * the y value passed in and the current {@link #getTop() top} property. 9609 * 9610 * @param y The visual y position of this view, in pixels. 9611 */ 9612 public void setY(float y) { 9613 setTranslationY(y - mTop); 9614 } 9615 9616 9617 /** 9618 * The horizontal location of this view relative to its {@link #getLeft() left} position. 9619 * This position is post-layout, in addition to wherever the object's 9620 * layout placed it. 9621 * 9622 * @return The horizontal position of this view relative to its left position, in pixels. 9623 */ 9624 @ViewDebug.ExportedProperty(category = "drawing") 9625 public float getTranslationX() { 9626 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 9627 } 9628 9629 /** 9630 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 9631 * This effectively positions the object post-layout, in addition to wherever the object's 9632 * layout placed it. 9633 * 9634 * @param translationX The horizontal position of this view relative to its left position, 9635 * in pixels. 9636 * 9637 * @attr ref android.R.styleable#View_translationX 9638 */ 9639 public void setTranslationX(float translationX) { 9640 ensureTransformationInfo(); 9641 final TransformationInfo info = mTransformationInfo; 9642 if (info.mTranslationX != translationX) { 9643 // Double-invalidation is necessary to capture view's old and new areas 9644 invalidateViewProperty(true, false); 9645 info.mTranslationX = translationX; 9646 info.mMatrixDirty = true; 9647 invalidateViewProperty(false, true); 9648 if (mDisplayList != null) { 9649 mDisplayList.setTranslationX(translationX); 9650 } 9651 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9652 // View was rejected last time it was drawn by its parent; this may have changed 9653 invalidateParentIfNeeded(); 9654 } 9655 } 9656 } 9657 9658 /** 9659 * The horizontal location of this view relative to its {@link #getTop() top} position. 9660 * This position is post-layout, in addition to wherever the object's 9661 * layout placed it. 9662 * 9663 * @return The vertical position of this view relative to its top position, 9664 * in pixels. 9665 */ 9666 @ViewDebug.ExportedProperty(category = "drawing") 9667 public float getTranslationY() { 9668 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 9669 } 9670 9671 /** 9672 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 9673 * This effectively positions the object post-layout, in addition to wherever the object's 9674 * layout placed it. 9675 * 9676 * @param translationY The vertical position of this view relative to its top position, 9677 * in pixels. 9678 * 9679 * @attr ref android.R.styleable#View_translationY 9680 */ 9681 public void setTranslationY(float translationY) { 9682 ensureTransformationInfo(); 9683 final TransformationInfo info = mTransformationInfo; 9684 if (info.mTranslationY != translationY) { 9685 invalidateViewProperty(true, false); 9686 info.mTranslationY = translationY; 9687 info.mMatrixDirty = true; 9688 invalidateViewProperty(false, true); 9689 if (mDisplayList != null) { 9690 mDisplayList.setTranslationY(translationY); 9691 } 9692 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9693 // View was rejected last time it was drawn by its parent; this may have changed 9694 invalidateParentIfNeeded(); 9695 } 9696 } 9697 } 9698 9699 /** 9700 * Hit rectangle in parent's coordinates 9701 * 9702 * @param outRect The hit rectangle of the view. 9703 */ 9704 public void getHitRect(Rect outRect) { 9705 updateMatrix(); 9706 final TransformationInfo info = mTransformationInfo; 9707 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 9708 outRect.set(mLeft, mTop, mRight, mBottom); 9709 } else { 9710 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 9711 tmpRect.set(-info.mPivotX, -info.mPivotY, 9712 getWidth() - info.mPivotX, getHeight() - info.mPivotY); 9713 info.mMatrix.mapRect(tmpRect); 9714 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 9715 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 9716 } 9717 } 9718 9719 /** 9720 * Determines whether the given point, in local coordinates is inside the view. 9721 */ 9722 /*package*/ final boolean pointInView(float localX, float localY) { 9723 return localX >= 0 && localX < (mRight - mLeft) 9724 && localY >= 0 && localY < (mBottom - mTop); 9725 } 9726 9727 /** 9728 * Utility method to determine whether the given point, in local coordinates, 9729 * is inside the view, where the area of the view is expanded by the slop factor. 9730 * This method is called while processing touch-move events to determine if the event 9731 * is still within the view. 9732 */ 9733 private boolean pointInView(float localX, float localY, float slop) { 9734 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 9735 localY < ((mBottom - mTop) + slop); 9736 } 9737 9738 /** 9739 * When a view has focus and the user navigates away from it, the next view is searched for 9740 * starting from the rectangle filled in by this method. 9741 * 9742 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 9743 * of the view. However, if your view maintains some idea of internal selection, 9744 * such as a cursor, or a selected row or column, you should override this method and 9745 * fill in a more specific rectangle. 9746 * 9747 * @param r The rectangle to fill in, in this view's coordinates. 9748 */ 9749 public void getFocusedRect(Rect r) { 9750 getDrawingRect(r); 9751 } 9752 9753 /** 9754 * If some part of this view is not clipped by any of its parents, then 9755 * return that area in r in global (root) coordinates. To convert r to local 9756 * coordinates (without taking possible View rotations into account), offset 9757 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 9758 * If the view is completely clipped or translated out, return false. 9759 * 9760 * @param r If true is returned, r holds the global coordinates of the 9761 * visible portion of this view. 9762 * @param globalOffset If true is returned, globalOffset holds the dx,dy 9763 * between this view and its root. globalOffet may be null. 9764 * @return true if r is non-empty (i.e. part of the view is visible at the 9765 * root level. 9766 */ 9767 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 9768 int width = mRight - mLeft; 9769 int height = mBottom - mTop; 9770 if (width > 0 && height > 0) { 9771 r.set(0, 0, width, height); 9772 if (globalOffset != null) { 9773 globalOffset.set(-mScrollX, -mScrollY); 9774 } 9775 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 9776 } 9777 return false; 9778 } 9779 9780 public final boolean getGlobalVisibleRect(Rect r) { 9781 return getGlobalVisibleRect(r, null); 9782 } 9783 9784 public final boolean getLocalVisibleRect(Rect r) { 9785 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 9786 if (getGlobalVisibleRect(r, offset)) { 9787 r.offset(-offset.x, -offset.y); // make r local 9788 return true; 9789 } 9790 return false; 9791 } 9792 9793 /** 9794 * Offset this view's vertical location by the specified number of pixels. 9795 * 9796 * @param offset the number of pixels to offset the view by 9797 */ 9798 public void offsetTopAndBottom(int offset) { 9799 if (offset != 0) { 9800 updateMatrix(); 9801 final boolean matrixIsIdentity = mTransformationInfo == null 9802 || mTransformationInfo.mMatrixIsIdentity; 9803 if (matrixIsIdentity) { 9804 if (mDisplayList != null) { 9805 invalidateViewProperty(false, false); 9806 } else { 9807 final ViewParent p = mParent; 9808 if (p != null && mAttachInfo != null) { 9809 final Rect r = mAttachInfo.mTmpInvalRect; 9810 int minTop; 9811 int maxBottom; 9812 int yLoc; 9813 if (offset < 0) { 9814 minTop = mTop + offset; 9815 maxBottom = mBottom; 9816 yLoc = offset; 9817 } else { 9818 minTop = mTop; 9819 maxBottom = mBottom + offset; 9820 yLoc = 0; 9821 } 9822 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 9823 p.invalidateChild(this, r); 9824 } 9825 } 9826 } else { 9827 invalidateViewProperty(false, false); 9828 } 9829 9830 mTop += offset; 9831 mBottom += offset; 9832 if (mDisplayList != null) { 9833 mDisplayList.offsetTopBottom(offset); 9834 invalidateViewProperty(false, false); 9835 } else { 9836 if (!matrixIsIdentity) { 9837 invalidateViewProperty(false, true); 9838 } 9839 invalidateParentIfNeeded(); 9840 } 9841 } 9842 } 9843 9844 /** 9845 * Offset this view's horizontal location by the specified amount of pixels. 9846 * 9847 * @param offset the numer of pixels to offset the view by 9848 */ 9849 public void offsetLeftAndRight(int offset) { 9850 if (offset != 0) { 9851 updateMatrix(); 9852 final boolean matrixIsIdentity = mTransformationInfo == null 9853 || mTransformationInfo.mMatrixIsIdentity; 9854 if (matrixIsIdentity) { 9855 if (mDisplayList != null) { 9856 invalidateViewProperty(false, false); 9857 } else { 9858 final ViewParent p = mParent; 9859 if (p != null && mAttachInfo != null) { 9860 final Rect r = mAttachInfo.mTmpInvalRect; 9861 int minLeft; 9862 int maxRight; 9863 if (offset < 0) { 9864 minLeft = mLeft + offset; 9865 maxRight = mRight; 9866 } else { 9867 minLeft = mLeft; 9868 maxRight = mRight + offset; 9869 } 9870 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 9871 p.invalidateChild(this, r); 9872 } 9873 } 9874 } else { 9875 invalidateViewProperty(false, false); 9876 } 9877 9878 mLeft += offset; 9879 mRight += offset; 9880 if (mDisplayList != null) { 9881 mDisplayList.offsetLeftRight(offset); 9882 invalidateViewProperty(false, false); 9883 } else { 9884 if (!matrixIsIdentity) { 9885 invalidateViewProperty(false, true); 9886 } 9887 invalidateParentIfNeeded(); 9888 } 9889 } 9890 } 9891 9892 /** 9893 * Get the LayoutParams associated with this view. All views should have 9894 * layout parameters. These supply parameters to the <i>parent</i> of this 9895 * view specifying how it should be arranged. There are many subclasses of 9896 * ViewGroup.LayoutParams, and these correspond to the different subclasses 9897 * of ViewGroup that are responsible for arranging their children. 9898 * 9899 * This method may return null if this View is not attached to a parent 9900 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 9901 * was not invoked successfully. When a View is attached to a parent 9902 * ViewGroup, this method must not return null. 9903 * 9904 * @return The LayoutParams associated with this view, or null if no 9905 * parameters have been set yet 9906 */ 9907 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 9908 public ViewGroup.LayoutParams getLayoutParams() { 9909 return mLayoutParams; 9910 } 9911 9912 /** 9913 * Set the layout parameters associated with this view. These supply 9914 * parameters to the <i>parent</i> of this view specifying how it should be 9915 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 9916 * correspond to the different subclasses of ViewGroup that are responsible 9917 * for arranging their children. 9918 * 9919 * @param params The layout parameters for this view, cannot be null 9920 */ 9921 public void setLayoutParams(ViewGroup.LayoutParams params) { 9922 if (params == null) { 9923 throw new NullPointerException("Layout parameters cannot be null"); 9924 } 9925 mLayoutParams = params; 9926 resolveLayoutParams(); 9927 if (mParent instanceof ViewGroup) { 9928 ((ViewGroup) mParent).onSetLayoutParams(this, params); 9929 } 9930 requestLayout(); 9931 } 9932 9933 /** 9934 * Resolve the layout parameters depending on the resolved layout direction 9935 */ 9936 private void resolveLayoutParams() { 9937 if (mLayoutParams != null) { 9938 mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection()); 9939 } 9940 } 9941 9942 /** 9943 * Set the scrolled position of your view. This will cause a call to 9944 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9945 * invalidated. 9946 * @param x the x position to scroll to 9947 * @param y the y position to scroll to 9948 */ 9949 public void scrollTo(int x, int y) { 9950 if (mScrollX != x || mScrollY != y) { 9951 int oldX = mScrollX; 9952 int oldY = mScrollY; 9953 mScrollX = x; 9954 mScrollY = y; 9955 invalidateParentCaches(); 9956 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 9957 if (!awakenScrollBars()) { 9958 postInvalidateOnAnimation(); 9959 } 9960 } 9961 } 9962 9963 /** 9964 * Move the scrolled position of your view. This will cause a call to 9965 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9966 * invalidated. 9967 * @param x the amount of pixels to scroll by horizontally 9968 * @param y the amount of pixels to scroll by vertically 9969 */ 9970 public void scrollBy(int x, int y) { 9971 scrollTo(mScrollX + x, mScrollY + y); 9972 } 9973 9974 /** 9975 * <p>Trigger the scrollbars to draw. When invoked this method starts an 9976 * animation to fade the scrollbars out after a default delay. If a subclass 9977 * provides animated scrolling, the start delay should equal the duration 9978 * of the scrolling animation.</p> 9979 * 9980 * <p>The animation starts only if at least one of the scrollbars is 9981 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 9982 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 9983 * this method returns true, and false otherwise. If the animation is 9984 * started, this method calls {@link #invalidate()}; in that case the 9985 * caller should not call {@link #invalidate()}.</p> 9986 * 9987 * <p>This method should be invoked every time a subclass directly updates 9988 * the scroll parameters.</p> 9989 * 9990 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 9991 * and {@link #scrollTo(int, int)}.</p> 9992 * 9993 * @return true if the animation is played, false otherwise 9994 * 9995 * @see #awakenScrollBars(int) 9996 * @see #scrollBy(int, int) 9997 * @see #scrollTo(int, int) 9998 * @see #isHorizontalScrollBarEnabled() 9999 * @see #isVerticalScrollBarEnabled() 10000 * @see #setHorizontalScrollBarEnabled(boolean) 10001 * @see #setVerticalScrollBarEnabled(boolean) 10002 */ 10003 protected boolean awakenScrollBars() { 10004 return mScrollCache != null && 10005 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 10006 } 10007 10008 /** 10009 * Trigger the scrollbars to draw. 10010 * This method differs from awakenScrollBars() only in its default duration. 10011 * initialAwakenScrollBars() will show the scroll bars for longer than 10012 * usual to give the user more of a chance to notice them. 10013 * 10014 * @return true if the animation is played, false otherwise. 10015 */ 10016 private boolean initialAwakenScrollBars() { 10017 return mScrollCache != null && 10018 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 10019 } 10020 10021 /** 10022 * <p> 10023 * Trigger the scrollbars to draw. When invoked this method starts an 10024 * animation to fade the scrollbars out after a fixed delay. If a subclass 10025 * provides animated scrolling, the start delay should equal the duration of 10026 * the scrolling animation. 10027 * </p> 10028 * 10029 * <p> 10030 * The animation starts only if at least one of the scrollbars is enabled, 10031 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10032 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10033 * this method returns true, and false otherwise. If the animation is 10034 * started, this method calls {@link #invalidate()}; in that case the caller 10035 * should not call {@link #invalidate()}. 10036 * </p> 10037 * 10038 * <p> 10039 * This method should be invoked everytime a subclass directly updates the 10040 * scroll parameters. 10041 * </p> 10042 * 10043 * @param startDelay the delay, in milliseconds, after which the animation 10044 * should start; when the delay is 0, the animation starts 10045 * immediately 10046 * @return true if the animation is played, false otherwise 10047 * 10048 * @see #scrollBy(int, int) 10049 * @see #scrollTo(int, int) 10050 * @see #isHorizontalScrollBarEnabled() 10051 * @see #isVerticalScrollBarEnabled() 10052 * @see #setHorizontalScrollBarEnabled(boolean) 10053 * @see #setVerticalScrollBarEnabled(boolean) 10054 */ 10055 protected boolean awakenScrollBars(int startDelay) { 10056 return awakenScrollBars(startDelay, true); 10057 } 10058 10059 /** 10060 * <p> 10061 * Trigger the scrollbars to draw. When invoked this method starts an 10062 * animation to fade the scrollbars out after a fixed delay. If a subclass 10063 * provides animated scrolling, the start delay should equal the duration of 10064 * the scrolling animation. 10065 * </p> 10066 * 10067 * <p> 10068 * The animation starts only if at least one of the scrollbars is enabled, 10069 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10070 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10071 * this method returns true, and false otherwise. If the animation is 10072 * started, this method calls {@link #invalidate()} if the invalidate parameter 10073 * is set to true; in that case the caller 10074 * should not call {@link #invalidate()}. 10075 * </p> 10076 * 10077 * <p> 10078 * This method should be invoked everytime a subclass directly updates the 10079 * scroll parameters. 10080 * </p> 10081 * 10082 * @param startDelay the delay, in milliseconds, after which the animation 10083 * should start; when the delay is 0, the animation starts 10084 * immediately 10085 * 10086 * @param invalidate Wheter this method should call invalidate 10087 * 10088 * @return true if the animation is played, false otherwise 10089 * 10090 * @see #scrollBy(int, int) 10091 * @see #scrollTo(int, int) 10092 * @see #isHorizontalScrollBarEnabled() 10093 * @see #isVerticalScrollBarEnabled() 10094 * @see #setHorizontalScrollBarEnabled(boolean) 10095 * @see #setVerticalScrollBarEnabled(boolean) 10096 */ 10097 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 10098 final ScrollabilityCache scrollCache = mScrollCache; 10099 10100 if (scrollCache == null || !scrollCache.fadeScrollBars) { 10101 return false; 10102 } 10103 10104 if (scrollCache.scrollBar == null) { 10105 scrollCache.scrollBar = new ScrollBarDrawable(); 10106 } 10107 10108 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 10109 10110 if (invalidate) { 10111 // Invalidate to show the scrollbars 10112 postInvalidateOnAnimation(); 10113 } 10114 10115 if (scrollCache.state == ScrollabilityCache.OFF) { 10116 // FIXME: this is copied from WindowManagerService. 10117 // We should get this value from the system when it 10118 // is possible to do so. 10119 final int KEY_REPEAT_FIRST_DELAY = 750; 10120 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 10121 } 10122 10123 // Tell mScrollCache when we should start fading. This may 10124 // extend the fade start time if one was already scheduled 10125 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 10126 scrollCache.fadeStartTime = fadeStartTime; 10127 scrollCache.state = ScrollabilityCache.ON; 10128 10129 // Schedule our fader to run, unscheduling any old ones first 10130 if (mAttachInfo != null) { 10131 mAttachInfo.mHandler.removeCallbacks(scrollCache); 10132 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 10133 } 10134 10135 return true; 10136 } 10137 10138 return false; 10139 } 10140 10141 /** 10142 * Do not invalidate views which are not visible and which are not running an animation. They 10143 * will not get drawn and they should not set dirty flags as if they will be drawn 10144 */ 10145 private boolean skipInvalidate() { 10146 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 10147 (!(mParent instanceof ViewGroup) || 10148 !((ViewGroup) mParent).isViewTransitioning(this)); 10149 } 10150 /** 10151 * Mark the area defined by dirty as needing to be drawn. If the view is 10152 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 10153 * in the future. This must be called from a UI thread. To call from a non-UI 10154 * thread, call {@link #postInvalidate()}. 10155 * 10156 * WARNING: This method is destructive to dirty. 10157 * @param dirty the rectangle representing the bounds of the dirty region 10158 */ 10159 public void invalidate(Rect dirty) { 10160 if (skipInvalidate()) { 10161 return; 10162 } 10163 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10164 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10165 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10166 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10167 mPrivateFlags |= PFLAG_INVALIDATED; 10168 mPrivateFlags |= PFLAG_DIRTY; 10169 final ViewParent p = mParent; 10170 final AttachInfo ai = mAttachInfo; 10171 //noinspection PointlessBooleanExpression,ConstantConditions 10172 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10173 if (p != null && ai != null && ai.mHardwareAccelerated) { 10174 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10175 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10176 p.invalidateChild(this, null); 10177 return; 10178 } 10179 } 10180 if (p != null && ai != null) { 10181 final int scrollX = mScrollX; 10182 final int scrollY = mScrollY; 10183 final Rect r = ai.mTmpInvalRect; 10184 r.set(dirty.left - scrollX, dirty.top - scrollY, 10185 dirty.right - scrollX, dirty.bottom - scrollY); 10186 mParent.invalidateChild(this, r); 10187 } 10188 } 10189 } 10190 10191 /** 10192 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 10193 * The coordinates of the dirty rect are relative to the view. 10194 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 10195 * will be called at some point in the future. This must be called from 10196 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 10197 * @param l the left position of the dirty region 10198 * @param t the top position of the dirty region 10199 * @param r the right position of the dirty region 10200 * @param b the bottom position of the dirty region 10201 */ 10202 public void invalidate(int l, int t, int r, int b) { 10203 if (skipInvalidate()) { 10204 return; 10205 } 10206 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10207 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10208 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10209 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10210 mPrivateFlags |= PFLAG_INVALIDATED; 10211 mPrivateFlags |= PFLAG_DIRTY; 10212 final ViewParent p = mParent; 10213 final AttachInfo ai = mAttachInfo; 10214 //noinspection PointlessBooleanExpression,ConstantConditions 10215 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10216 if (p != null && ai != null && ai.mHardwareAccelerated) { 10217 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10218 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10219 p.invalidateChild(this, null); 10220 return; 10221 } 10222 } 10223 if (p != null && ai != null && l < r && t < b) { 10224 final int scrollX = mScrollX; 10225 final int scrollY = mScrollY; 10226 final Rect tmpr = ai.mTmpInvalRect; 10227 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 10228 p.invalidateChild(this, tmpr); 10229 } 10230 } 10231 } 10232 10233 /** 10234 * Invalidate the whole view. If the view is visible, 10235 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 10236 * the future. This must be called from a UI thread. To call from a non-UI thread, 10237 * call {@link #postInvalidate()}. 10238 */ 10239 public void invalidate() { 10240 invalidate(true); 10241 } 10242 10243 /** 10244 * This is where the invalidate() work actually happens. A full invalidate() 10245 * causes the drawing cache to be invalidated, but this function can be called with 10246 * invalidateCache set to false to skip that invalidation step for cases that do not 10247 * need it (for example, a component that remains at the same dimensions with the same 10248 * content). 10249 * 10250 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 10251 * well. This is usually true for a full invalidate, but may be set to false if the 10252 * View's contents or dimensions have not changed. 10253 */ 10254 void invalidate(boolean invalidateCache) { 10255 if (skipInvalidate()) { 10256 return; 10257 } 10258 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10259 (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) || 10260 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) { 10261 mLastIsOpaque = isOpaque(); 10262 mPrivateFlags &= ~PFLAG_DRAWN; 10263 mPrivateFlags |= PFLAG_DIRTY; 10264 if (invalidateCache) { 10265 mPrivateFlags |= PFLAG_INVALIDATED; 10266 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10267 } 10268 final AttachInfo ai = mAttachInfo; 10269 final ViewParent p = mParent; 10270 //noinspection PointlessBooleanExpression,ConstantConditions 10271 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10272 if (p != null && ai != null && ai.mHardwareAccelerated) { 10273 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10274 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10275 p.invalidateChild(this, null); 10276 return; 10277 } 10278 } 10279 10280 if (p != null && ai != null) { 10281 final Rect r = ai.mTmpInvalRect; 10282 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10283 // Don't call invalidate -- we don't want to internally scroll 10284 // our own bounds 10285 p.invalidateChild(this, r); 10286 } 10287 } 10288 } 10289 10290 /** 10291 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 10292 * set any flags or handle all of the cases handled by the default invalidation methods. 10293 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 10294 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 10295 * walk up the hierarchy, transforming the dirty rect as necessary. 10296 * 10297 * The method also handles normal invalidation logic if display list properties are not 10298 * being used in this view. The invalidateParent and forceRedraw flags are used by that 10299 * backup approach, to handle these cases used in the various property-setting methods. 10300 * 10301 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 10302 * are not being used in this view 10303 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 10304 * list properties are not being used in this view 10305 */ 10306 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 10307 if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) { 10308 if (invalidateParent) { 10309 invalidateParentCaches(); 10310 } 10311 if (forceRedraw) { 10312 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10313 } 10314 invalidate(false); 10315 } else { 10316 final AttachInfo ai = mAttachInfo; 10317 final ViewParent p = mParent; 10318 if (p != null && ai != null) { 10319 final Rect r = ai.mTmpInvalRect; 10320 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10321 if (mParent instanceof ViewGroup) { 10322 ((ViewGroup) mParent).invalidateChildFast(this, r); 10323 } else { 10324 mParent.invalidateChild(this, r); 10325 } 10326 } 10327 } 10328 } 10329 10330 /** 10331 * Utility method to transform a given Rect by the current matrix of this view. 10332 */ 10333 void transformRect(final Rect rect) { 10334 if (!getMatrix().isIdentity()) { 10335 RectF boundingRect = mAttachInfo.mTmpTransformRect; 10336 boundingRect.set(rect); 10337 getMatrix().mapRect(boundingRect); 10338 rect.set((int) (boundingRect.left - 0.5f), 10339 (int) (boundingRect.top - 0.5f), 10340 (int) (boundingRect.right + 0.5f), 10341 (int) (boundingRect.bottom + 0.5f)); 10342 } 10343 } 10344 10345 /** 10346 * Used to indicate that the parent of this view should clear its caches. This functionality 10347 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10348 * which is necessary when various parent-managed properties of the view change, such as 10349 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 10350 * clears the parent caches and does not causes an invalidate event. 10351 * 10352 * @hide 10353 */ 10354 protected void invalidateParentCaches() { 10355 if (mParent instanceof View) { 10356 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 10357 } 10358 } 10359 10360 /** 10361 * Used to indicate that the parent of this view should be invalidated. This functionality 10362 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10363 * which is necessary when various parent-managed properties of the view change, such as 10364 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 10365 * an invalidation event to the parent. 10366 * 10367 * @hide 10368 */ 10369 protected void invalidateParentIfNeeded() { 10370 if (isHardwareAccelerated() && mParent instanceof View) { 10371 ((View) mParent).invalidate(true); 10372 } 10373 } 10374 10375 /** 10376 * Indicates whether this View is opaque. An opaque View guarantees that it will 10377 * draw all the pixels overlapping its bounds using a fully opaque color. 10378 * 10379 * Subclasses of View should override this method whenever possible to indicate 10380 * whether an instance is opaque. Opaque Views are treated in a special way by 10381 * the View hierarchy, possibly allowing it to perform optimizations during 10382 * invalidate/draw passes. 10383 * 10384 * @return True if this View is guaranteed to be fully opaque, false otherwise. 10385 */ 10386 @ViewDebug.ExportedProperty(category = "drawing") 10387 public boolean isOpaque() { 10388 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 10389 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f); 10390 } 10391 10392 /** 10393 * @hide 10394 */ 10395 protected void computeOpaqueFlags() { 10396 // Opaque if: 10397 // - Has a background 10398 // - Background is opaque 10399 // - Doesn't have scrollbars or scrollbars are inside overlay 10400 10401 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 10402 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 10403 } else { 10404 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 10405 } 10406 10407 final int flags = mViewFlags; 10408 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 10409 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 10410 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 10411 } else { 10412 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 10413 } 10414 } 10415 10416 /** 10417 * @hide 10418 */ 10419 protected boolean hasOpaqueScrollbars() { 10420 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 10421 } 10422 10423 /** 10424 * @return A handler associated with the thread running the View. This 10425 * handler can be used to pump events in the UI events queue. 10426 */ 10427 public Handler getHandler() { 10428 if (mAttachInfo != null) { 10429 return mAttachInfo.mHandler; 10430 } 10431 return null; 10432 } 10433 10434 /** 10435 * Gets the view root associated with the View. 10436 * @return The view root, or null if none. 10437 * @hide 10438 */ 10439 public ViewRootImpl getViewRootImpl() { 10440 if (mAttachInfo != null) { 10441 return mAttachInfo.mViewRootImpl; 10442 } 10443 return null; 10444 } 10445 10446 /** 10447 * <p>Causes the Runnable to be added to the message queue. 10448 * The runnable will be run on the user interface thread.</p> 10449 * 10450 * <p>This method can be invoked from outside of the UI thread 10451 * only when this View is attached to a window.</p> 10452 * 10453 * @param action The Runnable that will be executed. 10454 * 10455 * @return Returns true if the Runnable was successfully placed in to the 10456 * message queue. Returns false on failure, usually because the 10457 * looper processing the message queue is exiting. 10458 * 10459 * @see #postDelayed 10460 * @see #removeCallbacks 10461 */ 10462 public boolean post(Runnable action) { 10463 final AttachInfo attachInfo = mAttachInfo; 10464 if (attachInfo != null) { 10465 return attachInfo.mHandler.post(action); 10466 } 10467 // Assume that post will succeed later 10468 ViewRootImpl.getRunQueue().post(action); 10469 return true; 10470 } 10471 10472 /** 10473 * <p>Causes the Runnable to be added to the message queue, to be run 10474 * after the specified amount of time elapses. 10475 * The runnable will be run on the user interface thread.</p> 10476 * 10477 * <p>This method can be invoked from outside of the UI thread 10478 * only when this View is attached to a window.</p> 10479 * 10480 * @param action The Runnable that will be executed. 10481 * @param delayMillis The delay (in milliseconds) until the Runnable 10482 * will be executed. 10483 * 10484 * @return true if the Runnable was successfully placed in to the 10485 * message queue. Returns false on failure, usually because the 10486 * looper processing the message queue is exiting. Note that a 10487 * result of true does not mean the Runnable will be processed -- 10488 * if the looper is quit before the delivery time of the message 10489 * occurs then the message will be dropped. 10490 * 10491 * @see #post 10492 * @see #removeCallbacks 10493 */ 10494 public boolean postDelayed(Runnable action, long delayMillis) { 10495 final AttachInfo attachInfo = mAttachInfo; 10496 if (attachInfo != null) { 10497 return attachInfo.mHandler.postDelayed(action, delayMillis); 10498 } 10499 // Assume that post will succeed later 10500 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10501 return true; 10502 } 10503 10504 /** 10505 * <p>Causes the Runnable to execute on the next animation time step. 10506 * The runnable will be run on the user interface thread.</p> 10507 * 10508 * <p>This method can be invoked from outside of the UI thread 10509 * only when this View is attached to a window.</p> 10510 * 10511 * @param action The Runnable that will be executed. 10512 * 10513 * @see #postOnAnimationDelayed 10514 * @see #removeCallbacks 10515 */ 10516 public void postOnAnimation(Runnable action) { 10517 final AttachInfo attachInfo = mAttachInfo; 10518 if (attachInfo != null) { 10519 attachInfo.mViewRootImpl.mChoreographer.postCallback( 10520 Choreographer.CALLBACK_ANIMATION, action, null); 10521 } else { 10522 // Assume that post will succeed later 10523 ViewRootImpl.getRunQueue().post(action); 10524 } 10525 } 10526 10527 /** 10528 * <p>Causes the Runnable to execute on the next animation time step, 10529 * after the specified amount of time elapses. 10530 * The runnable will be run on the user interface thread.</p> 10531 * 10532 * <p>This method can be invoked from outside of the UI thread 10533 * only when this View is attached to a window.</p> 10534 * 10535 * @param action The Runnable that will be executed. 10536 * @param delayMillis The delay (in milliseconds) until the Runnable 10537 * will be executed. 10538 * 10539 * @see #postOnAnimation 10540 * @see #removeCallbacks 10541 */ 10542 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 10543 final AttachInfo attachInfo = mAttachInfo; 10544 if (attachInfo != null) { 10545 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 10546 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 10547 } else { 10548 // Assume that post will succeed later 10549 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10550 } 10551 } 10552 10553 /** 10554 * <p>Removes the specified Runnable from the message queue.</p> 10555 * 10556 * <p>This method can be invoked from outside of the UI thread 10557 * only when this View is attached to a window.</p> 10558 * 10559 * @param action The Runnable to remove from the message handling queue 10560 * 10561 * @return true if this view could ask the Handler to remove the Runnable, 10562 * false otherwise. When the returned value is true, the Runnable 10563 * may or may not have been actually removed from the message queue 10564 * (for instance, if the Runnable was not in the queue already.) 10565 * 10566 * @see #post 10567 * @see #postDelayed 10568 * @see #postOnAnimation 10569 * @see #postOnAnimationDelayed 10570 */ 10571 public boolean removeCallbacks(Runnable action) { 10572 if (action != null) { 10573 final AttachInfo attachInfo = mAttachInfo; 10574 if (attachInfo != null) { 10575 attachInfo.mHandler.removeCallbacks(action); 10576 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 10577 Choreographer.CALLBACK_ANIMATION, action, null); 10578 } else { 10579 // Assume that post will succeed later 10580 ViewRootImpl.getRunQueue().removeCallbacks(action); 10581 } 10582 } 10583 return true; 10584 } 10585 10586 /** 10587 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 10588 * Use this to invalidate the View from a non-UI thread.</p> 10589 * 10590 * <p>This method can be invoked from outside of the UI thread 10591 * only when this View is attached to a window.</p> 10592 * 10593 * @see #invalidate() 10594 * @see #postInvalidateDelayed(long) 10595 */ 10596 public void postInvalidate() { 10597 postInvalidateDelayed(0); 10598 } 10599 10600 /** 10601 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10602 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 10603 * 10604 * <p>This method can be invoked from outside of the UI thread 10605 * only when this View is attached to a window.</p> 10606 * 10607 * @param left The left coordinate of the rectangle to invalidate. 10608 * @param top The top coordinate of the rectangle to invalidate. 10609 * @param right The right coordinate of the rectangle to invalidate. 10610 * @param bottom The bottom coordinate of the rectangle to invalidate. 10611 * 10612 * @see #invalidate(int, int, int, int) 10613 * @see #invalidate(Rect) 10614 * @see #postInvalidateDelayed(long, int, int, int, int) 10615 */ 10616 public void postInvalidate(int left, int top, int right, int bottom) { 10617 postInvalidateDelayed(0, left, top, right, bottom); 10618 } 10619 10620 /** 10621 * <p>Cause an invalidate to happen on a subsequent cycle through the event 10622 * loop. Waits for the specified amount of time.</p> 10623 * 10624 * <p>This method can be invoked from outside of the UI thread 10625 * only when this View is attached to a window.</p> 10626 * 10627 * @param delayMilliseconds the duration in milliseconds to delay the 10628 * invalidation by 10629 * 10630 * @see #invalidate() 10631 * @see #postInvalidate() 10632 */ 10633 public void postInvalidateDelayed(long delayMilliseconds) { 10634 // We try only with the AttachInfo because there's no point in invalidating 10635 // if we are not attached to our window 10636 final AttachInfo attachInfo = mAttachInfo; 10637 if (attachInfo != null) { 10638 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 10639 } 10640 } 10641 10642 /** 10643 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10644 * through the event loop. Waits for the specified amount of time.</p> 10645 * 10646 * <p>This method can be invoked from outside of the UI thread 10647 * only when this View is attached to a window.</p> 10648 * 10649 * @param delayMilliseconds the duration in milliseconds to delay the 10650 * invalidation by 10651 * @param left The left coordinate of the rectangle to invalidate. 10652 * @param top The top coordinate of the rectangle to invalidate. 10653 * @param right The right coordinate of the rectangle to invalidate. 10654 * @param bottom The bottom coordinate of the rectangle to invalidate. 10655 * 10656 * @see #invalidate(int, int, int, int) 10657 * @see #invalidate(Rect) 10658 * @see #postInvalidate(int, int, int, int) 10659 */ 10660 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 10661 int right, int bottom) { 10662 10663 // We try only with the AttachInfo because there's no point in invalidating 10664 // if we are not attached to our window 10665 final AttachInfo attachInfo = mAttachInfo; 10666 if (attachInfo != null) { 10667 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 10668 info.target = this; 10669 info.left = left; 10670 info.top = top; 10671 info.right = right; 10672 info.bottom = bottom; 10673 10674 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 10675 } 10676 } 10677 10678 /** 10679 * <p>Cause an invalidate to happen on the next animation time step, typically the 10680 * next display frame.</p> 10681 * 10682 * <p>This method can be invoked from outside of the UI thread 10683 * only when this View is attached to a window.</p> 10684 * 10685 * @see #invalidate() 10686 */ 10687 public void postInvalidateOnAnimation() { 10688 // We try only with the AttachInfo because there's no point in invalidating 10689 // if we are not attached to our window 10690 final AttachInfo attachInfo = mAttachInfo; 10691 if (attachInfo != null) { 10692 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 10693 } 10694 } 10695 10696 /** 10697 * <p>Cause an invalidate of the specified area to happen on the next animation 10698 * time step, typically the next display frame.</p> 10699 * 10700 * <p>This method can be invoked from outside of the UI thread 10701 * only when this View is attached to a window.</p> 10702 * 10703 * @param left The left coordinate of the rectangle to invalidate. 10704 * @param top The top coordinate of the rectangle to invalidate. 10705 * @param right The right coordinate of the rectangle to invalidate. 10706 * @param bottom The bottom coordinate of the rectangle to invalidate. 10707 * 10708 * @see #invalidate(int, int, int, int) 10709 * @see #invalidate(Rect) 10710 */ 10711 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 10712 // We try only with the AttachInfo because there's no point in invalidating 10713 // if we are not attached to our window 10714 final AttachInfo attachInfo = mAttachInfo; 10715 if (attachInfo != null) { 10716 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 10717 info.target = this; 10718 info.left = left; 10719 info.top = top; 10720 info.right = right; 10721 info.bottom = bottom; 10722 10723 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 10724 } 10725 } 10726 10727 /** 10728 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 10729 * This event is sent at most once every 10730 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 10731 */ 10732 private void postSendViewScrolledAccessibilityEventCallback() { 10733 if (mSendViewScrolledAccessibilityEvent == null) { 10734 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 10735 } 10736 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 10737 mSendViewScrolledAccessibilityEvent.mIsPending = true; 10738 postDelayed(mSendViewScrolledAccessibilityEvent, 10739 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 10740 } 10741 } 10742 10743 /** 10744 * Called by a parent to request that a child update its values for mScrollX 10745 * and mScrollY if necessary. This will typically be done if the child is 10746 * animating a scroll using a {@link android.widget.Scroller Scroller} 10747 * object. 10748 */ 10749 public void computeScroll() { 10750 } 10751 10752 /** 10753 * <p>Indicate whether the horizontal edges are faded when the view is 10754 * scrolled horizontally.</p> 10755 * 10756 * @return true if the horizontal edges should are faded on scroll, false 10757 * otherwise 10758 * 10759 * @see #setHorizontalFadingEdgeEnabled(boolean) 10760 * 10761 * @attr ref android.R.styleable#View_requiresFadingEdge 10762 */ 10763 public boolean isHorizontalFadingEdgeEnabled() { 10764 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 10765 } 10766 10767 /** 10768 * <p>Define whether the horizontal edges should be faded when this view 10769 * is scrolled horizontally.</p> 10770 * 10771 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 10772 * be faded when the view is scrolled 10773 * horizontally 10774 * 10775 * @see #isHorizontalFadingEdgeEnabled() 10776 * 10777 * @attr ref android.R.styleable#View_requiresFadingEdge 10778 */ 10779 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 10780 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 10781 if (horizontalFadingEdgeEnabled) { 10782 initScrollCache(); 10783 } 10784 10785 mViewFlags ^= FADING_EDGE_HORIZONTAL; 10786 } 10787 } 10788 10789 /** 10790 * <p>Indicate whether the vertical edges are faded when the view is 10791 * scrolled horizontally.</p> 10792 * 10793 * @return true if the vertical edges should are faded on scroll, false 10794 * otherwise 10795 * 10796 * @see #setVerticalFadingEdgeEnabled(boolean) 10797 * 10798 * @attr ref android.R.styleable#View_requiresFadingEdge 10799 */ 10800 public boolean isVerticalFadingEdgeEnabled() { 10801 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 10802 } 10803 10804 /** 10805 * <p>Define whether the vertical edges should be faded when this view 10806 * is scrolled vertically.</p> 10807 * 10808 * @param verticalFadingEdgeEnabled true if the vertical edges should 10809 * be faded when the view is scrolled 10810 * vertically 10811 * 10812 * @see #isVerticalFadingEdgeEnabled() 10813 * 10814 * @attr ref android.R.styleable#View_requiresFadingEdge 10815 */ 10816 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 10817 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 10818 if (verticalFadingEdgeEnabled) { 10819 initScrollCache(); 10820 } 10821 10822 mViewFlags ^= FADING_EDGE_VERTICAL; 10823 } 10824 } 10825 10826 /** 10827 * Returns the strength, or intensity, of the top faded edge. The strength is 10828 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10829 * returns 0.0 or 1.0 but no value in between. 10830 * 10831 * Subclasses should override this method to provide a smoother fade transition 10832 * when scrolling occurs. 10833 * 10834 * @return the intensity of the top fade as a float between 0.0f and 1.0f 10835 */ 10836 protected float getTopFadingEdgeStrength() { 10837 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 10838 } 10839 10840 /** 10841 * Returns the strength, or intensity, of the bottom faded edge. The strength is 10842 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10843 * returns 0.0 or 1.0 but no value in between. 10844 * 10845 * Subclasses should override this method to provide a smoother fade transition 10846 * when scrolling occurs. 10847 * 10848 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 10849 */ 10850 protected float getBottomFadingEdgeStrength() { 10851 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 10852 computeVerticalScrollRange() ? 1.0f : 0.0f; 10853 } 10854 10855 /** 10856 * Returns the strength, or intensity, of the left faded edge. The strength is 10857 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10858 * returns 0.0 or 1.0 but no value in between. 10859 * 10860 * Subclasses should override this method to provide a smoother fade transition 10861 * when scrolling occurs. 10862 * 10863 * @return the intensity of the left fade as a float between 0.0f and 1.0f 10864 */ 10865 protected float getLeftFadingEdgeStrength() { 10866 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 10867 } 10868 10869 /** 10870 * Returns the strength, or intensity, of the right faded edge. The strength is 10871 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10872 * returns 0.0 or 1.0 but no value in between. 10873 * 10874 * Subclasses should override this method to provide a smoother fade transition 10875 * when scrolling occurs. 10876 * 10877 * @return the intensity of the right fade as a float between 0.0f and 1.0f 10878 */ 10879 protected float getRightFadingEdgeStrength() { 10880 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 10881 computeHorizontalScrollRange() ? 1.0f : 0.0f; 10882 } 10883 10884 /** 10885 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 10886 * scrollbar is not drawn by default.</p> 10887 * 10888 * @return true if the horizontal scrollbar should be painted, false 10889 * otherwise 10890 * 10891 * @see #setHorizontalScrollBarEnabled(boolean) 10892 */ 10893 public boolean isHorizontalScrollBarEnabled() { 10894 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 10895 } 10896 10897 /** 10898 * <p>Define whether the horizontal scrollbar should be drawn or not. The 10899 * scrollbar is not drawn by default.</p> 10900 * 10901 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 10902 * be painted 10903 * 10904 * @see #isHorizontalScrollBarEnabled() 10905 */ 10906 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 10907 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 10908 mViewFlags ^= SCROLLBARS_HORIZONTAL; 10909 computeOpaqueFlags(); 10910 resolvePadding(); 10911 } 10912 } 10913 10914 /** 10915 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 10916 * scrollbar is not drawn by default.</p> 10917 * 10918 * @return true if the vertical scrollbar should be painted, false 10919 * otherwise 10920 * 10921 * @see #setVerticalScrollBarEnabled(boolean) 10922 */ 10923 public boolean isVerticalScrollBarEnabled() { 10924 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 10925 } 10926 10927 /** 10928 * <p>Define whether the vertical scrollbar should be drawn or not. The 10929 * scrollbar is not drawn by default.</p> 10930 * 10931 * @param verticalScrollBarEnabled true if the vertical scrollbar should 10932 * be painted 10933 * 10934 * @see #isVerticalScrollBarEnabled() 10935 */ 10936 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 10937 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 10938 mViewFlags ^= SCROLLBARS_VERTICAL; 10939 computeOpaqueFlags(); 10940 resolvePadding(); 10941 } 10942 } 10943 10944 /** 10945 * @hide 10946 */ 10947 protected void recomputePadding() { 10948 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 10949 } 10950 10951 /** 10952 * Define whether scrollbars will fade when the view is not scrolling. 10953 * 10954 * @param fadeScrollbars wheter to enable fading 10955 * 10956 * @attr ref android.R.styleable#View_fadeScrollbars 10957 */ 10958 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 10959 initScrollCache(); 10960 final ScrollabilityCache scrollabilityCache = mScrollCache; 10961 scrollabilityCache.fadeScrollBars = fadeScrollbars; 10962 if (fadeScrollbars) { 10963 scrollabilityCache.state = ScrollabilityCache.OFF; 10964 } else { 10965 scrollabilityCache.state = ScrollabilityCache.ON; 10966 } 10967 } 10968 10969 /** 10970 * 10971 * Returns true if scrollbars will fade when this view is not scrolling 10972 * 10973 * @return true if scrollbar fading is enabled 10974 * 10975 * @attr ref android.R.styleable#View_fadeScrollbars 10976 */ 10977 public boolean isScrollbarFadingEnabled() { 10978 return mScrollCache != null && mScrollCache.fadeScrollBars; 10979 } 10980 10981 /** 10982 * 10983 * Returns the delay before scrollbars fade. 10984 * 10985 * @return the delay before scrollbars fade 10986 * 10987 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 10988 */ 10989 public int getScrollBarDefaultDelayBeforeFade() { 10990 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 10991 mScrollCache.scrollBarDefaultDelayBeforeFade; 10992 } 10993 10994 /** 10995 * Define the delay before scrollbars fade. 10996 * 10997 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 10998 * 10999 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11000 */ 11001 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 11002 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 11003 } 11004 11005 /** 11006 * 11007 * Returns the scrollbar fade duration. 11008 * 11009 * @return the scrollbar fade duration 11010 * 11011 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11012 */ 11013 public int getScrollBarFadeDuration() { 11014 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 11015 mScrollCache.scrollBarFadeDuration; 11016 } 11017 11018 /** 11019 * Define the scrollbar fade duration. 11020 * 11021 * @param scrollBarFadeDuration - the scrollbar fade duration 11022 * 11023 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11024 */ 11025 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 11026 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 11027 } 11028 11029 /** 11030 * 11031 * Returns the scrollbar size. 11032 * 11033 * @return the scrollbar size 11034 * 11035 * @attr ref android.R.styleable#View_scrollbarSize 11036 */ 11037 public int getScrollBarSize() { 11038 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 11039 mScrollCache.scrollBarSize; 11040 } 11041 11042 /** 11043 * Define the scrollbar size. 11044 * 11045 * @param scrollBarSize - the scrollbar size 11046 * 11047 * @attr ref android.R.styleable#View_scrollbarSize 11048 */ 11049 public void setScrollBarSize(int scrollBarSize) { 11050 getScrollCache().scrollBarSize = scrollBarSize; 11051 } 11052 11053 /** 11054 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 11055 * inset. When inset, they add to the padding of the view. And the scrollbars 11056 * can be drawn inside the padding area or on the edge of the view. For example, 11057 * if a view has a background drawable and you want to draw the scrollbars 11058 * inside the padding specified by the drawable, you can use 11059 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 11060 * appear at the edge of the view, ignoring the padding, then you can use 11061 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 11062 * @param style the style of the scrollbars. Should be one of 11063 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 11064 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 11065 * @see #SCROLLBARS_INSIDE_OVERLAY 11066 * @see #SCROLLBARS_INSIDE_INSET 11067 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11068 * @see #SCROLLBARS_OUTSIDE_INSET 11069 * 11070 * @attr ref android.R.styleable#View_scrollbarStyle 11071 */ 11072 public void setScrollBarStyle(int style) { 11073 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 11074 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 11075 computeOpaqueFlags(); 11076 resolvePadding(); 11077 } 11078 } 11079 11080 /** 11081 * <p>Returns the current scrollbar style.</p> 11082 * @return the current scrollbar style 11083 * @see #SCROLLBARS_INSIDE_OVERLAY 11084 * @see #SCROLLBARS_INSIDE_INSET 11085 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11086 * @see #SCROLLBARS_OUTSIDE_INSET 11087 * 11088 * @attr ref android.R.styleable#View_scrollbarStyle 11089 */ 11090 @ViewDebug.ExportedProperty(mapping = { 11091 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 11092 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 11093 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 11094 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 11095 }) 11096 public int getScrollBarStyle() { 11097 return mViewFlags & SCROLLBARS_STYLE_MASK; 11098 } 11099 11100 /** 11101 * <p>Compute the horizontal range that the horizontal scrollbar 11102 * represents.</p> 11103 * 11104 * <p>The range is expressed in arbitrary units that must be the same as the 11105 * units used by {@link #computeHorizontalScrollExtent()} and 11106 * {@link #computeHorizontalScrollOffset()}.</p> 11107 * 11108 * <p>The default range is the drawing width of this view.</p> 11109 * 11110 * @return the total horizontal range represented by the horizontal 11111 * scrollbar 11112 * 11113 * @see #computeHorizontalScrollExtent() 11114 * @see #computeHorizontalScrollOffset() 11115 * @see android.widget.ScrollBarDrawable 11116 */ 11117 protected int computeHorizontalScrollRange() { 11118 return getWidth(); 11119 } 11120 11121 /** 11122 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 11123 * within the horizontal range. This value is used to compute the position 11124 * of the thumb within the scrollbar's track.</p> 11125 * 11126 * <p>The range is expressed in arbitrary units that must be the same as the 11127 * units used by {@link #computeHorizontalScrollRange()} and 11128 * {@link #computeHorizontalScrollExtent()}.</p> 11129 * 11130 * <p>The default offset is the scroll offset of this view.</p> 11131 * 11132 * @return the horizontal offset of the scrollbar's thumb 11133 * 11134 * @see #computeHorizontalScrollRange() 11135 * @see #computeHorizontalScrollExtent() 11136 * @see android.widget.ScrollBarDrawable 11137 */ 11138 protected int computeHorizontalScrollOffset() { 11139 return mScrollX; 11140 } 11141 11142 /** 11143 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 11144 * within the horizontal range. This value is used to compute the length 11145 * of the thumb within the scrollbar's track.</p> 11146 * 11147 * <p>The range is expressed in arbitrary units that must be the same as the 11148 * units used by {@link #computeHorizontalScrollRange()} and 11149 * {@link #computeHorizontalScrollOffset()}.</p> 11150 * 11151 * <p>The default extent is the drawing width of this view.</p> 11152 * 11153 * @return the horizontal extent of the scrollbar's thumb 11154 * 11155 * @see #computeHorizontalScrollRange() 11156 * @see #computeHorizontalScrollOffset() 11157 * @see android.widget.ScrollBarDrawable 11158 */ 11159 protected int computeHorizontalScrollExtent() { 11160 return getWidth(); 11161 } 11162 11163 /** 11164 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 11165 * 11166 * <p>The range is expressed in arbitrary units that must be the same as the 11167 * units used by {@link #computeVerticalScrollExtent()} and 11168 * {@link #computeVerticalScrollOffset()}.</p> 11169 * 11170 * @return the total vertical range represented by the vertical scrollbar 11171 * 11172 * <p>The default range is the drawing height of this view.</p> 11173 * 11174 * @see #computeVerticalScrollExtent() 11175 * @see #computeVerticalScrollOffset() 11176 * @see android.widget.ScrollBarDrawable 11177 */ 11178 protected int computeVerticalScrollRange() { 11179 return getHeight(); 11180 } 11181 11182 /** 11183 * <p>Compute the vertical offset of the vertical scrollbar's thumb 11184 * within the horizontal range. This value is used to compute the position 11185 * of the thumb within the scrollbar's track.</p> 11186 * 11187 * <p>The range is expressed in arbitrary units that must be the same as the 11188 * units used by {@link #computeVerticalScrollRange()} and 11189 * {@link #computeVerticalScrollExtent()}.</p> 11190 * 11191 * <p>The default offset is the scroll offset of this view.</p> 11192 * 11193 * @return the vertical offset of the scrollbar's thumb 11194 * 11195 * @see #computeVerticalScrollRange() 11196 * @see #computeVerticalScrollExtent() 11197 * @see android.widget.ScrollBarDrawable 11198 */ 11199 protected int computeVerticalScrollOffset() { 11200 return mScrollY; 11201 } 11202 11203 /** 11204 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 11205 * within the vertical range. This value is used to compute the length 11206 * of the thumb within the scrollbar's track.</p> 11207 * 11208 * <p>The range is expressed in arbitrary units that must be the same as the 11209 * units used by {@link #computeVerticalScrollRange()} and 11210 * {@link #computeVerticalScrollOffset()}.</p> 11211 * 11212 * <p>The default extent is the drawing height of this view.</p> 11213 * 11214 * @return the vertical extent of the scrollbar's thumb 11215 * 11216 * @see #computeVerticalScrollRange() 11217 * @see #computeVerticalScrollOffset() 11218 * @see android.widget.ScrollBarDrawable 11219 */ 11220 protected int computeVerticalScrollExtent() { 11221 return getHeight(); 11222 } 11223 11224 /** 11225 * Check if this view can be scrolled horizontally in a certain direction. 11226 * 11227 * @param direction Negative to check scrolling left, positive to check scrolling right. 11228 * @return true if this view can be scrolled in the specified direction, false otherwise. 11229 */ 11230 public boolean canScrollHorizontally(int direction) { 11231 final int offset = computeHorizontalScrollOffset(); 11232 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 11233 if (range == 0) return false; 11234 if (direction < 0) { 11235 return offset > 0; 11236 } else { 11237 return offset < range - 1; 11238 } 11239 } 11240 11241 /** 11242 * Check if this view can be scrolled vertically in a certain direction. 11243 * 11244 * @param direction Negative to check scrolling up, positive to check scrolling down. 11245 * @return true if this view can be scrolled in the specified direction, false otherwise. 11246 */ 11247 public boolean canScrollVertically(int direction) { 11248 final int offset = computeVerticalScrollOffset(); 11249 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 11250 if (range == 0) return false; 11251 if (direction < 0) { 11252 return offset > 0; 11253 } else { 11254 return offset < range - 1; 11255 } 11256 } 11257 11258 /** 11259 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 11260 * scrollbars are painted only if they have been awakened first.</p> 11261 * 11262 * @param canvas the canvas on which to draw the scrollbars 11263 * 11264 * @see #awakenScrollBars(int) 11265 */ 11266 protected final void onDrawScrollBars(Canvas canvas) { 11267 // scrollbars are drawn only when the animation is running 11268 final ScrollabilityCache cache = mScrollCache; 11269 if (cache != null) { 11270 11271 int state = cache.state; 11272 11273 if (state == ScrollabilityCache.OFF) { 11274 return; 11275 } 11276 11277 boolean invalidate = false; 11278 11279 if (state == ScrollabilityCache.FADING) { 11280 // We're fading -- get our fade interpolation 11281 if (cache.interpolatorValues == null) { 11282 cache.interpolatorValues = new float[1]; 11283 } 11284 11285 float[] values = cache.interpolatorValues; 11286 11287 // Stops the animation if we're done 11288 if (cache.scrollBarInterpolator.timeToValues(values) == 11289 Interpolator.Result.FREEZE_END) { 11290 cache.state = ScrollabilityCache.OFF; 11291 } else { 11292 cache.scrollBar.setAlpha(Math.round(values[0])); 11293 } 11294 11295 // This will make the scroll bars inval themselves after 11296 // drawing. We only want this when we're fading so that 11297 // we prevent excessive redraws 11298 invalidate = true; 11299 } else { 11300 // We're just on -- but we may have been fading before so 11301 // reset alpha 11302 cache.scrollBar.setAlpha(255); 11303 } 11304 11305 11306 final int viewFlags = mViewFlags; 11307 11308 final boolean drawHorizontalScrollBar = 11309 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11310 final boolean drawVerticalScrollBar = 11311 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 11312 && !isVerticalScrollBarHidden(); 11313 11314 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 11315 final int width = mRight - mLeft; 11316 final int height = mBottom - mTop; 11317 11318 final ScrollBarDrawable scrollBar = cache.scrollBar; 11319 11320 final int scrollX = mScrollX; 11321 final int scrollY = mScrollY; 11322 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 11323 11324 int left, top, right, bottom; 11325 11326 if (drawHorizontalScrollBar) { 11327 int size = scrollBar.getSize(false); 11328 if (size <= 0) { 11329 size = cache.scrollBarSize; 11330 } 11331 11332 scrollBar.setParameters(computeHorizontalScrollRange(), 11333 computeHorizontalScrollOffset(), 11334 computeHorizontalScrollExtent(), false); 11335 final int verticalScrollBarGap = drawVerticalScrollBar ? 11336 getVerticalScrollbarWidth() : 0; 11337 top = scrollY + height - size - (mUserPaddingBottom & inside); 11338 left = scrollX + (mPaddingLeft & inside); 11339 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 11340 bottom = top + size; 11341 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 11342 if (invalidate) { 11343 invalidate(left, top, right, bottom); 11344 } 11345 } 11346 11347 if (drawVerticalScrollBar) { 11348 int size = scrollBar.getSize(true); 11349 if (size <= 0) { 11350 size = cache.scrollBarSize; 11351 } 11352 11353 scrollBar.setParameters(computeVerticalScrollRange(), 11354 computeVerticalScrollOffset(), 11355 computeVerticalScrollExtent(), true); 11356 int verticalScrollbarPosition = mVerticalScrollbarPosition; 11357 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 11358 verticalScrollbarPosition = isLayoutRtl() ? 11359 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 11360 } 11361 switch (verticalScrollbarPosition) { 11362 default: 11363 case SCROLLBAR_POSITION_RIGHT: 11364 left = scrollX + width - size - (mUserPaddingRight & inside); 11365 break; 11366 case SCROLLBAR_POSITION_LEFT: 11367 left = scrollX + (mUserPaddingLeft & inside); 11368 break; 11369 } 11370 top = scrollY + (mPaddingTop & inside); 11371 right = left + size; 11372 bottom = scrollY + height - (mUserPaddingBottom & inside); 11373 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 11374 if (invalidate) { 11375 invalidate(left, top, right, bottom); 11376 } 11377 } 11378 } 11379 } 11380 } 11381 11382 /** 11383 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 11384 * FastScroller is visible. 11385 * @return whether to temporarily hide the vertical scrollbar 11386 * @hide 11387 */ 11388 protected boolean isVerticalScrollBarHidden() { 11389 return false; 11390 } 11391 11392 /** 11393 * <p>Draw the horizontal scrollbar if 11394 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 11395 * 11396 * @param canvas the canvas on which to draw the scrollbar 11397 * @param scrollBar the scrollbar's drawable 11398 * 11399 * @see #isHorizontalScrollBarEnabled() 11400 * @see #computeHorizontalScrollRange() 11401 * @see #computeHorizontalScrollExtent() 11402 * @see #computeHorizontalScrollOffset() 11403 * @see android.widget.ScrollBarDrawable 11404 * @hide 11405 */ 11406 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 11407 int l, int t, int r, int b) { 11408 scrollBar.setBounds(l, t, r, b); 11409 scrollBar.draw(canvas); 11410 } 11411 11412 /** 11413 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 11414 * returns true.</p> 11415 * 11416 * @param canvas the canvas on which to draw the scrollbar 11417 * @param scrollBar the scrollbar's drawable 11418 * 11419 * @see #isVerticalScrollBarEnabled() 11420 * @see #computeVerticalScrollRange() 11421 * @see #computeVerticalScrollExtent() 11422 * @see #computeVerticalScrollOffset() 11423 * @see android.widget.ScrollBarDrawable 11424 * @hide 11425 */ 11426 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 11427 int l, int t, int r, int b) { 11428 scrollBar.setBounds(l, t, r, b); 11429 scrollBar.draw(canvas); 11430 } 11431 11432 /** 11433 * Implement this to do your drawing. 11434 * 11435 * @param canvas the canvas on which the background will be drawn 11436 */ 11437 protected void onDraw(Canvas canvas) { 11438 } 11439 11440 /* 11441 * Caller is responsible for calling requestLayout if necessary. 11442 * (This allows addViewInLayout to not request a new layout.) 11443 */ 11444 void assignParent(ViewParent parent) { 11445 if (mParent == null) { 11446 mParent = parent; 11447 } else if (parent == null) { 11448 mParent = null; 11449 } else { 11450 throw new RuntimeException("view " + this + " being added, but" 11451 + " it already has a parent"); 11452 } 11453 } 11454 11455 /** 11456 * This is called when the view is attached to a window. At this point it 11457 * has a Surface and will start drawing. Note that this function is 11458 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 11459 * however it may be called any time before the first onDraw -- including 11460 * before or after {@link #onMeasure(int, int)}. 11461 * 11462 * @see #onDetachedFromWindow() 11463 */ 11464 protected void onAttachedToWindow() { 11465 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 11466 mParent.requestTransparentRegion(this); 11467 } 11468 11469 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 11470 initialAwakenScrollBars(); 11471 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 11472 } 11473 11474 jumpDrawablesToCurrentState(); 11475 11476 resolveRtlProperties(); 11477 11478 clearAccessibilityFocus(); 11479 if (isFocused()) { 11480 InputMethodManager imm = InputMethodManager.peekInstance(); 11481 imm.focusIn(this); 11482 } 11483 11484 if (mAttachInfo != null && mDisplayList != null) { 11485 mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList); 11486 } 11487 } 11488 11489 void resolveRtlProperties() { 11490 // Order is important here: LayoutDirection MUST be resolved first... 11491 resolveLayoutDirection(); 11492 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 11493 resolvePadding(); 11494 resolveLayoutParams(); 11495 resolveTextDirection(); 11496 resolveTextAlignment(); 11497 resolveDrawables(); 11498 } 11499 11500 /** 11501 * @see #onScreenStateChanged(int) 11502 */ 11503 void dispatchScreenStateChanged(int screenState) { 11504 onScreenStateChanged(screenState); 11505 } 11506 11507 /** 11508 * This method is called whenever the state of the screen this view is 11509 * attached to changes. A state change will usually occurs when the screen 11510 * turns on or off (whether it happens automatically or the user does it 11511 * manually.) 11512 * 11513 * @param screenState The new state of the screen. Can be either 11514 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 11515 */ 11516 public void onScreenStateChanged(int screenState) { 11517 } 11518 11519 /** 11520 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 11521 */ 11522 private boolean hasRtlSupport() { 11523 return mContext.getApplicationInfo().hasRtlSupport(); 11524 } 11525 11526 /** 11527 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 11528 * that the parent directionality can and will be resolved before its children. 11529 * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done. 11530 */ 11531 public void resolveLayoutDirection() { 11532 // Clear any previous layout direction resolution 11533 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 11534 11535 if (hasRtlSupport()) { 11536 // Set resolved depending on layout direction 11537 switch (getLayoutDirection()) { 11538 case LAYOUT_DIRECTION_INHERIT: 11539 // We cannot resolve yet. LTR is by default and let the resolution happen again 11540 // later to get the correct resolved value 11541 if (!canResolveLayoutDirection()) return; 11542 11543 ViewGroup viewGroup = ((ViewGroup) mParent); 11544 11545 // We cannot resolve yet on the parent too. LTR is by default and let the 11546 // resolution happen again later 11547 if (!viewGroup.canResolveLayoutDirection()) return; 11548 11549 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11550 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11551 } 11552 break; 11553 case LAYOUT_DIRECTION_RTL: 11554 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11555 break; 11556 case LAYOUT_DIRECTION_LOCALE: 11557 if(isLayoutDirectionRtl(Locale.getDefault())) { 11558 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11559 } 11560 break; 11561 default: 11562 // Nothing to do, LTR by default 11563 } 11564 } 11565 11566 // Set to resolved 11567 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 11568 onResolvedLayoutDirectionChanged(); 11569 } 11570 11571 /** 11572 * Called when layout direction has been resolved. 11573 * 11574 * The default implementation does nothing. 11575 */ 11576 public void onResolvedLayoutDirectionChanged() { 11577 } 11578 11579 /** 11580 * Return if padding has been resolved 11581 */ 11582 boolean isPaddingResolved() { 11583 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) != 0; 11584 } 11585 11586 /** 11587 * Resolve padding depending on layout direction. 11588 */ 11589 public void resolvePadding() { 11590 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 11591 if (targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport()) { 11592 // Pre Jelly Bean MR1 case (compatibility mode) OR no RTL support case: 11593 // left / right padding are used if defined. If they are not defined and start / end 11594 // padding are defined (e.g. in Frameworks resources), then we use start / end and 11595 // resolve them as left / right (layout direction is not taken into account). 11596 if (mUserPaddingLeftInitial == UNDEFINED_PADDING && 11597 mUserPaddingStart != UNDEFINED_PADDING) { 11598 mUserPaddingLeft = mUserPaddingStart; 11599 } 11600 if (mUserPaddingRightInitial == UNDEFINED_PADDING 11601 && mUserPaddingEnd != UNDEFINED_PADDING) { 11602 mUserPaddingRight = mUserPaddingEnd; 11603 } 11604 11605 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 11606 11607 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, 11608 mUserPaddingBottom); 11609 } else { 11610 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 11611 // If start / end padding are defined, they will be resolved (hence overriding) to 11612 // left / right or right / left depending on the resolved layout direction. 11613 // If start / end padding are not defined, use the left / right ones. 11614 int resolvedLayoutDirection = getResolvedLayoutDirection(); 11615 // Set user padding to initial values ... 11616 mUserPaddingLeft = (mUserPaddingLeftInitial == UNDEFINED_PADDING) ? 11617 0 : mUserPaddingLeftInitial; 11618 mUserPaddingRight = (mUserPaddingRightInitial == UNDEFINED_PADDING) ? 11619 0 : mUserPaddingRightInitial; 11620 // ... then resolve it. 11621 switch (resolvedLayoutDirection) { 11622 case LAYOUT_DIRECTION_RTL: 11623 if (mUserPaddingStart != UNDEFINED_PADDING) { 11624 mUserPaddingRight = mUserPaddingStart; 11625 } 11626 if (mUserPaddingEnd != UNDEFINED_PADDING) { 11627 mUserPaddingLeft = mUserPaddingEnd; 11628 } 11629 break; 11630 case LAYOUT_DIRECTION_LTR: 11631 default: 11632 if (mUserPaddingStart != UNDEFINED_PADDING) { 11633 mUserPaddingLeft = mUserPaddingStart; 11634 } 11635 if (mUserPaddingEnd != UNDEFINED_PADDING) { 11636 mUserPaddingRight = mUserPaddingEnd; 11637 } 11638 } 11639 11640 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 11641 11642 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, 11643 mUserPaddingBottom); 11644 onPaddingChanged(resolvedLayoutDirection); 11645 } 11646 11647 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 11648 } 11649 11650 /** 11651 * Resolve padding depending on the layout direction. Subclasses that care about 11652 * padding resolution should override this method. The default implementation does 11653 * nothing. 11654 * 11655 * @param layoutDirection the direction of the layout 11656 * 11657 * @see #LAYOUT_DIRECTION_LTR 11658 * @see #LAYOUT_DIRECTION_RTL 11659 */ 11660 public void onPaddingChanged(int layoutDirection) { 11661 } 11662 11663 /** 11664 * Check if layout direction resolution can be done. 11665 * 11666 * @return true if layout direction resolution can be done otherwise return false. 11667 */ 11668 public boolean canResolveLayoutDirection() { 11669 switch (getLayoutDirection()) { 11670 case LAYOUT_DIRECTION_INHERIT: 11671 return (mParent != null) && (mParent instanceof ViewGroup); 11672 default: 11673 return true; 11674 } 11675 } 11676 11677 /** 11678 * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset} 11679 * when reset is done. 11680 */ 11681 public void resetResolvedLayoutDirection() { 11682 // Reset the current resolved bits 11683 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 11684 onResolvedLayoutDirectionReset(); 11685 // Reset also the text direction 11686 resetResolvedTextDirection(); 11687 } 11688 11689 /** 11690 * Called during reset of resolved layout direction. 11691 * 11692 * Subclasses need to override this method to clear cached information that depends on the 11693 * resolved layout direction, or to inform child views that inherit their layout direction. 11694 * 11695 * The default implementation does nothing. 11696 */ 11697 public void onResolvedLayoutDirectionReset() { 11698 } 11699 11700 /** 11701 * Check if a Locale uses an RTL script. 11702 * 11703 * @param locale Locale to check 11704 * @return true if the Locale uses an RTL script. 11705 */ 11706 protected static boolean isLayoutDirectionRtl(Locale locale) { 11707 return (LAYOUT_DIRECTION_RTL == TextUtils.getLayoutDirectionFromLocale(locale)); 11708 } 11709 11710 /** 11711 * This is called when the view is detached from a window. At this point it 11712 * no longer has a surface for drawing. 11713 * 11714 * @see #onAttachedToWindow() 11715 */ 11716 protected void onDetachedFromWindow() { 11717 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 11718 11719 removeUnsetPressCallback(); 11720 removeLongPressCallback(); 11721 removePerformClickCallback(); 11722 removeSendViewScrolledAccessibilityEventCallback(); 11723 11724 destroyDrawingCache(); 11725 11726 destroyLayer(false); 11727 11728 if (mAttachInfo != null) { 11729 if (mDisplayList != null) { 11730 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList); 11731 } 11732 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 11733 } else { 11734 // Should never happen 11735 clearDisplayList(); 11736 } 11737 11738 mCurrentAnimation = null; 11739 11740 resetResolvedLayoutDirection(); 11741 resetResolvedTextAlignment(); 11742 resetAccessibilityStateChanged(); 11743 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 11744 } 11745 11746 /** 11747 * @return The number of times this view has been attached to a window 11748 */ 11749 protected int getWindowAttachCount() { 11750 return mWindowAttachCount; 11751 } 11752 11753 /** 11754 * Retrieve a unique token identifying the window this view is attached to. 11755 * @return Return the window's token for use in 11756 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 11757 */ 11758 public IBinder getWindowToken() { 11759 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 11760 } 11761 11762 /** 11763 * Retrieve a unique token identifying the top-level "real" window of 11764 * the window that this view is attached to. That is, this is like 11765 * {@link #getWindowToken}, except if the window this view in is a panel 11766 * window (attached to another containing window), then the token of 11767 * the containing window is returned instead. 11768 * 11769 * @return Returns the associated window token, either 11770 * {@link #getWindowToken()} or the containing window's token. 11771 */ 11772 public IBinder getApplicationWindowToken() { 11773 AttachInfo ai = mAttachInfo; 11774 if (ai != null) { 11775 IBinder appWindowToken = ai.mPanelParentWindowToken; 11776 if (appWindowToken == null) { 11777 appWindowToken = ai.mWindowToken; 11778 } 11779 return appWindowToken; 11780 } 11781 return null; 11782 } 11783 11784 /** 11785 * Gets the logical display to which the view's window has been attached. 11786 * 11787 * @return The logical display, or null if the view is not currently attached to a window. 11788 */ 11789 public Display getDisplay() { 11790 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 11791 } 11792 11793 /** 11794 * Retrieve private session object this view hierarchy is using to 11795 * communicate with the window manager. 11796 * @return the session object to communicate with the window manager 11797 */ 11798 /*package*/ IWindowSession getWindowSession() { 11799 return mAttachInfo != null ? mAttachInfo.mSession : null; 11800 } 11801 11802 /** 11803 * @param info the {@link android.view.View.AttachInfo} to associated with 11804 * this view 11805 */ 11806 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 11807 //System.out.println("Attached! " + this); 11808 mAttachInfo = info; 11809 mWindowAttachCount++; 11810 // We will need to evaluate the drawable state at least once. 11811 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 11812 if (mFloatingTreeObserver != null) { 11813 info.mTreeObserver.merge(mFloatingTreeObserver); 11814 mFloatingTreeObserver = null; 11815 } 11816 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 11817 mAttachInfo.mScrollContainers.add(this); 11818 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 11819 } 11820 performCollectViewAttributes(mAttachInfo, visibility); 11821 onAttachedToWindow(); 11822 11823 ListenerInfo li = mListenerInfo; 11824 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 11825 li != null ? li.mOnAttachStateChangeListeners : null; 11826 if (listeners != null && listeners.size() > 0) { 11827 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 11828 // perform the dispatching. The iterator is a safe guard against listeners that 11829 // could mutate the list by calling the various add/remove methods. This prevents 11830 // the array from being modified while we iterate it. 11831 for (OnAttachStateChangeListener listener : listeners) { 11832 listener.onViewAttachedToWindow(this); 11833 } 11834 } 11835 11836 int vis = info.mWindowVisibility; 11837 if (vis != GONE) { 11838 onWindowVisibilityChanged(vis); 11839 } 11840 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 11841 // If nobody has evaluated the drawable state yet, then do it now. 11842 refreshDrawableState(); 11843 } 11844 needGlobalAttributesUpdate(false); 11845 } 11846 11847 void dispatchDetachedFromWindow() { 11848 AttachInfo info = mAttachInfo; 11849 if (info != null) { 11850 int vis = info.mWindowVisibility; 11851 if (vis != GONE) { 11852 onWindowVisibilityChanged(GONE); 11853 } 11854 } 11855 11856 onDetachedFromWindow(); 11857 11858 ListenerInfo li = mListenerInfo; 11859 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 11860 li != null ? li.mOnAttachStateChangeListeners : null; 11861 if (listeners != null && listeners.size() > 0) { 11862 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 11863 // perform the dispatching. The iterator is a safe guard against listeners that 11864 // could mutate the list by calling the various add/remove methods. This prevents 11865 // the array from being modified while we iterate it. 11866 for (OnAttachStateChangeListener listener : listeners) { 11867 listener.onViewDetachedFromWindow(this); 11868 } 11869 } 11870 11871 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 11872 mAttachInfo.mScrollContainers.remove(this); 11873 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 11874 } 11875 11876 mAttachInfo = null; 11877 } 11878 11879 /** 11880 * Store this view hierarchy's frozen state into the given container. 11881 * 11882 * @param container The SparseArray in which to save the view's state. 11883 * 11884 * @see #restoreHierarchyState(android.util.SparseArray) 11885 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11886 * @see #onSaveInstanceState() 11887 */ 11888 public void saveHierarchyState(SparseArray<Parcelable> container) { 11889 dispatchSaveInstanceState(container); 11890 } 11891 11892 /** 11893 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 11894 * this view and its children. May be overridden to modify how freezing happens to a 11895 * view's children; for example, some views may want to not store state for their children. 11896 * 11897 * @param container The SparseArray in which to save the view's state. 11898 * 11899 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 11900 * @see #saveHierarchyState(android.util.SparseArray) 11901 * @see #onSaveInstanceState() 11902 */ 11903 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 11904 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 11905 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 11906 Parcelable state = onSaveInstanceState(); 11907 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 11908 throw new IllegalStateException( 11909 "Derived class did not call super.onSaveInstanceState()"); 11910 } 11911 if (state != null) { 11912 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 11913 // + ": " + state); 11914 container.put(mID, state); 11915 } 11916 } 11917 } 11918 11919 /** 11920 * Hook allowing a view to generate a representation of its internal state 11921 * that can later be used to create a new instance with that same state. 11922 * This state should only contain information that is not persistent or can 11923 * not be reconstructed later. For example, you will never store your 11924 * current position on screen because that will be computed again when a 11925 * new instance of the view is placed in its view hierarchy. 11926 * <p> 11927 * Some examples of things you may store here: the current cursor position 11928 * in a text view (but usually not the text itself since that is stored in a 11929 * content provider or other persistent storage), the currently selected 11930 * item in a list view. 11931 * 11932 * @return Returns a Parcelable object containing the view's current dynamic 11933 * state, or null if there is nothing interesting to save. The 11934 * default implementation returns null. 11935 * @see #onRestoreInstanceState(android.os.Parcelable) 11936 * @see #saveHierarchyState(android.util.SparseArray) 11937 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11938 * @see #setSaveEnabled(boolean) 11939 */ 11940 protected Parcelable onSaveInstanceState() { 11941 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 11942 return BaseSavedState.EMPTY_STATE; 11943 } 11944 11945 /** 11946 * Restore this view hierarchy's frozen state from the given container. 11947 * 11948 * @param container The SparseArray which holds previously frozen states. 11949 * 11950 * @see #saveHierarchyState(android.util.SparseArray) 11951 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 11952 * @see #onRestoreInstanceState(android.os.Parcelable) 11953 */ 11954 public void restoreHierarchyState(SparseArray<Parcelable> container) { 11955 dispatchRestoreInstanceState(container); 11956 } 11957 11958 /** 11959 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 11960 * state for this view and its children. May be overridden to modify how restoring 11961 * happens to a view's children; for example, some views may want to not store state 11962 * for their children. 11963 * 11964 * @param container The SparseArray which holds previously saved state. 11965 * 11966 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11967 * @see #restoreHierarchyState(android.util.SparseArray) 11968 * @see #onRestoreInstanceState(android.os.Parcelable) 11969 */ 11970 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 11971 if (mID != NO_ID) { 11972 Parcelable state = container.get(mID); 11973 if (state != null) { 11974 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 11975 // + ": " + state); 11976 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 11977 onRestoreInstanceState(state); 11978 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 11979 throw new IllegalStateException( 11980 "Derived class did not call super.onRestoreInstanceState()"); 11981 } 11982 } 11983 } 11984 } 11985 11986 /** 11987 * Hook allowing a view to re-apply a representation of its internal state that had previously 11988 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 11989 * null state. 11990 * 11991 * @param state The frozen state that had previously been returned by 11992 * {@link #onSaveInstanceState}. 11993 * 11994 * @see #onSaveInstanceState() 11995 * @see #restoreHierarchyState(android.util.SparseArray) 11996 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 11997 */ 11998 protected void onRestoreInstanceState(Parcelable state) { 11999 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12000 if (state != BaseSavedState.EMPTY_STATE && state != null) { 12001 throw new IllegalArgumentException("Wrong state class, expecting View State but " 12002 + "received " + state.getClass().toString() + " instead. This usually happens " 12003 + "when two views of different type have the same id in the same hierarchy. " 12004 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 12005 + "other views do not use the same id."); 12006 } 12007 } 12008 12009 /** 12010 * <p>Return the time at which the drawing of the view hierarchy started.</p> 12011 * 12012 * @return the drawing start time in milliseconds 12013 */ 12014 public long getDrawingTime() { 12015 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 12016 } 12017 12018 /** 12019 * <p>Enables or disables the duplication of the parent's state into this view. When 12020 * duplication is enabled, this view gets its drawable state from its parent rather 12021 * than from its own internal properties.</p> 12022 * 12023 * <p>Note: in the current implementation, setting this property to true after the 12024 * view was added to a ViewGroup might have no effect at all. This property should 12025 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 12026 * 12027 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 12028 * property is enabled, an exception will be thrown.</p> 12029 * 12030 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 12031 * parent, these states should not be affected by this method.</p> 12032 * 12033 * @param enabled True to enable duplication of the parent's drawable state, false 12034 * to disable it. 12035 * 12036 * @see #getDrawableState() 12037 * @see #isDuplicateParentStateEnabled() 12038 */ 12039 public void setDuplicateParentStateEnabled(boolean enabled) { 12040 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 12041 } 12042 12043 /** 12044 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 12045 * 12046 * @return True if this view's drawable state is duplicated from the parent, 12047 * false otherwise 12048 * 12049 * @see #getDrawableState() 12050 * @see #setDuplicateParentStateEnabled(boolean) 12051 */ 12052 public boolean isDuplicateParentStateEnabled() { 12053 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 12054 } 12055 12056 /** 12057 * <p>Specifies the type of layer backing this view. The layer can be 12058 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 12059 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 12060 * 12061 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12062 * instance that controls how the layer is composed on screen. The following 12063 * properties of the paint are taken into account when composing the layer:</p> 12064 * <ul> 12065 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12066 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12067 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12068 * </ul> 12069 * 12070 * <p>If this view has an alpha value set to < 1.0 by calling 12071 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 12072 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 12073 * equivalent to setting a hardware layer on this view and providing a paint with 12074 * the desired alpha value.</p> 12075 * 12076 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 12077 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 12078 * for more information on when and how to use layers.</p> 12079 * 12080 * @param layerType The type of layer to use with this view, must be one of 12081 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12082 * {@link #LAYER_TYPE_HARDWARE} 12083 * @param paint The paint used to compose the layer. This argument is optional 12084 * and can be null. It is ignored when the layer type is 12085 * {@link #LAYER_TYPE_NONE} 12086 * 12087 * @see #getLayerType() 12088 * @see #LAYER_TYPE_NONE 12089 * @see #LAYER_TYPE_SOFTWARE 12090 * @see #LAYER_TYPE_HARDWARE 12091 * @see #setAlpha(float) 12092 * 12093 * @attr ref android.R.styleable#View_layerType 12094 */ 12095 public void setLayerType(int layerType, Paint paint) { 12096 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 12097 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 12098 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 12099 } 12100 12101 if (layerType == mLayerType) { 12102 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 12103 mLayerPaint = paint == null ? new Paint() : paint; 12104 invalidateParentCaches(); 12105 invalidate(true); 12106 } 12107 return; 12108 } 12109 12110 // Destroy any previous software drawing cache if needed 12111 switch (mLayerType) { 12112 case LAYER_TYPE_HARDWARE: 12113 destroyLayer(false); 12114 // fall through - non-accelerated views may use software layer mechanism instead 12115 case LAYER_TYPE_SOFTWARE: 12116 destroyDrawingCache(); 12117 break; 12118 default: 12119 break; 12120 } 12121 12122 mLayerType = layerType; 12123 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 12124 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 12125 mLocalDirtyRect = layerDisabled ? null : new Rect(); 12126 12127 invalidateParentCaches(); 12128 invalidate(true); 12129 } 12130 12131 /** 12132 * Updates the {@link Paint} object used with the current layer (used only if the current 12133 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 12134 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 12135 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 12136 * ensure that the view gets redrawn immediately. 12137 * 12138 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12139 * instance that controls how the layer is composed on screen. The following 12140 * properties of the paint are taken into account when composing the layer:</p> 12141 * <ul> 12142 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12143 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12144 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12145 * </ul> 12146 * 12147 * <p>If this view has an alpha value set to < 1.0 by calling 12148 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 12149 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 12150 * equivalent to setting a hardware layer on this view and providing a paint with 12151 * the desired alpha value.</p> 12152 * 12153 * @param paint The paint used to compose the layer. This argument is optional 12154 * and can be null. It is ignored when the layer type is 12155 * {@link #LAYER_TYPE_NONE} 12156 * 12157 * @see #setLayerType(int, android.graphics.Paint) 12158 */ 12159 public void setLayerPaint(Paint paint) { 12160 int layerType = getLayerType(); 12161 if (layerType != LAYER_TYPE_NONE) { 12162 mLayerPaint = paint == null ? new Paint() : paint; 12163 if (layerType == LAYER_TYPE_HARDWARE) { 12164 HardwareLayer layer = getHardwareLayer(); 12165 if (layer != null) { 12166 layer.setLayerPaint(paint); 12167 } 12168 invalidateViewProperty(false, false); 12169 } else { 12170 invalidate(); 12171 } 12172 } 12173 } 12174 12175 /** 12176 * Indicates whether this view has a static layer. A view with layer type 12177 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 12178 * dynamic. 12179 */ 12180 boolean hasStaticLayer() { 12181 return true; 12182 } 12183 12184 /** 12185 * Indicates what type of layer is currently associated with this view. By default 12186 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 12187 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 12188 * for more information on the different types of layers. 12189 * 12190 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12191 * {@link #LAYER_TYPE_HARDWARE} 12192 * 12193 * @see #setLayerType(int, android.graphics.Paint) 12194 * @see #buildLayer() 12195 * @see #LAYER_TYPE_NONE 12196 * @see #LAYER_TYPE_SOFTWARE 12197 * @see #LAYER_TYPE_HARDWARE 12198 */ 12199 public int getLayerType() { 12200 return mLayerType; 12201 } 12202 12203 /** 12204 * Forces this view's layer to be created and this view to be rendered 12205 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 12206 * invoking this method will have no effect. 12207 * 12208 * This method can for instance be used to render a view into its layer before 12209 * starting an animation. If this view is complex, rendering into the layer 12210 * before starting the animation will avoid skipping frames. 12211 * 12212 * @throws IllegalStateException If this view is not attached to a window 12213 * 12214 * @see #setLayerType(int, android.graphics.Paint) 12215 */ 12216 public void buildLayer() { 12217 if (mLayerType == LAYER_TYPE_NONE) return; 12218 12219 if (mAttachInfo == null) { 12220 throw new IllegalStateException("This view must be attached to a window first"); 12221 } 12222 12223 switch (mLayerType) { 12224 case LAYER_TYPE_HARDWARE: 12225 if (mAttachInfo.mHardwareRenderer != null && 12226 mAttachInfo.mHardwareRenderer.isEnabled() && 12227 mAttachInfo.mHardwareRenderer.validate()) { 12228 getHardwareLayer(); 12229 } 12230 break; 12231 case LAYER_TYPE_SOFTWARE: 12232 buildDrawingCache(true); 12233 break; 12234 } 12235 } 12236 12237 /** 12238 * <p>Returns a hardware layer that can be used to draw this view again 12239 * without executing its draw method.</p> 12240 * 12241 * @return A HardwareLayer ready to render, or null if an error occurred. 12242 */ 12243 HardwareLayer getHardwareLayer() { 12244 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 12245 !mAttachInfo.mHardwareRenderer.isEnabled()) { 12246 return null; 12247 } 12248 12249 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 12250 12251 final int width = mRight - mLeft; 12252 final int height = mBottom - mTop; 12253 12254 if (width == 0 || height == 0) { 12255 return null; 12256 } 12257 12258 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 12259 if (mHardwareLayer == null) { 12260 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 12261 width, height, isOpaque()); 12262 mLocalDirtyRect.set(0, 0, width, height); 12263 } else { 12264 if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 12265 if (mHardwareLayer.resize(width, height)) { 12266 mLocalDirtyRect.set(0, 0, width, height); 12267 } 12268 } 12269 12270 // This should not be necessary but applications that change 12271 // the parameters of their background drawable without calling 12272 // this.setBackground(Drawable) can leave the view in a bad state 12273 // (for instance isOpaque() returns true, but the background is 12274 // not opaque.) 12275 computeOpaqueFlags(); 12276 12277 final boolean opaque = isOpaque(); 12278 if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) { 12279 mHardwareLayer.setOpaque(opaque); 12280 mLocalDirtyRect.set(0, 0, width, height); 12281 } 12282 } 12283 12284 // The layer is not valid if the underlying GPU resources cannot be allocated 12285 if (!mHardwareLayer.isValid()) { 12286 return null; 12287 } 12288 mHardwareLayer.setLayerPaint(mLayerPaint); 12289 12290 mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 12291 mLocalDirtyRect.setEmpty(); 12292 } 12293 12294 return mHardwareLayer; 12295 } 12296 12297 /** 12298 * Destroys this View's hardware layer if possible. 12299 * 12300 * @return True if the layer was destroyed, false otherwise. 12301 * 12302 * @see #setLayerType(int, android.graphics.Paint) 12303 * @see #LAYER_TYPE_HARDWARE 12304 */ 12305 boolean destroyLayer(boolean valid) { 12306 if (mHardwareLayer != null) { 12307 AttachInfo info = mAttachInfo; 12308 if (info != null && info.mHardwareRenderer != null && 12309 info.mHardwareRenderer.isEnabled() && 12310 (valid || info.mHardwareRenderer.validate())) { 12311 mHardwareLayer.destroy(); 12312 mHardwareLayer = null; 12313 12314 invalidate(true); 12315 invalidateParentCaches(); 12316 } 12317 return true; 12318 } 12319 return false; 12320 } 12321 12322 /** 12323 * Destroys all hardware rendering resources. This method is invoked 12324 * when the system needs to reclaim resources. Upon execution of this 12325 * method, you should free any OpenGL resources created by the view. 12326 * 12327 * Note: you <strong>must</strong> call 12328 * <code>super.destroyHardwareResources()</code> when overriding 12329 * this method. 12330 * 12331 * @hide 12332 */ 12333 protected void destroyHardwareResources() { 12334 destroyLayer(true); 12335 } 12336 12337 /** 12338 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 12339 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 12340 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 12341 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 12342 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 12343 * null.</p> 12344 * 12345 * <p>Enabling the drawing cache is similar to 12346 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 12347 * acceleration is turned off. When hardware acceleration is turned on, enabling the 12348 * drawing cache has no effect on rendering because the system uses a different mechanism 12349 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 12350 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 12351 * for information on how to enable software and hardware layers.</p> 12352 * 12353 * <p>This API can be used to manually generate 12354 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 12355 * {@link #getDrawingCache()}.</p> 12356 * 12357 * @param enabled true to enable the drawing cache, false otherwise 12358 * 12359 * @see #isDrawingCacheEnabled() 12360 * @see #getDrawingCache() 12361 * @see #buildDrawingCache() 12362 * @see #setLayerType(int, android.graphics.Paint) 12363 */ 12364 public void setDrawingCacheEnabled(boolean enabled) { 12365 mCachingFailed = false; 12366 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 12367 } 12368 12369 /** 12370 * <p>Indicates whether the drawing cache is enabled for this view.</p> 12371 * 12372 * @return true if the drawing cache is enabled 12373 * 12374 * @see #setDrawingCacheEnabled(boolean) 12375 * @see #getDrawingCache() 12376 */ 12377 @ViewDebug.ExportedProperty(category = "drawing") 12378 public boolean isDrawingCacheEnabled() { 12379 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 12380 } 12381 12382 /** 12383 * Debugging utility which recursively outputs the dirty state of a view and its 12384 * descendants. 12385 * 12386 * @hide 12387 */ 12388 @SuppressWarnings({"UnusedDeclaration"}) 12389 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 12390 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 12391 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 12392 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 12393 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 12394 if (clear) { 12395 mPrivateFlags &= clearMask; 12396 } 12397 if (this instanceof ViewGroup) { 12398 ViewGroup parent = (ViewGroup) this; 12399 final int count = parent.getChildCount(); 12400 for (int i = 0; i < count; i++) { 12401 final View child = parent.getChildAt(i); 12402 child.outputDirtyFlags(indent + " ", clear, clearMask); 12403 } 12404 } 12405 } 12406 12407 /** 12408 * This method is used by ViewGroup to cause its children to restore or recreate their 12409 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 12410 * to recreate its own display list, which would happen if it went through the normal 12411 * draw/dispatchDraw mechanisms. 12412 * 12413 * @hide 12414 */ 12415 protected void dispatchGetDisplayList() {} 12416 12417 /** 12418 * A view that is not attached or hardware accelerated cannot create a display list. 12419 * This method checks these conditions and returns the appropriate result. 12420 * 12421 * @return true if view has the ability to create a display list, false otherwise. 12422 * 12423 * @hide 12424 */ 12425 public boolean canHaveDisplayList() { 12426 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 12427 } 12428 12429 /** 12430 * @return The HardwareRenderer associated with that view or null if hardware rendering 12431 * is not supported or this this has not been attached to a window. 12432 * 12433 * @hide 12434 */ 12435 public HardwareRenderer getHardwareRenderer() { 12436 if (mAttachInfo != null) { 12437 return mAttachInfo.mHardwareRenderer; 12438 } 12439 return null; 12440 } 12441 12442 /** 12443 * Returns a DisplayList. If the incoming displayList is null, one will be created. 12444 * Otherwise, the same display list will be returned (after having been rendered into 12445 * along the way, depending on the invalidation state of the view). 12446 * 12447 * @param displayList The previous version of this displayList, could be null. 12448 * @param isLayer Whether the requester of the display list is a layer. If so, 12449 * the view will avoid creating a layer inside the resulting display list. 12450 * @return A new or reused DisplayList object. 12451 */ 12452 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 12453 if (!canHaveDisplayList()) { 12454 return null; 12455 } 12456 12457 if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || 12458 displayList == null || !displayList.isValid() || 12459 (!isLayer && mRecreateDisplayList))) { 12460 // Don't need to recreate the display list, just need to tell our 12461 // children to restore/recreate theirs 12462 if (displayList != null && displayList.isValid() && 12463 !isLayer && !mRecreateDisplayList) { 12464 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12465 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12466 dispatchGetDisplayList(); 12467 12468 return displayList; 12469 } 12470 12471 if (!isLayer) { 12472 // If we got here, we're recreating it. Mark it as such to ensure that 12473 // we copy in child display lists into ours in drawChild() 12474 mRecreateDisplayList = true; 12475 } 12476 if (displayList == null) { 12477 final String name = getClass().getSimpleName(); 12478 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name); 12479 // If we're creating a new display list, make sure our parent gets invalidated 12480 // since they will need to recreate their display list to account for this 12481 // new child display list. 12482 invalidateParentCaches(); 12483 } 12484 12485 boolean caching = false; 12486 final HardwareCanvas canvas = displayList.start(); 12487 int width = mRight - mLeft; 12488 int height = mBottom - mTop; 12489 12490 try { 12491 canvas.setViewport(width, height); 12492 // The dirty rect should always be null for a display list 12493 canvas.onPreDraw(null); 12494 int layerType = getLayerType(); 12495 if (!isLayer && layerType != LAYER_TYPE_NONE) { 12496 if (layerType == LAYER_TYPE_HARDWARE) { 12497 final HardwareLayer layer = getHardwareLayer(); 12498 if (layer != null && layer.isValid()) { 12499 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 12500 } else { 12501 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 12502 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 12503 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 12504 } 12505 caching = true; 12506 } else { 12507 buildDrawingCache(true); 12508 Bitmap cache = getDrawingCache(true); 12509 if (cache != null) { 12510 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 12511 caching = true; 12512 } 12513 } 12514 } else { 12515 12516 computeScroll(); 12517 12518 canvas.translate(-mScrollX, -mScrollY); 12519 if (!isLayer) { 12520 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12521 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12522 } 12523 12524 // Fast path for layouts with no backgrounds 12525 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12526 dispatchDraw(canvas); 12527 } else { 12528 draw(canvas); 12529 } 12530 } 12531 } finally { 12532 canvas.onPostDraw(); 12533 12534 displayList.end(); 12535 displayList.setCaching(caching); 12536 if (isLayer) { 12537 displayList.setLeftTopRightBottom(0, 0, width, height); 12538 } else { 12539 setDisplayListProperties(displayList); 12540 } 12541 } 12542 } else if (!isLayer) { 12543 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12544 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12545 } 12546 12547 return displayList; 12548 } 12549 12550 /** 12551 * Get the DisplayList for the HardwareLayer 12552 * 12553 * @param layer The HardwareLayer whose DisplayList we want 12554 * @return A DisplayList fopr the specified HardwareLayer 12555 */ 12556 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 12557 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 12558 layer.setDisplayList(displayList); 12559 return displayList; 12560 } 12561 12562 12563 /** 12564 * <p>Returns a display list that can be used to draw this view again 12565 * without executing its draw method.</p> 12566 * 12567 * @return A DisplayList ready to replay, or null if caching is not enabled. 12568 * 12569 * @hide 12570 */ 12571 public DisplayList getDisplayList() { 12572 mDisplayList = getDisplayList(mDisplayList, false); 12573 return mDisplayList; 12574 } 12575 12576 private void clearDisplayList() { 12577 if (mDisplayList != null) { 12578 mDisplayList.invalidate(); 12579 mDisplayList.clear(); 12580 } 12581 } 12582 12583 /** 12584 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 12585 * 12586 * @return A non-scaled bitmap representing this view or null if cache is disabled. 12587 * 12588 * @see #getDrawingCache(boolean) 12589 */ 12590 public Bitmap getDrawingCache() { 12591 return getDrawingCache(false); 12592 } 12593 12594 /** 12595 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 12596 * is null when caching is disabled. If caching is enabled and the cache is not ready, 12597 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 12598 * draw from the cache when the cache is enabled. To benefit from the cache, you must 12599 * request the drawing cache by calling this method and draw it on screen if the 12600 * returned bitmap is not null.</p> 12601 * 12602 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 12603 * this method will create a bitmap of the same size as this view. Because this bitmap 12604 * will be drawn scaled by the parent ViewGroup, the result on screen might show 12605 * scaling artifacts. To avoid such artifacts, you should call this method by setting 12606 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 12607 * size than the view. This implies that your application must be able to handle this 12608 * size.</p> 12609 * 12610 * @param autoScale Indicates whether the generated bitmap should be scaled based on 12611 * the current density of the screen when the application is in compatibility 12612 * mode. 12613 * 12614 * @return A bitmap representing this view or null if cache is disabled. 12615 * 12616 * @see #setDrawingCacheEnabled(boolean) 12617 * @see #isDrawingCacheEnabled() 12618 * @see #buildDrawingCache(boolean) 12619 * @see #destroyDrawingCache() 12620 */ 12621 public Bitmap getDrawingCache(boolean autoScale) { 12622 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 12623 return null; 12624 } 12625 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 12626 buildDrawingCache(autoScale); 12627 } 12628 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 12629 } 12630 12631 /** 12632 * <p>Frees the resources used by the drawing cache. If you call 12633 * {@link #buildDrawingCache()} manually without calling 12634 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 12635 * should cleanup the cache with this method afterwards.</p> 12636 * 12637 * @see #setDrawingCacheEnabled(boolean) 12638 * @see #buildDrawingCache() 12639 * @see #getDrawingCache() 12640 */ 12641 public void destroyDrawingCache() { 12642 if (mDrawingCache != null) { 12643 mDrawingCache.recycle(); 12644 mDrawingCache = null; 12645 } 12646 if (mUnscaledDrawingCache != null) { 12647 mUnscaledDrawingCache.recycle(); 12648 mUnscaledDrawingCache = null; 12649 } 12650 } 12651 12652 /** 12653 * Setting a solid background color for the drawing cache's bitmaps will improve 12654 * performance and memory usage. Note, though that this should only be used if this 12655 * view will always be drawn on top of a solid color. 12656 * 12657 * @param color The background color to use for the drawing cache's bitmap 12658 * 12659 * @see #setDrawingCacheEnabled(boolean) 12660 * @see #buildDrawingCache() 12661 * @see #getDrawingCache() 12662 */ 12663 public void setDrawingCacheBackgroundColor(int color) { 12664 if (color != mDrawingCacheBackgroundColor) { 12665 mDrawingCacheBackgroundColor = color; 12666 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 12667 } 12668 } 12669 12670 /** 12671 * @see #setDrawingCacheBackgroundColor(int) 12672 * 12673 * @return The background color to used for the drawing cache's bitmap 12674 */ 12675 public int getDrawingCacheBackgroundColor() { 12676 return mDrawingCacheBackgroundColor; 12677 } 12678 12679 /** 12680 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 12681 * 12682 * @see #buildDrawingCache(boolean) 12683 */ 12684 public void buildDrawingCache() { 12685 buildDrawingCache(false); 12686 } 12687 12688 /** 12689 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 12690 * 12691 * <p>If you call {@link #buildDrawingCache()} manually without calling 12692 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 12693 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 12694 * 12695 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 12696 * this method will create a bitmap of the same size as this view. Because this bitmap 12697 * will be drawn scaled by the parent ViewGroup, the result on screen might show 12698 * scaling artifacts. To avoid such artifacts, you should call this method by setting 12699 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 12700 * size than the view. This implies that your application must be able to handle this 12701 * size.</p> 12702 * 12703 * <p>You should avoid calling this method when hardware acceleration is enabled. If 12704 * you do not need the drawing cache bitmap, calling this method will increase memory 12705 * usage and cause the view to be rendered in software once, thus negatively impacting 12706 * performance.</p> 12707 * 12708 * @see #getDrawingCache() 12709 * @see #destroyDrawingCache() 12710 */ 12711 public void buildDrawingCache(boolean autoScale) { 12712 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 12713 mDrawingCache == null : mUnscaledDrawingCache == null)) { 12714 mCachingFailed = false; 12715 12716 int width = mRight - mLeft; 12717 int height = mBottom - mTop; 12718 12719 final AttachInfo attachInfo = mAttachInfo; 12720 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 12721 12722 if (autoScale && scalingRequired) { 12723 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 12724 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 12725 } 12726 12727 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 12728 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 12729 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 12730 12731 final int projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 12732 final int drawingCacheSize = 12733 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 12734 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 12735 if (width > 0 && height > 0) { 12736 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 12737 + projectedBitmapSize + " bytes, only " 12738 + drawingCacheSize + " available"); 12739 } 12740 destroyDrawingCache(); 12741 mCachingFailed = true; 12742 return; 12743 } 12744 12745 boolean clear = true; 12746 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 12747 12748 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 12749 Bitmap.Config quality; 12750 if (!opaque) { 12751 // Never pick ARGB_4444 because it looks awful 12752 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 12753 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 12754 case DRAWING_CACHE_QUALITY_AUTO: 12755 quality = Bitmap.Config.ARGB_8888; 12756 break; 12757 case DRAWING_CACHE_QUALITY_LOW: 12758 quality = Bitmap.Config.ARGB_8888; 12759 break; 12760 case DRAWING_CACHE_QUALITY_HIGH: 12761 quality = Bitmap.Config.ARGB_8888; 12762 break; 12763 default: 12764 quality = Bitmap.Config.ARGB_8888; 12765 break; 12766 } 12767 } else { 12768 // Optimization for translucent windows 12769 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 12770 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 12771 } 12772 12773 // Try to cleanup memory 12774 if (bitmap != null) bitmap.recycle(); 12775 12776 try { 12777 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 12778 width, height, quality); 12779 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 12780 if (autoScale) { 12781 mDrawingCache = bitmap; 12782 } else { 12783 mUnscaledDrawingCache = bitmap; 12784 } 12785 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 12786 } catch (OutOfMemoryError e) { 12787 // If there is not enough memory to create the bitmap cache, just 12788 // ignore the issue as bitmap caches are not required to draw the 12789 // view hierarchy 12790 if (autoScale) { 12791 mDrawingCache = null; 12792 } else { 12793 mUnscaledDrawingCache = null; 12794 } 12795 mCachingFailed = true; 12796 return; 12797 } 12798 12799 clear = drawingCacheBackgroundColor != 0; 12800 } 12801 12802 Canvas canvas; 12803 if (attachInfo != null) { 12804 canvas = attachInfo.mCanvas; 12805 if (canvas == null) { 12806 canvas = new Canvas(); 12807 } 12808 canvas.setBitmap(bitmap); 12809 // Temporarily clobber the cached Canvas in case one of our children 12810 // is also using a drawing cache. Without this, the children would 12811 // steal the canvas by attaching their own bitmap to it and bad, bad 12812 // thing would happen (invisible views, corrupted drawings, etc.) 12813 attachInfo.mCanvas = null; 12814 } else { 12815 // This case should hopefully never or seldom happen 12816 canvas = new Canvas(bitmap); 12817 } 12818 12819 if (clear) { 12820 bitmap.eraseColor(drawingCacheBackgroundColor); 12821 } 12822 12823 computeScroll(); 12824 final int restoreCount = canvas.save(); 12825 12826 if (autoScale && scalingRequired) { 12827 final float scale = attachInfo.mApplicationScale; 12828 canvas.scale(scale, scale); 12829 } 12830 12831 canvas.translate(-mScrollX, -mScrollY); 12832 12833 mPrivateFlags |= PFLAG_DRAWN; 12834 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 12835 mLayerType != LAYER_TYPE_NONE) { 12836 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 12837 } 12838 12839 // Fast path for layouts with no backgrounds 12840 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12841 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12842 dispatchDraw(canvas); 12843 } else { 12844 draw(canvas); 12845 } 12846 12847 canvas.restoreToCount(restoreCount); 12848 canvas.setBitmap(null); 12849 12850 if (attachInfo != null) { 12851 // Restore the cached Canvas for our siblings 12852 attachInfo.mCanvas = canvas; 12853 } 12854 } 12855 } 12856 12857 /** 12858 * Create a snapshot of the view into a bitmap. We should probably make 12859 * some form of this public, but should think about the API. 12860 */ 12861 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 12862 int width = mRight - mLeft; 12863 int height = mBottom - mTop; 12864 12865 final AttachInfo attachInfo = mAttachInfo; 12866 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 12867 width = (int) ((width * scale) + 0.5f); 12868 height = (int) ((height * scale) + 0.5f); 12869 12870 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 12871 width > 0 ? width : 1, height > 0 ? height : 1, quality); 12872 if (bitmap == null) { 12873 throw new OutOfMemoryError(); 12874 } 12875 12876 Resources resources = getResources(); 12877 if (resources != null) { 12878 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 12879 } 12880 12881 Canvas canvas; 12882 if (attachInfo != null) { 12883 canvas = attachInfo.mCanvas; 12884 if (canvas == null) { 12885 canvas = new Canvas(); 12886 } 12887 canvas.setBitmap(bitmap); 12888 // Temporarily clobber the cached Canvas in case one of our children 12889 // is also using a drawing cache. Without this, the children would 12890 // steal the canvas by attaching their own bitmap to it and bad, bad 12891 // things would happen (invisible views, corrupted drawings, etc.) 12892 attachInfo.mCanvas = null; 12893 } else { 12894 // This case should hopefully never or seldom happen 12895 canvas = new Canvas(bitmap); 12896 } 12897 12898 if ((backgroundColor & 0xff000000) != 0) { 12899 bitmap.eraseColor(backgroundColor); 12900 } 12901 12902 computeScroll(); 12903 final int restoreCount = canvas.save(); 12904 canvas.scale(scale, scale); 12905 canvas.translate(-mScrollX, -mScrollY); 12906 12907 // Temporarily remove the dirty mask 12908 int flags = mPrivateFlags; 12909 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12910 12911 // Fast path for layouts with no backgrounds 12912 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12913 dispatchDraw(canvas); 12914 } else { 12915 draw(canvas); 12916 } 12917 12918 mPrivateFlags = flags; 12919 12920 canvas.restoreToCount(restoreCount); 12921 canvas.setBitmap(null); 12922 12923 if (attachInfo != null) { 12924 // Restore the cached Canvas for our siblings 12925 attachInfo.mCanvas = canvas; 12926 } 12927 12928 return bitmap; 12929 } 12930 12931 /** 12932 * Indicates whether this View is currently in edit mode. A View is usually 12933 * in edit mode when displayed within a developer tool. For instance, if 12934 * this View is being drawn by a visual user interface builder, this method 12935 * should return true. 12936 * 12937 * Subclasses should check the return value of this method to provide 12938 * different behaviors if their normal behavior might interfere with the 12939 * host environment. For instance: the class spawns a thread in its 12940 * constructor, the drawing code relies on device-specific features, etc. 12941 * 12942 * This method is usually checked in the drawing code of custom widgets. 12943 * 12944 * @return True if this View is in edit mode, false otherwise. 12945 */ 12946 public boolean isInEditMode() { 12947 return false; 12948 } 12949 12950 /** 12951 * If the View draws content inside its padding and enables fading edges, 12952 * it needs to support padding offsets. Padding offsets are added to the 12953 * fading edges to extend the length of the fade so that it covers pixels 12954 * drawn inside the padding. 12955 * 12956 * Subclasses of this class should override this method if they need 12957 * to draw content inside the padding. 12958 * 12959 * @return True if padding offset must be applied, false otherwise. 12960 * 12961 * @see #getLeftPaddingOffset() 12962 * @see #getRightPaddingOffset() 12963 * @see #getTopPaddingOffset() 12964 * @see #getBottomPaddingOffset() 12965 * 12966 * @since CURRENT 12967 */ 12968 protected boolean isPaddingOffsetRequired() { 12969 return false; 12970 } 12971 12972 /** 12973 * Amount by which to extend the left fading region. Called only when 12974 * {@link #isPaddingOffsetRequired()} returns true. 12975 * 12976 * @return The left padding offset in pixels. 12977 * 12978 * @see #isPaddingOffsetRequired() 12979 * 12980 * @since CURRENT 12981 */ 12982 protected int getLeftPaddingOffset() { 12983 return 0; 12984 } 12985 12986 /** 12987 * Amount by which to extend the right fading region. Called only when 12988 * {@link #isPaddingOffsetRequired()} returns true. 12989 * 12990 * @return The right padding offset in pixels. 12991 * 12992 * @see #isPaddingOffsetRequired() 12993 * 12994 * @since CURRENT 12995 */ 12996 protected int getRightPaddingOffset() { 12997 return 0; 12998 } 12999 13000 /** 13001 * Amount by which to extend the top fading region. Called only when 13002 * {@link #isPaddingOffsetRequired()} returns true. 13003 * 13004 * @return The top padding offset in pixels. 13005 * 13006 * @see #isPaddingOffsetRequired() 13007 * 13008 * @since CURRENT 13009 */ 13010 protected int getTopPaddingOffset() { 13011 return 0; 13012 } 13013 13014 /** 13015 * Amount by which to extend the bottom fading region. Called only when 13016 * {@link #isPaddingOffsetRequired()} returns true. 13017 * 13018 * @return The bottom padding offset in pixels. 13019 * 13020 * @see #isPaddingOffsetRequired() 13021 * 13022 * @since CURRENT 13023 */ 13024 protected int getBottomPaddingOffset() { 13025 return 0; 13026 } 13027 13028 /** 13029 * @hide 13030 * @param offsetRequired 13031 */ 13032 protected int getFadeTop(boolean offsetRequired) { 13033 int top = mPaddingTop; 13034 if (offsetRequired) top += getTopPaddingOffset(); 13035 return top; 13036 } 13037 13038 /** 13039 * @hide 13040 * @param offsetRequired 13041 */ 13042 protected int getFadeHeight(boolean offsetRequired) { 13043 int padding = mPaddingTop; 13044 if (offsetRequired) padding += getTopPaddingOffset(); 13045 return mBottom - mTop - mPaddingBottom - padding; 13046 } 13047 13048 /** 13049 * <p>Indicates whether this view is attached to a hardware accelerated 13050 * window or not.</p> 13051 * 13052 * <p>Even if this method returns true, it does not mean that every call 13053 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 13054 * accelerated {@link android.graphics.Canvas}. For instance, if this view 13055 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 13056 * window is hardware accelerated, 13057 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 13058 * return false, and this method will return true.</p> 13059 * 13060 * @return True if the view is attached to a window and the window is 13061 * hardware accelerated; false in any other case. 13062 */ 13063 public boolean isHardwareAccelerated() { 13064 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13065 } 13066 13067 /** 13068 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 13069 * case of an active Animation being run on the view. 13070 */ 13071 private boolean drawAnimation(ViewGroup parent, long drawingTime, 13072 Animation a, boolean scalingRequired) { 13073 Transformation invalidationTransform; 13074 final int flags = parent.mGroupFlags; 13075 final boolean initialized = a.isInitialized(); 13076 if (!initialized) { 13077 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 13078 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 13079 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 13080 onAnimationStart(); 13081 } 13082 13083 boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f); 13084 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 13085 if (parent.mInvalidationTransformation == null) { 13086 parent.mInvalidationTransformation = new Transformation(); 13087 } 13088 invalidationTransform = parent.mInvalidationTransformation; 13089 a.getTransformation(drawingTime, invalidationTransform, 1f); 13090 } else { 13091 invalidationTransform = parent.mChildTransformation; 13092 } 13093 13094 if (more) { 13095 if (!a.willChangeBounds()) { 13096 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 13097 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 13098 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 13099 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 13100 // The child need to draw an animation, potentially offscreen, so 13101 // make sure we do not cancel invalidate requests 13102 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13103 parent.invalidate(mLeft, mTop, mRight, mBottom); 13104 } 13105 } else { 13106 if (parent.mInvalidateRegion == null) { 13107 parent.mInvalidateRegion = new RectF(); 13108 } 13109 final RectF region = parent.mInvalidateRegion; 13110 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 13111 invalidationTransform); 13112 13113 // The child need to draw an animation, potentially offscreen, so 13114 // make sure we do not cancel invalidate requests 13115 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13116 13117 final int left = mLeft + (int) region.left; 13118 final int top = mTop + (int) region.top; 13119 parent.invalidate(left, top, left + (int) (region.width() + .5f), 13120 top + (int) (region.height() + .5f)); 13121 } 13122 } 13123 return more; 13124 } 13125 13126 /** 13127 * This method is called by getDisplayList() when a display list is created or re-rendered. 13128 * It sets or resets the current value of all properties on that display list (resetting is 13129 * necessary when a display list is being re-created, because we need to make sure that 13130 * previously-set transform values 13131 */ 13132 void setDisplayListProperties(DisplayList displayList) { 13133 if (displayList != null) { 13134 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 13135 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 13136 if (mParent instanceof ViewGroup) { 13137 displayList.setClipChildren( 13138 (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 13139 } 13140 float alpha = 1; 13141 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 13142 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13143 ViewGroup parentVG = (ViewGroup) mParent; 13144 final boolean hasTransform = 13145 parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation); 13146 if (hasTransform) { 13147 Transformation transform = parentVG.mChildTransformation; 13148 final int transformType = parentVG.mChildTransformation.getTransformationType(); 13149 if (transformType != Transformation.TYPE_IDENTITY) { 13150 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 13151 alpha = transform.getAlpha(); 13152 } 13153 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 13154 displayList.setStaticMatrix(transform.getMatrix()); 13155 } 13156 } 13157 } 13158 } 13159 if (mTransformationInfo != null) { 13160 alpha *= mTransformationInfo.mAlpha; 13161 if (alpha < 1) { 13162 final int multipliedAlpha = (int) (255 * alpha); 13163 if (onSetAlpha(multipliedAlpha)) { 13164 alpha = 1; 13165 } 13166 } 13167 displayList.setTransformationInfo(alpha, 13168 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 13169 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 13170 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 13171 mTransformationInfo.mScaleY); 13172 if (mTransformationInfo.mCamera == null) { 13173 mTransformationInfo.mCamera = new Camera(); 13174 mTransformationInfo.matrix3D = new Matrix(); 13175 } 13176 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 13177 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) { 13178 displayList.setPivotX(getPivotX()); 13179 displayList.setPivotY(getPivotY()); 13180 } 13181 } else if (alpha < 1) { 13182 displayList.setAlpha(alpha); 13183 } 13184 } 13185 } 13186 13187 /** 13188 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 13189 * This draw() method is an implementation detail and is not intended to be overridden or 13190 * to be called from anywhere else other than ViewGroup.drawChild(). 13191 */ 13192 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 13193 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13194 boolean more = false; 13195 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 13196 final int flags = parent.mGroupFlags; 13197 13198 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 13199 parent.mChildTransformation.clear(); 13200 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13201 } 13202 13203 Transformation transformToApply = null; 13204 boolean concatMatrix = false; 13205 13206 boolean scalingRequired = false; 13207 boolean caching; 13208 int layerType = getLayerType(); 13209 13210 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 13211 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 13212 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 13213 caching = true; 13214 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 13215 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 13216 } else { 13217 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 13218 } 13219 13220 final Animation a = getAnimation(); 13221 if (a != null) { 13222 more = drawAnimation(parent, drawingTime, a, scalingRequired); 13223 concatMatrix = a.willChangeTransformationMatrix(); 13224 if (concatMatrix) { 13225 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13226 } 13227 transformToApply = parent.mChildTransformation; 13228 } else { 13229 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && 13230 mDisplayList != null) { 13231 // No longer animating: clear out old animation matrix 13232 mDisplayList.setAnimationMatrix(null); 13233 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13234 } 13235 if (!useDisplayListProperties && 13236 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13237 final boolean hasTransform = 13238 parent.getChildStaticTransformation(this, parent.mChildTransformation); 13239 if (hasTransform) { 13240 final int transformType = parent.mChildTransformation.getTransformationType(); 13241 transformToApply = transformType != Transformation.TYPE_IDENTITY ? 13242 parent.mChildTransformation : null; 13243 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 13244 } 13245 } 13246 } 13247 13248 concatMatrix |= !childHasIdentityMatrix; 13249 13250 // Sets the flag as early as possible to allow draw() implementations 13251 // to call invalidate() successfully when doing animations 13252 mPrivateFlags |= PFLAG_DRAWN; 13253 13254 if (!concatMatrix && 13255 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 13256 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 13257 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 13258 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 13259 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 13260 return more; 13261 } 13262 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 13263 13264 if (hardwareAccelerated) { 13265 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 13266 // retain the flag's value temporarily in the mRecreateDisplayList flag 13267 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 13268 mPrivateFlags &= ~PFLAG_INVALIDATED; 13269 } 13270 13271 DisplayList displayList = null; 13272 Bitmap cache = null; 13273 boolean hasDisplayList = false; 13274 if (caching) { 13275 if (!hardwareAccelerated) { 13276 if (layerType != LAYER_TYPE_NONE) { 13277 layerType = LAYER_TYPE_SOFTWARE; 13278 buildDrawingCache(true); 13279 } 13280 cache = getDrawingCache(true); 13281 } else { 13282 switch (layerType) { 13283 case LAYER_TYPE_SOFTWARE: 13284 if (useDisplayListProperties) { 13285 hasDisplayList = canHaveDisplayList(); 13286 } else { 13287 buildDrawingCache(true); 13288 cache = getDrawingCache(true); 13289 } 13290 break; 13291 case LAYER_TYPE_HARDWARE: 13292 if (useDisplayListProperties) { 13293 hasDisplayList = canHaveDisplayList(); 13294 } 13295 break; 13296 case LAYER_TYPE_NONE: 13297 // Delay getting the display list until animation-driven alpha values are 13298 // set up and possibly passed on to the view 13299 hasDisplayList = canHaveDisplayList(); 13300 break; 13301 } 13302 } 13303 } 13304 useDisplayListProperties &= hasDisplayList; 13305 if (useDisplayListProperties) { 13306 displayList = getDisplayList(); 13307 if (!displayList.isValid()) { 13308 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13309 // to getDisplayList(), the display list will be marked invalid and we should not 13310 // try to use it again. 13311 displayList = null; 13312 hasDisplayList = false; 13313 useDisplayListProperties = false; 13314 } 13315 } 13316 13317 int sx = 0; 13318 int sy = 0; 13319 if (!hasDisplayList) { 13320 computeScroll(); 13321 sx = mScrollX; 13322 sy = mScrollY; 13323 } 13324 13325 final boolean hasNoCache = cache == null || hasDisplayList; 13326 final boolean offsetForScroll = cache == null && !hasDisplayList && 13327 layerType != LAYER_TYPE_HARDWARE; 13328 13329 int restoreTo = -1; 13330 if (!useDisplayListProperties || transformToApply != null) { 13331 restoreTo = canvas.save(); 13332 } 13333 if (offsetForScroll) { 13334 canvas.translate(mLeft - sx, mTop - sy); 13335 } else { 13336 if (!useDisplayListProperties) { 13337 canvas.translate(mLeft, mTop); 13338 } 13339 if (scalingRequired) { 13340 if (useDisplayListProperties) { 13341 // TODO: Might not need this if we put everything inside the DL 13342 restoreTo = canvas.save(); 13343 } 13344 // mAttachInfo cannot be null, otherwise scalingRequired == false 13345 final float scale = 1.0f / mAttachInfo.mApplicationScale; 13346 canvas.scale(scale, scale); 13347 } 13348 } 13349 13350 float alpha = useDisplayListProperties ? 1 : getAlpha(); 13351 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 13352 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13353 if (transformToApply != null || !childHasIdentityMatrix) { 13354 int transX = 0; 13355 int transY = 0; 13356 13357 if (offsetForScroll) { 13358 transX = -sx; 13359 transY = -sy; 13360 } 13361 13362 if (transformToApply != null) { 13363 if (concatMatrix) { 13364 if (useDisplayListProperties) { 13365 displayList.setAnimationMatrix(transformToApply.getMatrix()); 13366 } else { 13367 // Undo the scroll translation, apply the transformation matrix, 13368 // then redo the scroll translate to get the correct result. 13369 canvas.translate(-transX, -transY); 13370 canvas.concat(transformToApply.getMatrix()); 13371 canvas.translate(transX, transY); 13372 } 13373 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13374 } 13375 13376 float transformAlpha = transformToApply.getAlpha(); 13377 if (transformAlpha < 1) { 13378 alpha *= transformAlpha; 13379 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13380 } 13381 } 13382 13383 if (!childHasIdentityMatrix && !useDisplayListProperties) { 13384 canvas.translate(-transX, -transY); 13385 canvas.concat(getMatrix()); 13386 canvas.translate(transX, transY); 13387 } 13388 } 13389 13390 // Deal with alpha if it is or used to be <1 13391 if (alpha < 1 || 13392 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13393 if (alpha < 1) { 13394 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13395 } else { 13396 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13397 } 13398 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13399 if (hasNoCache) { 13400 final int multipliedAlpha = (int) (255 * alpha); 13401 if (!onSetAlpha(multipliedAlpha)) { 13402 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13403 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 13404 layerType != LAYER_TYPE_NONE) { 13405 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 13406 } 13407 if (useDisplayListProperties) { 13408 displayList.setAlpha(alpha * getAlpha()); 13409 } else if (layerType == LAYER_TYPE_NONE) { 13410 final int scrollX = hasDisplayList ? 0 : sx; 13411 final int scrollY = hasDisplayList ? 0 : sy; 13412 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 13413 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 13414 } 13415 } else { 13416 // Alpha is handled by the child directly, clobber the layer's alpha 13417 mPrivateFlags |= PFLAG_ALPHA_SET; 13418 } 13419 } 13420 } 13421 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 13422 onSetAlpha(255); 13423 mPrivateFlags &= ~PFLAG_ALPHA_SET; 13424 } 13425 13426 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 13427 !useDisplayListProperties) { 13428 if (offsetForScroll) { 13429 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 13430 } else { 13431 if (!scalingRequired || cache == null) { 13432 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 13433 } else { 13434 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 13435 } 13436 } 13437 } 13438 13439 if (!useDisplayListProperties && hasDisplayList) { 13440 displayList = getDisplayList(); 13441 if (!displayList.isValid()) { 13442 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13443 // to getDisplayList(), the display list will be marked invalid and we should not 13444 // try to use it again. 13445 displayList = null; 13446 hasDisplayList = false; 13447 } 13448 } 13449 13450 if (hasNoCache) { 13451 boolean layerRendered = false; 13452 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 13453 final HardwareLayer layer = getHardwareLayer(); 13454 if (layer != null && layer.isValid()) { 13455 mLayerPaint.setAlpha((int) (alpha * 255)); 13456 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 13457 layerRendered = true; 13458 } else { 13459 final int scrollX = hasDisplayList ? 0 : sx; 13460 final int scrollY = hasDisplayList ? 0 : sy; 13461 canvas.saveLayer(scrollX, scrollY, 13462 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 13463 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13464 } 13465 } 13466 13467 if (!layerRendered) { 13468 if (!hasDisplayList) { 13469 // Fast path for layouts with no backgrounds 13470 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13471 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13472 dispatchDraw(canvas); 13473 } else { 13474 draw(canvas); 13475 } 13476 } else { 13477 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13478 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 13479 } 13480 } 13481 } else if (cache != null) { 13482 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13483 Paint cachePaint; 13484 13485 if (layerType == LAYER_TYPE_NONE) { 13486 cachePaint = parent.mCachePaint; 13487 if (cachePaint == null) { 13488 cachePaint = new Paint(); 13489 cachePaint.setDither(false); 13490 parent.mCachePaint = cachePaint; 13491 } 13492 if (alpha < 1) { 13493 cachePaint.setAlpha((int) (alpha * 255)); 13494 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13495 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 13496 cachePaint.setAlpha(255); 13497 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13498 } 13499 } else { 13500 cachePaint = mLayerPaint; 13501 cachePaint.setAlpha((int) (alpha * 255)); 13502 } 13503 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 13504 } 13505 13506 if (restoreTo >= 0) { 13507 canvas.restoreToCount(restoreTo); 13508 } 13509 13510 if (a != null && !more) { 13511 if (!hardwareAccelerated && !a.getFillAfter()) { 13512 onSetAlpha(255); 13513 } 13514 parent.finishAnimatingView(this, a); 13515 } 13516 13517 if (more && hardwareAccelerated) { 13518 // invalidation is the trigger to recreate display lists, so if we're using 13519 // display lists to render, force an invalidate to allow the animation to 13520 // continue drawing another frame 13521 parent.invalidate(true); 13522 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 13523 // alpha animations should cause the child to recreate its display list 13524 invalidate(true); 13525 } 13526 } 13527 13528 mRecreateDisplayList = false; 13529 13530 return more; 13531 } 13532 13533 /** 13534 * Manually render this view (and all of its children) to the given Canvas. 13535 * The view must have already done a full layout before this function is 13536 * called. When implementing a view, implement 13537 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 13538 * If you do need to override this method, call the superclass version. 13539 * 13540 * @param canvas The Canvas to which the View is rendered. 13541 */ 13542 public void draw(Canvas canvas) { 13543 final int privateFlags = mPrivateFlags; 13544 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 13545 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 13546 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 13547 13548 /* 13549 * Draw traversal performs several drawing steps which must be executed 13550 * in the appropriate order: 13551 * 13552 * 1. Draw the background 13553 * 2. If necessary, save the canvas' layers to prepare for fading 13554 * 3. Draw view's content 13555 * 4. Draw children 13556 * 5. If necessary, draw the fading edges and restore layers 13557 * 6. Draw decorations (scrollbars for instance) 13558 */ 13559 13560 // Step 1, draw the background, if needed 13561 int saveCount; 13562 13563 if (!dirtyOpaque) { 13564 final Drawable background = mBackground; 13565 if (background != null) { 13566 final int scrollX = mScrollX; 13567 final int scrollY = mScrollY; 13568 13569 if (mBackgroundSizeChanged) { 13570 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 13571 mBackgroundSizeChanged = false; 13572 } 13573 13574 if ((scrollX | scrollY) == 0) { 13575 background.draw(canvas); 13576 } else { 13577 canvas.translate(scrollX, scrollY); 13578 background.draw(canvas); 13579 canvas.translate(-scrollX, -scrollY); 13580 } 13581 } 13582 } 13583 13584 // skip step 2 & 5 if possible (common case) 13585 final int viewFlags = mViewFlags; 13586 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 13587 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 13588 if (!verticalEdges && !horizontalEdges) { 13589 // Step 3, draw the content 13590 if (!dirtyOpaque) onDraw(canvas); 13591 13592 // Step 4, draw the children 13593 dispatchDraw(canvas); 13594 13595 // Step 6, draw decorations (scrollbars) 13596 onDrawScrollBars(canvas); 13597 13598 // we're done... 13599 return; 13600 } 13601 13602 /* 13603 * Here we do the full fledged routine... 13604 * (this is an uncommon case where speed matters less, 13605 * this is why we repeat some of the tests that have been 13606 * done above) 13607 */ 13608 13609 boolean drawTop = false; 13610 boolean drawBottom = false; 13611 boolean drawLeft = false; 13612 boolean drawRight = false; 13613 13614 float topFadeStrength = 0.0f; 13615 float bottomFadeStrength = 0.0f; 13616 float leftFadeStrength = 0.0f; 13617 float rightFadeStrength = 0.0f; 13618 13619 // Step 2, save the canvas' layers 13620 int paddingLeft = mPaddingLeft; 13621 13622 final boolean offsetRequired = isPaddingOffsetRequired(); 13623 if (offsetRequired) { 13624 paddingLeft += getLeftPaddingOffset(); 13625 } 13626 13627 int left = mScrollX + paddingLeft; 13628 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 13629 int top = mScrollY + getFadeTop(offsetRequired); 13630 int bottom = top + getFadeHeight(offsetRequired); 13631 13632 if (offsetRequired) { 13633 right += getRightPaddingOffset(); 13634 bottom += getBottomPaddingOffset(); 13635 } 13636 13637 final ScrollabilityCache scrollabilityCache = mScrollCache; 13638 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 13639 int length = (int) fadeHeight; 13640 13641 // clip the fade length if top and bottom fades overlap 13642 // overlapping fades produce odd-looking artifacts 13643 if (verticalEdges && (top + length > bottom - length)) { 13644 length = (bottom - top) / 2; 13645 } 13646 13647 // also clip horizontal fades if necessary 13648 if (horizontalEdges && (left + length > right - length)) { 13649 length = (right - left) / 2; 13650 } 13651 13652 if (verticalEdges) { 13653 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 13654 drawTop = topFadeStrength * fadeHeight > 1.0f; 13655 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 13656 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 13657 } 13658 13659 if (horizontalEdges) { 13660 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 13661 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 13662 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 13663 drawRight = rightFadeStrength * fadeHeight > 1.0f; 13664 } 13665 13666 saveCount = canvas.getSaveCount(); 13667 13668 int solidColor = getSolidColor(); 13669 if (solidColor == 0) { 13670 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13671 13672 if (drawTop) { 13673 canvas.saveLayer(left, top, right, top + length, null, flags); 13674 } 13675 13676 if (drawBottom) { 13677 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 13678 } 13679 13680 if (drawLeft) { 13681 canvas.saveLayer(left, top, left + length, bottom, null, flags); 13682 } 13683 13684 if (drawRight) { 13685 canvas.saveLayer(right - length, top, right, bottom, null, flags); 13686 } 13687 } else { 13688 scrollabilityCache.setFadeColor(solidColor); 13689 } 13690 13691 // Step 3, draw the content 13692 if (!dirtyOpaque) onDraw(canvas); 13693 13694 // Step 4, draw the children 13695 dispatchDraw(canvas); 13696 13697 // Step 5, draw the fade effect and restore layers 13698 final Paint p = scrollabilityCache.paint; 13699 final Matrix matrix = scrollabilityCache.matrix; 13700 final Shader fade = scrollabilityCache.shader; 13701 13702 if (drawTop) { 13703 matrix.setScale(1, fadeHeight * topFadeStrength); 13704 matrix.postTranslate(left, top); 13705 fade.setLocalMatrix(matrix); 13706 canvas.drawRect(left, top, right, top + length, p); 13707 } 13708 13709 if (drawBottom) { 13710 matrix.setScale(1, fadeHeight * bottomFadeStrength); 13711 matrix.postRotate(180); 13712 matrix.postTranslate(left, bottom); 13713 fade.setLocalMatrix(matrix); 13714 canvas.drawRect(left, bottom - length, right, bottom, p); 13715 } 13716 13717 if (drawLeft) { 13718 matrix.setScale(1, fadeHeight * leftFadeStrength); 13719 matrix.postRotate(-90); 13720 matrix.postTranslate(left, top); 13721 fade.setLocalMatrix(matrix); 13722 canvas.drawRect(left, top, left + length, bottom, p); 13723 } 13724 13725 if (drawRight) { 13726 matrix.setScale(1, fadeHeight * rightFadeStrength); 13727 matrix.postRotate(90); 13728 matrix.postTranslate(right, top); 13729 fade.setLocalMatrix(matrix); 13730 canvas.drawRect(right - length, top, right, bottom, p); 13731 } 13732 13733 canvas.restoreToCount(saveCount); 13734 13735 // Step 6, draw decorations (scrollbars) 13736 onDrawScrollBars(canvas); 13737 } 13738 13739 /** 13740 * Override this if your view is known to always be drawn on top of a solid color background, 13741 * and needs to draw fading edges. Returning a non-zero color enables the view system to 13742 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 13743 * should be set to 0xFF. 13744 * 13745 * @see #setVerticalFadingEdgeEnabled(boolean) 13746 * @see #setHorizontalFadingEdgeEnabled(boolean) 13747 * 13748 * @return The known solid color background for this view, or 0 if the color may vary 13749 */ 13750 @ViewDebug.ExportedProperty(category = "drawing") 13751 public int getSolidColor() { 13752 return 0; 13753 } 13754 13755 /** 13756 * Build a human readable string representation of the specified view flags. 13757 * 13758 * @param flags the view flags to convert to a string 13759 * @return a String representing the supplied flags 13760 */ 13761 private static String printFlags(int flags) { 13762 String output = ""; 13763 int numFlags = 0; 13764 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 13765 output += "TAKES_FOCUS"; 13766 numFlags++; 13767 } 13768 13769 switch (flags & VISIBILITY_MASK) { 13770 case INVISIBLE: 13771 if (numFlags > 0) { 13772 output += " "; 13773 } 13774 output += "INVISIBLE"; 13775 // USELESS HERE numFlags++; 13776 break; 13777 case GONE: 13778 if (numFlags > 0) { 13779 output += " "; 13780 } 13781 output += "GONE"; 13782 // USELESS HERE numFlags++; 13783 break; 13784 default: 13785 break; 13786 } 13787 return output; 13788 } 13789 13790 /** 13791 * Build a human readable string representation of the specified private 13792 * view flags. 13793 * 13794 * @param privateFlags the private view flags to convert to a string 13795 * @return a String representing the supplied flags 13796 */ 13797 private static String printPrivateFlags(int privateFlags) { 13798 String output = ""; 13799 int numFlags = 0; 13800 13801 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 13802 output += "WANTS_FOCUS"; 13803 numFlags++; 13804 } 13805 13806 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 13807 if (numFlags > 0) { 13808 output += " "; 13809 } 13810 output += "FOCUSED"; 13811 numFlags++; 13812 } 13813 13814 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 13815 if (numFlags > 0) { 13816 output += " "; 13817 } 13818 output += "SELECTED"; 13819 numFlags++; 13820 } 13821 13822 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 13823 if (numFlags > 0) { 13824 output += " "; 13825 } 13826 output += "IS_ROOT_NAMESPACE"; 13827 numFlags++; 13828 } 13829 13830 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 13831 if (numFlags > 0) { 13832 output += " "; 13833 } 13834 output += "HAS_BOUNDS"; 13835 numFlags++; 13836 } 13837 13838 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 13839 if (numFlags > 0) { 13840 output += " "; 13841 } 13842 output += "DRAWN"; 13843 // USELESS HERE numFlags++; 13844 } 13845 return output; 13846 } 13847 13848 /** 13849 * <p>Indicates whether or not this view's layout will be requested during 13850 * the next hierarchy layout pass.</p> 13851 * 13852 * @return true if the layout will be forced during next layout pass 13853 */ 13854 public boolean isLayoutRequested() { 13855 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 13856 } 13857 13858 /** 13859 * Assign a size and position to a view and all of its 13860 * descendants 13861 * 13862 * <p>This is the second phase of the layout mechanism. 13863 * (The first is measuring). In this phase, each parent calls 13864 * layout on all of its children to position them. 13865 * This is typically done using the child measurements 13866 * that were stored in the measure pass().</p> 13867 * 13868 * <p>Derived classes should not override this method. 13869 * Derived classes with children should override 13870 * onLayout. In that method, they should 13871 * call layout on each of their children.</p> 13872 * 13873 * @param l Left position, relative to parent 13874 * @param t Top position, relative to parent 13875 * @param r Right position, relative to parent 13876 * @param b Bottom position, relative to parent 13877 */ 13878 @SuppressWarnings({"unchecked"}) 13879 public void layout(int l, int t, int r, int b) { 13880 int oldL = mLeft; 13881 int oldT = mTop; 13882 int oldB = mBottom; 13883 int oldR = mRight; 13884 boolean changed = setFrame(l, t, r, b); 13885 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 13886 onLayout(changed, l, t, r, b); 13887 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 13888 13889 ListenerInfo li = mListenerInfo; 13890 if (li != null && li.mOnLayoutChangeListeners != null) { 13891 ArrayList<OnLayoutChangeListener> listenersCopy = 13892 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 13893 int numListeners = listenersCopy.size(); 13894 for (int i = 0; i < numListeners; ++i) { 13895 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 13896 } 13897 } 13898 } 13899 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 13900 } 13901 13902 /** 13903 * Called from layout when this view should 13904 * assign a size and position to each of its children. 13905 * 13906 * Derived classes with children should override 13907 * this method and call layout on each of 13908 * their children. 13909 * @param changed This is a new size or position for this view 13910 * @param left Left position, relative to parent 13911 * @param top Top position, relative to parent 13912 * @param right Right position, relative to parent 13913 * @param bottom Bottom position, relative to parent 13914 */ 13915 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 13916 } 13917 13918 /** 13919 * Assign a size and position to this view. 13920 * 13921 * This is called from layout. 13922 * 13923 * @param left Left position, relative to parent 13924 * @param top Top position, relative to parent 13925 * @param right Right position, relative to parent 13926 * @param bottom Bottom position, relative to parent 13927 * @return true if the new size and position are different than the 13928 * previous ones 13929 * {@hide} 13930 */ 13931 protected boolean setFrame(int left, int top, int right, int bottom) { 13932 boolean changed = false; 13933 13934 if (DBG) { 13935 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 13936 + right + "," + bottom + ")"); 13937 } 13938 13939 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 13940 changed = true; 13941 13942 // Remember our drawn bit 13943 int drawn = mPrivateFlags & PFLAG_DRAWN; 13944 13945 int oldWidth = mRight - mLeft; 13946 int oldHeight = mBottom - mTop; 13947 int newWidth = right - left; 13948 int newHeight = bottom - top; 13949 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 13950 13951 // Invalidate our old position 13952 invalidate(sizeChanged); 13953 13954 mLeft = left; 13955 mTop = top; 13956 mRight = right; 13957 mBottom = bottom; 13958 if (mDisplayList != null) { 13959 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 13960 } 13961 13962 mPrivateFlags |= PFLAG_HAS_BOUNDS; 13963 13964 13965 if (sizeChanged) { 13966 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 13967 // A change in dimension means an auto-centered pivot point changes, too 13968 if (mTransformationInfo != null) { 13969 mTransformationInfo.mMatrixDirty = true; 13970 } 13971 } 13972 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 13973 } 13974 13975 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 13976 // If we are visible, force the DRAWN bit to on so that 13977 // this invalidate will go through (at least to our parent). 13978 // This is because someone may have invalidated this view 13979 // before this call to setFrame came in, thereby clearing 13980 // the DRAWN bit. 13981 mPrivateFlags |= PFLAG_DRAWN; 13982 invalidate(sizeChanged); 13983 // parent display list may need to be recreated based on a change in the bounds 13984 // of any child 13985 invalidateParentCaches(); 13986 } 13987 13988 // Reset drawn bit to original value (invalidate turns it off) 13989 mPrivateFlags |= drawn; 13990 13991 mBackgroundSizeChanged = true; 13992 } 13993 return changed; 13994 } 13995 13996 /** 13997 * Finalize inflating a view from XML. This is called as the last phase 13998 * of inflation, after all child views have been added. 13999 * 14000 * <p>Even if the subclass overrides onFinishInflate, they should always be 14001 * sure to call the super method, so that we get called. 14002 */ 14003 protected void onFinishInflate() { 14004 } 14005 14006 /** 14007 * Returns the resources associated with this view. 14008 * 14009 * @return Resources object. 14010 */ 14011 public Resources getResources() { 14012 return mResources; 14013 } 14014 14015 /** 14016 * Invalidates the specified Drawable. 14017 * 14018 * @param drawable the drawable to invalidate 14019 */ 14020 public void invalidateDrawable(Drawable drawable) { 14021 if (verifyDrawable(drawable)) { 14022 final Rect dirty = drawable.getBounds(); 14023 final int scrollX = mScrollX; 14024 final int scrollY = mScrollY; 14025 14026 invalidate(dirty.left + scrollX, dirty.top + scrollY, 14027 dirty.right + scrollX, dirty.bottom + scrollY); 14028 } 14029 } 14030 14031 /** 14032 * Schedules an action on a drawable to occur at a specified time. 14033 * 14034 * @param who the recipient of the action 14035 * @param what the action to run on the drawable 14036 * @param when the time at which the action must occur. Uses the 14037 * {@link SystemClock#uptimeMillis} timebase. 14038 */ 14039 public void scheduleDrawable(Drawable who, Runnable what, long when) { 14040 if (verifyDrawable(who) && what != null) { 14041 final long delay = when - SystemClock.uptimeMillis(); 14042 if (mAttachInfo != null) { 14043 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 14044 Choreographer.CALLBACK_ANIMATION, what, who, 14045 Choreographer.subtractFrameDelay(delay)); 14046 } else { 14047 ViewRootImpl.getRunQueue().postDelayed(what, delay); 14048 } 14049 } 14050 } 14051 14052 /** 14053 * Cancels a scheduled action on a drawable. 14054 * 14055 * @param who the recipient of the action 14056 * @param what the action to cancel 14057 */ 14058 public void unscheduleDrawable(Drawable who, Runnable what) { 14059 if (verifyDrawable(who) && what != null) { 14060 if (mAttachInfo != null) { 14061 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14062 Choreographer.CALLBACK_ANIMATION, what, who); 14063 } else { 14064 ViewRootImpl.getRunQueue().removeCallbacks(what); 14065 } 14066 } 14067 } 14068 14069 /** 14070 * Unschedule any events associated with the given Drawable. This can be 14071 * used when selecting a new Drawable into a view, so that the previous 14072 * one is completely unscheduled. 14073 * 14074 * @param who The Drawable to unschedule. 14075 * 14076 * @see #drawableStateChanged 14077 */ 14078 public void unscheduleDrawable(Drawable who) { 14079 if (mAttachInfo != null && who != null) { 14080 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14081 Choreographer.CALLBACK_ANIMATION, null, who); 14082 } 14083 } 14084 14085 /** 14086 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 14087 * that the View directionality can and will be resolved before its Drawables. 14088 * 14089 * Will call {@link View#onResolveDrawables} when resolution is done. 14090 */ 14091 public void resolveDrawables() { 14092 if (mBackground != null) { 14093 mBackground.setLayoutDirection(getResolvedLayoutDirection()); 14094 } 14095 onResolveDrawables(getResolvedLayoutDirection()); 14096 } 14097 14098 /** 14099 * Called when layout direction has been resolved. 14100 * 14101 * The default implementation does nothing. 14102 * 14103 * @param layoutDirection The resolved layout direction. 14104 * 14105 * @see #LAYOUT_DIRECTION_LTR 14106 * @see #LAYOUT_DIRECTION_RTL 14107 */ 14108 public void onResolveDrawables(int layoutDirection) { 14109 } 14110 14111 /** 14112 * If your view subclass is displaying its own Drawable objects, it should 14113 * override this function and return true for any Drawable it is 14114 * displaying. This allows animations for those drawables to be 14115 * scheduled. 14116 * 14117 * <p>Be sure to call through to the super class when overriding this 14118 * function. 14119 * 14120 * @param who The Drawable to verify. Return true if it is one you are 14121 * displaying, else return the result of calling through to the 14122 * super class. 14123 * 14124 * @return boolean If true than the Drawable is being displayed in the 14125 * view; else false and it is not allowed to animate. 14126 * 14127 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 14128 * @see #drawableStateChanged() 14129 */ 14130 protected boolean verifyDrawable(Drawable who) { 14131 return who == mBackground; 14132 } 14133 14134 /** 14135 * This function is called whenever the state of the view changes in such 14136 * a way that it impacts the state of drawables being shown. 14137 * 14138 * <p>Be sure to call through to the superclass when overriding this 14139 * function. 14140 * 14141 * @see Drawable#setState(int[]) 14142 */ 14143 protected void drawableStateChanged() { 14144 Drawable d = mBackground; 14145 if (d != null && d.isStateful()) { 14146 d.setState(getDrawableState()); 14147 } 14148 } 14149 14150 /** 14151 * Call this to force a view to update its drawable state. This will cause 14152 * drawableStateChanged to be called on this view. Views that are interested 14153 * in the new state should call getDrawableState. 14154 * 14155 * @see #drawableStateChanged 14156 * @see #getDrawableState 14157 */ 14158 public void refreshDrawableState() { 14159 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 14160 drawableStateChanged(); 14161 14162 ViewParent parent = mParent; 14163 if (parent != null) { 14164 parent.childDrawableStateChanged(this); 14165 } 14166 } 14167 14168 /** 14169 * Return an array of resource IDs of the drawable states representing the 14170 * current state of the view. 14171 * 14172 * @return The current drawable state 14173 * 14174 * @see Drawable#setState(int[]) 14175 * @see #drawableStateChanged() 14176 * @see #onCreateDrawableState(int) 14177 */ 14178 public final int[] getDrawableState() { 14179 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 14180 return mDrawableState; 14181 } else { 14182 mDrawableState = onCreateDrawableState(0); 14183 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 14184 return mDrawableState; 14185 } 14186 } 14187 14188 /** 14189 * Generate the new {@link android.graphics.drawable.Drawable} state for 14190 * this view. This is called by the view 14191 * system when the cached Drawable state is determined to be invalid. To 14192 * retrieve the current state, you should use {@link #getDrawableState}. 14193 * 14194 * @param extraSpace if non-zero, this is the number of extra entries you 14195 * would like in the returned array in which you can place your own 14196 * states. 14197 * 14198 * @return Returns an array holding the current {@link Drawable} state of 14199 * the view. 14200 * 14201 * @see #mergeDrawableStates(int[], int[]) 14202 */ 14203 protected int[] onCreateDrawableState(int extraSpace) { 14204 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 14205 mParent instanceof View) { 14206 return ((View) mParent).onCreateDrawableState(extraSpace); 14207 } 14208 14209 int[] drawableState; 14210 14211 int privateFlags = mPrivateFlags; 14212 14213 int viewStateIndex = 0; 14214 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 14215 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 14216 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 14217 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 14218 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 14219 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 14220 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 14221 HardwareRenderer.isAvailable()) { 14222 // This is set if HW acceleration is requested, even if the current 14223 // process doesn't allow it. This is just to allow app preview 14224 // windows to better match their app. 14225 viewStateIndex |= VIEW_STATE_ACCELERATED; 14226 } 14227 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 14228 14229 final int privateFlags2 = mPrivateFlags2; 14230 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 14231 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 14232 14233 drawableState = VIEW_STATE_SETS[viewStateIndex]; 14234 14235 //noinspection ConstantIfStatement 14236 if (false) { 14237 Log.i("View", "drawableStateIndex=" + viewStateIndex); 14238 Log.i("View", toString() 14239 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 14240 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 14241 + " fo=" + hasFocus() 14242 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 14243 + " wf=" + hasWindowFocus() 14244 + ": " + Arrays.toString(drawableState)); 14245 } 14246 14247 if (extraSpace == 0) { 14248 return drawableState; 14249 } 14250 14251 final int[] fullState; 14252 if (drawableState != null) { 14253 fullState = new int[drawableState.length + extraSpace]; 14254 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 14255 } else { 14256 fullState = new int[extraSpace]; 14257 } 14258 14259 return fullState; 14260 } 14261 14262 /** 14263 * Merge your own state values in <var>additionalState</var> into the base 14264 * state values <var>baseState</var> that were returned by 14265 * {@link #onCreateDrawableState(int)}. 14266 * 14267 * @param baseState The base state values returned by 14268 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 14269 * own additional state values. 14270 * 14271 * @param additionalState The additional state values you would like 14272 * added to <var>baseState</var>; this array is not modified. 14273 * 14274 * @return As a convenience, the <var>baseState</var> array you originally 14275 * passed into the function is returned. 14276 * 14277 * @see #onCreateDrawableState(int) 14278 */ 14279 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 14280 final int N = baseState.length; 14281 int i = N - 1; 14282 while (i >= 0 && baseState[i] == 0) { 14283 i--; 14284 } 14285 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 14286 return baseState; 14287 } 14288 14289 /** 14290 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 14291 * on all Drawable objects associated with this view. 14292 */ 14293 public void jumpDrawablesToCurrentState() { 14294 if (mBackground != null) { 14295 mBackground.jumpToCurrentState(); 14296 } 14297 } 14298 14299 /** 14300 * Sets the background color for this view. 14301 * @param color the color of the background 14302 */ 14303 @RemotableViewMethod 14304 public void setBackgroundColor(int color) { 14305 if (mBackground instanceof ColorDrawable) { 14306 ((ColorDrawable) mBackground.mutate()).setColor(color); 14307 computeOpaqueFlags(); 14308 } else { 14309 setBackground(new ColorDrawable(color)); 14310 } 14311 } 14312 14313 /** 14314 * Set the background to a given resource. The resource should refer to 14315 * a Drawable object or 0 to remove the background. 14316 * @param resid The identifier of the resource. 14317 * 14318 * @attr ref android.R.styleable#View_background 14319 */ 14320 @RemotableViewMethod 14321 public void setBackgroundResource(int resid) { 14322 if (resid != 0 && resid == mBackgroundResource) { 14323 return; 14324 } 14325 14326 Drawable d= null; 14327 if (resid != 0) { 14328 d = mResources.getDrawable(resid); 14329 } 14330 setBackground(d); 14331 14332 mBackgroundResource = resid; 14333 } 14334 14335 /** 14336 * Set the background to a given Drawable, or remove the background. If the 14337 * background has padding, this View's padding is set to the background's 14338 * padding. However, when a background is removed, this View's padding isn't 14339 * touched. If setting the padding is desired, please use 14340 * {@link #setPadding(int, int, int, int)}. 14341 * 14342 * @param background The Drawable to use as the background, or null to remove the 14343 * background 14344 */ 14345 public void setBackground(Drawable background) { 14346 //noinspection deprecation 14347 setBackgroundDrawable(background); 14348 } 14349 14350 /** 14351 * @deprecated use {@link #setBackground(Drawable)} instead 14352 */ 14353 @Deprecated 14354 public void setBackgroundDrawable(Drawable background) { 14355 computeOpaqueFlags(); 14356 14357 if (background == mBackground) { 14358 return; 14359 } 14360 14361 boolean requestLayout = false; 14362 14363 mBackgroundResource = 0; 14364 14365 /* 14366 * Regardless of whether we're setting a new background or not, we want 14367 * to clear the previous drawable. 14368 */ 14369 if (mBackground != null) { 14370 mBackground.setCallback(null); 14371 unscheduleDrawable(mBackground); 14372 } 14373 14374 if (background != null) { 14375 Rect padding = sThreadLocal.get(); 14376 if (padding == null) { 14377 padding = new Rect(); 14378 sThreadLocal.set(padding); 14379 } 14380 background.setLayoutDirection(getResolvedLayoutDirection()); 14381 if (background.getPadding(padding)) { 14382 // Reset padding resolution 14383 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 14384 switch (background.getLayoutDirection()) { 14385 case LAYOUT_DIRECTION_RTL: 14386 mUserPaddingLeftInitial = padding.right; 14387 mUserPaddingRightInitial = padding.left; 14388 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 14389 break; 14390 case LAYOUT_DIRECTION_LTR: 14391 default: 14392 mUserPaddingLeftInitial = padding.left; 14393 mUserPaddingRightInitial = padding.right; 14394 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 14395 } 14396 } 14397 14398 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 14399 // if it has a different minimum size, we should layout again 14400 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 14401 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 14402 requestLayout = true; 14403 } 14404 14405 background.setCallback(this); 14406 if (background.isStateful()) { 14407 background.setState(getDrawableState()); 14408 } 14409 background.setVisible(getVisibility() == VISIBLE, false); 14410 mBackground = background; 14411 14412 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 14413 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 14414 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 14415 requestLayout = true; 14416 } 14417 } else { 14418 /* Remove the background */ 14419 mBackground = null; 14420 14421 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 14422 /* 14423 * This view ONLY drew the background before and we're removing 14424 * the background, so now it won't draw anything 14425 * (hence we SKIP_DRAW) 14426 */ 14427 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 14428 mPrivateFlags |= PFLAG_SKIP_DRAW; 14429 } 14430 14431 /* 14432 * When the background is set, we try to apply its padding to this 14433 * View. When the background is removed, we don't touch this View's 14434 * padding. This is noted in the Javadocs. Hence, we don't need to 14435 * requestLayout(), the invalidate() below is sufficient. 14436 */ 14437 14438 // The old background's minimum size could have affected this 14439 // View's layout, so let's requestLayout 14440 requestLayout = true; 14441 } 14442 14443 computeOpaqueFlags(); 14444 14445 if (requestLayout) { 14446 requestLayout(); 14447 } 14448 14449 mBackgroundSizeChanged = true; 14450 invalidate(true); 14451 } 14452 14453 /** 14454 * Gets the background drawable 14455 * 14456 * @return The drawable used as the background for this view, if any. 14457 * 14458 * @see #setBackground(Drawable) 14459 * 14460 * @attr ref android.R.styleable#View_background 14461 */ 14462 public Drawable getBackground() { 14463 return mBackground; 14464 } 14465 14466 /** 14467 * Sets the padding. The view may add on the space required to display 14468 * the scrollbars, depending on the style and visibility of the scrollbars. 14469 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 14470 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 14471 * from the values set in this call. 14472 * 14473 * @attr ref android.R.styleable#View_padding 14474 * @attr ref android.R.styleable#View_paddingBottom 14475 * @attr ref android.R.styleable#View_paddingLeft 14476 * @attr ref android.R.styleable#View_paddingRight 14477 * @attr ref android.R.styleable#View_paddingTop 14478 * @param left the left padding in pixels 14479 * @param top the top padding in pixels 14480 * @param right the right padding in pixels 14481 * @param bottom the bottom padding in pixels 14482 */ 14483 public void setPadding(int left, int top, int right, int bottom) { 14484 // Reset padding resolution 14485 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 14486 14487 mUserPaddingStart = UNDEFINED_PADDING; 14488 mUserPaddingEnd = UNDEFINED_PADDING; 14489 14490 mUserPaddingLeftInitial = left; 14491 mUserPaddingRightInitial = right; 14492 14493 internalSetPadding(left, top, right, bottom); 14494 } 14495 14496 /** 14497 * @hide 14498 */ 14499 protected void internalSetPadding(int left, int top, int right, int bottom) { 14500 mUserPaddingLeft = left; 14501 mUserPaddingRight = right; 14502 mUserPaddingBottom = bottom; 14503 14504 final int viewFlags = mViewFlags; 14505 boolean changed = false; 14506 14507 // Common case is there are no scroll bars. 14508 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 14509 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 14510 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 14511 ? 0 : getVerticalScrollbarWidth(); 14512 switch (mVerticalScrollbarPosition) { 14513 case SCROLLBAR_POSITION_DEFAULT: 14514 if (isLayoutRtl()) { 14515 left += offset; 14516 } else { 14517 right += offset; 14518 } 14519 break; 14520 case SCROLLBAR_POSITION_RIGHT: 14521 right += offset; 14522 break; 14523 case SCROLLBAR_POSITION_LEFT: 14524 left += offset; 14525 break; 14526 } 14527 } 14528 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 14529 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 14530 ? 0 : getHorizontalScrollbarHeight(); 14531 } 14532 } 14533 14534 if (mPaddingLeft != left) { 14535 changed = true; 14536 mPaddingLeft = left; 14537 } 14538 if (mPaddingTop != top) { 14539 changed = true; 14540 mPaddingTop = top; 14541 } 14542 if (mPaddingRight != right) { 14543 changed = true; 14544 mPaddingRight = right; 14545 } 14546 if (mPaddingBottom != bottom) { 14547 changed = true; 14548 mPaddingBottom = bottom; 14549 } 14550 14551 if (changed) { 14552 requestLayout(); 14553 } 14554 } 14555 14556 /** 14557 * Sets the relative padding. The view may add on the space required to display 14558 * the scrollbars, depending on the style and visibility of the scrollbars. 14559 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 14560 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 14561 * from the values set in this call. 14562 * 14563 * @attr ref android.R.styleable#View_padding 14564 * @attr ref android.R.styleable#View_paddingBottom 14565 * @attr ref android.R.styleable#View_paddingStart 14566 * @attr ref android.R.styleable#View_paddingEnd 14567 * @attr ref android.R.styleable#View_paddingTop 14568 * @param start the start padding in pixels 14569 * @param top the top padding in pixels 14570 * @param end the end padding in pixels 14571 * @param bottom the bottom padding in pixels 14572 */ 14573 public void setPaddingRelative(int start, int top, int end, int bottom) { 14574 // Reset padding resolution 14575 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 14576 14577 mUserPaddingStart = start; 14578 mUserPaddingEnd = end; 14579 14580 switch(getResolvedLayoutDirection()) { 14581 case LAYOUT_DIRECTION_RTL: 14582 mUserPaddingLeftInitial = end; 14583 mUserPaddingRightInitial = start; 14584 internalSetPadding(end, top, start, bottom); 14585 break; 14586 case LAYOUT_DIRECTION_LTR: 14587 default: 14588 mUserPaddingLeftInitial = start; 14589 mUserPaddingRightInitial = end; 14590 internalSetPadding(start, top, end, bottom); 14591 } 14592 } 14593 14594 /** 14595 * Returns the top padding of this view. 14596 * 14597 * @return the top padding in pixels 14598 */ 14599 public int getPaddingTop() { 14600 return mPaddingTop; 14601 } 14602 14603 /** 14604 * Returns the bottom padding of this view. If there are inset and enabled 14605 * scrollbars, this value may include the space required to display the 14606 * scrollbars as well. 14607 * 14608 * @return the bottom padding in pixels 14609 */ 14610 public int getPaddingBottom() { 14611 return mPaddingBottom; 14612 } 14613 14614 /** 14615 * Returns the left padding of this view. If there are inset and enabled 14616 * scrollbars, this value may include the space required to display the 14617 * scrollbars as well. 14618 * 14619 * @return the left padding in pixels 14620 */ 14621 public int getPaddingLeft() { 14622 if (!isPaddingResolved()) { 14623 resolvePadding(); 14624 } 14625 return mPaddingLeft; 14626 } 14627 14628 /** 14629 * Returns the start padding of this view depending on its resolved layout direction. 14630 * If there are inset and enabled scrollbars, this value may include the space 14631 * required to display the scrollbars as well. 14632 * 14633 * @return the start padding in pixels 14634 */ 14635 public int getPaddingStart() { 14636 if (!isPaddingResolved()) { 14637 resolvePadding(); 14638 } 14639 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 14640 mPaddingRight : mPaddingLeft; 14641 } 14642 14643 /** 14644 * Returns the right padding of this view. If there are inset and enabled 14645 * scrollbars, this value may include the space required to display the 14646 * scrollbars as well. 14647 * 14648 * @return the right padding in pixels 14649 */ 14650 public int getPaddingRight() { 14651 if (!isPaddingResolved()) { 14652 resolvePadding(); 14653 } 14654 return mPaddingRight; 14655 } 14656 14657 /** 14658 * Returns the end padding of this view depending on its resolved layout direction. 14659 * If there are inset and enabled scrollbars, this value may include the space 14660 * required to display the scrollbars as well. 14661 * 14662 * @return the end padding in pixels 14663 */ 14664 public int getPaddingEnd() { 14665 if (!isPaddingResolved()) { 14666 resolvePadding(); 14667 } 14668 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 14669 mPaddingLeft : mPaddingRight; 14670 } 14671 14672 /** 14673 * Return if the padding as been set thru relative values 14674 * {@link #setPaddingRelative(int, int, int, int)} or thru 14675 * @attr ref android.R.styleable#View_paddingStart or 14676 * @attr ref android.R.styleable#View_paddingEnd 14677 * 14678 * @return true if the padding is relative or false if it is not. 14679 */ 14680 public boolean isPaddingRelative() { 14681 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 14682 } 14683 14684 /** 14685 * @hide 14686 */ 14687 public Insets getOpticalInsets() { 14688 if (mLayoutInsets == null) { 14689 mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets(); 14690 } 14691 return mLayoutInsets; 14692 } 14693 14694 /** 14695 * @hide 14696 */ 14697 public void setLayoutInsets(Insets layoutInsets) { 14698 mLayoutInsets = layoutInsets; 14699 } 14700 14701 /** 14702 * Changes the selection state of this view. A view can be selected or not. 14703 * Note that selection is not the same as focus. Views are typically 14704 * selected in the context of an AdapterView like ListView or GridView; 14705 * the selected view is the view that is highlighted. 14706 * 14707 * @param selected true if the view must be selected, false otherwise 14708 */ 14709 public void setSelected(boolean selected) { 14710 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 14711 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 14712 if (!selected) resetPressedState(); 14713 invalidate(true); 14714 refreshDrawableState(); 14715 dispatchSetSelected(selected); 14716 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 14717 notifyAccessibilityStateChanged(); 14718 } 14719 } 14720 } 14721 14722 /** 14723 * Dispatch setSelected to all of this View's children. 14724 * 14725 * @see #setSelected(boolean) 14726 * 14727 * @param selected The new selected state 14728 */ 14729 protected void dispatchSetSelected(boolean selected) { 14730 } 14731 14732 /** 14733 * Indicates the selection state of this view. 14734 * 14735 * @return true if the view is selected, false otherwise 14736 */ 14737 @ViewDebug.ExportedProperty 14738 public boolean isSelected() { 14739 return (mPrivateFlags & PFLAG_SELECTED) != 0; 14740 } 14741 14742 /** 14743 * Changes the activated state of this view. A view can be activated or not. 14744 * Note that activation is not the same as selection. Selection is 14745 * a transient property, representing the view (hierarchy) the user is 14746 * currently interacting with. Activation is a longer-term state that the 14747 * user can move views in and out of. For example, in a list view with 14748 * single or multiple selection enabled, the views in the current selection 14749 * set are activated. (Um, yeah, we are deeply sorry about the terminology 14750 * here.) The activated state is propagated down to children of the view it 14751 * is set on. 14752 * 14753 * @param activated true if the view must be activated, false otherwise 14754 */ 14755 public void setActivated(boolean activated) { 14756 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 14757 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 14758 invalidate(true); 14759 refreshDrawableState(); 14760 dispatchSetActivated(activated); 14761 } 14762 } 14763 14764 /** 14765 * Dispatch setActivated to all of this View's children. 14766 * 14767 * @see #setActivated(boolean) 14768 * 14769 * @param activated The new activated state 14770 */ 14771 protected void dispatchSetActivated(boolean activated) { 14772 } 14773 14774 /** 14775 * Indicates the activation state of this view. 14776 * 14777 * @return true if the view is activated, false otherwise 14778 */ 14779 @ViewDebug.ExportedProperty 14780 public boolean isActivated() { 14781 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 14782 } 14783 14784 /** 14785 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 14786 * observer can be used to get notifications when global events, like 14787 * layout, happen. 14788 * 14789 * The returned ViewTreeObserver observer is not guaranteed to remain 14790 * valid for the lifetime of this View. If the caller of this method keeps 14791 * a long-lived reference to ViewTreeObserver, it should always check for 14792 * the return value of {@link ViewTreeObserver#isAlive()}. 14793 * 14794 * @return The ViewTreeObserver for this view's hierarchy. 14795 */ 14796 public ViewTreeObserver getViewTreeObserver() { 14797 if (mAttachInfo != null) { 14798 return mAttachInfo.mTreeObserver; 14799 } 14800 if (mFloatingTreeObserver == null) { 14801 mFloatingTreeObserver = new ViewTreeObserver(); 14802 } 14803 return mFloatingTreeObserver; 14804 } 14805 14806 /** 14807 * <p>Finds the topmost view in the current view hierarchy.</p> 14808 * 14809 * @return the topmost view containing this view 14810 */ 14811 public View getRootView() { 14812 if (mAttachInfo != null) { 14813 final View v = mAttachInfo.mRootView; 14814 if (v != null) { 14815 return v; 14816 } 14817 } 14818 14819 View parent = this; 14820 14821 while (parent.mParent != null && parent.mParent instanceof View) { 14822 parent = (View) parent.mParent; 14823 } 14824 14825 return parent; 14826 } 14827 14828 /** 14829 * <p>Computes the coordinates of this view on the screen. The argument 14830 * must be an array of two integers. After the method returns, the array 14831 * contains the x and y location in that order.</p> 14832 * 14833 * @param location an array of two integers in which to hold the coordinates 14834 */ 14835 public void getLocationOnScreen(int[] location) { 14836 getLocationInWindow(location); 14837 14838 final AttachInfo info = mAttachInfo; 14839 if (info != null) { 14840 location[0] += info.mWindowLeft; 14841 location[1] += info.mWindowTop; 14842 } 14843 } 14844 14845 /** 14846 * <p>Computes the coordinates of this view in its window. The argument 14847 * must be an array of two integers. After the method returns, the array 14848 * contains the x and y location in that order.</p> 14849 * 14850 * @param location an array of two integers in which to hold the coordinates 14851 */ 14852 public void getLocationInWindow(int[] location) { 14853 if (location == null || location.length < 2) { 14854 throw new IllegalArgumentException("location must be an array of two integers"); 14855 } 14856 14857 if (mAttachInfo == null) { 14858 // When the view is not attached to a window, this method does not make sense 14859 location[0] = location[1] = 0; 14860 return; 14861 } 14862 14863 float[] position = mAttachInfo.mTmpTransformLocation; 14864 position[0] = position[1] = 0.0f; 14865 14866 if (!hasIdentityMatrix()) { 14867 getMatrix().mapPoints(position); 14868 } 14869 14870 position[0] += mLeft; 14871 position[1] += mTop; 14872 14873 ViewParent viewParent = mParent; 14874 while (viewParent instanceof View) { 14875 final View view = (View) viewParent; 14876 14877 position[0] -= view.mScrollX; 14878 position[1] -= view.mScrollY; 14879 14880 if (!view.hasIdentityMatrix()) { 14881 view.getMatrix().mapPoints(position); 14882 } 14883 14884 position[0] += view.mLeft; 14885 position[1] += view.mTop; 14886 14887 viewParent = view.mParent; 14888 } 14889 14890 if (viewParent instanceof ViewRootImpl) { 14891 // *cough* 14892 final ViewRootImpl vr = (ViewRootImpl) viewParent; 14893 position[1] -= vr.mCurScrollY; 14894 } 14895 14896 location[0] = (int) (position[0] + 0.5f); 14897 location[1] = (int) (position[1] + 0.5f); 14898 } 14899 14900 /** 14901 * {@hide} 14902 * @param id the id of the view to be found 14903 * @return the view of the specified id, null if cannot be found 14904 */ 14905 protected View findViewTraversal(int id) { 14906 if (id == mID) { 14907 return this; 14908 } 14909 return null; 14910 } 14911 14912 /** 14913 * {@hide} 14914 * @param tag the tag of the view to be found 14915 * @return the view of specified tag, null if cannot be found 14916 */ 14917 protected View findViewWithTagTraversal(Object tag) { 14918 if (tag != null && tag.equals(mTag)) { 14919 return this; 14920 } 14921 return null; 14922 } 14923 14924 /** 14925 * {@hide} 14926 * @param predicate The predicate to evaluate. 14927 * @param childToSkip If not null, ignores this child during the recursive traversal. 14928 * @return The first view that matches the predicate or null. 14929 */ 14930 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 14931 if (predicate.apply(this)) { 14932 return this; 14933 } 14934 return null; 14935 } 14936 14937 /** 14938 * Look for a child view with the given id. If this view has the given 14939 * id, return this view. 14940 * 14941 * @param id The id to search for. 14942 * @return The view that has the given id in the hierarchy or null 14943 */ 14944 public final View findViewById(int id) { 14945 if (id < 0) { 14946 return null; 14947 } 14948 return findViewTraversal(id); 14949 } 14950 14951 /** 14952 * Finds a view by its unuque and stable accessibility id. 14953 * 14954 * @param accessibilityId The searched accessibility id. 14955 * @return The found view. 14956 */ 14957 final View findViewByAccessibilityId(int accessibilityId) { 14958 if (accessibilityId < 0) { 14959 return null; 14960 } 14961 return findViewByAccessibilityIdTraversal(accessibilityId); 14962 } 14963 14964 /** 14965 * Performs the traversal to find a view by its unuque and stable accessibility id. 14966 * 14967 * <strong>Note:</strong>This method does not stop at the root namespace 14968 * boundary since the user can touch the screen at an arbitrary location 14969 * potentially crossing the root namespace bounday which will send an 14970 * accessibility event to accessibility services and they should be able 14971 * to obtain the event source. Also accessibility ids are guaranteed to be 14972 * unique in the window. 14973 * 14974 * @param accessibilityId The accessibility id. 14975 * @return The found view. 14976 */ 14977 View findViewByAccessibilityIdTraversal(int accessibilityId) { 14978 if (getAccessibilityViewId() == accessibilityId) { 14979 return this; 14980 } 14981 return null; 14982 } 14983 14984 /** 14985 * Look for a child view with the given tag. If this view has the given 14986 * tag, return this view. 14987 * 14988 * @param tag The tag to search for, using "tag.equals(getTag())". 14989 * @return The View that has the given tag in the hierarchy or null 14990 */ 14991 public final View findViewWithTag(Object tag) { 14992 if (tag == null) { 14993 return null; 14994 } 14995 return findViewWithTagTraversal(tag); 14996 } 14997 14998 /** 14999 * {@hide} 15000 * Look for a child view that matches the specified predicate. 15001 * If this view matches the predicate, return this view. 15002 * 15003 * @param predicate The predicate to evaluate. 15004 * @return The first view that matches the predicate or null. 15005 */ 15006 public final View findViewByPredicate(Predicate<View> predicate) { 15007 return findViewByPredicateTraversal(predicate, null); 15008 } 15009 15010 /** 15011 * {@hide} 15012 * Look for a child view that matches the specified predicate, 15013 * starting with the specified view and its descendents and then 15014 * recusively searching the ancestors and siblings of that view 15015 * until this view is reached. 15016 * 15017 * This method is useful in cases where the predicate does not match 15018 * a single unique view (perhaps multiple views use the same id) 15019 * and we are trying to find the view that is "closest" in scope to the 15020 * starting view. 15021 * 15022 * @param start The view to start from. 15023 * @param predicate The predicate to evaluate. 15024 * @return The first view that matches the predicate or null. 15025 */ 15026 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 15027 View childToSkip = null; 15028 for (;;) { 15029 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 15030 if (view != null || start == this) { 15031 return view; 15032 } 15033 15034 ViewParent parent = start.getParent(); 15035 if (parent == null || !(parent instanceof View)) { 15036 return null; 15037 } 15038 15039 childToSkip = start; 15040 start = (View) parent; 15041 } 15042 } 15043 15044 /** 15045 * Sets the identifier for this view. The identifier does not have to be 15046 * unique in this view's hierarchy. The identifier should be a positive 15047 * number. 15048 * 15049 * @see #NO_ID 15050 * @see #getId() 15051 * @see #findViewById(int) 15052 * 15053 * @param id a number used to identify the view 15054 * 15055 * @attr ref android.R.styleable#View_id 15056 */ 15057 public void setId(int id) { 15058 mID = id; 15059 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 15060 mID = generateViewId(); 15061 } 15062 } 15063 15064 /** 15065 * {@hide} 15066 * 15067 * @param isRoot true if the view belongs to the root namespace, false 15068 * otherwise 15069 */ 15070 public void setIsRootNamespace(boolean isRoot) { 15071 if (isRoot) { 15072 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 15073 } else { 15074 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 15075 } 15076 } 15077 15078 /** 15079 * {@hide} 15080 * 15081 * @return true if the view belongs to the root namespace, false otherwise 15082 */ 15083 public boolean isRootNamespace() { 15084 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 15085 } 15086 15087 /** 15088 * Returns this view's identifier. 15089 * 15090 * @return a positive integer used to identify the view or {@link #NO_ID} 15091 * if the view has no ID 15092 * 15093 * @see #setId(int) 15094 * @see #findViewById(int) 15095 * @attr ref android.R.styleable#View_id 15096 */ 15097 @ViewDebug.CapturedViewProperty 15098 public int getId() { 15099 return mID; 15100 } 15101 15102 /** 15103 * Returns this view's tag. 15104 * 15105 * @return the Object stored in this view as a tag 15106 * 15107 * @see #setTag(Object) 15108 * @see #getTag(int) 15109 */ 15110 @ViewDebug.ExportedProperty 15111 public Object getTag() { 15112 return mTag; 15113 } 15114 15115 /** 15116 * Sets the tag associated with this view. A tag can be used to mark 15117 * a view in its hierarchy and does not have to be unique within the 15118 * hierarchy. Tags can also be used to store data within a view without 15119 * resorting to another data structure. 15120 * 15121 * @param tag an Object to tag the view with 15122 * 15123 * @see #getTag() 15124 * @see #setTag(int, Object) 15125 */ 15126 public void setTag(final Object tag) { 15127 mTag = tag; 15128 } 15129 15130 /** 15131 * Returns the tag associated with this view and the specified key. 15132 * 15133 * @param key The key identifying the tag 15134 * 15135 * @return the Object stored in this view as a tag 15136 * 15137 * @see #setTag(int, Object) 15138 * @see #getTag() 15139 */ 15140 public Object getTag(int key) { 15141 if (mKeyedTags != null) return mKeyedTags.get(key); 15142 return null; 15143 } 15144 15145 /** 15146 * Sets a tag associated with this view and a key. A tag can be used 15147 * to mark a view in its hierarchy and does not have to be unique within 15148 * the hierarchy. Tags can also be used to store data within a view 15149 * without resorting to another data structure. 15150 * 15151 * The specified key should be an id declared in the resources of the 15152 * application to ensure it is unique (see the <a 15153 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 15154 * Keys identified as belonging to 15155 * the Android framework or not associated with any package will cause 15156 * an {@link IllegalArgumentException} to be thrown. 15157 * 15158 * @param key The key identifying the tag 15159 * @param tag An Object to tag the view with 15160 * 15161 * @throws IllegalArgumentException If they specified key is not valid 15162 * 15163 * @see #setTag(Object) 15164 * @see #getTag(int) 15165 */ 15166 public void setTag(int key, final Object tag) { 15167 // If the package id is 0x00 or 0x01, it's either an undefined package 15168 // or a framework id 15169 if ((key >>> 24) < 2) { 15170 throw new IllegalArgumentException("The key must be an application-specific " 15171 + "resource id."); 15172 } 15173 15174 setKeyedTag(key, tag); 15175 } 15176 15177 /** 15178 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 15179 * framework id. 15180 * 15181 * @hide 15182 */ 15183 public void setTagInternal(int key, Object tag) { 15184 if ((key >>> 24) != 0x1) { 15185 throw new IllegalArgumentException("The key must be a framework-specific " 15186 + "resource id."); 15187 } 15188 15189 setKeyedTag(key, tag); 15190 } 15191 15192 private void setKeyedTag(int key, Object tag) { 15193 if (mKeyedTags == null) { 15194 mKeyedTags = new SparseArray<Object>(); 15195 } 15196 15197 mKeyedTags.put(key, tag); 15198 } 15199 15200 /** 15201 * Prints information about this view in the log output, with the tag 15202 * {@link #VIEW_LOG_TAG}. 15203 * 15204 * @hide 15205 */ 15206 public void debug() { 15207 debug(0); 15208 } 15209 15210 /** 15211 * Prints information about this view in the log output, with the tag 15212 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 15213 * indentation defined by the <code>depth</code>. 15214 * 15215 * @param depth the indentation level 15216 * 15217 * @hide 15218 */ 15219 protected void debug(int depth) { 15220 String output = debugIndent(depth - 1); 15221 15222 output += "+ " + this; 15223 int id = getId(); 15224 if (id != -1) { 15225 output += " (id=" + id + ")"; 15226 } 15227 Object tag = getTag(); 15228 if (tag != null) { 15229 output += " (tag=" + tag + ")"; 15230 } 15231 Log.d(VIEW_LOG_TAG, output); 15232 15233 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 15234 output = debugIndent(depth) + " FOCUSED"; 15235 Log.d(VIEW_LOG_TAG, output); 15236 } 15237 15238 output = debugIndent(depth); 15239 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 15240 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 15241 + "} "; 15242 Log.d(VIEW_LOG_TAG, output); 15243 15244 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 15245 || mPaddingBottom != 0) { 15246 output = debugIndent(depth); 15247 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 15248 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 15249 Log.d(VIEW_LOG_TAG, output); 15250 } 15251 15252 output = debugIndent(depth); 15253 output += "mMeasureWidth=" + mMeasuredWidth + 15254 " mMeasureHeight=" + mMeasuredHeight; 15255 Log.d(VIEW_LOG_TAG, output); 15256 15257 output = debugIndent(depth); 15258 if (mLayoutParams == null) { 15259 output += "BAD! no layout params"; 15260 } else { 15261 output = mLayoutParams.debug(output); 15262 } 15263 Log.d(VIEW_LOG_TAG, output); 15264 15265 output = debugIndent(depth); 15266 output += "flags={"; 15267 output += View.printFlags(mViewFlags); 15268 output += "}"; 15269 Log.d(VIEW_LOG_TAG, output); 15270 15271 output = debugIndent(depth); 15272 output += "privateFlags={"; 15273 output += View.printPrivateFlags(mPrivateFlags); 15274 output += "}"; 15275 Log.d(VIEW_LOG_TAG, output); 15276 } 15277 15278 /** 15279 * Creates a string of whitespaces used for indentation. 15280 * 15281 * @param depth the indentation level 15282 * @return a String containing (depth * 2 + 3) * 2 white spaces 15283 * 15284 * @hide 15285 */ 15286 protected static String debugIndent(int depth) { 15287 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 15288 for (int i = 0; i < (depth * 2) + 3; i++) { 15289 spaces.append(' ').append(' '); 15290 } 15291 return spaces.toString(); 15292 } 15293 15294 /** 15295 * <p>Return the offset of the widget's text baseline from the widget's top 15296 * boundary. If this widget does not support baseline alignment, this 15297 * method returns -1. </p> 15298 * 15299 * @return the offset of the baseline within the widget's bounds or -1 15300 * if baseline alignment is not supported 15301 */ 15302 @ViewDebug.ExportedProperty(category = "layout") 15303 public int getBaseline() { 15304 return -1; 15305 } 15306 15307 /** 15308 * Returns whether the view hierarchy is currently undergoing a layout pass. This 15309 * information is useful to avoid situations such as calling {@link #requestLayout()} during 15310 * a layout pass. 15311 * 15312 * @return whether the view hierarchy is currently undergoing a layout pass 15313 */ 15314 public boolean isInLayout() { 15315 ViewRootImpl viewRoot = getViewRootImpl(); 15316 return (viewRoot != null && viewRoot.isInLayout()); 15317 } 15318 15319 /** 15320 * Call this when something has changed which has invalidated the 15321 * layout of this view. This will schedule a layout pass of the view 15322 * tree. This should not be called while the view hierarchy is currently in a layout 15323 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 15324 * end of the current layout pass (and then layout will run again) or after the current 15325 * frame is drawn and the next layout occurs. 15326 * 15327 * <p>Subclasses which override this method should call the superclass method to 15328 * handle possible request-during-layout errors correctly.</p> 15329 */ 15330 public void requestLayout() { 15331 ViewRootImpl viewRoot = getViewRootImpl(); 15332 if (viewRoot != null && viewRoot.isInLayout()) { 15333 viewRoot.requestLayoutDuringLayout(this); 15334 return; 15335 } 15336 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 15337 mPrivateFlags |= PFLAG_INVALIDATED; 15338 15339 if (mParent != null && !mParent.isLayoutRequested()) { 15340 mParent.requestLayout(); 15341 } 15342 } 15343 15344 /** 15345 * Forces this view to be laid out during the next layout pass. 15346 * This method does not call requestLayout() or forceLayout() 15347 * on the parent. 15348 */ 15349 public void forceLayout() { 15350 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 15351 mPrivateFlags |= PFLAG_INVALIDATED; 15352 } 15353 15354 /** 15355 * <p> 15356 * This is called to find out how big a view should be. The parent 15357 * supplies constraint information in the width and height parameters. 15358 * </p> 15359 * 15360 * <p> 15361 * The actual measurement work of a view is performed in 15362 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 15363 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 15364 * </p> 15365 * 15366 * 15367 * @param widthMeasureSpec Horizontal space requirements as imposed by the 15368 * parent 15369 * @param heightMeasureSpec Vertical space requirements as imposed by the 15370 * parent 15371 * 15372 * @see #onMeasure(int, int) 15373 */ 15374 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 15375 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 15376 widthMeasureSpec != mOldWidthMeasureSpec || 15377 heightMeasureSpec != mOldHeightMeasureSpec) { 15378 15379 // first clears the measured dimension flag 15380 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 15381 15382 if (!isPaddingResolved()) { 15383 resolvePadding(); 15384 } 15385 15386 // measure ourselves, this should set the measured dimension flag back 15387 onMeasure(widthMeasureSpec, heightMeasureSpec); 15388 15389 // flag not set, setMeasuredDimension() was not invoked, we raise 15390 // an exception to warn the developer 15391 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 15392 throw new IllegalStateException("onMeasure() did not set the" 15393 + " measured dimension by calling" 15394 + " setMeasuredDimension()"); 15395 } 15396 15397 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 15398 } 15399 15400 mOldWidthMeasureSpec = widthMeasureSpec; 15401 mOldHeightMeasureSpec = heightMeasureSpec; 15402 } 15403 15404 /** 15405 * <p> 15406 * Measure the view and its content to determine the measured width and the 15407 * measured height. This method is invoked by {@link #measure(int, int)} and 15408 * should be overriden by subclasses to provide accurate and efficient 15409 * measurement of their contents. 15410 * </p> 15411 * 15412 * <p> 15413 * <strong>CONTRACT:</strong> When overriding this method, you 15414 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 15415 * measured width and height of this view. Failure to do so will trigger an 15416 * <code>IllegalStateException</code>, thrown by 15417 * {@link #measure(int, int)}. Calling the superclass' 15418 * {@link #onMeasure(int, int)} is a valid use. 15419 * </p> 15420 * 15421 * <p> 15422 * The base class implementation of measure defaults to the background size, 15423 * unless a larger size is allowed by the MeasureSpec. Subclasses should 15424 * override {@link #onMeasure(int, int)} to provide better measurements of 15425 * their content. 15426 * </p> 15427 * 15428 * <p> 15429 * If this method is overridden, it is the subclass's responsibility to make 15430 * sure the measured height and width are at least the view's minimum height 15431 * and width ({@link #getSuggestedMinimumHeight()} and 15432 * {@link #getSuggestedMinimumWidth()}). 15433 * </p> 15434 * 15435 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 15436 * The requirements are encoded with 15437 * {@link android.view.View.MeasureSpec}. 15438 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 15439 * The requirements are encoded with 15440 * {@link android.view.View.MeasureSpec}. 15441 * 15442 * @see #getMeasuredWidth() 15443 * @see #getMeasuredHeight() 15444 * @see #setMeasuredDimension(int, int) 15445 * @see #getSuggestedMinimumHeight() 15446 * @see #getSuggestedMinimumWidth() 15447 * @see android.view.View.MeasureSpec#getMode(int) 15448 * @see android.view.View.MeasureSpec#getSize(int) 15449 */ 15450 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 15451 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 15452 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 15453 } 15454 15455 /** 15456 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 15457 * measured width and measured height. Failing to do so will trigger an 15458 * exception at measurement time.</p> 15459 * 15460 * @param measuredWidth The measured width of this view. May be a complex 15461 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 15462 * {@link #MEASURED_STATE_TOO_SMALL}. 15463 * @param measuredHeight The measured height of this view. May be a complex 15464 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 15465 * {@link #MEASURED_STATE_TOO_SMALL}. 15466 */ 15467 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 15468 mMeasuredWidth = measuredWidth; 15469 mMeasuredHeight = measuredHeight; 15470 15471 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 15472 } 15473 15474 /** 15475 * Merge two states as returned by {@link #getMeasuredState()}. 15476 * @param curState The current state as returned from a view or the result 15477 * of combining multiple views. 15478 * @param newState The new view state to combine. 15479 * @return Returns a new integer reflecting the combination of the two 15480 * states. 15481 */ 15482 public static int combineMeasuredStates(int curState, int newState) { 15483 return curState | newState; 15484 } 15485 15486 /** 15487 * Version of {@link #resolveSizeAndState(int, int, int)} 15488 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 15489 */ 15490 public static int resolveSize(int size, int measureSpec) { 15491 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 15492 } 15493 15494 /** 15495 * Utility to reconcile a desired size and state, with constraints imposed 15496 * by a MeasureSpec. Will take the desired size, unless a different size 15497 * is imposed by the constraints. The returned value is a compound integer, 15498 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 15499 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 15500 * size is smaller than the size the view wants to be. 15501 * 15502 * @param size How big the view wants to be 15503 * @param measureSpec Constraints imposed by the parent 15504 * @return Size information bit mask as defined by 15505 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 15506 */ 15507 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 15508 int result = size; 15509 int specMode = MeasureSpec.getMode(measureSpec); 15510 int specSize = MeasureSpec.getSize(measureSpec); 15511 switch (specMode) { 15512 case MeasureSpec.UNSPECIFIED: 15513 result = size; 15514 break; 15515 case MeasureSpec.AT_MOST: 15516 if (specSize < size) { 15517 result = specSize | MEASURED_STATE_TOO_SMALL; 15518 } else { 15519 result = size; 15520 } 15521 break; 15522 case MeasureSpec.EXACTLY: 15523 result = specSize; 15524 break; 15525 } 15526 return result | (childMeasuredState&MEASURED_STATE_MASK); 15527 } 15528 15529 /** 15530 * Utility to return a default size. Uses the supplied size if the 15531 * MeasureSpec imposed no constraints. Will get larger if allowed 15532 * by the MeasureSpec. 15533 * 15534 * @param size Default size for this view 15535 * @param measureSpec Constraints imposed by the parent 15536 * @return The size this view should be. 15537 */ 15538 public static int getDefaultSize(int size, int measureSpec) { 15539 int result = size; 15540 int specMode = MeasureSpec.getMode(measureSpec); 15541 int specSize = MeasureSpec.getSize(measureSpec); 15542 15543 switch (specMode) { 15544 case MeasureSpec.UNSPECIFIED: 15545 result = size; 15546 break; 15547 case MeasureSpec.AT_MOST: 15548 case MeasureSpec.EXACTLY: 15549 result = specSize; 15550 break; 15551 } 15552 return result; 15553 } 15554 15555 /** 15556 * Returns the suggested minimum height that the view should use. This 15557 * returns the maximum of the view's minimum height 15558 * and the background's minimum height 15559 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 15560 * <p> 15561 * When being used in {@link #onMeasure(int, int)}, the caller should still 15562 * ensure the returned height is within the requirements of the parent. 15563 * 15564 * @return The suggested minimum height of the view. 15565 */ 15566 protected int getSuggestedMinimumHeight() { 15567 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 15568 15569 } 15570 15571 /** 15572 * Returns the suggested minimum width that the view should use. This 15573 * returns the maximum of the view's minimum width) 15574 * and the background's minimum width 15575 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 15576 * <p> 15577 * When being used in {@link #onMeasure(int, int)}, the caller should still 15578 * ensure the returned width is within the requirements of the parent. 15579 * 15580 * @return The suggested minimum width of the view. 15581 */ 15582 protected int getSuggestedMinimumWidth() { 15583 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 15584 } 15585 15586 /** 15587 * Returns the minimum height of the view. 15588 * 15589 * @return the minimum height the view will try to be. 15590 * 15591 * @see #setMinimumHeight(int) 15592 * 15593 * @attr ref android.R.styleable#View_minHeight 15594 */ 15595 public int getMinimumHeight() { 15596 return mMinHeight; 15597 } 15598 15599 /** 15600 * Sets the minimum height of the view. It is not guaranteed the view will 15601 * be able to achieve this minimum height (for example, if its parent layout 15602 * constrains it with less available height). 15603 * 15604 * @param minHeight The minimum height the view will try to be. 15605 * 15606 * @see #getMinimumHeight() 15607 * 15608 * @attr ref android.R.styleable#View_minHeight 15609 */ 15610 public void setMinimumHeight(int minHeight) { 15611 mMinHeight = minHeight; 15612 requestLayout(); 15613 } 15614 15615 /** 15616 * Returns the minimum width of the view. 15617 * 15618 * @return the minimum width the view will try to be. 15619 * 15620 * @see #setMinimumWidth(int) 15621 * 15622 * @attr ref android.R.styleable#View_minWidth 15623 */ 15624 public int getMinimumWidth() { 15625 return mMinWidth; 15626 } 15627 15628 /** 15629 * Sets the minimum width of the view. It is not guaranteed the view will 15630 * be able to achieve this minimum width (for example, if its parent layout 15631 * constrains it with less available width). 15632 * 15633 * @param minWidth The minimum width the view will try to be. 15634 * 15635 * @see #getMinimumWidth() 15636 * 15637 * @attr ref android.R.styleable#View_minWidth 15638 */ 15639 public void setMinimumWidth(int minWidth) { 15640 mMinWidth = minWidth; 15641 requestLayout(); 15642 15643 } 15644 15645 /** 15646 * Get the animation currently associated with this view. 15647 * 15648 * @return The animation that is currently playing or 15649 * scheduled to play for this view. 15650 */ 15651 public Animation getAnimation() { 15652 return mCurrentAnimation; 15653 } 15654 15655 /** 15656 * Start the specified animation now. 15657 * 15658 * @param animation the animation to start now 15659 */ 15660 public void startAnimation(Animation animation) { 15661 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 15662 setAnimation(animation); 15663 invalidateParentCaches(); 15664 invalidate(true); 15665 } 15666 15667 /** 15668 * Cancels any animations for this view. 15669 */ 15670 public void clearAnimation() { 15671 if (mCurrentAnimation != null) { 15672 mCurrentAnimation.detach(); 15673 } 15674 mCurrentAnimation = null; 15675 invalidateParentIfNeeded(); 15676 } 15677 15678 /** 15679 * Sets the next animation to play for this view. 15680 * If you want the animation to play immediately, use 15681 * {@link #startAnimation(android.view.animation.Animation)} instead. 15682 * This method provides allows fine-grained 15683 * control over the start time and invalidation, but you 15684 * must make sure that 1) the animation has a start time set, and 15685 * 2) the view's parent (which controls animations on its children) 15686 * will be invalidated when the animation is supposed to 15687 * start. 15688 * 15689 * @param animation The next animation, or null. 15690 */ 15691 public void setAnimation(Animation animation) { 15692 mCurrentAnimation = animation; 15693 15694 if (animation != null) { 15695 // If the screen is off assume the animation start time is now instead of 15696 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 15697 // would cause the animation to start when the screen turns back on 15698 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 15699 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 15700 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 15701 } 15702 animation.reset(); 15703 } 15704 } 15705 15706 /** 15707 * Invoked by a parent ViewGroup to notify the start of the animation 15708 * currently associated with this view. If you override this method, 15709 * always call super.onAnimationStart(); 15710 * 15711 * @see #setAnimation(android.view.animation.Animation) 15712 * @see #getAnimation() 15713 */ 15714 protected void onAnimationStart() { 15715 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 15716 } 15717 15718 /** 15719 * Invoked by a parent ViewGroup to notify the end of the animation 15720 * currently associated with this view. If you override this method, 15721 * always call super.onAnimationEnd(); 15722 * 15723 * @see #setAnimation(android.view.animation.Animation) 15724 * @see #getAnimation() 15725 */ 15726 protected void onAnimationEnd() { 15727 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 15728 } 15729 15730 /** 15731 * Invoked if there is a Transform that involves alpha. Subclass that can 15732 * draw themselves with the specified alpha should return true, and then 15733 * respect that alpha when their onDraw() is called. If this returns false 15734 * then the view may be redirected to draw into an offscreen buffer to 15735 * fulfill the request, which will look fine, but may be slower than if the 15736 * subclass handles it internally. The default implementation returns false. 15737 * 15738 * @param alpha The alpha (0..255) to apply to the view's drawing 15739 * @return true if the view can draw with the specified alpha. 15740 */ 15741 protected boolean onSetAlpha(int alpha) { 15742 return false; 15743 } 15744 15745 /** 15746 * This is used by the RootView to perform an optimization when 15747 * the view hierarchy contains one or several SurfaceView. 15748 * SurfaceView is always considered transparent, but its children are not, 15749 * therefore all View objects remove themselves from the global transparent 15750 * region (passed as a parameter to this function). 15751 * 15752 * @param region The transparent region for this ViewAncestor (window). 15753 * 15754 * @return Returns true if the effective visibility of the view at this 15755 * point is opaque, regardless of the transparent region; returns false 15756 * if it is possible for underlying windows to be seen behind the view. 15757 * 15758 * {@hide} 15759 */ 15760 public boolean gatherTransparentRegion(Region region) { 15761 final AttachInfo attachInfo = mAttachInfo; 15762 if (region != null && attachInfo != null) { 15763 final int pflags = mPrivateFlags; 15764 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 15765 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 15766 // remove it from the transparent region. 15767 final int[] location = attachInfo.mTransparentLocation; 15768 getLocationInWindow(location); 15769 region.op(location[0], location[1], location[0] + mRight - mLeft, 15770 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 15771 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 15772 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 15773 // exists, so we remove the background drawable's non-transparent 15774 // parts from this transparent region. 15775 applyDrawableToTransparentRegion(mBackground, region); 15776 } 15777 } 15778 return true; 15779 } 15780 15781 /** 15782 * Play a sound effect for this view. 15783 * 15784 * <p>The framework will play sound effects for some built in actions, such as 15785 * clicking, but you may wish to play these effects in your widget, 15786 * for instance, for internal navigation. 15787 * 15788 * <p>The sound effect will only be played if sound effects are enabled by the user, and 15789 * {@link #isSoundEffectsEnabled()} is true. 15790 * 15791 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 15792 */ 15793 public void playSoundEffect(int soundConstant) { 15794 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 15795 return; 15796 } 15797 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 15798 } 15799 15800 /** 15801 * BZZZTT!!1! 15802 * 15803 * <p>Provide haptic feedback to the user for this view. 15804 * 15805 * <p>The framework will provide haptic feedback for some built in actions, 15806 * such as long presses, but you may wish to provide feedback for your 15807 * own widget. 15808 * 15809 * <p>The feedback will only be performed if 15810 * {@link #isHapticFeedbackEnabled()} is true. 15811 * 15812 * @param feedbackConstant One of the constants defined in 15813 * {@link HapticFeedbackConstants} 15814 */ 15815 public boolean performHapticFeedback(int feedbackConstant) { 15816 return performHapticFeedback(feedbackConstant, 0); 15817 } 15818 15819 /** 15820 * BZZZTT!!1! 15821 * 15822 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 15823 * 15824 * @param feedbackConstant One of the constants defined in 15825 * {@link HapticFeedbackConstants} 15826 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 15827 */ 15828 public boolean performHapticFeedback(int feedbackConstant, int flags) { 15829 if (mAttachInfo == null) { 15830 return false; 15831 } 15832 //noinspection SimplifiableIfStatement 15833 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 15834 && !isHapticFeedbackEnabled()) { 15835 return false; 15836 } 15837 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 15838 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 15839 } 15840 15841 /** 15842 * Request that the visibility of the status bar or other screen/window 15843 * decorations be changed. 15844 * 15845 * <p>This method is used to put the over device UI into temporary modes 15846 * where the user's attention is focused more on the application content, 15847 * by dimming or hiding surrounding system affordances. This is typically 15848 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 15849 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 15850 * to be placed behind the action bar (and with these flags other system 15851 * affordances) so that smooth transitions between hiding and showing them 15852 * can be done. 15853 * 15854 * <p>Two representative examples of the use of system UI visibility is 15855 * implementing a content browsing application (like a magazine reader) 15856 * and a video playing application. 15857 * 15858 * <p>The first code shows a typical implementation of a View in a content 15859 * browsing application. In this implementation, the application goes 15860 * into a content-oriented mode by hiding the status bar and action bar, 15861 * and putting the navigation elements into lights out mode. The user can 15862 * then interact with content while in this mode. Such an application should 15863 * provide an easy way for the user to toggle out of the mode (such as to 15864 * check information in the status bar or access notifications). In the 15865 * implementation here, this is done simply by tapping on the content. 15866 * 15867 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 15868 * content} 15869 * 15870 * <p>This second code sample shows a typical implementation of a View 15871 * in a video playing application. In this situation, while the video is 15872 * playing the application would like to go into a complete full-screen mode, 15873 * to use as much of the display as possible for the video. When in this state 15874 * the user can not interact with the application; the system intercepts 15875 * touching on the screen to pop the UI out of full screen mode. See 15876 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 15877 * 15878 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 15879 * content} 15880 * 15881 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 15882 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 15883 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 15884 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 15885 */ 15886 public void setSystemUiVisibility(int visibility) { 15887 if (visibility != mSystemUiVisibility) { 15888 mSystemUiVisibility = visibility; 15889 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 15890 mParent.recomputeViewAttributes(this); 15891 } 15892 } 15893 } 15894 15895 /** 15896 * Returns the last {@link #setSystemUiVisibility(int) that this view has requested. 15897 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 15898 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 15899 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 15900 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 15901 */ 15902 public int getSystemUiVisibility() { 15903 return mSystemUiVisibility; 15904 } 15905 15906 /** 15907 * Returns the current system UI visibility that is currently set for 15908 * the entire window. This is the combination of the 15909 * {@link #setSystemUiVisibility(int)} values supplied by all of the 15910 * views in the window. 15911 */ 15912 public int getWindowSystemUiVisibility() { 15913 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 15914 } 15915 15916 /** 15917 * Override to find out when the window's requested system UI visibility 15918 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 15919 * This is different from the callbacks recieved through 15920 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 15921 * in that this is only telling you about the local request of the window, 15922 * not the actual values applied by the system. 15923 */ 15924 public void onWindowSystemUiVisibilityChanged(int visible) { 15925 } 15926 15927 /** 15928 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 15929 * the view hierarchy. 15930 */ 15931 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 15932 onWindowSystemUiVisibilityChanged(visible); 15933 } 15934 15935 /** 15936 * Set a listener to receive callbacks when the visibility of the system bar changes. 15937 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 15938 */ 15939 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 15940 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 15941 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 15942 mParent.recomputeViewAttributes(this); 15943 } 15944 } 15945 15946 /** 15947 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 15948 * the view hierarchy. 15949 */ 15950 public void dispatchSystemUiVisibilityChanged(int visibility) { 15951 ListenerInfo li = mListenerInfo; 15952 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 15953 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 15954 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 15955 } 15956 } 15957 15958 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 15959 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 15960 if (val != mSystemUiVisibility) { 15961 setSystemUiVisibility(val); 15962 return true; 15963 } 15964 return false; 15965 } 15966 15967 /** @hide */ 15968 public void setDisabledSystemUiVisibility(int flags) { 15969 if (mAttachInfo != null) { 15970 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 15971 mAttachInfo.mDisabledSystemUiVisibility = flags; 15972 if (mParent != null) { 15973 mParent.recomputeViewAttributes(this); 15974 } 15975 } 15976 } 15977 } 15978 15979 /** 15980 * Creates an image that the system displays during the drag and drop 15981 * operation. This is called a "drag shadow". The default implementation 15982 * for a DragShadowBuilder based on a View returns an image that has exactly the same 15983 * appearance as the given View. The default also positions the center of the drag shadow 15984 * directly under the touch point. If no View is provided (the constructor with no parameters 15985 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 15986 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 15987 * default is an invisible drag shadow. 15988 * <p> 15989 * You are not required to use the View you provide to the constructor as the basis of the 15990 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 15991 * anything you want as the drag shadow. 15992 * </p> 15993 * <p> 15994 * You pass a DragShadowBuilder object to the system when you start the drag. The system 15995 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 15996 * size and position of the drag shadow. It uses this data to construct a 15997 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 15998 * so that your application can draw the shadow image in the Canvas. 15999 * </p> 16000 * 16001 * <div class="special reference"> 16002 * <h3>Developer Guides</h3> 16003 * <p>For a guide to implementing drag and drop features, read the 16004 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 16005 * </div> 16006 */ 16007 public static class DragShadowBuilder { 16008 private final WeakReference<View> mView; 16009 16010 /** 16011 * Constructs a shadow image builder based on a View. By default, the resulting drag 16012 * shadow will have the same appearance and dimensions as the View, with the touch point 16013 * over the center of the View. 16014 * @param view A View. Any View in scope can be used. 16015 */ 16016 public DragShadowBuilder(View view) { 16017 mView = new WeakReference<View>(view); 16018 } 16019 16020 /** 16021 * Construct a shadow builder object with no associated View. This 16022 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 16023 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 16024 * to supply the drag shadow's dimensions and appearance without 16025 * reference to any View object. If they are not overridden, then the result is an 16026 * invisible drag shadow. 16027 */ 16028 public DragShadowBuilder() { 16029 mView = new WeakReference<View>(null); 16030 } 16031 16032 /** 16033 * Returns the View object that had been passed to the 16034 * {@link #View.DragShadowBuilder(View)} 16035 * constructor. If that View parameter was {@code null} or if the 16036 * {@link #View.DragShadowBuilder()} 16037 * constructor was used to instantiate the builder object, this method will return 16038 * null. 16039 * 16040 * @return The View object associate with this builder object. 16041 */ 16042 @SuppressWarnings({"JavadocReference"}) 16043 final public View getView() { 16044 return mView.get(); 16045 } 16046 16047 /** 16048 * Provides the metrics for the shadow image. These include the dimensions of 16049 * the shadow image, and the point within that shadow that should 16050 * be centered under the touch location while dragging. 16051 * <p> 16052 * The default implementation sets the dimensions of the shadow to be the 16053 * same as the dimensions of the View itself and centers the shadow under 16054 * the touch point. 16055 * </p> 16056 * 16057 * @param shadowSize A {@link android.graphics.Point} containing the width and height 16058 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 16059 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 16060 * image. 16061 * 16062 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 16063 * shadow image that should be underneath the touch point during the drag and drop 16064 * operation. Your application must set {@link android.graphics.Point#x} to the 16065 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 16066 */ 16067 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 16068 final View view = mView.get(); 16069 if (view != null) { 16070 shadowSize.set(view.getWidth(), view.getHeight()); 16071 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 16072 } else { 16073 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 16074 } 16075 } 16076 16077 /** 16078 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 16079 * based on the dimensions it received from the 16080 * {@link #onProvideShadowMetrics(Point, Point)} callback. 16081 * 16082 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 16083 */ 16084 public void onDrawShadow(Canvas canvas) { 16085 final View view = mView.get(); 16086 if (view != null) { 16087 view.draw(canvas); 16088 } else { 16089 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 16090 } 16091 } 16092 } 16093 16094 /** 16095 * Starts a drag and drop operation. When your application calls this method, it passes a 16096 * {@link android.view.View.DragShadowBuilder} object to the system. The 16097 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 16098 * to get metrics for the drag shadow, and then calls the object's 16099 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 16100 * <p> 16101 * Once the system has the drag shadow, it begins the drag and drop operation by sending 16102 * drag events to all the View objects in your application that are currently visible. It does 16103 * this either by calling the View object's drag listener (an implementation of 16104 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 16105 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 16106 * Both are passed a {@link android.view.DragEvent} object that has a 16107 * {@link android.view.DragEvent#getAction()} value of 16108 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 16109 * </p> 16110 * <p> 16111 * Your application can invoke startDrag() on any attached View object. The View object does not 16112 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 16113 * be related to the View the user selected for dragging. 16114 * </p> 16115 * @param data A {@link android.content.ClipData} object pointing to the data to be 16116 * transferred by the drag and drop operation. 16117 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 16118 * drag shadow. 16119 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 16120 * drop operation. This Object is put into every DragEvent object sent by the system during the 16121 * current drag. 16122 * <p> 16123 * myLocalState is a lightweight mechanism for the sending information from the dragged View 16124 * to the target Views. For example, it can contain flags that differentiate between a 16125 * a copy operation and a move operation. 16126 * </p> 16127 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 16128 * so the parameter should be set to 0. 16129 * @return {@code true} if the method completes successfully, or 16130 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 16131 * do a drag, and so no drag operation is in progress. 16132 */ 16133 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 16134 Object myLocalState, int flags) { 16135 if (ViewDebug.DEBUG_DRAG) { 16136 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 16137 } 16138 boolean okay = false; 16139 16140 Point shadowSize = new Point(); 16141 Point shadowTouchPoint = new Point(); 16142 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 16143 16144 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 16145 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 16146 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 16147 } 16148 16149 if (ViewDebug.DEBUG_DRAG) { 16150 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 16151 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 16152 } 16153 Surface surface = new Surface(); 16154 try { 16155 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 16156 flags, shadowSize.x, shadowSize.y, surface); 16157 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 16158 + " surface=" + surface); 16159 if (token != null) { 16160 Canvas canvas = surface.lockCanvas(null); 16161 try { 16162 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 16163 shadowBuilder.onDrawShadow(canvas); 16164 } finally { 16165 surface.unlockCanvasAndPost(canvas); 16166 } 16167 16168 final ViewRootImpl root = getViewRootImpl(); 16169 16170 // Cache the local state object for delivery with DragEvents 16171 root.setLocalDragState(myLocalState); 16172 16173 // repurpose 'shadowSize' for the last touch point 16174 root.getLastTouchPoint(shadowSize); 16175 16176 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 16177 shadowSize.x, shadowSize.y, 16178 shadowTouchPoint.x, shadowTouchPoint.y, data); 16179 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 16180 16181 // Off and running! Release our local surface instance; the drag 16182 // shadow surface is now managed by the system process. 16183 surface.release(); 16184 } 16185 } catch (Exception e) { 16186 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 16187 surface.destroy(); 16188 } 16189 16190 return okay; 16191 } 16192 16193 /** 16194 * Handles drag events sent by the system following a call to 16195 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 16196 *<p> 16197 * When the system calls this method, it passes a 16198 * {@link android.view.DragEvent} object. A call to 16199 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 16200 * in DragEvent. The method uses these to determine what is happening in the drag and drop 16201 * operation. 16202 * @param event The {@link android.view.DragEvent} sent by the system. 16203 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 16204 * in DragEvent, indicating the type of drag event represented by this object. 16205 * @return {@code true} if the method was successful, otherwise {@code false}. 16206 * <p> 16207 * The method should return {@code true} in response to an action type of 16208 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 16209 * operation. 16210 * </p> 16211 * <p> 16212 * The method should also return {@code true} in response to an action type of 16213 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 16214 * {@code false} if it didn't. 16215 * </p> 16216 */ 16217 public boolean onDragEvent(DragEvent event) { 16218 return false; 16219 } 16220 16221 /** 16222 * Detects if this View is enabled and has a drag event listener. 16223 * If both are true, then it calls the drag event listener with the 16224 * {@link android.view.DragEvent} it received. If the drag event listener returns 16225 * {@code true}, then dispatchDragEvent() returns {@code true}. 16226 * <p> 16227 * For all other cases, the method calls the 16228 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 16229 * method and returns its result. 16230 * </p> 16231 * <p> 16232 * This ensures that a drag event is always consumed, even if the View does not have a drag 16233 * event listener. However, if the View has a listener and the listener returns true, then 16234 * onDragEvent() is not called. 16235 * </p> 16236 */ 16237 public boolean dispatchDragEvent(DragEvent event) { 16238 //noinspection SimplifiableIfStatement 16239 ListenerInfo li = mListenerInfo; 16240 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 16241 && li.mOnDragListener.onDrag(this, event)) { 16242 return true; 16243 } 16244 return onDragEvent(event); 16245 } 16246 16247 boolean canAcceptDrag() { 16248 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 16249 } 16250 16251 /** 16252 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 16253 * it is ever exposed at all. 16254 * @hide 16255 */ 16256 public void onCloseSystemDialogs(String reason) { 16257 } 16258 16259 /** 16260 * Given a Drawable whose bounds have been set to draw into this view, 16261 * update a Region being computed for 16262 * {@link #gatherTransparentRegion(android.graphics.Region)} so 16263 * that any non-transparent parts of the Drawable are removed from the 16264 * given transparent region. 16265 * 16266 * @param dr The Drawable whose transparency is to be applied to the region. 16267 * @param region A Region holding the current transparency information, 16268 * where any parts of the region that are set are considered to be 16269 * transparent. On return, this region will be modified to have the 16270 * transparency information reduced by the corresponding parts of the 16271 * Drawable that are not transparent. 16272 * {@hide} 16273 */ 16274 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 16275 if (DBG) { 16276 Log.i("View", "Getting transparent region for: " + this); 16277 } 16278 final Region r = dr.getTransparentRegion(); 16279 final Rect db = dr.getBounds(); 16280 final AttachInfo attachInfo = mAttachInfo; 16281 if (r != null && attachInfo != null) { 16282 final int w = getRight()-getLeft(); 16283 final int h = getBottom()-getTop(); 16284 if (db.left > 0) { 16285 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 16286 r.op(0, 0, db.left, h, Region.Op.UNION); 16287 } 16288 if (db.right < w) { 16289 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 16290 r.op(db.right, 0, w, h, Region.Op.UNION); 16291 } 16292 if (db.top > 0) { 16293 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 16294 r.op(0, 0, w, db.top, Region.Op.UNION); 16295 } 16296 if (db.bottom < h) { 16297 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 16298 r.op(0, db.bottom, w, h, Region.Op.UNION); 16299 } 16300 final int[] location = attachInfo.mTransparentLocation; 16301 getLocationInWindow(location); 16302 r.translate(location[0], location[1]); 16303 region.op(r, Region.Op.INTERSECT); 16304 } else { 16305 region.op(db, Region.Op.DIFFERENCE); 16306 } 16307 } 16308 16309 private void checkForLongClick(int delayOffset) { 16310 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 16311 mHasPerformedLongPress = false; 16312 16313 if (mPendingCheckForLongPress == null) { 16314 mPendingCheckForLongPress = new CheckForLongPress(); 16315 } 16316 mPendingCheckForLongPress.rememberWindowAttachCount(); 16317 postDelayed(mPendingCheckForLongPress, 16318 ViewConfiguration.getLongPressTimeout() - delayOffset); 16319 } 16320 } 16321 16322 /** 16323 * Inflate a view from an XML resource. This convenience method wraps the {@link 16324 * LayoutInflater} class, which provides a full range of options for view inflation. 16325 * 16326 * @param context The Context object for your activity or application. 16327 * @param resource The resource ID to inflate 16328 * @param root A view group that will be the parent. Used to properly inflate the 16329 * layout_* parameters. 16330 * @see LayoutInflater 16331 */ 16332 public static View inflate(Context context, int resource, ViewGroup root) { 16333 LayoutInflater factory = LayoutInflater.from(context); 16334 return factory.inflate(resource, root); 16335 } 16336 16337 /** 16338 * Scroll the view with standard behavior for scrolling beyond the normal 16339 * content boundaries. Views that call this method should override 16340 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 16341 * results of an over-scroll operation. 16342 * 16343 * Views can use this method to handle any touch or fling-based scrolling. 16344 * 16345 * @param deltaX Change in X in pixels 16346 * @param deltaY Change in Y in pixels 16347 * @param scrollX Current X scroll value in pixels before applying deltaX 16348 * @param scrollY Current Y scroll value in pixels before applying deltaY 16349 * @param scrollRangeX Maximum content scroll range along the X axis 16350 * @param scrollRangeY Maximum content scroll range along the Y axis 16351 * @param maxOverScrollX Number of pixels to overscroll by in either direction 16352 * along the X axis. 16353 * @param maxOverScrollY Number of pixels to overscroll by in either direction 16354 * along the Y axis. 16355 * @param isTouchEvent true if this scroll operation is the result of a touch event. 16356 * @return true if scrolling was clamped to an over-scroll boundary along either 16357 * axis, false otherwise. 16358 */ 16359 @SuppressWarnings({"UnusedParameters"}) 16360 protected boolean overScrollBy(int deltaX, int deltaY, 16361 int scrollX, int scrollY, 16362 int scrollRangeX, int scrollRangeY, 16363 int maxOverScrollX, int maxOverScrollY, 16364 boolean isTouchEvent) { 16365 final int overScrollMode = mOverScrollMode; 16366 final boolean canScrollHorizontal = 16367 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 16368 final boolean canScrollVertical = 16369 computeVerticalScrollRange() > computeVerticalScrollExtent(); 16370 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 16371 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 16372 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 16373 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 16374 16375 int newScrollX = scrollX + deltaX; 16376 if (!overScrollHorizontal) { 16377 maxOverScrollX = 0; 16378 } 16379 16380 int newScrollY = scrollY + deltaY; 16381 if (!overScrollVertical) { 16382 maxOverScrollY = 0; 16383 } 16384 16385 // Clamp values if at the limits and record 16386 final int left = -maxOverScrollX; 16387 final int right = maxOverScrollX + scrollRangeX; 16388 final int top = -maxOverScrollY; 16389 final int bottom = maxOverScrollY + scrollRangeY; 16390 16391 boolean clampedX = false; 16392 if (newScrollX > right) { 16393 newScrollX = right; 16394 clampedX = true; 16395 } else if (newScrollX < left) { 16396 newScrollX = left; 16397 clampedX = true; 16398 } 16399 16400 boolean clampedY = false; 16401 if (newScrollY > bottom) { 16402 newScrollY = bottom; 16403 clampedY = true; 16404 } else if (newScrollY < top) { 16405 newScrollY = top; 16406 clampedY = true; 16407 } 16408 16409 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 16410 16411 return clampedX || clampedY; 16412 } 16413 16414 /** 16415 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 16416 * respond to the results of an over-scroll operation. 16417 * 16418 * @param scrollX New X scroll value in pixels 16419 * @param scrollY New Y scroll value in pixels 16420 * @param clampedX True if scrollX was clamped to an over-scroll boundary 16421 * @param clampedY True if scrollY was clamped to an over-scroll boundary 16422 */ 16423 protected void onOverScrolled(int scrollX, int scrollY, 16424 boolean clampedX, boolean clampedY) { 16425 // Intentionally empty. 16426 } 16427 16428 /** 16429 * Returns the over-scroll mode for this view. The result will be 16430 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16431 * (allow over-scrolling only if the view content is larger than the container), 16432 * or {@link #OVER_SCROLL_NEVER}. 16433 * 16434 * @return This view's over-scroll mode. 16435 */ 16436 public int getOverScrollMode() { 16437 return mOverScrollMode; 16438 } 16439 16440 /** 16441 * Set the over-scroll mode for this view. Valid over-scroll modes are 16442 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16443 * (allow over-scrolling only if the view content is larger than the container), 16444 * or {@link #OVER_SCROLL_NEVER}. 16445 * 16446 * Setting the over-scroll mode of a view will have an effect only if the 16447 * view is capable of scrolling. 16448 * 16449 * @param overScrollMode The new over-scroll mode for this view. 16450 */ 16451 public void setOverScrollMode(int overScrollMode) { 16452 if (overScrollMode != OVER_SCROLL_ALWAYS && 16453 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 16454 overScrollMode != OVER_SCROLL_NEVER) { 16455 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 16456 } 16457 mOverScrollMode = overScrollMode; 16458 } 16459 16460 /** 16461 * Gets a scale factor that determines the distance the view should scroll 16462 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 16463 * @return The vertical scroll scale factor. 16464 * @hide 16465 */ 16466 protected float getVerticalScrollFactor() { 16467 if (mVerticalScrollFactor == 0) { 16468 TypedValue outValue = new TypedValue(); 16469 if (!mContext.getTheme().resolveAttribute( 16470 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 16471 throw new IllegalStateException( 16472 "Expected theme to define listPreferredItemHeight."); 16473 } 16474 mVerticalScrollFactor = outValue.getDimension( 16475 mContext.getResources().getDisplayMetrics()); 16476 } 16477 return mVerticalScrollFactor; 16478 } 16479 16480 /** 16481 * Gets a scale factor that determines the distance the view should scroll 16482 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 16483 * @return The horizontal scroll scale factor. 16484 * @hide 16485 */ 16486 protected float getHorizontalScrollFactor() { 16487 // TODO: Should use something else. 16488 return getVerticalScrollFactor(); 16489 } 16490 16491 /** 16492 * Return the value specifying the text direction or policy that was set with 16493 * {@link #setTextDirection(int)}. 16494 * 16495 * @return the defined text direction. It can be one of: 16496 * 16497 * {@link #TEXT_DIRECTION_INHERIT}, 16498 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16499 * {@link #TEXT_DIRECTION_ANY_RTL}, 16500 * {@link #TEXT_DIRECTION_LTR}, 16501 * {@link #TEXT_DIRECTION_RTL}, 16502 * {@link #TEXT_DIRECTION_LOCALE} 16503 */ 16504 @ViewDebug.ExportedProperty(category = "text", mapping = { 16505 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 16506 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 16507 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 16508 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 16509 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 16510 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 16511 }) 16512 public int getTextDirection() { 16513 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 16514 } 16515 16516 /** 16517 * Set the text direction. 16518 * 16519 * @param textDirection the direction to set. Should be one of: 16520 * 16521 * {@link #TEXT_DIRECTION_INHERIT}, 16522 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16523 * {@link #TEXT_DIRECTION_ANY_RTL}, 16524 * {@link #TEXT_DIRECTION_LTR}, 16525 * {@link #TEXT_DIRECTION_RTL}, 16526 * {@link #TEXT_DIRECTION_LOCALE} 16527 */ 16528 public void setTextDirection(int textDirection) { 16529 if (getTextDirection() != textDirection) { 16530 // Reset the current text direction and the resolved one 16531 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 16532 resetResolvedTextDirection(); 16533 // Set the new text direction 16534 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 16535 // Refresh 16536 requestLayout(); 16537 invalidate(true); 16538 } 16539 } 16540 16541 /** 16542 * Return the resolved text direction. 16543 * 16544 * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches 16545 * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds 16546 * up the parent chain of the view. if there is no parent, then it will return the default 16547 * {@link #TEXT_DIRECTION_FIRST_STRONG}. 16548 * 16549 * @return the resolved text direction. Returns one of: 16550 * 16551 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16552 * {@link #TEXT_DIRECTION_ANY_RTL}, 16553 * {@link #TEXT_DIRECTION_LTR}, 16554 * {@link #TEXT_DIRECTION_RTL}, 16555 * {@link #TEXT_DIRECTION_LOCALE} 16556 */ 16557 public int getResolvedTextDirection() { 16558 // The text direction will be resolved only if needed 16559 if ((mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) != PFLAG2_TEXT_DIRECTION_RESOLVED) { 16560 resolveTextDirection(); 16561 } 16562 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 16563 } 16564 16565 /** 16566 * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when 16567 * resolution is done. 16568 */ 16569 public void resolveTextDirection() { 16570 // Reset any previous text direction resolution 16571 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 16572 16573 if (hasRtlSupport()) { 16574 // Set resolved text direction flag depending on text direction flag 16575 final int textDirection = getTextDirection(); 16576 switch(textDirection) { 16577 case TEXT_DIRECTION_INHERIT: 16578 if (canResolveTextDirection()) { 16579 ViewGroup viewGroup = ((ViewGroup) mParent); 16580 16581 // Set current resolved direction to the same value as the parent's one 16582 final int parentResolvedDirection = viewGroup.getResolvedTextDirection(); 16583 switch (parentResolvedDirection) { 16584 case TEXT_DIRECTION_FIRST_STRONG: 16585 case TEXT_DIRECTION_ANY_RTL: 16586 case TEXT_DIRECTION_LTR: 16587 case TEXT_DIRECTION_RTL: 16588 case TEXT_DIRECTION_LOCALE: 16589 mPrivateFlags2 |= 16590 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 16591 break; 16592 default: 16593 // Default resolved direction is "first strong" heuristic 16594 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16595 } 16596 } else { 16597 // We cannot do the resolution if there is no parent, so use the default one 16598 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16599 } 16600 break; 16601 case TEXT_DIRECTION_FIRST_STRONG: 16602 case TEXT_DIRECTION_ANY_RTL: 16603 case TEXT_DIRECTION_LTR: 16604 case TEXT_DIRECTION_RTL: 16605 case TEXT_DIRECTION_LOCALE: 16606 // Resolved direction is the same as text direction 16607 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 16608 break; 16609 default: 16610 // Default resolved direction is "first strong" heuristic 16611 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16612 } 16613 } else { 16614 // Default resolved direction is "first strong" heuristic 16615 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16616 } 16617 16618 // Set to resolved 16619 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 16620 onResolvedTextDirectionChanged(); 16621 } 16622 16623 /** 16624 * Called when text direction has been resolved. Subclasses that care about text direction 16625 * resolution should override this method. 16626 * 16627 * The default implementation does nothing. 16628 */ 16629 public void onResolvedTextDirectionChanged() { 16630 } 16631 16632 /** 16633 * Check if text direction resolution can be done. 16634 * 16635 * @return true if text direction resolution can be done otherwise return false. 16636 */ 16637 public boolean canResolveTextDirection() { 16638 switch (getTextDirection()) { 16639 case TEXT_DIRECTION_INHERIT: 16640 return (mParent != null) && (mParent instanceof ViewGroup); 16641 default: 16642 return true; 16643 } 16644 } 16645 16646 /** 16647 * Reset resolved text direction. Text direction can be resolved with a call to 16648 * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when 16649 * reset is done. 16650 */ 16651 public void resetResolvedTextDirection() { 16652 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 16653 onResolvedTextDirectionReset(); 16654 } 16655 16656 /** 16657 * Called when text direction is reset. Subclasses that care about text direction reset should 16658 * override this method and do a reset of the text direction of their children. The default 16659 * implementation does nothing. 16660 */ 16661 public void onResolvedTextDirectionReset() { 16662 } 16663 16664 /** 16665 * Return the value specifying the text alignment or policy that was set with 16666 * {@link #setTextAlignment(int)}. 16667 * 16668 * @return the defined text alignment. It can be one of: 16669 * 16670 * {@link #TEXT_ALIGNMENT_INHERIT}, 16671 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16672 * {@link #TEXT_ALIGNMENT_CENTER}, 16673 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16674 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16675 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16676 * {@link #TEXT_ALIGNMENT_VIEW_END} 16677 */ 16678 @ViewDebug.ExportedProperty(category = "text", mapping = { 16679 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 16680 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 16681 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 16682 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 16683 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 16684 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 16685 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 16686 }) 16687 public int getTextAlignment() { 16688 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 16689 } 16690 16691 /** 16692 * Set the text alignment. 16693 * 16694 * @param textAlignment The text alignment to set. Should be one of 16695 * 16696 * {@link #TEXT_ALIGNMENT_INHERIT}, 16697 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16698 * {@link #TEXT_ALIGNMENT_CENTER}, 16699 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16700 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16701 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16702 * {@link #TEXT_ALIGNMENT_VIEW_END} 16703 * 16704 * @attr ref android.R.styleable#View_textAlignment 16705 */ 16706 public void setTextAlignment(int textAlignment) { 16707 if (textAlignment != getTextAlignment()) { 16708 // Reset the current and resolved text alignment 16709 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 16710 resetResolvedTextAlignment(); 16711 // Set the new text alignment 16712 mPrivateFlags2 |= ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 16713 // Refresh 16714 requestLayout(); 16715 invalidate(true); 16716 } 16717 } 16718 16719 /** 16720 * Return the resolved text alignment. 16721 * 16722 * The resolved text alignment. This needs resolution if the value is 16723 * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)} if it is 16724 * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view. 16725 * 16726 * @return the resolved text alignment. Returns one of: 16727 * 16728 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16729 * {@link #TEXT_ALIGNMENT_CENTER}, 16730 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16731 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16732 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16733 * {@link #TEXT_ALIGNMENT_VIEW_END} 16734 */ 16735 @ViewDebug.ExportedProperty(category = "text", mapping = { 16736 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 16737 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 16738 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 16739 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 16740 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 16741 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 16742 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 16743 }) 16744 public int getResolvedTextAlignment() { 16745 // If text alignment is not resolved, then resolve it 16746 if ((mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) != PFLAG2_TEXT_ALIGNMENT_RESOLVED) { 16747 resolveTextAlignment(); 16748 } 16749 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 16750 } 16751 16752 /** 16753 * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when 16754 * resolution is done. 16755 */ 16756 public void resolveTextAlignment() { 16757 // Reset any previous text alignment resolution 16758 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 16759 16760 if (hasRtlSupport()) { 16761 // Set resolved text alignment flag depending on text alignment flag 16762 final int textAlignment = getTextAlignment(); 16763 switch (textAlignment) { 16764 case TEXT_ALIGNMENT_INHERIT: 16765 // Check if we can resolve the text alignment 16766 if (canResolveLayoutDirection() && mParent instanceof View) { 16767 View view = (View) mParent; 16768 16769 final int parentResolvedTextAlignment = view.getResolvedTextAlignment(); 16770 switch (parentResolvedTextAlignment) { 16771 case TEXT_ALIGNMENT_GRAVITY: 16772 case TEXT_ALIGNMENT_TEXT_START: 16773 case TEXT_ALIGNMENT_TEXT_END: 16774 case TEXT_ALIGNMENT_CENTER: 16775 case TEXT_ALIGNMENT_VIEW_START: 16776 case TEXT_ALIGNMENT_VIEW_END: 16777 // Resolved text alignment is the same as the parent resolved 16778 // text alignment 16779 mPrivateFlags2 |= 16780 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 16781 break; 16782 default: 16783 // Use default resolved text alignment 16784 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16785 } 16786 } 16787 else { 16788 // We cannot do the resolution if there is no parent so use the default 16789 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16790 } 16791 break; 16792 case TEXT_ALIGNMENT_GRAVITY: 16793 case TEXT_ALIGNMENT_TEXT_START: 16794 case TEXT_ALIGNMENT_TEXT_END: 16795 case TEXT_ALIGNMENT_CENTER: 16796 case TEXT_ALIGNMENT_VIEW_START: 16797 case TEXT_ALIGNMENT_VIEW_END: 16798 // Resolved text alignment is the same as text alignment 16799 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 16800 break; 16801 default: 16802 // Use default resolved text alignment 16803 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16804 } 16805 } else { 16806 // Use default resolved text alignment 16807 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16808 } 16809 16810 // Set the resolved 16811 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 16812 onResolvedTextAlignmentChanged(); 16813 } 16814 16815 /** 16816 * Check if text alignment resolution can be done. 16817 * 16818 * @return true if text alignment resolution can be done otherwise return false. 16819 */ 16820 public boolean canResolveTextAlignment() { 16821 switch (getTextAlignment()) { 16822 case TEXT_DIRECTION_INHERIT: 16823 return (mParent != null); 16824 default: 16825 return true; 16826 } 16827 } 16828 16829 /** 16830 * Called when text alignment has been resolved. Subclasses that care about text alignment 16831 * resolution should override this method. 16832 * 16833 * The default implementation does nothing. 16834 */ 16835 public void onResolvedTextAlignmentChanged() { 16836 } 16837 16838 /** 16839 * Reset resolved text alignment. Text alignment can be resolved with a call to 16840 * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when 16841 * reset is done. 16842 */ 16843 public void resetResolvedTextAlignment() { 16844 // Reset any previous text alignment resolution 16845 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 16846 onResolvedTextAlignmentReset(); 16847 } 16848 16849 /** 16850 * Called when text alignment is reset. Subclasses that care about text alignment reset should 16851 * override this method and do a reset of the text alignment of their children. The default 16852 * implementation does nothing. 16853 */ 16854 public void onResolvedTextAlignmentReset() { 16855 } 16856 16857 /** 16858 * Generate a value suitable for use in {@link #setId(int)}. 16859 * This value will not collide with ID values generated at build time by aapt for R.id. 16860 * 16861 * @return a generated ID value 16862 */ 16863 public static int generateViewId() { 16864 for (;;) { 16865 final int result = sNextGeneratedId.get(); 16866 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 16867 int newValue = result + 1; 16868 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 16869 if (sNextGeneratedId.compareAndSet(result, newValue)) { 16870 return result; 16871 } 16872 } 16873 } 16874 16875 // 16876 // Properties 16877 // 16878 /** 16879 * A Property wrapper around the <code>alpha</code> functionality handled by the 16880 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 16881 */ 16882 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 16883 @Override 16884 public void setValue(View object, float value) { 16885 object.setAlpha(value); 16886 } 16887 16888 @Override 16889 public Float get(View object) { 16890 return object.getAlpha(); 16891 } 16892 }; 16893 16894 /** 16895 * A Property wrapper around the <code>translationX</code> functionality handled by the 16896 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 16897 */ 16898 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 16899 @Override 16900 public void setValue(View object, float value) { 16901 object.setTranslationX(value); 16902 } 16903 16904 @Override 16905 public Float get(View object) { 16906 return object.getTranslationX(); 16907 } 16908 }; 16909 16910 /** 16911 * A Property wrapper around the <code>translationY</code> functionality handled by the 16912 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 16913 */ 16914 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 16915 @Override 16916 public void setValue(View object, float value) { 16917 object.setTranslationY(value); 16918 } 16919 16920 @Override 16921 public Float get(View object) { 16922 return object.getTranslationY(); 16923 } 16924 }; 16925 16926 /** 16927 * A Property wrapper around the <code>x</code> functionality handled by the 16928 * {@link View#setX(float)} and {@link View#getX()} methods. 16929 */ 16930 public static final Property<View, Float> X = new FloatProperty<View>("x") { 16931 @Override 16932 public void setValue(View object, float value) { 16933 object.setX(value); 16934 } 16935 16936 @Override 16937 public Float get(View object) { 16938 return object.getX(); 16939 } 16940 }; 16941 16942 /** 16943 * A Property wrapper around the <code>y</code> functionality handled by the 16944 * {@link View#setY(float)} and {@link View#getY()} methods. 16945 */ 16946 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 16947 @Override 16948 public void setValue(View object, float value) { 16949 object.setY(value); 16950 } 16951 16952 @Override 16953 public Float get(View object) { 16954 return object.getY(); 16955 } 16956 }; 16957 16958 /** 16959 * A Property wrapper around the <code>rotation</code> functionality handled by the 16960 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 16961 */ 16962 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 16963 @Override 16964 public void setValue(View object, float value) { 16965 object.setRotation(value); 16966 } 16967 16968 @Override 16969 public Float get(View object) { 16970 return object.getRotation(); 16971 } 16972 }; 16973 16974 /** 16975 * A Property wrapper around the <code>rotationX</code> functionality handled by the 16976 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 16977 */ 16978 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 16979 @Override 16980 public void setValue(View object, float value) { 16981 object.setRotationX(value); 16982 } 16983 16984 @Override 16985 public Float get(View object) { 16986 return object.getRotationX(); 16987 } 16988 }; 16989 16990 /** 16991 * A Property wrapper around the <code>rotationY</code> functionality handled by the 16992 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 16993 */ 16994 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 16995 @Override 16996 public void setValue(View object, float value) { 16997 object.setRotationY(value); 16998 } 16999 17000 @Override 17001 public Float get(View object) { 17002 return object.getRotationY(); 17003 } 17004 }; 17005 17006 /** 17007 * A Property wrapper around the <code>scaleX</code> functionality handled by the 17008 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 17009 */ 17010 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 17011 @Override 17012 public void setValue(View object, float value) { 17013 object.setScaleX(value); 17014 } 17015 17016 @Override 17017 public Float get(View object) { 17018 return object.getScaleX(); 17019 } 17020 }; 17021 17022 /** 17023 * A Property wrapper around the <code>scaleY</code> functionality handled by the 17024 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 17025 */ 17026 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 17027 @Override 17028 public void setValue(View object, float value) { 17029 object.setScaleY(value); 17030 } 17031 17032 @Override 17033 public Float get(View object) { 17034 return object.getScaleY(); 17035 } 17036 }; 17037 17038 /** 17039 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 17040 * Each MeasureSpec represents a requirement for either the width or the height. 17041 * A MeasureSpec is comprised of a size and a mode. There are three possible 17042 * modes: 17043 * <dl> 17044 * <dt>UNSPECIFIED</dt> 17045 * <dd> 17046 * The parent has not imposed any constraint on the child. It can be whatever size 17047 * it wants. 17048 * </dd> 17049 * 17050 * <dt>EXACTLY</dt> 17051 * <dd> 17052 * The parent has determined an exact size for the child. The child is going to be 17053 * given those bounds regardless of how big it wants to be. 17054 * </dd> 17055 * 17056 * <dt>AT_MOST</dt> 17057 * <dd> 17058 * The child can be as large as it wants up to the specified size. 17059 * </dd> 17060 * </dl> 17061 * 17062 * MeasureSpecs are implemented as ints to reduce object allocation. This class 17063 * is provided to pack and unpack the <size, mode> tuple into the int. 17064 */ 17065 public static class MeasureSpec { 17066 private static final int MODE_SHIFT = 30; 17067 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 17068 17069 /** 17070 * Measure specification mode: The parent has not imposed any constraint 17071 * on the child. It can be whatever size it wants. 17072 */ 17073 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 17074 17075 /** 17076 * Measure specification mode: The parent has determined an exact size 17077 * for the child. The child is going to be given those bounds regardless 17078 * of how big it wants to be. 17079 */ 17080 public static final int EXACTLY = 1 << MODE_SHIFT; 17081 17082 /** 17083 * Measure specification mode: The child can be as large as it wants up 17084 * to the specified size. 17085 */ 17086 public static final int AT_MOST = 2 << MODE_SHIFT; 17087 17088 /** 17089 * Creates a measure specification based on the supplied size and mode. 17090 * 17091 * The mode must always be one of the following: 17092 * <ul> 17093 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 17094 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 17095 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 17096 * </ul> 17097 * 17098 * @param size the size of the measure specification 17099 * @param mode the mode of the measure specification 17100 * @return the measure specification based on size and mode 17101 */ 17102 public static int makeMeasureSpec(int size, int mode) { 17103 return size + mode; 17104 } 17105 17106 /** 17107 * Extracts the mode from the supplied measure specification. 17108 * 17109 * @param measureSpec the measure specification to extract the mode from 17110 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 17111 * {@link android.view.View.MeasureSpec#AT_MOST} or 17112 * {@link android.view.View.MeasureSpec#EXACTLY} 17113 */ 17114 public static int getMode(int measureSpec) { 17115 return (measureSpec & MODE_MASK); 17116 } 17117 17118 /** 17119 * Extracts the size from the supplied measure specification. 17120 * 17121 * @param measureSpec the measure specification to extract the size from 17122 * @return the size in pixels defined in the supplied measure specification 17123 */ 17124 public static int getSize(int measureSpec) { 17125 return (measureSpec & ~MODE_MASK); 17126 } 17127 17128 /** 17129 * Returns a String representation of the specified measure 17130 * specification. 17131 * 17132 * @param measureSpec the measure specification to convert to a String 17133 * @return a String with the following format: "MeasureSpec: MODE SIZE" 17134 */ 17135 public static String toString(int measureSpec) { 17136 int mode = getMode(measureSpec); 17137 int size = getSize(measureSpec); 17138 17139 StringBuilder sb = new StringBuilder("MeasureSpec: "); 17140 17141 if (mode == UNSPECIFIED) 17142 sb.append("UNSPECIFIED "); 17143 else if (mode == EXACTLY) 17144 sb.append("EXACTLY "); 17145 else if (mode == AT_MOST) 17146 sb.append("AT_MOST "); 17147 else 17148 sb.append(mode).append(" "); 17149 17150 sb.append(size); 17151 return sb.toString(); 17152 } 17153 } 17154 17155 class CheckForLongPress implements Runnable { 17156 17157 private int mOriginalWindowAttachCount; 17158 17159 public void run() { 17160 if (isPressed() && (mParent != null) 17161 && mOriginalWindowAttachCount == mWindowAttachCount) { 17162 if (performLongClick()) { 17163 mHasPerformedLongPress = true; 17164 } 17165 } 17166 } 17167 17168 public void rememberWindowAttachCount() { 17169 mOriginalWindowAttachCount = mWindowAttachCount; 17170 } 17171 } 17172 17173 private final class CheckForTap implements Runnable { 17174 public void run() { 17175 mPrivateFlags &= ~PFLAG_PREPRESSED; 17176 setPressed(true); 17177 checkForLongClick(ViewConfiguration.getTapTimeout()); 17178 } 17179 } 17180 17181 private final class PerformClick implements Runnable { 17182 public void run() { 17183 performClick(); 17184 } 17185 } 17186 17187 /** @hide */ 17188 public void hackTurnOffWindowResizeAnim(boolean off) { 17189 mAttachInfo.mTurnOffWindowResizeAnim = off; 17190 } 17191 17192 /** 17193 * This method returns a ViewPropertyAnimator object, which can be used to animate 17194 * specific properties on this View. 17195 * 17196 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 17197 */ 17198 public ViewPropertyAnimator animate() { 17199 if (mAnimator == null) { 17200 mAnimator = new ViewPropertyAnimator(this); 17201 } 17202 return mAnimator; 17203 } 17204 17205 /** 17206 * Interface definition for a callback to be invoked when a hardware key event is 17207 * dispatched to this view. The callback will be invoked before the key event is 17208 * given to the view. This is only useful for hardware keyboards; a software input 17209 * method has no obligation to trigger this listener. 17210 */ 17211 public interface OnKeyListener { 17212 /** 17213 * Called when a hardware key is dispatched to a view. This allows listeners to 17214 * get a chance to respond before the target view. 17215 * <p>Key presses in software keyboards will generally NOT trigger this method, 17216 * although some may elect to do so in some situations. Do not assume a 17217 * software input method has to be key-based; even if it is, it may use key presses 17218 * in a different way than you expect, so there is no way to reliably catch soft 17219 * input key presses. 17220 * 17221 * @param v The view the key has been dispatched to. 17222 * @param keyCode The code for the physical key that was pressed 17223 * @param event The KeyEvent object containing full information about 17224 * the event. 17225 * @return True if the listener has consumed the event, false otherwise. 17226 */ 17227 boolean onKey(View v, int keyCode, KeyEvent event); 17228 } 17229 17230 /** 17231 * Interface definition for a callback to be invoked when a touch event is 17232 * dispatched to this view. The callback will be invoked before the touch 17233 * event is given to the view. 17234 */ 17235 public interface OnTouchListener { 17236 /** 17237 * Called when a touch event is dispatched to a view. This allows listeners to 17238 * get a chance to respond before the target view. 17239 * 17240 * @param v The view the touch event has been dispatched to. 17241 * @param event The MotionEvent object containing full information about 17242 * the event. 17243 * @return True if the listener has consumed the event, false otherwise. 17244 */ 17245 boolean onTouch(View v, MotionEvent event); 17246 } 17247 17248 /** 17249 * Interface definition for a callback to be invoked when a hover event is 17250 * dispatched to this view. The callback will be invoked before the hover 17251 * event is given to the view. 17252 */ 17253 public interface OnHoverListener { 17254 /** 17255 * Called when a hover event is dispatched to a view. This allows listeners to 17256 * get a chance to respond before the target view. 17257 * 17258 * @param v The view the hover event has been dispatched to. 17259 * @param event The MotionEvent object containing full information about 17260 * the event. 17261 * @return True if the listener has consumed the event, false otherwise. 17262 */ 17263 boolean onHover(View v, MotionEvent event); 17264 } 17265 17266 /** 17267 * Interface definition for a callback to be invoked when a generic motion event is 17268 * dispatched to this view. The callback will be invoked before the generic motion 17269 * event is given to the view. 17270 */ 17271 public interface OnGenericMotionListener { 17272 /** 17273 * Called when a generic motion event is dispatched to a view. This allows listeners to 17274 * get a chance to respond before the target view. 17275 * 17276 * @param v The view the generic motion event has been dispatched to. 17277 * @param event The MotionEvent object containing full information about 17278 * the event. 17279 * @return True if the listener has consumed the event, false otherwise. 17280 */ 17281 boolean onGenericMotion(View v, MotionEvent event); 17282 } 17283 17284 /** 17285 * Interface definition for a callback to be invoked when a view has been clicked and held. 17286 */ 17287 public interface OnLongClickListener { 17288 /** 17289 * Called when a view has been clicked and held. 17290 * 17291 * @param v The view that was clicked and held. 17292 * 17293 * @return true if the callback consumed the long click, false otherwise. 17294 */ 17295 boolean onLongClick(View v); 17296 } 17297 17298 /** 17299 * Interface definition for a callback to be invoked when a drag is being dispatched 17300 * to this view. The callback will be invoked before the hosting view's own 17301 * onDrag(event) method. If the listener wants to fall back to the hosting view's 17302 * onDrag(event) behavior, it should return 'false' from this callback. 17303 * 17304 * <div class="special reference"> 17305 * <h3>Developer Guides</h3> 17306 * <p>For a guide to implementing drag and drop features, read the 17307 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17308 * </div> 17309 */ 17310 public interface OnDragListener { 17311 /** 17312 * Called when a drag event is dispatched to a view. This allows listeners 17313 * to get a chance to override base View behavior. 17314 * 17315 * @param v The View that received the drag event. 17316 * @param event The {@link android.view.DragEvent} object for the drag event. 17317 * @return {@code true} if the drag event was handled successfully, or {@code false} 17318 * if the drag event was not handled. Note that {@code false} will trigger the View 17319 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 17320 */ 17321 boolean onDrag(View v, DragEvent event); 17322 } 17323 17324 /** 17325 * Interface definition for a callback to be invoked when the focus state of 17326 * a view changed. 17327 */ 17328 public interface OnFocusChangeListener { 17329 /** 17330 * Called when the focus state of a view has changed. 17331 * 17332 * @param v The view whose state has changed. 17333 * @param hasFocus The new focus state of v. 17334 */ 17335 void onFocusChange(View v, boolean hasFocus); 17336 } 17337 17338 /** 17339 * Interface definition for a callback to be invoked when a view is clicked. 17340 */ 17341 public interface OnClickListener { 17342 /** 17343 * Called when a view has been clicked. 17344 * 17345 * @param v The view that was clicked. 17346 */ 17347 void onClick(View v); 17348 } 17349 17350 /** 17351 * Interface definition for a callback to be invoked when the context menu 17352 * for this view is being built. 17353 */ 17354 public interface OnCreateContextMenuListener { 17355 /** 17356 * Called when the context menu for this view is being built. It is not 17357 * safe to hold onto the menu after this method returns. 17358 * 17359 * @param menu The context menu that is being built 17360 * @param v The view for which the context menu is being built 17361 * @param menuInfo Extra information about the item for which the 17362 * context menu should be shown. This information will vary 17363 * depending on the class of v. 17364 */ 17365 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 17366 } 17367 17368 /** 17369 * Interface definition for a callback to be invoked when the status bar changes 17370 * visibility. This reports <strong>global</strong> changes to the system UI 17371 * state, not what the application is requesting. 17372 * 17373 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 17374 */ 17375 public interface OnSystemUiVisibilityChangeListener { 17376 /** 17377 * Called when the status bar changes visibility because of a call to 17378 * {@link View#setSystemUiVisibility(int)}. 17379 * 17380 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17381 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 17382 * This tells you the <strong>global</strong> state of these UI visibility 17383 * flags, not what your app is currently applying. 17384 */ 17385 public void onSystemUiVisibilityChange(int visibility); 17386 } 17387 17388 /** 17389 * Interface definition for a callback to be invoked when this view is attached 17390 * or detached from its window. 17391 */ 17392 public interface OnAttachStateChangeListener { 17393 /** 17394 * Called when the view is attached to a window. 17395 * @param v The view that was attached 17396 */ 17397 public void onViewAttachedToWindow(View v); 17398 /** 17399 * Called when the view is detached from a window. 17400 * @param v The view that was detached 17401 */ 17402 public void onViewDetachedFromWindow(View v); 17403 } 17404 17405 private final class UnsetPressedState implements Runnable { 17406 public void run() { 17407 setPressed(false); 17408 } 17409 } 17410 17411 /** 17412 * Base class for derived classes that want to save and restore their own 17413 * state in {@link android.view.View#onSaveInstanceState()}. 17414 */ 17415 public static class BaseSavedState extends AbsSavedState { 17416 /** 17417 * Constructor used when reading from a parcel. Reads the state of the superclass. 17418 * 17419 * @param source 17420 */ 17421 public BaseSavedState(Parcel source) { 17422 super(source); 17423 } 17424 17425 /** 17426 * Constructor called by derived classes when creating their SavedState objects 17427 * 17428 * @param superState The state of the superclass of this view 17429 */ 17430 public BaseSavedState(Parcelable superState) { 17431 super(superState); 17432 } 17433 17434 public static final Parcelable.Creator<BaseSavedState> CREATOR = 17435 new Parcelable.Creator<BaseSavedState>() { 17436 public BaseSavedState createFromParcel(Parcel in) { 17437 return new BaseSavedState(in); 17438 } 17439 17440 public BaseSavedState[] newArray(int size) { 17441 return new BaseSavedState[size]; 17442 } 17443 }; 17444 } 17445 17446 /** 17447 * A set of information given to a view when it is attached to its parent 17448 * window. 17449 */ 17450 static class AttachInfo { 17451 interface Callbacks { 17452 void playSoundEffect(int effectId); 17453 boolean performHapticFeedback(int effectId, boolean always); 17454 } 17455 17456 /** 17457 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 17458 * to a Handler. This class contains the target (View) to invalidate and 17459 * the coordinates of the dirty rectangle. 17460 * 17461 * For performance purposes, this class also implements a pool of up to 17462 * POOL_LIMIT objects that get reused. This reduces memory allocations 17463 * whenever possible. 17464 */ 17465 static class InvalidateInfo implements Poolable<InvalidateInfo> { 17466 private static final int POOL_LIMIT = 10; 17467 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 17468 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 17469 public InvalidateInfo newInstance() { 17470 return new InvalidateInfo(); 17471 } 17472 17473 public void onAcquired(InvalidateInfo element) { 17474 } 17475 17476 public void onReleased(InvalidateInfo element) { 17477 element.target = null; 17478 } 17479 }, POOL_LIMIT) 17480 ); 17481 17482 private InvalidateInfo mNext; 17483 private boolean mIsPooled; 17484 17485 View target; 17486 17487 int left; 17488 int top; 17489 int right; 17490 int bottom; 17491 17492 public void setNextPoolable(InvalidateInfo element) { 17493 mNext = element; 17494 } 17495 17496 public InvalidateInfo getNextPoolable() { 17497 return mNext; 17498 } 17499 17500 static InvalidateInfo acquire() { 17501 return sPool.acquire(); 17502 } 17503 17504 void release() { 17505 sPool.release(this); 17506 } 17507 17508 public boolean isPooled() { 17509 return mIsPooled; 17510 } 17511 17512 public void setPooled(boolean isPooled) { 17513 mIsPooled = isPooled; 17514 } 17515 } 17516 17517 final IWindowSession mSession; 17518 17519 final IWindow mWindow; 17520 17521 final IBinder mWindowToken; 17522 17523 final Display mDisplay; 17524 17525 final Callbacks mRootCallbacks; 17526 17527 HardwareCanvas mHardwareCanvas; 17528 17529 /** 17530 * The top view of the hierarchy. 17531 */ 17532 View mRootView; 17533 17534 IBinder mPanelParentWindowToken; 17535 Surface mSurface; 17536 17537 boolean mHardwareAccelerated; 17538 boolean mHardwareAccelerationRequested; 17539 HardwareRenderer mHardwareRenderer; 17540 17541 boolean mScreenOn; 17542 17543 /** 17544 * Scale factor used by the compatibility mode 17545 */ 17546 float mApplicationScale; 17547 17548 /** 17549 * Indicates whether the application is in compatibility mode 17550 */ 17551 boolean mScalingRequired; 17552 17553 /** 17554 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 17555 */ 17556 boolean mTurnOffWindowResizeAnim; 17557 17558 /** 17559 * Left position of this view's window 17560 */ 17561 int mWindowLeft; 17562 17563 /** 17564 * Top position of this view's window 17565 */ 17566 int mWindowTop; 17567 17568 /** 17569 * Indicates whether views need to use 32-bit drawing caches 17570 */ 17571 boolean mUse32BitDrawingCache; 17572 17573 /** 17574 * For windows that are full-screen but using insets to layout inside 17575 * of the screen decorations, these are the current insets for the 17576 * content of the window. 17577 */ 17578 final Rect mContentInsets = new Rect(); 17579 17580 /** 17581 * For windows that are full-screen but using insets to layout inside 17582 * of the screen decorations, these are the current insets for the 17583 * actual visible parts of the window. 17584 */ 17585 final Rect mVisibleInsets = new Rect(); 17586 17587 /** 17588 * The internal insets given by this window. This value is 17589 * supplied by the client (through 17590 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 17591 * be given to the window manager when changed to be used in laying 17592 * out windows behind it. 17593 */ 17594 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 17595 = new ViewTreeObserver.InternalInsetsInfo(); 17596 17597 /** 17598 * All views in the window's hierarchy that serve as scroll containers, 17599 * used to determine if the window can be resized or must be panned 17600 * to adjust for a soft input area. 17601 */ 17602 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 17603 17604 final KeyEvent.DispatcherState mKeyDispatchState 17605 = new KeyEvent.DispatcherState(); 17606 17607 /** 17608 * Indicates whether the view's window currently has the focus. 17609 */ 17610 boolean mHasWindowFocus; 17611 17612 /** 17613 * The current visibility of the window. 17614 */ 17615 int mWindowVisibility; 17616 17617 /** 17618 * Indicates the time at which drawing started to occur. 17619 */ 17620 long mDrawingTime; 17621 17622 /** 17623 * Indicates whether or not ignoring the DIRTY_MASK flags. 17624 */ 17625 boolean mIgnoreDirtyState; 17626 17627 /** 17628 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 17629 * to avoid clearing that flag prematurely. 17630 */ 17631 boolean mSetIgnoreDirtyState = false; 17632 17633 /** 17634 * Indicates whether the view's window is currently in touch mode. 17635 */ 17636 boolean mInTouchMode; 17637 17638 /** 17639 * Indicates that ViewAncestor should trigger a global layout change 17640 * the next time it performs a traversal 17641 */ 17642 boolean mRecomputeGlobalAttributes; 17643 17644 /** 17645 * Always report new attributes at next traversal. 17646 */ 17647 boolean mForceReportNewAttributes; 17648 17649 /** 17650 * Set during a traveral if any views want to keep the screen on. 17651 */ 17652 boolean mKeepScreenOn; 17653 17654 /** 17655 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 17656 */ 17657 int mSystemUiVisibility; 17658 17659 /** 17660 * Hack to force certain system UI visibility flags to be cleared. 17661 */ 17662 int mDisabledSystemUiVisibility; 17663 17664 /** 17665 * Last global system UI visibility reported by the window manager. 17666 */ 17667 int mGlobalSystemUiVisibility; 17668 17669 /** 17670 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 17671 * attached. 17672 */ 17673 boolean mHasSystemUiListeners; 17674 17675 /** 17676 * Set if the visibility of any views has changed. 17677 */ 17678 boolean mViewVisibilityChanged; 17679 17680 /** 17681 * Set to true if a view has been scrolled. 17682 */ 17683 boolean mViewScrollChanged; 17684 17685 /** 17686 * Global to the view hierarchy used as a temporary for dealing with 17687 * x/y points in the transparent region computations. 17688 */ 17689 final int[] mTransparentLocation = new int[2]; 17690 17691 /** 17692 * Global to the view hierarchy used as a temporary for dealing with 17693 * x/y points in the ViewGroup.invalidateChild implementation. 17694 */ 17695 final int[] mInvalidateChildLocation = new int[2]; 17696 17697 17698 /** 17699 * Global to the view hierarchy used as a temporary for dealing with 17700 * x/y location when view is transformed. 17701 */ 17702 final float[] mTmpTransformLocation = new float[2]; 17703 17704 /** 17705 * The view tree observer used to dispatch global events like 17706 * layout, pre-draw, touch mode change, etc. 17707 */ 17708 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 17709 17710 /** 17711 * A Canvas used by the view hierarchy to perform bitmap caching. 17712 */ 17713 Canvas mCanvas; 17714 17715 /** 17716 * The view root impl. 17717 */ 17718 final ViewRootImpl mViewRootImpl; 17719 17720 /** 17721 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 17722 * handler can be used to pump events in the UI events queue. 17723 */ 17724 final Handler mHandler; 17725 17726 /** 17727 * Temporary for use in computing invalidate rectangles while 17728 * calling up the hierarchy. 17729 */ 17730 final Rect mTmpInvalRect = new Rect(); 17731 17732 /** 17733 * Temporary for use in computing hit areas with transformed views 17734 */ 17735 final RectF mTmpTransformRect = new RectF(); 17736 17737 /** 17738 * Temporary for use in transforming invalidation rect 17739 */ 17740 final Matrix mTmpMatrix = new Matrix(); 17741 17742 /** 17743 * Temporary for use in transforming invalidation rect 17744 */ 17745 final Transformation mTmpTransformation = new Transformation(); 17746 17747 /** 17748 * Temporary list for use in collecting focusable descendents of a view. 17749 */ 17750 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 17751 17752 /** 17753 * The id of the window for accessibility purposes. 17754 */ 17755 int mAccessibilityWindowId = View.NO_ID; 17756 17757 /** 17758 * Whether to ingore not exposed for accessibility Views when 17759 * reporting the view tree to accessibility services. 17760 */ 17761 boolean mIncludeNotImportantViews; 17762 17763 /** 17764 * The drawable for highlighting accessibility focus. 17765 */ 17766 Drawable mAccessibilityFocusDrawable; 17767 17768 /** 17769 * Show where the margins, bounds and layout bounds are for each view. 17770 */ 17771 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 17772 17773 /** 17774 * Point used to compute visible regions. 17775 */ 17776 final Point mPoint = new Point(); 17777 17778 /** 17779 * Creates a new set of attachment information with the specified 17780 * events handler and thread. 17781 * 17782 * @param handler the events handler the view must use 17783 */ 17784 AttachInfo(IWindowSession session, IWindow window, Display display, 17785 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 17786 mSession = session; 17787 mWindow = window; 17788 mWindowToken = window.asBinder(); 17789 mDisplay = display; 17790 mViewRootImpl = viewRootImpl; 17791 mHandler = handler; 17792 mRootCallbacks = effectPlayer; 17793 } 17794 } 17795 17796 /** 17797 * <p>ScrollabilityCache holds various fields used by a View when scrolling 17798 * is supported. This avoids keeping too many unused fields in most 17799 * instances of View.</p> 17800 */ 17801 private static class ScrollabilityCache implements Runnable { 17802 17803 /** 17804 * Scrollbars are not visible 17805 */ 17806 public static final int OFF = 0; 17807 17808 /** 17809 * Scrollbars are visible 17810 */ 17811 public static final int ON = 1; 17812 17813 /** 17814 * Scrollbars are fading away 17815 */ 17816 public static final int FADING = 2; 17817 17818 public boolean fadeScrollBars; 17819 17820 public int fadingEdgeLength; 17821 public int scrollBarDefaultDelayBeforeFade; 17822 public int scrollBarFadeDuration; 17823 17824 public int scrollBarSize; 17825 public ScrollBarDrawable scrollBar; 17826 public float[] interpolatorValues; 17827 public View host; 17828 17829 public final Paint paint; 17830 public final Matrix matrix; 17831 public Shader shader; 17832 17833 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 17834 17835 private static final float[] OPAQUE = { 255 }; 17836 private static final float[] TRANSPARENT = { 0.0f }; 17837 17838 /** 17839 * When fading should start. This time moves into the future every time 17840 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 17841 */ 17842 public long fadeStartTime; 17843 17844 17845 /** 17846 * The current state of the scrollbars: ON, OFF, or FADING 17847 */ 17848 public int state = OFF; 17849 17850 private int mLastColor; 17851 17852 public ScrollabilityCache(ViewConfiguration configuration, View host) { 17853 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 17854 scrollBarSize = configuration.getScaledScrollBarSize(); 17855 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 17856 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 17857 17858 paint = new Paint(); 17859 matrix = new Matrix(); 17860 // use use a height of 1, and then wack the matrix each time we 17861 // actually use it. 17862 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 17863 paint.setShader(shader); 17864 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 17865 17866 this.host = host; 17867 } 17868 17869 public void setFadeColor(int color) { 17870 if (color != mLastColor) { 17871 mLastColor = color; 17872 17873 if (color != 0) { 17874 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 17875 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 17876 paint.setShader(shader); 17877 // Restore the default transfer mode (src_over) 17878 paint.setXfermode(null); 17879 } else { 17880 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 17881 paint.setShader(shader); 17882 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 17883 } 17884 } 17885 } 17886 17887 public void run() { 17888 long now = AnimationUtils.currentAnimationTimeMillis(); 17889 if (now >= fadeStartTime) { 17890 17891 // the animation fades the scrollbars out by changing 17892 // the opacity (alpha) from fully opaque to fully 17893 // transparent 17894 int nextFrame = (int) now; 17895 int framesCount = 0; 17896 17897 Interpolator interpolator = scrollBarInterpolator; 17898 17899 // Start opaque 17900 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 17901 17902 // End transparent 17903 nextFrame += scrollBarFadeDuration; 17904 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 17905 17906 state = FADING; 17907 17908 // Kick off the fade animation 17909 host.invalidate(true); 17910 } 17911 } 17912 } 17913 17914 /** 17915 * Resuable callback for sending 17916 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 17917 */ 17918 private class SendViewScrolledAccessibilityEvent implements Runnable { 17919 public volatile boolean mIsPending; 17920 17921 public void run() { 17922 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 17923 mIsPending = false; 17924 } 17925 } 17926 17927 /** 17928 * <p> 17929 * This class represents a delegate that can be registered in a {@link View} 17930 * to enhance accessibility support via composition rather via inheritance. 17931 * It is specifically targeted to widget developers that extend basic View 17932 * classes i.e. classes in package android.view, that would like their 17933 * applications to be backwards compatible. 17934 * </p> 17935 * <div class="special reference"> 17936 * <h3>Developer Guides</h3> 17937 * <p>For more information about making applications accessible, read the 17938 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 17939 * developer guide.</p> 17940 * </div> 17941 * <p> 17942 * A scenario in which a developer would like to use an accessibility delegate 17943 * is overriding a method introduced in a later API version then the minimal API 17944 * version supported by the application. For example, the method 17945 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 17946 * in API version 4 when the accessibility APIs were first introduced. If a 17947 * developer would like his application to run on API version 4 devices (assuming 17948 * all other APIs used by the application are version 4 or lower) and take advantage 17949 * of this method, instead of overriding the method which would break the application's 17950 * backwards compatibility, he can override the corresponding method in this 17951 * delegate and register the delegate in the target View if the API version of 17952 * the system is high enough i.e. the API version is same or higher to the API 17953 * version that introduced 17954 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 17955 * </p> 17956 * <p> 17957 * Here is an example implementation: 17958 * </p> 17959 * <code><pre><p> 17960 * if (Build.VERSION.SDK_INT >= 14) { 17961 * // If the API version is equal of higher than the version in 17962 * // which onInitializeAccessibilityNodeInfo was introduced we 17963 * // register a delegate with a customized implementation. 17964 * View view = findViewById(R.id.view_id); 17965 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 17966 * public void onInitializeAccessibilityNodeInfo(View host, 17967 * AccessibilityNodeInfo info) { 17968 * // Let the default implementation populate the info. 17969 * super.onInitializeAccessibilityNodeInfo(host, info); 17970 * // Set some other information. 17971 * info.setEnabled(host.isEnabled()); 17972 * } 17973 * }); 17974 * } 17975 * </code></pre></p> 17976 * <p> 17977 * This delegate contains methods that correspond to the accessibility methods 17978 * in View. If a delegate has been specified the implementation in View hands 17979 * off handling to the corresponding method in this delegate. The default 17980 * implementation the delegate methods behaves exactly as the corresponding 17981 * method in View for the case of no accessibility delegate been set. Hence, 17982 * to customize the behavior of a View method, clients can override only the 17983 * corresponding delegate method without altering the behavior of the rest 17984 * accessibility related methods of the host view. 17985 * </p> 17986 */ 17987 public static class AccessibilityDelegate { 17988 17989 /** 17990 * Sends an accessibility event of the given type. If accessibility is not 17991 * enabled this method has no effect. 17992 * <p> 17993 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 17994 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 17995 * been set. 17996 * </p> 17997 * 17998 * @param host The View hosting the delegate. 17999 * @param eventType The type of the event to send. 18000 * 18001 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 18002 */ 18003 public void sendAccessibilityEvent(View host, int eventType) { 18004 host.sendAccessibilityEventInternal(eventType); 18005 } 18006 18007 /** 18008 * Performs the specified accessibility action on the view. For 18009 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 18010 * <p> 18011 * The default implementation behaves as 18012 * {@link View#performAccessibilityAction(int, Bundle) 18013 * View#performAccessibilityAction(int, Bundle)} for the case of 18014 * no accessibility delegate been set. 18015 * </p> 18016 * 18017 * @param action The action to perform. 18018 * @return Whether the action was performed. 18019 * 18020 * @see View#performAccessibilityAction(int, Bundle) 18021 * View#performAccessibilityAction(int, Bundle) 18022 */ 18023 public boolean performAccessibilityAction(View host, int action, Bundle args) { 18024 return host.performAccessibilityActionInternal(action, args); 18025 } 18026 18027 /** 18028 * Sends an accessibility event. This method behaves exactly as 18029 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 18030 * empty {@link AccessibilityEvent} and does not perform a check whether 18031 * accessibility is enabled. 18032 * <p> 18033 * The default implementation behaves as 18034 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18035 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 18036 * the case of no accessibility delegate been set. 18037 * </p> 18038 * 18039 * @param host The View hosting the delegate. 18040 * @param event The event to send. 18041 * 18042 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18043 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18044 */ 18045 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 18046 host.sendAccessibilityEventUncheckedInternal(event); 18047 } 18048 18049 /** 18050 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 18051 * to its children for adding their text content to the event. 18052 * <p> 18053 * The default implementation behaves as 18054 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18055 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 18056 * the case of no accessibility delegate been set. 18057 * </p> 18058 * 18059 * @param host The View hosting the delegate. 18060 * @param event The event. 18061 * @return True if the event population was completed. 18062 * 18063 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18064 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18065 */ 18066 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18067 return host.dispatchPopulateAccessibilityEventInternal(event); 18068 } 18069 18070 /** 18071 * Gives a chance to the host View to populate the accessibility event with its 18072 * text content. 18073 * <p> 18074 * The default implementation behaves as 18075 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 18076 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 18077 * the case of no accessibility delegate been set. 18078 * </p> 18079 * 18080 * @param host The View hosting the delegate. 18081 * @param event The accessibility event which to populate. 18082 * 18083 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 18084 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 18085 */ 18086 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18087 host.onPopulateAccessibilityEventInternal(event); 18088 } 18089 18090 /** 18091 * Initializes an {@link AccessibilityEvent} with information about the 18092 * the host View which is the event source. 18093 * <p> 18094 * The default implementation behaves as 18095 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 18096 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 18097 * the case of no accessibility delegate been set. 18098 * </p> 18099 * 18100 * @param host The View hosting the delegate. 18101 * @param event The event to initialize. 18102 * 18103 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 18104 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 18105 */ 18106 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 18107 host.onInitializeAccessibilityEventInternal(event); 18108 } 18109 18110 /** 18111 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 18112 * <p> 18113 * The default implementation behaves as 18114 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18115 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 18116 * the case of no accessibility delegate been set. 18117 * </p> 18118 * 18119 * @param host The View hosting the delegate. 18120 * @param info The instance to initialize. 18121 * 18122 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18123 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18124 */ 18125 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 18126 host.onInitializeAccessibilityNodeInfoInternal(info); 18127 } 18128 18129 /** 18130 * Called when a child of the host View has requested sending an 18131 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 18132 * to augment the event. 18133 * <p> 18134 * The default implementation behaves as 18135 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18136 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 18137 * the case of no accessibility delegate been set. 18138 * </p> 18139 * 18140 * @param host The View hosting the delegate. 18141 * @param child The child which requests sending the event. 18142 * @param event The event to be sent. 18143 * @return True if the event should be sent 18144 * 18145 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18146 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18147 */ 18148 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 18149 AccessibilityEvent event) { 18150 return host.onRequestSendAccessibilityEventInternal(child, event); 18151 } 18152 18153 /** 18154 * Gets the provider for managing a virtual view hierarchy rooted at this View 18155 * and reported to {@link android.accessibilityservice.AccessibilityService}s 18156 * that explore the window content. 18157 * <p> 18158 * The default implementation behaves as 18159 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 18160 * the case of no accessibility delegate been set. 18161 * </p> 18162 * 18163 * @return The provider. 18164 * 18165 * @see AccessibilityNodeProvider 18166 */ 18167 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 18168 return null; 18169 } 18170 } 18171 18172 private class MatchIdPredicate implements Predicate<View> { 18173 public int mId; 18174 18175 @Override 18176 public boolean apply(View view) { 18177 return (view.mID == mId); 18178 } 18179 } 18180 18181 private class MatchLabelForPredicate implements Predicate<View> { 18182 private int mLabeledId; 18183 18184 @Override 18185 public boolean apply(View view) { 18186 return (view.mLabelForId == mLabeledId); 18187 } 18188 } 18189 18190 /** 18191 * Dump all private flags in readable format, useful for documentation and 18192 * sanity checking. 18193 */ 18194 private static void dumpFlags() { 18195 final HashMap<String, String> found = Maps.newHashMap(); 18196 try { 18197 for (Field field : View.class.getDeclaredFields()) { 18198 final int modifiers = field.getModifiers(); 18199 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 18200 if (field.getType().equals(int.class)) { 18201 final int value = field.getInt(null); 18202 dumpFlag(found, field.getName(), value); 18203 } else if (field.getType().equals(int[].class)) { 18204 final int[] values = (int[]) field.get(null); 18205 for (int i = 0; i < values.length; i++) { 18206 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 18207 } 18208 } 18209 } 18210 } 18211 } catch (IllegalAccessException e) { 18212 throw new RuntimeException(e); 18213 } 18214 18215 final ArrayList<String> keys = Lists.newArrayList(); 18216 keys.addAll(found.keySet()); 18217 Collections.sort(keys); 18218 for (String key : keys) { 18219 Log.d(VIEW_LOG_TAG, found.get(key)); 18220 } 18221 } 18222 18223 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 18224 // Sort flags by prefix, then by bits, always keeping unique keys 18225 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 18226 final int prefix = name.indexOf('_'); 18227 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 18228 final String output = bits + " " + name; 18229 found.put(key, output); 18230 } 18231} 18232