View.java revision a85236e510b26002761bd5856fb371f7aed37527
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.content.ClipData; 20import android.content.Context; 21import android.content.res.Configuration; 22import android.content.res.Resources; 23import android.content.res.TypedArray; 24import android.graphics.Bitmap; 25import android.graphics.Camera; 26import android.graphics.Canvas; 27import android.graphics.Insets; 28import android.graphics.Interpolator; 29import android.graphics.LinearGradient; 30import android.graphics.Matrix; 31import android.graphics.Paint; 32import android.graphics.PixelFormat; 33import android.graphics.Point; 34import android.graphics.PorterDuff; 35import android.graphics.PorterDuffXfermode; 36import android.graphics.Rect; 37import android.graphics.RectF; 38import android.graphics.Region; 39import android.graphics.Shader; 40import android.graphics.drawable.ColorDrawable; 41import android.graphics.drawable.Drawable; 42import android.hardware.display.DisplayManagerGlobal; 43import android.os.Bundle; 44import android.os.Handler; 45import android.os.IBinder; 46import android.os.Parcel; 47import android.os.Parcelable; 48import android.os.RemoteException; 49import android.os.SystemClock; 50import android.os.SystemProperties; 51import android.text.TextUtils; 52import android.util.AttributeSet; 53import android.util.FloatProperty; 54import android.util.Log; 55import android.util.Pool; 56import android.util.Poolable; 57import android.util.PoolableManager; 58import android.util.Pools; 59import android.util.Property; 60import android.util.SparseArray; 61import android.util.TypedValue; 62import android.view.ContextMenu.ContextMenuInfo; 63import android.view.AccessibilityIterators.TextSegmentIterator; 64import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 65import android.view.AccessibilityIterators.WordTextSegmentIterator; 66import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 67import android.view.accessibility.AccessibilityEvent; 68import android.view.accessibility.AccessibilityEventSource; 69import android.view.accessibility.AccessibilityManager; 70import android.view.accessibility.AccessibilityNodeInfo; 71import android.view.accessibility.AccessibilityNodeProvider; 72import android.view.animation.Animation; 73import android.view.animation.AnimationUtils; 74import android.view.animation.Transformation; 75import android.view.inputmethod.EditorInfo; 76import android.view.inputmethod.InputConnection; 77import android.view.inputmethod.InputMethodManager; 78import android.widget.ScrollBarDrawable; 79 80import static android.os.Build.VERSION_CODES.*; 81import static java.lang.Math.max; 82 83import com.android.internal.R; 84import com.android.internal.util.Predicate; 85import com.android.internal.view.menu.MenuBuilder; 86import com.google.android.collect.Lists; 87import com.google.android.collect.Maps; 88 89import java.lang.ref.WeakReference; 90import java.lang.reflect.Field; 91import java.lang.reflect.InvocationTargetException; 92import java.lang.reflect.Method; 93import java.lang.reflect.Modifier; 94import java.util.ArrayList; 95import java.util.Arrays; 96import java.util.Collections; 97import java.util.HashMap; 98import java.util.Locale; 99import java.util.concurrent.CopyOnWriteArrayList; 100import java.util.concurrent.atomic.AtomicInteger; 101 102/** 103 * <p> 104 * This class represents the basic building block for user interface components. A View 105 * occupies a rectangular area on the screen and is responsible for drawing and 106 * event handling. View is the base class for <em>widgets</em>, which are 107 * used to create interactive UI components (buttons, text fields, etc.). The 108 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 109 * are invisible containers that hold other Views (or other ViewGroups) and define 110 * their layout properties. 111 * </p> 112 * 113 * <div class="special reference"> 114 * <h3>Developer Guides</h3> 115 * <p>For information about using this class to develop your application's user interface, 116 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 117 * </div> 118 * 119 * <a name="Using"></a> 120 * <h3>Using Views</h3> 121 * <p> 122 * All of the views in a window are arranged in a single tree. You can add views 123 * either from code or by specifying a tree of views in one or more XML layout 124 * files. There are many specialized subclasses of views that act as controls or 125 * are capable of displaying text, images, or other content. 126 * </p> 127 * <p> 128 * Once you have created a tree of views, there are typically a few types of 129 * common operations you may wish to perform: 130 * <ul> 131 * <li><strong>Set properties:</strong> for example setting the text of a 132 * {@link android.widget.TextView}. The available properties and the methods 133 * that set them will vary among the different subclasses of views. Note that 134 * properties that are known at build time can be set in the XML layout 135 * files.</li> 136 * <li><strong>Set focus:</strong> The framework will handled moving focus in 137 * response to user input. To force focus to a specific view, call 138 * {@link #requestFocus}.</li> 139 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 140 * that will be notified when something interesting happens to the view. For 141 * example, all views will let you set a listener to be notified when the view 142 * gains or loses focus. You can register such a listener using 143 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 144 * Other view subclasses offer more specialized listeners. For example, a Button 145 * exposes a listener to notify clients when the button is clicked.</li> 146 * <li><strong>Set visibility:</strong> You can hide or show views using 147 * {@link #setVisibility(int)}.</li> 148 * </ul> 149 * </p> 150 * <p><em> 151 * Note: The Android framework is responsible for measuring, laying out and 152 * drawing views. You should not call methods that perform these actions on 153 * views yourself unless you are actually implementing a 154 * {@link android.view.ViewGroup}. 155 * </em></p> 156 * 157 * <a name="Lifecycle"></a> 158 * <h3>Implementing a Custom View</h3> 159 * 160 * <p> 161 * To implement a custom view, you will usually begin by providing overrides for 162 * some of the standard methods that the framework calls on all views. You do 163 * not need to override all of these methods. In fact, you can start by just 164 * overriding {@link #onDraw(android.graphics.Canvas)}. 165 * <table border="2" width="85%" align="center" cellpadding="5"> 166 * <thead> 167 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 168 * </thead> 169 * 170 * <tbody> 171 * <tr> 172 * <td rowspan="2">Creation</td> 173 * <td>Constructors</td> 174 * <td>There is a form of the constructor that are called when the view 175 * is created from code and a form that is called when the view is 176 * inflated from a layout file. The second form should parse and apply 177 * any attributes defined in the layout file. 178 * </td> 179 * </tr> 180 * <tr> 181 * <td><code>{@link #onFinishInflate()}</code></td> 182 * <td>Called after a view and all of its children has been inflated 183 * from XML.</td> 184 * </tr> 185 * 186 * <tr> 187 * <td rowspan="3">Layout</td> 188 * <td><code>{@link #onMeasure(int, int)}</code></td> 189 * <td>Called to determine the size requirements for this view and all 190 * of its children. 191 * </td> 192 * </tr> 193 * <tr> 194 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 195 * <td>Called when this view should assign a size and position to all 196 * of its children. 197 * </td> 198 * </tr> 199 * <tr> 200 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 201 * <td>Called when the size of this view has changed. 202 * </td> 203 * </tr> 204 * 205 * <tr> 206 * <td>Drawing</td> 207 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 208 * <td>Called when the view should render its content. 209 * </td> 210 * </tr> 211 * 212 * <tr> 213 * <td rowspan="4">Event processing</td> 214 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 215 * <td>Called when a new hardware key event occurs. 216 * </td> 217 * </tr> 218 * <tr> 219 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 220 * <td>Called when a hardware key up event occurs. 221 * </td> 222 * </tr> 223 * <tr> 224 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 225 * <td>Called when a trackball motion event occurs. 226 * </td> 227 * </tr> 228 * <tr> 229 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 230 * <td>Called when a touch screen motion event occurs. 231 * </td> 232 * </tr> 233 * 234 * <tr> 235 * <td rowspan="2">Focus</td> 236 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 237 * <td>Called when the view gains or loses focus. 238 * </td> 239 * </tr> 240 * 241 * <tr> 242 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 243 * <td>Called when the window containing the view gains or loses focus. 244 * </td> 245 * </tr> 246 * 247 * <tr> 248 * <td rowspan="3">Attaching</td> 249 * <td><code>{@link #onAttachedToWindow()}</code></td> 250 * <td>Called when the view is attached to a window. 251 * </td> 252 * </tr> 253 * 254 * <tr> 255 * <td><code>{@link #onDetachedFromWindow}</code></td> 256 * <td>Called when the view is detached from its window. 257 * </td> 258 * </tr> 259 * 260 * <tr> 261 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 262 * <td>Called when the visibility of the window containing the view 263 * has changed. 264 * </td> 265 * </tr> 266 * </tbody> 267 * 268 * </table> 269 * </p> 270 * 271 * <a name="IDs"></a> 272 * <h3>IDs</h3> 273 * Views may have an integer id associated with them. These ids are typically 274 * assigned in the layout XML files, and are used to find specific views within 275 * the view tree. A common pattern is to: 276 * <ul> 277 * <li>Define a Button in the layout file and assign it a unique ID. 278 * <pre> 279 * <Button 280 * android:id="@+id/my_button" 281 * android:layout_width="wrap_content" 282 * android:layout_height="wrap_content" 283 * android:text="@string/my_button_text"/> 284 * </pre></li> 285 * <li>From the onCreate method of an Activity, find the Button 286 * <pre class="prettyprint"> 287 * Button myButton = (Button) findViewById(R.id.my_button); 288 * </pre></li> 289 * </ul> 290 * <p> 291 * View IDs need not be unique throughout the tree, but it is good practice to 292 * ensure that they are at least unique within the part of the tree you are 293 * searching. 294 * </p> 295 * 296 * <a name="Position"></a> 297 * <h3>Position</h3> 298 * <p> 299 * The geometry of a view is that of a rectangle. A view has a location, 300 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 301 * two dimensions, expressed as a width and a height. The unit for location 302 * and dimensions is the pixel. 303 * </p> 304 * 305 * <p> 306 * It is possible to retrieve the location of a view by invoking the methods 307 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 308 * coordinate of the rectangle representing the view. The latter returns the 309 * top, or Y, coordinate of the rectangle representing the view. These methods 310 * both return the location of the view relative to its parent. For instance, 311 * when getLeft() returns 20, that means the view is located 20 pixels to the 312 * right of the left edge of its direct parent. 313 * </p> 314 * 315 * <p> 316 * In addition, several convenience methods are offered to avoid unnecessary 317 * computations, namely {@link #getRight()} and {@link #getBottom()}. 318 * These methods return the coordinates of the right and bottom edges of the 319 * rectangle representing the view. For instance, calling {@link #getRight()} 320 * is similar to the following computation: <code>getLeft() + getWidth()</code> 321 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 322 * </p> 323 * 324 * <a name="SizePaddingMargins"></a> 325 * <h3>Size, padding and margins</h3> 326 * <p> 327 * The size of a view is expressed with a width and a height. A view actually 328 * possess two pairs of width and height values. 329 * </p> 330 * 331 * <p> 332 * The first pair is known as <em>measured width</em> and 333 * <em>measured height</em>. These dimensions define how big a view wants to be 334 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 335 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 336 * and {@link #getMeasuredHeight()}. 337 * </p> 338 * 339 * <p> 340 * The second pair is simply known as <em>width</em> and <em>height</em>, or 341 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 342 * dimensions define the actual size of the view on screen, at drawing time and 343 * after layout. These values may, but do not have to, be different from the 344 * measured width and height. The width and height can be obtained by calling 345 * {@link #getWidth()} and {@link #getHeight()}. 346 * </p> 347 * 348 * <p> 349 * To measure its dimensions, a view takes into account its padding. The padding 350 * is expressed in pixels for the left, top, right and bottom parts of the view. 351 * Padding can be used to offset the content of the view by a specific amount of 352 * pixels. For instance, a left padding of 2 will push the view's content by 353 * 2 pixels to the right of the left edge. Padding can be set using the 354 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 355 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 356 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 357 * {@link #getPaddingEnd()}. 358 * </p> 359 * 360 * <p> 361 * Even though a view can define a padding, it does not provide any support for 362 * margins. However, view groups provide such a support. Refer to 363 * {@link android.view.ViewGroup} and 364 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 365 * </p> 366 * 367 * <a name="Layout"></a> 368 * <h3>Layout</h3> 369 * <p> 370 * Layout is a two pass process: a measure pass and a layout pass. The measuring 371 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 372 * of the view tree. Each view pushes dimension specifications down the tree 373 * during the recursion. At the end of the measure pass, every view has stored 374 * its measurements. The second pass happens in 375 * {@link #layout(int,int,int,int)} and is also top-down. During 376 * this pass each parent is responsible for positioning all of its children 377 * using the sizes computed in the measure pass. 378 * </p> 379 * 380 * <p> 381 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 382 * {@link #getMeasuredHeight()} values must be set, along with those for all of 383 * that view's descendants. A view's measured width and measured height values 384 * must respect the constraints imposed by the view's parents. This guarantees 385 * that at the end of the measure pass, all parents accept all of their 386 * children's measurements. A parent view may call measure() more than once on 387 * its children. For example, the parent may measure each child once with 388 * unspecified dimensions to find out how big they want to be, then call 389 * measure() on them again with actual numbers if the sum of all the children's 390 * unconstrained sizes is too big or too small. 391 * </p> 392 * 393 * <p> 394 * The measure pass uses two classes to communicate dimensions. The 395 * {@link MeasureSpec} class is used by views to tell their parents how they 396 * want to be measured and positioned. The base LayoutParams class just 397 * describes how big the view wants to be for both width and height. For each 398 * dimension, it can specify one of: 399 * <ul> 400 * <li> an exact number 401 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 402 * (minus padding) 403 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 404 * enclose its content (plus padding). 405 * </ul> 406 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 407 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 408 * an X and Y value. 409 * </p> 410 * 411 * <p> 412 * MeasureSpecs are used to push requirements down the tree from parent to 413 * child. A MeasureSpec can be in one of three modes: 414 * <ul> 415 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 416 * of a child view. For example, a LinearLayout may call measure() on its child 417 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 418 * tall the child view wants to be given a width of 240 pixels. 419 * <li>EXACTLY: This is used by the parent to impose an exact size on the 420 * child. The child must use this size, and guarantee that all of its 421 * descendants will fit within this size. 422 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 423 * child. The child must gurantee that it and all of its descendants will fit 424 * within this size. 425 * </ul> 426 * </p> 427 * 428 * <p> 429 * To intiate a layout, call {@link #requestLayout}. This method is typically 430 * called by a view on itself when it believes that is can no longer fit within 431 * its current bounds. 432 * </p> 433 * 434 * <a name="Drawing"></a> 435 * <h3>Drawing</h3> 436 * <p> 437 * Drawing is handled by walking the tree and rendering each view that 438 * intersects the invalid region. Because the tree is traversed in-order, 439 * this means that parents will draw before (i.e., behind) their children, with 440 * siblings drawn in the order they appear in the tree. 441 * If you set a background drawable for a View, then the View will draw it for you 442 * before calling back to its <code>onDraw()</code> method. 443 * </p> 444 * 445 * <p> 446 * Note that the framework will not draw views that are not in the invalid region. 447 * </p> 448 * 449 * <p> 450 * To force a view to draw, call {@link #invalidate()}. 451 * </p> 452 * 453 * <a name="EventHandlingThreading"></a> 454 * <h3>Event Handling and Threading</h3> 455 * <p> 456 * The basic cycle of a view is as follows: 457 * <ol> 458 * <li>An event comes in and is dispatched to the appropriate view. The view 459 * handles the event and notifies any listeners.</li> 460 * <li>If in the course of processing the event, the view's bounds may need 461 * to be changed, the view will call {@link #requestLayout()}.</li> 462 * <li>Similarly, if in the course of processing the event the view's appearance 463 * may need to be changed, the view will call {@link #invalidate()}.</li> 464 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 465 * the framework will take care of measuring, laying out, and drawing the tree 466 * as appropriate.</li> 467 * </ol> 468 * </p> 469 * 470 * <p><em>Note: The entire view tree is single threaded. You must always be on 471 * the UI thread when calling any method on any view.</em> 472 * If you are doing work on other threads and want to update the state of a view 473 * from that thread, you should use a {@link Handler}. 474 * </p> 475 * 476 * <a name="FocusHandling"></a> 477 * <h3>Focus Handling</h3> 478 * <p> 479 * The framework will handle routine focus movement in response to user input. 480 * This includes changing the focus as views are removed or hidden, or as new 481 * views become available. Views indicate their willingness to take focus 482 * through the {@link #isFocusable} method. To change whether a view can take 483 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 484 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 485 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 486 * </p> 487 * <p> 488 * Focus movement is based on an algorithm which finds the nearest neighbor in a 489 * given direction. In rare cases, the default algorithm may not match the 490 * intended behavior of the developer. In these situations, you can provide 491 * explicit overrides by using these XML attributes in the layout file: 492 * <pre> 493 * nextFocusDown 494 * nextFocusLeft 495 * nextFocusRight 496 * nextFocusUp 497 * </pre> 498 * </p> 499 * 500 * 501 * <p> 502 * To get a particular view to take focus, call {@link #requestFocus()}. 503 * </p> 504 * 505 * <a name="TouchMode"></a> 506 * <h3>Touch Mode</h3> 507 * <p> 508 * When a user is navigating a user interface via directional keys such as a D-pad, it is 509 * necessary to give focus to actionable items such as buttons so the user can see 510 * what will take input. If the device has touch capabilities, however, and the user 511 * begins interacting with the interface by touching it, it is no longer necessary to 512 * always highlight, or give focus to, a particular view. This motivates a mode 513 * for interaction named 'touch mode'. 514 * </p> 515 * <p> 516 * For a touch capable device, once the user touches the screen, the device 517 * will enter touch mode. From this point onward, only views for which 518 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 519 * Other views that are touchable, like buttons, will not take focus when touched; they will 520 * only fire the on click listeners. 521 * </p> 522 * <p> 523 * Any time a user hits a directional key, such as a D-pad direction, the view device will 524 * exit touch mode, and find a view to take focus, so that the user may resume interacting 525 * with the user interface without touching the screen again. 526 * </p> 527 * <p> 528 * The touch mode state is maintained across {@link android.app.Activity}s. Call 529 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 530 * </p> 531 * 532 * <a name="Scrolling"></a> 533 * <h3>Scrolling</h3> 534 * <p> 535 * The framework provides basic support for views that wish to internally 536 * scroll their content. This includes keeping track of the X and Y scroll 537 * offset as well as mechanisms for drawing scrollbars. See 538 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 539 * {@link #awakenScrollBars()} for more details. 540 * </p> 541 * 542 * <a name="Tags"></a> 543 * <h3>Tags</h3> 544 * <p> 545 * Unlike IDs, tags are not used to identify views. Tags are essentially an 546 * extra piece of information that can be associated with a view. They are most 547 * often used as a convenience to store data related to views in the views 548 * themselves rather than by putting them in a separate structure. 549 * </p> 550 * 551 * <a name="Properties"></a> 552 * <h3>Properties</h3> 553 * <p> 554 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 555 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 556 * available both in the {@link Property} form as well as in similarly-named setter/getter 557 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 558 * be used to set persistent state associated with these rendering-related properties on the view. 559 * The properties and methods can also be used in conjunction with 560 * {@link android.animation.Animator Animator}-based animations, described more in the 561 * <a href="#Animation">Animation</a> section. 562 * </p> 563 * 564 * <a name="Animation"></a> 565 * <h3>Animation</h3> 566 * <p> 567 * Starting with Android 3.0, the preferred way of animating views is to use the 568 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 569 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 570 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 571 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 572 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 573 * makes animating these View properties particularly easy and efficient. 574 * </p> 575 * <p> 576 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 577 * You can attach an {@link Animation} object to a view using 578 * {@link #setAnimation(Animation)} or 579 * {@link #startAnimation(Animation)}. The animation can alter the scale, 580 * rotation, translation and alpha of a view over time. If the animation is 581 * attached to a view that has children, the animation will affect the entire 582 * subtree rooted by that node. When an animation is started, the framework will 583 * take care of redrawing the appropriate views until the animation completes. 584 * </p> 585 * 586 * <a name="Security"></a> 587 * <h3>Security</h3> 588 * <p> 589 * Sometimes it is essential that an application be able to verify that an action 590 * is being performed with the full knowledge and consent of the user, such as 591 * granting a permission request, making a purchase or clicking on an advertisement. 592 * Unfortunately, a malicious application could try to spoof the user into 593 * performing these actions, unaware, by concealing the intended purpose of the view. 594 * As a remedy, the framework offers a touch filtering mechanism that can be used to 595 * improve the security of views that provide access to sensitive functionality. 596 * </p><p> 597 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 598 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 599 * will discard touches that are received whenever the view's window is obscured by 600 * another visible window. As a result, the view will not receive touches whenever a 601 * toast, dialog or other window appears above the view's window. 602 * </p><p> 603 * For more fine-grained control over security, consider overriding the 604 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 605 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 606 * </p> 607 * 608 * @attr ref android.R.styleable#View_alpha 609 * @attr ref android.R.styleable#View_background 610 * @attr ref android.R.styleable#View_clickable 611 * @attr ref android.R.styleable#View_contentDescription 612 * @attr ref android.R.styleable#View_drawingCacheQuality 613 * @attr ref android.R.styleable#View_duplicateParentState 614 * @attr ref android.R.styleable#View_id 615 * @attr ref android.R.styleable#View_requiresFadingEdge 616 * @attr ref android.R.styleable#View_fadeScrollbars 617 * @attr ref android.R.styleable#View_fadingEdgeLength 618 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 619 * @attr ref android.R.styleable#View_fitsSystemWindows 620 * @attr ref android.R.styleable#View_isScrollContainer 621 * @attr ref android.R.styleable#View_focusable 622 * @attr ref android.R.styleable#View_focusableInTouchMode 623 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 624 * @attr ref android.R.styleable#View_keepScreenOn 625 * @attr ref android.R.styleable#View_layerType 626 * @attr ref android.R.styleable#View_longClickable 627 * @attr ref android.R.styleable#View_minHeight 628 * @attr ref android.R.styleable#View_minWidth 629 * @attr ref android.R.styleable#View_nextFocusDown 630 * @attr ref android.R.styleable#View_nextFocusLeft 631 * @attr ref android.R.styleable#View_nextFocusRight 632 * @attr ref android.R.styleable#View_nextFocusUp 633 * @attr ref android.R.styleable#View_onClick 634 * @attr ref android.R.styleable#View_padding 635 * @attr ref android.R.styleable#View_paddingBottom 636 * @attr ref android.R.styleable#View_paddingLeft 637 * @attr ref android.R.styleable#View_paddingRight 638 * @attr ref android.R.styleable#View_paddingTop 639 * @attr ref android.R.styleable#View_paddingStart 640 * @attr ref android.R.styleable#View_paddingEnd 641 * @attr ref android.R.styleable#View_saveEnabled 642 * @attr ref android.R.styleable#View_rotation 643 * @attr ref android.R.styleable#View_rotationX 644 * @attr ref android.R.styleable#View_rotationY 645 * @attr ref android.R.styleable#View_scaleX 646 * @attr ref android.R.styleable#View_scaleY 647 * @attr ref android.R.styleable#View_scrollX 648 * @attr ref android.R.styleable#View_scrollY 649 * @attr ref android.R.styleable#View_scrollbarSize 650 * @attr ref android.R.styleable#View_scrollbarStyle 651 * @attr ref android.R.styleable#View_scrollbars 652 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 653 * @attr ref android.R.styleable#View_scrollbarFadeDuration 654 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 655 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 656 * @attr ref android.R.styleable#View_scrollbarThumbVertical 657 * @attr ref android.R.styleable#View_scrollbarTrackVertical 658 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 660 * @attr ref android.R.styleable#View_soundEffectsEnabled 661 * @attr ref android.R.styleable#View_tag 662 * @attr ref android.R.styleable#View_textAlignment 663 * @attr ref android.R.styleable#View_transformPivotX 664 * @attr ref android.R.styleable#View_transformPivotY 665 * @attr ref android.R.styleable#View_translationX 666 * @attr ref android.R.styleable#View_translationY 667 * @attr ref android.R.styleable#View_visibility 668 * 669 * @see android.view.ViewGroup 670 */ 671public class View implements Drawable.Callback, KeyEvent.Callback, 672 AccessibilityEventSource { 673 private static final boolean DBG = false; 674 675 /** 676 * The logging tag used by this class with android.util.Log. 677 */ 678 protected static final String VIEW_LOG_TAG = "View"; 679 680 /** 681 * When set to true, apps will draw debugging information about their layouts. 682 * 683 * @hide 684 */ 685 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 686 687 /** 688 * Used to mark a View that has no ID. 689 */ 690 public static final int NO_ID = -1; 691 692 /** 693 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 694 * calling setFlags. 695 */ 696 private static final int NOT_FOCUSABLE = 0x00000000; 697 698 /** 699 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 700 * setFlags. 701 */ 702 private static final int FOCUSABLE = 0x00000001; 703 704 /** 705 * Mask for use with setFlags indicating bits used for focus. 706 */ 707 private static final int FOCUSABLE_MASK = 0x00000001; 708 709 /** 710 * This view will adjust its padding to fit sytem windows (e.g. status bar) 711 */ 712 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 713 714 /** 715 * This view is visible. 716 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 717 * android:visibility}. 718 */ 719 public static final int VISIBLE = 0x00000000; 720 721 /** 722 * This view is invisible, but it still takes up space for layout purposes. 723 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 724 * android:visibility}. 725 */ 726 public static final int INVISIBLE = 0x00000004; 727 728 /** 729 * This view is invisible, and it doesn't take any space for layout 730 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 731 * android:visibility}. 732 */ 733 public static final int GONE = 0x00000008; 734 735 /** 736 * Mask for use with setFlags indicating bits used for visibility. 737 * {@hide} 738 */ 739 static final int VISIBILITY_MASK = 0x0000000C; 740 741 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 742 743 /** 744 * This view is enabled. Interpretation varies by subclass. 745 * Use with ENABLED_MASK when calling setFlags. 746 * {@hide} 747 */ 748 static final int ENABLED = 0x00000000; 749 750 /** 751 * This view is disabled. Interpretation varies by subclass. 752 * Use with ENABLED_MASK when calling setFlags. 753 * {@hide} 754 */ 755 static final int DISABLED = 0x00000020; 756 757 /** 758 * Mask for use with setFlags indicating bits used for indicating whether 759 * this view is enabled 760 * {@hide} 761 */ 762 static final int ENABLED_MASK = 0x00000020; 763 764 /** 765 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 766 * called and further optimizations will be performed. It is okay to have 767 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 768 * {@hide} 769 */ 770 static final int WILL_NOT_DRAW = 0x00000080; 771 772 /** 773 * Mask for use with setFlags indicating bits used for indicating whether 774 * this view is will draw 775 * {@hide} 776 */ 777 static final int DRAW_MASK = 0x00000080; 778 779 /** 780 * <p>This view doesn't show scrollbars.</p> 781 * {@hide} 782 */ 783 static final int SCROLLBARS_NONE = 0x00000000; 784 785 /** 786 * <p>This view shows horizontal scrollbars.</p> 787 * {@hide} 788 */ 789 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 790 791 /** 792 * <p>This view shows vertical scrollbars.</p> 793 * {@hide} 794 */ 795 static final int SCROLLBARS_VERTICAL = 0x00000200; 796 797 /** 798 * <p>Mask for use with setFlags indicating bits used for indicating which 799 * scrollbars are enabled.</p> 800 * {@hide} 801 */ 802 static final int SCROLLBARS_MASK = 0x00000300; 803 804 /** 805 * Indicates that the view should filter touches when its window is obscured. 806 * Refer to the class comments for more information about this security feature. 807 * {@hide} 808 */ 809 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 810 811 /** 812 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 813 * that they are optional and should be skipped if the window has 814 * requested system UI flags that ignore those insets for layout. 815 */ 816 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 817 818 /** 819 * <p>This view doesn't show fading edges.</p> 820 * {@hide} 821 */ 822 static final int FADING_EDGE_NONE = 0x00000000; 823 824 /** 825 * <p>This view shows horizontal fading edges.</p> 826 * {@hide} 827 */ 828 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 829 830 /** 831 * <p>This view shows vertical fading edges.</p> 832 * {@hide} 833 */ 834 static final int FADING_EDGE_VERTICAL = 0x00002000; 835 836 /** 837 * <p>Mask for use with setFlags indicating bits used for indicating which 838 * fading edges are enabled.</p> 839 * {@hide} 840 */ 841 static final int FADING_EDGE_MASK = 0x00003000; 842 843 /** 844 * <p>Indicates this view can be clicked. When clickable, a View reacts 845 * to clicks by notifying the OnClickListener.<p> 846 * {@hide} 847 */ 848 static final int CLICKABLE = 0x00004000; 849 850 /** 851 * <p>Indicates this view is caching its drawing into a bitmap.</p> 852 * {@hide} 853 */ 854 static final int DRAWING_CACHE_ENABLED = 0x00008000; 855 856 /** 857 * <p>Indicates that no icicle should be saved for this view.<p> 858 * {@hide} 859 */ 860 static final int SAVE_DISABLED = 0x000010000; 861 862 /** 863 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 864 * property.</p> 865 * {@hide} 866 */ 867 static final int SAVE_DISABLED_MASK = 0x000010000; 868 869 /** 870 * <p>Indicates that no drawing cache should ever be created for this view.<p> 871 * {@hide} 872 */ 873 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 874 875 /** 876 * <p>Indicates this view can take / keep focus when int touch mode.</p> 877 * {@hide} 878 */ 879 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 880 881 /** 882 * <p>Enables low quality mode for the drawing cache.</p> 883 */ 884 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 885 886 /** 887 * <p>Enables high quality mode for the drawing cache.</p> 888 */ 889 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 890 891 /** 892 * <p>Enables automatic quality mode for the drawing cache.</p> 893 */ 894 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 895 896 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 897 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 898 }; 899 900 /** 901 * <p>Mask for use with setFlags indicating bits used for the cache 902 * quality property.</p> 903 * {@hide} 904 */ 905 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 906 907 /** 908 * <p> 909 * Indicates this view can be long clicked. When long clickable, a View 910 * reacts to long clicks by notifying the OnLongClickListener or showing a 911 * context menu. 912 * </p> 913 * {@hide} 914 */ 915 static final int LONG_CLICKABLE = 0x00200000; 916 917 /** 918 * <p>Indicates that this view gets its drawable states from its direct parent 919 * and ignores its original internal states.</p> 920 * 921 * @hide 922 */ 923 static final int DUPLICATE_PARENT_STATE = 0x00400000; 924 925 /** 926 * The scrollbar style to display the scrollbars inside the content area, 927 * without increasing the padding. The scrollbars will be overlaid with 928 * translucency on the view's content. 929 */ 930 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 931 932 /** 933 * The scrollbar style to display the scrollbars inside the padded area, 934 * increasing the padding of the view. The scrollbars will not overlap the 935 * content area of the view. 936 */ 937 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 938 939 /** 940 * The scrollbar style to display the scrollbars at the edge of the view, 941 * without increasing the padding. The scrollbars will be overlaid with 942 * translucency. 943 */ 944 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 945 946 /** 947 * The scrollbar style to display the scrollbars at the edge of the view, 948 * increasing the padding of the view. The scrollbars will only overlap the 949 * background, if any. 950 */ 951 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 952 953 /** 954 * Mask to check if the scrollbar style is overlay or inset. 955 * {@hide} 956 */ 957 static final int SCROLLBARS_INSET_MASK = 0x01000000; 958 959 /** 960 * Mask to check if the scrollbar style is inside or outside. 961 * {@hide} 962 */ 963 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 964 965 /** 966 * Mask for scrollbar style. 967 * {@hide} 968 */ 969 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 970 971 /** 972 * View flag indicating that the screen should remain on while the 973 * window containing this view is visible to the user. This effectively 974 * takes care of automatically setting the WindowManager's 975 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 976 */ 977 public static final int KEEP_SCREEN_ON = 0x04000000; 978 979 /** 980 * View flag indicating whether this view should have sound effects enabled 981 * for events such as clicking and touching. 982 */ 983 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 984 985 /** 986 * View flag indicating whether this view should have haptic feedback 987 * enabled for events such as long presses. 988 */ 989 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 990 991 /** 992 * <p>Indicates that the view hierarchy should stop saving state when 993 * it reaches this view. If state saving is initiated immediately at 994 * the view, it will be allowed. 995 * {@hide} 996 */ 997 static final int PARENT_SAVE_DISABLED = 0x20000000; 998 999 /** 1000 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1001 * {@hide} 1002 */ 1003 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1004 1005 /** 1006 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1007 * should add all focusable Views regardless if they are focusable in touch mode. 1008 */ 1009 public static final int FOCUSABLES_ALL = 0x00000000; 1010 1011 /** 1012 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1013 * should add only Views focusable in touch mode. 1014 */ 1015 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1016 1017 /** 1018 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1019 * item. 1020 */ 1021 public static final int FOCUS_BACKWARD = 0x00000001; 1022 1023 /** 1024 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1025 * item. 1026 */ 1027 public static final int FOCUS_FORWARD = 0x00000002; 1028 1029 /** 1030 * Use with {@link #focusSearch(int)}. Move focus to the left. 1031 */ 1032 public static final int FOCUS_LEFT = 0x00000011; 1033 1034 /** 1035 * Use with {@link #focusSearch(int)}. Move focus up. 1036 */ 1037 public static final int FOCUS_UP = 0x00000021; 1038 1039 /** 1040 * Use with {@link #focusSearch(int)}. Move focus to the right. 1041 */ 1042 public static final int FOCUS_RIGHT = 0x00000042; 1043 1044 /** 1045 * Use with {@link #focusSearch(int)}. Move focus down. 1046 */ 1047 public static final int FOCUS_DOWN = 0x00000082; 1048 1049 /** 1050 * Bits of {@link #getMeasuredWidthAndState()} and 1051 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1052 */ 1053 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1054 1055 /** 1056 * Bits of {@link #getMeasuredWidthAndState()} and 1057 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1058 */ 1059 public static final int MEASURED_STATE_MASK = 0xff000000; 1060 1061 /** 1062 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1063 * for functions that combine both width and height into a single int, 1064 * such as {@link #getMeasuredState()} and the childState argument of 1065 * {@link #resolveSizeAndState(int, int, int)}. 1066 */ 1067 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1068 1069 /** 1070 * Bit of {@link #getMeasuredWidthAndState()} and 1071 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1072 * is smaller that the space the view would like to have. 1073 */ 1074 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1075 1076 /** 1077 * Base View state sets 1078 */ 1079 // Singles 1080 /** 1081 * Indicates the view has no states set. States are used with 1082 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1083 * view depending on its state. 1084 * 1085 * @see android.graphics.drawable.Drawable 1086 * @see #getDrawableState() 1087 */ 1088 protected static final int[] EMPTY_STATE_SET; 1089 /** 1090 * Indicates the view is enabled. States are used with 1091 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1092 * view depending on its state. 1093 * 1094 * @see android.graphics.drawable.Drawable 1095 * @see #getDrawableState() 1096 */ 1097 protected static final int[] ENABLED_STATE_SET; 1098 /** 1099 * Indicates the view is focused. States are used with 1100 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1101 * view depending on its state. 1102 * 1103 * @see android.graphics.drawable.Drawable 1104 * @see #getDrawableState() 1105 */ 1106 protected static final int[] FOCUSED_STATE_SET; 1107 /** 1108 * Indicates the view is selected. States are used with 1109 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1110 * view depending on its state. 1111 * 1112 * @see android.graphics.drawable.Drawable 1113 * @see #getDrawableState() 1114 */ 1115 protected static final int[] SELECTED_STATE_SET; 1116 /** 1117 * Indicates the view is pressed. States are used with 1118 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1119 * view depending on its state. 1120 * 1121 * @see android.graphics.drawable.Drawable 1122 * @see #getDrawableState() 1123 * @hide 1124 */ 1125 protected static final int[] PRESSED_STATE_SET; 1126 /** 1127 * Indicates the view's window has focus. States are used with 1128 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1129 * view depending on its state. 1130 * 1131 * @see android.graphics.drawable.Drawable 1132 * @see #getDrawableState() 1133 */ 1134 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1135 // Doubles 1136 /** 1137 * Indicates the view is enabled and has the focus. 1138 * 1139 * @see #ENABLED_STATE_SET 1140 * @see #FOCUSED_STATE_SET 1141 */ 1142 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1143 /** 1144 * Indicates the view is enabled and selected. 1145 * 1146 * @see #ENABLED_STATE_SET 1147 * @see #SELECTED_STATE_SET 1148 */ 1149 protected static final int[] ENABLED_SELECTED_STATE_SET; 1150 /** 1151 * Indicates the view is enabled and that its window has focus. 1152 * 1153 * @see #ENABLED_STATE_SET 1154 * @see #WINDOW_FOCUSED_STATE_SET 1155 */ 1156 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1157 /** 1158 * Indicates the view is focused and selected. 1159 * 1160 * @see #FOCUSED_STATE_SET 1161 * @see #SELECTED_STATE_SET 1162 */ 1163 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1164 /** 1165 * Indicates the view has the focus and that its window has the focus. 1166 * 1167 * @see #FOCUSED_STATE_SET 1168 * @see #WINDOW_FOCUSED_STATE_SET 1169 */ 1170 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1171 /** 1172 * Indicates the view is selected and that its window has the focus. 1173 * 1174 * @see #SELECTED_STATE_SET 1175 * @see #WINDOW_FOCUSED_STATE_SET 1176 */ 1177 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1178 // Triples 1179 /** 1180 * Indicates the view is enabled, focused and selected. 1181 * 1182 * @see #ENABLED_STATE_SET 1183 * @see #FOCUSED_STATE_SET 1184 * @see #SELECTED_STATE_SET 1185 */ 1186 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1187 /** 1188 * Indicates the view is enabled, focused and its window has the focus. 1189 * 1190 * @see #ENABLED_STATE_SET 1191 * @see #FOCUSED_STATE_SET 1192 * @see #WINDOW_FOCUSED_STATE_SET 1193 */ 1194 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1195 /** 1196 * Indicates the view is enabled, selected and its window has the focus. 1197 * 1198 * @see #ENABLED_STATE_SET 1199 * @see #SELECTED_STATE_SET 1200 * @see #WINDOW_FOCUSED_STATE_SET 1201 */ 1202 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1203 /** 1204 * Indicates the view is focused, selected and its window has the focus. 1205 * 1206 * @see #FOCUSED_STATE_SET 1207 * @see #SELECTED_STATE_SET 1208 * @see #WINDOW_FOCUSED_STATE_SET 1209 */ 1210 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1211 /** 1212 * Indicates the view is enabled, focused, selected and its window 1213 * has the focus. 1214 * 1215 * @see #ENABLED_STATE_SET 1216 * @see #FOCUSED_STATE_SET 1217 * @see #SELECTED_STATE_SET 1218 * @see #WINDOW_FOCUSED_STATE_SET 1219 */ 1220 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1221 /** 1222 * Indicates the view is pressed and its window has the focus. 1223 * 1224 * @see #PRESSED_STATE_SET 1225 * @see #WINDOW_FOCUSED_STATE_SET 1226 */ 1227 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1228 /** 1229 * Indicates the view is pressed and selected. 1230 * 1231 * @see #PRESSED_STATE_SET 1232 * @see #SELECTED_STATE_SET 1233 */ 1234 protected static final int[] PRESSED_SELECTED_STATE_SET; 1235 /** 1236 * Indicates the view is pressed, selected and its window has the focus. 1237 * 1238 * @see #PRESSED_STATE_SET 1239 * @see #SELECTED_STATE_SET 1240 * @see #WINDOW_FOCUSED_STATE_SET 1241 */ 1242 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1243 /** 1244 * Indicates the view is pressed and focused. 1245 * 1246 * @see #PRESSED_STATE_SET 1247 * @see #FOCUSED_STATE_SET 1248 */ 1249 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1250 /** 1251 * Indicates the view is pressed, focused and its window has the focus. 1252 * 1253 * @see #PRESSED_STATE_SET 1254 * @see #FOCUSED_STATE_SET 1255 * @see #WINDOW_FOCUSED_STATE_SET 1256 */ 1257 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1258 /** 1259 * Indicates the view is pressed, focused and selected. 1260 * 1261 * @see #PRESSED_STATE_SET 1262 * @see #SELECTED_STATE_SET 1263 * @see #FOCUSED_STATE_SET 1264 */ 1265 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1266 /** 1267 * Indicates the view is pressed, focused, selected and its window has the focus. 1268 * 1269 * @see #PRESSED_STATE_SET 1270 * @see #FOCUSED_STATE_SET 1271 * @see #SELECTED_STATE_SET 1272 * @see #WINDOW_FOCUSED_STATE_SET 1273 */ 1274 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1275 /** 1276 * Indicates the view is pressed and enabled. 1277 * 1278 * @see #PRESSED_STATE_SET 1279 * @see #ENABLED_STATE_SET 1280 */ 1281 protected static final int[] PRESSED_ENABLED_STATE_SET; 1282 /** 1283 * Indicates the view is pressed, enabled and its window has the focus. 1284 * 1285 * @see #PRESSED_STATE_SET 1286 * @see #ENABLED_STATE_SET 1287 * @see #WINDOW_FOCUSED_STATE_SET 1288 */ 1289 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1290 /** 1291 * Indicates the view is pressed, enabled and selected. 1292 * 1293 * @see #PRESSED_STATE_SET 1294 * @see #ENABLED_STATE_SET 1295 * @see #SELECTED_STATE_SET 1296 */ 1297 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1298 /** 1299 * Indicates the view is pressed, enabled, selected and its window has the 1300 * focus. 1301 * 1302 * @see #PRESSED_STATE_SET 1303 * @see #ENABLED_STATE_SET 1304 * @see #SELECTED_STATE_SET 1305 * @see #WINDOW_FOCUSED_STATE_SET 1306 */ 1307 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1308 /** 1309 * Indicates the view is pressed, enabled and focused. 1310 * 1311 * @see #PRESSED_STATE_SET 1312 * @see #ENABLED_STATE_SET 1313 * @see #FOCUSED_STATE_SET 1314 */ 1315 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1316 /** 1317 * Indicates the view is pressed, enabled, focused and its window has the 1318 * focus. 1319 * 1320 * @see #PRESSED_STATE_SET 1321 * @see #ENABLED_STATE_SET 1322 * @see #FOCUSED_STATE_SET 1323 * @see #WINDOW_FOCUSED_STATE_SET 1324 */ 1325 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1326 /** 1327 * Indicates the view is pressed, enabled, focused and selected. 1328 * 1329 * @see #PRESSED_STATE_SET 1330 * @see #ENABLED_STATE_SET 1331 * @see #SELECTED_STATE_SET 1332 * @see #FOCUSED_STATE_SET 1333 */ 1334 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1335 /** 1336 * Indicates the view is pressed, enabled, focused, selected and its window 1337 * has the focus. 1338 * 1339 * @see #PRESSED_STATE_SET 1340 * @see #ENABLED_STATE_SET 1341 * @see #SELECTED_STATE_SET 1342 * @see #FOCUSED_STATE_SET 1343 * @see #WINDOW_FOCUSED_STATE_SET 1344 */ 1345 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1346 1347 /** 1348 * The order here is very important to {@link #getDrawableState()} 1349 */ 1350 private static final int[][] VIEW_STATE_SETS; 1351 1352 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1353 static final int VIEW_STATE_SELECTED = 1 << 1; 1354 static final int VIEW_STATE_FOCUSED = 1 << 2; 1355 static final int VIEW_STATE_ENABLED = 1 << 3; 1356 static final int VIEW_STATE_PRESSED = 1 << 4; 1357 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1358 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1359 static final int VIEW_STATE_HOVERED = 1 << 7; 1360 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1361 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1362 1363 static final int[] VIEW_STATE_IDS = new int[] { 1364 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1365 R.attr.state_selected, VIEW_STATE_SELECTED, 1366 R.attr.state_focused, VIEW_STATE_FOCUSED, 1367 R.attr.state_enabled, VIEW_STATE_ENABLED, 1368 R.attr.state_pressed, VIEW_STATE_PRESSED, 1369 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1370 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1371 R.attr.state_hovered, VIEW_STATE_HOVERED, 1372 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1373 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1374 }; 1375 1376 static { 1377 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1378 throw new IllegalStateException( 1379 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1380 } 1381 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1382 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1383 int viewState = R.styleable.ViewDrawableStates[i]; 1384 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1385 if (VIEW_STATE_IDS[j] == viewState) { 1386 orderedIds[i * 2] = viewState; 1387 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1388 } 1389 } 1390 } 1391 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1392 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1393 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1394 int numBits = Integer.bitCount(i); 1395 int[] set = new int[numBits]; 1396 int pos = 0; 1397 for (int j = 0; j < orderedIds.length; j += 2) { 1398 if ((i & orderedIds[j+1]) != 0) { 1399 set[pos++] = orderedIds[j]; 1400 } 1401 } 1402 VIEW_STATE_SETS[i] = set; 1403 } 1404 1405 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1406 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1407 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1408 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1409 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1410 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1411 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1412 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1413 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1414 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1415 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1416 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1417 | VIEW_STATE_FOCUSED]; 1418 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1419 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1420 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1421 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1422 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1423 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1424 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1425 | VIEW_STATE_ENABLED]; 1426 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1427 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1428 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1429 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1430 | VIEW_STATE_ENABLED]; 1431 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1432 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1433 | VIEW_STATE_ENABLED]; 1434 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1435 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1436 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1437 1438 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1439 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1440 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1441 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1442 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1443 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1444 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1445 | VIEW_STATE_PRESSED]; 1446 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1447 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1448 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1449 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1450 | VIEW_STATE_PRESSED]; 1451 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1452 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1453 | VIEW_STATE_PRESSED]; 1454 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1455 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1456 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1457 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1458 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1459 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1460 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1461 | VIEW_STATE_PRESSED]; 1462 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1463 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1464 | VIEW_STATE_PRESSED]; 1465 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1466 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1467 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1468 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1469 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1470 | VIEW_STATE_PRESSED]; 1471 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1472 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1473 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1474 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1475 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1476 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1477 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1478 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1479 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1480 | VIEW_STATE_PRESSED]; 1481 } 1482 1483 /** 1484 * Accessibility event types that are dispatched for text population. 1485 */ 1486 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1487 AccessibilityEvent.TYPE_VIEW_CLICKED 1488 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1489 | AccessibilityEvent.TYPE_VIEW_SELECTED 1490 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1491 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1492 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1493 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1494 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1495 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1496 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1497 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1498 1499 /** 1500 * Temporary Rect currently for use in setBackground(). This will probably 1501 * be extended in the future to hold our own class with more than just 1502 * a Rect. :) 1503 */ 1504 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1505 1506 /** 1507 * Map used to store views' tags. 1508 */ 1509 private SparseArray<Object> mKeyedTags; 1510 1511 /** 1512 * The next available accessibility id. 1513 */ 1514 private static int sNextAccessibilityViewId; 1515 1516 /** 1517 * The animation currently associated with this view. 1518 * @hide 1519 */ 1520 protected Animation mCurrentAnimation = null; 1521 1522 /** 1523 * Width as measured during measure pass. 1524 * {@hide} 1525 */ 1526 @ViewDebug.ExportedProperty(category = "measurement") 1527 int mMeasuredWidth; 1528 1529 /** 1530 * Height as measured during measure pass. 1531 * {@hide} 1532 */ 1533 @ViewDebug.ExportedProperty(category = "measurement") 1534 int mMeasuredHeight; 1535 1536 /** 1537 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1538 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1539 * its display list. This flag, used only when hw accelerated, allows us to clear the 1540 * flag while retaining this information until it's needed (at getDisplayList() time and 1541 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1542 * 1543 * {@hide} 1544 */ 1545 boolean mRecreateDisplayList = false; 1546 1547 /** 1548 * The view's identifier. 1549 * {@hide} 1550 * 1551 * @see #setId(int) 1552 * @see #getId() 1553 */ 1554 @ViewDebug.ExportedProperty(resolveId = true) 1555 int mID = NO_ID; 1556 1557 /** 1558 * The stable ID of this view for accessibility purposes. 1559 */ 1560 int mAccessibilityViewId = NO_ID; 1561 1562 /** 1563 * @hide 1564 */ 1565 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1566 1567 /** 1568 * The view's tag. 1569 * {@hide} 1570 * 1571 * @see #setTag(Object) 1572 * @see #getTag() 1573 */ 1574 protected Object mTag; 1575 1576 // for mPrivateFlags: 1577 /** {@hide} */ 1578 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1579 /** {@hide} */ 1580 static final int PFLAG_FOCUSED = 0x00000002; 1581 /** {@hide} */ 1582 static final int PFLAG_SELECTED = 0x00000004; 1583 /** {@hide} */ 1584 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1585 /** {@hide} */ 1586 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1587 /** {@hide} */ 1588 static final int PFLAG_DRAWN = 0x00000020; 1589 /** 1590 * When this flag is set, this view is running an animation on behalf of its 1591 * children and should therefore not cancel invalidate requests, even if they 1592 * lie outside of this view's bounds. 1593 * 1594 * {@hide} 1595 */ 1596 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1597 /** {@hide} */ 1598 static final int PFLAG_SKIP_DRAW = 0x00000080; 1599 /** {@hide} */ 1600 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1601 /** {@hide} */ 1602 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1603 /** {@hide} */ 1604 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1605 /** {@hide} */ 1606 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1607 /** {@hide} */ 1608 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1609 /** {@hide} */ 1610 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1611 1612 private static final int PFLAG_PRESSED = 0x00004000; 1613 1614 /** {@hide} */ 1615 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1616 /** 1617 * Flag used to indicate that this view should be drawn once more (and only once 1618 * more) after its animation has completed. 1619 * {@hide} 1620 */ 1621 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1622 1623 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1624 1625 /** 1626 * Indicates that the View returned true when onSetAlpha() was called and that 1627 * the alpha must be restored. 1628 * {@hide} 1629 */ 1630 static final int PFLAG_ALPHA_SET = 0x00040000; 1631 1632 /** 1633 * Set by {@link #setScrollContainer(boolean)}. 1634 */ 1635 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1636 1637 /** 1638 * Set by {@link #setScrollContainer(boolean)}. 1639 */ 1640 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1641 1642 /** 1643 * View flag indicating whether this view was invalidated (fully or partially.) 1644 * 1645 * @hide 1646 */ 1647 static final int PFLAG_DIRTY = 0x00200000; 1648 1649 /** 1650 * View flag indicating whether this view was invalidated by an opaque 1651 * invalidate request. 1652 * 1653 * @hide 1654 */ 1655 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1656 1657 /** 1658 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1659 * 1660 * @hide 1661 */ 1662 static final int PFLAG_DIRTY_MASK = 0x00600000; 1663 1664 /** 1665 * Indicates whether the background is opaque. 1666 * 1667 * @hide 1668 */ 1669 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1670 1671 /** 1672 * Indicates whether the scrollbars are opaque. 1673 * 1674 * @hide 1675 */ 1676 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1677 1678 /** 1679 * Indicates whether the view is opaque. 1680 * 1681 * @hide 1682 */ 1683 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1684 1685 /** 1686 * Indicates a prepressed state; 1687 * the short time between ACTION_DOWN and recognizing 1688 * a 'real' press. Prepressed is used to recognize quick taps 1689 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1690 * 1691 * @hide 1692 */ 1693 private static final int PFLAG_PREPRESSED = 0x02000000; 1694 1695 /** 1696 * Indicates whether the view is temporarily detached. 1697 * 1698 * @hide 1699 */ 1700 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1701 1702 /** 1703 * Indicates that we should awaken scroll bars once attached 1704 * 1705 * @hide 1706 */ 1707 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1708 1709 /** 1710 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1711 * @hide 1712 */ 1713 private static final int PFLAG_HOVERED = 0x10000000; 1714 1715 /** 1716 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1717 * for transform operations 1718 * 1719 * @hide 1720 */ 1721 private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000; 1722 1723 /** {@hide} */ 1724 static final int PFLAG_ACTIVATED = 0x40000000; 1725 1726 /** 1727 * Indicates that this view was specifically invalidated, not just dirtied because some 1728 * child view was invalidated. The flag is used to determine when we need to recreate 1729 * a view's display list (as opposed to just returning a reference to its existing 1730 * display list). 1731 * 1732 * @hide 1733 */ 1734 static final int PFLAG_INVALIDATED = 0x80000000; 1735 1736 /** 1737 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1738 * 1739 * -------|-------|-------|-------| 1740 * PFLAG2_TEXT_ALIGNMENT_FLAGS[0] 1741 * PFLAG2_TEXT_DIRECTION_FLAGS[0] 1742 * 1 PFLAG2_DRAG_CAN_ACCEPT 1743 * 1 PFLAG2_DRAG_HOVERED 1744 * 1 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT 1745 * 11 PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1746 * 1 1 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT 1747 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1748 * 11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 1749 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1750 * 1 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT 1751 * 1 1 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT 1752 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1753 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1754 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1755 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1756 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1757 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1758 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1759 * 111 PFLAG2_TEXT_DIRECTION_MASK 1760 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1761 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1762 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1763 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1764 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1765 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1766 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1767 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1768 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1769 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1770 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1771 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1772 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1773 * 11 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1774 * 1 PFLAG2_HAS_TRANSIENT_STATE 1775 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1776 * 1 PFLAG2_ACCESSIBILITY_STATE_CHANGED 1777 * 1 PFLAG2_VIEW_QUICK_REJECTED 1778 * 1 PFLAG2_PADDING_RESOLVED 1779 * -------|-------|-------|-------| 1780 */ 1781 1782 /** 1783 * Indicates that this view has reported that it can accept the current drag's content. 1784 * Cleared when the drag operation concludes. 1785 * @hide 1786 */ 1787 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1788 1789 /** 1790 * Indicates that this view is currently directly under the drag location in a 1791 * drag-and-drop operation involving content that it can accept. Cleared when 1792 * the drag exits the view, or when the drag operation concludes. 1793 * @hide 1794 */ 1795 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1796 1797 /** 1798 * Horizontal layout direction of this view is from Left to Right. 1799 * Use with {@link #setLayoutDirection}. 1800 */ 1801 public static final int LAYOUT_DIRECTION_LTR = 0; 1802 1803 /** 1804 * Horizontal layout direction of this view is from Right to Left. 1805 * Use with {@link #setLayoutDirection}. 1806 */ 1807 public static final int LAYOUT_DIRECTION_RTL = 1; 1808 1809 /** 1810 * Horizontal layout direction of this view is inherited from its parent. 1811 * Use with {@link #setLayoutDirection}. 1812 */ 1813 public static final int LAYOUT_DIRECTION_INHERIT = 2; 1814 1815 /** 1816 * Horizontal layout direction of this view is from deduced from the default language 1817 * script for the locale. Use with {@link #setLayoutDirection}. 1818 */ 1819 public static final int LAYOUT_DIRECTION_LOCALE = 3; 1820 1821 /** 1822 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1823 * @hide 1824 */ 1825 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1826 1827 /** 1828 * Mask for use with private flags indicating bits used for horizontal layout direction. 1829 * @hide 1830 */ 1831 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1832 1833 /** 1834 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1835 * right-to-left direction. 1836 * @hide 1837 */ 1838 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1839 1840 /** 1841 * Indicates whether the view horizontal layout direction has been resolved. 1842 * @hide 1843 */ 1844 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1845 1846 /** 1847 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1848 * @hide 1849 */ 1850 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1851 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1852 1853 /* 1854 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1855 * flag value. 1856 * @hide 1857 */ 1858 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1859 LAYOUT_DIRECTION_LTR, 1860 LAYOUT_DIRECTION_RTL, 1861 LAYOUT_DIRECTION_INHERIT, 1862 LAYOUT_DIRECTION_LOCALE 1863 }; 1864 1865 /** 1866 * Default horizontal layout direction. 1867 * @hide 1868 */ 1869 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1870 1871 /** 1872 * Indicates that the view is tracking some sort of transient state 1873 * that the app should not need to be aware of, but that the framework 1874 * should take special care to preserve. 1875 * 1876 * @hide 1877 */ 1878 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22; 1879 1880 /** 1881 * Text direction is inherited thru {@link ViewGroup} 1882 */ 1883 public static final int TEXT_DIRECTION_INHERIT = 0; 1884 1885 /** 1886 * Text direction is using "first strong algorithm". The first strong directional character 1887 * determines the paragraph direction. If there is no strong directional character, the 1888 * paragraph direction is the view's resolved layout direction. 1889 */ 1890 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1891 1892 /** 1893 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1894 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1895 * If there are neither, the paragraph direction is the view's resolved layout direction. 1896 */ 1897 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1898 1899 /** 1900 * Text direction is forced to LTR. 1901 */ 1902 public static final int TEXT_DIRECTION_LTR = 3; 1903 1904 /** 1905 * Text direction is forced to RTL. 1906 */ 1907 public static final int TEXT_DIRECTION_RTL = 4; 1908 1909 /** 1910 * Text direction is coming from the system Locale. 1911 */ 1912 public static final int TEXT_DIRECTION_LOCALE = 5; 1913 1914 /** 1915 * Default text direction is inherited 1916 */ 1917 public static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 1918 1919 /** 1920 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 1921 * @hide 1922 */ 1923 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 1924 1925 /** 1926 * Mask for use with private flags indicating bits used for text direction. 1927 * @hide 1928 */ 1929 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 1930 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1931 1932 /** 1933 * Array of text direction flags for mapping attribute "textDirection" to correct 1934 * flag value. 1935 * @hide 1936 */ 1937 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 1938 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1939 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1940 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1941 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1942 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1943 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1944 }; 1945 1946 /** 1947 * Indicates whether the view text direction has been resolved. 1948 * @hide 1949 */ 1950 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 1951 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1952 1953 /** 1954 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1955 * @hide 1956 */ 1957 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 1958 1959 /** 1960 * Mask for use with private flags indicating bits used for resolved text direction. 1961 * @hide 1962 */ 1963 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 1964 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1965 1966 /** 1967 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 1968 * @hide 1969 */ 1970 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 1971 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1972 1973 /* 1974 * Default text alignment. The text alignment of this View is inherited from its parent. 1975 * Use with {@link #setTextAlignment(int)} 1976 */ 1977 public static final int TEXT_ALIGNMENT_INHERIT = 0; 1978 1979 /** 1980 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 1981 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 1982 * 1983 * Use with {@link #setTextAlignment(int)} 1984 */ 1985 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 1986 1987 /** 1988 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 1989 * 1990 * Use with {@link #setTextAlignment(int)} 1991 */ 1992 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 1993 1994 /** 1995 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 1996 * 1997 * Use with {@link #setTextAlignment(int)} 1998 */ 1999 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2000 2001 /** 2002 * Center the paragraph, e.g. ALIGN_CENTER. 2003 * 2004 * Use with {@link #setTextAlignment(int)} 2005 */ 2006 public static final int TEXT_ALIGNMENT_CENTER = 4; 2007 2008 /** 2009 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2010 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2011 * 2012 * Use with {@link #setTextAlignment(int)} 2013 */ 2014 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2015 2016 /** 2017 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2018 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2019 * 2020 * Use with {@link #setTextAlignment(int)} 2021 */ 2022 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2023 2024 /** 2025 * Default text alignment is inherited 2026 */ 2027 public static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2028 2029 /** 2030 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2031 * @hide 2032 */ 2033 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2034 2035 /** 2036 * Mask for use with private flags indicating bits used for text alignment. 2037 * @hide 2038 */ 2039 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2040 2041 /** 2042 * Array of text direction flags for mapping attribute "textAlignment" to correct 2043 * flag value. 2044 * @hide 2045 */ 2046 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2047 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2048 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2049 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2050 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2051 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2052 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2053 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2054 }; 2055 2056 /** 2057 * Indicates whether the view text alignment has been resolved. 2058 * @hide 2059 */ 2060 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2061 2062 /** 2063 * Bit shift to get the resolved text alignment. 2064 * @hide 2065 */ 2066 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2067 2068 /** 2069 * Mask for use with private flags indicating bits used for text alignment. 2070 * @hide 2071 */ 2072 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2073 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2074 2075 /** 2076 * Indicates whether if the view text alignment has been resolved to gravity 2077 */ 2078 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2079 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2080 2081 // Accessiblity constants for mPrivateFlags2 2082 2083 /** 2084 * Shift for the bits in {@link #mPrivateFlags2} related to the 2085 * "importantForAccessibility" attribute. 2086 */ 2087 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2088 2089 /** 2090 * Automatically determine whether a view is important for accessibility. 2091 */ 2092 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2093 2094 /** 2095 * The view is important for accessibility. 2096 */ 2097 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2098 2099 /** 2100 * The view is not important for accessibility. 2101 */ 2102 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2103 2104 /** 2105 * The default whether the view is important for accessibility. 2106 */ 2107 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2108 2109 /** 2110 * Mask for obtainig the bits which specify how to determine 2111 * whether a view is important for accessibility. 2112 */ 2113 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2114 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO) 2115 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2116 2117 /** 2118 * Flag indicating whether a view has accessibility focus. 2119 */ 2120 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x00000040 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2121 2122 /** 2123 * Flag indicating whether a view state for accessibility has changed. 2124 */ 2125 static final int PFLAG2_ACCESSIBILITY_STATE_CHANGED = 0x00000080 2126 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2127 2128 /** 2129 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2130 * is used to check whether later changes to the view's transform should invalidate the 2131 * view to force the quickReject test to run again. 2132 */ 2133 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2134 2135 /** 2136 * Flag indicating that start/end padding has been resolved into left/right padding 2137 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2138 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2139 * during measurement. In some special cases this is required such as when an adapter-based 2140 * view measures prospective children without attaching them to a window. 2141 */ 2142 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2143 2144 /** 2145 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2146 */ 2147 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2148 2149 /** 2150 * Group of bits indicating that RTL properties resolution is done. 2151 */ 2152 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2153 PFLAG2_TEXT_DIRECTION_RESOLVED | 2154 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2155 PFLAG2_PADDING_RESOLVED | 2156 PFLAG2_DRAWABLE_RESOLVED; 2157 2158 // There are a couple of flags left in mPrivateFlags2 2159 2160 /* End of masks for mPrivateFlags2 */ 2161 2162 /* Masks for mPrivateFlags3 */ 2163 2164 /** 2165 * Flag indicating that view has a transform animation set on it. This is used to track whether 2166 * an animation is cleared between successive frames, in order to tell the associated 2167 * DisplayList to clear its animation matrix. 2168 */ 2169 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2170 2171 /** 2172 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2173 * animation is cleared between successive frames, in order to tell the associated 2174 * DisplayList to restore its alpha value. 2175 */ 2176 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2177 2178 2179 /* End of masks for mPrivateFlags3 */ 2180 2181 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2182 2183 /** 2184 * Always allow a user to over-scroll this view, provided it is a 2185 * view that can scroll. 2186 * 2187 * @see #getOverScrollMode() 2188 * @see #setOverScrollMode(int) 2189 */ 2190 public static final int OVER_SCROLL_ALWAYS = 0; 2191 2192 /** 2193 * Allow a user to over-scroll this view only if the content is large 2194 * enough to meaningfully scroll, provided it is a view that can scroll. 2195 * 2196 * @see #getOverScrollMode() 2197 * @see #setOverScrollMode(int) 2198 */ 2199 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2200 2201 /** 2202 * Never allow a user to over-scroll this view. 2203 * 2204 * @see #getOverScrollMode() 2205 * @see #setOverScrollMode(int) 2206 */ 2207 public static final int OVER_SCROLL_NEVER = 2; 2208 2209 /** 2210 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2211 * requested the system UI (status bar) to be visible (the default). 2212 * 2213 * @see #setSystemUiVisibility(int) 2214 */ 2215 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2216 2217 /** 2218 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2219 * system UI to enter an unobtrusive "low profile" mode. 2220 * 2221 * <p>This is for use in games, book readers, video players, or any other 2222 * "immersive" application where the usual system chrome is deemed too distracting. 2223 * 2224 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2225 * 2226 * @see #setSystemUiVisibility(int) 2227 */ 2228 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2229 2230 /** 2231 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2232 * system navigation be temporarily hidden. 2233 * 2234 * <p>This is an even less obtrusive state than that called for by 2235 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2236 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2237 * those to disappear. This is useful (in conjunction with the 2238 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2239 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2240 * window flags) for displaying content using every last pixel on the display. 2241 * 2242 * <p>There is a limitation: because navigation controls are so important, the least user 2243 * interaction will cause them to reappear immediately. When this happens, both 2244 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2245 * so that both elements reappear at the same time. 2246 * 2247 * @see #setSystemUiVisibility(int) 2248 */ 2249 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2250 2251 /** 2252 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2253 * into the normal fullscreen mode so that its content can take over the screen 2254 * while still allowing the user to interact with the application. 2255 * 2256 * <p>This has the same visual effect as 2257 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2258 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2259 * meaning that non-critical screen decorations (such as the status bar) will be 2260 * hidden while the user is in the View's window, focusing the experience on 2261 * that content. Unlike the window flag, if you are using ActionBar in 2262 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2263 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2264 * hide the action bar. 2265 * 2266 * <p>This approach to going fullscreen is best used over the window flag when 2267 * it is a transient state -- that is, the application does this at certain 2268 * points in its user interaction where it wants to allow the user to focus 2269 * on content, but not as a continuous state. For situations where the application 2270 * would like to simply stay full screen the entire time (such as a game that 2271 * wants to take over the screen), the 2272 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2273 * is usually a better approach. The state set here will be removed by the system 2274 * in various situations (such as the user moving to another application) like 2275 * the other system UI states. 2276 * 2277 * <p>When using this flag, the application should provide some easy facility 2278 * for the user to go out of it. A common example would be in an e-book 2279 * reader, where tapping on the screen brings back whatever screen and UI 2280 * decorations that had been hidden while the user was immersed in reading 2281 * the book. 2282 * 2283 * @see #setSystemUiVisibility(int) 2284 */ 2285 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2286 2287 /** 2288 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2289 * flags, we would like a stable view of the content insets given to 2290 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2291 * will always represent the worst case that the application can expect 2292 * as a continuous state. In the stock Android UI this is the space for 2293 * the system bar, nav bar, and status bar, but not more transient elements 2294 * such as an input method. 2295 * 2296 * The stable layout your UI sees is based on the system UI modes you can 2297 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2298 * then you will get a stable layout for changes of the 2299 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2300 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2301 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2302 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2303 * with a stable layout. (Note that you should avoid using 2304 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2305 * 2306 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2307 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2308 * then a hidden status bar will be considered a "stable" state for purposes 2309 * here. This allows your UI to continually hide the status bar, while still 2310 * using the system UI flags to hide the action bar while still retaining 2311 * a stable layout. Note that changing the window fullscreen flag will never 2312 * provide a stable layout for a clean transition. 2313 * 2314 * <p>If you are using ActionBar in 2315 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2316 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2317 * insets it adds to those given to the application. 2318 */ 2319 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2320 2321 /** 2322 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2323 * to be layed out as if it has requested 2324 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2325 * allows it to avoid artifacts when switching in and out of that mode, at 2326 * the expense that some of its user interface may be covered by screen 2327 * decorations when they are shown. You can perform layout of your inner 2328 * UI elements to account for the navagation system UI through the 2329 * {@link #fitSystemWindows(Rect)} method. 2330 */ 2331 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2332 2333 /** 2334 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2335 * to be layed out as if it has requested 2336 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2337 * allows it to avoid artifacts when switching in and out of that mode, at 2338 * the expense that some of its user interface may be covered by screen 2339 * decorations when they are shown. You can perform layout of your inner 2340 * UI elements to account for non-fullscreen system UI through the 2341 * {@link #fitSystemWindows(Rect)} method. 2342 */ 2343 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2344 2345 /** 2346 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2347 */ 2348 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2349 2350 /** 2351 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2352 */ 2353 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2354 2355 /** 2356 * @hide 2357 * 2358 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2359 * out of the public fields to keep the undefined bits out of the developer's way. 2360 * 2361 * Flag to make the status bar not expandable. Unless you also 2362 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2363 */ 2364 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2365 2366 /** 2367 * @hide 2368 * 2369 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2370 * out of the public fields to keep the undefined bits out of the developer's way. 2371 * 2372 * Flag to hide notification icons and scrolling ticker text. 2373 */ 2374 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2375 2376 /** 2377 * @hide 2378 * 2379 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2380 * out of the public fields to keep the undefined bits out of the developer's way. 2381 * 2382 * Flag to disable incoming notification alerts. This will not block 2383 * icons, but it will block sound, vibrating and other visual or aural notifications. 2384 */ 2385 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2386 2387 /** 2388 * @hide 2389 * 2390 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2391 * out of the public fields to keep the undefined bits out of the developer's way. 2392 * 2393 * Flag to hide only the scrolling ticker. Note that 2394 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2395 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2396 */ 2397 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2398 2399 /** 2400 * @hide 2401 * 2402 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2403 * out of the public fields to keep the undefined bits out of the developer's way. 2404 * 2405 * Flag to hide the center system info area. 2406 */ 2407 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2408 2409 /** 2410 * @hide 2411 * 2412 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2413 * out of the public fields to keep the undefined bits out of the developer's way. 2414 * 2415 * Flag to hide only the home button. Don't use this 2416 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2417 */ 2418 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2419 2420 /** 2421 * @hide 2422 * 2423 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2424 * out of the public fields to keep the undefined bits out of the developer's way. 2425 * 2426 * Flag to hide only the back button. Don't use this 2427 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2428 */ 2429 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2430 2431 /** 2432 * @hide 2433 * 2434 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2435 * out of the public fields to keep the undefined bits out of the developer's way. 2436 * 2437 * Flag to hide only the clock. You might use this if your activity has 2438 * its own clock making the status bar's clock redundant. 2439 */ 2440 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2441 2442 /** 2443 * @hide 2444 * 2445 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2446 * out of the public fields to keep the undefined bits out of the developer's way. 2447 * 2448 * Flag to hide only the recent apps button. Don't use this 2449 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2450 */ 2451 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2452 2453 /** 2454 * @hide 2455 */ 2456 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2457 2458 /** 2459 * These are the system UI flags that can be cleared by events outside 2460 * of an application. Currently this is just the ability to tap on the 2461 * screen while hiding the navigation bar to have it return. 2462 * @hide 2463 */ 2464 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2465 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2466 | SYSTEM_UI_FLAG_FULLSCREEN; 2467 2468 /** 2469 * Flags that can impact the layout in relation to system UI. 2470 */ 2471 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2472 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2473 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2474 2475 /** 2476 * Find views that render the specified text. 2477 * 2478 * @see #findViewsWithText(ArrayList, CharSequence, int) 2479 */ 2480 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2481 2482 /** 2483 * Find find views that contain the specified content description. 2484 * 2485 * @see #findViewsWithText(ArrayList, CharSequence, int) 2486 */ 2487 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2488 2489 /** 2490 * Find views that contain {@link AccessibilityNodeProvider}. Such 2491 * a View is a root of virtual view hierarchy and may contain the searched 2492 * text. If this flag is set Views with providers are automatically 2493 * added and it is a responsibility of the client to call the APIs of 2494 * the provider to determine whether the virtual tree rooted at this View 2495 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2496 * represeting the virtual views with this text. 2497 * 2498 * @see #findViewsWithText(ArrayList, CharSequence, int) 2499 * 2500 * @hide 2501 */ 2502 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2503 2504 /** 2505 * The undefined cursor position. 2506 */ 2507 private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2508 2509 /** 2510 * Indicates that the screen has changed state and is now off. 2511 * 2512 * @see #onScreenStateChanged(int) 2513 */ 2514 public static final int SCREEN_STATE_OFF = 0x0; 2515 2516 /** 2517 * Indicates that the screen has changed state and is now on. 2518 * 2519 * @see #onScreenStateChanged(int) 2520 */ 2521 public static final int SCREEN_STATE_ON = 0x1; 2522 2523 /** 2524 * Controls the over-scroll mode for this view. 2525 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2526 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2527 * and {@link #OVER_SCROLL_NEVER}. 2528 */ 2529 private int mOverScrollMode; 2530 2531 /** 2532 * The parent this view is attached to. 2533 * {@hide} 2534 * 2535 * @see #getParent() 2536 */ 2537 protected ViewParent mParent; 2538 2539 /** 2540 * {@hide} 2541 */ 2542 AttachInfo mAttachInfo; 2543 2544 /** 2545 * {@hide} 2546 */ 2547 @ViewDebug.ExportedProperty(flagMapping = { 2548 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2549 name = "FORCE_LAYOUT"), 2550 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2551 name = "LAYOUT_REQUIRED"), 2552 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2553 name = "DRAWING_CACHE_INVALID", outputIf = false), 2554 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2555 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2556 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2557 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2558 }) 2559 int mPrivateFlags; 2560 int mPrivateFlags2; 2561 int mPrivateFlags3; 2562 2563 /** 2564 * This view's request for the visibility of the status bar. 2565 * @hide 2566 */ 2567 @ViewDebug.ExportedProperty(flagMapping = { 2568 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2569 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2570 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2571 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2572 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2573 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2574 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2575 equals = SYSTEM_UI_FLAG_VISIBLE, 2576 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2577 }) 2578 int mSystemUiVisibility; 2579 2580 /** 2581 * Reference count for transient state. 2582 * @see #setHasTransientState(boolean) 2583 */ 2584 int mTransientStateCount = 0; 2585 2586 /** 2587 * Count of how many windows this view has been attached to. 2588 */ 2589 int mWindowAttachCount; 2590 2591 /** 2592 * The layout parameters associated with this view and used by the parent 2593 * {@link android.view.ViewGroup} to determine how this view should be 2594 * laid out. 2595 * {@hide} 2596 */ 2597 protected ViewGroup.LayoutParams mLayoutParams; 2598 2599 /** 2600 * The view flags hold various views states. 2601 * {@hide} 2602 */ 2603 @ViewDebug.ExportedProperty 2604 int mViewFlags; 2605 2606 static class TransformationInfo { 2607 /** 2608 * The transform matrix for the View. This transform is calculated internally 2609 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2610 * is used by default. Do *not* use this variable directly; instead call 2611 * getMatrix(), which will automatically recalculate the matrix if necessary 2612 * to get the correct matrix based on the latest rotation and scale properties. 2613 */ 2614 private final Matrix mMatrix = new Matrix(); 2615 2616 /** 2617 * The transform matrix for the View. This transform is calculated internally 2618 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2619 * is used by default. Do *not* use this variable directly; instead call 2620 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2621 * to get the correct matrix based on the latest rotation and scale properties. 2622 */ 2623 private Matrix mInverseMatrix; 2624 2625 /** 2626 * An internal variable that tracks whether we need to recalculate the 2627 * transform matrix, based on whether the rotation or scaleX/Y properties 2628 * have changed since the matrix was last calculated. 2629 */ 2630 boolean mMatrixDirty = false; 2631 2632 /** 2633 * An internal variable that tracks whether we need to recalculate the 2634 * transform matrix, based on whether the rotation or scaleX/Y properties 2635 * have changed since the matrix was last calculated. 2636 */ 2637 private boolean mInverseMatrixDirty = true; 2638 2639 /** 2640 * A variable that tracks whether we need to recalculate the 2641 * transform matrix, based on whether the rotation or scaleX/Y properties 2642 * have changed since the matrix was last calculated. This variable 2643 * is only valid after a call to updateMatrix() or to a function that 2644 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2645 */ 2646 private boolean mMatrixIsIdentity = true; 2647 2648 /** 2649 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2650 */ 2651 private Camera mCamera = null; 2652 2653 /** 2654 * This matrix is used when computing the matrix for 3D rotations. 2655 */ 2656 private Matrix matrix3D = null; 2657 2658 /** 2659 * These prev values are used to recalculate a centered pivot point when necessary. The 2660 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2661 * set), so thes values are only used then as well. 2662 */ 2663 private int mPrevWidth = -1; 2664 private int mPrevHeight = -1; 2665 2666 /** 2667 * The degrees rotation around the vertical axis through the pivot point. 2668 */ 2669 @ViewDebug.ExportedProperty 2670 float mRotationY = 0f; 2671 2672 /** 2673 * The degrees rotation around the horizontal axis through the pivot point. 2674 */ 2675 @ViewDebug.ExportedProperty 2676 float mRotationX = 0f; 2677 2678 /** 2679 * The degrees rotation around the pivot point. 2680 */ 2681 @ViewDebug.ExportedProperty 2682 float mRotation = 0f; 2683 2684 /** 2685 * The amount of translation of the object away from its left property (post-layout). 2686 */ 2687 @ViewDebug.ExportedProperty 2688 float mTranslationX = 0f; 2689 2690 /** 2691 * The amount of translation of the object away from its top property (post-layout). 2692 */ 2693 @ViewDebug.ExportedProperty 2694 float mTranslationY = 0f; 2695 2696 /** 2697 * The amount of scale in the x direction around the pivot point. A 2698 * value of 1 means no scaling is applied. 2699 */ 2700 @ViewDebug.ExportedProperty 2701 float mScaleX = 1f; 2702 2703 /** 2704 * The amount of scale in the y direction around the pivot point. A 2705 * value of 1 means no scaling is applied. 2706 */ 2707 @ViewDebug.ExportedProperty 2708 float mScaleY = 1f; 2709 2710 /** 2711 * The x location of the point around which the view is rotated and scaled. 2712 */ 2713 @ViewDebug.ExportedProperty 2714 float mPivotX = 0f; 2715 2716 /** 2717 * The y location of the point around which the view is rotated and scaled. 2718 */ 2719 @ViewDebug.ExportedProperty 2720 float mPivotY = 0f; 2721 2722 /** 2723 * The opacity of the View. This is a value from 0 to 1, where 0 means 2724 * completely transparent and 1 means completely opaque. 2725 */ 2726 @ViewDebug.ExportedProperty 2727 float mAlpha = 1f; 2728 } 2729 2730 TransformationInfo mTransformationInfo; 2731 2732 private boolean mLastIsOpaque; 2733 2734 /** 2735 * Convenience value to check for float values that are close enough to zero to be considered 2736 * zero. 2737 */ 2738 private static final float NONZERO_EPSILON = .001f; 2739 2740 /** 2741 * The distance in pixels from the left edge of this view's parent 2742 * to the left edge of this view. 2743 * {@hide} 2744 */ 2745 @ViewDebug.ExportedProperty(category = "layout") 2746 protected int mLeft; 2747 /** 2748 * The distance in pixels from the left edge of this view's parent 2749 * to the right edge of this view. 2750 * {@hide} 2751 */ 2752 @ViewDebug.ExportedProperty(category = "layout") 2753 protected int mRight; 2754 /** 2755 * The distance in pixels from the top edge of this view's parent 2756 * to the top edge of this view. 2757 * {@hide} 2758 */ 2759 @ViewDebug.ExportedProperty(category = "layout") 2760 protected int mTop; 2761 /** 2762 * The distance in pixels from the top edge of this view's parent 2763 * to the bottom edge of this view. 2764 * {@hide} 2765 */ 2766 @ViewDebug.ExportedProperty(category = "layout") 2767 protected int mBottom; 2768 2769 /** 2770 * The offset, in pixels, by which the content of this view is scrolled 2771 * horizontally. 2772 * {@hide} 2773 */ 2774 @ViewDebug.ExportedProperty(category = "scrolling") 2775 protected int mScrollX; 2776 /** 2777 * The offset, in pixels, by which the content of this view is scrolled 2778 * vertically. 2779 * {@hide} 2780 */ 2781 @ViewDebug.ExportedProperty(category = "scrolling") 2782 protected int mScrollY; 2783 2784 /** 2785 * The left padding in pixels, that is the distance in pixels between the 2786 * left edge of this view and the left edge of its content. 2787 * {@hide} 2788 */ 2789 @ViewDebug.ExportedProperty(category = "padding") 2790 protected int mPaddingLeft = 0; 2791 /** 2792 * The right padding in pixels, that is the distance in pixels between the 2793 * right edge of this view and the right edge of its content. 2794 * {@hide} 2795 */ 2796 @ViewDebug.ExportedProperty(category = "padding") 2797 protected int mPaddingRight = 0; 2798 /** 2799 * The top padding in pixels, that is the distance in pixels between the 2800 * top edge of this view and the top edge of its content. 2801 * {@hide} 2802 */ 2803 @ViewDebug.ExportedProperty(category = "padding") 2804 protected int mPaddingTop; 2805 /** 2806 * The bottom padding in pixels, that is the distance in pixels between the 2807 * bottom edge of this view and the bottom edge of its content. 2808 * {@hide} 2809 */ 2810 @ViewDebug.ExportedProperty(category = "padding") 2811 protected int mPaddingBottom; 2812 2813 /** 2814 * The layout insets in pixels, that is the distance in pixels between the 2815 * visible edges of this view its bounds. 2816 */ 2817 private Insets mLayoutInsets; 2818 2819 /** 2820 * Briefly describes the view and is primarily used for accessibility support. 2821 */ 2822 private CharSequence mContentDescription; 2823 2824 /** 2825 * Specifies the id of a view for which this view serves as a label for 2826 * accessibility purposes. 2827 */ 2828 private int mLabelForId = View.NO_ID; 2829 2830 /** 2831 * Predicate for matching labeled view id with its label for 2832 * accessibility purposes. 2833 */ 2834 private MatchLabelForPredicate mMatchLabelForPredicate; 2835 2836 /** 2837 * Predicate for matching a view by its id. 2838 */ 2839 private MatchIdPredicate mMatchIdPredicate; 2840 2841 /** 2842 * Cache the paddingRight set by the user to append to the scrollbar's size. 2843 * 2844 * @hide 2845 */ 2846 @ViewDebug.ExportedProperty(category = "padding") 2847 protected int mUserPaddingRight; 2848 2849 /** 2850 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2851 * 2852 * @hide 2853 */ 2854 @ViewDebug.ExportedProperty(category = "padding") 2855 protected int mUserPaddingBottom; 2856 2857 /** 2858 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2859 * 2860 * @hide 2861 */ 2862 @ViewDebug.ExportedProperty(category = "padding") 2863 protected int mUserPaddingLeft; 2864 2865 /** 2866 * Cache the paddingStart set by the user to append to the scrollbar's size. 2867 * 2868 */ 2869 @ViewDebug.ExportedProperty(category = "padding") 2870 int mUserPaddingStart; 2871 2872 /** 2873 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2874 * 2875 */ 2876 @ViewDebug.ExportedProperty(category = "padding") 2877 int mUserPaddingEnd; 2878 2879 /** 2880 * Cache initial left padding. 2881 * 2882 * @hide 2883 */ 2884 int mUserPaddingLeftInitial = 0; 2885 2886 /** 2887 * Cache initial right padding. 2888 * 2889 * @hide 2890 */ 2891 int mUserPaddingRightInitial = 0; 2892 2893 /** 2894 * Default undefined padding 2895 */ 2896 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 2897 2898 /** 2899 * @hide 2900 */ 2901 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2902 /** 2903 * @hide 2904 */ 2905 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2906 2907 private Drawable mBackground; 2908 2909 private int mBackgroundResource; 2910 private boolean mBackgroundSizeChanged; 2911 2912 static class ListenerInfo { 2913 /** 2914 * Listener used to dispatch focus change events. 2915 * This field should be made private, so it is hidden from the SDK. 2916 * {@hide} 2917 */ 2918 protected OnFocusChangeListener mOnFocusChangeListener; 2919 2920 /** 2921 * Listeners for layout change events. 2922 */ 2923 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2924 2925 /** 2926 * Listeners for attach events. 2927 */ 2928 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2929 2930 /** 2931 * Listener used to dispatch click events. 2932 * This field should be made private, so it is hidden from the SDK. 2933 * {@hide} 2934 */ 2935 public OnClickListener mOnClickListener; 2936 2937 /** 2938 * Listener used to dispatch long click events. 2939 * This field should be made private, so it is hidden from the SDK. 2940 * {@hide} 2941 */ 2942 protected OnLongClickListener mOnLongClickListener; 2943 2944 /** 2945 * Listener used to build the context menu. 2946 * This field should be made private, so it is hidden from the SDK. 2947 * {@hide} 2948 */ 2949 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2950 2951 private OnKeyListener mOnKeyListener; 2952 2953 private OnTouchListener mOnTouchListener; 2954 2955 private OnHoverListener mOnHoverListener; 2956 2957 private OnGenericMotionListener mOnGenericMotionListener; 2958 2959 private OnDragListener mOnDragListener; 2960 2961 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2962 } 2963 2964 ListenerInfo mListenerInfo; 2965 2966 /** 2967 * The application environment this view lives in. 2968 * This field should be made private, so it is hidden from the SDK. 2969 * {@hide} 2970 */ 2971 protected Context mContext; 2972 2973 private final Resources mResources; 2974 2975 private ScrollabilityCache mScrollCache; 2976 2977 private int[] mDrawableState = null; 2978 2979 /** 2980 * Set to true when drawing cache is enabled and cannot be created. 2981 * 2982 * @hide 2983 */ 2984 public boolean mCachingFailed; 2985 2986 private Bitmap mDrawingCache; 2987 private Bitmap mUnscaledDrawingCache; 2988 private HardwareLayer mHardwareLayer; 2989 DisplayList mDisplayList; 2990 2991 /** 2992 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2993 * the user may specify which view to go to next. 2994 */ 2995 private int mNextFocusLeftId = View.NO_ID; 2996 2997 /** 2998 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2999 * the user may specify which view to go to next. 3000 */ 3001 private int mNextFocusRightId = View.NO_ID; 3002 3003 /** 3004 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3005 * the user may specify which view to go to next. 3006 */ 3007 private int mNextFocusUpId = View.NO_ID; 3008 3009 /** 3010 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3011 * the user may specify which view to go to next. 3012 */ 3013 private int mNextFocusDownId = View.NO_ID; 3014 3015 /** 3016 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3017 * the user may specify which view to go to next. 3018 */ 3019 int mNextFocusForwardId = View.NO_ID; 3020 3021 private CheckForLongPress mPendingCheckForLongPress; 3022 private CheckForTap mPendingCheckForTap = null; 3023 private PerformClick mPerformClick; 3024 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3025 3026 private UnsetPressedState mUnsetPressedState; 3027 3028 /** 3029 * Whether the long press's action has been invoked. The tap's action is invoked on the 3030 * up event while a long press is invoked as soon as the long press duration is reached, so 3031 * a long press could be performed before the tap is checked, in which case the tap's action 3032 * should not be invoked. 3033 */ 3034 private boolean mHasPerformedLongPress; 3035 3036 /** 3037 * The minimum height of the view. We'll try our best to have the height 3038 * of this view to at least this amount. 3039 */ 3040 @ViewDebug.ExportedProperty(category = "measurement") 3041 private int mMinHeight; 3042 3043 /** 3044 * The minimum width of the view. We'll try our best to have the width 3045 * of this view to at least this amount. 3046 */ 3047 @ViewDebug.ExportedProperty(category = "measurement") 3048 private int mMinWidth; 3049 3050 /** 3051 * The delegate to handle touch events that are physically in this view 3052 * but should be handled by another view. 3053 */ 3054 private TouchDelegate mTouchDelegate = null; 3055 3056 /** 3057 * Solid color to use as a background when creating the drawing cache. Enables 3058 * the cache to use 16 bit bitmaps instead of 32 bit. 3059 */ 3060 private int mDrawingCacheBackgroundColor = 0; 3061 3062 /** 3063 * Special tree observer used when mAttachInfo is null. 3064 */ 3065 private ViewTreeObserver mFloatingTreeObserver; 3066 3067 /** 3068 * Cache the touch slop from the context that created the view. 3069 */ 3070 private int mTouchSlop; 3071 3072 /** 3073 * Object that handles automatic animation of view properties. 3074 */ 3075 private ViewPropertyAnimator mAnimator = null; 3076 3077 /** 3078 * Flag indicating that a drag can cross window boundaries. When 3079 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3080 * with this flag set, all visible applications will be able to participate 3081 * in the drag operation and receive the dragged content. 3082 * 3083 * @hide 3084 */ 3085 public static final int DRAG_FLAG_GLOBAL = 1; 3086 3087 /** 3088 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3089 */ 3090 private float mVerticalScrollFactor; 3091 3092 /** 3093 * Position of the vertical scroll bar. 3094 */ 3095 private int mVerticalScrollbarPosition; 3096 3097 /** 3098 * Position the scroll bar at the default position as determined by the system. 3099 */ 3100 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3101 3102 /** 3103 * Position the scroll bar along the left edge. 3104 */ 3105 public static final int SCROLLBAR_POSITION_LEFT = 1; 3106 3107 /** 3108 * Position the scroll bar along the right edge. 3109 */ 3110 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3111 3112 /** 3113 * Indicates that the view does not have a layer. 3114 * 3115 * @see #getLayerType() 3116 * @see #setLayerType(int, android.graphics.Paint) 3117 * @see #LAYER_TYPE_SOFTWARE 3118 * @see #LAYER_TYPE_HARDWARE 3119 */ 3120 public static final int LAYER_TYPE_NONE = 0; 3121 3122 /** 3123 * <p>Indicates that the view has a software layer. A software layer is backed 3124 * by a bitmap and causes the view to be rendered using Android's software 3125 * rendering pipeline, even if hardware acceleration is enabled.</p> 3126 * 3127 * <p>Software layers have various usages:</p> 3128 * <p>When the application is not using hardware acceleration, a software layer 3129 * is useful to apply a specific color filter and/or blending mode and/or 3130 * translucency to a view and all its children.</p> 3131 * <p>When the application is using hardware acceleration, a software layer 3132 * is useful to render drawing primitives not supported by the hardware 3133 * accelerated pipeline. It can also be used to cache a complex view tree 3134 * into a texture and reduce the complexity of drawing operations. For instance, 3135 * when animating a complex view tree with a translation, a software layer can 3136 * be used to render the view tree only once.</p> 3137 * <p>Software layers should be avoided when the affected view tree updates 3138 * often. Every update will require to re-render the software layer, which can 3139 * potentially be slow (particularly when hardware acceleration is turned on 3140 * since the layer will have to be uploaded into a hardware texture after every 3141 * update.)</p> 3142 * 3143 * @see #getLayerType() 3144 * @see #setLayerType(int, android.graphics.Paint) 3145 * @see #LAYER_TYPE_NONE 3146 * @see #LAYER_TYPE_HARDWARE 3147 */ 3148 public static final int LAYER_TYPE_SOFTWARE = 1; 3149 3150 /** 3151 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3152 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3153 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3154 * rendering pipeline, but only if hardware acceleration is turned on for the 3155 * view hierarchy. When hardware acceleration is turned off, hardware layers 3156 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3157 * 3158 * <p>A hardware layer is useful to apply a specific color filter and/or 3159 * blending mode and/or translucency to a view and all its children.</p> 3160 * <p>A hardware layer can be used to cache a complex view tree into a 3161 * texture and reduce the complexity of drawing operations. For instance, 3162 * when animating a complex view tree with a translation, a hardware layer can 3163 * be used to render the view tree only once.</p> 3164 * <p>A hardware layer can also be used to increase the rendering quality when 3165 * rotation transformations are applied on a view. It can also be used to 3166 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3167 * 3168 * @see #getLayerType() 3169 * @see #setLayerType(int, android.graphics.Paint) 3170 * @see #LAYER_TYPE_NONE 3171 * @see #LAYER_TYPE_SOFTWARE 3172 */ 3173 public static final int LAYER_TYPE_HARDWARE = 2; 3174 3175 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3176 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3177 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3178 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3179 }) 3180 int mLayerType = LAYER_TYPE_NONE; 3181 Paint mLayerPaint; 3182 Rect mLocalDirtyRect; 3183 3184 /** 3185 * Set to true when the view is sending hover accessibility events because it 3186 * is the innermost hovered view. 3187 */ 3188 private boolean mSendingHoverAccessibilityEvents; 3189 3190 /** 3191 * Delegate for injecting accessibility functionality. 3192 */ 3193 AccessibilityDelegate mAccessibilityDelegate; 3194 3195 /** 3196 * Consistency verifier for debugging purposes. 3197 * @hide 3198 */ 3199 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3200 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3201 new InputEventConsistencyVerifier(this, 0) : null; 3202 3203 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3204 3205 /** 3206 * Simple constructor to use when creating a view from code. 3207 * 3208 * @param context The Context the view is running in, through which it can 3209 * access the current theme, resources, etc. 3210 */ 3211 public View(Context context) { 3212 mContext = context; 3213 mResources = context != null ? context.getResources() : null; 3214 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3215 // Set layout and text direction defaults 3216 mPrivateFlags2 = 3217 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3218 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3219 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3220 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3221 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3222 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3223 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3224 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3225 mUserPaddingStart = UNDEFINED_PADDING; 3226 mUserPaddingEnd = UNDEFINED_PADDING; 3227 } 3228 3229 /** 3230 * Constructor that is called when inflating a view from XML. This is called 3231 * when a view is being constructed from an XML file, supplying attributes 3232 * that were specified in the XML file. This version uses a default style of 3233 * 0, so the only attribute values applied are those in the Context's Theme 3234 * and the given AttributeSet. 3235 * 3236 * <p> 3237 * The method onFinishInflate() will be called after all children have been 3238 * added. 3239 * 3240 * @param context The Context the view is running in, through which it can 3241 * access the current theme, resources, etc. 3242 * @param attrs The attributes of the XML tag that is inflating the view. 3243 * @see #View(Context, AttributeSet, int) 3244 */ 3245 public View(Context context, AttributeSet attrs) { 3246 this(context, attrs, 0); 3247 } 3248 3249 /** 3250 * Perform inflation from XML and apply a class-specific base style. This 3251 * constructor of View allows subclasses to use their own base style when 3252 * they are inflating. For example, a Button class's constructor would call 3253 * this version of the super class constructor and supply 3254 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 3255 * the theme's button style to modify all of the base view attributes (in 3256 * particular its background) as well as the Button class's attributes. 3257 * 3258 * @param context The Context the view is running in, through which it can 3259 * access the current theme, resources, etc. 3260 * @param attrs The attributes of the XML tag that is inflating the view. 3261 * @param defStyle The default style to apply to this view. If 0, no style 3262 * will be applied (beyond what is included in the theme). This may 3263 * either be an attribute resource, whose value will be retrieved 3264 * from the current theme, or an explicit style resource. 3265 * @see #View(Context, AttributeSet) 3266 */ 3267 public View(Context context, AttributeSet attrs, int defStyle) { 3268 this(context); 3269 3270 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 3271 defStyle, 0); 3272 3273 Drawable background = null; 3274 3275 int leftPadding = -1; 3276 int topPadding = -1; 3277 int rightPadding = -1; 3278 int bottomPadding = -1; 3279 int startPadding = UNDEFINED_PADDING; 3280 int endPadding = UNDEFINED_PADDING; 3281 3282 int padding = -1; 3283 3284 int viewFlagValues = 0; 3285 int viewFlagMasks = 0; 3286 3287 boolean setScrollContainer = false; 3288 3289 int x = 0; 3290 int y = 0; 3291 3292 float tx = 0; 3293 float ty = 0; 3294 float rotation = 0; 3295 float rotationX = 0; 3296 float rotationY = 0; 3297 float sx = 1f; 3298 float sy = 1f; 3299 boolean transformSet = false; 3300 3301 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3302 int overScrollMode = mOverScrollMode; 3303 boolean initializeScrollbars = false; 3304 3305 boolean leftPaddingDefined = false; 3306 boolean rightPaddingDefined = false; 3307 boolean startPaddingDefined = false; 3308 boolean endPaddingDefined = false; 3309 3310 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3311 3312 final int N = a.getIndexCount(); 3313 for (int i = 0; i < N; i++) { 3314 int attr = a.getIndex(i); 3315 switch (attr) { 3316 case com.android.internal.R.styleable.View_background: 3317 background = a.getDrawable(attr); 3318 break; 3319 case com.android.internal.R.styleable.View_padding: 3320 padding = a.getDimensionPixelSize(attr, -1); 3321 mUserPaddingLeftInitial = padding; 3322 mUserPaddingRightInitial = padding; 3323 leftPaddingDefined = true; 3324 rightPaddingDefined = true; 3325 break; 3326 case com.android.internal.R.styleable.View_paddingLeft: 3327 leftPadding = a.getDimensionPixelSize(attr, -1); 3328 mUserPaddingLeftInitial = leftPadding; 3329 leftPaddingDefined = true; 3330 break; 3331 case com.android.internal.R.styleable.View_paddingTop: 3332 topPadding = a.getDimensionPixelSize(attr, -1); 3333 break; 3334 case com.android.internal.R.styleable.View_paddingRight: 3335 rightPadding = a.getDimensionPixelSize(attr, -1); 3336 mUserPaddingRightInitial = rightPadding; 3337 rightPaddingDefined = true; 3338 break; 3339 case com.android.internal.R.styleable.View_paddingBottom: 3340 bottomPadding = a.getDimensionPixelSize(attr, -1); 3341 break; 3342 case com.android.internal.R.styleable.View_paddingStart: 3343 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3344 startPaddingDefined = true; 3345 break; 3346 case com.android.internal.R.styleable.View_paddingEnd: 3347 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3348 endPaddingDefined = true; 3349 break; 3350 case com.android.internal.R.styleable.View_scrollX: 3351 x = a.getDimensionPixelOffset(attr, 0); 3352 break; 3353 case com.android.internal.R.styleable.View_scrollY: 3354 y = a.getDimensionPixelOffset(attr, 0); 3355 break; 3356 case com.android.internal.R.styleable.View_alpha: 3357 setAlpha(a.getFloat(attr, 1f)); 3358 break; 3359 case com.android.internal.R.styleable.View_transformPivotX: 3360 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3361 break; 3362 case com.android.internal.R.styleable.View_transformPivotY: 3363 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3364 break; 3365 case com.android.internal.R.styleable.View_translationX: 3366 tx = a.getDimensionPixelOffset(attr, 0); 3367 transformSet = true; 3368 break; 3369 case com.android.internal.R.styleable.View_translationY: 3370 ty = a.getDimensionPixelOffset(attr, 0); 3371 transformSet = true; 3372 break; 3373 case com.android.internal.R.styleable.View_rotation: 3374 rotation = a.getFloat(attr, 0); 3375 transformSet = true; 3376 break; 3377 case com.android.internal.R.styleable.View_rotationX: 3378 rotationX = a.getFloat(attr, 0); 3379 transformSet = true; 3380 break; 3381 case com.android.internal.R.styleable.View_rotationY: 3382 rotationY = a.getFloat(attr, 0); 3383 transformSet = true; 3384 break; 3385 case com.android.internal.R.styleable.View_scaleX: 3386 sx = a.getFloat(attr, 1f); 3387 transformSet = true; 3388 break; 3389 case com.android.internal.R.styleable.View_scaleY: 3390 sy = a.getFloat(attr, 1f); 3391 transformSet = true; 3392 break; 3393 case com.android.internal.R.styleable.View_id: 3394 mID = a.getResourceId(attr, NO_ID); 3395 break; 3396 case com.android.internal.R.styleable.View_tag: 3397 mTag = a.getText(attr); 3398 break; 3399 case com.android.internal.R.styleable.View_fitsSystemWindows: 3400 if (a.getBoolean(attr, false)) { 3401 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3402 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3403 } 3404 break; 3405 case com.android.internal.R.styleable.View_focusable: 3406 if (a.getBoolean(attr, false)) { 3407 viewFlagValues |= FOCUSABLE; 3408 viewFlagMasks |= FOCUSABLE_MASK; 3409 } 3410 break; 3411 case com.android.internal.R.styleable.View_focusableInTouchMode: 3412 if (a.getBoolean(attr, false)) { 3413 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3414 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3415 } 3416 break; 3417 case com.android.internal.R.styleable.View_clickable: 3418 if (a.getBoolean(attr, false)) { 3419 viewFlagValues |= CLICKABLE; 3420 viewFlagMasks |= CLICKABLE; 3421 } 3422 break; 3423 case com.android.internal.R.styleable.View_longClickable: 3424 if (a.getBoolean(attr, false)) { 3425 viewFlagValues |= LONG_CLICKABLE; 3426 viewFlagMasks |= LONG_CLICKABLE; 3427 } 3428 break; 3429 case com.android.internal.R.styleable.View_saveEnabled: 3430 if (!a.getBoolean(attr, true)) { 3431 viewFlagValues |= SAVE_DISABLED; 3432 viewFlagMasks |= SAVE_DISABLED_MASK; 3433 } 3434 break; 3435 case com.android.internal.R.styleable.View_duplicateParentState: 3436 if (a.getBoolean(attr, false)) { 3437 viewFlagValues |= DUPLICATE_PARENT_STATE; 3438 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3439 } 3440 break; 3441 case com.android.internal.R.styleable.View_visibility: 3442 final int visibility = a.getInt(attr, 0); 3443 if (visibility != 0) { 3444 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3445 viewFlagMasks |= VISIBILITY_MASK; 3446 } 3447 break; 3448 case com.android.internal.R.styleable.View_layoutDirection: 3449 // Clear any layout direction flags (included resolved bits) already set 3450 mPrivateFlags2 &= 3451 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3452 // Set the layout direction flags depending on the value of the attribute 3453 final int layoutDirection = a.getInt(attr, -1); 3454 final int value = (layoutDirection != -1) ? 3455 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3456 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3457 break; 3458 case com.android.internal.R.styleable.View_drawingCacheQuality: 3459 final int cacheQuality = a.getInt(attr, 0); 3460 if (cacheQuality != 0) { 3461 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3462 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3463 } 3464 break; 3465 case com.android.internal.R.styleable.View_contentDescription: 3466 setContentDescription(a.getString(attr)); 3467 break; 3468 case com.android.internal.R.styleable.View_labelFor: 3469 setLabelFor(a.getResourceId(attr, NO_ID)); 3470 break; 3471 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3472 if (!a.getBoolean(attr, true)) { 3473 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3474 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3475 } 3476 break; 3477 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3478 if (!a.getBoolean(attr, true)) { 3479 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3480 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3481 } 3482 break; 3483 case R.styleable.View_scrollbars: 3484 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3485 if (scrollbars != SCROLLBARS_NONE) { 3486 viewFlagValues |= scrollbars; 3487 viewFlagMasks |= SCROLLBARS_MASK; 3488 initializeScrollbars = true; 3489 } 3490 break; 3491 //noinspection deprecation 3492 case R.styleable.View_fadingEdge: 3493 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3494 // Ignore the attribute starting with ICS 3495 break; 3496 } 3497 // With builds < ICS, fall through and apply fading edges 3498 case R.styleable.View_requiresFadingEdge: 3499 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3500 if (fadingEdge != FADING_EDGE_NONE) { 3501 viewFlagValues |= fadingEdge; 3502 viewFlagMasks |= FADING_EDGE_MASK; 3503 initializeFadingEdge(a); 3504 } 3505 break; 3506 case R.styleable.View_scrollbarStyle: 3507 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3508 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3509 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3510 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3511 } 3512 break; 3513 case R.styleable.View_isScrollContainer: 3514 setScrollContainer = true; 3515 if (a.getBoolean(attr, false)) { 3516 setScrollContainer(true); 3517 } 3518 break; 3519 case com.android.internal.R.styleable.View_keepScreenOn: 3520 if (a.getBoolean(attr, false)) { 3521 viewFlagValues |= KEEP_SCREEN_ON; 3522 viewFlagMasks |= KEEP_SCREEN_ON; 3523 } 3524 break; 3525 case R.styleable.View_filterTouchesWhenObscured: 3526 if (a.getBoolean(attr, false)) { 3527 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3528 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3529 } 3530 break; 3531 case R.styleable.View_nextFocusLeft: 3532 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3533 break; 3534 case R.styleable.View_nextFocusRight: 3535 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3536 break; 3537 case R.styleable.View_nextFocusUp: 3538 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3539 break; 3540 case R.styleable.View_nextFocusDown: 3541 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3542 break; 3543 case R.styleable.View_nextFocusForward: 3544 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3545 break; 3546 case R.styleable.View_minWidth: 3547 mMinWidth = a.getDimensionPixelSize(attr, 0); 3548 break; 3549 case R.styleable.View_minHeight: 3550 mMinHeight = a.getDimensionPixelSize(attr, 0); 3551 break; 3552 case R.styleable.View_onClick: 3553 if (context.isRestricted()) { 3554 throw new IllegalStateException("The android:onClick attribute cannot " 3555 + "be used within a restricted context"); 3556 } 3557 3558 final String handlerName = a.getString(attr); 3559 if (handlerName != null) { 3560 setOnClickListener(new OnClickListener() { 3561 private Method mHandler; 3562 3563 public void onClick(View v) { 3564 if (mHandler == null) { 3565 try { 3566 mHandler = getContext().getClass().getMethod(handlerName, 3567 View.class); 3568 } catch (NoSuchMethodException e) { 3569 int id = getId(); 3570 String idText = id == NO_ID ? "" : " with id '" 3571 + getContext().getResources().getResourceEntryName( 3572 id) + "'"; 3573 throw new IllegalStateException("Could not find a method " + 3574 handlerName + "(View) in the activity " 3575 + getContext().getClass() + " for onClick handler" 3576 + " on view " + View.this.getClass() + idText, e); 3577 } 3578 } 3579 3580 try { 3581 mHandler.invoke(getContext(), View.this); 3582 } catch (IllegalAccessException e) { 3583 throw new IllegalStateException("Could not execute non " 3584 + "public method of the activity", e); 3585 } catch (InvocationTargetException e) { 3586 throw new IllegalStateException("Could not execute " 3587 + "method of the activity", e); 3588 } 3589 } 3590 }); 3591 } 3592 break; 3593 case R.styleable.View_overScrollMode: 3594 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3595 break; 3596 case R.styleable.View_verticalScrollbarPosition: 3597 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3598 break; 3599 case R.styleable.View_layerType: 3600 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3601 break; 3602 case R.styleable.View_textDirection: 3603 // Clear any text direction flag already set 3604 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3605 // Set the text direction flags depending on the value of the attribute 3606 final int textDirection = a.getInt(attr, -1); 3607 if (textDirection != -1) { 3608 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3609 } 3610 break; 3611 case R.styleable.View_textAlignment: 3612 // Clear any text alignment flag already set 3613 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3614 // Set the text alignment flag depending on the value of the attribute 3615 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3616 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 3617 break; 3618 case R.styleable.View_importantForAccessibility: 3619 setImportantForAccessibility(a.getInt(attr, 3620 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 3621 break; 3622 } 3623 } 3624 3625 setOverScrollMode(overScrollMode); 3626 3627 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 3628 // the resolved layout direction). Those cached values will be used later during padding 3629 // resolution. 3630 mUserPaddingStart = startPadding; 3631 mUserPaddingEnd = endPadding; 3632 3633 if (background != null) { 3634 setBackground(background); 3635 } 3636 3637 if (padding >= 0) { 3638 leftPadding = padding; 3639 topPadding = padding; 3640 rightPadding = padding; 3641 bottomPadding = padding; 3642 mUserPaddingLeftInitial = padding; 3643 mUserPaddingRightInitial = padding; 3644 } 3645 3646 if (isRtlCompatibilityMode()) { 3647 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 3648 // left / right padding are used if defined (meaning here nothing to do). If they are not 3649 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 3650 // start / end and resolve them as left / right (layout direction is not taken into account). 3651 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3652 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3653 // defined. 3654 if (!leftPaddingDefined && startPaddingDefined) { 3655 leftPadding = startPadding; 3656 } 3657 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 3658 if (!rightPaddingDefined && endPaddingDefined) { 3659 rightPadding = endPadding; 3660 } 3661 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 3662 } else { 3663 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 3664 // values defined. Otherwise, left /right values are used. 3665 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3666 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3667 // defined. 3668 if (startPaddingDefined) { 3669 mUserPaddingLeftInitial = startPadding; 3670 } else if (leftPaddingDefined) { 3671 mUserPaddingLeftInitial = leftPadding; 3672 } 3673 if (endPaddingDefined) { 3674 mUserPaddingRightInitial = endPadding; 3675 } 3676 else if (rightPaddingDefined) { 3677 mUserPaddingRightInitial = rightPadding; 3678 } 3679 } 3680 3681 internalSetPadding( 3682 mUserPaddingLeftInitial, 3683 topPadding >= 0 ? topPadding : mPaddingTop, 3684 mUserPaddingRightInitial, 3685 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3686 3687 if (viewFlagMasks != 0) { 3688 setFlags(viewFlagValues, viewFlagMasks); 3689 } 3690 3691 if (initializeScrollbars) { 3692 initializeScrollbars(a); 3693 } 3694 3695 a.recycle(); 3696 3697 // Needs to be called after mViewFlags is set 3698 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3699 recomputePadding(); 3700 } 3701 3702 if (x != 0 || y != 0) { 3703 scrollTo(x, y); 3704 } 3705 3706 if (transformSet) { 3707 setTranslationX(tx); 3708 setTranslationY(ty); 3709 setRotation(rotation); 3710 setRotationX(rotationX); 3711 setRotationY(rotationY); 3712 setScaleX(sx); 3713 setScaleY(sy); 3714 } 3715 3716 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3717 setScrollContainer(true); 3718 } 3719 3720 computeOpaqueFlags(); 3721 } 3722 3723 /** 3724 * Non-public constructor for use in testing 3725 */ 3726 View() { 3727 mResources = null; 3728 } 3729 3730 public String toString() { 3731 StringBuilder out = new StringBuilder(128); 3732 out.append(getClass().getName()); 3733 out.append('{'); 3734 out.append(Integer.toHexString(System.identityHashCode(this))); 3735 out.append(' '); 3736 switch (mViewFlags&VISIBILITY_MASK) { 3737 case VISIBLE: out.append('V'); break; 3738 case INVISIBLE: out.append('I'); break; 3739 case GONE: out.append('G'); break; 3740 default: out.append('.'); break; 3741 } 3742 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 3743 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 3744 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 3745 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 3746 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 3747 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 3748 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 3749 out.append(' '); 3750 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 3751 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 3752 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 3753 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 3754 out.append('p'); 3755 } else { 3756 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 3757 } 3758 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 3759 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 3760 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 3761 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 3762 out.append(' '); 3763 out.append(mLeft); 3764 out.append(','); 3765 out.append(mTop); 3766 out.append('-'); 3767 out.append(mRight); 3768 out.append(','); 3769 out.append(mBottom); 3770 final int id = getId(); 3771 if (id != NO_ID) { 3772 out.append(" #"); 3773 out.append(Integer.toHexString(id)); 3774 final Resources r = mResources; 3775 if (id != 0 && r != null) { 3776 try { 3777 String pkgname; 3778 switch (id&0xff000000) { 3779 case 0x7f000000: 3780 pkgname="app"; 3781 break; 3782 case 0x01000000: 3783 pkgname="android"; 3784 break; 3785 default: 3786 pkgname = r.getResourcePackageName(id); 3787 break; 3788 } 3789 String typename = r.getResourceTypeName(id); 3790 String entryname = r.getResourceEntryName(id); 3791 out.append(" "); 3792 out.append(pkgname); 3793 out.append(":"); 3794 out.append(typename); 3795 out.append("/"); 3796 out.append(entryname); 3797 } catch (Resources.NotFoundException e) { 3798 } 3799 } 3800 } 3801 out.append("}"); 3802 return out.toString(); 3803 } 3804 3805 /** 3806 * <p> 3807 * Initializes the fading edges from a given set of styled attributes. This 3808 * method should be called by subclasses that need fading edges and when an 3809 * instance of these subclasses is created programmatically rather than 3810 * being inflated from XML. This method is automatically called when the XML 3811 * is inflated. 3812 * </p> 3813 * 3814 * @param a the styled attributes set to initialize the fading edges from 3815 */ 3816 protected void initializeFadingEdge(TypedArray a) { 3817 initScrollCache(); 3818 3819 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3820 R.styleable.View_fadingEdgeLength, 3821 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3822 } 3823 3824 /** 3825 * Returns the size of the vertical faded edges used to indicate that more 3826 * content in this view is visible. 3827 * 3828 * @return The size in pixels of the vertical faded edge or 0 if vertical 3829 * faded edges are not enabled for this view. 3830 * @attr ref android.R.styleable#View_fadingEdgeLength 3831 */ 3832 public int getVerticalFadingEdgeLength() { 3833 if (isVerticalFadingEdgeEnabled()) { 3834 ScrollabilityCache cache = mScrollCache; 3835 if (cache != null) { 3836 return cache.fadingEdgeLength; 3837 } 3838 } 3839 return 0; 3840 } 3841 3842 /** 3843 * Set the size of the faded edge used to indicate that more content in this 3844 * view is available. Will not change whether the fading edge is enabled; use 3845 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3846 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3847 * for the vertical or horizontal fading edges. 3848 * 3849 * @param length The size in pixels of the faded edge used to indicate that more 3850 * content in this view is visible. 3851 */ 3852 public void setFadingEdgeLength(int length) { 3853 initScrollCache(); 3854 mScrollCache.fadingEdgeLength = length; 3855 } 3856 3857 /** 3858 * Returns the size of the horizontal faded edges used to indicate that more 3859 * content in this view is visible. 3860 * 3861 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3862 * faded edges are not enabled for this view. 3863 * @attr ref android.R.styleable#View_fadingEdgeLength 3864 */ 3865 public int getHorizontalFadingEdgeLength() { 3866 if (isHorizontalFadingEdgeEnabled()) { 3867 ScrollabilityCache cache = mScrollCache; 3868 if (cache != null) { 3869 return cache.fadingEdgeLength; 3870 } 3871 } 3872 return 0; 3873 } 3874 3875 /** 3876 * Returns the width of the vertical scrollbar. 3877 * 3878 * @return The width in pixels of the vertical scrollbar or 0 if there 3879 * is no vertical scrollbar. 3880 */ 3881 public int getVerticalScrollbarWidth() { 3882 ScrollabilityCache cache = mScrollCache; 3883 if (cache != null) { 3884 ScrollBarDrawable scrollBar = cache.scrollBar; 3885 if (scrollBar != null) { 3886 int size = scrollBar.getSize(true); 3887 if (size <= 0) { 3888 size = cache.scrollBarSize; 3889 } 3890 return size; 3891 } 3892 return 0; 3893 } 3894 return 0; 3895 } 3896 3897 /** 3898 * Returns the height of the horizontal scrollbar. 3899 * 3900 * @return The height in pixels of the horizontal scrollbar or 0 if 3901 * there is no horizontal scrollbar. 3902 */ 3903 protected int getHorizontalScrollbarHeight() { 3904 ScrollabilityCache cache = mScrollCache; 3905 if (cache != null) { 3906 ScrollBarDrawable scrollBar = cache.scrollBar; 3907 if (scrollBar != null) { 3908 int size = scrollBar.getSize(false); 3909 if (size <= 0) { 3910 size = cache.scrollBarSize; 3911 } 3912 return size; 3913 } 3914 return 0; 3915 } 3916 return 0; 3917 } 3918 3919 /** 3920 * <p> 3921 * Initializes the scrollbars from a given set of styled attributes. This 3922 * method should be called by subclasses that need scrollbars and when an 3923 * instance of these subclasses is created programmatically rather than 3924 * being inflated from XML. This method is automatically called when the XML 3925 * is inflated. 3926 * </p> 3927 * 3928 * @param a the styled attributes set to initialize the scrollbars from 3929 */ 3930 protected void initializeScrollbars(TypedArray a) { 3931 initScrollCache(); 3932 3933 final ScrollabilityCache scrollabilityCache = mScrollCache; 3934 3935 if (scrollabilityCache.scrollBar == null) { 3936 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3937 } 3938 3939 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3940 3941 if (!fadeScrollbars) { 3942 scrollabilityCache.state = ScrollabilityCache.ON; 3943 } 3944 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3945 3946 3947 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3948 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3949 .getScrollBarFadeDuration()); 3950 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3951 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3952 ViewConfiguration.getScrollDefaultDelay()); 3953 3954 3955 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3956 com.android.internal.R.styleable.View_scrollbarSize, 3957 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3958 3959 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3960 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3961 3962 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3963 if (thumb != null) { 3964 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3965 } 3966 3967 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3968 false); 3969 if (alwaysDraw) { 3970 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3971 } 3972 3973 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3974 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3975 3976 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3977 if (thumb != null) { 3978 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3979 } 3980 3981 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3982 false); 3983 if (alwaysDraw) { 3984 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3985 } 3986 3987 // Apply layout direction to the new Drawables if needed 3988 final int layoutDirection = getLayoutDirection(); 3989 if (track != null) { 3990 track.setLayoutDirection(layoutDirection); 3991 } 3992 if (thumb != null) { 3993 thumb.setLayoutDirection(layoutDirection); 3994 } 3995 3996 // Re-apply user/background padding so that scrollbar(s) get added 3997 resolvePadding(); 3998 } 3999 4000 /** 4001 * <p> 4002 * Initalizes the scrollability cache if necessary. 4003 * </p> 4004 */ 4005 private void initScrollCache() { 4006 if (mScrollCache == null) { 4007 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4008 } 4009 } 4010 4011 private ScrollabilityCache getScrollCache() { 4012 initScrollCache(); 4013 return mScrollCache; 4014 } 4015 4016 /** 4017 * Set the position of the vertical scroll bar. Should be one of 4018 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4019 * {@link #SCROLLBAR_POSITION_RIGHT}. 4020 * 4021 * @param position Where the vertical scroll bar should be positioned. 4022 */ 4023 public void setVerticalScrollbarPosition(int position) { 4024 if (mVerticalScrollbarPosition != position) { 4025 mVerticalScrollbarPosition = position; 4026 computeOpaqueFlags(); 4027 resolvePadding(); 4028 } 4029 } 4030 4031 /** 4032 * @return The position where the vertical scroll bar will show, if applicable. 4033 * @see #setVerticalScrollbarPosition(int) 4034 */ 4035 public int getVerticalScrollbarPosition() { 4036 return mVerticalScrollbarPosition; 4037 } 4038 4039 ListenerInfo getListenerInfo() { 4040 if (mListenerInfo != null) { 4041 return mListenerInfo; 4042 } 4043 mListenerInfo = new ListenerInfo(); 4044 return mListenerInfo; 4045 } 4046 4047 /** 4048 * Register a callback to be invoked when focus of this view changed. 4049 * 4050 * @param l The callback that will run. 4051 */ 4052 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4053 getListenerInfo().mOnFocusChangeListener = l; 4054 } 4055 4056 /** 4057 * Add a listener that will be called when the bounds of the view change due to 4058 * layout processing. 4059 * 4060 * @param listener The listener that will be called when layout bounds change. 4061 */ 4062 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4063 ListenerInfo li = getListenerInfo(); 4064 if (li.mOnLayoutChangeListeners == null) { 4065 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4066 } 4067 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4068 li.mOnLayoutChangeListeners.add(listener); 4069 } 4070 } 4071 4072 /** 4073 * Remove a listener for layout changes. 4074 * 4075 * @param listener The listener for layout bounds change. 4076 */ 4077 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4078 ListenerInfo li = mListenerInfo; 4079 if (li == null || li.mOnLayoutChangeListeners == null) { 4080 return; 4081 } 4082 li.mOnLayoutChangeListeners.remove(listener); 4083 } 4084 4085 /** 4086 * Add a listener for attach state changes. 4087 * 4088 * This listener will be called whenever this view is attached or detached 4089 * from a window. Remove the listener using 4090 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4091 * 4092 * @param listener Listener to attach 4093 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4094 */ 4095 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4096 ListenerInfo li = getListenerInfo(); 4097 if (li.mOnAttachStateChangeListeners == null) { 4098 li.mOnAttachStateChangeListeners 4099 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4100 } 4101 li.mOnAttachStateChangeListeners.add(listener); 4102 } 4103 4104 /** 4105 * Remove a listener for attach state changes. The listener will receive no further 4106 * notification of window attach/detach events. 4107 * 4108 * @param listener Listener to remove 4109 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4110 */ 4111 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4112 ListenerInfo li = mListenerInfo; 4113 if (li == null || li.mOnAttachStateChangeListeners == null) { 4114 return; 4115 } 4116 li.mOnAttachStateChangeListeners.remove(listener); 4117 } 4118 4119 /** 4120 * Returns the focus-change callback registered for this view. 4121 * 4122 * @return The callback, or null if one is not registered. 4123 */ 4124 public OnFocusChangeListener getOnFocusChangeListener() { 4125 ListenerInfo li = mListenerInfo; 4126 return li != null ? li.mOnFocusChangeListener : null; 4127 } 4128 4129 /** 4130 * Register a callback to be invoked when this view is clicked. If this view is not 4131 * clickable, it becomes clickable. 4132 * 4133 * @param l The callback that will run 4134 * 4135 * @see #setClickable(boolean) 4136 */ 4137 public void setOnClickListener(OnClickListener l) { 4138 if (!isClickable()) { 4139 setClickable(true); 4140 } 4141 getListenerInfo().mOnClickListener = l; 4142 } 4143 4144 /** 4145 * Return whether this view has an attached OnClickListener. Returns 4146 * true if there is a listener, false if there is none. 4147 */ 4148 public boolean hasOnClickListeners() { 4149 ListenerInfo li = mListenerInfo; 4150 return (li != null && li.mOnClickListener != null); 4151 } 4152 4153 /** 4154 * Register a callback to be invoked when this view is clicked and held. If this view is not 4155 * long clickable, it becomes long clickable. 4156 * 4157 * @param l The callback that will run 4158 * 4159 * @see #setLongClickable(boolean) 4160 */ 4161 public void setOnLongClickListener(OnLongClickListener l) { 4162 if (!isLongClickable()) { 4163 setLongClickable(true); 4164 } 4165 getListenerInfo().mOnLongClickListener = l; 4166 } 4167 4168 /** 4169 * Register a callback to be invoked when the context menu for this view is 4170 * being built. If this view is not long clickable, it becomes long clickable. 4171 * 4172 * @param l The callback that will run 4173 * 4174 */ 4175 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4176 if (!isLongClickable()) { 4177 setLongClickable(true); 4178 } 4179 getListenerInfo().mOnCreateContextMenuListener = l; 4180 } 4181 4182 /** 4183 * Call this view's OnClickListener, if it is defined. Performs all normal 4184 * actions associated with clicking: reporting accessibility event, playing 4185 * a sound, etc. 4186 * 4187 * @return True there was an assigned OnClickListener that was called, false 4188 * otherwise is returned. 4189 */ 4190 public boolean performClick() { 4191 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4192 4193 ListenerInfo li = mListenerInfo; 4194 if (li != null && li.mOnClickListener != null) { 4195 playSoundEffect(SoundEffectConstants.CLICK); 4196 li.mOnClickListener.onClick(this); 4197 return true; 4198 } 4199 4200 return false; 4201 } 4202 4203 /** 4204 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4205 * this only calls the listener, and does not do any associated clicking 4206 * actions like reporting an accessibility event. 4207 * 4208 * @return True there was an assigned OnClickListener that was called, false 4209 * otherwise is returned. 4210 */ 4211 public boolean callOnClick() { 4212 ListenerInfo li = mListenerInfo; 4213 if (li != null && li.mOnClickListener != null) { 4214 li.mOnClickListener.onClick(this); 4215 return true; 4216 } 4217 return false; 4218 } 4219 4220 /** 4221 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4222 * OnLongClickListener did not consume the event. 4223 * 4224 * @return True if one of the above receivers consumed the event, false otherwise. 4225 */ 4226 public boolean performLongClick() { 4227 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4228 4229 boolean handled = false; 4230 ListenerInfo li = mListenerInfo; 4231 if (li != null && li.mOnLongClickListener != null) { 4232 handled = li.mOnLongClickListener.onLongClick(View.this); 4233 } 4234 if (!handled) { 4235 handled = showContextMenu(); 4236 } 4237 if (handled) { 4238 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4239 } 4240 return handled; 4241 } 4242 4243 /** 4244 * Performs button-related actions during a touch down event. 4245 * 4246 * @param event The event. 4247 * @return True if the down was consumed. 4248 * 4249 * @hide 4250 */ 4251 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4252 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4253 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4254 return true; 4255 } 4256 } 4257 return false; 4258 } 4259 4260 /** 4261 * Bring up the context menu for this view. 4262 * 4263 * @return Whether a context menu was displayed. 4264 */ 4265 public boolean showContextMenu() { 4266 return getParent().showContextMenuForChild(this); 4267 } 4268 4269 /** 4270 * Bring up the context menu for this view, referring to the item under the specified point. 4271 * 4272 * @param x The referenced x coordinate. 4273 * @param y The referenced y coordinate. 4274 * @param metaState The keyboard modifiers that were pressed. 4275 * @return Whether a context menu was displayed. 4276 * 4277 * @hide 4278 */ 4279 public boolean showContextMenu(float x, float y, int metaState) { 4280 return showContextMenu(); 4281 } 4282 4283 /** 4284 * Start an action mode. 4285 * 4286 * @param callback Callback that will control the lifecycle of the action mode 4287 * @return The new action mode if it is started, null otherwise 4288 * 4289 * @see ActionMode 4290 */ 4291 public ActionMode startActionMode(ActionMode.Callback callback) { 4292 ViewParent parent = getParent(); 4293 if (parent == null) return null; 4294 return parent.startActionModeForChild(this, callback); 4295 } 4296 4297 /** 4298 * Register a callback to be invoked when a hardware key is pressed in this view. 4299 * Key presses in software input methods will generally not trigger the methods of 4300 * this listener. 4301 * @param l the key listener to attach to this view 4302 */ 4303 public void setOnKeyListener(OnKeyListener l) { 4304 getListenerInfo().mOnKeyListener = l; 4305 } 4306 4307 /** 4308 * Register a callback to be invoked when a touch event is sent to this view. 4309 * @param l the touch listener to attach to this view 4310 */ 4311 public void setOnTouchListener(OnTouchListener l) { 4312 getListenerInfo().mOnTouchListener = l; 4313 } 4314 4315 /** 4316 * Register a callback to be invoked when a generic motion event is sent to this view. 4317 * @param l the generic motion listener to attach to this view 4318 */ 4319 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4320 getListenerInfo().mOnGenericMotionListener = l; 4321 } 4322 4323 /** 4324 * Register a callback to be invoked when a hover event is sent to this view. 4325 * @param l the hover listener to attach to this view 4326 */ 4327 public void setOnHoverListener(OnHoverListener l) { 4328 getListenerInfo().mOnHoverListener = l; 4329 } 4330 4331 /** 4332 * Register a drag event listener callback object for this View. The parameter is 4333 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4334 * View, the system calls the 4335 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4336 * @param l An implementation of {@link android.view.View.OnDragListener}. 4337 */ 4338 public void setOnDragListener(OnDragListener l) { 4339 getListenerInfo().mOnDragListener = l; 4340 } 4341 4342 /** 4343 * Give this view focus. This will cause 4344 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4345 * 4346 * Note: this does not check whether this {@link View} should get focus, it just 4347 * gives it focus no matter what. It should only be called internally by framework 4348 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4349 * 4350 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4351 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4352 * focus moved when requestFocus() is called. It may not always 4353 * apply, in which case use the default View.FOCUS_DOWN. 4354 * @param previouslyFocusedRect The rectangle of the view that had focus 4355 * prior in this View's coordinate system. 4356 */ 4357 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 4358 if (DBG) { 4359 System.out.println(this + " requestFocus()"); 4360 } 4361 4362 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4363 mPrivateFlags |= PFLAG_FOCUSED; 4364 4365 if (mParent != null) { 4366 mParent.requestChildFocus(this, this); 4367 } 4368 4369 onFocusChanged(true, direction, previouslyFocusedRect); 4370 refreshDrawableState(); 4371 4372 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4373 notifyAccessibilityStateChanged(); 4374 } 4375 } 4376 } 4377 4378 /** 4379 * Request that a rectangle of this view be visible on the screen, 4380 * scrolling if necessary just enough. 4381 * 4382 * <p>A View should call this if it maintains some notion of which part 4383 * of its content is interesting. For example, a text editing view 4384 * should call this when its cursor moves. 4385 * 4386 * @param rectangle The rectangle. 4387 * @return Whether any parent scrolled. 4388 */ 4389 public boolean requestRectangleOnScreen(Rect rectangle) { 4390 return requestRectangleOnScreen(rectangle, false); 4391 } 4392 4393 /** 4394 * Request that a rectangle of this view be visible on the screen, 4395 * scrolling if necessary just enough. 4396 * 4397 * <p>A View should call this if it maintains some notion of which part 4398 * of its content is interesting. For example, a text editing view 4399 * should call this when its cursor moves. 4400 * 4401 * <p>When <code>immediate</code> is set to true, scrolling will not be 4402 * animated. 4403 * 4404 * @param rectangle The rectangle. 4405 * @param immediate True to forbid animated scrolling, false otherwise 4406 * @return Whether any parent scrolled. 4407 */ 4408 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4409 if (mParent == null) { 4410 return false; 4411 } 4412 4413 View child = this; 4414 4415 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4416 position.set(rectangle); 4417 4418 ViewParent parent = mParent; 4419 boolean scrolled = false; 4420 while (parent != null) { 4421 rectangle.set((int) position.left, (int) position.top, 4422 (int) position.right, (int) position.bottom); 4423 4424 scrolled |= parent.requestChildRectangleOnScreen(child, 4425 rectangle, immediate); 4426 4427 if (!child.hasIdentityMatrix()) { 4428 child.getMatrix().mapRect(position); 4429 } 4430 4431 position.offset(child.mLeft, child.mTop); 4432 4433 if (!(parent instanceof View)) { 4434 break; 4435 } 4436 4437 View parentView = (View) parent; 4438 4439 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4440 4441 child = parentView; 4442 parent = child.getParent(); 4443 } 4444 4445 return scrolled; 4446 } 4447 4448 /** 4449 * Called when this view wants to give up focus. If focus is cleared 4450 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4451 * <p> 4452 * <strong>Note:</strong> When a View clears focus the framework is trying 4453 * to give focus to the first focusable View from the top. Hence, if this 4454 * View is the first from the top that can take focus, then all callbacks 4455 * related to clearing focus will be invoked after wich the framework will 4456 * give focus to this view. 4457 * </p> 4458 */ 4459 public void clearFocus() { 4460 if (DBG) { 4461 System.out.println(this + " clearFocus()"); 4462 } 4463 4464 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4465 mPrivateFlags &= ~PFLAG_FOCUSED; 4466 4467 if (mParent != null) { 4468 mParent.clearChildFocus(this); 4469 } 4470 4471 onFocusChanged(false, 0, null); 4472 4473 refreshDrawableState(); 4474 4475 ensureInputFocusOnFirstFocusable(); 4476 4477 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4478 notifyAccessibilityStateChanged(); 4479 } 4480 } 4481 } 4482 4483 void ensureInputFocusOnFirstFocusable() { 4484 View root = getRootView(); 4485 if (root != null) { 4486 root.requestFocus(); 4487 } 4488 } 4489 4490 /** 4491 * Called internally by the view system when a new view is getting focus. 4492 * This is what clears the old focus. 4493 */ 4494 void unFocus() { 4495 if (DBG) { 4496 System.out.println(this + " unFocus()"); 4497 } 4498 4499 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4500 mPrivateFlags &= ~PFLAG_FOCUSED; 4501 4502 onFocusChanged(false, 0, null); 4503 refreshDrawableState(); 4504 4505 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4506 notifyAccessibilityStateChanged(); 4507 } 4508 } 4509 } 4510 4511 /** 4512 * Returns true if this view has focus iteself, or is the ancestor of the 4513 * view that has focus. 4514 * 4515 * @return True if this view has or contains focus, false otherwise. 4516 */ 4517 @ViewDebug.ExportedProperty(category = "focus") 4518 public boolean hasFocus() { 4519 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4520 } 4521 4522 /** 4523 * Returns true if this view is focusable or if it contains a reachable View 4524 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4525 * is a View whose parents do not block descendants focus. 4526 * 4527 * Only {@link #VISIBLE} views are considered focusable. 4528 * 4529 * @return True if the view is focusable or if the view contains a focusable 4530 * View, false otherwise. 4531 * 4532 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4533 */ 4534 public boolean hasFocusable() { 4535 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4536 } 4537 4538 /** 4539 * Called by the view system when the focus state of this view changes. 4540 * When the focus change event is caused by directional navigation, direction 4541 * and previouslyFocusedRect provide insight into where the focus is coming from. 4542 * When overriding, be sure to call up through to the super class so that 4543 * the standard focus handling will occur. 4544 * 4545 * @param gainFocus True if the View has focus; false otherwise. 4546 * @param direction The direction focus has moved when requestFocus() 4547 * is called to give this view focus. Values are 4548 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4549 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4550 * It may not always apply, in which case use the default. 4551 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4552 * system, of the previously focused view. If applicable, this will be 4553 * passed in as finer grained information about where the focus is coming 4554 * from (in addition to direction). Will be <code>null</code> otherwise. 4555 */ 4556 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 4557 if (gainFocus) { 4558 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4559 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4560 } 4561 } 4562 4563 InputMethodManager imm = InputMethodManager.peekInstance(); 4564 if (!gainFocus) { 4565 if (isPressed()) { 4566 setPressed(false); 4567 } 4568 if (imm != null && mAttachInfo != null 4569 && mAttachInfo.mHasWindowFocus) { 4570 imm.focusOut(this); 4571 } 4572 onFocusLost(); 4573 } else if (imm != null && mAttachInfo != null 4574 && mAttachInfo.mHasWindowFocus) { 4575 imm.focusIn(this); 4576 } 4577 4578 invalidate(true); 4579 ListenerInfo li = mListenerInfo; 4580 if (li != null && li.mOnFocusChangeListener != null) { 4581 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 4582 } 4583 4584 if (mAttachInfo != null) { 4585 mAttachInfo.mKeyDispatchState.reset(this); 4586 } 4587 } 4588 4589 /** 4590 * Sends an accessibility event of the given type. If accessibility is 4591 * not enabled this method has no effect. The default implementation calls 4592 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 4593 * to populate information about the event source (this View), then calls 4594 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 4595 * populate the text content of the event source including its descendants, 4596 * and last calls 4597 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 4598 * on its parent to resuest sending of the event to interested parties. 4599 * <p> 4600 * If an {@link AccessibilityDelegate} has been specified via calling 4601 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4602 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 4603 * responsible for handling this call. 4604 * </p> 4605 * 4606 * @param eventType The type of the event to send, as defined by several types from 4607 * {@link android.view.accessibility.AccessibilityEvent}, such as 4608 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 4609 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 4610 * 4611 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4612 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4613 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 4614 * @see AccessibilityDelegate 4615 */ 4616 public void sendAccessibilityEvent(int eventType) { 4617 if (mAccessibilityDelegate != null) { 4618 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 4619 } else { 4620 sendAccessibilityEventInternal(eventType); 4621 } 4622 } 4623 4624 /** 4625 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 4626 * {@link AccessibilityEvent} to make an announcement which is related to some 4627 * sort of a context change for which none of the events representing UI transitions 4628 * is a good fit. For example, announcing a new page in a book. If accessibility 4629 * is not enabled this method does nothing. 4630 * 4631 * @param text The announcement text. 4632 */ 4633 public void announceForAccessibility(CharSequence text) { 4634 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 4635 AccessibilityEvent event = AccessibilityEvent.obtain( 4636 AccessibilityEvent.TYPE_ANNOUNCEMENT); 4637 onInitializeAccessibilityEvent(event); 4638 event.getText().add(text); 4639 event.setContentDescription(null); 4640 mParent.requestSendAccessibilityEvent(this, event); 4641 } 4642 } 4643 4644 /** 4645 * @see #sendAccessibilityEvent(int) 4646 * 4647 * Note: Called from the default {@link AccessibilityDelegate}. 4648 */ 4649 void sendAccessibilityEventInternal(int eventType) { 4650 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4651 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 4652 } 4653 } 4654 4655 /** 4656 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 4657 * takes as an argument an empty {@link AccessibilityEvent} and does not 4658 * perform a check whether accessibility is enabled. 4659 * <p> 4660 * If an {@link AccessibilityDelegate} has been specified via calling 4661 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4662 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 4663 * is responsible for handling this call. 4664 * </p> 4665 * 4666 * @param event The event to send. 4667 * 4668 * @see #sendAccessibilityEvent(int) 4669 */ 4670 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 4671 if (mAccessibilityDelegate != null) { 4672 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 4673 } else { 4674 sendAccessibilityEventUncheckedInternal(event); 4675 } 4676 } 4677 4678 /** 4679 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 4680 * 4681 * Note: Called from the default {@link AccessibilityDelegate}. 4682 */ 4683 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 4684 if (!isShown()) { 4685 return; 4686 } 4687 onInitializeAccessibilityEvent(event); 4688 // Only a subset of accessibility events populates text content. 4689 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4690 dispatchPopulateAccessibilityEvent(event); 4691 } 4692 // In the beginning we called #isShown(), so we know that getParent() is not null. 4693 getParent().requestSendAccessibilityEvent(this, event); 4694 } 4695 4696 /** 4697 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4698 * to its children for adding their text content to the event. Note that the 4699 * event text is populated in a separate dispatch path since we add to the 4700 * event not only the text of the source but also the text of all its descendants. 4701 * A typical implementation will call 4702 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4703 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4704 * on each child. Override this method if custom population of the event text 4705 * content is required. 4706 * <p> 4707 * If an {@link AccessibilityDelegate} has been specified via calling 4708 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4709 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4710 * is responsible for handling this call. 4711 * </p> 4712 * <p> 4713 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4714 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4715 * </p> 4716 * 4717 * @param event The event. 4718 * 4719 * @return True if the event population was completed. 4720 */ 4721 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4722 if (mAccessibilityDelegate != null) { 4723 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4724 } else { 4725 return dispatchPopulateAccessibilityEventInternal(event); 4726 } 4727 } 4728 4729 /** 4730 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4731 * 4732 * Note: Called from the default {@link AccessibilityDelegate}. 4733 */ 4734 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4735 onPopulateAccessibilityEvent(event); 4736 return false; 4737 } 4738 4739 /** 4740 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4741 * giving a chance to this View to populate the accessibility event with its 4742 * text content. While this method is free to modify event 4743 * attributes other than text content, doing so should normally be performed in 4744 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4745 * <p> 4746 * Example: Adding formatted date string to an accessibility event in addition 4747 * to the text added by the super implementation: 4748 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4749 * super.onPopulateAccessibilityEvent(event); 4750 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4751 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4752 * mCurrentDate.getTimeInMillis(), flags); 4753 * event.getText().add(selectedDateUtterance); 4754 * }</pre> 4755 * <p> 4756 * If an {@link AccessibilityDelegate} has been specified via calling 4757 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4758 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 4759 * is responsible for handling this call. 4760 * </p> 4761 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4762 * information to the event, in case the default implementation has basic information to add. 4763 * </p> 4764 * 4765 * @param event The accessibility event which to populate. 4766 * 4767 * @see #sendAccessibilityEvent(int) 4768 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4769 */ 4770 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4771 if (mAccessibilityDelegate != null) { 4772 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 4773 } else { 4774 onPopulateAccessibilityEventInternal(event); 4775 } 4776 } 4777 4778 /** 4779 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 4780 * 4781 * Note: Called from the default {@link AccessibilityDelegate}. 4782 */ 4783 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4784 4785 } 4786 4787 /** 4788 * Initializes an {@link AccessibilityEvent} with information about 4789 * this View which is the event source. In other words, the source of 4790 * an accessibility event is the view whose state change triggered firing 4791 * the event. 4792 * <p> 4793 * Example: Setting the password property of an event in addition 4794 * to properties set by the super implementation: 4795 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4796 * super.onInitializeAccessibilityEvent(event); 4797 * event.setPassword(true); 4798 * }</pre> 4799 * <p> 4800 * If an {@link AccessibilityDelegate} has been specified via calling 4801 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4802 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4803 * is responsible for handling this call. 4804 * </p> 4805 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4806 * information to the event, in case the default implementation has basic information to add. 4807 * </p> 4808 * @param event The event to initialize. 4809 * 4810 * @see #sendAccessibilityEvent(int) 4811 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4812 */ 4813 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4814 if (mAccessibilityDelegate != null) { 4815 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 4816 } else { 4817 onInitializeAccessibilityEventInternal(event); 4818 } 4819 } 4820 4821 /** 4822 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4823 * 4824 * Note: Called from the default {@link AccessibilityDelegate}. 4825 */ 4826 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 4827 event.setSource(this); 4828 event.setClassName(View.class.getName()); 4829 event.setPackageName(getContext().getPackageName()); 4830 event.setEnabled(isEnabled()); 4831 event.setContentDescription(mContentDescription); 4832 4833 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 4834 ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList; 4835 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 4836 FOCUSABLES_ALL); 4837 event.setItemCount(focusablesTempList.size()); 4838 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4839 focusablesTempList.clear(); 4840 } 4841 } 4842 4843 /** 4844 * Returns an {@link AccessibilityNodeInfo} representing this view from the 4845 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 4846 * This method is responsible for obtaining an accessibility node info from a 4847 * pool of reusable instances and calling 4848 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 4849 * initialize the former. 4850 * <p> 4851 * Note: The client is responsible for recycling the obtained instance by calling 4852 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4853 * </p> 4854 * 4855 * @return A populated {@link AccessibilityNodeInfo}. 4856 * 4857 * @see AccessibilityNodeInfo 4858 */ 4859 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4860 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 4861 if (provider != null) { 4862 return provider.createAccessibilityNodeInfo(View.NO_ID); 4863 } else { 4864 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4865 onInitializeAccessibilityNodeInfo(info); 4866 return info; 4867 } 4868 } 4869 4870 /** 4871 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4872 * The base implementation sets: 4873 * <ul> 4874 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4875 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4876 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4877 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4878 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4879 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4880 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4881 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4882 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4883 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4884 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4885 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4886 * </ul> 4887 * <p> 4888 * Subclasses should override this method, call the super implementation, 4889 * and set additional attributes. 4890 * </p> 4891 * <p> 4892 * If an {@link AccessibilityDelegate} has been specified via calling 4893 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4894 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 4895 * is responsible for handling this call. 4896 * </p> 4897 * 4898 * @param info The instance to initialize. 4899 */ 4900 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 4901 if (mAccessibilityDelegate != null) { 4902 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 4903 } else { 4904 onInitializeAccessibilityNodeInfoInternal(info); 4905 } 4906 } 4907 4908 /** 4909 * Gets the location of this view in screen coordintates. 4910 * 4911 * @param outRect The output location 4912 */ 4913 private void getBoundsOnScreen(Rect outRect) { 4914 if (mAttachInfo == null) { 4915 return; 4916 } 4917 4918 RectF position = mAttachInfo.mTmpTransformRect; 4919 position.set(0, 0, mRight - mLeft, mBottom - mTop); 4920 4921 if (!hasIdentityMatrix()) { 4922 getMatrix().mapRect(position); 4923 } 4924 4925 position.offset(mLeft, mTop); 4926 4927 ViewParent parent = mParent; 4928 while (parent instanceof View) { 4929 View parentView = (View) parent; 4930 4931 position.offset(-parentView.mScrollX, -parentView.mScrollY); 4932 4933 if (!parentView.hasIdentityMatrix()) { 4934 parentView.getMatrix().mapRect(position); 4935 } 4936 4937 position.offset(parentView.mLeft, parentView.mTop); 4938 4939 parent = parentView.mParent; 4940 } 4941 4942 if (parent instanceof ViewRootImpl) { 4943 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 4944 position.offset(0, -viewRootImpl.mCurScrollY); 4945 } 4946 4947 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 4948 4949 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 4950 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 4951 } 4952 4953 /** 4954 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 4955 * 4956 * Note: Called from the default {@link AccessibilityDelegate}. 4957 */ 4958 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 4959 Rect bounds = mAttachInfo.mTmpInvalRect; 4960 4961 getDrawingRect(bounds); 4962 info.setBoundsInParent(bounds); 4963 4964 getBoundsOnScreen(bounds); 4965 info.setBoundsInScreen(bounds); 4966 4967 ViewParent parent = getParentForAccessibility(); 4968 if (parent instanceof View) { 4969 info.setParent((View) parent); 4970 } 4971 4972 if (mID != View.NO_ID) { 4973 View rootView = getRootView(); 4974 if (rootView == null) { 4975 rootView = this; 4976 } 4977 View label = rootView.findLabelForView(this, mID); 4978 if (label != null) { 4979 info.setLabeledBy(label); 4980 } 4981 } 4982 4983 if (mLabelForId != View.NO_ID) { 4984 View rootView = getRootView(); 4985 if (rootView == null) { 4986 rootView = this; 4987 } 4988 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 4989 if (labeled != null) { 4990 info.setLabelFor(labeled); 4991 } 4992 } 4993 4994 info.setVisibleToUser(isVisibleToUser()); 4995 4996 info.setPackageName(mContext.getPackageName()); 4997 info.setClassName(View.class.getName()); 4998 info.setContentDescription(getContentDescription()); 4999 5000 info.setEnabled(isEnabled()); 5001 info.setClickable(isClickable()); 5002 info.setFocusable(isFocusable()); 5003 info.setFocused(isFocused()); 5004 info.setAccessibilityFocused(isAccessibilityFocused()); 5005 info.setSelected(isSelected()); 5006 info.setLongClickable(isLongClickable()); 5007 5008 // TODO: These make sense only if we are in an AdapterView but all 5009 // views can be selected. Maybe from accessibility perspective 5010 // we should report as selectable view in an AdapterView. 5011 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5012 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5013 5014 if (isFocusable()) { 5015 if (isFocused()) { 5016 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5017 } else { 5018 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5019 } 5020 } 5021 5022 if (!isAccessibilityFocused()) { 5023 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5024 } else { 5025 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5026 } 5027 5028 if (isClickable() && isEnabled()) { 5029 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5030 } 5031 5032 if (isLongClickable() && isEnabled()) { 5033 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5034 } 5035 5036 if (mContentDescription != null && mContentDescription.length() > 0) { 5037 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5038 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5039 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5040 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5041 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5042 } 5043 } 5044 5045 private View findLabelForView(View view, int labeledId) { 5046 if (mMatchLabelForPredicate == null) { 5047 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5048 } 5049 mMatchLabelForPredicate.mLabeledId = labeledId; 5050 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5051 } 5052 5053 /** 5054 * Computes whether this view is visible to the user. Such a view is 5055 * attached, visible, all its predecessors are visible, it is not clipped 5056 * entirely by its predecessors, and has an alpha greater than zero. 5057 * 5058 * @return Whether the view is visible on the screen. 5059 * 5060 * @hide 5061 */ 5062 protected boolean isVisibleToUser() { 5063 return isVisibleToUser(null); 5064 } 5065 5066 /** 5067 * Computes whether the given portion of this view is visible to the user. 5068 * Such a view is attached, visible, all its predecessors are visible, 5069 * has an alpha greater than zero, and the specified portion is not 5070 * clipped entirely by its predecessors. 5071 * 5072 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5073 * <code>null</code>, and the entire view will be tested in this case. 5074 * When <code>true</code> is returned by the function, the actual visible 5075 * region will be stored in this parameter; that is, if boundInView is fully 5076 * contained within the view, no modification will be made, otherwise regions 5077 * outside of the visible area of the view will be clipped. 5078 * 5079 * @return Whether the specified portion of the view is visible on the screen. 5080 * 5081 * @hide 5082 */ 5083 protected boolean isVisibleToUser(Rect boundInView) { 5084 if (mAttachInfo != null) { 5085 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5086 Point offset = mAttachInfo.mPoint; 5087 // The first two checks are made also made by isShown() which 5088 // however traverses the tree up to the parent to catch that. 5089 // Therefore, we do some fail fast check to minimize the up 5090 // tree traversal. 5091 boolean isVisible = mAttachInfo.mWindowVisibility == View.VISIBLE 5092 && getAlpha() > 0 5093 && isShown() 5094 && getGlobalVisibleRect(visibleRect, offset); 5095 if (isVisible && boundInView != null) { 5096 visibleRect.offset(-offset.x, -offset.y); 5097 // isVisible is always true here, use a simple assignment 5098 isVisible = boundInView.intersect(visibleRect); 5099 } 5100 return isVisible; 5101 } 5102 5103 return false; 5104 } 5105 5106 /** 5107 * Returns the delegate for implementing accessibility support via 5108 * composition. For more details see {@link AccessibilityDelegate}. 5109 * 5110 * @return The delegate, or null if none set. 5111 * 5112 * @hide 5113 */ 5114 public AccessibilityDelegate getAccessibilityDelegate() { 5115 return mAccessibilityDelegate; 5116 } 5117 5118 /** 5119 * Sets a delegate for implementing accessibility support via composition as 5120 * opposed to inheritance. The delegate's primary use is for implementing 5121 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5122 * 5123 * @param delegate The delegate instance. 5124 * 5125 * @see AccessibilityDelegate 5126 */ 5127 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5128 mAccessibilityDelegate = delegate; 5129 } 5130 5131 /** 5132 * Gets the provider for managing a virtual view hierarchy rooted at this View 5133 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5134 * that explore the window content. 5135 * <p> 5136 * If this method returns an instance, this instance is responsible for managing 5137 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5138 * View including the one representing the View itself. Similarly the returned 5139 * instance is responsible for performing accessibility actions on any virtual 5140 * view or the root view itself. 5141 * </p> 5142 * <p> 5143 * If an {@link AccessibilityDelegate} has been specified via calling 5144 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5145 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5146 * is responsible for handling this call. 5147 * </p> 5148 * 5149 * @return The provider. 5150 * 5151 * @see AccessibilityNodeProvider 5152 */ 5153 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5154 if (mAccessibilityDelegate != null) { 5155 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5156 } else { 5157 return null; 5158 } 5159 } 5160 5161 /** 5162 * Gets the unique identifier of this view on the screen for accessibility purposes. 5163 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5164 * 5165 * @return The view accessibility id. 5166 * 5167 * @hide 5168 */ 5169 public int getAccessibilityViewId() { 5170 if (mAccessibilityViewId == NO_ID) { 5171 mAccessibilityViewId = sNextAccessibilityViewId++; 5172 } 5173 return mAccessibilityViewId; 5174 } 5175 5176 /** 5177 * Gets the unique identifier of the window in which this View reseides. 5178 * 5179 * @return The window accessibility id. 5180 * 5181 * @hide 5182 */ 5183 public int getAccessibilityWindowId() { 5184 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 5185 } 5186 5187 /** 5188 * Gets the {@link View} description. It briefly describes the view and is 5189 * primarily used for accessibility support. Set this property to enable 5190 * better accessibility support for your application. This is especially 5191 * true for views that do not have textual representation (For example, 5192 * ImageButton). 5193 * 5194 * @return The content description. 5195 * 5196 * @attr ref android.R.styleable#View_contentDescription 5197 */ 5198 @ViewDebug.ExportedProperty(category = "accessibility") 5199 public CharSequence getContentDescription() { 5200 return mContentDescription; 5201 } 5202 5203 /** 5204 * Sets the {@link View} description. It briefly describes the view and is 5205 * primarily used for accessibility support. Set this property to enable 5206 * better accessibility support for your application. This is especially 5207 * true for views that do not have textual representation (For example, 5208 * ImageButton). 5209 * 5210 * @param contentDescription The content description. 5211 * 5212 * @attr ref android.R.styleable#View_contentDescription 5213 */ 5214 @RemotableViewMethod 5215 public void setContentDescription(CharSequence contentDescription) { 5216 mContentDescription = contentDescription; 5217 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5218 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5219 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5220 } 5221 } 5222 5223 /** 5224 * Gets the id of a view for which this view serves as a label for 5225 * accessibility purposes. 5226 * 5227 * @return The labeled view id. 5228 */ 5229 @ViewDebug.ExportedProperty(category = "accessibility") 5230 public int getLabelFor() { 5231 return mLabelForId; 5232 } 5233 5234 /** 5235 * Sets the id of a view for which this view serves as a label for 5236 * accessibility purposes. 5237 * 5238 * @param id The labeled view id. 5239 */ 5240 @RemotableViewMethod 5241 public void setLabelFor(int id) { 5242 mLabelForId = id; 5243 if (mLabelForId != View.NO_ID 5244 && mID == View.NO_ID) { 5245 mID = generateViewId(); 5246 } 5247 } 5248 5249 /** 5250 * Invoked whenever this view loses focus, either by losing window focus or by losing 5251 * focus within its window. This method can be used to clear any state tied to the 5252 * focus. For instance, if a button is held pressed with the trackball and the window 5253 * loses focus, this method can be used to cancel the press. 5254 * 5255 * Subclasses of View overriding this method should always call super.onFocusLost(). 5256 * 5257 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5258 * @see #onWindowFocusChanged(boolean) 5259 * 5260 * @hide pending API council approval 5261 */ 5262 protected void onFocusLost() { 5263 resetPressedState(); 5264 } 5265 5266 private void resetPressedState() { 5267 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5268 return; 5269 } 5270 5271 if (isPressed()) { 5272 setPressed(false); 5273 5274 if (!mHasPerformedLongPress) { 5275 removeLongPressCallback(); 5276 } 5277 } 5278 } 5279 5280 /** 5281 * Returns true if this view has focus 5282 * 5283 * @return True if this view has focus, false otherwise. 5284 */ 5285 @ViewDebug.ExportedProperty(category = "focus") 5286 public boolean isFocused() { 5287 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5288 } 5289 5290 /** 5291 * Find the view in the hierarchy rooted at this view that currently has 5292 * focus. 5293 * 5294 * @return The view that currently has focus, or null if no focused view can 5295 * be found. 5296 */ 5297 public View findFocus() { 5298 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5299 } 5300 5301 /** 5302 * Indicates whether this view is one of the set of scrollable containers in 5303 * its window. 5304 * 5305 * @return whether this view is one of the set of scrollable containers in 5306 * its window 5307 * 5308 * @attr ref android.R.styleable#View_isScrollContainer 5309 */ 5310 public boolean isScrollContainer() { 5311 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5312 } 5313 5314 /** 5315 * Change whether this view is one of the set of scrollable containers in 5316 * its window. This will be used to determine whether the window can 5317 * resize or must pan when a soft input area is open -- scrollable 5318 * containers allow the window to use resize mode since the container 5319 * will appropriately shrink. 5320 * 5321 * @attr ref android.R.styleable#View_isScrollContainer 5322 */ 5323 public void setScrollContainer(boolean isScrollContainer) { 5324 if (isScrollContainer) { 5325 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5326 mAttachInfo.mScrollContainers.add(this); 5327 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5328 } 5329 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5330 } else { 5331 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5332 mAttachInfo.mScrollContainers.remove(this); 5333 } 5334 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5335 } 5336 } 5337 5338 /** 5339 * Returns the quality of the drawing cache. 5340 * 5341 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5342 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5343 * 5344 * @see #setDrawingCacheQuality(int) 5345 * @see #setDrawingCacheEnabled(boolean) 5346 * @see #isDrawingCacheEnabled() 5347 * 5348 * @attr ref android.R.styleable#View_drawingCacheQuality 5349 */ 5350 public int getDrawingCacheQuality() { 5351 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5352 } 5353 5354 /** 5355 * Set the drawing cache quality of this view. This value is used only when the 5356 * drawing cache is enabled 5357 * 5358 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5359 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5360 * 5361 * @see #getDrawingCacheQuality() 5362 * @see #setDrawingCacheEnabled(boolean) 5363 * @see #isDrawingCacheEnabled() 5364 * 5365 * @attr ref android.R.styleable#View_drawingCacheQuality 5366 */ 5367 public void setDrawingCacheQuality(int quality) { 5368 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5369 } 5370 5371 /** 5372 * Returns whether the screen should remain on, corresponding to the current 5373 * value of {@link #KEEP_SCREEN_ON}. 5374 * 5375 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5376 * 5377 * @see #setKeepScreenOn(boolean) 5378 * 5379 * @attr ref android.R.styleable#View_keepScreenOn 5380 */ 5381 public boolean getKeepScreenOn() { 5382 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5383 } 5384 5385 /** 5386 * Controls whether the screen should remain on, modifying the 5387 * value of {@link #KEEP_SCREEN_ON}. 5388 * 5389 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5390 * 5391 * @see #getKeepScreenOn() 5392 * 5393 * @attr ref android.R.styleable#View_keepScreenOn 5394 */ 5395 public void setKeepScreenOn(boolean keepScreenOn) { 5396 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5397 } 5398 5399 /** 5400 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5401 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5402 * 5403 * @attr ref android.R.styleable#View_nextFocusLeft 5404 */ 5405 public int getNextFocusLeftId() { 5406 return mNextFocusLeftId; 5407 } 5408 5409 /** 5410 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5411 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5412 * decide automatically. 5413 * 5414 * @attr ref android.R.styleable#View_nextFocusLeft 5415 */ 5416 public void setNextFocusLeftId(int nextFocusLeftId) { 5417 mNextFocusLeftId = nextFocusLeftId; 5418 } 5419 5420 /** 5421 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5422 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5423 * 5424 * @attr ref android.R.styleable#View_nextFocusRight 5425 */ 5426 public int getNextFocusRightId() { 5427 return mNextFocusRightId; 5428 } 5429 5430 /** 5431 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5432 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5433 * decide automatically. 5434 * 5435 * @attr ref android.R.styleable#View_nextFocusRight 5436 */ 5437 public void setNextFocusRightId(int nextFocusRightId) { 5438 mNextFocusRightId = nextFocusRightId; 5439 } 5440 5441 /** 5442 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5443 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5444 * 5445 * @attr ref android.R.styleable#View_nextFocusUp 5446 */ 5447 public int getNextFocusUpId() { 5448 return mNextFocusUpId; 5449 } 5450 5451 /** 5452 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5453 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5454 * decide automatically. 5455 * 5456 * @attr ref android.R.styleable#View_nextFocusUp 5457 */ 5458 public void setNextFocusUpId(int nextFocusUpId) { 5459 mNextFocusUpId = nextFocusUpId; 5460 } 5461 5462 /** 5463 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5464 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5465 * 5466 * @attr ref android.R.styleable#View_nextFocusDown 5467 */ 5468 public int getNextFocusDownId() { 5469 return mNextFocusDownId; 5470 } 5471 5472 /** 5473 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5474 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5475 * decide automatically. 5476 * 5477 * @attr ref android.R.styleable#View_nextFocusDown 5478 */ 5479 public void setNextFocusDownId(int nextFocusDownId) { 5480 mNextFocusDownId = nextFocusDownId; 5481 } 5482 5483 /** 5484 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5485 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5486 * 5487 * @attr ref android.R.styleable#View_nextFocusForward 5488 */ 5489 public int getNextFocusForwardId() { 5490 return mNextFocusForwardId; 5491 } 5492 5493 /** 5494 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5495 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 5496 * decide automatically. 5497 * 5498 * @attr ref android.R.styleable#View_nextFocusForward 5499 */ 5500 public void setNextFocusForwardId(int nextFocusForwardId) { 5501 mNextFocusForwardId = nextFocusForwardId; 5502 } 5503 5504 /** 5505 * Returns the visibility of this view and all of its ancestors 5506 * 5507 * @return True if this view and all of its ancestors are {@link #VISIBLE} 5508 */ 5509 public boolean isShown() { 5510 View current = this; 5511 //noinspection ConstantConditions 5512 do { 5513 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5514 return false; 5515 } 5516 ViewParent parent = current.mParent; 5517 if (parent == null) { 5518 return false; // We are not attached to the view root 5519 } 5520 if (!(parent instanceof View)) { 5521 return true; 5522 } 5523 current = (View) parent; 5524 } while (current != null); 5525 5526 return false; 5527 } 5528 5529 /** 5530 * Called by the view hierarchy when the content insets for a window have 5531 * changed, to allow it to adjust its content to fit within those windows. 5532 * The content insets tell you the space that the status bar, input method, 5533 * and other system windows infringe on the application's window. 5534 * 5535 * <p>You do not normally need to deal with this function, since the default 5536 * window decoration given to applications takes care of applying it to the 5537 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 5538 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 5539 * and your content can be placed under those system elements. You can then 5540 * use this method within your view hierarchy if you have parts of your UI 5541 * which you would like to ensure are not being covered. 5542 * 5543 * <p>The default implementation of this method simply applies the content 5544 * inset's to the view's padding, consuming that content (modifying the 5545 * insets to be 0), and returning true. This behavior is off by default, but can 5546 * be enabled through {@link #setFitsSystemWindows(boolean)}. 5547 * 5548 * <p>This function's traversal down the hierarchy is depth-first. The same content 5549 * insets object is propagated down the hierarchy, so any changes made to it will 5550 * be seen by all following views (including potentially ones above in 5551 * the hierarchy since this is a depth-first traversal). The first view 5552 * that returns true will abort the entire traversal. 5553 * 5554 * <p>The default implementation works well for a situation where it is 5555 * used with a container that covers the entire window, allowing it to 5556 * apply the appropriate insets to its content on all edges. If you need 5557 * a more complicated layout (such as two different views fitting system 5558 * windows, one on the top of the window, and one on the bottom), 5559 * you can override the method and handle the insets however you would like. 5560 * Note that the insets provided by the framework are always relative to the 5561 * far edges of the window, not accounting for the location of the called view 5562 * within that window. (In fact when this method is called you do not yet know 5563 * where the layout will place the view, as it is done before layout happens.) 5564 * 5565 * <p>Note: unlike many View methods, there is no dispatch phase to this 5566 * call. If you are overriding it in a ViewGroup and want to allow the 5567 * call to continue to your children, you must be sure to call the super 5568 * implementation. 5569 * 5570 * <p>Here is a sample layout that makes use of fitting system windows 5571 * to have controls for a video view placed inside of the window decorations 5572 * that it hides and shows. This can be used with code like the second 5573 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 5574 * 5575 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 5576 * 5577 * @param insets Current content insets of the window. Prior to 5578 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 5579 * the insets or else you and Android will be unhappy. 5580 * 5581 * @return Return true if this view applied the insets and it should not 5582 * continue propagating further down the hierarchy, false otherwise. 5583 * @see #getFitsSystemWindows() 5584 * @see #setFitsSystemWindows(boolean) 5585 * @see #setSystemUiVisibility(int) 5586 */ 5587 protected boolean fitSystemWindows(Rect insets) { 5588 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 5589 mUserPaddingStart = UNDEFINED_PADDING; 5590 mUserPaddingEnd = UNDEFINED_PADDING; 5591 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 5592 || mAttachInfo == null 5593 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 5594 internalSetPadding(insets.left, insets.top, insets.right, insets.bottom); 5595 return true; 5596 } else { 5597 internalSetPadding(0, 0, 0, 0); 5598 return false; 5599 } 5600 } 5601 return false; 5602 } 5603 5604 /** 5605 * Sets whether or not this view should account for system screen decorations 5606 * such as the status bar and inset its content; that is, controlling whether 5607 * the default implementation of {@link #fitSystemWindows(Rect)} will be 5608 * executed. See that method for more details. 5609 * 5610 * <p>Note that if you are providing your own implementation of 5611 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 5612 * flag to true -- your implementation will be overriding the default 5613 * implementation that checks this flag. 5614 * 5615 * @param fitSystemWindows If true, then the default implementation of 5616 * {@link #fitSystemWindows(Rect)} will be executed. 5617 * 5618 * @attr ref android.R.styleable#View_fitsSystemWindows 5619 * @see #getFitsSystemWindows() 5620 * @see #fitSystemWindows(Rect) 5621 * @see #setSystemUiVisibility(int) 5622 */ 5623 public void setFitsSystemWindows(boolean fitSystemWindows) { 5624 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 5625 } 5626 5627 /** 5628 * Check for state of {@link #setFitsSystemWindows(boolean). If this method 5629 * returns true, the default implementation of {@link #fitSystemWindows(Rect)} 5630 * will be executed. 5631 * 5632 * @return Returns true if the default implementation of 5633 * {@link #fitSystemWindows(Rect)} will be executed. 5634 * 5635 * @attr ref android.R.styleable#View_fitsSystemWindows 5636 * @see #setFitsSystemWindows() 5637 * @see #fitSystemWindows(Rect) 5638 * @see #setSystemUiVisibility(int) 5639 */ 5640 public boolean getFitsSystemWindows() { 5641 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 5642 } 5643 5644 /** @hide */ 5645 public boolean fitsSystemWindows() { 5646 return getFitsSystemWindows(); 5647 } 5648 5649 /** 5650 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 5651 */ 5652 public void requestFitSystemWindows() { 5653 if (mParent != null) { 5654 mParent.requestFitSystemWindows(); 5655 } 5656 } 5657 5658 /** 5659 * For use by PhoneWindow to make its own system window fitting optional. 5660 * @hide 5661 */ 5662 public void makeOptionalFitsSystemWindows() { 5663 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 5664 } 5665 5666 /** 5667 * Returns the visibility status for this view. 5668 * 5669 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5670 * @attr ref android.R.styleable#View_visibility 5671 */ 5672 @ViewDebug.ExportedProperty(mapping = { 5673 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 5674 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 5675 @ViewDebug.IntToString(from = GONE, to = "GONE") 5676 }) 5677 public int getVisibility() { 5678 return mViewFlags & VISIBILITY_MASK; 5679 } 5680 5681 /** 5682 * Set the enabled state of this view. 5683 * 5684 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5685 * @attr ref android.R.styleable#View_visibility 5686 */ 5687 @RemotableViewMethod 5688 public void setVisibility(int visibility) { 5689 setFlags(visibility, VISIBILITY_MASK); 5690 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 5691 } 5692 5693 /** 5694 * Returns the enabled status for this view. The interpretation of the 5695 * enabled state varies by subclass. 5696 * 5697 * @return True if this view is enabled, false otherwise. 5698 */ 5699 @ViewDebug.ExportedProperty 5700 public boolean isEnabled() { 5701 return (mViewFlags & ENABLED_MASK) == ENABLED; 5702 } 5703 5704 /** 5705 * Set the enabled state of this view. The interpretation of the enabled 5706 * state varies by subclass. 5707 * 5708 * @param enabled True if this view is enabled, false otherwise. 5709 */ 5710 @RemotableViewMethod 5711 public void setEnabled(boolean enabled) { 5712 if (enabled == isEnabled()) return; 5713 5714 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 5715 5716 /* 5717 * The View most likely has to change its appearance, so refresh 5718 * the drawable state. 5719 */ 5720 refreshDrawableState(); 5721 5722 // Invalidate too, since the default behavior for views is to be 5723 // be drawn at 50% alpha rather than to change the drawable. 5724 invalidate(true); 5725 } 5726 5727 /** 5728 * Set whether this view can receive the focus. 5729 * 5730 * Setting this to false will also ensure that this view is not focusable 5731 * in touch mode. 5732 * 5733 * @param focusable If true, this view can receive the focus. 5734 * 5735 * @see #setFocusableInTouchMode(boolean) 5736 * @attr ref android.R.styleable#View_focusable 5737 */ 5738 public void setFocusable(boolean focusable) { 5739 if (!focusable) { 5740 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 5741 } 5742 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 5743 } 5744 5745 /** 5746 * Set whether this view can receive focus while in touch mode. 5747 * 5748 * Setting this to true will also ensure that this view is focusable. 5749 * 5750 * @param focusableInTouchMode If true, this view can receive the focus while 5751 * in touch mode. 5752 * 5753 * @see #setFocusable(boolean) 5754 * @attr ref android.R.styleable#View_focusableInTouchMode 5755 */ 5756 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 5757 // Focusable in touch mode should always be set before the focusable flag 5758 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 5759 // which, in touch mode, will not successfully request focus on this view 5760 // because the focusable in touch mode flag is not set 5761 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 5762 if (focusableInTouchMode) { 5763 setFlags(FOCUSABLE, FOCUSABLE_MASK); 5764 } 5765 } 5766 5767 /** 5768 * Set whether this view should have sound effects enabled for events such as 5769 * clicking and touching. 5770 * 5771 * <p>You may wish to disable sound effects for a view if you already play sounds, 5772 * for instance, a dial key that plays dtmf tones. 5773 * 5774 * @param soundEffectsEnabled whether sound effects are enabled for this view. 5775 * @see #isSoundEffectsEnabled() 5776 * @see #playSoundEffect(int) 5777 * @attr ref android.R.styleable#View_soundEffectsEnabled 5778 */ 5779 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 5780 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 5781 } 5782 5783 /** 5784 * @return whether this view should have sound effects enabled for events such as 5785 * clicking and touching. 5786 * 5787 * @see #setSoundEffectsEnabled(boolean) 5788 * @see #playSoundEffect(int) 5789 * @attr ref android.R.styleable#View_soundEffectsEnabled 5790 */ 5791 @ViewDebug.ExportedProperty 5792 public boolean isSoundEffectsEnabled() { 5793 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 5794 } 5795 5796 /** 5797 * Set whether this view should have haptic feedback for events such as 5798 * long presses. 5799 * 5800 * <p>You may wish to disable haptic feedback if your view already controls 5801 * its own haptic feedback. 5802 * 5803 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 5804 * @see #isHapticFeedbackEnabled() 5805 * @see #performHapticFeedback(int) 5806 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5807 */ 5808 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 5809 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 5810 } 5811 5812 /** 5813 * @return whether this view should have haptic feedback enabled for events 5814 * long presses. 5815 * 5816 * @see #setHapticFeedbackEnabled(boolean) 5817 * @see #performHapticFeedback(int) 5818 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5819 */ 5820 @ViewDebug.ExportedProperty 5821 public boolean isHapticFeedbackEnabled() { 5822 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 5823 } 5824 5825 /** 5826 * Returns the layout direction for this view. 5827 * 5828 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 5829 * {@link #LAYOUT_DIRECTION_RTL}, 5830 * {@link #LAYOUT_DIRECTION_INHERIT} or 5831 * {@link #LAYOUT_DIRECTION_LOCALE}. 5832 * @attr ref android.R.styleable#View_layoutDirection 5833 * 5834 * @hide 5835 */ 5836 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5837 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 5838 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 5839 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 5840 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 5841 }) 5842 public int getRawLayoutDirection() { 5843 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 5844 } 5845 5846 /** 5847 * Set the layout direction for this view. This will propagate a reset of layout direction 5848 * resolution to the view's children and resolve layout direction for this view. 5849 * 5850 * @param layoutDirection the layout direction to set. Should be one of: 5851 * 5852 * {@link #LAYOUT_DIRECTION_LTR}, 5853 * {@link #LAYOUT_DIRECTION_RTL}, 5854 * {@link #LAYOUT_DIRECTION_INHERIT}, 5855 * {@link #LAYOUT_DIRECTION_LOCALE}. 5856 * 5857 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 5858 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 5859 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 5860 * 5861 * @attr ref android.R.styleable#View_layoutDirection 5862 */ 5863 @RemotableViewMethod 5864 public void setLayoutDirection(int layoutDirection) { 5865 if (getRawLayoutDirection() != layoutDirection) { 5866 // Reset the current layout direction and the resolved one 5867 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 5868 resetRtlProperties(); 5869 // Set the new layout direction (filtered) 5870 mPrivateFlags2 |= 5871 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 5872 // We need to resolve all RTL properties as they all depend on layout direction 5873 resolveRtlPropertiesIfNeeded(); 5874 } 5875 } 5876 5877 /** 5878 * Returns the resolved layout direction for this view. 5879 * 5880 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 5881 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 5882 * 5883 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 5884 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 5885 */ 5886 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5887 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 5888 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 5889 }) 5890 public int getLayoutDirection() { 5891 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 5892 if (targetSdkVersion < JELLY_BEAN_MR1) { 5893 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 5894 return LAYOUT_DIRECTION_LTR; 5895 } 5896 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 5897 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 5898 } 5899 5900 /** 5901 * Indicates whether or not this view's layout is right-to-left. This is resolved from 5902 * layout attribute and/or the inherited value from the parent 5903 * 5904 * @return true if the layout is right-to-left. 5905 * 5906 * @hide 5907 */ 5908 @ViewDebug.ExportedProperty(category = "layout") 5909 public boolean isLayoutRtl() { 5910 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 5911 } 5912 5913 /** 5914 * Indicates whether the view is currently tracking transient state that the 5915 * app should not need to concern itself with saving and restoring, but that 5916 * the framework should take special note to preserve when possible. 5917 * 5918 * <p>A view with transient state cannot be trivially rebound from an external 5919 * data source, such as an adapter binding item views in a list. This may be 5920 * because the view is performing an animation, tracking user selection 5921 * of content, or similar.</p> 5922 * 5923 * @return true if the view has transient state 5924 */ 5925 @ViewDebug.ExportedProperty(category = "layout") 5926 public boolean hasTransientState() { 5927 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 5928 } 5929 5930 /** 5931 * Set whether this view is currently tracking transient state that the 5932 * framework should attempt to preserve when possible. This flag is reference counted, 5933 * so every call to setHasTransientState(true) should be paired with a later call 5934 * to setHasTransientState(false). 5935 * 5936 * <p>A view with transient state cannot be trivially rebound from an external 5937 * data source, such as an adapter binding item views in a list. This may be 5938 * because the view is performing an animation, tracking user selection 5939 * of content, or similar.</p> 5940 * 5941 * @param hasTransientState true if this view has transient state 5942 */ 5943 public void setHasTransientState(boolean hasTransientState) { 5944 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 5945 mTransientStateCount - 1; 5946 if (mTransientStateCount < 0) { 5947 mTransientStateCount = 0; 5948 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 5949 "unmatched pair of setHasTransientState calls"); 5950 } 5951 if ((hasTransientState && mTransientStateCount == 1) || 5952 (!hasTransientState && mTransientStateCount == 0)) { 5953 // update flag if we've just incremented up from 0 or decremented down to 0 5954 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 5955 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 5956 if (mParent != null) { 5957 try { 5958 mParent.childHasTransientStateChanged(this, hasTransientState); 5959 } catch (AbstractMethodError e) { 5960 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 5961 " does not fully implement ViewParent", e); 5962 } 5963 } 5964 } 5965 } 5966 5967 /** 5968 * If this view doesn't do any drawing on its own, set this flag to 5969 * allow further optimizations. By default, this flag is not set on 5970 * View, but could be set on some View subclasses such as ViewGroup. 5971 * 5972 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 5973 * you should clear this flag. 5974 * 5975 * @param willNotDraw whether or not this View draw on its own 5976 */ 5977 public void setWillNotDraw(boolean willNotDraw) { 5978 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 5979 } 5980 5981 /** 5982 * Returns whether or not this View draws on its own. 5983 * 5984 * @return true if this view has nothing to draw, false otherwise 5985 */ 5986 @ViewDebug.ExportedProperty(category = "drawing") 5987 public boolean willNotDraw() { 5988 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 5989 } 5990 5991 /** 5992 * When a View's drawing cache is enabled, drawing is redirected to an 5993 * offscreen bitmap. Some views, like an ImageView, must be able to 5994 * bypass this mechanism if they already draw a single bitmap, to avoid 5995 * unnecessary usage of the memory. 5996 * 5997 * @param willNotCacheDrawing true if this view does not cache its 5998 * drawing, false otherwise 5999 */ 6000 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6001 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6002 } 6003 6004 /** 6005 * Returns whether or not this View can cache its drawing or not. 6006 * 6007 * @return true if this view does not cache its drawing, false otherwise 6008 */ 6009 @ViewDebug.ExportedProperty(category = "drawing") 6010 public boolean willNotCacheDrawing() { 6011 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6012 } 6013 6014 /** 6015 * Indicates whether this view reacts to click events or not. 6016 * 6017 * @return true if the view is clickable, false otherwise 6018 * 6019 * @see #setClickable(boolean) 6020 * @attr ref android.R.styleable#View_clickable 6021 */ 6022 @ViewDebug.ExportedProperty 6023 public boolean isClickable() { 6024 return (mViewFlags & CLICKABLE) == CLICKABLE; 6025 } 6026 6027 /** 6028 * Enables or disables click events for this view. When a view 6029 * is clickable it will change its state to "pressed" on every click. 6030 * Subclasses should set the view clickable to visually react to 6031 * user's clicks. 6032 * 6033 * @param clickable true to make the view clickable, false otherwise 6034 * 6035 * @see #isClickable() 6036 * @attr ref android.R.styleable#View_clickable 6037 */ 6038 public void setClickable(boolean clickable) { 6039 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6040 } 6041 6042 /** 6043 * Indicates whether this view reacts to long click events or not. 6044 * 6045 * @return true if the view is long clickable, false otherwise 6046 * 6047 * @see #setLongClickable(boolean) 6048 * @attr ref android.R.styleable#View_longClickable 6049 */ 6050 public boolean isLongClickable() { 6051 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6052 } 6053 6054 /** 6055 * Enables or disables long click events for this view. When a view is long 6056 * clickable it reacts to the user holding down the button for a longer 6057 * duration than a tap. This event can either launch the listener or a 6058 * context menu. 6059 * 6060 * @param longClickable true to make the view long clickable, false otherwise 6061 * @see #isLongClickable() 6062 * @attr ref android.R.styleable#View_longClickable 6063 */ 6064 public void setLongClickable(boolean longClickable) { 6065 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6066 } 6067 6068 /** 6069 * Sets the pressed state for this view. 6070 * 6071 * @see #isClickable() 6072 * @see #setClickable(boolean) 6073 * 6074 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6075 * the View's internal state from a previously set "pressed" state. 6076 */ 6077 public void setPressed(boolean pressed) { 6078 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6079 6080 if (pressed) { 6081 mPrivateFlags |= PFLAG_PRESSED; 6082 } else { 6083 mPrivateFlags &= ~PFLAG_PRESSED; 6084 } 6085 6086 if (needsRefresh) { 6087 refreshDrawableState(); 6088 } 6089 dispatchSetPressed(pressed); 6090 } 6091 6092 /** 6093 * Dispatch setPressed to all of this View's children. 6094 * 6095 * @see #setPressed(boolean) 6096 * 6097 * @param pressed The new pressed state 6098 */ 6099 protected void dispatchSetPressed(boolean pressed) { 6100 } 6101 6102 /** 6103 * Indicates whether the view is currently in pressed state. Unless 6104 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6105 * the pressed state. 6106 * 6107 * @see #setPressed(boolean) 6108 * @see #isClickable() 6109 * @see #setClickable(boolean) 6110 * 6111 * @return true if the view is currently pressed, false otherwise 6112 */ 6113 public boolean isPressed() { 6114 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6115 } 6116 6117 /** 6118 * Indicates whether this view will save its state (that is, 6119 * whether its {@link #onSaveInstanceState} method will be called). 6120 * 6121 * @return Returns true if the view state saving is enabled, else false. 6122 * 6123 * @see #setSaveEnabled(boolean) 6124 * @attr ref android.R.styleable#View_saveEnabled 6125 */ 6126 public boolean isSaveEnabled() { 6127 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6128 } 6129 6130 /** 6131 * Controls whether the saving of this view's state is 6132 * enabled (that is, whether its {@link #onSaveInstanceState} method 6133 * will be called). Note that even if freezing is enabled, the 6134 * view still must have an id assigned to it (via {@link #setId(int)}) 6135 * for its state to be saved. This flag can only disable the 6136 * saving of this view; any child views may still have their state saved. 6137 * 6138 * @param enabled Set to false to <em>disable</em> state saving, or true 6139 * (the default) to allow it. 6140 * 6141 * @see #isSaveEnabled() 6142 * @see #setId(int) 6143 * @see #onSaveInstanceState() 6144 * @attr ref android.R.styleable#View_saveEnabled 6145 */ 6146 public void setSaveEnabled(boolean enabled) { 6147 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6148 } 6149 6150 /** 6151 * Gets whether the framework should discard touches when the view's 6152 * window is obscured by another visible window. 6153 * Refer to the {@link View} security documentation for more details. 6154 * 6155 * @return True if touch filtering is enabled. 6156 * 6157 * @see #setFilterTouchesWhenObscured(boolean) 6158 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6159 */ 6160 @ViewDebug.ExportedProperty 6161 public boolean getFilterTouchesWhenObscured() { 6162 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6163 } 6164 6165 /** 6166 * Sets whether the framework should discard touches when the view's 6167 * window is obscured by another visible window. 6168 * Refer to the {@link View} security documentation for more details. 6169 * 6170 * @param enabled True if touch filtering should be enabled. 6171 * 6172 * @see #getFilterTouchesWhenObscured 6173 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6174 */ 6175 public void setFilterTouchesWhenObscured(boolean enabled) { 6176 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 6177 FILTER_TOUCHES_WHEN_OBSCURED); 6178 } 6179 6180 /** 6181 * Indicates whether the entire hierarchy under this view will save its 6182 * state when a state saving traversal occurs from its parent. The default 6183 * is true; if false, these views will not be saved unless 6184 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6185 * 6186 * @return Returns true if the view state saving from parent is enabled, else false. 6187 * 6188 * @see #setSaveFromParentEnabled(boolean) 6189 */ 6190 public boolean isSaveFromParentEnabled() { 6191 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6192 } 6193 6194 /** 6195 * Controls whether the entire hierarchy under this view will save its 6196 * state when a state saving traversal occurs from its parent. The default 6197 * is true; if false, these views will not be saved unless 6198 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6199 * 6200 * @param enabled Set to false to <em>disable</em> state saving, or true 6201 * (the default) to allow it. 6202 * 6203 * @see #isSaveFromParentEnabled() 6204 * @see #setId(int) 6205 * @see #onSaveInstanceState() 6206 */ 6207 public void setSaveFromParentEnabled(boolean enabled) { 6208 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6209 } 6210 6211 6212 /** 6213 * Returns whether this View is able to take focus. 6214 * 6215 * @return True if this view can take focus, or false otherwise. 6216 * @attr ref android.R.styleable#View_focusable 6217 */ 6218 @ViewDebug.ExportedProperty(category = "focus") 6219 public final boolean isFocusable() { 6220 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6221 } 6222 6223 /** 6224 * When a view is focusable, it may not want to take focus when in touch mode. 6225 * For example, a button would like focus when the user is navigating via a D-pad 6226 * so that the user can click on it, but once the user starts touching the screen, 6227 * the button shouldn't take focus 6228 * @return Whether the view is focusable in touch mode. 6229 * @attr ref android.R.styleable#View_focusableInTouchMode 6230 */ 6231 @ViewDebug.ExportedProperty 6232 public final boolean isFocusableInTouchMode() { 6233 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6234 } 6235 6236 /** 6237 * Find the nearest view in the specified direction that can take focus. 6238 * This does not actually give focus to that view. 6239 * 6240 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6241 * 6242 * @return The nearest focusable in the specified direction, or null if none 6243 * can be found. 6244 */ 6245 public View focusSearch(int direction) { 6246 if (mParent != null) { 6247 return mParent.focusSearch(this, direction); 6248 } else { 6249 return null; 6250 } 6251 } 6252 6253 /** 6254 * This method is the last chance for the focused view and its ancestors to 6255 * respond to an arrow key. This is called when the focused view did not 6256 * consume the key internally, nor could the view system find a new view in 6257 * the requested direction to give focus to. 6258 * 6259 * @param focused The currently focused view. 6260 * @param direction The direction focus wants to move. One of FOCUS_UP, 6261 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6262 * @return True if the this view consumed this unhandled move. 6263 */ 6264 public boolean dispatchUnhandledMove(View focused, int direction) { 6265 return false; 6266 } 6267 6268 /** 6269 * If a user manually specified the next view id for a particular direction, 6270 * use the root to look up the view. 6271 * @param root The root view of the hierarchy containing this view. 6272 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6273 * or FOCUS_BACKWARD. 6274 * @return The user specified next view, or null if there is none. 6275 */ 6276 View findUserSetNextFocus(View root, int direction) { 6277 switch (direction) { 6278 case FOCUS_LEFT: 6279 if (mNextFocusLeftId == View.NO_ID) return null; 6280 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6281 case FOCUS_RIGHT: 6282 if (mNextFocusRightId == View.NO_ID) return null; 6283 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6284 case FOCUS_UP: 6285 if (mNextFocusUpId == View.NO_ID) return null; 6286 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6287 case FOCUS_DOWN: 6288 if (mNextFocusDownId == View.NO_ID) return null; 6289 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6290 case FOCUS_FORWARD: 6291 if (mNextFocusForwardId == View.NO_ID) return null; 6292 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6293 case FOCUS_BACKWARD: { 6294 if (mID == View.NO_ID) return null; 6295 final int id = mID; 6296 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6297 @Override 6298 public boolean apply(View t) { 6299 return t.mNextFocusForwardId == id; 6300 } 6301 }); 6302 } 6303 } 6304 return null; 6305 } 6306 6307 private View findViewInsideOutShouldExist(View root, int id) { 6308 if (mMatchIdPredicate == null) { 6309 mMatchIdPredicate = new MatchIdPredicate(); 6310 } 6311 mMatchIdPredicate.mId = id; 6312 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6313 if (result == null) { 6314 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6315 } 6316 return result; 6317 } 6318 6319 /** 6320 * Find and return all focusable views that are descendants of this view, 6321 * possibly including this view if it is focusable itself. 6322 * 6323 * @param direction The direction of the focus 6324 * @return A list of focusable views 6325 */ 6326 public ArrayList<View> getFocusables(int direction) { 6327 ArrayList<View> result = new ArrayList<View>(24); 6328 addFocusables(result, direction); 6329 return result; 6330 } 6331 6332 /** 6333 * Add any focusable views that are descendants of this view (possibly 6334 * including this view if it is focusable itself) to views. If we are in touch mode, 6335 * only add views that are also focusable in touch mode. 6336 * 6337 * @param views Focusable views found so far 6338 * @param direction The direction of the focus 6339 */ 6340 public void addFocusables(ArrayList<View> views, int direction) { 6341 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6342 } 6343 6344 /** 6345 * Adds any focusable views that are descendants of this view (possibly 6346 * including this view if it is focusable itself) to views. This method 6347 * adds all focusable views regardless if we are in touch mode or 6348 * only views focusable in touch mode if we are in touch mode or 6349 * only views that can take accessibility focus if accessibility is enabeld 6350 * depending on the focusable mode paramater. 6351 * 6352 * @param views Focusable views found so far or null if all we are interested is 6353 * the number of focusables. 6354 * @param direction The direction of the focus. 6355 * @param focusableMode The type of focusables to be added. 6356 * 6357 * @see #FOCUSABLES_ALL 6358 * @see #FOCUSABLES_TOUCH_MODE 6359 */ 6360 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 6361 if (views == null) { 6362 return; 6363 } 6364 if (!isFocusable()) { 6365 return; 6366 } 6367 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6368 && isInTouchMode() && !isFocusableInTouchMode()) { 6369 return; 6370 } 6371 views.add(this); 6372 } 6373 6374 /** 6375 * Finds the Views that contain given text. The containment is case insensitive. 6376 * The search is performed by either the text that the View renders or the content 6377 * description that describes the view for accessibility purposes and the view does 6378 * not render or both. Clients can specify how the search is to be performed via 6379 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 6380 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 6381 * 6382 * @param outViews The output list of matching Views. 6383 * @param searched The text to match against. 6384 * 6385 * @see #FIND_VIEWS_WITH_TEXT 6386 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 6387 * @see #setContentDescription(CharSequence) 6388 */ 6389 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 6390 if (getAccessibilityNodeProvider() != null) { 6391 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 6392 outViews.add(this); 6393 } 6394 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 6395 && (searched != null && searched.length() > 0) 6396 && (mContentDescription != null && mContentDescription.length() > 0)) { 6397 String searchedLowerCase = searched.toString().toLowerCase(); 6398 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 6399 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 6400 outViews.add(this); 6401 } 6402 } 6403 } 6404 6405 /** 6406 * Find and return all touchable views that are descendants of this view, 6407 * possibly including this view if it is touchable itself. 6408 * 6409 * @return A list of touchable views 6410 */ 6411 public ArrayList<View> getTouchables() { 6412 ArrayList<View> result = new ArrayList<View>(); 6413 addTouchables(result); 6414 return result; 6415 } 6416 6417 /** 6418 * Add any touchable views that are descendants of this view (possibly 6419 * including this view if it is touchable itself) to views. 6420 * 6421 * @param views Touchable views found so far 6422 */ 6423 public void addTouchables(ArrayList<View> views) { 6424 final int viewFlags = mViewFlags; 6425 6426 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 6427 && (viewFlags & ENABLED_MASK) == ENABLED) { 6428 views.add(this); 6429 } 6430 } 6431 6432 /** 6433 * Returns whether this View is accessibility focused. 6434 * 6435 * @return True if this View is accessibility focused. 6436 */ 6437 boolean isAccessibilityFocused() { 6438 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 6439 } 6440 6441 /** 6442 * Call this to try to give accessibility focus to this view. 6443 * 6444 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 6445 * returns false or the view is no visible or the view already has accessibility 6446 * focus. 6447 * 6448 * See also {@link #focusSearch(int)}, which is what you call to say that you 6449 * have focus, and you want your parent to look for the next one. 6450 * 6451 * @return Whether this view actually took accessibility focus. 6452 * 6453 * @hide 6454 */ 6455 public boolean requestAccessibilityFocus() { 6456 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 6457 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 6458 return false; 6459 } 6460 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6461 return false; 6462 } 6463 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 6464 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 6465 ViewRootImpl viewRootImpl = getViewRootImpl(); 6466 if (viewRootImpl != null) { 6467 viewRootImpl.setAccessibilityFocus(this, null); 6468 } 6469 invalidate(); 6470 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 6471 notifyAccessibilityStateChanged(); 6472 return true; 6473 } 6474 return false; 6475 } 6476 6477 /** 6478 * Call this to try to clear accessibility focus of this view. 6479 * 6480 * See also {@link #focusSearch(int)}, which is what you call to say that you 6481 * have focus, and you want your parent to look for the next one. 6482 * 6483 * @hide 6484 */ 6485 public void clearAccessibilityFocus() { 6486 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6487 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6488 invalidate(); 6489 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 6490 notifyAccessibilityStateChanged(); 6491 } 6492 // Clear the global reference of accessibility focus if this 6493 // view or any of its descendants had accessibility focus. 6494 ViewRootImpl viewRootImpl = getViewRootImpl(); 6495 if (viewRootImpl != null) { 6496 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 6497 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 6498 viewRootImpl.setAccessibilityFocus(null, null); 6499 } 6500 } 6501 } 6502 6503 private void sendAccessibilityHoverEvent(int eventType) { 6504 // Since we are not delivering to a client accessibility events from not 6505 // important views (unless the clinet request that) we need to fire the 6506 // event from the deepest view exposed to the client. As a consequence if 6507 // the user crosses a not exposed view the client will see enter and exit 6508 // of the exposed predecessor followed by and enter and exit of that same 6509 // predecessor when entering and exiting the not exposed descendant. This 6510 // is fine since the client has a clear idea which view is hovered at the 6511 // price of a couple more events being sent. This is a simple and 6512 // working solution. 6513 View source = this; 6514 while (true) { 6515 if (source.includeForAccessibility()) { 6516 source.sendAccessibilityEvent(eventType); 6517 return; 6518 } 6519 ViewParent parent = source.getParent(); 6520 if (parent instanceof View) { 6521 source = (View) parent; 6522 } else { 6523 return; 6524 } 6525 } 6526 } 6527 6528 /** 6529 * Clears accessibility focus without calling any callback methods 6530 * normally invoked in {@link #clearAccessibilityFocus()}. This method 6531 * is used for clearing accessibility focus when giving this focus to 6532 * another view. 6533 */ 6534 void clearAccessibilityFocusNoCallbacks() { 6535 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6536 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6537 invalidate(); 6538 } 6539 } 6540 6541 /** 6542 * Call this to try to give focus to a specific view or to one of its 6543 * descendants. 6544 * 6545 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6546 * false), or if it is focusable and it is not focusable in touch mode 6547 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6548 * 6549 * See also {@link #focusSearch(int)}, which is what you call to say that you 6550 * have focus, and you want your parent to look for the next one. 6551 * 6552 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 6553 * {@link #FOCUS_DOWN} and <code>null</code>. 6554 * 6555 * @return Whether this view or one of its descendants actually took focus. 6556 */ 6557 public final boolean requestFocus() { 6558 return requestFocus(View.FOCUS_DOWN); 6559 } 6560 6561 /** 6562 * Call this to try to give focus to a specific view or to one of its 6563 * descendants and give it a hint about what direction focus is heading. 6564 * 6565 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6566 * false), or if it is focusable and it is not focusable in touch mode 6567 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6568 * 6569 * See also {@link #focusSearch(int)}, which is what you call to say that you 6570 * have focus, and you want your parent to look for the next one. 6571 * 6572 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 6573 * <code>null</code> set for the previously focused rectangle. 6574 * 6575 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6576 * @return Whether this view or one of its descendants actually took focus. 6577 */ 6578 public final boolean requestFocus(int direction) { 6579 return requestFocus(direction, null); 6580 } 6581 6582 /** 6583 * Call this to try to give focus to a specific view or to one of its descendants 6584 * and give it hints about the direction and a specific rectangle that the focus 6585 * is coming from. The rectangle can help give larger views a finer grained hint 6586 * about where focus is coming from, and therefore, where to show selection, or 6587 * forward focus change internally. 6588 * 6589 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6590 * false), or if it is focusable and it is not focusable in touch mode 6591 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6592 * 6593 * A View will not take focus if it is not visible. 6594 * 6595 * A View will not take focus if one of its parents has 6596 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 6597 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 6598 * 6599 * See also {@link #focusSearch(int)}, which is what you call to say that you 6600 * have focus, and you want your parent to look for the next one. 6601 * 6602 * You may wish to override this method if your custom {@link View} has an internal 6603 * {@link View} that it wishes to forward the request to. 6604 * 6605 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6606 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 6607 * to give a finer grained hint about where focus is coming from. May be null 6608 * if there is no hint. 6609 * @return Whether this view or one of its descendants actually took focus. 6610 */ 6611 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 6612 return requestFocusNoSearch(direction, previouslyFocusedRect); 6613 } 6614 6615 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 6616 // need to be focusable 6617 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 6618 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6619 return false; 6620 } 6621 6622 // need to be focusable in touch mode if in touch mode 6623 if (isInTouchMode() && 6624 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 6625 return false; 6626 } 6627 6628 // need to not have any parents blocking us 6629 if (hasAncestorThatBlocksDescendantFocus()) { 6630 return false; 6631 } 6632 6633 handleFocusGainInternal(direction, previouslyFocusedRect); 6634 return true; 6635 } 6636 6637 /** 6638 * Call this to try to give focus to a specific view or to one of its descendants. This is a 6639 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 6640 * touch mode to request focus when they are touched. 6641 * 6642 * @return Whether this view or one of its descendants actually took focus. 6643 * 6644 * @see #isInTouchMode() 6645 * 6646 */ 6647 public final boolean requestFocusFromTouch() { 6648 // Leave touch mode if we need to 6649 if (isInTouchMode()) { 6650 ViewRootImpl viewRoot = getViewRootImpl(); 6651 if (viewRoot != null) { 6652 viewRoot.ensureTouchMode(false); 6653 } 6654 } 6655 return requestFocus(View.FOCUS_DOWN); 6656 } 6657 6658 /** 6659 * @return Whether any ancestor of this view blocks descendant focus. 6660 */ 6661 private boolean hasAncestorThatBlocksDescendantFocus() { 6662 ViewParent ancestor = mParent; 6663 while (ancestor instanceof ViewGroup) { 6664 final ViewGroup vgAncestor = (ViewGroup) ancestor; 6665 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 6666 return true; 6667 } else { 6668 ancestor = vgAncestor.getParent(); 6669 } 6670 } 6671 return false; 6672 } 6673 6674 /** 6675 * Gets the mode for determining whether this View is important for accessibility 6676 * which is if it fires accessibility events and if it is reported to 6677 * accessibility services that query the screen. 6678 * 6679 * @return The mode for determining whether a View is important for accessibility. 6680 * 6681 * @attr ref android.R.styleable#View_importantForAccessibility 6682 * 6683 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6684 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6685 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6686 */ 6687 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 6688 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 6689 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 6690 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no") 6691 }) 6692 public int getImportantForAccessibility() { 6693 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6694 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6695 } 6696 6697 /** 6698 * Sets how to determine whether this view is important for accessibility 6699 * which is if it fires accessibility events and if it is reported to 6700 * accessibility services that query the screen. 6701 * 6702 * @param mode How to determine whether this view is important for accessibility. 6703 * 6704 * @attr ref android.R.styleable#View_importantForAccessibility 6705 * 6706 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6707 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6708 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6709 */ 6710 public void setImportantForAccessibility(int mode) { 6711 if (mode != getImportantForAccessibility()) { 6712 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6713 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 6714 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6715 notifyAccessibilityStateChanged(); 6716 } 6717 } 6718 6719 /** 6720 * Gets whether this view should be exposed for accessibility. 6721 * 6722 * @return Whether the view is exposed for accessibility. 6723 * 6724 * @hide 6725 */ 6726 public boolean isImportantForAccessibility() { 6727 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6728 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6729 switch (mode) { 6730 case IMPORTANT_FOR_ACCESSIBILITY_YES: 6731 return true; 6732 case IMPORTANT_FOR_ACCESSIBILITY_NO: 6733 return false; 6734 case IMPORTANT_FOR_ACCESSIBILITY_AUTO: 6735 return isActionableForAccessibility() || hasListenersForAccessibility() 6736 || getAccessibilityNodeProvider() != null; 6737 default: 6738 throw new IllegalArgumentException("Unknow important for accessibility mode: " 6739 + mode); 6740 } 6741 } 6742 6743 /** 6744 * Gets the parent for accessibility purposes. Note that the parent for 6745 * accessibility is not necessary the immediate parent. It is the first 6746 * predecessor that is important for accessibility. 6747 * 6748 * @return The parent for accessibility purposes. 6749 */ 6750 public ViewParent getParentForAccessibility() { 6751 if (mParent instanceof View) { 6752 View parentView = (View) mParent; 6753 if (parentView.includeForAccessibility()) { 6754 return mParent; 6755 } else { 6756 return mParent.getParentForAccessibility(); 6757 } 6758 } 6759 return null; 6760 } 6761 6762 /** 6763 * Adds the children of a given View for accessibility. Since some Views are 6764 * not important for accessibility the children for accessibility are not 6765 * necessarily direct children of the riew, rather they are the first level of 6766 * descendants important for accessibility. 6767 * 6768 * @param children The list of children for accessibility. 6769 */ 6770 public void addChildrenForAccessibility(ArrayList<View> children) { 6771 if (includeForAccessibility()) { 6772 children.add(this); 6773 } 6774 } 6775 6776 /** 6777 * Whether to regard this view for accessibility. A view is regarded for 6778 * accessibility if it is important for accessibility or the querying 6779 * accessibility service has explicitly requested that view not 6780 * important for accessibility are regarded. 6781 * 6782 * @return Whether to regard the view for accessibility. 6783 * 6784 * @hide 6785 */ 6786 public boolean includeForAccessibility() { 6787 if (mAttachInfo != null) { 6788 return mAttachInfo.mIncludeNotImportantViews || isImportantForAccessibility(); 6789 } 6790 return false; 6791 } 6792 6793 /** 6794 * Returns whether the View is considered actionable from 6795 * accessibility perspective. Such view are important for 6796 * accessibility. 6797 * 6798 * @return True if the view is actionable for accessibility. 6799 * 6800 * @hide 6801 */ 6802 public boolean isActionableForAccessibility() { 6803 return (isClickable() || isLongClickable() || isFocusable()); 6804 } 6805 6806 /** 6807 * Returns whether the View has registered callbacks wich makes it 6808 * important for accessibility. 6809 * 6810 * @return True if the view is actionable for accessibility. 6811 */ 6812 private boolean hasListenersForAccessibility() { 6813 ListenerInfo info = getListenerInfo(); 6814 return mTouchDelegate != null || info.mOnKeyListener != null 6815 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 6816 || info.mOnHoverListener != null || info.mOnDragListener != null; 6817 } 6818 6819 /** 6820 * Notifies accessibility services that some view's important for 6821 * accessibility state has changed. Note that such notifications 6822 * are made at most once every 6823 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 6824 * to avoid unnecessary load to the system. Also once a view has 6825 * made a notifucation this method is a NOP until the notification has 6826 * been sent to clients. 6827 * 6828 * @hide 6829 * 6830 * TODO: Makse sure this method is called for any view state change 6831 * that is interesting for accessilility purposes. 6832 */ 6833 public void notifyAccessibilityStateChanged() { 6834 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 6835 return; 6836 } 6837 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) { 6838 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED; 6839 if (mParent != null) { 6840 mParent.childAccessibilityStateChanged(this); 6841 } 6842 } 6843 } 6844 6845 /** 6846 * Reset the state indicating the this view has requested clients 6847 * interested in its accessibility state to be notified. 6848 * 6849 * @hide 6850 */ 6851 public void resetAccessibilityStateChanged() { 6852 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED; 6853 } 6854 6855 /** 6856 * Performs the specified accessibility action on the view. For 6857 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 6858 * <p> 6859 * If an {@link AccessibilityDelegate} has been specified via calling 6860 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6861 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 6862 * is responsible for handling this call. 6863 * </p> 6864 * 6865 * @param action The action to perform. 6866 * @param arguments Optional action arguments. 6867 * @return Whether the action was performed. 6868 */ 6869 public boolean performAccessibilityAction(int action, Bundle arguments) { 6870 if (mAccessibilityDelegate != null) { 6871 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 6872 } else { 6873 return performAccessibilityActionInternal(action, arguments); 6874 } 6875 } 6876 6877 /** 6878 * @see #performAccessibilityAction(int, Bundle) 6879 * 6880 * Note: Called from the default {@link AccessibilityDelegate}. 6881 */ 6882 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 6883 switch (action) { 6884 case AccessibilityNodeInfo.ACTION_CLICK: { 6885 if (isClickable()) { 6886 return performClick(); 6887 } 6888 } break; 6889 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 6890 if (isLongClickable()) { 6891 return performLongClick(); 6892 } 6893 } break; 6894 case AccessibilityNodeInfo.ACTION_FOCUS: { 6895 if (!hasFocus()) { 6896 // Get out of touch mode since accessibility 6897 // wants to move focus around. 6898 getViewRootImpl().ensureTouchMode(false); 6899 return requestFocus(); 6900 } 6901 } break; 6902 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 6903 if (hasFocus()) { 6904 clearFocus(); 6905 return !isFocused(); 6906 } 6907 } break; 6908 case AccessibilityNodeInfo.ACTION_SELECT: { 6909 if (!isSelected()) { 6910 setSelected(true); 6911 return isSelected(); 6912 } 6913 } break; 6914 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 6915 if (isSelected()) { 6916 setSelected(false); 6917 return !isSelected(); 6918 } 6919 } break; 6920 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 6921 if (!isAccessibilityFocused()) { 6922 return requestAccessibilityFocus(); 6923 } 6924 } break; 6925 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 6926 if (isAccessibilityFocused()) { 6927 clearAccessibilityFocus(); 6928 return true; 6929 } 6930 } break; 6931 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 6932 if (arguments != null) { 6933 final int granularity = arguments.getInt( 6934 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 6935 return nextAtGranularity(granularity); 6936 } 6937 } break; 6938 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 6939 if (arguments != null) { 6940 final int granularity = arguments.getInt( 6941 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 6942 return previousAtGranularity(granularity); 6943 } 6944 } break; 6945 } 6946 return false; 6947 } 6948 6949 private boolean nextAtGranularity(int granularity) { 6950 CharSequence text = getIterableTextForAccessibility(); 6951 if (text == null || text.length() == 0) { 6952 return false; 6953 } 6954 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 6955 if (iterator == null) { 6956 return false; 6957 } 6958 final int current = getAccessibilityCursorPosition(); 6959 final int[] range = iterator.following(current); 6960 if (range == null) { 6961 return false; 6962 } 6963 final int start = range[0]; 6964 final int end = range[1]; 6965 setAccessibilityCursorPosition(end); 6966 sendViewTextTraversedAtGranularityEvent( 6967 AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, 6968 granularity, start, end); 6969 return true; 6970 } 6971 6972 private boolean previousAtGranularity(int granularity) { 6973 CharSequence text = getIterableTextForAccessibility(); 6974 if (text == null || text.length() == 0) { 6975 return false; 6976 } 6977 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 6978 if (iterator == null) { 6979 return false; 6980 } 6981 int current = getAccessibilityCursorPosition(); 6982 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 6983 current = text.length(); 6984 } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) { 6985 // When traversing by character we always put the cursor after the character 6986 // to ease edit and have to compensate before asking the for previous segment. 6987 current--; 6988 } 6989 final int[] range = iterator.preceding(current); 6990 if (range == null) { 6991 return false; 6992 } 6993 final int start = range[0]; 6994 final int end = range[1]; 6995 // Always put the cursor after the character to ease edit. 6996 if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) { 6997 setAccessibilityCursorPosition(end); 6998 } else { 6999 setAccessibilityCursorPosition(start); 7000 } 7001 sendViewTextTraversedAtGranularityEvent( 7002 AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, 7003 granularity, start, end); 7004 return true; 7005 } 7006 7007 /** 7008 * Gets the text reported for accessibility purposes. 7009 * 7010 * @return The accessibility text. 7011 * 7012 * @hide 7013 */ 7014 public CharSequence getIterableTextForAccessibility() { 7015 return getContentDescription(); 7016 } 7017 7018 /** 7019 * @hide 7020 */ 7021 public int getAccessibilityCursorPosition() { 7022 return mAccessibilityCursorPosition; 7023 } 7024 7025 /** 7026 * @hide 7027 */ 7028 public void setAccessibilityCursorPosition(int position) { 7029 mAccessibilityCursorPosition = position; 7030 } 7031 7032 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7033 int fromIndex, int toIndex) { 7034 if (mParent == null) { 7035 return; 7036 } 7037 AccessibilityEvent event = AccessibilityEvent.obtain( 7038 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7039 onInitializeAccessibilityEvent(event); 7040 onPopulateAccessibilityEvent(event); 7041 event.setFromIndex(fromIndex); 7042 event.setToIndex(toIndex); 7043 event.setAction(action); 7044 event.setMovementGranularity(granularity); 7045 mParent.requestSendAccessibilityEvent(this, event); 7046 } 7047 7048 /** 7049 * @hide 7050 */ 7051 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7052 switch (granularity) { 7053 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7054 CharSequence text = getIterableTextForAccessibility(); 7055 if (text != null && text.length() > 0) { 7056 CharacterTextSegmentIterator iterator = 7057 CharacterTextSegmentIterator.getInstance( 7058 mContext.getResources().getConfiguration().locale); 7059 iterator.initialize(text.toString()); 7060 return iterator; 7061 } 7062 } break; 7063 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7064 CharSequence text = getIterableTextForAccessibility(); 7065 if (text != null && text.length() > 0) { 7066 WordTextSegmentIterator iterator = 7067 WordTextSegmentIterator.getInstance( 7068 mContext.getResources().getConfiguration().locale); 7069 iterator.initialize(text.toString()); 7070 return iterator; 7071 } 7072 } break; 7073 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7074 CharSequence text = getIterableTextForAccessibility(); 7075 if (text != null && text.length() > 0) { 7076 ParagraphTextSegmentIterator iterator = 7077 ParagraphTextSegmentIterator.getInstance(); 7078 iterator.initialize(text.toString()); 7079 return iterator; 7080 } 7081 } break; 7082 } 7083 return null; 7084 } 7085 7086 /** 7087 * @hide 7088 */ 7089 public void dispatchStartTemporaryDetach() { 7090 clearAccessibilityFocus(); 7091 clearDisplayList(); 7092 7093 onStartTemporaryDetach(); 7094 } 7095 7096 /** 7097 * This is called when a container is going to temporarily detach a child, with 7098 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7099 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7100 * {@link #onDetachedFromWindow()} when the container is done. 7101 */ 7102 public void onStartTemporaryDetach() { 7103 removeUnsetPressCallback(); 7104 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7105 } 7106 7107 /** 7108 * @hide 7109 */ 7110 public void dispatchFinishTemporaryDetach() { 7111 onFinishTemporaryDetach(); 7112 } 7113 7114 /** 7115 * Called after {@link #onStartTemporaryDetach} when the container is done 7116 * changing the view. 7117 */ 7118 public void onFinishTemporaryDetach() { 7119 } 7120 7121 /** 7122 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7123 * for this view's window. Returns null if the view is not currently attached 7124 * to the window. Normally you will not need to use this directly, but 7125 * just use the standard high-level event callbacks like 7126 * {@link #onKeyDown(int, KeyEvent)}. 7127 */ 7128 public KeyEvent.DispatcherState getKeyDispatcherState() { 7129 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7130 } 7131 7132 /** 7133 * Dispatch a key event before it is processed by any input method 7134 * associated with the view hierarchy. This can be used to intercept 7135 * key events in special situations before the IME consumes them; a 7136 * typical example would be handling the BACK key to update the application's 7137 * UI instead of allowing the IME to see it and close itself. 7138 * 7139 * @param event The key event to be dispatched. 7140 * @return True if the event was handled, false otherwise. 7141 */ 7142 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7143 return onKeyPreIme(event.getKeyCode(), event); 7144 } 7145 7146 /** 7147 * Dispatch a key event to the next view on the focus path. This path runs 7148 * from the top of the view tree down to the currently focused view. If this 7149 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7150 * the next node down the focus path. This method also fires any key 7151 * listeners. 7152 * 7153 * @param event The key event to be dispatched. 7154 * @return True if the event was handled, false otherwise. 7155 */ 7156 public boolean dispatchKeyEvent(KeyEvent event) { 7157 if (mInputEventConsistencyVerifier != null) { 7158 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7159 } 7160 7161 // Give any attached key listener a first crack at the event. 7162 //noinspection SimplifiableIfStatement 7163 ListenerInfo li = mListenerInfo; 7164 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7165 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7166 return true; 7167 } 7168 7169 if (event.dispatch(this, mAttachInfo != null 7170 ? mAttachInfo.mKeyDispatchState : null, this)) { 7171 return true; 7172 } 7173 7174 if (mInputEventConsistencyVerifier != null) { 7175 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7176 } 7177 return false; 7178 } 7179 7180 /** 7181 * Dispatches a key shortcut event. 7182 * 7183 * @param event The key event to be dispatched. 7184 * @return True if the event was handled by the view, false otherwise. 7185 */ 7186 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 7187 return onKeyShortcut(event.getKeyCode(), event); 7188 } 7189 7190 /** 7191 * Pass the touch screen motion event down to the target view, or this 7192 * view if it is the target. 7193 * 7194 * @param event The motion event to be dispatched. 7195 * @return True if the event was handled by the view, false otherwise. 7196 */ 7197 public boolean dispatchTouchEvent(MotionEvent event) { 7198 if (mInputEventConsistencyVerifier != null) { 7199 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 7200 } 7201 7202 if (onFilterTouchEventForSecurity(event)) { 7203 //noinspection SimplifiableIfStatement 7204 ListenerInfo li = mListenerInfo; 7205 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7206 && li.mOnTouchListener.onTouch(this, event)) { 7207 return true; 7208 } 7209 7210 if (onTouchEvent(event)) { 7211 return true; 7212 } 7213 } 7214 7215 if (mInputEventConsistencyVerifier != null) { 7216 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7217 } 7218 return false; 7219 } 7220 7221 /** 7222 * Filter the touch event to apply security policies. 7223 * 7224 * @param event The motion event to be filtered. 7225 * @return True if the event should be dispatched, false if the event should be dropped. 7226 * 7227 * @see #getFilterTouchesWhenObscured 7228 */ 7229 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 7230 //noinspection RedundantIfStatement 7231 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 7232 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 7233 // Window is obscured, drop this touch. 7234 return false; 7235 } 7236 return true; 7237 } 7238 7239 /** 7240 * Pass a trackball motion event down to the focused view. 7241 * 7242 * @param event The motion event to be dispatched. 7243 * @return True if the event was handled by the view, false otherwise. 7244 */ 7245 public boolean dispatchTrackballEvent(MotionEvent event) { 7246 if (mInputEventConsistencyVerifier != null) { 7247 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 7248 } 7249 7250 return onTrackballEvent(event); 7251 } 7252 7253 /** 7254 * Dispatch a generic motion event. 7255 * <p> 7256 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7257 * are delivered to the view under the pointer. All other generic motion events are 7258 * delivered to the focused view. Hover events are handled specially and are delivered 7259 * to {@link #onHoverEvent(MotionEvent)}. 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 public boolean dispatchGenericMotionEvent(MotionEvent event) { 7266 if (mInputEventConsistencyVerifier != null) { 7267 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 7268 } 7269 7270 final int source = event.getSource(); 7271 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7272 final int action = event.getAction(); 7273 if (action == MotionEvent.ACTION_HOVER_ENTER 7274 || action == MotionEvent.ACTION_HOVER_MOVE 7275 || action == MotionEvent.ACTION_HOVER_EXIT) { 7276 if (dispatchHoverEvent(event)) { 7277 return true; 7278 } 7279 } else if (dispatchGenericPointerEvent(event)) { 7280 return true; 7281 } 7282 } else if (dispatchGenericFocusedEvent(event)) { 7283 return true; 7284 } 7285 7286 if (dispatchGenericMotionEventInternal(event)) { 7287 return true; 7288 } 7289 7290 if (mInputEventConsistencyVerifier != null) { 7291 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7292 } 7293 return false; 7294 } 7295 7296 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 7297 //noinspection SimplifiableIfStatement 7298 ListenerInfo li = mListenerInfo; 7299 if (li != null && li.mOnGenericMotionListener != null 7300 && (mViewFlags & ENABLED_MASK) == ENABLED 7301 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 7302 return true; 7303 } 7304 7305 if (onGenericMotionEvent(event)) { 7306 return true; 7307 } 7308 7309 if (mInputEventConsistencyVerifier != null) { 7310 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7311 } 7312 return false; 7313 } 7314 7315 /** 7316 * Dispatch a hover event. 7317 * <p> 7318 * Do not call this method directly. 7319 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7320 * </p> 7321 * 7322 * @param event The motion event to be dispatched. 7323 * @return True if the event was handled by the view, false otherwise. 7324 */ 7325 protected boolean dispatchHoverEvent(MotionEvent event) { 7326 //noinspection SimplifiableIfStatement 7327 ListenerInfo li = mListenerInfo; 7328 if (li != null && li.mOnHoverListener != null 7329 && (mViewFlags & ENABLED_MASK) == ENABLED 7330 && li.mOnHoverListener.onHover(this, event)) { 7331 return true; 7332 } 7333 7334 return onHoverEvent(event); 7335 } 7336 7337 /** 7338 * Returns true if the view has a child to which it has recently sent 7339 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 7340 * it does not have a hovered child, then it must be the innermost hovered view. 7341 * @hide 7342 */ 7343 protected boolean hasHoveredChild() { 7344 return false; 7345 } 7346 7347 /** 7348 * Dispatch a generic motion event to the view under the first pointer. 7349 * <p> 7350 * Do not call this method directly. 7351 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7352 * </p> 7353 * 7354 * @param event The motion event to be dispatched. 7355 * @return True if the event was handled by the view, false otherwise. 7356 */ 7357 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 7358 return false; 7359 } 7360 7361 /** 7362 * Dispatch a generic motion event to the currently focused view. 7363 * <p> 7364 * Do not call this method directly. 7365 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7366 * </p> 7367 * 7368 * @param event The motion event to be dispatched. 7369 * @return True if the event was handled by the view, false otherwise. 7370 */ 7371 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 7372 return false; 7373 } 7374 7375 /** 7376 * Dispatch a pointer event. 7377 * <p> 7378 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 7379 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 7380 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 7381 * and should not be expected to handle other pointing device features. 7382 * </p> 7383 * 7384 * @param event The motion event to be dispatched. 7385 * @return True if the event was handled by the view, false otherwise. 7386 * @hide 7387 */ 7388 public final boolean dispatchPointerEvent(MotionEvent event) { 7389 if (event.isTouchEvent()) { 7390 return dispatchTouchEvent(event); 7391 } else { 7392 return dispatchGenericMotionEvent(event); 7393 } 7394 } 7395 7396 /** 7397 * Called when the window containing this view gains or loses window focus. 7398 * ViewGroups should override to route to their children. 7399 * 7400 * @param hasFocus True if the window containing this view now has focus, 7401 * false otherwise. 7402 */ 7403 public void dispatchWindowFocusChanged(boolean hasFocus) { 7404 onWindowFocusChanged(hasFocus); 7405 } 7406 7407 /** 7408 * Called when the window containing this view gains or loses focus. Note 7409 * that this is separate from view focus: to receive key events, both 7410 * your view and its window must have focus. If a window is displayed 7411 * on top of yours that takes input focus, then your own window will lose 7412 * focus but the view focus will remain unchanged. 7413 * 7414 * @param hasWindowFocus True if the window containing this view now has 7415 * focus, false otherwise. 7416 */ 7417 public void onWindowFocusChanged(boolean hasWindowFocus) { 7418 InputMethodManager imm = InputMethodManager.peekInstance(); 7419 if (!hasWindowFocus) { 7420 if (isPressed()) { 7421 setPressed(false); 7422 } 7423 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7424 imm.focusOut(this); 7425 } 7426 removeLongPressCallback(); 7427 removeTapCallback(); 7428 onFocusLost(); 7429 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7430 imm.focusIn(this); 7431 } 7432 refreshDrawableState(); 7433 } 7434 7435 /** 7436 * Returns true if this view is in a window that currently has window focus. 7437 * Note that this is not the same as the view itself having focus. 7438 * 7439 * @return True if this view is in a window that currently has window focus. 7440 */ 7441 public boolean hasWindowFocus() { 7442 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 7443 } 7444 7445 /** 7446 * Dispatch a view visibility change down the view hierarchy. 7447 * ViewGroups should override to route to their children. 7448 * @param changedView The view whose visibility changed. Could be 'this' or 7449 * an ancestor view. 7450 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7451 * {@link #INVISIBLE} or {@link #GONE}. 7452 */ 7453 protected void dispatchVisibilityChanged(View changedView, int visibility) { 7454 onVisibilityChanged(changedView, visibility); 7455 } 7456 7457 /** 7458 * Called when the visibility of the view or an ancestor of the view is changed. 7459 * @param changedView The view whose visibility changed. Could be 'this' or 7460 * an ancestor view. 7461 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7462 * {@link #INVISIBLE} or {@link #GONE}. 7463 */ 7464 protected void onVisibilityChanged(View changedView, int visibility) { 7465 if (visibility == VISIBLE) { 7466 if (mAttachInfo != null) { 7467 initialAwakenScrollBars(); 7468 } else { 7469 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 7470 } 7471 } 7472 } 7473 7474 /** 7475 * Dispatch a hint about whether this view is displayed. For instance, when 7476 * a View moves out of the screen, it might receives a display hint indicating 7477 * the view is not displayed. Applications should not <em>rely</em> on this hint 7478 * as there is no guarantee that they will receive one. 7479 * 7480 * @param hint A hint about whether or not this view is displayed: 7481 * {@link #VISIBLE} or {@link #INVISIBLE}. 7482 */ 7483 public void dispatchDisplayHint(int hint) { 7484 onDisplayHint(hint); 7485 } 7486 7487 /** 7488 * Gives this view a hint about whether is displayed or not. For instance, when 7489 * a View moves out of the screen, it might receives a display hint indicating 7490 * the view is not displayed. Applications should not <em>rely</em> on this hint 7491 * as there is no guarantee that they will receive one. 7492 * 7493 * @param hint A hint about whether or not this view is displayed: 7494 * {@link #VISIBLE} or {@link #INVISIBLE}. 7495 */ 7496 protected void onDisplayHint(int hint) { 7497 } 7498 7499 /** 7500 * Dispatch a window visibility change down the view hierarchy. 7501 * ViewGroups should override to route to their children. 7502 * 7503 * @param visibility The new visibility of the window. 7504 * 7505 * @see #onWindowVisibilityChanged(int) 7506 */ 7507 public void dispatchWindowVisibilityChanged(int visibility) { 7508 onWindowVisibilityChanged(visibility); 7509 } 7510 7511 /** 7512 * Called when the window containing has change its visibility 7513 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 7514 * that this tells you whether or not your window is being made visible 7515 * to the window manager; this does <em>not</em> tell you whether or not 7516 * your window is obscured by other windows on the screen, even if it 7517 * is itself visible. 7518 * 7519 * @param visibility The new visibility of the window. 7520 */ 7521 protected void onWindowVisibilityChanged(int visibility) { 7522 if (visibility == VISIBLE) { 7523 initialAwakenScrollBars(); 7524 } 7525 } 7526 7527 /** 7528 * Returns the current visibility of the window this view is attached to 7529 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 7530 * 7531 * @return Returns the current visibility of the view's window. 7532 */ 7533 public int getWindowVisibility() { 7534 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 7535 } 7536 7537 /** 7538 * Retrieve the overall visible display size in which the window this view is 7539 * attached to has been positioned in. This takes into account screen 7540 * decorations above the window, for both cases where the window itself 7541 * is being position inside of them or the window is being placed under 7542 * then and covered insets are used for the window to position its content 7543 * inside. In effect, this tells you the available area where content can 7544 * be placed and remain visible to users. 7545 * 7546 * <p>This function requires an IPC back to the window manager to retrieve 7547 * the requested information, so should not be used in performance critical 7548 * code like drawing. 7549 * 7550 * @param outRect Filled in with the visible display frame. If the view 7551 * is not attached to a window, this is simply the raw display size. 7552 */ 7553 public void getWindowVisibleDisplayFrame(Rect outRect) { 7554 if (mAttachInfo != null) { 7555 try { 7556 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 7557 } catch (RemoteException e) { 7558 return; 7559 } 7560 // XXX This is really broken, and probably all needs to be done 7561 // in the window manager, and we need to know more about whether 7562 // we want the area behind or in front of the IME. 7563 final Rect insets = mAttachInfo.mVisibleInsets; 7564 outRect.left += insets.left; 7565 outRect.top += insets.top; 7566 outRect.right -= insets.right; 7567 outRect.bottom -= insets.bottom; 7568 return; 7569 } 7570 // The view is not attached to a display so we don't have a context. 7571 // Make a best guess about the display size. 7572 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 7573 d.getRectSize(outRect); 7574 } 7575 7576 /** 7577 * Dispatch a notification about a resource configuration change down 7578 * the view hierarchy. 7579 * ViewGroups should override to route to their children. 7580 * 7581 * @param newConfig The new resource configuration. 7582 * 7583 * @see #onConfigurationChanged(android.content.res.Configuration) 7584 */ 7585 public void dispatchConfigurationChanged(Configuration newConfig) { 7586 onConfigurationChanged(newConfig); 7587 } 7588 7589 /** 7590 * Called when the current configuration of the resources being used 7591 * by the application have changed. You can use this to decide when 7592 * to reload resources that can changed based on orientation and other 7593 * configuration characterstics. You only need to use this if you are 7594 * not relying on the normal {@link android.app.Activity} mechanism of 7595 * recreating the activity instance upon a configuration change. 7596 * 7597 * @param newConfig The new resource configuration. 7598 */ 7599 protected void onConfigurationChanged(Configuration newConfig) { 7600 } 7601 7602 /** 7603 * Private function to aggregate all per-view attributes in to the view 7604 * root. 7605 */ 7606 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7607 performCollectViewAttributes(attachInfo, visibility); 7608 } 7609 7610 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7611 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 7612 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 7613 attachInfo.mKeepScreenOn = true; 7614 } 7615 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 7616 ListenerInfo li = mListenerInfo; 7617 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 7618 attachInfo.mHasSystemUiListeners = true; 7619 } 7620 } 7621 } 7622 7623 void needGlobalAttributesUpdate(boolean force) { 7624 final AttachInfo ai = mAttachInfo; 7625 if (ai != null && !ai.mRecomputeGlobalAttributes) { 7626 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 7627 || ai.mHasSystemUiListeners) { 7628 ai.mRecomputeGlobalAttributes = true; 7629 } 7630 } 7631 } 7632 7633 /** 7634 * Returns whether the device is currently in touch mode. Touch mode is entered 7635 * once the user begins interacting with the device by touch, and affects various 7636 * things like whether focus is always visible to the user. 7637 * 7638 * @return Whether the device is in touch mode. 7639 */ 7640 @ViewDebug.ExportedProperty 7641 public boolean isInTouchMode() { 7642 if (mAttachInfo != null) { 7643 return mAttachInfo.mInTouchMode; 7644 } else { 7645 return ViewRootImpl.isInTouchMode(); 7646 } 7647 } 7648 7649 /** 7650 * Returns the context the view is running in, through which it can 7651 * access the current theme, resources, etc. 7652 * 7653 * @return The view's Context. 7654 */ 7655 @ViewDebug.CapturedViewProperty 7656 public final Context getContext() { 7657 return mContext; 7658 } 7659 7660 /** 7661 * Handle a key event before it is processed by any input method 7662 * associated with the view hierarchy. This can be used to intercept 7663 * key events in special situations before the IME consumes them; a 7664 * typical example would be handling the BACK key to update the application's 7665 * UI instead of allowing the IME to see it and close itself. 7666 * 7667 * @param keyCode The value in event.getKeyCode(). 7668 * @param event Description of the key event. 7669 * @return If you handled the event, return true. If you want to allow the 7670 * event to be handled by the next receiver, return false. 7671 */ 7672 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 7673 return false; 7674 } 7675 7676 /** 7677 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 7678 * KeyEvent.Callback.onKeyDown()}: perform press of the view 7679 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 7680 * is released, if the view is enabled and clickable. 7681 * 7682 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7683 * although some may elect to do so in some situations. Do not rely on this to 7684 * catch software key presses. 7685 * 7686 * @param keyCode A key code that represents the button pressed, from 7687 * {@link android.view.KeyEvent}. 7688 * @param event The KeyEvent object that defines the button action. 7689 */ 7690 public boolean onKeyDown(int keyCode, KeyEvent event) { 7691 boolean result = false; 7692 7693 switch (keyCode) { 7694 case KeyEvent.KEYCODE_DPAD_CENTER: 7695 case KeyEvent.KEYCODE_ENTER: { 7696 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7697 return true; 7698 } 7699 // Long clickable items don't necessarily have to be clickable 7700 if (((mViewFlags & CLICKABLE) == CLICKABLE || 7701 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 7702 (event.getRepeatCount() == 0)) { 7703 setPressed(true); 7704 checkForLongClick(0); 7705 return true; 7706 } 7707 break; 7708 } 7709 } 7710 return result; 7711 } 7712 7713 /** 7714 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 7715 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 7716 * the event). 7717 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7718 * although some may elect to do so in some situations. Do not rely on this to 7719 * catch software key presses. 7720 */ 7721 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 7722 return false; 7723 } 7724 7725 /** 7726 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 7727 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 7728 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 7729 * {@link KeyEvent#KEYCODE_ENTER} is released. 7730 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7731 * although some may elect to do so in some situations. Do not rely on this to 7732 * catch software key presses. 7733 * 7734 * @param keyCode A key code that represents the button pressed, from 7735 * {@link android.view.KeyEvent}. 7736 * @param event The KeyEvent object that defines the button action. 7737 */ 7738 public boolean onKeyUp(int keyCode, KeyEvent event) { 7739 boolean result = false; 7740 7741 switch (keyCode) { 7742 case KeyEvent.KEYCODE_DPAD_CENTER: 7743 case KeyEvent.KEYCODE_ENTER: { 7744 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7745 return true; 7746 } 7747 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 7748 setPressed(false); 7749 7750 if (!mHasPerformedLongPress) { 7751 // This is a tap, so remove the longpress check 7752 removeLongPressCallback(); 7753 7754 result = performClick(); 7755 } 7756 } 7757 break; 7758 } 7759 } 7760 return result; 7761 } 7762 7763 /** 7764 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 7765 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 7766 * the event). 7767 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7768 * although some may elect to do so in some situations. Do not rely on this to 7769 * catch software key presses. 7770 * 7771 * @param keyCode A key code that represents the button pressed, from 7772 * {@link android.view.KeyEvent}. 7773 * @param repeatCount The number of times the action was made. 7774 * @param event The KeyEvent object that defines the button action. 7775 */ 7776 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 7777 return false; 7778 } 7779 7780 /** 7781 * Called on the focused view when a key shortcut event is not handled. 7782 * Override this method to implement local key shortcuts for the View. 7783 * Key shortcuts can also be implemented by setting the 7784 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 7785 * 7786 * @param keyCode The value in event.getKeyCode(). 7787 * @param event Description of the key event. 7788 * @return If you handled the event, return true. If you want to allow the 7789 * event to be handled by the next receiver, return false. 7790 */ 7791 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 7792 return false; 7793 } 7794 7795 /** 7796 * Check whether the called view is a text editor, in which case it 7797 * would make sense to automatically display a soft input window for 7798 * it. Subclasses should override this if they implement 7799 * {@link #onCreateInputConnection(EditorInfo)} to return true if 7800 * a call on that method would return a non-null InputConnection, and 7801 * they are really a first-class editor that the user would normally 7802 * start typing on when the go into a window containing your view. 7803 * 7804 * <p>The default implementation always returns false. This does 7805 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 7806 * will not be called or the user can not otherwise perform edits on your 7807 * view; it is just a hint to the system that this is not the primary 7808 * purpose of this view. 7809 * 7810 * @return Returns true if this view is a text editor, else false. 7811 */ 7812 public boolean onCheckIsTextEditor() { 7813 return false; 7814 } 7815 7816 /** 7817 * Create a new InputConnection for an InputMethod to interact 7818 * with the view. The default implementation returns null, since it doesn't 7819 * support input methods. You can override this to implement such support. 7820 * This is only needed for views that take focus and text input. 7821 * 7822 * <p>When implementing this, you probably also want to implement 7823 * {@link #onCheckIsTextEditor()} to indicate you will return a 7824 * non-null InputConnection. 7825 * 7826 * @param outAttrs Fill in with attribute information about the connection. 7827 */ 7828 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 7829 return null; 7830 } 7831 7832 /** 7833 * Called by the {@link android.view.inputmethod.InputMethodManager} 7834 * when a view who is not the current 7835 * input connection target is trying to make a call on the manager. The 7836 * default implementation returns false; you can override this to return 7837 * true for certain views if you are performing InputConnection proxying 7838 * to them. 7839 * @param view The View that is making the InputMethodManager call. 7840 * @return Return true to allow the call, false to reject. 7841 */ 7842 public boolean checkInputConnectionProxy(View view) { 7843 return false; 7844 } 7845 7846 /** 7847 * Show the context menu for this view. It is not safe to hold on to the 7848 * menu after returning from this method. 7849 * 7850 * You should normally not overload this method. Overload 7851 * {@link #onCreateContextMenu(ContextMenu)} or define an 7852 * {@link OnCreateContextMenuListener} to add items to the context menu. 7853 * 7854 * @param menu The context menu to populate 7855 */ 7856 public void createContextMenu(ContextMenu menu) { 7857 ContextMenuInfo menuInfo = getContextMenuInfo(); 7858 7859 // Sets the current menu info so all items added to menu will have 7860 // my extra info set. 7861 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 7862 7863 onCreateContextMenu(menu); 7864 ListenerInfo li = mListenerInfo; 7865 if (li != null && li.mOnCreateContextMenuListener != null) { 7866 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 7867 } 7868 7869 // Clear the extra information so subsequent items that aren't mine don't 7870 // have my extra info. 7871 ((MenuBuilder)menu).setCurrentMenuInfo(null); 7872 7873 if (mParent != null) { 7874 mParent.createContextMenu(menu); 7875 } 7876 } 7877 7878 /** 7879 * Views should implement this if they have extra information to associate 7880 * with the context menu. The return result is supplied as a parameter to 7881 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 7882 * callback. 7883 * 7884 * @return Extra information about the item for which the context menu 7885 * should be shown. This information will vary across different 7886 * subclasses of View. 7887 */ 7888 protected ContextMenuInfo getContextMenuInfo() { 7889 return null; 7890 } 7891 7892 /** 7893 * Views should implement this if the view itself is going to add items to 7894 * the context menu. 7895 * 7896 * @param menu the context menu to populate 7897 */ 7898 protected void onCreateContextMenu(ContextMenu menu) { 7899 } 7900 7901 /** 7902 * Implement this method to handle trackball motion events. The 7903 * <em>relative</em> movement of the trackball since the last event 7904 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 7905 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 7906 * that a movement of 1 corresponds to the user pressing one DPAD key (so 7907 * they will often be fractional values, representing the more fine-grained 7908 * movement information available from a trackball). 7909 * 7910 * @param event The motion event. 7911 * @return True if the event was handled, false otherwise. 7912 */ 7913 public boolean onTrackballEvent(MotionEvent event) { 7914 return false; 7915 } 7916 7917 /** 7918 * Implement this method to handle generic motion events. 7919 * <p> 7920 * Generic motion events describe joystick movements, mouse hovers, track pad 7921 * touches, scroll wheel movements and other input events. The 7922 * {@link MotionEvent#getSource() source} of the motion event specifies 7923 * the class of input that was received. Implementations of this method 7924 * must examine the bits in the source before processing the event. 7925 * The following code example shows how this is done. 7926 * </p><p> 7927 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7928 * are delivered to the view under the pointer. All other generic motion events are 7929 * delivered to the focused view. 7930 * </p> 7931 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 7932 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 7933 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 7934 * // process the joystick movement... 7935 * return true; 7936 * } 7937 * } 7938 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7939 * switch (event.getAction()) { 7940 * case MotionEvent.ACTION_HOVER_MOVE: 7941 * // process the mouse hover movement... 7942 * return true; 7943 * case MotionEvent.ACTION_SCROLL: 7944 * // process the scroll wheel movement... 7945 * return true; 7946 * } 7947 * } 7948 * return super.onGenericMotionEvent(event); 7949 * }</pre> 7950 * 7951 * @param event The generic motion event being processed. 7952 * @return True if the event was handled, false otherwise. 7953 */ 7954 public boolean onGenericMotionEvent(MotionEvent event) { 7955 return false; 7956 } 7957 7958 /** 7959 * Implement this method to handle hover events. 7960 * <p> 7961 * This method is called whenever a pointer is hovering into, over, or out of the 7962 * bounds of a view and the view is not currently being touched. 7963 * Hover events are represented as pointer events with action 7964 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 7965 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 7966 * </p> 7967 * <ul> 7968 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 7969 * when the pointer enters the bounds of the view.</li> 7970 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 7971 * when the pointer has already entered the bounds of the view and has moved.</li> 7972 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 7973 * when the pointer has exited the bounds of the view or when the pointer is 7974 * about to go down due to a button click, tap, or similar user action that 7975 * causes the view to be touched.</li> 7976 * </ul> 7977 * <p> 7978 * The view should implement this method to return true to indicate that it is 7979 * handling the hover event, such as by changing its drawable state. 7980 * </p><p> 7981 * The default implementation calls {@link #setHovered} to update the hovered state 7982 * of the view when a hover enter or hover exit event is received, if the view 7983 * is enabled and is clickable. The default implementation also sends hover 7984 * accessibility events. 7985 * </p> 7986 * 7987 * @param event The motion event that describes the hover. 7988 * @return True if the view handled the hover event. 7989 * 7990 * @see #isHovered 7991 * @see #setHovered 7992 * @see #onHoverChanged 7993 */ 7994 public boolean onHoverEvent(MotionEvent event) { 7995 // The root view may receive hover (or touch) events that are outside the bounds of 7996 // the window. This code ensures that we only send accessibility events for 7997 // hovers that are actually within the bounds of the root view. 7998 final int action = event.getActionMasked(); 7999 if (!mSendingHoverAccessibilityEvents) { 8000 if ((action == MotionEvent.ACTION_HOVER_ENTER 8001 || action == MotionEvent.ACTION_HOVER_MOVE) 8002 && !hasHoveredChild() 8003 && pointInView(event.getX(), event.getY())) { 8004 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8005 mSendingHoverAccessibilityEvents = true; 8006 } 8007 } else { 8008 if (action == MotionEvent.ACTION_HOVER_EXIT 8009 || (action == MotionEvent.ACTION_MOVE 8010 && !pointInView(event.getX(), event.getY()))) { 8011 mSendingHoverAccessibilityEvents = false; 8012 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8013 // If the window does not have input focus we take away accessibility 8014 // focus as soon as the user stop hovering over the view. 8015 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 8016 getViewRootImpl().setAccessibilityFocus(null, null); 8017 } 8018 } 8019 } 8020 8021 if (isHoverable()) { 8022 switch (action) { 8023 case MotionEvent.ACTION_HOVER_ENTER: 8024 setHovered(true); 8025 break; 8026 case MotionEvent.ACTION_HOVER_EXIT: 8027 setHovered(false); 8028 break; 8029 } 8030 8031 // Dispatch the event to onGenericMotionEvent before returning true. 8032 // This is to provide compatibility with existing applications that 8033 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8034 // break because of the new default handling for hoverable views 8035 // in onHoverEvent. 8036 // Note that onGenericMotionEvent will be called by default when 8037 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8038 dispatchGenericMotionEventInternal(event); 8039 return true; 8040 } 8041 8042 return false; 8043 } 8044 8045 /** 8046 * Returns true if the view should handle {@link #onHoverEvent} 8047 * by calling {@link #setHovered} to change its hovered state. 8048 * 8049 * @return True if the view is hoverable. 8050 */ 8051 private boolean isHoverable() { 8052 final int viewFlags = mViewFlags; 8053 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8054 return false; 8055 } 8056 8057 return (viewFlags & CLICKABLE) == CLICKABLE 8058 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8059 } 8060 8061 /** 8062 * Returns true if the view is currently hovered. 8063 * 8064 * @return True if the view is currently hovered. 8065 * 8066 * @see #setHovered 8067 * @see #onHoverChanged 8068 */ 8069 @ViewDebug.ExportedProperty 8070 public boolean isHovered() { 8071 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8072 } 8073 8074 /** 8075 * Sets whether the view is currently hovered. 8076 * <p> 8077 * Calling this method also changes the drawable state of the view. This 8078 * enables the view to react to hover by using different drawable resources 8079 * to change its appearance. 8080 * </p><p> 8081 * The {@link #onHoverChanged} method is called when the hovered state changes. 8082 * </p> 8083 * 8084 * @param hovered True if the view is hovered. 8085 * 8086 * @see #isHovered 8087 * @see #onHoverChanged 8088 */ 8089 public void setHovered(boolean hovered) { 8090 if (hovered) { 8091 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8092 mPrivateFlags |= PFLAG_HOVERED; 8093 refreshDrawableState(); 8094 onHoverChanged(true); 8095 } 8096 } else { 8097 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8098 mPrivateFlags &= ~PFLAG_HOVERED; 8099 refreshDrawableState(); 8100 onHoverChanged(false); 8101 } 8102 } 8103 } 8104 8105 /** 8106 * Implement this method to handle hover state changes. 8107 * <p> 8108 * This method is called whenever the hover state changes as a result of a 8109 * call to {@link #setHovered}. 8110 * </p> 8111 * 8112 * @param hovered The current hover state, as returned by {@link #isHovered}. 8113 * 8114 * @see #isHovered 8115 * @see #setHovered 8116 */ 8117 public void onHoverChanged(boolean hovered) { 8118 } 8119 8120 /** 8121 * Implement this method to handle touch screen motion events. 8122 * 8123 * @param event The motion event. 8124 * @return True if the event was handled, false otherwise. 8125 */ 8126 public boolean onTouchEvent(MotionEvent event) { 8127 final int viewFlags = mViewFlags; 8128 8129 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8130 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8131 setPressed(false); 8132 } 8133 // A disabled view that is clickable still consumes the touch 8134 // events, it just doesn't respond to them. 8135 return (((viewFlags & CLICKABLE) == CLICKABLE || 8136 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8137 } 8138 8139 if (mTouchDelegate != null) { 8140 if (mTouchDelegate.onTouchEvent(event)) { 8141 return true; 8142 } 8143 } 8144 8145 if (((viewFlags & CLICKABLE) == CLICKABLE || 8146 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8147 switch (event.getAction()) { 8148 case MotionEvent.ACTION_UP: 8149 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8150 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8151 // take focus if we don't have it already and we should in 8152 // touch mode. 8153 boolean focusTaken = false; 8154 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8155 focusTaken = requestFocus(); 8156 } 8157 8158 if (prepressed) { 8159 // The button is being released before we actually 8160 // showed it as pressed. Make it show the pressed 8161 // state now (before scheduling the click) to ensure 8162 // the user sees it. 8163 setPressed(true); 8164 } 8165 8166 if (!mHasPerformedLongPress) { 8167 // This is a tap, so remove the longpress check 8168 removeLongPressCallback(); 8169 8170 // Only perform take click actions if we were in the pressed state 8171 if (!focusTaken) { 8172 // Use a Runnable and post this rather than calling 8173 // performClick directly. This lets other visual state 8174 // of the view update before click actions start. 8175 if (mPerformClick == null) { 8176 mPerformClick = new PerformClick(); 8177 } 8178 if (!post(mPerformClick)) { 8179 performClick(); 8180 } 8181 } 8182 } 8183 8184 if (mUnsetPressedState == null) { 8185 mUnsetPressedState = new UnsetPressedState(); 8186 } 8187 8188 if (prepressed) { 8189 postDelayed(mUnsetPressedState, 8190 ViewConfiguration.getPressedStateDuration()); 8191 } else if (!post(mUnsetPressedState)) { 8192 // If the post failed, unpress right now 8193 mUnsetPressedState.run(); 8194 } 8195 removeTapCallback(); 8196 } 8197 break; 8198 8199 case MotionEvent.ACTION_DOWN: 8200 mHasPerformedLongPress = false; 8201 8202 if (performButtonActionOnTouchDown(event)) { 8203 break; 8204 } 8205 8206 // Walk up the hierarchy to determine if we're inside a scrolling container. 8207 boolean isInScrollingContainer = isInScrollingContainer(); 8208 8209 // For views inside a scrolling container, delay the pressed feedback for 8210 // a short period in case this is a scroll. 8211 if (isInScrollingContainer) { 8212 mPrivateFlags |= PFLAG_PREPRESSED; 8213 if (mPendingCheckForTap == null) { 8214 mPendingCheckForTap = new CheckForTap(); 8215 } 8216 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 8217 } else { 8218 // Not inside a scrolling container, so show the feedback right away 8219 setPressed(true); 8220 checkForLongClick(0); 8221 } 8222 break; 8223 8224 case MotionEvent.ACTION_CANCEL: 8225 setPressed(false); 8226 removeTapCallback(); 8227 break; 8228 8229 case MotionEvent.ACTION_MOVE: 8230 final int x = (int) event.getX(); 8231 final int y = (int) event.getY(); 8232 8233 // Be lenient about moving outside of buttons 8234 if (!pointInView(x, y, mTouchSlop)) { 8235 // Outside button 8236 removeTapCallback(); 8237 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 8238 // Remove any future long press/tap checks 8239 removeLongPressCallback(); 8240 8241 setPressed(false); 8242 } 8243 } 8244 break; 8245 } 8246 return true; 8247 } 8248 8249 return false; 8250 } 8251 8252 /** 8253 * @hide 8254 */ 8255 public boolean isInScrollingContainer() { 8256 ViewParent p = getParent(); 8257 while (p != null && p instanceof ViewGroup) { 8258 if (((ViewGroup) p).shouldDelayChildPressedState()) { 8259 return true; 8260 } 8261 p = p.getParent(); 8262 } 8263 return false; 8264 } 8265 8266 /** 8267 * Remove the longpress detection timer. 8268 */ 8269 private void removeLongPressCallback() { 8270 if (mPendingCheckForLongPress != null) { 8271 removeCallbacks(mPendingCheckForLongPress); 8272 } 8273 } 8274 8275 /** 8276 * Remove the pending click action 8277 */ 8278 private void removePerformClickCallback() { 8279 if (mPerformClick != null) { 8280 removeCallbacks(mPerformClick); 8281 } 8282 } 8283 8284 /** 8285 * Remove the prepress detection timer. 8286 */ 8287 private void removeUnsetPressCallback() { 8288 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 8289 setPressed(false); 8290 removeCallbacks(mUnsetPressedState); 8291 } 8292 } 8293 8294 /** 8295 * Remove the tap detection timer. 8296 */ 8297 private void removeTapCallback() { 8298 if (mPendingCheckForTap != null) { 8299 mPrivateFlags &= ~PFLAG_PREPRESSED; 8300 removeCallbacks(mPendingCheckForTap); 8301 } 8302 } 8303 8304 /** 8305 * Cancels a pending long press. Your subclass can use this if you 8306 * want the context menu to come up if the user presses and holds 8307 * at the same place, but you don't want it to come up if they press 8308 * and then move around enough to cause scrolling. 8309 */ 8310 public void cancelLongPress() { 8311 removeLongPressCallback(); 8312 8313 /* 8314 * The prepressed state handled by the tap callback is a display 8315 * construct, but the tap callback will post a long press callback 8316 * less its own timeout. Remove it here. 8317 */ 8318 removeTapCallback(); 8319 } 8320 8321 /** 8322 * Remove the pending callback for sending a 8323 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 8324 */ 8325 private void removeSendViewScrolledAccessibilityEventCallback() { 8326 if (mSendViewScrolledAccessibilityEvent != null) { 8327 removeCallbacks(mSendViewScrolledAccessibilityEvent); 8328 mSendViewScrolledAccessibilityEvent.mIsPending = false; 8329 } 8330 } 8331 8332 /** 8333 * Sets the TouchDelegate for this View. 8334 */ 8335 public void setTouchDelegate(TouchDelegate delegate) { 8336 mTouchDelegate = delegate; 8337 } 8338 8339 /** 8340 * Gets the TouchDelegate for this View. 8341 */ 8342 public TouchDelegate getTouchDelegate() { 8343 return mTouchDelegate; 8344 } 8345 8346 /** 8347 * Set flags controlling behavior of this view. 8348 * 8349 * @param flags Constant indicating the value which should be set 8350 * @param mask Constant indicating the bit range that should be changed 8351 */ 8352 void setFlags(int flags, int mask) { 8353 int old = mViewFlags; 8354 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 8355 8356 int changed = mViewFlags ^ old; 8357 if (changed == 0) { 8358 return; 8359 } 8360 int privateFlags = mPrivateFlags; 8361 8362 /* Check if the FOCUSABLE bit has changed */ 8363 if (((changed & FOCUSABLE_MASK) != 0) && 8364 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 8365 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 8366 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 8367 /* Give up focus if we are no longer focusable */ 8368 clearFocus(); 8369 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 8370 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 8371 /* 8372 * Tell the view system that we are now available to take focus 8373 * if no one else already has it. 8374 */ 8375 if (mParent != null) mParent.focusableViewAvailable(this); 8376 } 8377 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8378 notifyAccessibilityStateChanged(); 8379 } 8380 } 8381 8382 if ((flags & VISIBILITY_MASK) == VISIBLE) { 8383 if ((changed & VISIBILITY_MASK) != 0) { 8384 /* 8385 * If this view is becoming visible, invalidate it in case it changed while 8386 * it was not visible. Marking it drawn ensures that the invalidation will 8387 * go through. 8388 */ 8389 mPrivateFlags |= PFLAG_DRAWN; 8390 invalidate(true); 8391 8392 needGlobalAttributesUpdate(true); 8393 8394 // a view becoming visible is worth notifying the parent 8395 // about in case nothing has focus. even if this specific view 8396 // isn't focusable, it may contain something that is, so let 8397 // the root view try to give this focus if nothing else does. 8398 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 8399 mParent.focusableViewAvailable(this); 8400 } 8401 } 8402 } 8403 8404 /* Check if the GONE bit has changed */ 8405 if ((changed & GONE) != 0) { 8406 needGlobalAttributesUpdate(false); 8407 requestLayout(); 8408 8409 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 8410 if (hasFocus()) clearFocus(); 8411 clearAccessibilityFocus(); 8412 destroyDrawingCache(); 8413 if (mParent instanceof View) { 8414 // GONE views noop invalidation, so invalidate the parent 8415 ((View) mParent).invalidate(true); 8416 } 8417 // Mark the view drawn to ensure that it gets invalidated properly the next 8418 // time it is visible and gets invalidated 8419 mPrivateFlags |= PFLAG_DRAWN; 8420 } 8421 if (mAttachInfo != null) { 8422 mAttachInfo.mViewVisibilityChanged = true; 8423 } 8424 } 8425 8426 /* Check if the VISIBLE bit has changed */ 8427 if ((changed & INVISIBLE) != 0) { 8428 needGlobalAttributesUpdate(false); 8429 /* 8430 * If this view is becoming invisible, set the DRAWN flag so that 8431 * the next invalidate() will not be skipped. 8432 */ 8433 mPrivateFlags |= PFLAG_DRAWN; 8434 8435 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 8436 // root view becoming invisible shouldn't clear focus and accessibility focus 8437 if (getRootView() != this) { 8438 clearFocus(); 8439 clearAccessibilityFocus(); 8440 } 8441 } 8442 if (mAttachInfo != null) { 8443 mAttachInfo.mViewVisibilityChanged = true; 8444 } 8445 } 8446 8447 if ((changed & VISIBILITY_MASK) != 0) { 8448 if (mParent instanceof ViewGroup) { 8449 ((ViewGroup) mParent).onChildVisibilityChanged(this, 8450 (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK)); 8451 ((View) mParent).invalidate(true); 8452 } else if (mParent != null) { 8453 mParent.invalidateChild(this, null); 8454 } 8455 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 8456 } 8457 8458 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 8459 destroyDrawingCache(); 8460 } 8461 8462 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 8463 destroyDrawingCache(); 8464 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8465 invalidateParentCaches(); 8466 } 8467 8468 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 8469 destroyDrawingCache(); 8470 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8471 } 8472 8473 if ((changed & DRAW_MASK) != 0) { 8474 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 8475 if (mBackground != null) { 8476 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8477 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 8478 } else { 8479 mPrivateFlags |= PFLAG_SKIP_DRAW; 8480 } 8481 } else { 8482 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8483 } 8484 requestLayout(); 8485 invalidate(true); 8486 } 8487 8488 if ((changed & KEEP_SCREEN_ON) != 0) { 8489 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 8490 mParent.recomputeViewAttributes(this); 8491 } 8492 } 8493 8494 if (AccessibilityManager.getInstance(mContext).isEnabled() 8495 && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0 8496 || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) { 8497 notifyAccessibilityStateChanged(); 8498 } 8499 } 8500 8501 /** 8502 * Change the view's z order in the tree, so it's on top of other sibling 8503 * views 8504 */ 8505 public void bringToFront() { 8506 if (mParent != null) { 8507 mParent.bringChildToFront(this); 8508 } 8509 } 8510 8511 /** 8512 * This is called in response to an internal scroll in this view (i.e., the 8513 * view scrolled its own contents). This is typically as a result of 8514 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 8515 * called. 8516 * 8517 * @param l Current horizontal scroll origin. 8518 * @param t Current vertical scroll origin. 8519 * @param oldl Previous horizontal scroll origin. 8520 * @param oldt Previous vertical scroll origin. 8521 */ 8522 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 8523 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8524 postSendViewScrolledAccessibilityEventCallback(); 8525 } 8526 8527 mBackgroundSizeChanged = true; 8528 8529 final AttachInfo ai = mAttachInfo; 8530 if (ai != null) { 8531 ai.mViewScrollChanged = true; 8532 } 8533 } 8534 8535 /** 8536 * Interface definition for a callback to be invoked when the layout bounds of a view 8537 * changes due to layout processing. 8538 */ 8539 public interface OnLayoutChangeListener { 8540 /** 8541 * Called when the focus state of a view has changed. 8542 * 8543 * @param v The view whose state has changed. 8544 * @param left The new value of the view's left property. 8545 * @param top The new value of the view's top property. 8546 * @param right The new value of the view's right property. 8547 * @param bottom The new value of the view's bottom property. 8548 * @param oldLeft The previous value of the view's left property. 8549 * @param oldTop The previous value of the view's top property. 8550 * @param oldRight The previous value of the view's right property. 8551 * @param oldBottom The previous value of the view's bottom property. 8552 */ 8553 void onLayoutChange(View v, int left, int top, int right, int bottom, 8554 int oldLeft, int oldTop, int oldRight, int oldBottom); 8555 } 8556 8557 /** 8558 * This is called during layout when the size of this view has changed. If 8559 * you were just added to the view hierarchy, you're called with the old 8560 * values of 0. 8561 * 8562 * @param w Current width of this view. 8563 * @param h Current height of this view. 8564 * @param oldw Old width of this view. 8565 * @param oldh Old height of this view. 8566 */ 8567 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 8568 } 8569 8570 /** 8571 * Called by draw to draw the child views. This may be overridden 8572 * by derived classes to gain control just before its children are drawn 8573 * (but after its own view has been drawn). 8574 * @param canvas the canvas on which to draw the view 8575 */ 8576 protected void dispatchDraw(Canvas canvas) { 8577 8578 } 8579 8580 /** 8581 * Gets the parent of this view. Note that the parent is a 8582 * ViewParent and not necessarily a View. 8583 * 8584 * @return Parent of this view. 8585 */ 8586 public final ViewParent getParent() { 8587 return mParent; 8588 } 8589 8590 /** 8591 * Set the horizontal scrolled position of your view. This will cause a call to 8592 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8593 * invalidated. 8594 * @param value the x position to scroll to 8595 */ 8596 public void setScrollX(int value) { 8597 scrollTo(value, mScrollY); 8598 } 8599 8600 /** 8601 * Set the vertical scrolled position of your view. This will cause a call to 8602 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8603 * invalidated. 8604 * @param value the y position to scroll to 8605 */ 8606 public void setScrollY(int value) { 8607 scrollTo(mScrollX, value); 8608 } 8609 8610 /** 8611 * Return the scrolled left position of this view. This is the left edge of 8612 * the displayed part of your view. You do not need to draw any pixels 8613 * farther left, since those are outside of the frame of your view on 8614 * screen. 8615 * 8616 * @return The left edge of the displayed part of your view, in pixels. 8617 */ 8618 public final int getScrollX() { 8619 return mScrollX; 8620 } 8621 8622 /** 8623 * Return the scrolled top position of this view. This is the top edge of 8624 * the displayed part of your view. You do not need to draw any pixels above 8625 * it, since those are outside of the frame of your view on screen. 8626 * 8627 * @return The top edge of the displayed part of your view, in pixels. 8628 */ 8629 public final int getScrollY() { 8630 return mScrollY; 8631 } 8632 8633 /** 8634 * Return the width of the your view. 8635 * 8636 * @return The width of your view, in pixels. 8637 */ 8638 @ViewDebug.ExportedProperty(category = "layout") 8639 public final int getWidth() { 8640 return mRight - mLeft; 8641 } 8642 8643 /** 8644 * Return the height of your view. 8645 * 8646 * @return The height of your view, in pixels. 8647 */ 8648 @ViewDebug.ExportedProperty(category = "layout") 8649 public final int getHeight() { 8650 return mBottom - mTop; 8651 } 8652 8653 /** 8654 * Return the visible drawing bounds of your view. Fills in the output 8655 * rectangle with the values from getScrollX(), getScrollY(), 8656 * getWidth(), and getHeight(). 8657 * 8658 * @param outRect The (scrolled) drawing bounds of the view. 8659 */ 8660 public void getDrawingRect(Rect outRect) { 8661 outRect.left = mScrollX; 8662 outRect.top = mScrollY; 8663 outRect.right = mScrollX + (mRight - mLeft); 8664 outRect.bottom = mScrollY + (mBottom - mTop); 8665 } 8666 8667 /** 8668 * Like {@link #getMeasuredWidthAndState()}, but only returns the 8669 * raw width component (that is the result is masked by 8670 * {@link #MEASURED_SIZE_MASK}). 8671 * 8672 * @return The raw measured width of this view. 8673 */ 8674 public final int getMeasuredWidth() { 8675 return mMeasuredWidth & MEASURED_SIZE_MASK; 8676 } 8677 8678 /** 8679 * Return the full width measurement information for this view as computed 8680 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8681 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8682 * This should be used during measurement and layout calculations only. Use 8683 * {@link #getWidth()} to see how wide a view is after layout. 8684 * 8685 * @return The measured width of this view as a bit mask. 8686 */ 8687 public final int getMeasuredWidthAndState() { 8688 return mMeasuredWidth; 8689 } 8690 8691 /** 8692 * Like {@link #getMeasuredHeightAndState()}, but only returns the 8693 * raw width component (that is the result is masked by 8694 * {@link #MEASURED_SIZE_MASK}). 8695 * 8696 * @return The raw measured height of this view. 8697 */ 8698 public final int getMeasuredHeight() { 8699 return mMeasuredHeight & MEASURED_SIZE_MASK; 8700 } 8701 8702 /** 8703 * Return the full height measurement information for this view as computed 8704 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8705 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8706 * This should be used during measurement and layout calculations only. Use 8707 * {@link #getHeight()} to see how wide a view is after layout. 8708 * 8709 * @return The measured width of this view as a bit mask. 8710 */ 8711 public final int getMeasuredHeightAndState() { 8712 return mMeasuredHeight; 8713 } 8714 8715 /** 8716 * Return only the state bits of {@link #getMeasuredWidthAndState()} 8717 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 8718 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 8719 * and the height component is at the shifted bits 8720 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 8721 */ 8722 public final int getMeasuredState() { 8723 return (mMeasuredWidth&MEASURED_STATE_MASK) 8724 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 8725 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 8726 } 8727 8728 /** 8729 * The transform matrix of this view, which is calculated based on the current 8730 * roation, scale, and pivot properties. 8731 * 8732 * @see #getRotation() 8733 * @see #getScaleX() 8734 * @see #getScaleY() 8735 * @see #getPivotX() 8736 * @see #getPivotY() 8737 * @return The current transform matrix for the view 8738 */ 8739 public Matrix getMatrix() { 8740 if (mTransformationInfo != null) { 8741 updateMatrix(); 8742 return mTransformationInfo.mMatrix; 8743 } 8744 return Matrix.IDENTITY_MATRIX; 8745 } 8746 8747 /** 8748 * Utility function to determine if the value is far enough away from zero to be 8749 * considered non-zero. 8750 * @param value A floating point value to check for zero-ness 8751 * @return whether the passed-in value is far enough away from zero to be considered non-zero 8752 */ 8753 private static boolean nonzero(float value) { 8754 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 8755 } 8756 8757 /** 8758 * Returns true if the transform matrix is the identity matrix. 8759 * Recomputes the matrix if necessary. 8760 * 8761 * @return True if the transform matrix is the identity matrix, false otherwise. 8762 */ 8763 final boolean hasIdentityMatrix() { 8764 if (mTransformationInfo != null) { 8765 updateMatrix(); 8766 return mTransformationInfo.mMatrixIsIdentity; 8767 } 8768 return true; 8769 } 8770 8771 void ensureTransformationInfo() { 8772 if (mTransformationInfo == null) { 8773 mTransformationInfo = new TransformationInfo(); 8774 } 8775 } 8776 8777 /** 8778 * Recomputes the transform matrix if necessary. 8779 */ 8780 private void updateMatrix() { 8781 final TransformationInfo info = mTransformationInfo; 8782 if (info == null) { 8783 return; 8784 } 8785 if (info.mMatrixDirty) { 8786 // transform-related properties have changed since the last time someone 8787 // asked for the matrix; recalculate it with the current values 8788 8789 // Figure out if we need to update the pivot point 8790 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 8791 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 8792 info.mPrevWidth = mRight - mLeft; 8793 info.mPrevHeight = mBottom - mTop; 8794 info.mPivotX = info.mPrevWidth / 2f; 8795 info.mPivotY = info.mPrevHeight / 2f; 8796 } 8797 } 8798 info.mMatrix.reset(); 8799 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 8800 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 8801 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 8802 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 8803 } else { 8804 if (info.mCamera == null) { 8805 info.mCamera = new Camera(); 8806 info.matrix3D = new Matrix(); 8807 } 8808 info.mCamera.save(); 8809 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 8810 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 8811 info.mCamera.getMatrix(info.matrix3D); 8812 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 8813 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 8814 info.mPivotY + info.mTranslationY); 8815 info.mMatrix.postConcat(info.matrix3D); 8816 info.mCamera.restore(); 8817 } 8818 info.mMatrixDirty = false; 8819 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 8820 info.mInverseMatrixDirty = true; 8821 } 8822 } 8823 8824 /** 8825 * Utility method to retrieve the inverse of the current mMatrix property. 8826 * We cache the matrix to avoid recalculating it when transform properties 8827 * have not changed. 8828 * 8829 * @return The inverse of the current matrix of this view. 8830 */ 8831 final Matrix getInverseMatrix() { 8832 final TransformationInfo info = mTransformationInfo; 8833 if (info != null) { 8834 updateMatrix(); 8835 if (info.mInverseMatrixDirty) { 8836 if (info.mInverseMatrix == null) { 8837 info.mInverseMatrix = new Matrix(); 8838 } 8839 info.mMatrix.invert(info.mInverseMatrix); 8840 info.mInverseMatrixDirty = false; 8841 } 8842 return info.mInverseMatrix; 8843 } 8844 return Matrix.IDENTITY_MATRIX; 8845 } 8846 8847 /** 8848 * Gets the distance along the Z axis from the camera to this view. 8849 * 8850 * @see #setCameraDistance(float) 8851 * 8852 * @return The distance along the Z axis. 8853 */ 8854 public float getCameraDistance() { 8855 ensureTransformationInfo(); 8856 final float dpi = mResources.getDisplayMetrics().densityDpi; 8857 final TransformationInfo info = mTransformationInfo; 8858 if (info.mCamera == null) { 8859 info.mCamera = new Camera(); 8860 info.matrix3D = new Matrix(); 8861 } 8862 return -(info.mCamera.getLocationZ() * dpi); 8863 } 8864 8865 /** 8866 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 8867 * views are drawn) from the camera to this view. The camera's distance 8868 * affects 3D transformations, for instance rotations around the X and Y 8869 * axis. If the rotationX or rotationY properties are changed and this view is 8870 * large (more than half the size of the screen), it is recommended to always 8871 * use a camera distance that's greater than the height (X axis rotation) or 8872 * the width (Y axis rotation) of this view.</p> 8873 * 8874 * <p>The distance of the camera from the view plane can have an affect on the 8875 * perspective distortion of the view when it is rotated around the x or y axis. 8876 * For example, a large distance will result in a large viewing angle, and there 8877 * will not be much perspective distortion of the view as it rotates. A short 8878 * distance may cause much more perspective distortion upon rotation, and can 8879 * also result in some drawing artifacts if the rotated view ends up partially 8880 * behind the camera (which is why the recommendation is to use a distance at 8881 * least as far as the size of the view, if the view is to be rotated.)</p> 8882 * 8883 * <p>The distance is expressed in "depth pixels." The default distance depends 8884 * on the screen density. For instance, on a medium density display, the 8885 * default distance is 1280. On a high density display, the default distance 8886 * is 1920.</p> 8887 * 8888 * <p>If you want to specify a distance that leads to visually consistent 8889 * results across various densities, use the following formula:</p> 8890 * <pre> 8891 * float scale = context.getResources().getDisplayMetrics().density; 8892 * view.setCameraDistance(distance * scale); 8893 * </pre> 8894 * 8895 * <p>The density scale factor of a high density display is 1.5, 8896 * and 1920 = 1280 * 1.5.</p> 8897 * 8898 * @param distance The distance in "depth pixels", if negative the opposite 8899 * value is used 8900 * 8901 * @see #setRotationX(float) 8902 * @see #setRotationY(float) 8903 */ 8904 public void setCameraDistance(float distance) { 8905 invalidateViewProperty(true, false); 8906 8907 ensureTransformationInfo(); 8908 final float dpi = mResources.getDisplayMetrics().densityDpi; 8909 final TransformationInfo info = mTransformationInfo; 8910 if (info.mCamera == null) { 8911 info.mCamera = new Camera(); 8912 info.matrix3D = new Matrix(); 8913 } 8914 8915 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 8916 info.mMatrixDirty = true; 8917 8918 invalidateViewProperty(false, false); 8919 if (mDisplayList != null) { 8920 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 8921 } 8922 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 8923 // View was rejected last time it was drawn by its parent; this may have changed 8924 invalidateParentIfNeeded(); 8925 } 8926 } 8927 8928 /** 8929 * The degrees that the view is rotated around the pivot point. 8930 * 8931 * @see #setRotation(float) 8932 * @see #getPivotX() 8933 * @see #getPivotY() 8934 * 8935 * @return The degrees of rotation. 8936 */ 8937 @ViewDebug.ExportedProperty(category = "drawing") 8938 public float getRotation() { 8939 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 8940 } 8941 8942 /** 8943 * Sets the degrees that the view is rotated around the pivot point. Increasing values 8944 * result in clockwise rotation. 8945 * 8946 * @param rotation The degrees of rotation. 8947 * 8948 * @see #getRotation() 8949 * @see #getPivotX() 8950 * @see #getPivotY() 8951 * @see #setRotationX(float) 8952 * @see #setRotationY(float) 8953 * 8954 * @attr ref android.R.styleable#View_rotation 8955 */ 8956 public void setRotation(float rotation) { 8957 ensureTransformationInfo(); 8958 final TransformationInfo info = mTransformationInfo; 8959 if (info.mRotation != rotation) { 8960 // Double-invalidation is necessary to capture view's old and new areas 8961 invalidateViewProperty(true, false); 8962 info.mRotation = rotation; 8963 info.mMatrixDirty = true; 8964 invalidateViewProperty(false, true); 8965 if (mDisplayList != null) { 8966 mDisplayList.setRotation(rotation); 8967 } 8968 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 8969 // View was rejected last time it was drawn by its parent; this may have changed 8970 invalidateParentIfNeeded(); 8971 } 8972 } 8973 } 8974 8975 /** 8976 * The degrees that the view is rotated around the vertical axis through the pivot point. 8977 * 8978 * @see #getPivotX() 8979 * @see #getPivotY() 8980 * @see #setRotationY(float) 8981 * 8982 * @return The degrees of Y rotation. 8983 */ 8984 @ViewDebug.ExportedProperty(category = "drawing") 8985 public float getRotationY() { 8986 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 8987 } 8988 8989 /** 8990 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 8991 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 8992 * down the y axis. 8993 * 8994 * When rotating large views, it is recommended to adjust the camera distance 8995 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 8996 * 8997 * @param rotationY The degrees of Y rotation. 8998 * 8999 * @see #getRotationY() 9000 * @see #getPivotX() 9001 * @see #getPivotY() 9002 * @see #setRotation(float) 9003 * @see #setRotationX(float) 9004 * @see #setCameraDistance(float) 9005 * 9006 * @attr ref android.R.styleable#View_rotationY 9007 */ 9008 public void setRotationY(float rotationY) { 9009 ensureTransformationInfo(); 9010 final TransformationInfo info = mTransformationInfo; 9011 if (info.mRotationY != rotationY) { 9012 invalidateViewProperty(true, false); 9013 info.mRotationY = rotationY; 9014 info.mMatrixDirty = true; 9015 invalidateViewProperty(false, true); 9016 if (mDisplayList != null) { 9017 mDisplayList.setRotationY(rotationY); 9018 } 9019 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9020 // View was rejected last time it was drawn by its parent; this may have changed 9021 invalidateParentIfNeeded(); 9022 } 9023 } 9024 } 9025 9026 /** 9027 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9028 * 9029 * @see #getPivotX() 9030 * @see #getPivotY() 9031 * @see #setRotationX(float) 9032 * 9033 * @return The degrees of X rotation. 9034 */ 9035 @ViewDebug.ExportedProperty(category = "drawing") 9036 public float getRotationX() { 9037 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 9038 } 9039 9040 /** 9041 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9042 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9043 * x axis. 9044 * 9045 * When rotating large views, it is recommended to adjust the camera distance 9046 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9047 * 9048 * @param rotationX The degrees of X rotation. 9049 * 9050 * @see #getRotationX() 9051 * @see #getPivotX() 9052 * @see #getPivotY() 9053 * @see #setRotation(float) 9054 * @see #setRotationY(float) 9055 * @see #setCameraDistance(float) 9056 * 9057 * @attr ref android.R.styleable#View_rotationX 9058 */ 9059 public void setRotationX(float rotationX) { 9060 ensureTransformationInfo(); 9061 final TransformationInfo info = mTransformationInfo; 9062 if (info.mRotationX != rotationX) { 9063 invalidateViewProperty(true, false); 9064 info.mRotationX = rotationX; 9065 info.mMatrixDirty = true; 9066 invalidateViewProperty(false, true); 9067 if (mDisplayList != null) { 9068 mDisplayList.setRotationX(rotationX); 9069 } 9070 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9071 // View was rejected last time it was drawn by its parent; this may have changed 9072 invalidateParentIfNeeded(); 9073 } 9074 } 9075 } 9076 9077 /** 9078 * The amount that the view is scaled in x around the pivot point, as a proportion of 9079 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9080 * 9081 * <p>By default, this is 1.0f. 9082 * 9083 * @see #getPivotX() 9084 * @see #getPivotY() 9085 * @return The scaling factor. 9086 */ 9087 @ViewDebug.ExportedProperty(category = "drawing") 9088 public float getScaleX() { 9089 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 9090 } 9091 9092 /** 9093 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9094 * the view's unscaled width. A value of 1 means that no scaling is applied. 9095 * 9096 * @param scaleX The scaling factor. 9097 * @see #getPivotX() 9098 * @see #getPivotY() 9099 * 9100 * @attr ref android.R.styleable#View_scaleX 9101 */ 9102 public void setScaleX(float scaleX) { 9103 ensureTransformationInfo(); 9104 final TransformationInfo info = mTransformationInfo; 9105 if (info.mScaleX != scaleX) { 9106 invalidateViewProperty(true, false); 9107 info.mScaleX = scaleX; 9108 info.mMatrixDirty = true; 9109 invalidateViewProperty(false, true); 9110 if (mDisplayList != null) { 9111 mDisplayList.setScaleX(scaleX); 9112 } 9113 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9114 // View was rejected last time it was drawn by its parent; this may have changed 9115 invalidateParentIfNeeded(); 9116 } 9117 } 9118 } 9119 9120 /** 9121 * The amount that the view is scaled in y around the pivot point, as a proportion of 9122 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9123 * 9124 * <p>By default, this is 1.0f. 9125 * 9126 * @see #getPivotX() 9127 * @see #getPivotY() 9128 * @return The scaling factor. 9129 */ 9130 @ViewDebug.ExportedProperty(category = "drawing") 9131 public float getScaleY() { 9132 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 9133 } 9134 9135 /** 9136 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9137 * the view's unscaled width. A value of 1 means that no scaling is applied. 9138 * 9139 * @param scaleY The scaling factor. 9140 * @see #getPivotX() 9141 * @see #getPivotY() 9142 * 9143 * @attr ref android.R.styleable#View_scaleY 9144 */ 9145 public void setScaleY(float scaleY) { 9146 ensureTransformationInfo(); 9147 final TransformationInfo info = mTransformationInfo; 9148 if (info.mScaleY != scaleY) { 9149 invalidateViewProperty(true, false); 9150 info.mScaleY = scaleY; 9151 info.mMatrixDirty = true; 9152 invalidateViewProperty(false, true); 9153 if (mDisplayList != null) { 9154 mDisplayList.setScaleY(scaleY); 9155 } 9156 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9157 // View was rejected last time it was drawn by its parent; this may have changed 9158 invalidateParentIfNeeded(); 9159 } 9160 } 9161 } 9162 9163 /** 9164 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9165 * and {@link #setScaleX(float) scaled}. 9166 * 9167 * @see #getRotation() 9168 * @see #getScaleX() 9169 * @see #getScaleY() 9170 * @see #getPivotY() 9171 * @return The x location of the pivot point. 9172 * 9173 * @attr ref android.R.styleable#View_transformPivotX 9174 */ 9175 @ViewDebug.ExportedProperty(category = "drawing") 9176 public float getPivotX() { 9177 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 9178 } 9179 9180 /** 9181 * Sets the x location of the point around which the view is 9182 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9183 * By default, the pivot point is centered on the object. 9184 * Setting this property disables this behavior and causes the view to use only the 9185 * explicitly set pivotX and pivotY values. 9186 * 9187 * @param pivotX The x location of the pivot point. 9188 * @see #getRotation() 9189 * @see #getScaleX() 9190 * @see #getScaleY() 9191 * @see #getPivotY() 9192 * 9193 * @attr ref android.R.styleable#View_transformPivotX 9194 */ 9195 public void setPivotX(float pivotX) { 9196 ensureTransformationInfo(); 9197 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9198 final TransformationInfo info = mTransformationInfo; 9199 if (info.mPivotX != pivotX) { 9200 invalidateViewProperty(true, false); 9201 info.mPivotX = pivotX; 9202 info.mMatrixDirty = true; 9203 invalidateViewProperty(false, true); 9204 if (mDisplayList != null) { 9205 mDisplayList.setPivotX(pivotX); 9206 } 9207 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9208 // View was rejected last time it was drawn by its parent; this may have changed 9209 invalidateParentIfNeeded(); 9210 } 9211 } 9212 } 9213 9214 /** 9215 * The y location of the point around which the view is {@link #setRotation(float) rotated} 9216 * and {@link #setScaleY(float) scaled}. 9217 * 9218 * @see #getRotation() 9219 * @see #getScaleX() 9220 * @see #getScaleY() 9221 * @see #getPivotY() 9222 * @return The y location of the pivot point. 9223 * 9224 * @attr ref android.R.styleable#View_transformPivotY 9225 */ 9226 @ViewDebug.ExportedProperty(category = "drawing") 9227 public float getPivotY() { 9228 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 9229 } 9230 9231 /** 9232 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 9233 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 9234 * Setting this property disables this behavior and causes the view to use only the 9235 * explicitly set pivotX and pivotY values. 9236 * 9237 * @param pivotY The y location of the pivot point. 9238 * @see #getRotation() 9239 * @see #getScaleX() 9240 * @see #getScaleY() 9241 * @see #getPivotY() 9242 * 9243 * @attr ref android.R.styleable#View_transformPivotY 9244 */ 9245 public void setPivotY(float pivotY) { 9246 ensureTransformationInfo(); 9247 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9248 final TransformationInfo info = mTransformationInfo; 9249 if (info.mPivotY != pivotY) { 9250 invalidateViewProperty(true, false); 9251 info.mPivotY = pivotY; 9252 info.mMatrixDirty = true; 9253 invalidateViewProperty(false, true); 9254 if (mDisplayList != null) { 9255 mDisplayList.setPivotY(pivotY); 9256 } 9257 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9258 // View was rejected last time it was drawn by its parent; this may have changed 9259 invalidateParentIfNeeded(); 9260 } 9261 } 9262 } 9263 9264 /** 9265 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 9266 * completely transparent and 1 means the view is completely opaque. 9267 * 9268 * <p>By default this is 1.0f. 9269 * @return The opacity of the view. 9270 */ 9271 @ViewDebug.ExportedProperty(category = "drawing") 9272 public float getAlpha() { 9273 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 9274 } 9275 9276 /** 9277 * Returns whether this View has content which overlaps. This function, intended to be 9278 * overridden by specific View types, is an optimization when alpha is set on a view. If 9279 * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer 9280 * and then composited it into place, which can be expensive. If the view has no overlapping 9281 * rendering, the view can draw each primitive with the appropriate alpha value directly. 9282 * An example of overlapping rendering is a TextView with a background image, such as a 9283 * Button. An example of non-overlapping rendering is a TextView with no background, or 9284 * an ImageView with only the foreground image. The default implementation returns true; 9285 * subclasses should override if they have cases which can be optimized. 9286 * 9287 * @return true if the content in this view might overlap, false otherwise. 9288 */ 9289 public boolean hasOverlappingRendering() { 9290 return true; 9291 } 9292 9293 /** 9294 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 9295 * completely transparent and 1 means the view is completely opaque.</p> 9296 * 9297 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 9298 * responsible for applying the opacity itself. Otherwise, calling this method is 9299 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 9300 * setting a hardware layer.</p> 9301 * 9302 * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have 9303 * performance implications. It is generally best to use the alpha property sparingly and 9304 * transiently, as in the case of fading animations.</p> 9305 * 9306 * @param alpha The opacity of the view. 9307 * 9308 * @see #setLayerType(int, android.graphics.Paint) 9309 * 9310 * @attr ref android.R.styleable#View_alpha 9311 */ 9312 public void setAlpha(float alpha) { 9313 ensureTransformationInfo(); 9314 if (mTransformationInfo.mAlpha != alpha) { 9315 mTransformationInfo.mAlpha = alpha; 9316 if (onSetAlpha((int) (alpha * 255))) { 9317 mPrivateFlags |= PFLAG_ALPHA_SET; 9318 // subclass is handling alpha - don't optimize rendering cache invalidation 9319 invalidateParentCaches(); 9320 invalidate(true); 9321 } else { 9322 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9323 invalidateViewProperty(true, false); 9324 if (mDisplayList != null) { 9325 mDisplayList.setAlpha(alpha); 9326 } 9327 } 9328 } 9329 } 9330 9331 /** 9332 * Faster version of setAlpha() which performs the same steps except there are 9333 * no calls to invalidate(). The caller of this function should perform proper invalidation 9334 * on the parent and this object. The return value indicates whether the subclass handles 9335 * alpha (the return value for onSetAlpha()). 9336 * 9337 * @param alpha The new value for the alpha property 9338 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 9339 * the new value for the alpha property is different from the old value 9340 */ 9341 boolean setAlphaNoInvalidation(float alpha) { 9342 ensureTransformationInfo(); 9343 if (mTransformationInfo.mAlpha != alpha) { 9344 mTransformationInfo.mAlpha = alpha; 9345 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 9346 if (subclassHandlesAlpha) { 9347 mPrivateFlags |= PFLAG_ALPHA_SET; 9348 return true; 9349 } else { 9350 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9351 if (mDisplayList != null) { 9352 mDisplayList.setAlpha(alpha); 9353 } 9354 } 9355 } 9356 return false; 9357 } 9358 9359 /** 9360 * Top position of this view relative to its parent. 9361 * 9362 * @return The top of this view, in pixels. 9363 */ 9364 @ViewDebug.CapturedViewProperty 9365 public final int getTop() { 9366 return mTop; 9367 } 9368 9369 /** 9370 * Sets the top position of this view relative to its parent. This method is meant to be called 9371 * by the layout system and should not generally be called otherwise, because the property 9372 * may be changed at any time by the layout. 9373 * 9374 * @param top The top of this view, in pixels. 9375 */ 9376 public final void setTop(int top) { 9377 if (top != mTop) { 9378 updateMatrix(); 9379 final boolean matrixIsIdentity = mTransformationInfo == null 9380 || mTransformationInfo.mMatrixIsIdentity; 9381 if (matrixIsIdentity) { 9382 if (mAttachInfo != null) { 9383 int minTop; 9384 int yLoc; 9385 if (top < mTop) { 9386 minTop = top; 9387 yLoc = top - mTop; 9388 } else { 9389 minTop = mTop; 9390 yLoc = 0; 9391 } 9392 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 9393 } 9394 } else { 9395 // Double-invalidation is necessary to capture view's old and new areas 9396 invalidate(true); 9397 } 9398 9399 int width = mRight - mLeft; 9400 int oldHeight = mBottom - mTop; 9401 9402 mTop = top; 9403 if (mDisplayList != null) { 9404 mDisplayList.setTop(mTop); 9405 } 9406 9407 onSizeChanged(width, mBottom - mTop, width, oldHeight); 9408 9409 if (!matrixIsIdentity) { 9410 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9411 // A change in dimension means an auto-centered pivot point changes, too 9412 mTransformationInfo.mMatrixDirty = true; 9413 } 9414 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9415 invalidate(true); 9416 } 9417 mBackgroundSizeChanged = true; 9418 invalidateParentIfNeeded(); 9419 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9420 // View was rejected last time it was drawn by its parent; this may have changed 9421 invalidateParentIfNeeded(); 9422 } 9423 } 9424 } 9425 9426 /** 9427 * Bottom position of this view relative to its parent. 9428 * 9429 * @return The bottom of this view, in pixels. 9430 */ 9431 @ViewDebug.CapturedViewProperty 9432 public final int getBottom() { 9433 return mBottom; 9434 } 9435 9436 /** 9437 * True if this view has changed since the last time being drawn. 9438 * 9439 * @return The dirty state of this view. 9440 */ 9441 public boolean isDirty() { 9442 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 9443 } 9444 9445 /** 9446 * Sets the bottom position of this view relative to its parent. This method is meant to be 9447 * called by the layout system and should not generally be called otherwise, because the 9448 * property may be changed at any time by the layout. 9449 * 9450 * @param bottom The bottom of this view, in pixels. 9451 */ 9452 public final void setBottom(int bottom) { 9453 if (bottom != mBottom) { 9454 updateMatrix(); 9455 final boolean matrixIsIdentity = mTransformationInfo == null 9456 || mTransformationInfo.mMatrixIsIdentity; 9457 if (matrixIsIdentity) { 9458 if (mAttachInfo != null) { 9459 int maxBottom; 9460 if (bottom < mBottom) { 9461 maxBottom = mBottom; 9462 } else { 9463 maxBottom = bottom; 9464 } 9465 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 9466 } 9467 } else { 9468 // Double-invalidation is necessary to capture view's old and new areas 9469 invalidate(true); 9470 } 9471 9472 int width = mRight - mLeft; 9473 int oldHeight = mBottom - mTop; 9474 9475 mBottom = bottom; 9476 if (mDisplayList != null) { 9477 mDisplayList.setBottom(mBottom); 9478 } 9479 9480 onSizeChanged(width, mBottom - mTop, width, oldHeight); 9481 9482 if (!matrixIsIdentity) { 9483 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9484 // A change in dimension means an auto-centered pivot point changes, too 9485 mTransformationInfo.mMatrixDirty = true; 9486 } 9487 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9488 invalidate(true); 9489 } 9490 mBackgroundSizeChanged = true; 9491 invalidateParentIfNeeded(); 9492 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9493 // View was rejected last time it was drawn by its parent; this may have changed 9494 invalidateParentIfNeeded(); 9495 } 9496 } 9497 } 9498 9499 /** 9500 * Left position of this view relative to its parent. 9501 * 9502 * @return The left edge of this view, in pixels. 9503 */ 9504 @ViewDebug.CapturedViewProperty 9505 public final int getLeft() { 9506 return mLeft; 9507 } 9508 9509 /** 9510 * Sets the left position of this view relative to its parent. This method is meant to be called 9511 * by the layout system and should not generally be called otherwise, because the property 9512 * may be changed at any time by the layout. 9513 * 9514 * @param left The bottom of this view, in pixels. 9515 */ 9516 public final void setLeft(int left) { 9517 if (left != mLeft) { 9518 updateMatrix(); 9519 final boolean matrixIsIdentity = mTransformationInfo == null 9520 || mTransformationInfo.mMatrixIsIdentity; 9521 if (matrixIsIdentity) { 9522 if (mAttachInfo != null) { 9523 int minLeft; 9524 int xLoc; 9525 if (left < mLeft) { 9526 minLeft = left; 9527 xLoc = left - mLeft; 9528 } else { 9529 minLeft = mLeft; 9530 xLoc = 0; 9531 } 9532 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 9533 } 9534 } else { 9535 // Double-invalidation is necessary to capture view's old and new areas 9536 invalidate(true); 9537 } 9538 9539 int oldWidth = mRight - mLeft; 9540 int height = mBottom - mTop; 9541 9542 mLeft = left; 9543 if (mDisplayList != null) { 9544 mDisplayList.setLeft(left); 9545 } 9546 9547 onSizeChanged(mRight - mLeft, height, oldWidth, height); 9548 9549 if (!matrixIsIdentity) { 9550 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9551 // A change in dimension means an auto-centered pivot point changes, too 9552 mTransformationInfo.mMatrixDirty = true; 9553 } 9554 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9555 invalidate(true); 9556 } 9557 mBackgroundSizeChanged = true; 9558 invalidateParentIfNeeded(); 9559 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9560 // View was rejected last time it was drawn by its parent; this may have changed 9561 invalidateParentIfNeeded(); 9562 } 9563 } 9564 } 9565 9566 /** 9567 * Right position of this view relative to its parent. 9568 * 9569 * @return The right edge of this view, in pixels. 9570 */ 9571 @ViewDebug.CapturedViewProperty 9572 public final int getRight() { 9573 return mRight; 9574 } 9575 9576 /** 9577 * Sets the right position of this view relative to its parent. This method is meant to be called 9578 * by the layout system and should not generally be called otherwise, because the property 9579 * may be changed at any time by the layout. 9580 * 9581 * @param right The bottom of this view, in pixels. 9582 */ 9583 public final void setRight(int right) { 9584 if (right != mRight) { 9585 updateMatrix(); 9586 final boolean matrixIsIdentity = mTransformationInfo == null 9587 || mTransformationInfo.mMatrixIsIdentity; 9588 if (matrixIsIdentity) { 9589 if (mAttachInfo != null) { 9590 int maxRight; 9591 if (right < mRight) { 9592 maxRight = mRight; 9593 } else { 9594 maxRight = right; 9595 } 9596 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 9597 } 9598 } else { 9599 // Double-invalidation is necessary to capture view's old and new areas 9600 invalidate(true); 9601 } 9602 9603 int oldWidth = mRight - mLeft; 9604 int height = mBottom - mTop; 9605 9606 mRight = right; 9607 if (mDisplayList != null) { 9608 mDisplayList.setRight(mRight); 9609 } 9610 9611 onSizeChanged(mRight - mLeft, height, oldWidth, height); 9612 9613 if (!matrixIsIdentity) { 9614 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9615 // A change in dimension means an auto-centered pivot point changes, too 9616 mTransformationInfo.mMatrixDirty = true; 9617 } 9618 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9619 invalidate(true); 9620 } 9621 mBackgroundSizeChanged = true; 9622 invalidateParentIfNeeded(); 9623 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9624 // View was rejected last time it was drawn by its parent; this may have changed 9625 invalidateParentIfNeeded(); 9626 } 9627 } 9628 } 9629 9630 /** 9631 * The visual x position of this view, in pixels. This is equivalent to the 9632 * {@link #setTranslationX(float) translationX} property plus the current 9633 * {@link #getLeft() left} property. 9634 * 9635 * @return The visual x position of this view, in pixels. 9636 */ 9637 @ViewDebug.ExportedProperty(category = "drawing") 9638 public float getX() { 9639 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 9640 } 9641 9642 /** 9643 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 9644 * {@link #setTranslationX(float) translationX} property to be the difference between 9645 * the x value passed in and the current {@link #getLeft() left} property. 9646 * 9647 * @param x The visual x position of this view, in pixels. 9648 */ 9649 public void setX(float x) { 9650 setTranslationX(x - mLeft); 9651 } 9652 9653 /** 9654 * The visual y position of this view, in pixels. This is equivalent to the 9655 * {@link #setTranslationY(float) translationY} property plus the current 9656 * {@link #getTop() top} property. 9657 * 9658 * @return The visual y position of this view, in pixels. 9659 */ 9660 @ViewDebug.ExportedProperty(category = "drawing") 9661 public float getY() { 9662 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 9663 } 9664 9665 /** 9666 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 9667 * {@link #setTranslationY(float) translationY} property to be the difference between 9668 * the y value passed in and the current {@link #getTop() top} property. 9669 * 9670 * @param y The visual y position of this view, in pixels. 9671 */ 9672 public void setY(float y) { 9673 setTranslationY(y - mTop); 9674 } 9675 9676 9677 /** 9678 * The horizontal location of this view relative to its {@link #getLeft() left} position. 9679 * This position is post-layout, in addition to wherever the object's 9680 * layout placed it. 9681 * 9682 * @return The horizontal position of this view relative to its left position, in pixels. 9683 */ 9684 @ViewDebug.ExportedProperty(category = "drawing") 9685 public float getTranslationX() { 9686 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 9687 } 9688 9689 /** 9690 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 9691 * This effectively positions the object post-layout, in addition to wherever the object's 9692 * layout placed it. 9693 * 9694 * @param translationX The horizontal position of this view relative to its left position, 9695 * in pixels. 9696 * 9697 * @attr ref android.R.styleable#View_translationX 9698 */ 9699 public void setTranslationX(float translationX) { 9700 ensureTransformationInfo(); 9701 final TransformationInfo info = mTransformationInfo; 9702 if (info.mTranslationX != translationX) { 9703 // Double-invalidation is necessary to capture view's old and new areas 9704 invalidateViewProperty(true, false); 9705 info.mTranslationX = translationX; 9706 info.mMatrixDirty = true; 9707 invalidateViewProperty(false, true); 9708 if (mDisplayList != null) { 9709 mDisplayList.setTranslationX(translationX); 9710 } 9711 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9712 // View was rejected last time it was drawn by its parent; this may have changed 9713 invalidateParentIfNeeded(); 9714 } 9715 } 9716 } 9717 9718 /** 9719 * The horizontal location of this view relative to its {@link #getTop() top} position. 9720 * This position is post-layout, in addition to wherever the object's 9721 * layout placed it. 9722 * 9723 * @return The vertical position of this view relative to its top position, 9724 * in pixels. 9725 */ 9726 @ViewDebug.ExportedProperty(category = "drawing") 9727 public float getTranslationY() { 9728 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 9729 } 9730 9731 /** 9732 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 9733 * This effectively positions the object post-layout, in addition to wherever the object's 9734 * layout placed it. 9735 * 9736 * @param translationY The vertical position of this view relative to its top position, 9737 * in pixels. 9738 * 9739 * @attr ref android.R.styleable#View_translationY 9740 */ 9741 public void setTranslationY(float translationY) { 9742 ensureTransformationInfo(); 9743 final TransformationInfo info = mTransformationInfo; 9744 if (info.mTranslationY != translationY) { 9745 invalidateViewProperty(true, false); 9746 info.mTranslationY = translationY; 9747 info.mMatrixDirty = true; 9748 invalidateViewProperty(false, true); 9749 if (mDisplayList != null) { 9750 mDisplayList.setTranslationY(translationY); 9751 } 9752 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9753 // View was rejected last time it was drawn by its parent; this may have changed 9754 invalidateParentIfNeeded(); 9755 } 9756 } 9757 } 9758 9759 /** 9760 * Hit rectangle in parent's coordinates 9761 * 9762 * @param outRect The hit rectangle of the view. 9763 */ 9764 public void getHitRect(Rect outRect) { 9765 updateMatrix(); 9766 final TransformationInfo info = mTransformationInfo; 9767 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 9768 outRect.set(mLeft, mTop, mRight, mBottom); 9769 } else { 9770 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 9771 tmpRect.set(-info.mPivotX, -info.mPivotY, 9772 getWidth() - info.mPivotX, getHeight() - info.mPivotY); 9773 info.mMatrix.mapRect(tmpRect); 9774 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 9775 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 9776 } 9777 } 9778 9779 /** 9780 * Determines whether the given point, in local coordinates is inside the view. 9781 */ 9782 /*package*/ final boolean pointInView(float localX, float localY) { 9783 return localX >= 0 && localX < (mRight - mLeft) 9784 && localY >= 0 && localY < (mBottom - mTop); 9785 } 9786 9787 /** 9788 * Utility method to determine whether the given point, in local coordinates, 9789 * is inside the view, where the area of the view is expanded by the slop factor. 9790 * This method is called while processing touch-move events to determine if the event 9791 * is still within the view. 9792 */ 9793 private boolean pointInView(float localX, float localY, float slop) { 9794 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 9795 localY < ((mBottom - mTop) + slop); 9796 } 9797 9798 /** 9799 * When a view has focus and the user navigates away from it, the next view is searched for 9800 * starting from the rectangle filled in by this method. 9801 * 9802 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 9803 * of the view. However, if your view maintains some idea of internal selection, 9804 * such as a cursor, or a selected row or column, you should override this method and 9805 * fill in a more specific rectangle. 9806 * 9807 * @param r The rectangle to fill in, in this view's coordinates. 9808 */ 9809 public void getFocusedRect(Rect r) { 9810 getDrawingRect(r); 9811 } 9812 9813 /** 9814 * If some part of this view is not clipped by any of its parents, then 9815 * return that area in r in global (root) coordinates. To convert r to local 9816 * coordinates (without taking possible View rotations into account), offset 9817 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 9818 * If the view is completely clipped or translated out, return false. 9819 * 9820 * @param r If true is returned, r holds the global coordinates of the 9821 * visible portion of this view. 9822 * @param globalOffset If true is returned, globalOffset holds the dx,dy 9823 * between this view and its root. globalOffet may be null. 9824 * @return true if r is non-empty (i.e. part of the view is visible at the 9825 * root level. 9826 */ 9827 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 9828 int width = mRight - mLeft; 9829 int height = mBottom - mTop; 9830 if (width > 0 && height > 0) { 9831 r.set(0, 0, width, height); 9832 if (globalOffset != null) { 9833 globalOffset.set(-mScrollX, -mScrollY); 9834 } 9835 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 9836 } 9837 return false; 9838 } 9839 9840 public final boolean getGlobalVisibleRect(Rect r) { 9841 return getGlobalVisibleRect(r, null); 9842 } 9843 9844 public final boolean getLocalVisibleRect(Rect r) { 9845 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 9846 if (getGlobalVisibleRect(r, offset)) { 9847 r.offset(-offset.x, -offset.y); // make r local 9848 return true; 9849 } 9850 return false; 9851 } 9852 9853 /** 9854 * Offset this view's vertical location by the specified number of pixels. 9855 * 9856 * @param offset the number of pixels to offset the view by 9857 */ 9858 public void offsetTopAndBottom(int offset) { 9859 if (offset != 0) { 9860 updateMatrix(); 9861 final boolean matrixIsIdentity = mTransformationInfo == null 9862 || mTransformationInfo.mMatrixIsIdentity; 9863 if (matrixIsIdentity) { 9864 if (mDisplayList != null) { 9865 invalidateViewProperty(false, false); 9866 } else { 9867 final ViewParent p = mParent; 9868 if (p != null && mAttachInfo != null) { 9869 final Rect r = mAttachInfo.mTmpInvalRect; 9870 int minTop; 9871 int maxBottom; 9872 int yLoc; 9873 if (offset < 0) { 9874 minTop = mTop + offset; 9875 maxBottom = mBottom; 9876 yLoc = offset; 9877 } else { 9878 minTop = mTop; 9879 maxBottom = mBottom + offset; 9880 yLoc = 0; 9881 } 9882 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 9883 p.invalidateChild(this, r); 9884 } 9885 } 9886 } else { 9887 invalidateViewProperty(false, false); 9888 } 9889 9890 mTop += offset; 9891 mBottom += offset; 9892 if (mDisplayList != null) { 9893 mDisplayList.offsetTopBottom(offset); 9894 invalidateViewProperty(false, false); 9895 } else { 9896 if (!matrixIsIdentity) { 9897 invalidateViewProperty(false, true); 9898 } 9899 invalidateParentIfNeeded(); 9900 } 9901 } 9902 } 9903 9904 /** 9905 * Offset this view's horizontal location by the specified amount of pixels. 9906 * 9907 * @param offset the numer of pixels to offset the view by 9908 */ 9909 public void offsetLeftAndRight(int offset) { 9910 if (offset != 0) { 9911 updateMatrix(); 9912 final boolean matrixIsIdentity = mTransformationInfo == null 9913 || mTransformationInfo.mMatrixIsIdentity; 9914 if (matrixIsIdentity) { 9915 if (mDisplayList != null) { 9916 invalidateViewProperty(false, false); 9917 } else { 9918 final ViewParent p = mParent; 9919 if (p != null && mAttachInfo != null) { 9920 final Rect r = mAttachInfo.mTmpInvalRect; 9921 int minLeft; 9922 int maxRight; 9923 if (offset < 0) { 9924 minLeft = mLeft + offset; 9925 maxRight = mRight; 9926 } else { 9927 minLeft = mLeft; 9928 maxRight = mRight + offset; 9929 } 9930 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 9931 p.invalidateChild(this, r); 9932 } 9933 } 9934 } else { 9935 invalidateViewProperty(false, false); 9936 } 9937 9938 mLeft += offset; 9939 mRight += offset; 9940 if (mDisplayList != null) { 9941 mDisplayList.offsetLeftRight(offset); 9942 invalidateViewProperty(false, false); 9943 } else { 9944 if (!matrixIsIdentity) { 9945 invalidateViewProperty(false, true); 9946 } 9947 invalidateParentIfNeeded(); 9948 } 9949 } 9950 } 9951 9952 /** 9953 * Get the LayoutParams associated with this view. All views should have 9954 * layout parameters. These supply parameters to the <i>parent</i> of this 9955 * view specifying how it should be arranged. There are many subclasses of 9956 * ViewGroup.LayoutParams, and these correspond to the different subclasses 9957 * of ViewGroup that are responsible for arranging their children. 9958 * 9959 * This method may return null if this View is not attached to a parent 9960 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 9961 * was not invoked successfully. When a View is attached to a parent 9962 * ViewGroup, this method must not return null. 9963 * 9964 * @return The LayoutParams associated with this view, or null if no 9965 * parameters have been set yet 9966 */ 9967 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 9968 public ViewGroup.LayoutParams getLayoutParams() { 9969 return mLayoutParams; 9970 } 9971 9972 /** 9973 * Set the layout parameters associated with this view. These supply 9974 * parameters to the <i>parent</i> of this view specifying how it should be 9975 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 9976 * correspond to the different subclasses of ViewGroup that are responsible 9977 * for arranging their children. 9978 * 9979 * @param params The layout parameters for this view, cannot be null 9980 */ 9981 public void setLayoutParams(ViewGroup.LayoutParams params) { 9982 if (params == null) { 9983 throw new NullPointerException("Layout parameters cannot be null"); 9984 } 9985 mLayoutParams = params; 9986 resolveLayoutParams(); 9987 if (mParent instanceof ViewGroup) { 9988 ((ViewGroup) mParent).onSetLayoutParams(this, params); 9989 } 9990 requestLayout(); 9991 } 9992 9993 /** 9994 * Resolve the layout parameters depending on the resolved layout direction 9995 */ 9996 private void resolveLayoutParams() { 9997 if (mLayoutParams != null) { 9998 mLayoutParams.onResolveLayoutDirection(getLayoutDirection()); 9999 } 10000 } 10001 10002 /** 10003 * Set the scrolled position of your view. This will cause a call to 10004 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10005 * invalidated. 10006 * @param x the x position to scroll to 10007 * @param y the y position to scroll to 10008 */ 10009 public void scrollTo(int x, int y) { 10010 if (mScrollX != x || mScrollY != y) { 10011 int oldX = mScrollX; 10012 int oldY = mScrollY; 10013 mScrollX = x; 10014 mScrollY = y; 10015 invalidateParentCaches(); 10016 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 10017 if (!awakenScrollBars()) { 10018 postInvalidateOnAnimation(); 10019 } 10020 } 10021 } 10022 10023 /** 10024 * Move the scrolled position of your view. This will cause a call to 10025 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10026 * invalidated. 10027 * @param x the amount of pixels to scroll by horizontally 10028 * @param y the amount of pixels to scroll by vertically 10029 */ 10030 public void scrollBy(int x, int y) { 10031 scrollTo(mScrollX + x, mScrollY + y); 10032 } 10033 10034 /** 10035 * <p>Trigger the scrollbars to draw. When invoked this method starts an 10036 * animation to fade the scrollbars out after a default delay. If a subclass 10037 * provides animated scrolling, the start delay should equal the duration 10038 * of the scrolling animation.</p> 10039 * 10040 * <p>The animation starts only if at least one of the scrollbars is 10041 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 10042 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10043 * this method returns true, and false otherwise. If the animation is 10044 * started, this method calls {@link #invalidate()}; in that case the 10045 * caller should not call {@link #invalidate()}.</p> 10046 * 10047 * <p>This method should be invoked every time a subclass directly updates 10048 * the scroll parameters.</p> 10049 * 10050 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 10051 * and {@link #scrollTo(int, int)}.</p> 10052 * 10053 * @return true if the animation is played, false otherwise 10054 * 10055 * @see #awakenScrollBars(int) 10056 * @see #scrollBy(int, int) 10057 * @see #scrollTo(int, int) 10058 * @see #isHorizontalScrollBarEnabled() 10059 * @see #isVerticalScrollBarEnabled() 10060 * @see #setHorizontalScrollBarEnabled(boolean) 10061 * @see #setVerticalScrollBarEnabled(boolean) 10062 */ 10063 protected boolean awakenScrollBars() { 10064 return mScrollCache != null && 10065 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 10066 } 10067 10068 /** 10069 * Trigger the scrollbars to draw. 10070 * This method differs from awakenScrollBars() only in its default duration. 10071 * initialAwakenScrollBars() will show the scroll bars for longer than 10072 * usual to give the user more of a chance to notice them. 10073 * 10074 * @return true if the animation is played, false otherwise. 10075 */ 10076 private boolean initialAwakenScrollBars() { 10077 return mScrollCache != null && 10078 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 10079 } 10080 10081 /** 10082 * <p> 10083 * Trigger the scrollbars to draw. When invoked this method starts an 10084 * animation to fade the scrollbars out after a fixed delay. If a subclass 10085 * provides animated scrolling, the start delay should equal the duration of 10086 * the scrolling animation. 10087 * </p> 10088 * 10089 * <p> 10090 * The animation starts only if at least one of the scrollbars is enabled, 10091 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10092 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10093 * this method returns true, and false otherwise. If the animation is 10094 * started, this method calls {@link #invalidate()}; in that case the caller 10095 * should not call {@link #invalidate()}. 10096 * </p> 10097 * 10098 * <p> 10099 * This method should be invoked everytime a subclass directly updates the 10100 * scroll parameters. 10101 * </p> 10102 * 10103 * @param startDelay the delay, in milliseconds, after which the animation 10104 * should start; when the delay is 0, the animation starts 10105 * immediately 10106 * @return true if the animation is played, false otherwise 10107 * 10108 * @see #scrollBy(int, int) 10109 * @see #scrollTo(int, int) 10110 * @see #isHorizontalScrollBarEnabled() 10111 * @see #isVerticalScrollBarEnabled() 10112 * @see #setHorizontalScrollBarEnabled(boolean) 10113 * @see #setVerticalScrollBarEnabled(boolean) 10114 */ 10115 protected boolean awakenScrollBars(int startDelay) { 10116 return awakenScrollBars(startDelay, true); 10117 } 10118 10119 /** 10120 * <p> 10121 * Trigger the scrollbars to draw. When invoked this method starts an 10122 * animation to fade the scrollbars out after a fixed delay. If a subclass 10123 * provides animated scrolling, the start delay should equal the duration of 10124 * the scrolling animation. 10125 * </p> 10126 * 10127 * <p> 10128 * The animation starts only if at least one of the scrollbars is enabled, 10129 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10130 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10131 * this method returns true, and false otherwise. If the animation is 10132 * started, this method calls {@link #invalidate()} if the invalidate parameter 10133 * is set to true; in that case the caller 10134 * should not call {@link #invalidate()}. 10135 * </p> 10136 * 10137 * <p> 10138 * This method should be invoked everytime a subclass directly updates the 10139 * scroll parameters. 10140 * </p> 10141 * 10142 * @param startDelay the delay, in milliseconds, after which the animation 10143 * should start; when the delay is 0, the animation starts 10144 * immediately 10145 * 10146 * @param invalidate Wheter this method should call invalidate 10147 * 10148 * @return true if the animation is played, false otherwise 10149 * 10150 * @see #scrollBy(int, int) 10151 * @see #scrollTo(int, int) 10152 * @see #isHorizontalScrollBarEnabled() 10153 * @see #isVerticalScrollBarEnabled() 10154 * @see #setHorizontalScrollBarEnabled(boolean) 10155 * @see #setVerticalScrollBarEnabled(boolean) 10156 */ 10157 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 10158 final ScrollabilityCache scrollCache = mScrollCache; 10159 10160 if (scrollCache == null || !scrollCache.fadeScrollBars) { 10161 return false; 10162 } 10163 10164 if (scrollCache.scrollBar == null) { 10165 scrollCache.scrollBar = new ScrollBarDrawable(); 10166 } 10167 10168 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 10169 10170 if (invalidate) { 10171 // Invalidate to show the scrollbars 10172 postInvalidateOnAnimation(); 10173 } 10174 10175 if (scrollCache.state == ScrollabilityCache.OFF) { 10176 // FIXME: this is copied from WindowManagerService. 10177 // We should get this value from the system when it 10178 // is possible to do so. 10179 final int KEY_REPEAT_FIRST_DELAY = 750; 10180 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 10181 } 10182 10183 // Tell mScrollCache when we should start fading. This may 10184 // extend the fade start time if one was already scheduled 10185 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 10186 scrollCache.fadeStartTime = fadeStartTime; 10187 scrollCache.state = ScrollabilityCache.ON; 10188 10189 // Schedule our fader to run, unscheduling any old ones first 10190 if (mAttachInfo != null) { 10191 mAttachInfo.mHandler.removeCallbacks(scrollCache); 10192 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 10193 } 10194 10195 return true; 10196 } 10197 10198 return false; 10199 } 10200 10201 /** 10202 * Do not invalidate views which are not visible and which are not running an animation. They 10203 * will not get drawn and they should not set dirty flags as if they will be drawn 10204 */ 10205 private boolean skipInvalidate() { 10206 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 10207 (!(mParent instanceof ViewGroup) || 10208 !((ViewGroup) mParent).isViewTransitioning(this)); 10209 } 10210 /** 10211 * Mark the area defined by dirty as needing to be drawn. If the view is 10212 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 10213 * in the future. This must be called from a UI thread. To call from a non-UI 10214 * thread, call {@link #postInvalidate()}. 10215 * 10216 * WARNING: This method is destructive to dirty. 10217 * @param dirty the rectangle representing the bounds of the dirty region 10218 */ 10219 public void invalidate(Rect dirty) { 10220 if (skipInvalidate()) { 10221 return; 10222 } 10223 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10224 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10225 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10226 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10227 mPrivateFlags |= PFLAG_INVALIDATED; 10228 mPrivateFlags |= PFLAG_DIRTY; 10229 final ViewParent p = mParent; 10230 final AttachInfo ai = mAttachInfo; 10231 //noinspection PointlessBooleanExpression,ConstantConditions 10232 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10233 if (p != null && ai != null && ai.mHardwareAccelerated) { 10234 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10235 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10236 p.invalidateChild(this, null); 10237 return; 10238 } 10239 } 10240 if (p != null && ai != null) { 10241 final int scrollX = mScrollX; 10242 final int scrollY = mScrollY; 10243 final Rect r = ai.mTmpInvalRect; 10244 r.set(dirty.left - scrollX, dirty.top - scrollY, 10245 dirty.right - scrollX, dirty.bottom - scrollY); 10246 mParent.invalidateChild(this, r); 10247 } 10248 } 10249 } 10250 10251 /** 10252 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 10253 * The coordinates of the dirty rect are relative to the view. 10254 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 10255 * will be called at some point in the future. This must be called from 10256 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 10257 * @param l the left position of the dirty region 10258 * @param t the top position of the dirty region 10259 * @param r the right position of the dirty region 10260 * @param b the bottom position of the dirty region 10261 */ 10262 public void invalidate(int l, int t, int r, int b) { 10263 if (skipInvalidate()) { 10264 return; 10265 } 10266 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10267 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10268 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10269 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10270 mPrivateFlags |= PFLAG_INVALIDATED; 10271 mPrivateFlags |= PFLAG_DIRTY; 10272 final ViewParent p = mParent; 10273 final AttachInfo ai = mAttachInfo; 10274 //noinspection PointlessBooleanExpression,ConstantConditions 10275 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10276 if (p != null && ai != null && ai.mHardwareAccelerated) { 10277 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10278 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10279 p.invalidateChild(this, null); 10280 return; 10281 } 10282 } 10283 if (p != null && ai != null && l < r && t < b) { 10284 final int scrollX = mScrollX; 10285 final int scrollY = mScrollY; 10286 final Rect tmpr = ai.mTmpInvalRect; 10287 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 10288 p.invalidateChild(this, tmpr); 10289 } 10290 } 10291 } 10292 10293 /** 10294 * Invalidate the whole view. If the view is visible, 10295 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 10296 * the future. This must be called from a UI thread. To call from a non-UI thread, 10297 * call {@link #postInvalidate()}. 10298 */ 10299 public void invalidate() { 10300 invalidate(true); 10301 } 10302 10303 /** 10304 * This is where the invalidate() work actually happens. A full invalidate() 10305 * causes the drawing cache to be invalidated, but this function can be called with 10306 * invalidateCache set to false to skip that invalidation step for cases that do not 10307 * need it (for example, a component that remains at the same dimensions with the same 10308 * content). 10309 * 10310 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 10311 * well. This is usually true for a full invalidate, but may be set to false if the 10312 * View's contents or dimensions have not changed. 10313 */ 10314 void invalidate(boolean invalidateCache) { 10315 if (skipInvalidate()) { 10316 return; 10317 } 10318 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10319 (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) || 10320 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) { 10321 mLastIsOpaque = isOpaque(); 10322 mPrivateFlags &= ~PFLAG_DRAWN; 10323 mPrivateFlags |= PFLAG_DIRTY; 10324 if (invalidateCache) { 10325 mPrivateFlags |= PFLAG_INVALIDATED; 10326 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10327 } 10328 final AttachInfo ai = mAttachInfo; 10329 final ViewParent p = mParent; 10330 //noinspection PointlessBooleanExpression,ConstantConditions 10331 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10332 if (p != null && ai != null && ai.mHardwareAccelerated) { 10333 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10334 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10335 p.invalidateChild(this, null); 10336 return; 10337 } 10338 } 10339 10340 if (p != null && ai != null) { 10341 final Rect r = ai.mTmpInvalRect; 10342 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10343 // Don't call invalidate -- we don't want to internally scroll 10344 // our own bounds 10345 p.invalidateChild(this, r); 10346 } 10347 } 10348 } 10349 10350 /** 10351 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 10352 * set any flags or handle all of the cases handled by the default invalidation methods. 10353 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 10354 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 10355 * walk up the hierarchy, transforming the dirty rect as necessary. 10356 * 10357 * The method also handles normal invalidation logic if display list properties are not 10358 * being used in this view. The invalidateParent and forceRedraw flags are used by that 10359 * backup approach, to handle these cases used in the various property-setting methods. 10360 * 10361 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 10362 * are not being used in this view 10363 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 10364 * list properties are not being used in this view 10365 */ 10366 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 10367 if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) { 10368 if (invalidateParent) { 10369 invalidateParentCaches(); 10370 } 10371 if (forceRedraw) { 10372 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10373 } 10374 invalidate(false); 10375 } else { 10376 final AttachInfo ai = mAttachInfo; 10377 final ViewParent p = mParent; 10378 if (p != null && ai != null) { 10379 final Rect r = ai.mTmpInvalRect; 10380 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10381 if (mParent instanceof ViewGroup) { 10382 ((ViewGroup) mParent).invalidateChildFast(this, r); 10383 } else { 10384 mParent.invalidateChild(this, r); 10385 } 10386 } 10387 } 10388 } 10389 10390 /** 10391 * Utility method to transform a given Rect by the current matrix of this view. 10392 */ 10393 void transformRect(final Rect rect) { 10394 if (!getMatrix().isIdentity()) { 10395 RectF boundingRect = mAttachInfo.mTmpTransformRect; 10396 boundingRect.set(rect); 10397 getMatrix().mapRect(boundingRect); 10398 rect.set((int) (boundingRect.left - 0.5f), 10399 (int) (boundingRect.top - 0.5f), 10400 (int) (boundingRect.right + 0.5f), 10401 (int) (boundingRect.bottom + 0.5f)); 10402 } 10403 } 10404 10405 /** 10406 * Used to indicate that the parent of this view should clear its caches. This functionality 10407 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10408 * which is necessary when various parent-managed properties of the view change, such as 10409 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 10410 * clears the parent caches and does not causes an invalidate event. 10411 * 10412 * @hide 10413 */ 10414 protected void invalidateParentCaches() { 10415 if (mParent instanceof View) { 10416 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 10417 } 10418 } 10419 10420 /** 10421 * Used to indicate that the parent of this view should be invalidated. This functionality 10422 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10423 * which is necessary when various parent-managed properties of the view change, such as 10424 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 10425 * an invalidation event to the parent. 10426 * 10427 * @hide 10428 */ 10429 protected void invalidateParentIfNeeded() { 10430 if (isHardwareAccelerated() && mParent instanceof View) { 10431 ((View) mParent).invalidate(true); 10432 } 10433 } 10434 10435 /** 10436 * Indicates whether this View is opaque. An opaque View guarantees that it will 10437 * draw all the pixels overlapping its bounds using a fully opaque color. 10438 * 10439 * Subclasses of View should override this method whenever possible to indicate 10440 * whether an instance is opaque. Opaque Views are treated in a special way by 10441 * the View hierarchy, possibly allowing it to perform optimizations during 10442 * invalidate/draw passes. 10443 * 10444 * @return True if this View is guaranteed to be fully opaque, false otherwise. 10445 */ 10446 @ViewDebug.ExportedProperty(category = "drawing") 10447 public boolean isOpaque() { 10448 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 10449 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f); 10450 } 10451 10452 /** 10453 * @hide 10454 */ 10455 protected void computeOpaqueFlags() { 10456 // Opaque if: 10457 // - Has a background 10458 // - Background is opaque 10459 // - Doesn't have scrollbars or scrollbars are inside overlay 10460 10461 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 10462 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 10463 } else { 10464 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 10465 } 10466 10467 final int flags = mViewFlags; 10468 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 10469 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 10470 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 10471 } else { 10472 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 10473 } 10474 } 10475 10476 /** 10477 * @hide 10478 */ 10479 protected boolean hasOpaqueScrollbars() { 10480 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 10481 } 10482 10483 /** 10484 * @return A handler associated with the thread running the View. This 10485 * handler can be used to pump events in the UI events queue. 10486 */ 10487 public Handler getHandler() { 10488 if (mAttachInfo != null) { 10489 return mAttachInfo.mHandler; 10490 } 10491 return null; 10492 } 10493 10494 /** 10495 * Gets the view root associated with the View. 10496 * @return The view root, or null if none. 10497 * @hide 10498 */ 10499 public ViewRootImpl getViewRootImpl() { 10500 if (mAttachInfo != null) { 10501 return mAttachInfo.mViewRootImpl; 10502 } 10503 return null; 10504 } 10505 10506 /** 10507 * <p>Causes the Runnable to be added to the message queue. 10508 * The runnable will be run on the user interface thread.</p> 10509 * 10510 * <p>This method can be invoked from outside of the UI thread 10511 * only when this View is attached to a window.</p> 10512 * 10513 * @param action The Runnable that will be executed. 10514 * 10515 * @return Returns true if the Runnable was successfully placed in to the 10516 * message queue. Returns false on failure, usually because the 10517 * looper processing the message queue is exiting. 10518 * 10519 * @see #postDelayed 10520 * @see #removeCallbacks 10521 */ 10522 public boolean post(Runnable action) { 10523 final AttachInfo attachInfo = mAttachInfo; 10524 if (attachInfo != null) { 10525 return attachInfo.mHandler.post(action); 10526 } 10527 // Assume that post will succeed later 10528 ViewRootImpl.getRunQueue().post(action); 10529 return true; 10530 } 10531 10532 /** 10533 * <p>Causes the Runnable to be added to the message queue, to be run 10534 * after the specified amount of time elapses. 10535 * The runnable will be run on the user interface thread.</p> 10536 * 10537 * <p>This method can be invoked from outside of the UI thread 10538 * only when this View is attached to a window.</p> 10539 * 10540 * @param action The Runnable that will be executed. 10541 * @param delayMillis The delay (in milliseconds) until the Runnable 10542 * will be executed. 10543 * 10544 * @return true if the Runnable was successfully placed in to the 10545 * message queue. Returns false on failure, usually because the 10546 * looper processing the message queue is exiting. Note that a 10547 * result of true does not mean the Runnable will be processed -- 10548 * if the looper is quit before the delivery time of the message 10549 * occurs then the message will be dropped. 10550 * 10551 * @see #post 10552 * @see #removeCallbacks 10553 */ 10554 public boolean postDelayed(Runnable action, long delayMillis) { 10555 final AttachInfo attachInfo = mAttachInfo; 10556 if (attachInfo != null) { 10557 return attachInfo.mHandler.postDelayed(action, delayMillis); 10558 } 10559 // Assume that post will succeed later 10560 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10561 return true; 10562 } 10563 10564 /** 10565 * <p>Causes the Runnable to execute on the next animation time step. 10566 * The runnable will be run on the user interface thread.</p> 10567 * 10568 * <p>This method can be invoked from outside of the UI thread 10569 * only when this View is attached to a window.</p> 10570 * 10571 * @param action The Runnable that will be executed. 10572 * 10573 * @see #postOnAnimationDelayed 10574 * @see #removeCallbacks 10575 */ 10576 public void postOnAnimation(Runnable action) { 10577 final AttachInfo attachInfo = mAttachInfo; 10578 if (attachInfo != null) { 10579 attachInfo.mViewRootImpl.mChoreographer.postCallback( 10580 Choreographer.CALLBACK_ANIMATION, action, null); 10581 } else { 10582 // Assume that post will succeed later 10583 ViewRootImpl.getRunQueue().post(action); 10584 } 10585 } 10586 10587 /** 10588 * <p>Causes the Runnable to execute on the next animation time step, 10589 * after the specified amount of time elapses. 10590 * The runnable will be run on the user interface thread.</p> 10591 * 10592 * <p>This method can be invoked from outside of the UI thread 10593 * only when this View is attached to a window.</p> 10594 * 10595 * @param action The Runnable that will be executed. 10596 * @param delayMillis The delay (in milliseconds) until the Runnable 10597 * will be executed. 10598 * 10599 * @see #postOnAnimation 10600 * @see #removeCallbacks 10601 */ 10602 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 10603 final AttachInfo attachInfo = mAttachInfo; 10604 if (attachInfo != null) { 10605 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 10606 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 10607 } else { 10608 // Assume that post will succeed later 10609 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10610 } 10611 } 10612 10613 /** 10614 * <p>Removes the specified Runnable from the message queue.</p> 10615 * 10616 * <p>This method can be invoked from outside of the UI thread 10617 * only when this View is attached to a window.</p> 10618 * 10619 * @param action The Runnable to remove from the message handling queue 10620 * 10621 * @return true if this view could ask the Handler to remove the Runnable, 10622 * false otherwise. When the returned value is true, the Runnable 10623 * may or may not have been actually removed from the message queue 10624 * (for instance, if the Runnable was not in the queue already.) 10625 * 10626 * @see #post 10627 * @see #postDelayed 10628 * @see #postOnAnimation 10629 * @see #postOnAnimationDelayed 10630 */ 10631 public boolean removeCallbacks(Runnable action) { 10632 if (action != null) { 10633 final AttachInfo attachInfo = mAttachInfo; 10634 if (attachInfo != null) { 10635 attachInfo.mHandler.removeCallbacks(action); 10636 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 10637 Choreographer.CALLBACK_ANIMATION, action, null); 10638 } else { 10639 // Assume that post will succeed later 10640 ViewRootImpl.getRunQueue().removeCallbacks(action); 10641 } 10642 } 10643 return true; 10644 } 10645 10646 /** 10647 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 10648 * Use this to invalidate the View from a non-UI thread.</p> 10649 * 10650 * <p>This method can be invoked from outside of the UI thread 10651 * only when this View is attached to a window.</p> 10652 * 10653 * @see #invalidate() 10654 * @see #postInvalidateDelayed(long) 10655 */ 10656 public void postInvalidate() { 10657 postInvalidateDelayed(0); 10658 } 10659 10660 /** 10661 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10662 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 10663 * 10664 * <p>This method can be invoked from outside of the UI thread 10665 * only when this View is attached to a window.</p> 10666 * 10667 * @param left The left coordinate of the rectangle to invalidate. 10668 * @param top The top coordinate of the rectangle to invalidate. 10669 * @param right The right coordinate of the rectangle to invalidate. 10670 * @param bottom The bottom coordinate of the rectangle to invalidate. 10671 * 10672 * @see #invalidate(int, int, int, int) 10673 * @see #invalidate(Rect) 10674 * @see #postInvalidateDelayed(long, int, int, int, int) 10675 */ 10676 public void postInvalidate(int left, int top, int right, int bottom) { 10677 postInvalidateDelayed(0, left, top, right, bottom); 10678 } 10679 10680 /** 10681 * <p>Cause an invalidate to happen on a subsequent cycle through the event 10682 * loop. Waits for the specified amount of time.</p> 10683 * 10684 * <p>This method can be invoked from outside of the UI thread 10685 * only when this View is attached to a window.</p> 10686 * 10687 * @param delayMilliseconds the duration in milliseconds to delay the 10688 * invalidation by 10689 * 10690 * @see #invalidate() 10691 * @see #postInvalidate() 10692 */ 10693 public void postInvalidateDelayed(long delayMilliseconds) { 10694 // We try only with the AttachInfo because there's no point in invalidating 10695 // if we are not attached to our window 10696 final AttachInfo attachInfo = mAttachInfo; 10697 if (attachInfo != null) { 10698 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 10699 } 10700 } 10701 10702 /** 10703 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10704 * through the event loop. Waits for the specified amount of time.</p> 10705 * 10706 * <p>This method can be invoked from outside of the UI thread 10707 * only when this View is attached to a window.</p> 10708 * 10709 * @param delayMilliseconds the duration in milliseconds to delay the 10710 * invalidation by 10711 * @param left The left coordinate of the rectangle to invalidate. 10712 * @param top The top coordinate of the rectangle to invalidate. 10713 * @param right The right coordinate of the rectangle to invalidate. 10714 * @param bottom The bottom coordinate of the rectangle to invalidate. 10715 * 10716 * @see #invalidate(int, int, int, int) 10717 * @see #invalidate(Rect) 10718 * @see #postInvalidate(int, int, int, int) 10719 */ 10720 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 10721 int right, int bottom) { 10722 10723 // We try only with the AttachInfo because there's no point in invalidating 10724 // if we are not attached to our window 10725 final AttachInfo attachInfo = mAttachInfo; 10726 if (attachInfo != null) { 10727 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 10728 info.target = this; 10729 info.left = left; 10730 info.top = top; 10731 info.right = right; 10732 info.bottom = bottom; 10733 10734 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 10735 } 10736 } 10737 10738 /** 10739 * <p>Cause an invalidate to happen on the next animation time step, typically the 10740 * next display frame.</p> 10741 * 10742 * <p>This method can be invoked from outside of the UI thread 10743 * only when this View is attached to a window.</p> 10744 * 10745 * @see #invalidate() 10746 */ 10747 public void postInvalidateOnAnimation() { 10748 // We try only with the AttachInfo because there's no point in invalidating 10749 // if we are not attached to our window 10750 final AttachInfo attachInfo = mAttachInfo; 10751 if (attachInfo != null) { 10752 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 10753 } 10754 } 10755 10756 /** 10757 * <p>Cause an invalidate of the specified area to happen on the next animation 10758 * time step, typically the next display frame.</p> 10759 * 10760 * <p>This method can be invoked from outside of the UI thread 10761 * only when this View is attached to a window.</p> 10762 * 10763 * @param left The left coordinate of the rectangle to invalidate. 10764 * @param top The top coordinate of the rectangle to invalidate. 10765 * @param right The right coordinate of the rectangle to invalidate. 10766 * @param bottom The bottom coordinate of the rectangle to invalidate. 10767 * 10768 * @see #invalidate(int, int, int, int) 10769 * @see #invalidate(Rect) 10770 */ 10771 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 10772 // We try only with the AttachInfo because there's no point in invalidating 10773 // if we are not attached to our window 10774 final AttachInfo attachInfo = mAttachInfo; 10775 if (attachInfo != null) { 10776 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 10777 info.target = this; 10778 info.left = left; 10779 info.top = top; 10780 info.right = right; 10781 info.bottom = bottom; 10782 10783 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 10784 } 10785 } 10786 10787 /** 10788 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 10789 * This event is sent at most once every 10790 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 10791 */ 10792 private void postSendViewScrolledAccessibilityEventCallback() { 10793 if (mSendViewScrolledAccessibilityEvent == null) { 10794 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 10795 } 10796 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 10797 mSendViewScrolledAccessibilityEvent.mIsPending = true; 10798 postDelayed(mSendViewScrolledAccessibilityEvent, 10799 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 10800 } 10801 } 10802 10803 /** 10804 * Called by a parent to request that a child update its values for mScrollX 10805 * and mScrollY if necessary. This will typically be done if the child is 10806 * animating a scroll using a {@link android.widget.Scroller Scroller} 10807 * object. 10808 */ 10809 public void computeScroll() { 10810 } 10811 10812 /** 10813 * <p>Indicate whether the horizontal edges are faded when the view is 10814 * scrolled horizontally.</p> 10815 * 10816 * @return true if the horizontal edges should are faded on scroll, false 10817 * otherwise 10818 * 10819 * @see #setHorizontalFadingEdgeEnabled(boolean) 10820 * 10821 * @attr ref android.R.styleable#View_requiresFadingEdge 10822 */ 10823 public boolean isHorizontalFadingEdgeEnabled() { 10824 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 10825 } 10826 10827 /** 10828 * <p>Define whether the horizontal edges should be faded when this view 10829 * is scrolled horizontally.</p> 10830 * 10831 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 10832 * be faded when the view is scrolled 10833 * horizontally 10834 * 10835 * @see #isHorizontalFadingEdgeEnabled() 10836 * 10837 * @attr ref android.R.styleable#View_requiresFadingEdge 10838 */ 10839 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 10840 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 10841 if (horizontalFadingEdgeEnabled) { 10842 initScrollCache(); 10843 } 10844 10845 mViewFlags ^= FADING_EDGE_HORIZONTAL; 10846 } 10847 } 10848 10849 /** 10850 * <p>Indicate whether the vertical edges are faded when the view is 10851 * scrolled horizontally.</p> 10852 * 10853 * @return true if the vertical edges should are faded on scroll, false 10854 * otherwise 10855 * 10856 * @see #setVerticalFadingEdgeEnabled(boolean) 10857 * 10858 * @attr ref android.R.styleable#View_requiresFadingEdge 10859 */ 10860 public boolean isVerticalFadingEdgeEnabled() { 10861 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 10862 } 10863 10864 /** 10865 * <p>Define whether the vertical edges should be faded when this view 10866 * is scrolled vertically.</p> 10867 * 10868 * @param verticalFadingEdgeEnabled true if the vertical edges should 10869 * be faded when the view is scrolled 10870 * vertically 10871 * 10872 * @see #isVerticalFadingEdgeEnabled() 10873 * 10874 * @attr ref android.R.styleable#View_requiresFadingEdge 10875 */ 10876 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 10877 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 10878 if (verticalFadingEdgeEnabled) { 10879 initScrollCache(); 10880 } 10881 10882 mViewFlags ^= FADING_EDGE_VERTICAL; 10883 } 10884 } 10885 10886 /** 10887 * Returns the strength, or intensity, of the top faded edge. The strength is 10888 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10889 * returns 0.0 or 1.0 but no value in between. 10890 * 10891 * Subclasses should override this method to provide a smoother fade transition 10892 * when scrolling occurs. 10893 * 10894 * @return the intensity of the top fade as a float between 0.0f and 1.0f 10895 */ 10896 protected float getTopFadingEdgeStrength() { 10897 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 10898 } 10899 10900 /** 10901 * Returns the strength, or intensity, of the bottom faded edge. The strength is 10902 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10903 * returns 0.0 or 1.0 but no value in between. 10904 * 10905 * Subclasses should override this method to provide a smoother fade transition 10906 * when scrolling occurs. 10907 * 10908 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 10909 */ 10910 protected float getBottomFadingEdgeStrength() { 10911 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 10912 computeVerticalScrollRange() ? 1.0f : 0.0f; 10913 } 10914 10915 /** 10916 * Returns the strength, or intensity, of the left faded edge. The strength is 10917 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10918 * returns 0.0 or 1.0 but no value in between. 10919 * 10920 * Subclasses should override this method to provide a smoother fade transition 10921 * when scrolling occurs. 10922 * 10923 * @return the intensity of the left fade as a float between 0.0f and 1.0f 10924 */ 10925 protected float getLeftFadingEdgeStrength() { 10926 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 10927 } 10928 10929 /** 10930 * Returns the strength, or intensity, of the right faded edge. The strength is 10931 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10932 * returns 0.0 or 1.0 but no value in between. 10933 * 10934 * Subclasses should override this method to provide a smoother fade transition 10935 * when scrolling occurs. 10936 * 10937 * @return the intensity of the right fade as a float between 0.0f and 1.0f 10938 */ 10939 protected float getRightFadingEdgeStrength() { 10940 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 10941 computeHorizontalScrollRange() ? 1.0f : 0.0f; 10942 } 10943 10944 /** 10945 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 10946 * scrollbar is not drawn by default.</p> 10947 * 10948 * @return true if the horizontal scrollbar should be painted, false 10949 * otherwise 10950 * 10951 * @see #setHorizontalScrollBarEnabled(boolean) 10952 */ 10953 public boolean isHorizontalScrollBarEnabled() { 10954 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 10955 } 10956 10957 /** 10958 * <p>Define whether the horizontal scrollbar should be drawn or not. The 10959 * scrollbar is not drawn by default.</p> 10960 * 10961 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 10962 * be painted 10963 * 10964 * @see #isHorizontalScrollBarEnabled() 10965 */ 10966 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 10967 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 10968 mViewFlags ^= SCROLLBARS_HORIZONTAL; 10969 computeOpaqueFlags(); 10970 resolvePadding(); 10971 } 10972 } 10973 10974 /** 10975 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 10976 * scrollbar is not drawn by default.</p> 10977 * 10978 * @return true if the vertical scrollbar should be painted, false 10979 * otherwise 10980 * 10981 * @see #setVerticalScrollBarEnabled(boolean) 10982 */ 10983 public boolean isVerticalScrollBarEnabled() { 10984 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 10985 } 10986 10987 /** 10988 * <p>Define whether the vertical scrollbar should be drawn or not. The 10989 * scrollbar is not drawn by default.</p> 10990 * 10991 * @param verticalScrollBarEnabled true if the vertical scrollbar should 10992 * be painted 10993 * 10994 * @see #isVerticalScrollBarEnabled() 10995 */ 10996 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 10997 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 10998 mViewFlags ^= SCROLLBARS_VERTICAL; 10999 computeOpaqueFlags(); 11000 resolvePadding(); 11001 } 11002 } 11003 11004 /** 11005 * @hide 11006 */ 11007 protected void recomputePadding() { 11008 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 11009 } 11010 11011 /** 11012 * Define whether scrollbars will fade when the view is not scrolling. 11013 * 11014 * @param fadeScrollbars wheter to enable fading 11015 * 11016 * @attr ref android.R.styleable#View_fadeScrollbars 11017 */ 11018 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 11019 initScrollCache(); 11020 final ScrollabilityCache scrollabilityCache = mScrollCache; 11021 scrollabilityCache.fadeScrollBars = fadeScrollbars; 11022 if (fadeScrollbars) { 11023 scrollabilityCache.state = ScrollabilityCache.OFF; 11024 } else { 11025 scrollabilityCache.state = ScrollabilityCache.ON; 11026 } 11027 } 11028 11029 /** 11030 * 11031 * Returns true if scrollbars will fade when this view is not scrolling 11032 * 11033 * @return true if scrollbar fading is enabled 11034 * 11035 * @attr ref android.R.styleable#View_fadeScrollbars 11036 */ 11037 public boolean isScrollbarFadingEnabled() { 11038 return mScrollCache != null && mScrollCache.fadeScrollBars; 11039 } 11040 11041 /** 11042 * 11043 * Returns the delay before scrollbars fade. 11044 * 11045 * @return the delay before scrollbars fade 11046 * 11047 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11048 */ 11049 public int getScrollBarDefaultDelayBeforeFade() { 11050 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 11051 mScrollCache.scrollBarDefaultDelayBeforeFade; 11052 } 11053 11054 /** 11055 * Define the delay before scrollbars fade. 11056 * 11057 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 11058 * 11059 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11060 */ 11061 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 11062 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 11063 } 11064 11065 /** 11066 * 11067 * Returns the scrollbar fade duration. 11068 * 11069 * @return the scrollbar fade duration 11070 * 11071 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11072 */ 11073 public int getScrollBarFadeDuration() { 11074 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 11075 mScrollCache.scrollBarFadeDuration; 11076 } 11077 11078 /** 11079 * Define the scrollbar fade duration. 11080 * 11081 * @param scrollBarFadeDuration - the scrollbar fade duration 11082 * 11083 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11084 */ 11085 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 11086 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 11087 } 11088 11089 /** 11090 * 11091 * Returns the scrollbar size. 11092 * 11093 * @return the scrollbar size 11094 * 11095 * @attr ref android.R.styleable#View_scrollbarSize 11096 */ 11097 public int getScrollBarSize() { 11098 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 11099 mScrollCache.scrollBarSize; 11100 } 11101 11102 /** 11103 * Define the scrollbar size. 11104 * 11105 * @param scrollBarSize - the scrollbar size 11106 * 11107 * @attr ref android.R.styleable#View_scrollbarSize 11108 */ 11109 public void setScrollBarSize(int scrollBarSize) { 11110 getScrollCache().scrollBarSize = scrollBarSize; 11111 } 11112 11113 /** 11114 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 11115 * inset. When inset, they add to the padding of the view. And the scrollbars 11116 * can be drawn inside the padding area or on the edge of the view. For example, 11117 * if a view has a background drawable and you want to draw the scrollbars 11118 * inside the padding specified by the drawable, you can use 11119 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 11120 * appear at the edge of the view, ignoring the padding, then you can use 11121 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 11122 * @param style the style of the scrollbars. Should be one of 11123 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 11124 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 11125 * @see #SCROLLBARS_INSIDE_OVERLAY 11126 * @see #SCROLLBARS_INSIDE_INSET 11127 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11128 * @see #SCROLLBARS_OUTSIDE_INSET 11129 * 11130 * @attr ref android.R.styleable#View_scrollbarStyle 11131 */ 11132 public void setScrollBarStyle(int style) { 11133 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 11134 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 11135 computeOpaqueFlags(); 11136 resolvePadding(); 11137 } 11138 } 11139 11140 /** 11141 * <p>Returns the current scrollbar style.</p> 11142 * @return the current scrollbar style 11143 * @see #SCROLLBARS_INSIDE_OVERLAY 11144 * @see #SCROLLBARS_INSIDE_INSET 11145 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11146 * @see #SCROLLBARS_OUTSIDE_INSET 11147 * 11148 * @attr ref android.R.styleable#View_scrollbarStyle 11149 */ 11150 @ViewDebug.ExportedProperty(mapping = { 11151 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 11152 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 11153 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 11154 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 11155 }) 11156 public int getScrollBarStyle() { 11157 return mViewFlags & SCROLLBARS_STYLE_MASK; 11158 } 11159 11160 /** 11161 * <p>Compute the horizontal range that the horizontal scrollbar 11162 * represents.</p> 11163 * 11164 * <p>The range is expressed in arbitrary units that must be the same as the 11165 * units used by {@link #computeHorizontalScrollExtent()} and 11166 * {@link #computeHorizontalScrollOffset()}.</p> 11167 * 11168 * <p>The default range is the drawing width of this view.</p> 11169 * 11170 * @return the total horizontal range represented by the horizontal 11171 * scrollbar 11172 * 11173 * @see #computeHorizontalScrollExtent() 11174 * @see #computeHorizontalScrollOffset() 11175 * @see android.widget.ScrollBarDrawable 11176 */ 11177 protected int computeHorizontalScrollRange() { 11178 return getWidth(); 11179 } 11180 11181 /** 11182 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 11183 * within the horizontal range. This value is used to compute the position 11184 * of the thumb within the scrollbar's track.</p> 11185 * 11186 * <p>The range is expressed in arbitrary units that must be the same as the 11187 * units used by {@link #computeHorizontalScrollRange()} and 11188 * {@link #computeHorizontalScrollExtent()}.</p> 11189 * 11190 * <p>The default offset is the scroll offset of this view.</p> 11191 * 11192 * @return the horizontal offset of the scrollbar's thumb 11193 * 11194 * @see #computeHorizontalScrollRange() 11195 * @see #computeHorizontalScrollExtent() 11196 * @see android.widget.ScrollBarDrawable 11197 */ 11198 protected int computeHorizontalScrollOffset() { 11199 return mScrollX; 11200 } 11201 11202 /** 11203 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 11204 * within the horizontal range. This value is used to compute the length 11205 * of the thumb within the scrollbar's track.</p> 11206 * 11207 * <p>The range is expressed in arbitrary units that must be the same as the 11208 * units used by {@link #computeHorizontalScrollRange()} and 11209 * {@link #computeHorizontalScrollOffset()}.</p> 11210 * 11211 * <p>The default extent is the drawing width of this view.</p> 11212 * 11213 * @return the horizontal extent of the scrollbar's thumb 11214 * 11215 * @see #computeHorizontalScrollRange() 11216 * @see #computeHorizontalScrollOffset() 11217 * @see android.widget.ScrollBarDrawable 11218 */ 11219 protected int computeHorizontalScrollExtent() { 11220 return getWidth(); 11221 } 11222 11223 /** 11224 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 11225 * 11226 * <p>The range is expressed in arbitrary units that must be the same as the 11227 * units used by {@link #computeVerticalScrollExtent()} and 11228 * {@link #computeVerticalScrollOffset()}.</p> 11229 * 11230 * @return the total vertical range represented by the vertical scrollbar 11231 * 11232 * <p>The default range is the drawing height of this view.</p> 11233 * 11234 * @see #computeVerticalScrollExtent() 11235 * @see #computeVerticalScrollOffset() 11236 * @see android.widget.ScrollBarDrawable 11237 */ 11238 protected int computeVerticalScrollRange() { 11239 return getHeight(); 11240 } 11241 11242 /** 11243 * <p>Compute the vertical offset of the vertical scrollbar's thumb 11244 * within the horizontal range. This value is used to compute the position 11245 * of the thumb within the scrollbar's track.</p> 11246 * 11247 * <p>The range is expressed in arbitrary units that must be the same as the 11248 * units used by {@link #computeVerticalScrollRange()} and 11249 * {@link #computeVerticalScrollExtent()}.</p> 11250 * 11251 * <p>The default offset is the scroll offset of this view.</p> 11252 * 11253 * @return the vertical offset of the scrollbar's thumb 11254 * 11255 * @see #computeVerticalScrollRange() 11256 * @see #computeVerticalScrollExtent() 11257 * @see android.widget.ScrollBarDrawable 11258 */ 11259 protected int computeVerticalScrollOffset() { 11260 return mScrollY; 11261 } 11262 11263 /** 11264 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 11265 * within the vertical range. This value is used to compute the length 11266 * of the thumb within the scrollbar's track.</p> 11267 * 11268 * <p>The range is expressed in arbitrary units that must be the same as the 11269 * units used by {@link #computeVerticalScrollRange()} and 11270 * {@link #computeVerticalScrollOffset()}.</p> 11271 * 11272 * <p>The default extent is the drawing height of this view.</p> 11273 * 11274 * @return the vertical extent of the scrollbar's thumb 11275 * 11276 * @see #computeVerticalScrollRange() 11277 * @see #computeVerticalScrollOffset() 11278 * @see android.widget.ScrollBarDrawable 11279 */ 11280 protected int computeVerticalScrollExtent() { 11281 return getHeight(); 11282 } 11283 11284 /** 11285 * Check if this view can be scrolled horizontally in a certain direction. 11286 * 11287 * @param direction Negative to check scrolling left, positive to check scrolling right. 11288 * @return true if this view can be scrolled in the specified direction, false otherwise. 11289 */ 11290 public boolean canScrollHorizontally(int direction) { 11291 final int offset = computeHorizontalScrollOffset(); 11292 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 11293 if (range == 0) return false; 11294 if (direction < 0) { 11295 return offset > 0; 11296 } else { 11297 return offset < range - 1; 11298 } 11299 } 11300 11301 /** 11302 * Check if this view can be scrolled vertically in a certain direction. 11303 * 11304 * @param direction Negative to check scrolling up, positive to check scrolling down. 11305 * @return true if this view can be scrolled in the specified direction, false otherwise. 11306 */ 11307 public boolean canScrollVertically(int direction) { 11308 final int offset = computeVerticalScrollOffset(); 11309 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 11310 if (range == 0) return false; 11311 if (direction < 0) { 11312 return offset > 0; 11313 } else { 11314 return offset < range - 1; 11315 } 11316 } 11317 11318 /** 11319 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 11320 * scrollbars are painted only if they have been awakened first.</p> 11321 * 11322 * @param canvas the canvas on which to draw the scrollbars 11323 * 11324 * @see #awakenScrollBars(int) 11325 */ 11326 protected final void onDrawScrollBars(Canvas canvas) { 11327 // scrollbars are drawn only when the animation is running 11328 final ScrollabilityCache cache = mScrollCache; 11329 if (cache != null) { 11330 11331 int state = cache.state; 11332 11333 if (state == ScrollabilityCache.OFF) { 11334 return; 11335 } 11336 11337 boolean invalidate = false; 11338 11339 if (state == ScrollabilityCache.FADING) { 11340 // We're fading -- get our fade interpolation 11341 if (cache.interpolatorValues == null) { 11342 cache.interpolatorValues = new float[1]; 11343 } 11344 11345 float[] values = cache.interpolatorValues; 11346 11347 // Stops the animation if we're done 11348 if (cache.scrollBarInterpolator.timeToValues(values) == 11349 Interpolator.Result.FREEZE_END) { 11350 cache.state = ScrollabilityCache.OFF; 11351 } else { 11352 cache.scrollBar.setAlpha(Math.round(values[0])); 11353 } 11354 11355 // This will make the scroll bars inval themselves after 11356 // drawing. We only want this when we're fading so that 11357 // we prevent excessive redraws 11358 invalidate = true; 11359 } else { 11360 // We're just on -- but we may have been fading before so 11361 // reset alpha 11362 cache.scrollBar.setAlpha(255); 11363 } 11364 11365 11366 final int viewFlags = mViewFlags; 11367 11368 final boolean drawHorizontalScrollBar = 11369 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11370 final boolean drawVerticalScrollBar = 11371 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 11372 && !isVerticalScrollBarHidden(); 11373 11374 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 11375 final int width = mRight - mLeft; 11376 final int height = mBottom - mTop; 11377 11378 final ScrollBarDrawable scrollBar = cache.scrollBar; 11379 11380 final int scrollX = mScrollX; 11381 final int scrollY = mScrollY; 11382 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 11383 11384 int left, top, right, bottom; 11385 11386 if (drawHorizontalScrollBar) { 11387 int size = scrollBar.getSize(false); 11388 if (size <= 0) { 11389 size = cache.scrollBarSize; 11390 } 11391 11392 scrollBar.setParameters(computeHorizontalScrollRange(), 11393 computeHorizontalScrollOffset(), 11394 computeHorizontalScrollExtent(), false); 11395 final int verticalScrollBarGap = drawVerticalScrollBar ? 11396 getVerticalScrollbarWidth() : 0; 11397 top = scrollY + height - size - (mUserPaddingBottom & inside); 11398 left = scrollX + (mPaddingLeft & inside); 11399 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 11400 bottom = top + size; 11401 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 11402 if (invalidate) { 11403 invalidate(left, top, right, bottom); 11404 } 11405 } 11406 11407 if (drawVerticalScrollBar) { 11408 int size = scrollBar.getSize(true); 11409 if (size <= 0) { 11410 size = cache.scrollBarSize; 11411 } 11412 11413 scrollBar.setParameters(computeVerticalScrollRange(), 11414 computeVerticalScrollOffset(), 11415 computeVerticalScrollExtent(), true); 11416 int verticalScrollbarPosition = mVerticalScrollbarPosition; 11417 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 11418 verticalScrollbarPosition = isLayoutRtl() ? 11419 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 11420 } 11421 switch (verticalScrollbarPosition) { 11422 default: 11423 case SCROLLBAR_POSITION_RIGHT: 11424 left = scrollX + width - size - (mUserPaddingRight & inside); 11425 break; 11426 case SCROLLBAR_POSITION_LEFT: 11427 left = scrollX + (mUserPaddingLeft & inside); 11428 break; 11429 } 11430 top = scrollY + (mPaddingTop & inside); 11431 right = left + size; 11432 bottom = scrollY + height - (mUserPaddingBottom & inside); 11433 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 11434 if (invalidate) { 11435 invalidate(left, top, right, bottom); 11436 } 11437 } 11438 } 11439 } 11440 } 11441 11442 /** 11443 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 11444 * FastScroller is visible. 11445 * @return whether to temporarily hide the vertical scrollbar 11446 * @hide 11447 */ 11448 protected boolean isVerticalScrollBarHidden() { 11449 return false; 11450 } 11451 11452 /** 11453 * <p>Draw the horizontal scrollbar if 11454 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 11455 * 11456 * @param canvas the canvas on which to draw the scrollbar 11457 * @param scrollBar the scrollbar's drawable 11458 * 11459 * @see #isHorizontalScrollBarEnabled() 11460 * @see #computeHorizontalScrollRange() 11461 * @see #computeHorizontalScrollExtent() 11462 * @see #computeHorizontalScrollOffset() 11463 * @see android.widget.ScrollBarDrawable 11464 * @hide 11465 */ 11466 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 11467 int l, int t, int r, int b) { 11468 scrollBar.setBounds(l, t, r, b); 11469 scrollBar.draw(canvas); 11470 } 11471 11472 /** 11473 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 11474 * returns true.</p> 11475 * 11476 * @param canvas the canvas on which to draw the scrollbar 11477 * @param scrollBar the scrollbar's drawable 11478 * 11479 * @see #isVerticalScrollBarEnabled() 11480 * @see #computeVerticalScrollRange() 11481 * @see #computeVerticalScrollExtent() 11482 * @see #computeVerticalScrollOffset() 11483 * @see android.widget.ScrollBarDrawable 11484 * @hide 11485 */ 11486 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 11487 int l, int t, int r, int b) { 11488 scrollBar.setBounds(l, t, r, b); 11489 scrollBar.draw(canvas); 11490 } 11491 11492 /** 11493 * Implement this to do your drawing. 11494 * 11495 * @param canvas the canvas on which the background will be drawn 11496 */ 11497 protected void onDraw(Canvas canvas) { 11498 } 11499 11500 /* 11501 * Caller is responsible for calling requestLayout if necessary. 11502 * (This allows addViewInLayout to not request a new layout.) 11503 */ 11504 void assignParent(ViewParent parent) { 11505 if (mParent == null) { 11506 mParent = parent; 11507 } else if (parent == null) { 11508 mParent = null; 11509 } else { 11510 throw new RuntimeException("view " + this + " being added, but" 11511 + " it already has a parent"); 11512 } 11513 } 11514 11515 /** 11516 * This is called when the view is attached to a window. At this point it 11517 * has a Surface and will start drawing. Note that this function is 11518 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 11519 * however it may be called any time before the first onDraw -- including 11520 * before or after {@link #onMeasure(int, int)}. 11521 * 11522 * @see #onDetachedFromWindow() 11523 */ 11524 protected void onAttachedToWindow() { 11525 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 11526 mParent.requestTransparentRegion(this); 11527 } 11528 11529 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 11530 initialAwakenScrollBars(); 11531 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 11532 } 11533 11534 jumpDrawablesToCurrentState(); 11535 11536 clearAccessibilityFocus(); 11537 if (isFocused()) { 11538 InputMethodManager imm = InputMethodManager.peekInstance(); 11539 imm.focusIn(this); 11540 } 11541 11542 if (mAttachInfo != null && mDisplayList != null) { 11543 mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList); 11544 } 11545 } 11546 11547 /** 11548 * Resolve all RTL related properties. 11549 */ 11550 void resolveRtlPropertiesIfNeeded() { 11551 if (!needRtlPropertiesResolution()) return; 11552 11553 // Order is important here: LayoutDirection MUST be resolved first 11554 if (!isLayoutDirectionResolved()) { 11555 resolveLayoutDirection(); 11556 resolveLayoutParams(); 11557 } 11558 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 11559 if (!isTextDirectionResolved()) { 11560 resolveTextDirection(); 11561 } 11562 if (!isTextAlignmentResolved()) { 11563 resolveTextAlignment(); 11564 } 11565 if (!isPaddingResolved()) { 11566 resolvePadding(); 11567 } 11568 if (!isDrawablesResolved()) { 11569 resolveDrawables(); 11570 } 11571 requestLayout(); 11572 invalidate(true); 11573 onRtlPropertiesChanged(getLayoutDirection()); 11574 } 11575 11576 // Reset resolution of all RTL related properties. 11577 void resetRtlProperties() { 11578 resetResolvedLayoutDirection(); 11579 resetResolvedTextDirection(); 11580 resetResolvedTextAlignment(); 11581 resetResolvedPadding(); 11582 resetResolvedDrawables(); 11583 } 11584 11585 /** 11586 * @see #onScreenStateChanged(int) 11587 */ 11588 void dispatchScreenStateChanged(int screenState) { 11589 onScreenStateChanged(screenState); 11590 } 11591 11592 /** 11593 * This method is called whenever the state of the screen this view is 11594 * attached to changes. A state change will usually occurs when the screen 11595 * turns on or off (whether it happens automatically or the user does it 11596 * manually.) 11597 * 11598 * @param screenState The new state of the screen. Can be either 11599 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 11600 */ 11601 public void onScreenStateChanged(int screenState) { 11602 } 11603 11604 /** 11605 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 11606 */ 11607 private boolean hasRtlSupport() { 11608 return mContext.getApplicationInfo().hasRtlSupport(); 11609 } 11610 11611 /** 11612 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 11613 * RTL not supported) 11614 */ 11615 private boolean isRtlCompatibilityMode() { 11616 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 11617 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 11618 } 11619 11620 /** 11621 * @return true if RTL properties need resolution. 11622 */ 11623 private boolean needRtlPropertiesResolution() { 11624 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 11625 } 11626 11627 /** 11628 * Called when any RTL property (layout direction or text direction or text alignment) has 11629 * been changed. 11630 * 11631 * Subclasses need to override this method to take care of cached information that depends on the 11632 * resolved layout direction, or to inform child views that inherit their layout direction. 11633 * 11634 * The default implementation does nothing. 11635 * 11636 * @param layoutDirection the direction of the layout 11637 * 11638 * @see #LAYOUT_DIRECTION_LTR 11639 * @see #LAYOUT_DIRECTION_RTL 11640 */ 11641 public void onRtlPropertiesChanged(int layoutDirection) { 11642 } 11643 11644 /** 11645 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 11646 * that the parent directionality can and will be resolved before its children. 11647 * 11648 * @return true if resolution has been done, false otherwise. 11649 * 11650 * @hide 11651 */ 11652 public boolean resolveLayoutDirection() { 11653 // Clear any previous layout direction resolution 11654 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 11655 11656 if (hasRtlSupport()) { 11657 // Set resolved depending on layout direction 11658 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 11659 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 11660 case LAYOUT_DIRECTION_INHERIT: 11661 // We cannot resolve yet. LTR is by default and let the resolution happen again 11662 // later to get the correct resolved value 11663 if (!canResolveLayoutDirection()) return false; 11664 11665 View parent = ((View) mParent); 11666 // Parent has not yet resolved, LTR is still the default 11667 if (!parent.isLayoutDirectionResolved()) return false; 11668 11669 if (parent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11670 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11671 } 11672 break; 11673 case LAYOUT_DIRECTION_RTL: 11674 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11675 break; 11676 case LAYOUT_DIRECTION_LOCALE: 11677 if((LAYOUT_DIRECTION_RTL == 11678 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 11679 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11680 } 11681 break; 11682 default: 11683 // Nothing to do, LTR by default 11684 } 11685 } 11686 11687 // Set to resolved 11688 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 11689 return true; 11690 } 11691 11692 /** 11693 * Check if layout direction resolution can be done. 11694 * 11695 * @return true if layout direction resolution can be done otherwise return false. 11696 * 11697 * @hide 11698 */ 11699 public boolean canResolveLayoutDirection() { 11700 switch (getRawLayoutDirection()) { 11701 case LAYOUT_DIRECTION_INHERIT: 11702 return (mParent != null) && (mParent instanceof ViewGroup) && 11703 ((ViewGroup) mParent).canResolveLayoutDirection(); 11704 default: 11705 return true; 11706 } 11707 } 11708 11709 /** 11710 * Reset the resolved layout direction. Layout direction will be resolved during a call to 11711 * {@link #onMeasure(int, int)}. 11712 * 11713 * @hide 11714 */ 11715 public void resetResolvedLayoutDirection() { 11716 // Reset the current resolved bits 11717 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 11718 } 11719 11720 /** 11721 * @return true if the layout direction is inherited. 11722 * 11723 * @hide 11724 */ 11725 public boolean isLayoutDirectionInherited() { 11726 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 11727 } 11728 11729 /** 11730 * @return true if layout direction has been resolved. 11731 */ 11732 private boolean isLayoutDirectionResolved() { 11733 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 11734 } 11735 11736 /** 11737 * Return if padding has been resolved 11738 * 11739 * @hide 11740 */ 11741 boolean isPaddingResolved() { 11742 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 11743 } 11744 11745 /** 11746 * Resolve padding depending on layout direction. 11747 * 11748 * @hide 11749 */ 11750 public void resolvePadding() { 11751 if (!isRtlCompatibilityMode()) { 11752 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 11753 // If start / end padding are defined, they will be resolved (hence overriding) to 11754 // left / right or right / left depending on the resolved layout direction. 11755 // If start / end padding are not defined, use the left / right ones. 11756 int resolvedLayoutDirection = getLayoutDirection(); 11757 // Set user padding to initial values ... 11758 mUserPaddingLeft = mUserPaddingLeftInitial; 11759 mUserPaddingRight = mUserPaddingRightInitial; 11760 // ... then resolve it. 11761 switch (resolvedLayoutDirection) { 11762 case LAYOUT_DIRECTION_RTL: 11763 if (mUserPaddingStart != UNDEFINED_PADDING) { 11764 mUserPaddingRight = mUserPaddingStart; 11765 } 11766 if (mUserPaddingEnd != UNDEFINED_PADDING) { 11767 mUserPaddingLeft = mUserPaddingEnd; 11768 } 11769 break; 11770 case LAYOUT_DIRECTION_LTR: 11771 default: 11772 if (mUserPaddingStart != UNDEFINED_PADDING) { 11773 mUserPaddingLeft = mUserPaddingStart; 11774 } 11775 if (mUserPaddingEnd != UNDEFINED_PADDING) { 11776 mUserPaddingRight = mUserPaddingEnd; 11777 } 11778 } 11779 11780 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 11781 11782 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, 11783 mUserPaddingBottom); 11784 onRtlPropertiesChanged(resolvedLayoutDirection); 11785 } 11786 11787 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 11788 } 11789 11790 /** 11791 * Reset the resolved layout direction. 11792 * 11793 * @hide 11794 */ 11795 public void resetResolvedPadding() { 11796 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 11797 } 11798 11799 /** 11800 * This is called when the view is detached from a window. At this point it 11801 * no longer has a surface for drawing. 11802 * 11803 * @see #onAttachedToWindow() 11804 */ 11805 protected void onDetachedFromWindow() { 11806 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 11807 11808 removeUnsetPressCallback(); 11809 removeLongPressCallback(); 11810 removePerformClickCallback(); 11811 removeSendViewScrolledAccessibilityEventCallback(); 11812 11813 destroyDrawingCache(); 11814 11815 destroyLayer(false); 11816 11817 if (mAttachInfo != null) { 11818 if (mDisplayList != null) { 11819 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList); 11820 } 11821 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 11822 } else { 11823 // Should never happen 11824 clearDisplayList(); 11825 } 11826 11827 mCurrentAnimation = null; 11828 11829 resetRtlProperties(); 11830 onRtlPropertiesChanged(LAYOUT_DIRECTION_DEFAULT); 11831 resetAccessibilityStateChanged(); 11832 } 11833 11834 /** 11835 * @return The number of times this view has been attached to a window 11836 */ 11837 protected int getWindowAttachCount() { 11838 return mWindowAttachCount; 11839 } 11840 11841 /** 11842 * Retrieve a unique token identifying the window this view is attached to. 11843 * @return Return the window's token for use in 11844 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 11845 */ 11846 public IBinder getWindowToken() { 11847 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 11848 } 11849 11850 /** 11851 * Retrieve a unique token identifying the top-level "real" window of 11852 * the window that this view is attached to. That is, this is like 11853 * {@link #getWindowToken}, except if the window this view in is a panel 11854 * window (attached to another containing window), then the token of 11855 * the containing window is returned instead. 11856 * 11857 * @return Returns the associated window token, either 11858 * {@link #getWindowToken()} or the containing window's token. 11859 */ 11860 public IBinder getApplicationWindowToken() { 11861 AttachInfo ai = mAttachInfo; 11862 if (ai != null) { 11863 IBinder appWindowToken = ai.mPanelParentWindowToken; 11864 if (appWindowToken == null) { 11865 appWindowToken = ai.mWindowToken; 11866 } 11867 return appWindowToken; 11868 } 11869 return null; 11870 } 11871 11872 /** 11873 * Gets the logical display to which the view's window has been attached. 11874 * 11875 * @return The logical display, or null if the view is not currently attached to a window. 11876 */ 11877 public Display getDisplay() { 11878 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 11879 } 11880 11881 /** 11882 * Retrieve private session object this view hierarchy is using to 11883 * communicate with the window manager. 11884 * @return the session object to communicate with the window manager 11885 */ 11886 /*package*/ IWindowSession getWindowSession() { 11887 return mAttachInfo != null ? mAttachInfo.mSession : null; 11888 } 11889 11890 /** 11891 * @param info the {@link android.view.View.AttachInfo} to associated with 11892 * this view 11893 */ 11894 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 11895 //System.out.println("Attached! " + this); 11896 mAttachInfo = info; 11897 mWindowAttachCount++; 11898 // We will need to evaluate the drawable state at least once. 11899 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 11900 if (mFloatingTreeObserver != null) { 11901 info.mTreeObserver.merge(mFloatingTreeObserver); 11902 mFloatingTreeObserver = null; 11903 } 11904 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 11905 mAttachInfo.mScrollContainers.add(this); 11906 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 11907 } 11908 performCollectViewAttributes(mAttachInfo, visibility); 11909 onAttachedToWindow(); 11910 11911 ListenerInfo li = mListenerInfo; 11912 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 11913 li != null ? li.mOnAttachStateChangeListeners : null; 11914 if (listeners != null && listeners.size() > 0) { 11915 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 11916 // perform the dispatching. The iterator is a safe guard against listeners that 11917 // could mutate the list by calling the various add/remove methods. This prevents 11918 // the array from being modified while we iterate it. 11919 for (OnAttachStateChangeListener listener : listeners) { 11920 listener.onViewAttachedToWindow(this); 11921 } 11922 } 11923 11924 int vis = info.mWindowVisibility; 11925 if (vis != GONE) { 11926 onWindowVisibilityChanged(vis); 11927 } 11928 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 11929 // If nobody has evaluated the drawable state yet, then do it now. 11930 refreshDrawableState(); 11931 } 11932 needGlobalAttributesUpdate(false); 11933 } 11934 11935 void dispatchDetachedFromWindow() { 11936 AttachInfo info = mAttachInfo; 11937 if (info != null) { 11938 int vis = info.mWindowVisibility; 11939 if (vis != GONE) { 11940 onWindowVisibilityChanged(GONE); 11941 } 11942 } 11943 11944 onDetachedFromWindow(); 11945 11946 ListenerInfo li = mListenerInfo; 11947 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 11948 li != null ? li.mOnAttachStateChangeListeners : null; 11949 if (listeners != null && listeners.size() > 0) { 11950 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 11951 // perform the dispatching. The iterator is a safe guard against listeners that 11952 // could mutate the list by calling the various add/remove methods. This prevents 11953 // the array from being modified while we iterate it. 11954 for (OnAttachStateChangeListener listener : listeners) { 11955 listener.onViewDetachedFromWindow(this); 11956 } 11957 } 11958 11959 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 11960 mAttachInfo.mScrollContainers.remove(this); 11961 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 11962 } 11963 11964 mAttachInfo = null; 11965 } 11966 11967 /** 11968 * Store this view hierarchy's frozen state into the given container. 11969 * 11970 * @param container The SparseArray in which to save the view's state. 11971 * 11972 * @see #restoreHierarchyState(android.util.SparseArray) 11973 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11974 * @see #onSaveInstanceState() 11975 */ 11976 public void saveHierarchyState(SparseArray<Parcelable> container) { 11977 dispatchSaveInstanceState(container); 11978 } 11979 11980 /** 11981 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 11982 * this view and its children. May be overridden to modify how freezing happens to a 11983 * view's children; for example, some views may want to not store state for their children. 11984 * 11985 * @param container The SparseArray in which to save the view's state. 11986 * 11987 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 11988 * @see #saveHierarchyState(android.util.SparseArray) 11989 * @see #onSaveInstanceState() 11990 */ 11991 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 11992 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 11993 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 11994 Parcelable state = onSaveInstanceState(); 11995 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 11996 throw new IllegalStateException( 11997 "Derived class did not call super.onSaveInstanceState()"); 11998 } 11999 if (state != null) { 12000 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 12001 // + ": " + state); 12002 container.put(mID, state); 12003 } 12004 } 12005 } 12006 12007 /** 12008 * Hook allowing a view to generate a representation of its internal state 12009 * that can later be used to create a new instance with that same state. 12010 * This state should only contain information that is not persistent or can 12011 * not be reconstructed later. For example, you will never store your 12012 * current position on screen because that will be computed again when a 12013 * new instance of the view is placed in its view hierarchy. 12014 * <p> 12015 * Some examples of things you may store here: the current cursor position 12016 * in a text view (but usually not the text itself since that is stored in a 12017 * content provider or other persistent storage), the currently selected 12018 * item in a list view. 12019 * 12020 * @return Returns a Parcelable object containing the view's current dynamic 12021 * state, or null if there is nothing interesting to save. The 12022 * default implementation returns null. 12023 * @see #onRestoreInstanceState(android.os.Parcelable) 12024 * @see #saveHierarchyState(android.util.SparseArray) 12025 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12026 * @see #setSaveEnabled(boolean) 12027 */ 12028 protected Parcelable onSaveInstanceState() { 12029 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12030 return BaseSavedState.EMPTY_STATE; 12031 } 12032 12033 /** 12034 * Restore this view hierarchy's frozen state from the given container. 12035 * 12036 * @param container The SparseArray which holds previously frozen states. 12037 * 12038 * @see #saveHierarchyState(android.util.SparseArray) 12039 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12040 * @see #onRestoreInstanceState(android.os.Parcelable) 12041 */ 12042 public void restoreHierarchyState(SparseArray<Parcelable> container) { 12043 dispatchRestoreInstanceState(container); 12044 } 12045 12046 /** 12047 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 12048 * state for this view and its children. May be overridden to modify how restoring 12049 * happens to a view's children; for example, some views may want to not store state 12050 * for their children. 12051 * 12052 * @param container The SparseArray which holds previously saved state. 12053 * 12054 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12055 * @see #restoreHierarchyState(android.util.SparseArray) 12056 * @see #onRestoreInstanceState(android.os.Parcelable) 12057 */ 12058 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 12059 if (mID != NO_ID) { 12060 Parcelable state = container.get(mID); 12061 if (state != null) { 12062 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 12063 // + ": " + state); 12064 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 12065 onRestoreInstanceState(state); 12066 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 12067 throw new IllegalStateException( 12068 "Derived class did not call super.onRestoreInstanceState()"); 12069 } 12070 } 12071 } 12072 } 12073 12074 /** 12075 * Hook allowing a view to re-apply a representation of its internal state that had previously 12076 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 12077 * null state. 12078 * 12079 * @param state The frozen state that had previously been returned by 12080 * {@link #onSaveInstanceState}. 12081 * 12082 * @see #onSaveInstanceState() 12083 * @see #restoreHierarchyState(android.util.SparseArray) 12084 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12085 */ 12086 protected void onRestoreInstanceState(Parcelable state) { 12087 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12088 if (state != BaseSavedState.EMPTY_STATE && state != null) { 12089 throw new IllegalArgumentException("Wrong state class, expecting View State but " 12090 + "received " + state.getClass().toString() + " instead. This usually happens " 12091 + "when two views of different type have the same id in the same hierarchy. " 12092 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 12093 + "other views do not use the same id."); 12094 } 12095 } 12096 12097 /** 12098 * <p>Return the time at which the drawing of the view hierarchy started.</p> 12099 * 12100 * @return the drawing start time in milliseconds 12101 */ 12102 public long getDrawingTime() { 12103 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 12104 } 12105 12106 /** 12107 * <p>Enables or disables the duplication of the parent's state into this view. When 12108 * duplication is enabled, this view gets its drawable state from its parent rather 12109 * than from its own internal properties.</p> 12110 * 12111 * <p>Note: in the current implementation, setting this property to true after the 12112 * view was added to a ViewGroup might have no effect at all. This property should 12113 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 12114 * 12115 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 12116 * property is enabled, an exception will be thrown.</p> 12117 * 12118 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 12119 * parent, these states should not be affected by this method.</p> 12120 * 12121 * @param enabled True to enable duplication of the parent's drawable state, false 12122 * to disable it. 12123 * 12124 * @see #getDrawableState() 12125 * @see #isDuplicateParentStateEnabled() 12126 */ 12127 public void setDuplicateParentStateEnabled(boolean enabled) { 12128 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 12129 } 12130 12131 /** 12132 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 12133 * 12134 * @return True if this view's drawable state is duplicated from the parent, 12135 * false otherwise 12136 * 12137 * @see #getDrawableState() 12138 * @see #setDuplicateParentStateEnabled(boolean) 12139 */ 12140 public boolean isDuplicateParentStateEnabled() { 12141 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 12142 } 12143 12144 /** 12145 * <p>Specifies the type of layer backing this view. The layer can be 12146 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 12147 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 12148 * 12149 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12150 * instance that controls how the layer is composed on screen. The following 12151 * properties of the paint are taken into account when composing the layer:</p> 12152 * <ul> 12153 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12154 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12155 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12156 * </ul> 12157 * 12158 * <p>If this view has an alpha value set to < 1.0 by calling 12159 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 12160 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 12161 * equivalent to setting a hardware layer on this view and providing a paint with 12162 * the desired alpha value.</p> 12163 * 12164 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 12165 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 12166 * for more information on when and how to use layers.</p> 12167 * 12168 * @param layerType The type of layer to use with this view, must be one of 12169 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12170 * {@link #LAYER_TYPE_HARDWARE} 12171 * @param paint The paint used to compose the layer. This argument is optional 12172 * and can be null. It is ignored when the layer type is 12173 * {@link #LAYER_TYPE_NONE} 12174 * 12175 * @see #getLayerType() 12176 * @see #LAYER_TYPE_NONE 12177 * @see #LAYER_TYPE_SOFTWARE 12178 * @see #LAYER_TYPE_HARDWARE 12179 * @see #setAlpha(float) 12180 * 12181 * @attr ref android.R.styleable#View_layerType 12182 */ 12183 public void setLayerType(int layerType, Paint paint) { 12184 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 12185 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 12186 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 12187 } 12188 12189 if (layerType == mLayerType) { 12190 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 12191 mLayerPaint = paint == null ? new Paint() : paint; 12192 invalidateParentCaches(); 12193 invalidate(true); 12194 } 12195 return; 12196 } 12197 12198 // Destroy any previous software drawing cache if needed 12199 switch (mLayerType) { 12200 case LAYER_TYPE_HARDWARE: 12201 destroyLayer(false); 12202 // fall through - non-accelerated views may use software layer mechanism instead 12203 case LAYER_TYPE_SOFTWARE: 12204 destroyDrawingCache(); 12205 break; 12206 default: 12207 break; 12208 } 12209 12210 mLayerType = layerType; 12211 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 12212 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 12213 mLocalDirtyRect = layerDisabled ? null : new Rect(); 12214 12215 invalidateParentCaches(); 12216 invalidate(true); 12217 } 12218 12219 /** 12220 * Updates the {@link Paint} object used with the current layer (used only if the current 12221 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 12222 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 12223 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 12224 * ensure that the view gets redrawn immediately. 12225 * 12226 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12227 * instance that controls how the layer is composed on screen. The following 12228 * properties of the paint are taken into account when composing the layer:</p> 12229 * <ul> 12230 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12231 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12232 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12233 * </ul> 12234 * 12235 * <p>If this view has an alpha value set to < 1.0 by calling 12236 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 12237 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 12238 * equivalent to setting a hardware layer on this view and providing a paint with 12239 * the desired alpha value.</p> 12240 * 12241 * @param paint The paint used to compose the layer. This argument is optional 12242 * and can be null. It is ignored when the layer type is 12243 * {@link #LAYER_TYPE_NONE} 12244 * 12245 * @see #setLayerType(int, android.graphics.Paint) 12246 */ 12247 public void setLayerPaint(Paint paint) { 12248 int layerType = getLayerType(); 12249 if (layerType != LAYER_TYPE_NONE) { 12250 mLayerPaint = paint == null ? new Paint() : paint; 12251 if (layerType == LAYER_TYPE_HARDWARE) { 12252 HardwareLayer layer = getHardwareLayer(); 12253 if (layer != null) { 12254 layer.setLayerPaint(paint); 12255 } 12256 invalidateViewProperty(false, false); 12257 } else { 12258 invalidate(); 12259 } 12260 } 12261 } 12262 12263 /** 12264 * Indicates whether this view has a static layer. A view with layer type 12265 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 12266 * dynamic. 12267 */ 12268 boolean hasStaticLayer() { 12269 return true; 12270 } 12271 12272 /** 12273 * Indicates what type of layer is currently associated with this view. By default 12274 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 12275 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 12276 * for more information on the different types of layers. 12277 * 12278 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12279 * {@link #LAYER_TYPE_HARDWARE} 12280 * 12281 * @see #setLayerType(int, android.graphics.Paint) 12282 * @see #buildLayer() 12283 * @see #LAYER_TYPE_NONE 12284 * @see #LAYER_TYPE_SOFTWARE 12285 * @see #LAYER_TYPE_HARDWARE 12286 */ 12287 public int getLayerType() { 12288 return mLayerType; 12289 } 12290 12291 /** 12292 * Forces this view's layer to be created and this view to be rendered 12293 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 12294 * invoking this method will have no effect. 12295 * 12296 * This method can for instance be used to render a view into its layer before 12297 * starting an animation. If this view is complex, rendering into the layer 12298 * before starting the animation will avoid skipping frames. 12299 * 12300 * @throws IllegalStateException If this view is not attached to a window 12301 * 12302 * @see #setLayerType(int, android.graphics.Paint) 12303 */ 12304 public void buildLayer() { 12305 if (mLayerType == LAYER_TYPE_NONE) return; 12306 12307 if (mAttachInfo == null) { 12308 throw new IllegalStateException("This view must be attached to a window first"); 12309 } 12310 12311 switch (mLayerType) { 12312 case LAYER_TYPE_HARDWARE: 12313 if (mAttachInfo.mHardwareRenderer != null && 12314 mAttachInfo.mHardwareRenderer.isEnabled() && 12315 mAttachInfo.mHardwareRenderer.validate()) { 12316 getHardwareLayer(); 12317 } 12318 break; 12319 case LAYER_TYPE_SOFTWARE: 12320 buildDrawingCache(true); 12321 break; 12322 } 12323 } 12324 12325 /** 12326 * <p>Returns a hardware layer that can be used to draw this view again 12327 * without executing its draw method.</p> 12328 * 12329 * @return A HardwareLayer ready to render, or null if an error occurred. 12330 */ 12331 HardwareLayer getHardwareLayer() { 12332 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 12333 !mAttachInfo.mHardwareRenderer.isEnabled()) { 12334 return null; 12335 } 12336 12337 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 12338 12339 final int width = mRight - mLeft; 12340 final int height = mBottom - mTop; 12341 12342 if (width == 0 || height == 0) { 12343 return null; 12344 } 12345 12346 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 12347 if (mHardwareLayer == null) { 12348 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 12349 width, height, isOpaque()); 12350 mLocalDirtyRect.set(0, 0, width, height); 12351 } else { 12352 if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 12353 if (mHardwareLayer.resize(width, height)) { 12354 mLocalDirtyRect.set(0, 0, width, height); 12355 } 12356 } 12357 12358 // This should not be necessary but applications that change 12359 // the parameters of their background drawable without calling 12360 // this.setBackground(Drawable) can leave the view in a bad state 12361 // (for instance isOpaque() returns true, but the background is 12362 // not opaque.) 12363 computeOpaqueFlags(); 12364 12365 final boolean opaque = isOpaque(); 12366 if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) { 12367 mHardwareLayer.setOpaque(opaque); 12368 mLocalDirtyRect.set(0, 0, width, height); 12369 } 12370 } 12371 12372 // The layer is not valid if the underlying GPU resources cannot be allocated 12373 if (!mHardwareLayer.isValid()) { 12374 return null; 12375 } 12376 12377 mHardwareLayer.setLayerPaint(mLayerPaint); 12378 mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 12379 ViewRootImpl viewRoot = getViewRootImpl(); 12380 if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer); 12381 12382 mLocalDirtyRect.setEmpty(); 12383 } 12384 12385 return mHardwareLayer; 12386 } 12387 12388 /** 12389 * Destroys this View's hardware layer if possible. 12390 * 12391 * @return True if the layer was destroyed, false otherwise. 12392 * 12393 * @see #setLayerType(int, android.graphics.Paint) 12394 * @see #LAYER_TYPE_HARDWARE 12395 */ 12396 boolean destroyLayer(boolean valid) { 12397 if (mHardwareLayer != null) { 12398 AttachInfo info = mAttachInfo; 12399 if (info != null && info.mHardwareRenderer != null && 12400 info.mHardwareRenderer.isEnabled() && 12401 (valid || info.mHardwareRenderer.validate())) { 12402 mHardwareLayer.destroy(); 12403 mHardwareLayer = null; 12404 12405 if (mDisplayList != null) { 12406 mDisplayList.reset(); 12407 } 12408 invalidate(true); 12409 invalidateParentCaches(); 12410 } 12411 return true; 12412 } 12413 return false; 12414 } 12415 12416 /** 12417 * Destroys all hardware rendering resources. This method is invoked 12418 * when the system needs to reclaim resources. Upon execution of this 12419 * method, you should free any OpenGL resources created by the view. 12420 * 12421 * Note: you <strong>must</strong> call 12422 * <code>super.destroyHardwareResources()</code> when overriding 12423 * this method. 12424 * 12425 * @hide 12426 */ 12427 protected void destroyHardwareResources() { 12428 destroyLayer(true); 12429 } 12430 12431 /** 12432 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 12433 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 12434 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 12435 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 12436 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 12437 * null.</p> 12438 * 12439 * <p>Enabling the drawing cache is similar to 12440 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 12441 * acceleration is turned off. When hardware acceleration is turned on, enabling the 12442 * drawing cache has no effect on rendering because the system uses a different mechanism 12443 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 12444 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 12445 * for information on how to enable software and hardware layers.</p> 12446 * 12447 * <p>This API can be used to manually generate 12448 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 12449 * {@link #getDrawingCache()}.</p> 12450 * 12451 * @param enabled true to enable the drawing cache, false otherwise 12452 * 12453 * @see #isDrawingCacheEnabled() 12454 * @see #getDrawingCache() 12455 * @see #buildDrawingCache() 12456 * @see #setLayerType(int, android.graphics.Paint) 12457 */ 12458 public void setDrawingCacheEnabled(boolean enabled) { 12459 mCachingFailed = false; 12460 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 12461 } 12462 12463 /** 12464 * <p>Indicates whether the drawing cache is enabled for this view.</p> 12465 * 12466 * @return true if the drawing cache is enabled 12467 * 12468 * @see #setDrawingCacheEnabled(boolean) 12469 * @see #getDrawingCache() 12470 */ 12471 @ViewDebug.ExportedProperty(category = "drawing") 12472 public boolean isDrawingCacheEnabled() { 12473 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 12474 } 12475 12476 /** 12477 * Debugging utility which recursively outputs the dirty state of a view and its 12478 * descendants. 12479 * 12480 * @hide 12481 */ 12482 @SuppressWarnings({"UnusedDeclaration"}) 12483 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 12484 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 12485 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 12486 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 12487 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 12488 if (clear) { 12489 mPrivateFlags &= clearMask; 12490 } 12491 if (this instanceof ViewGroup) { 12492 ViewGroup parent = (ViewGroup) this; 12493 final int count = parent.getChildCount(); 12494 for (int i = 0; i < count; i++) { 12495 final View child = parent.getChildAt(i); 12496 child.outputDirtyFlags(indent + " ", clear, clearMask); 12497 } 12498 } 12499 } 12500 12501 /** 12502 * This method is used by ViewGroup to cause its children to restore or recreate their 12503 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 12504 * to recreate its own display list, which would happen if it went through the normal 12505 * draw/dispatchDraw mechanisms. 12506 * 12507 * @hide 12508 */ 12509 protected void dispatchGetDisplayList() {} 12510 12511 /** 12512 * A view that is not attached or hardware accelerated cannot create a display list. 12513 * This method checks these conditions and returns the appropriate result. 12514 * 12515 * @return true if view has the ability to create a display list, false otherwise. 12516 * 12517 * @hide 12518 */ 12519 public boolean canHaveDisplayList() { 12520 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 12521 } 12522 12523 /** 12524 * @return The HardwareRenderer associated with that view or null if hardware rendering 12525 * is not supported or this this has not been attached to a window. 12526 * 12527 * @hide 12528 */ 12529 public HardwareRenderer getHardwareRenderer() { 12530 if (mAttachInfo != null) { 12531 return mAttachInfo.mHardwareRenderer; 12532 } 12533 return null; 12534 } 12535 12536 /** 12537 * Returns a DisplayList. If the incoming displayList is null, one will be created. 12538 * Otherwise, the same display list will be returned (after having been rendered into 12539 * along the way, depending on the invalidation state of the view). 12540 * 12541 * @param displayList The previous version of this displayList, could be null. 12542 * @param isLayer Whether the requester of the display list is a layer. If so, 12543 * the view will avoid creating a layer inside the resulting display list. 12544 * @return A new or reused DisplayList object. 12545 */ 12546 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 12547 if (!canHaveDisplayList()) { 12548 return null; 12549 } 12550 12551 if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || 12552 displayList == null || !displayList.isValid() || 12553 (!isLayer && mRecreateDisplayList))) { 12554 // Don't need to recreate the display list, just need to tell our 12555 // children to restore/recreate theirs 12556 if (displayList != null && displayList.isValid() && 12557 !isLayer && !mRecreateDisplayList) { 12558 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12559 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12560 dispatchGetDisplayList(); 12561 12562 return displayList; 12563 } 12564 12565 if (!isLayer) { 12566 // If we got here, we're recreating it. Mark it as such to ensure that 12567 // we copy in child display lists into ours in drawChild() 12568 mRecreateDisplayList = true; 12569 } 12570 if (displayList == null) { 12571 final String name = getClass().getSimpleName(); 12572 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name); 12573 // If we're creating a new display list, make sure our parent gets invalidated 12574 // since they will need to recreate their display list to account for this 12575 // new child display list. 12576 invalidateParentCaches(); 12577 } 12578 12579 boolean caching = false; 12580 final HardwareCanvas canvas = displayList.start(); 12581 int width = mRight - mLeft; 12582 int height = mBottom - mTop; 12583 12584 try { 12585 canvas.setViewport(width, height); 12586 // The dirty rect should always be null for a display list 12587 canvas.onPreDraw(null); 12588 int layerType = getLayerType(); 12589 if (!isLayer && layerType != LAYER_TYPE_NONE) { 12590 if (layerType == LAYER_TYPE_HARDWARE) { 12591 final HardwareLayer layer = getHardwareLayer(); 12592 if (layer != null && layer.isValid()) { 12593 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 12594 } else { 12595 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 12596 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 12597 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 12598 } 12599 caching = true; 12600 } else { 12601 buildDrawingCache(true); 12602 Bitmap cache = getDrawingCache(true); 12603 if (cache != null) { 12604 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 12605 caching = true; 12606 } 12607 } 12608 } else { 12609 12610 computeScroll(); 12611 12612 canvas.translate(-mScrollX, -mScrollY); 12613 if (!isLayer) { 12614 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12615 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12616 } 12617 12618 // Fast path for layouts with no backgrounds 12619 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12620 dispatchDraw(canvas); 12621 } else { 12622 draw(canvas); 12623 } 12624 } 12625 } finally { 12626 canvas.onPostDraw(); 12627 12628 displayList.end(); 12629 displayList.setCaching(caching); 12630 if (isLayer) { 12631 displayList.setLeftTopRightBottom(0, 0, width, height); 12632 } else { 12633 setDisplayListProperties(displayList); 12634 } 12635 } 12636 } else if (!isLayer) { 12637 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12638 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12639 } 12640 12641 return displayList; 12642 } 12643 12644 /** 12645 * Get the DisplayList for the HardwareLayer 12646 * 12647 * @param layer The HardwareLayer whose DisplayList we want 12648 * @return A DisplayList fopr the specified HardwareLayer 12649 */ 12650 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 12651 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 12652 layer.setDisplayList(displayList); 12653 return displayList; 12654 } 12655 12656 12657 /** 12658 * <p>Returns a display list that can be used to draw this view again 12659 * without executing its draw method.</p> 12660 * 12661 * @return A DisplayList ready to replay, or null if caching is not enabled. 12662 * 12663 * @hide 12664 */ 12665 public DisplayList getDisplayList() { 12666 mDisplayList = getDisplayList(mDisplayList, false); 12667 return mDisplayList; 12668 } 12669 12670 private void clearDisplayList() { 12671 if (mDisplayList != null) { 12672 mDisplayList.invalidate(); 12673 mDisplayList.clear(); 12674 } 12675 } 12676 12677 /** 12678 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 12679 * 12680 * @return A non-scaled bitmap representing this view or null if cache is disabled. 12681 * 12682 * @see #getDrawingCache(boolean) 12683 */ 12684 public Bitmap getDrawingCache() { 12685 return getDrawingCache(false); 12686 } 12687 12688 /** 12689 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 12690 * is null when caching is disabled. If caching is enabled and the cache is not ready, 12691 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 12692 * draw from the cache when the cache is enabled. To benefit from the cache, you must 12693 * request the drawing cache by calling this method and draw it on screen if the 12694 * returned bitmap is not null.</p> 12695 * 12696 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 12697 * this method will create a bitmap of the same size as this view. Because this bitmap 12698 * will be drawn scaled by the parent ViewGroup, the result on screen might show 12699 * scaling artifacts. To avoid such artifacts, you should call this method by setting 12700 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 12701 * size than the view. This implies that your application must be able to handle this 12702 * size.</p> 12703 * 12704 * @param autoScale Indicates whether the generated bitmap should be scaled based on 12705 * the current density of the screen when the application is in compatibility 12706 * mode. 12707 * 12708 * @return A bitmap representing this view or null if cache is disabled. 12709 * 12710 * @see #setDrawingCacheEnabled(boolean) 12711 * @see #isDrawingCacheEnabled() 12712 * @see #buildDrawingCache(boolean) 12713 * @see #destroyDrawingCache() 12714 */ 12715 public Bitmap getDrawingCache(boolean autoScale) { 12716 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 12717 return null; 12718 } 12719 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 12720 buildDrawingCache(autoScale); 12721 } 12722 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 12723 } 12724 12725 /** 12726 * <p>Frees the resources used by the drawing cache. If you call 12727 * {@link #buildDrawingCache()} manually without calling 12728 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 12729 * should cleanup the cache with this method afterwards.</p> 12730 * 12731 * @see #setDrawingCacheEnabled(boolean) 12732 * @see #buildDrawingCache() 12733 * @see #getDrawingCache() 12734 */ 12735 public void destroyDrawingCache() { 12736 if (mDrawingCache != null) { 12737 mDrawingCache.recycle(); 12738 mDrawingCache = null; 12739 } 12740 if (mUnscaledDrawingCache != null) { 12741 mUnscaledDrawingCache.recycle(); 12742 mUnscaledDrawingCache = null; 12743 } 12744 } 12745 12746 /** 12747 * Setting a solid background color for the drawing cache's bitmaps will improve 12748 * performance and memory usage. Note, though that this should only be used if this 12749 * view will always be drawn on top of a solid color. 12750 * 12751 * @param color The background color to use for the drawing cache's bitmap 12752 * 12753 * @see #setDrawingCacheEnabled(boolean) 12754 * @see #buildDrawingCache() 12755 * @see #getDrawingCache() 12756 */ 12757 public void setDrawingCacheBackgroundColor(int color) { 12758 if (color != mDrawingCacheBackgroundColor) { 12759 mDrawingCacheBackgroundColor = color; 12760 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 12761 } 12762 } 12763 12764 /** 12765 * @see #setDrawingCacheBackgroundColor(int) 12766 * 12767 * @return The background color to used for the drawing cache's bitmap 12768 */ 12769 public int getDrawingCacheBackgroundColor() { 12770 return mDrawingCacheBackgroundColor; 12771 } 12772 12773 /** 12774 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 12775 * 12776 * @see #buildDrawingCache(boolean) 12777 */ 12778 public void buildDrawingCache() { 12779 buildDrawingCache(false); 12780 } 12781 12782 /** 12783 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 12784 * 12785 * <p>If you call {@link #buildDrawingCache()} manually without calling 12786 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 12787 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 12788 * 12789 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 12790 * this method will create a bitmap of the same size as this view. Because this bitmap 12791 * will be drawn scaled by the parent ViewGroup, the result on screen might show 12792 * scaling artifacts. To avoid such artifacts, you should call this method by setting 12793 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 12794 * size than the view. This implies that your application must be able to handle this 12795 * size.</p> 12796 * 12797 * <p>You should avoid calling this method when hardware acceleration is enabled. If 12798 * you do not need the drawing cache bitmap, calling this method will increase memory 12799 * usage and cause the view to be rendered in software once, thus negatively impacting 12800 * performance.</p> 12801 * 12802 * @see #getDrawingCache() 12803 * @see #destroyDrawingCache() 12804 */ 12805 public void buildDrawingCache(boolean autoScale) { 12806 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 12807 mDrawingCache == null : mUnscaledDrawingCache == null)) { 12808 mCachingFailed = false; 12809 12810 int width = mRight - mLeft; 12811 int height = mBottom - mTop; 12812 12813 final AttachInfo attachInfo = mAttachInfo; 12814 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 12815 12816 if (autoScale && scalingRequired) { 12817 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 12818 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 12819 } 12820 12821 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 12822 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 12823 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 12824 12825 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 12826 final long drawingCacheSize = 12827 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 12828 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 12829 if (width > 0 && height > 0) { 12830 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 12831 + projectedBitmapSize + " bytes, only " 12832 + drawingCacheSize + " available"); 12833 } 12834 destroyDrawingCache(); 12835 mCachingFailed = true; 12836 return; 12837 } 12838 12839 boolean clear = true; 12840 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 12841 12842 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 12843 Bitmap.Config quality; 12844 if (!opaque) { 12845 // Never pick ARGB_4444 because it looks awful 12846 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 12847 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 12848 case DRAWING_CACHE_QUALITY_AUTO: 12849 quality = Bitmap.Config.ARGB_8888; 12850 break; 12851 case DRAWING_CACHE_QUALITY_LOW: 12852 quality = Bitmap.Config.ARGB_8888; 12853 break; 12854 case DRAWING_CACHE_QUALITY_HIGH: 12855 quality = Bitmap.Config.ARGB_8888; 12856 break; 12857 default: 12858 quality = Bitmap.Config.ARGB_8888; 12859 break; 12860 } 12861 } else { 12862 // Optimization for translucent windows 12863 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 12864 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 12865 } 12866 12867 // Try to cleanup memory 12868 if (bitmap != null) bitmap.recycle(); 12869 12870 try { 12871 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 12872 width, height, quality); 12873 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 12874 if (autoScale) { 12875 mDrawingCache = bitmap; 12876 } else { 12877 mUnscaledDrawingCache = bitmap; 12878 } 12879 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 12880 } catch (OutOfMemoryError e) { 12881 // If there is not enough memory to create the bitmap cache, just 12882 // ignore the issue as bitmap caches are not required to draw the 12883 // view hierarchy 12884 if (autoScale) { 12885 mDrawingCache = null; 12886 } else { 12887 mUnscaledDrawingCache = null; 12888 } 12889 mCachingFailed = true; 12890 return; 12891 } 12892 12893 clear = drawingCacheBackgroundColor != 0; 12894 } 12895 12896 Canvas canvas; 12897 if (attachInfo != null) { 12898 canvas = attachInfo.mCanvas; 12899 if (canvas == null) { 12900 canvas = new Canvas(); 12901 } 12902 canvas.setBitmap(bitmap); 12903 // Temporarily clobber the cached Canvas in case one of our children 12904 // is also using a drawing cache. Without this, the children would 12905 // steal the canvas by attaching their own bitmap to it and bad, bad 12906 // thing would happen (invisible views, corrupted drawings, etc.) 12907 attachInfo.mCanvas = null; 12908 } else { 12909 // This case should hopefully never or seldom happen 12910 canvas = new Canvas(bitmap); 12911 } 12912 12913 if (clear) { 12914 bitmap.eraseColor(drawingCacheBackgroundColor); 12915 } 12916 12917 computeScroll(); 12918 final int restoreCount = canvas.save(); 12919 12920 if (autoScale && scalingRequired) { 12921 final float scale = attachInfo.mApplicationScale; 12922 canvas.scale(scale, scale); 12923 } 12924 12925 canvas.translate(-mScrollX, -mScrollY); 12926 12927 mPrivateFlags |= PFLAG_DRAWN; 12928 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 12929 mLayerType != LAYER_TYPE_NONE) { 12930 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 12931 } 12932 12933 // Fast path for layouts with no backgrounds 12934 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12935 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12936 dispatchDraw(canvas); 12937 } else { 12938 draw(canvas); 12939 } 12940 12941 canvas.restoreToCount(restoreCount); 12942 canvas.setBitmap(null); 12943 12944 if (attachInfo != null) { 12945 // Restore the cached Canvas for our siblings 12946 attachInfo.mCanvas = canvas; 12947 } 12948 } 12949 } 12950 12951 /** 12952 * Create a snapshot of the view into a bitmap. We should probably make 12953 * some form of this public, but should think about the API. 12954 */ 12955 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 12956 int width = mRight - mLeft; 12957 int height = mBottom - mTop; 12958 12959 final AttachInfo attachInfo = mAttachInfo; 12960 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 12961 width = (int) ((width * scale) + 0.5f); 12962 height = (int) ((height * scale) + 0.5f); 12963 12964 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 12965 width > 0 ? width : 1, height > 0 ? height : 1, quality); 12966 if (bitmap == null) { 12967 throw new OutOfMemoryError(); 12968 } 12969 12970 Resources resources = getResources(); 12971 if (resources != null) { 12972 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 12973 } 12974 12975 Canvas canvas; 12976 if (attachInfo != null) { 12977 canvas = attachInfo.mCanvas; 12978 if (canvas == null) { 12979 canvas = new Canvas(); 12980 } 12981 canvas.setBitmap(bitmap); 12982 // Temporarily clobber the cached Canvas in case one of our children 12983 // is also using a drawing cache. Without this, the children would 12984 // steal the canvas by attaching their own bitmap to it and bad, bad 12985 // things would happen (invisible views, corrupted drawings, etc.) 12986 attachInfo.mCanvas = null; 12987 } else { 12988 // This case should hopefully never or seldom happen 12989 canvas = new Canvas(bitmap); 12990 } 12991 12992 if ((backgroundColor & 0xff000000) != 0) { 12993 bitmap.eraseColor(backgroundColor); 12994 } 12995 12996 computeScroll(); 12997 final int restoreCount = canvas.save(); 12998 canvas.scale(scale, scale); 12999 canvas.translate(-mScrollX, -mScrollY); 13000 13001 // Temporarily remove the dirty mask 13002 int flags = mPrivateFlags; 13003 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13004 13005 // Fast path for layouts with no backgrounds 13006 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13007 dispatchDraw(canvas); 13008 } else { 13009 draw(canvas); 13010 } 13011 13012 mPrivateFlags = flags; 13013 13014 canvas.restoreToCount(restoreCount); 13015 canvas.setBitmap(null); 13016 13017 if (attachInfo != null) { 13018 // Restore the cached Canvas for our siblings 13019 attachInfo.mCanvas = canvas; 13020 } 13021 13022 return bitmap; 13023 } 13024 13025 /** 13026 * Indicates whether this View is currently in edit mode. A View is usually 13027 * in edit mode when displayed within a developer tool. For instance, if 13028 * this View is being drawn by a visual user interface builder, this method 13029 * should return true. 13030 * 13031 * Subclasses should check the return value of this method to provide 13032 * different behaviors if their normal behavior might interfere with the 13033 * host environment. For instance: the class spawns a thread in its 13034 * constructor, the drawing code relies on device-specific features, etc. 13035 * 13036 * This method is usually checked in the drawing code of custom widgets. 13037 * 13038 * @return True if this View is in edit mode, false otherwise. 13039 */ 13040 public boolean isInEditMode() { 13041 return false; 13042 } 13043 13044 /** 13045 * If the View draws content inside its padding and enables fading edges, 13046 * it needs to support padding offsets. Padding offsets are added to the 13047 * fading edges to extend the length of the fade so that it covers pixels 13048 * drawn inside the padding. 13049 * 13050 * Subclasses of this class should override this method if they need 13051 * to draw content inside the padding. 13052 * 13053 * @return True if padding offset must be applied, false otherwise. 13054 * 13055 * @see #getLeftPaddingOffset() 13056 * @see #getRightPaddingOffset() 13057 * @see #getTopPaddingOffset() 13058 * @see #getBottomPaddingOffset() 13059 * 13060 * @since CURRENT 13061 */ 13062 protected boolean isPaddingOffsetRequired() { 13063 return false; 13064 } 13065 13066 /** 13067 * Amount by which to extend the left fading region. Called only when 13068 * {@link #isPaddingOffsetRequired()} returns true. 13069 * 13070 * @return The left padding offset in pixels. 13071 * 13072 * @see #isPaddingOffsetRequired() 13073 * 13074 * @since CURRENT 13075 */ 13076 protected int getLeftPaddingOffset() { 13077 return 0; 13078 } 13079 13080 /** 13081 * Amount by which to extend the right fading region. Called only when 13082 * {@link #isPaddingOffsetRequired()} returns true. 13083 * 13084 * @return The right padding offset in pixels. 13085 * 13086 * @see #isPaddingOffsetRequired() 13087 * 13088 * @since CURRENT 13089 */ 13090 protected int getRightPaddingOffset() { 13091 return 0; 13092 } 13093 13094 /** 13095 * Amount by which to extend the top fading region. Called only when 13096 * {@link #isPaddingOffsetRequired()} returns true. 13097 * 13098 * @return The top padding offset in pixels. 13099 * 13100 * @see #isPaddingOffsetRequired() 13101 * 13102 * @since CURRENT 13103 */ 13104 protected int getTopPaddingOffset() { 13105 return 0; 13106 } 13107 13108 /** 13109 * Amount by which to extend the bottom fading region. Called only when 13110 * {@link #isPaddingOffsetRequired()} returns true. 13111 * 13112 * @return The bottom padding offset in pixels. 13113 * 13114 * @see #isPaddingOffsetRequired() 13115 * 13116 * @since CURRENT 13117 */ 13118 protected int getBottomPaddingOffset() { 13119 return 0; 13120 } 13121 13122 /** 13123 * @hide 13124 * @param offsetRequired 13125 */ 13126 protected int getFadeTop(boolean offsetRequired) { 13127 int top = mPaddingTop; 13128 if (offsetRequired) top += getTopPaddingOffset(); 13129 return top; 13130 } 13131 13132 /** 13133 * @hide 13134 * @param offsetRequired 13135 */ 13136 protected int getFadeHeight(boolean offsetRequired) { 13137 int padding = mPaddingTop; 13138 if (offsetRequired) padding += getTopPaddingOffset(); 13139 return mBottom - mTop - mPaddingBottom - padding; 13140 } 13141 13142 /** 13143 * <p>Indicates whether this view is attached to a hardware accelerated 13144 * window or not.</p> 13145 * 13146 * <p>Even if this method returns true, it does not mean that every call 13147 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 13148 * accelerated {@link android.graphics.Canvas}. For instance, if this view 13149 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 13150 * window is hardware accelerated, 13151 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 13152 * return false, and this method will return true.</p> 13153 * 13154 * @return True if the view is attached to a window and the window is 13155 * hardware accelerated; false in any other case. 13156 */ 13157 public boolean isHardwareAccelerated() { 13158 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13159 } 13160 13161 /** 13162 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 13163 * case of an active Animation being run on the view. 13164 */ 13165 private boolean drawAnimation(ViewGroup parent, long drawingTime, 13166 Animation a, boolean scalingRequired) { 13167 Transformation invalidationTransform; 13168 final int flags = parent.mGroupFlags; 13169 final boolean initialized = a.isInitialized(); 13170 if (!initialized) { 13171 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 13172 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 13173 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 13174 onAnimationStart(); 13175 } 13176 13177 boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f); 13178 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 13179 if (parent.mInvalidationTransformation == null) { 13180 parent.mInvalidationTransformation = new Transformation(); 13181 } 13182 invalidationTransform = parent.mInvalidationTransformation; 13183 a.getTransformation(drawingTime, invalidationTransform, 1f); 13184 } else { 13185 invalidationTransform = parent.mChildTransformation; 13186 } 13187 13188 if (more) { 13189 if (!a.willChangeBounds()) { 13190 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 13191 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 13192 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 13193 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 13194 // The child need to draw an animation, potentially offscreen, so 13195 // make sure we do not cancel invalidate requests 13196 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13197 parent.invalidate(mLeft, mTop, mRight, mBottom); 13198 } 13199 } else { 13200 if (parent.mInvalidateRegion == null) { 13201 parent.mInvalidateRegion = new RectF(); 13202 } 13203 final RectF region = parent.mInvalidateRegion; 13204 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 13205 invalidationTransform); 13206 13207 // The child need to draw an animation, potentially offscreen, so 13208 // make sure we do not cancel invalidate requests 13209 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13210 13211 final int left = mLeft + (int) region.left; 13212 final int top = mTop + (int) region.top; 13213 parent.invalidate(left, top, left + (int) (region.width() + .5f), 13214 top + (int) (region.height() + .5f)); 13215 } 13216 } 13217 return more; 13218 } 13219 13220 /** 13221 * This method is called by getDisplayList() when a display list is created or re-rendered. 13222 * It sets or resets the current value of all properties on that display list (resetting is 13223 * necessary when a display list is being re-created, because we need to make sure that 13224 * previously-set transform values 13225 */ 13226 void setDisplayListProperties(DisplayList displayList) { 13227 if (displayList != null) { 13228 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 13229 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 13230 if (mParent instanceof ViewGroup) { 13231 displayList.setClipChildren( 13232 (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 13233 } 13234 float alpha = 1; 13235 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 13236 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13237 ViewGroup parentVG = (ViewGroup) mParent; 13238 final boolean hasTransform = 13239 parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation); 13240 if (hasTransform) { 13241 Transformation transform = parentVG.mChildTransformation; 13242 final int transformType = parentVG.mChildTransformation.getTransformationType(); 13243 if (transformType != Transformation.TYPE_IDENTITY) { 13244 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 13245 alpha = transform.getAlpha(); 13246 } 13247 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 13248 displayList.setStaticMatrix(transform.getMatrix()); 13249 } 13250 } 13251 } 13252 } 13253 if (mTransformationInfo != null) { 13254 alpha *= mTransformationInfo.mAlpha; 13255 if (alpha < 1) { 13256 final int multipliedAlpha = (int) (255 * alpha); 13257 if (onSetAlpha(multipliedAlpha)) { 13258 alpha = 1; 13259 } 13260 } 13261 displayList.setTransformationInfo(alpha, 13262 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 13263 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 13264 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 13265 mTransformationInfo.mScaleY); 13266 if (mTransformationInfo.mCamera == null) { 13267 mTransformationInfo.mCamera = new Camera(); 13268 mTransformationInfo.matrix3D = new Matrix(); 13269 } 13270 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 13271 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) { 13272 displayList.setPivotX(getPivotX()); 13273 displayList.setPivotY(getPivotY()); 13274 } 13275 } else if (alpha < 1) { 13276 displayList.setAlpha(alpha); 13277 } 13278 } 13279 } 13280 13281 /** 13282 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 13283 * This draw() method is an implementation detail and is not intended to be overridden or 13284 * to be called from anywhere else other than ViewGroup.drawChild(). 13285 */ 13286 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 13287 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13288 boolean more = false; 13289 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 13290 final int flags = parent.mGroupFlags; 13291 13292 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 13293 parent.mChildTransformation.clear(); 13294 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13295 } 13296 13297 Transformation transformToApply = null; 13298 boolean concatMatrix = false; 13299 13300 boolean scalingRequired = false; 13301 boolean caching; 13302 int layerType = getLayerType(); 13303 13304 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 13305 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 13306 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 13307 caching = true; 13308 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 13309 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 13310 } else { 13311 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 13312 } 13313 13314 final Animation a = getAnimation(); 13315 if (a != null) { 13316 more = drawAnimation(parent, drawingTime, a, scalingRequired); 13317 concatMatrix = a.willChangeTransformationMatrix(); 13318 if (concatMatrix) { 13319 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13320 } 13321 transformToApply = parent.mChildTransformation; 13322 } else { 13323 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && 13324 mDisplayList != null) { 13325 // No longer animating: clear out old animation matrix 13326 mDisplayList.setAnimationMatrix(null); 13327 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13328 } 13329 if (!useDisplayListProperties && 13330 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13331 final boolean hasTransform = 13332 parent.getChildStaticTransformation(this, parent.mChildTransformation); 13333 if (hasTransform) { 13334 final int transformType = parent.mChildTransformation.getTransformationType(); 13335 transformToApply = transformType != Transformation.TYPE_IDENTITY ? 13336 parent.mChildTransformation : null; 13337 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 13338 } 13339 } 13340 } 13341 13342 concatMatrix |= !childHasIdentityMatrix; 13343 13344 // Sets the flag as early as possible to allow draw() implementations 13345 // to call invalidate() successfully when doing animations 13346 mPrivateFlags |= PFLAG_DRAWN; 13347 13348 if (!concatMatrix && 13349 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 13350 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 13351 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 13352 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 13353 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 13354 return more; 13355 } 13356 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 13357 13358 if (hardwareAccelerated) { 13359 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 13360 // retain the flag's value temporarily in the mRecreateDisplayList flag 13361 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 13362 mPrivateFlags &= ~PFLAG_INVALIDATED; 13363 } 13364 13365 DisplayList displayList = null; 13366 Bitmap cache = null; 13367 boolean hasDisplayList = false; 13368 if (caching) { 13369 if (!hardwareAccelerated) { 13370 if (layerType != LAYER_TYPE_NONE) { 13371 layerType = LAYER_TYPE_SOFTWARE; 13372 buildDrawingCache(true); 13373 } 13374 cache = getDrawingCache(true); 13375 } else { 13376 switch (layerType) { 13377 case LAYER_TYPE_SOFTWARE: 13378 if (useDisplayListProperties) { 13379 hasDisplayList = canHaveDisplayList(); 13380 } else { 13381 buildDrawingCache(true); 13382 cache = getDrawingCache(true); 13383 } 13384 break; 13385 case LAYER_TYPE_HARDWARE: 13386 if (useDisplayListProperties) { 13387 hasDisplayList = canHaveDisplayList(); 13388 } 13389 break; 13390 case LAYER_TYPE_NONE: 13391 // Delay getting the display list until animation-driven alpha values are 13392 // set up and possibly passed on to the view 13393 hasDisplayList = canHaveDisplayList(); 13394 break; 13395 } 13396 } 13397 } 13398 useDisplayListProperties &= hasDisplayList; 13399 if (useDisplayListProperties) { 13400 displayList = getDisplayList(); 13401 if (!displayList.isValid()) { 13402 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13403 // to getDisplayList(), the display list will be marked invalid and we should not 13404 // try to use it again. 13405 displayList = null; 13406 hasDisplayList = false; 13407 useDisplayListProperties = false; 13408 } 13409 } 13410 13411 int sx = 0; 13412 int sy = 0; 13413 if (!hasDisplayList) { 13414 computeScroll(); 13415 sx = mScrollX; 13416 sy = mScrollY; 13417 } 13418 13419 final boolean hasNoCache = cache == null || hasDisplayList; 13420 final boolean offsetForScroll = cache == null && !hasDisplayList && 13421 layerType != LAYER_TYPE_HARDWARE; 13422 13423 int restoreTo = -1; 13424 if (!useDisplayListProperties || transformToApply != null) { 13425 restoreTo = canvas.save(); 13426 } 13427 if (offsetForScroll) { 13428 canvas.translate(mLeft - sx, mTop - sy); 13429 } else { 13430 if (!useDisplayListProperties) { 13431 canvas.translate(mLeft, mTop); 13432 } 13433 if (scalingRequired) { 13434 if (useDisplayListProperties) { 13435 // TODO: Might not need this if we put everything inside the DL 13436 restoreTo = canvas.save(); 13437 } 13438 // mAttachInfo cannot be null, otherwise scalingRequired == false 13439 final float scale = 1.0f / mAttachInfo.mApplicationScale; 13440 canvas.scale(scale, scale); 13441 } 13442 } 13443 13444 float alpha = useDisplayListProperties ? 1 : getAlpha(); 13445 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 13446 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13447 if (transformToApply != null || !childHasIdentityMatrix) { 13448 int transX = 0; 13449 int transY = 0; 13450 13451 if (offsetForScroll) { 13452 transX = -sx; 13453 transY = -sy; 13454 } 13455 13456 if (transformToApply != null) { 13457 if (concatMatrix) { 13458 if (useDisplayListProperties) { 13459 displayList.setAnimationMatrix(transformToApply.getMatrix()); 13460 } else { 13461 // Undo the scroll translation, apply the transformation matrix, 13462 // then redo the scroll translate to get the correct result. 13463 canvas.translate(-transX, -transY); 13464 canvas.concat(transformToApply.getMatrix()); 13465 canvas.translate(transX, transY); 13466 } 13467 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13468 } 13469 13470 float transformAlpha = transformToApply.getAlpha(); 13471 if (transformAlpha < 1) { 13472 alpha *= transformAlpha; 13473 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13474 } 13475 } 13476 13477 if (!childHasIdentityMatrix && !useDisplayListProperties) { 13478 canvas.translate(-transX, -transY); 13479 canvas.concat(getMatrix()); 13480 canvas.translate(transX, transY); 13481 } 13482 } 13483 13484 // Deal with alpha if it is or used to be <1 13485 if (alpha < 1 || 13486 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13487 if (alpha < 1) { 13488 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13489 } else { 13490 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13491 } 13492 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13493 if (hasNoCache) { 13494 final int multipliedAlpha = (int) (255 * alpha); 13495 if (!onSetAlpha(multipliedAlpha)) { 13496 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13497 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 13498 layerType != LAYER_TYPE_NONE) { 13499 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 13500 } 13501 if (useDisplayListProperties) { 13502 displayList.setAlpha(alpha * getAlpha()); 13503 } else if (layerType == LAYER_TYPE_NONE) { 13504 final int scrollX = hasDisplayList ? 0 : sx; 13505 final int scrollY = hasDisplayList ? 0 : sy; 13506 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 13507 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 13508 } 13509 } else { 13510 // Alpha is handled by the child directly, clobber the layer's alpha 13511 mPrivateFlags |= PFLAG_ALPHA_SET; 13512 } 13513 } 13514 } 13515 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 13516 onSetAlpha(255); 13517 mPrivateFlags &= ~PFLAG_ALPHA_SET; 13518 } 13519 13520 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 13521 !useDisplayListProperties) { 13522 if (offsetForScroll) { 13523 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 13524 } else { 13525 if (!scalingRequired || cache == null) { 13526 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 13527 } else { 13528 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 13529 } 13530 } 13531 } 13532 13533 if (!useDisplayListProperties && hasDisplayList) { 13534 displayList = getDisplayList(); 13535 if (!displayList.isValid()) { 13536 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13537 // to getDisplayList(), the display list will be marked invalid and we should not 13538 // try to use it again. 13539 displayList = null; 13540 hasDisplayList = false; 13541 } 13542 } 13543 13544 if (hasNoCache) { 13545 boolean layerRendered = false; 13546 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 13547 final HardwareLayer layer = getHardwareLayer(); 13548 if (layer != null && layer.isValid()) { 13549 mLayerPaint.setAlpha((int) (alpha * 255)); 13550 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 13551 layerRendered = true; 13552 } else { 13553 final int scrollX = hasDisplayList ? 0 : sx; 13554 final int scrollY = hasDisplayList ? 0 : sy; 13555 canvas.saveLayer(scrollX, scrollY, 13556 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 13557 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13558 } 13559 } 13560 13561 if (!layerRendered) { 13562 if (!hasDisplayList) { 13563 // Fast path for layouts with no backgrounds 13564 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13565 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13566 dispatchDraw(canvas); 13567 } else { 13568 draw(canvas); 13569 } 13570 } else { 13571 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13572 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 13573 } 13574 } 13575 } else if (cache != null) { 13576 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13577 Paint cachePaint; 13578 13579 if (layerType == LAYER_TYPE_NONE) { 13580 cachePaint = parent.mCachePaint; 13581 if (cachePaint == null) { 13582 cachePaint = new Paint(); 13583 cachePaint.setDither(false); 13584 parent.mCachePaint = cachePaint; 13585 } 13586 if (alpha < 1) { 13587 cachePaint.setAlpha((int) (alpha * 255)); 13588 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13589 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 13590 cachePaint.setAlpha(255); 13591 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13592 } 13593 } else { 13594 cachePaint = mLayerPaint; 13595 cachePaint.setAlpha((int) (alpha * 255)); 13596 } 13597 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 13598 } 13599 13600 if (restoreTo >= 0) { 13601 canvas.restoreToCount(restoreTo); 13602 } 13603 13604 if (a != null && !more) { 13605 if (!hardwareAccelerated && !a.getFillAfter()) { 13606 onSetAlpha(255); 13607 } 13608 parent.finishAnimatingView(this, a); 13609 } 13610 13611 if (more && hardwareAccelerated) { 13612 // invalidation is the trigger to recreate display lists, so if we're using 13613 // display lists to render, force an invalidate to allow the animation to 13614 // continue drawing another frame 13615 parent.invalidate(true); 13616 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 13617 // alpha animations should cause the child to recreate its display list 13618 invalidate(true); 13619 } 13620 } 13621 13622 mRecreateDisplayList = false; 13623 13624 return more; 13625 } 13626 13627 /** 13628 * Manually render this view (and all of its children) to the given Canvas. 13629 * The view must have already done a full layout before this function is 13630 * called. When implementing a view, implement 13631 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 13632 * If you do need to override this method, call the superclass version. 13633 * 13634 * @param canvas The Canvas to which the View is rendered. 13635 */ 13636 public void draw(Canvas canvas) { 13637 final int privateFlags = mPrivateFlags; 13638 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 13639 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 13640 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 13641 13642 /* 13643 * Draw traversal performs several drawing steps which must be executed 13644 * in the appropriate order: 13645 * 13646 * 1. Draw the background 13647 * 2. If necessary, save the canvas' layers to prepare for fading 13648 * 3. Draw view's content 13649 * 4. Draw children 13650 * 5. If necessary, draw the fading edges and restore layers 13651 * 6. Draw decorations (scrollbars for instance) 13652 */ 13653 13654 // Step 1, draw the background, if needed 13655 int saveCount; 13656 13657 if (!dirtyOpaque) { 13658 final Drawable background = mBackground; 13659 if (background != null) { 13660 final int scrollX = mScrollX; 13661 final int scrollY = mScrollY; 13662 13663 if (mBackgroundSizeChanged) { 13664 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 13665 mBackgroundSizeChanged = false; 13666 } 13667 13668 if ((scrollX | scrollY) == 0) { 13669 background.draw(canvas); 13670 } else { 13671 canvas.translate(scrollX, scrollY); 13672 background.draw(canvas); 13673 canvas.translate(-scrollX, -scrollY); 13674 } 13675 } 13676 } 13677 13678 // skip step 2 & 5 if possible (common case) 13679 final int viewFlags = mViewFlags; 13680 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 13681 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 13682 if (!verticalEdges && !horizontalEdges) { 13683 // Step 3, draw the content 13684 if (!dirtyOpaque) onDraw(canvas); 13685 13686 // Step 4, draw the children 13687 dispatchDraw(canvas); 13688 13689 // Step 6, draw decorations (scrollbars) 13690 onDrawScrollBars(canvas); 13691 13692 // we're done... 13693 return; 13694 } 13695 13696 /* 13697 * Here we do the full fledged routine... 13698 * (this is an uncommon case where speed matters less, 13699 * this is why we repeat some of the tests that have been 13700 * done above) 13701 */ 13702 13703 boolean drawTop = false; 13704 boolean drawBottom = false; 13705 boolean drawLeft = false; 13706 boolean drawRight = false; 13707 13708 float topFadeStrength = 0.0f; 13709 float bottomFadeStrength = 0.0f; 13710 float leftFadeStrength = 0.0f; 13711 float rightFadeStrength = 0.0f; 13712 13713 // Step 2, save the canvas' layers 13714 int paddingLeft = mPaddingLeft; 13715 13716 final boolean offsetRequired = isPaddingOffsetRequired(); 13717 if (offsetRequired) { 13718 paddingLeft += getLeftPaddingOffset(); 13719 } 13720 13721 int left = mScrollX + paddingLeft; 13722 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 13723 int top = mScrollY + getFadeTop(offsetRequired); 13724 int bottom = top + getFadeHeight(offsetRequired); 13725 13726 if (offsetRequired) { 13727 right += getRightPaddingOffset(); 13728 bottom += getBottomPaddingOffset(); 13729 } 13730 13731 final ScrollabilityCache scrollabilityCache = mScrollCache; 13732 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 13733 int length = (int) fadeHeight; 13734 13735 // clip the fade length if top and bottom fades overlap 13736 // overlapping fades produce odd-looking artifacts 13737 if (verticalEdges && (top + length > bottom - length)) { 13738 length = (bottom - top) / 2; 13739 } 13740 13741 // also clip horizontal fades if necessary 13742 if (horizontalEdges && (left + length > right - length)) { 13743 length = (right - left) / 2; 13744 } 13745 13746 if (verticalEdges) { 13747 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 13748 drawTop = topFadeStrength * fadeHeight > 1.0f; 13749 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 13750 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 13751 } 13752 13753 if (horizontalEdges) { 13754 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 13755 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 13756 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 13757 drawRight = rightFadeStrength * fadeHeight > 1.0f; 13758 } 13759 13760 saveCount = canvas.getSaveCount(); 13761 13762 int solidColor = getSolidColor(); 13763 if (solidColor == 0) { 13764 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13765 13766 if (drawTop) { 13767 canvas.saveLayer(left, top, right, top + length, null, flags); 13768 } 13769 13770 if (drawBottom) { 13771 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 13772 } 13773 13774 if (drawLeft) { 13775 canvas.saveLayer(left, top, left + length, bottom, null, flags); 13776 } 13777 13778 if (drawRight) { 13779 canvas.saveLayer(right - length, top, right, bottom, null, flags); 13780 } 13781 } else { 13782 scrollabilityCache.setFadeColor(solidColor); 13783 } 13784 13785 // Step 3, draw the content 13786 if (!dirtyOpaque) onDraw(canvas); 13787 13788 // Step 4, draw the children 13789 dispatchDraw(canvas); 13790 13791 // Step 5, draw the fade effect and restore layers 13792 final Paint p = scrollabilityCache.paint; 13793 final Matrix matrix = scrollabilityCache.matrix; 13794 final Shader fade = scrollabilityCache.shader; 13795 13796 if (drawTop) { 13797 matrix.setScale(1, fadeHeight * topFadeStrength); 13798 matrix.postTranslate(left, top); 13799 fade.setLocalMatrix(matrix); 13800 canvas.drawRect(left, top, right, top + length, p); 13801 } 13802 13803 if (drawBottom) { 13804 matrix.setScale(1, fadeHeight * bottomFadeStrength); 13805 matrix.postRotate(180); 13806 matrix.postTranslate(left, bottom); 13807 fade.setLocalMatrix(matrix); 13808 canvas.drawRect(left, bottom - length, right, bottom, p); 13809 } 13810 13811 if (drawLeft) { 13812 matrix.setScale(1, fadeHeight * leftFadeStrength); 13813 matrix.postRotate(-90); 13814 matrix.postTranslate(left, top); 13815 fade.setLocalMatrix(matrix); 13816 canvas.drawRect(left, top, left + length, bottom, p); 13817 } 13818 13819 if (drawRight) { 13820 matrix.setScale(1, fadeHeight * rightFadeStrength); 13821 matrix.postRotate(90); 13822 matrix.postTranslate(right, top); 13823 fade.setLocalMatrix(matrix); 13824 canvas.drawRect(right - length, top, right, bottom, p); 13825 } 13826 13827 canvas.restoreToCount(saveCount); 13828 13829 // Step 6, draw decorations (scrollbars) 13830 onDrawScrollBars(canvas); 13831 } 13832 13833 /** 13834 * Override this if your view is known to always be drawn on top of a solid color background, 13835 * and needs to draw fading edges. Returning a non-zero color enables the view system to 13836 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 13837 * should be set to 0xFF. 13838 * 13839 * @see #setVerticalFadingEdgeEnabled(boolean) 13840 * @see #setHorizontalFadingEdgeEnabled(boolean) 13841 * 13842 * @return The known solid color background for this view, or 0 if the color may vary 13843 */ 13844 @ViewDebug.ExportedProperty(category = "drawing") 13845 public int getSolidColor() { 13846 return 0; 13847 } 13848 13849 /** 13850 * Build a human readable string representation of the specified view flags. 13851 * 13852 * @param flags the view flags to convert to a string 13853 * @return a String representing the supplied flags 13854 */ 13855 private static String printFlags(int flags) { 13856 String output = ""; 13857 int numFlags = 0; 13858 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 13859 output += "TAKES_FOCUS"; 13860 numFlags++; 13861 } 13862 13863 switch (flags & VISIBILITY_MASK) { 13864 case INVISIBLE: 13865 if (numFlags > 0) { 13866 output += " "; 13867 } 13868 output += "INVISIBLE"; 13869 // USELESS HERE numFlags++; 13870 break; 13871 case GONE: 13872 if (numFlags > 0) { 13873 output += " "; 13874 } 13875 output += "GONE"; 13876 // USELESS HERE numFlags++; 13877 break; 13878 default: 13879 break; 13880 } 13881 return output; 13882 } 13883 13884 /** 13885 * Build a human readable string representation of the specified private 13886 * view flags. 13887 * 13888 * @param privateFlags the private view flags to convert to a string 13889 * @return a String representing the supplied flags 13890 */ 13891 private static String printPrivateFlags(int privateFlags) { 13892 String output = ""; 13893 int numFlags = 0; 13894 13895 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 13896 output += "WANTS_FOCUS"; 13897 numFlags++; 13898 } 13899 13900 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 13901 if (numFlags > 0) { 13902 output += " "; 13903 } 13904 output += "FOCUSED"; 13905 numFlags++; 13906 } 13907 13908 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 13909 if (numFlags > 0) { 13910 output += " "; 13911 } 13912 output += "SELECTED"; 13913 numFlags++; 13914 } 13915 13916 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 13917 if (numFlags > 0) { 13918 output += " "; 13919 } 13920 output += "IS_ROOT_NAMESPACE"; 13921 numFlags++; 13922 } 13923 13924 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 13925 if (numFlags > 0) { 13926 output += " "; 13927 } 13928 output += "HAS_BOUNDS"; 13929 numFlags++; 13930 } 13931 13932 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 13933 if (numFlags > 0) { 13934 output += " "; 13935 } 13936 output += "DRAWN"; 13937 // USELESS HERE numFlags++; 13938 } 13939 return output; 13940 } 13941 13942 /** 13943 * <p>Indicates whether or not this view's layout will be requested during 13944 * the next hierarchy layout pass.</p> 13945 * 13946 * @return true if the layout will be forced during next layout pass 13947 */ 13948 public boolean isLayoutRequested() { 13949 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 13950 } 13951 13952 /** 13953 * Assign a size and position to a view and all of its 13954 * descendants 13955 * 13956 * <p>This is the second phase of the layout mechanism. 13957 * (The first is measuring). In this phase, each parent calls 13958 * layout on all of its children to position them. 13959 * This is typically done using the child measurements 13960 * that were stored in the measure pass().</p> 13961 * 13962 * <p>Derived classes should not override this method. 13963 * Derived classes with children should override 13964 * onLayout. In that method, they should 13965 * call layout on each of their children.</p> 13966 * 13967 * @param l Left position, relative to parent 13968 * @param t Top position, relative to parent 13969 * @param r Right position, relative to parent 13970 * @param b Bottom position, relative to parent 13971 */ 13972 @SuppressWarnings({"unchecked"}) 13973 public void layout(int l, int t, int r, int b) { 13974 int oldL = mLeft; 13975 int oldT = mTop; 13976 int oldB = mBottom; 13977 int oldR = mRight; 13978 boolean changed = setFrame(l, t, r, b); 13979 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 13980 onLayout(changed, l, t, r, b); 13981 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 13982 13983 ListenerInfo li = mListenerInfo; 13984 if (li != null && li.mOnLayoutChangeListeners != null) { 13985 ArrayList<OnLayoutChangeListener> listenersCopy = 13986 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 13987 int numListeners = listenersCopy.size(); 13988 for (int i = 0; i < numListeners; ++i) { 13989 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 13990 } 13991 } 13992 } 13993 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 13994 } 13995 13996 /** 13997 * Called from layout when this view should 13998 * assign a size and position to each of its children. 13999 * 14000 * Derived classes with children should override 14001 * this method and call layout on each of 14002 * their children. 14003 * @param changed This is a new size or position for this view 14004 * @param left Left position, relative to parent 14005 * @param top Top position, relative to parent 14006 * @param right Right position, relative to parent 14007 * @param bottom Bottom position, relative to parent 14008 */ 14009 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 14010 } 14011 14012 /** 14013 * Assign a size and position to this view. 14014 * 14015 * This is called from layout. 14016 * 14017 * @param left Left position, relative to parent 14018 * @param top Top position, relative to parent 14019 * @param right Right position, relative to parent 14020 * @param bottom Bottom position, relative to parent 14021 * @return true if the new size and position are different than the 14022 * previous ones 14023 * {@hide} 14024 */ 14025 protected boolean setFrame(int left, int top, int right, int bottom) { 14026 boolean changed = false; 14027 14028 if (DBG) { 14029 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 14030 + right + "," + bottom + ")"); 14031 } 14032 14033 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 14034 changed = true; 14035 14036 // Remember our drawn bit 14037 int drawn = mPrivateFlags & PFLAG_DRAWN; 14038 14039 int oldWidth = mRight - mLeft; 14040 int oldHeight = mBottom - mTop; 14041 int newWidth = right - left; 14042 int newHeight = bottom - top; 14043 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 14044 14045 // Invalidate our old position 14046 invalidate(sizeChanged); 14047 14048 mLeft = left; 14049 mTop = top; 14050 mRight = right; 14051 mBottom = bottom; 14052 if (mDisplayList != null) { 14053 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 14054 } 14055 14056 mPrivateFlags |= PFLAG_HAS_BOUNDS; 14057 14058 14059 if (sizeChanged) { 14060 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 14061 // A change in dimension means an auto-centered pivot point changes, too 14062 if (mTransformationInfo != null) { 14063 mTransformationInfo.mMatrixDirty = true; 14064 } 14065 } 14066 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 14067 } 14068 14069 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 14070 // If we are visible, force the DRAWN bit to on so that 14071 // this invalidate will go through (at least to our parent). 14072 // This is because someone may have invalidated this view 14073 // before this call to setFrame came in, thereby clearing 14074 // the DRAWN bit. 14075 mPrivateFlags |= PFLAG_DRAWN; 14076 invalidate(sizeChanged); 14077 // parent display list may need to be recreated based on a change in the bounds 14078 // of any child 14079 invalidateParentCaches(); 14080 } 14081 14082 // Reset drawn bit to original value (invalidate turns it off) 14083 mPrivateFlags |= drawn; 14084 14085 mBackgroundSizeChanged = true; 14086 } 14087 return changed; 14088 } 14089 14090 /** 14091 * Finalize inflating a view from XML. This is called as the last phase 14092 * of inflation, after all child views have been added. 14093 * 14094 * <p>Even if the subclass overrides onFinishInflate, they should always be 14095 * sure to call the super method, so that we get called. 14096 */ 14097 protected void onFinishInflate() { 14098 } 14099 14100 /** 14101 * Returns the resources associated with this view. 14102 * 14103 * @return Resources object. 14104 */ 14105 public Resources getResources() { 14106 return mResources; 14107 } 14108 14109 /** 14110 * Invalidates the specified Drawable. 14111 * 14112 * @param drawable the drawable to invalidate 14113 */ 14114 public void invalidateDrawable(Drawable drawable) { 14115 if (verifyDrawable(drawable)) { 14116 final Rect dirty = drawable.getBounds(); 14117 final int scrollX = mScrollX; 14118 final int scrollY = mScrollY; 14119 14120 invalidate(dirty.left + scrollX, dirty.top + scrollY, 14121 dirty.right + scrollX, dirty.bottom + scrollY); 14122 } 14123 } 14124 14125 /** 14126 * Schedules an action on a drawable to occur at a specified time. 14127 * 14128 * @param who the recipient of the action 14129 * @param what the action to run on the drawable 14130 * @param when the time at which the action must occur. Uses the 14131 * {@link SystemClock#uptimeMillis} timebase. 14132 */ 14133 public void scheduleDrawable(Drawable who, Runnable what, long when) { 14134 if (verifyDrawable(who) && what != null) { 14135 final long delay = when - SystemClock.uptimeMillis(); 14136 if (mAttachInfo != null) { 14137 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 14138 Choreographer.CALLBACK_ANIMATION, what, who, 14139 Choreographer.subtractFrameDelay(delay)); 14140 } else { 14141 ViewRootImpl.getRunQueue().postDelayed(what, delay); 14142 } 14143 } 14144 } 14145 14146 /** 14147 * Cancels a scheduled action on a drawable. 14148 * 14149 * @param who the recipient of the action 14150 * @param what the action to cancel 14151 */ 14152 public void unscheduleDrawable(Drawable who, Runnable what) { 14153 if (verifyDrawable(who) && what != null) { 14154 if (mAttachInfo != null) { 14155 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14156 Choreographer.CALLBACK_ANIMATION, what, who); 14157 } else { 14158 ViewRootImpl.getRunQueue().removeCallbacks(what); 14159 } 14160 } 14161 } 14162 14163 /** 14164 * Unschedule any events associated with the given Drawable. This can be 14165 * used when selecting a new Drawable into a view, so that the previous 14166 * one is completely unscheduled. 14167 * 14168 * @param who The Drawable to unschedule. 14169 * 14170 * @see #drawableStateChanged 14171 */ 14172 public void unscheduleDrawable(Drawable who) { 14173 if (mAttachInfo != null && who != null) { 14174 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14175 Choreographer.CALLBACK_ANIMATION, null, who); 14176 } 14177 } 14178 14179 /** 14180 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 14181 * that the View directionality can and will be resolved before its Drawables. 14182 * 14183 * Will call {@link View#onResolveDrawables} when resolution is done. 14184 * 14185 * @hide 14186 */ 14187 public void resolveDrawables() { 14188 if (mBackground != null) { 14189 mBackground.setLayoutDirection(getLayoutDirection()); 14190 } 14191 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 14192 onResolveDrawables(getLayoutDirection()); 14193 } 14194 14195 /** 14196 * Called when layout direction has been resolved. 14197 * 14198 * The default implementation does nothing. 14199 * 14200 * @param layoutDirection The resolved layout direction. 14201 * 14202 * @see #LAYOUT_DIRECTION_LTR 14203 * @see #LAYOUT_DIRECTION_RTL 14204 * 14205 * @hide 14206 */ 14207 public void onResolveDrawables(int layoutDirection) { 14208 } 14209 14210 private void resetResolvedDrawables() { 14211 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 14212 } 14213 14214 private boolean isDrawablesResolved() { 14215 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 14216 } 14217 14218 /** 14219 * If your view subclass is displaying its own Drawable objects, it should 14220 * override this function and return true for any Drawable it is 14221 * displaying. This allows animations for those drawables to be 14222 * scheduled. 14223 * 14224 * <p>Be sure to call through to the super class when overriding this 14225 * function. 14226 * 14227 * @param who The Drawable to verify. Return true if it is one you are 14228 * displaying, else return the result of calling through to the 14229 * super class. 14230 * 14231 * @return boolean If true than the Drawable is being displayed in the 14232 * view; else false and it is not allowed to animate. 14233 * 14234 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 14235 * @see #drawableStateChanged() 14236 */ 14237 protected boolean verifyDrawable(Drawable who) { 14238 return who == mBackground; 14239 } 14240 14241 /** 14242 * This function is called whenever the state of the view changes in such 14243 * a way that it impacts the state of drawables being shown. 14244 * 14245 * <p>Be sure to call through to the superclass when overriding this 14246 * function. 14247 * 14248 * @see Drawable#setState(int[]) 14249 */ 14250 protected void drawableStateChanged() { 14251 Drawable d = mBackground; 14252 if (d != null && d.isStateful()) { 14253 d.setState(getDrawableState()); 14254 } 14255 } 14256 14257 /** 14258 * Call this to force a view to update its drawable state. This will cause 14259 * drawableStateChanged to be called on this view. Views that are interested 14260 * in the new state should call getDrawableState. 14261 * 14262 * @see #drawableStateChanged 14263 * @see #getDrawableState 14264 */ 14265 public void refreshDrawableState() { 14266 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 14267 drawableStateChanged(); 14268 14269 ViewParent parent = mParent; 14270 if (parent != null) { 14271 parent.childDrawableStateChanged(this); 14272 } 14273 } 14274 14275 /** 14276 * Return an array of resource IDs of the drawable states representing the 14277 * current state of the view. 14278 * 14279 * @return The current drawable state 14280 * 14281 * @see Drawable#setState(int[]) 14282 * @see #drawableStateChanged() 14283 * @see #onCreateDrawableState(int) 14284 */ 14285 public final int[] getDrawableState() { 14286 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 14287 return mDrawableState; 14288 } else { 14289 mDrawableState = onCreateDrawableState(0); 14290 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 14291 return mDrawableState; 14292 } 14293 } 14294 14295 /** 14296 * Generate the new {@link android.graphics.drawable.Drawable} state for 14297 * this view. This is called by the view 14298 * system when the cached Drawable state is determined to be invalid. To 14299 * retrieve the current state, you should use {@link #getDrawableState}. 14300 * 14301 * @param extraSpace if non-zero, this is the number of extra entries you 14302 * would like in the returned array in which you can place your own 14303 * states. 14304 * 14305 * @return Returns an array holding the current {@link Drawable} state of 14306 * the view. 14307 * 14308 * @see #mergeDrawableStates(int[], int[]) 14309 */ 14310 protected int[] onCreateDrawableState(int extraSpace) { 14311 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 14312 mParent instanceof View) { 14313 return ((View) mParent).onCreateDrawableState(extraSpace); 14314 } 14315 14316 int[] drawableState; 14317 14318 int privateFlags = mPrivateFlags; 14319 14320 int viewStateIndex = 0; 14321 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 14322 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 14323 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 14324 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 14325 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 14326 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 14327 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 14328 HardwareRenderer.isAvailable()) { 14329 // This is set if HW acceleration is requested, even if the current 14330 // process doesn't allow it. This is just to allow app preview 14331 // windows to better match their app. 14332 viewStateIndex |= VIEW_STATE_ACCELERATED; 14333 } 14334 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 14335 14336 final int privateFlags2 = mPrivateFlags2; 14337 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 14338 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 14339 14340 drawableState = VIEW_STATE_SETS[viewStateIndex]; 14341 14342 //noinspection ConstantIfStatement 14343 if (false) { 14344 Log.i("View", "drawableStateIndex=" + viewStateIndex); 14345 Log.i("View", toString() 14346 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 14347 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 14348 + " fo=" + hasFocus() 14349 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 14350 + " wf=" + hasWindowFocus() 14351 + ": " + Arrays.toString(drawableState)); 14352 } 14353 14354 if (extraSpace == 0) { 14355 return drawableState; 14356 } 14357 14358 final int[] fullState; 14359 if (drawableState != null) { 14360 fullState = new int[drawableState.length + extraSpace]; 14361 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 14362 } else { 14363 fullState = new int[extraSpace]; 14364 } 14365 14366 return fullState; 14367 } 14368 14369 /** 14370 * Merge your own state values in <var>additionalState</var> into the base 14371 * state values <var>baseState</var> that were returned by 14372 * {@link #onCreateDrawableState(int)}. 14373 * 14374 * @param baseState The base state values returned by 14375 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 14376 * own additional state values. 14377 * 14378 * @param additionalState The additional state values you would like 14379 * added to <var>baseState</var>; this array is not modified. 14380 * 14381 * @return As a convenience, the <var>baseState</var> array you originally 14382 * passed into the function is returned. 14383 * 14384 * @see #onCreateDrawableState(int) 14385 */ 14386 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 14387 final int N = baseState.length; 14388 int i = N - 1; 14389 while (i >= 0 && baseState[i] == 0) { 14390 i--; 14391 } 14392 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 14393 return baseState; 14394 } 14395 14396 /** 14397 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 14398 * on all Drawable objects associated with this view. 14399 */ 14400 public void jumpDrawablesToCurrentState() { 14401 if (mBackground != null) { 14402 mBackground.jumpToCurrentState(); 14403 } 14404 } 14405 14406 /** 14407 * Sets the background color for this view. 14408 * @param color the color of the background 14409 */ 14410 @RemotableViewMethod 14411 public void setBackgroundColor(int color) { 14412 if (mBackground instanceof ColorDrawable) { 14413 ((ColorDrawable) mBackground.mutate()).setColor(color); 14414 computeOpaqueFlags(); 14415 } else { 14416 setBackground(new ColorDrawable(color)); 14417 } 14418 } 14419 14420 /** 14421 * Set the background to a given resource. The resource should refer to 14422 * a Drawable object or 0 to remove the background. 14423 * @param resid The identifier of the resource. 14424 * 14425 * @attr ref android.R.styleable#View_background 14426 */ 14427 @RemotableViewMethod 14428 public void setBackgroundResource(int resid) { 14429 if (resid != 0 && resid == mBackgroundResource) { 14430 return; 14431 } 14432 14433 Drawable d= null; 14434 if (resid != 0) { 14435 d = mResources.getDrawable(resid); 14436 } 14437 setBackground(d); 14438 14439 mBackgroundResource = resid; 14440 } 14441 14442 /** 14443 * Set the background to a given Drawable, or remove the background. If the 14444 * background has padding, this View's padding is set to the background's 14445 * padding. However, when a background is removed, this View's padding isn't 14446 * touched. If setting the padding is desired, please use 14447 * {@link #setPadding(int, int, int, int)}. 14448 * 14449 * @param background The Drawable to use as the background, or null to remove the 14450 * background 14451 */ 14452 public void setBackground(Drawable background) { 14453 //noinspection deprecation 14454 setBackgroundDrawable(background); 14455 } 14456 14457 /** 14458 * @deprecated use {@link #setBackground(Drawable)} instead 14459 */ 14460 @Deprecated 14461 public void setBackgroundDrawable(Drawable background) { 14462 computeOpaqueFlags(); 14463 14464 if (background == mBackground) { 14465 return; 14466 } 14467 14468 boolean requestLayout = false; 14469 14470 mBackgroundResource = 0; 14471 14472 /* 14473 * Regardless of whether we're setting a new background or not, we want 14474 * to clear the previous drawable. 14475 */ 14476 if (mBackground != null) { 14477 mBackground.setCallback(null); 14478 unscheduleDrawable(mBackground); 14479 } 14480 14481 if (background != null) { 14482 Rect padding = sThreadLocal.get(); 14483 if (padding == null) { 14484 padding = new Rect(); 14485 sThreadLocal.set(padding); 14486 } 14487 resetResolvedDrawables(); 14488 background.setLayoutDirection(getLayoutDirection()); 14489 if (background.getPadding(padding)) { 14490 resetResolvedPadding(); 14491 switch (background.getLayoutDirection()) { 14492 case LAYOUT_DIRECTION_RTL: 14493 mUserPaddingLeftInitial = padding.right; 14494 mUserPaddingRightInitial = padding.left; 14495 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 14496 break; 14497 case LAYOUT_DIRECTION_LTR: 14498 default: 14499 mUserPaddingLeftInitial = padding.left; 14500 mUserPaddingRightInitial = padding.right; 14501 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 14502 } 14503 } 14504 14505 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 14506 // if it has a different minimum size, we should layout again 14507 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 14508 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 14509 requestLayout = true; 14510 } 14511 14512 background.setCallback(this); 14513 if (background.isStateful()) { 14514 background.setState(getDrawableState()); 14515 } 14516 background.setVisible(getVisibility() == VISIBLE, false); 14517 mBackground = background; 14518 14519 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 14520 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 14521 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 14522 requestLayout = true; 14523 } 14524 } else { 14525 /* Remove the background */ 14526 mBackground = null; 14527 14528 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 14529 /* 14530 * This view ONLY drew the background before and we're removing 14531 * the background, so now it won't draw anything 14532 * (hence we SKIP_DRAW) 14533 */ 14534 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 14535 mPrivateFlags |= PFLAG_SKIP_DRAW; 14536 } 14537 14538 /* 14539 * When the background is set, we try to apply its padding to this 14540 * View. When the background is removed, we don't touch this View's 14541 * padding. This is noted in the Javadocs. Hence, we don't need to 14542 * requestLayout(), the invalidate() below is sufficient. 14543 */ 14544 14545 // The old background's minimum size could have affected this 14546 // View's layout, so let's requestLayout 14547 requestLayout = true; 14548 } 14549 14550 computeOpaqueFlags(); 14551 14552 if (requestLayout) { 14553 requestLayout(); 14554 } 14555 14556 mBackgroundSizeChanged = true; 14557 invalidate(true); 14558 } 14559 14560 /** 14561 * Gets the background drawable 14562 * 14563 * @return The drawable used as the background for this view, if any. 14564 * 14565 * @see #setBackground(Drawable) 14566 * 14567 * @attr ref android.R.styleable#View_background 14568 */ 14569 public Drawable getBackground() { 14570 return mBackground; 14571 } 14572 14573 /** 14574 * Sets the padding. The view may add on the space required to display 14575 * the scrollbars, depending on the style and visibility of the scrollbars. 14576 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 14577 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 14578 * from the values set in this call. 14579 * 14580 * @attr ref android.R.styleable#View_padding 14581 * @attr ref android.R.styleable#View_paddingBottom 14582 * @attr ref android.R.styleable#View_paddingLeft 14583 * @attr ref android.R.styleable#View_paddingRight 14584 * @attr ref android.R.styleable#View_paddingTop 14585 * @param left the left padding in pixels 14586 * @param top the top padding in pixels 14587 * @param right the right padding in pixels 14588 * @param bottom the bottom padding in pixels 14589 */ 14590 public void setPadding(int left, int top, int right, int bottom) { 14591 resetResolvedPadding(); 14592 14593 mUserPaddingStart = UNDEFINED_PADDING; 14594 mUserPaddingEnd = UNDEFINED_PADDING; 14595 14596 mUserPaddingLeftInitial = left; 14597 mUserPaddingRightInitial = right; 14598 14599 internalSetPadding(left, top, right, bottom); 14600 } 14601 14602 /** 14603 * @hide 14604 */ 14605 protected void internalSetPadding(int left, int top, int right, int bottom) { 14606 mUserPaddingLeft = left; 14607 mUserPaddingRight = right; 14608 mUserPaddingBottom = bottom; 14609 14610 final int viewFlags = mViewFlags; 14611 boolean changed = false; 14612 14613 // Common case is there are no scroll bars. 14614 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 14615 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 14616 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 14617 ? 0 : getVerticalScrollbarWidth(); 14618 switch (mVerticalScrollbarPosition) { 14619 case SCROLLBAR_POSITION_DEFAULT: 14620 if (isLayoutRtl()) { 14621 left += offset; 14622 } else { 14623 right += offset; 14624 } 14625 break; 14626 case SCROLLBAR_POSITION_RIGHT: 14627 right += offset; 14628 break; 14629 case SCROLLBAR_POSITION_LEFT: 14630 left += offset; 14631 break; 14632 } 14633 } 14634 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 14635 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 14636 ? 0 : getHorizontalScrollbarHeight(); 14637 } 14638 } 14639 14640 if (mPaddingLeft != left) { 14641 changed = true; 14642 mPaddingLeft = left; 14643 } 14644 if (mPaddingTop != top) { 14645 changed = true; 14646 mPaddingTop = top; 14647 } 14648 if (mPaddingRight != right) { 14649 changed = true; 14650 mPaddingRight = right; 14651 } 14652 if (mPaddingBottom != bottom) { 14653 changed = true; 14654 mPaddingBottom = bottom; 14655 } 14656 14657 if (changed) { 14658 requestLayout(); 14659 } 14660 } 14661 14662 /** 14663 * Sets the relative padding. The view may add on the space required to display 14664 * the scrollbars, depending on the style and visibility of the scrollbars. 14665 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 14666 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 14667 * from the values set in this call. 14668 * 14669 * @attr ref android.R.styleable#View_padding 14670 * @attr ref android.R.styleable#View_paddingBottom 14671 * @attr ref android.R.styleable#View_paddingStart 14672 * @attr ref android.R.styleable#View_paddingEnd 14673 * @attr ref android.R.styleable#View_paddingTop 14674 * @param start the start padding in pixels 14675 * @param top the top padding in pixels 14676 * @param end the end padding in pixels 14677 * @param bottom the bottom padding in pixels 14678 */ 14679 public void setPaddingRelative(int start, int top, int end, int bottom) { 14680 resetResolvedPadding(); 14681 14682 mUserPaddingStart = start; 14683 mUserPaddingEnd = end; 14684 14685 switch(getLayoutDirection()) { 14686 case LAYOUT_DIRECTION_RTL: 14687 mUserPaddingLeftInitial = end; 14688 mUserPaddingRightInitial = start; 14689 internalSetPadding(end, top, start, bottom); 14690 break; 14691 case LAYOUT_DIRECTION_LTR: 14692 default: 14693 mUserPaddingLeftInitial = start; 14694 mUserPaddingRightInitial = end; 14695 internalSetPadding(start, top, end, bottom); 14696 } 14697 } 14698 14699 /** 14700 * Returns the top padding of this view. 14701 * 14702 * @return the top padding in pixels 14703 */ 14704 public int getPaddingTop() { 14705 return mPaddingTop; 14706 } 14707 14708 /** 14709 * Returns the bottom padding of this view. If there are inset and enabled 14710 * scrollbars, this value may include the space required to display the 14711 * scrollbars as well. 14712 * 14713 * @return the bottom padding in pixels 14714 */ 14715 public int getPaddingBottom() { 14716 return mPaddingBottom; 14717 } 14718 14719 /** 14720 * Returns the left padding of this view. If there are inset and enabled 14721 * scrollbars, this value may include the space required to display the 14722 * scrollbars as well. 14723 * 14724 * @return the left padding in pixels 14725 */ 14726 public int getPaddingLeft() { 14727 if (!isPaddingResolved()) { 14728 resolvePadding(); 14729 } 14730 return mPaddingLeft; 14731 } 14732 14733 /** 14734 * Returns the start padding of this view depending on its resolved layout direction. 14735 * If there are inset and enabled scrollbars, this value may include the space 14736 * required to display the scrollbars as well. 14737 * 14738 * @return the start padding in pixels 14739 */ 14740 public int getPaddingStart() { 14741 if (!isPaddingResolved()) { 14742 resolvePadding(); 14743 } 14744 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 14745 mPaddingRight : mPaddingLeft; 14746 } 14747 14748 /** 14749 * Returns the right padding of this view. If there are inset and enabled 14750 * scrollbars, this value may include the space required to display the 14751 * scrollbars as well. 14752 * 14753 * @return the right padding in pixels 14754 */ 14755 public int getPaddingRight() { 14756 if (!isPaddingResolved()) { 14757 resolvePadding(); 14758 } 14759 return mPaddingRight; 14760 } 14761 14762 /** 14763 * Returns the end padding of this view depending on its resolved layout direction. 14764 * If there are inset and enabled scrollbars, this value may include the space 14765 * required to display the scrollbars as well. 14766 * 14767 * @return the end padding in pixels 14768 */ 14769 public int getPaddingEnd() { 14770 if (!isPaddingResolved()) { 14771 resolvePadding(); 14772 } 14773 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 14774 mPaddingLeft : mPaddingRight; 14775 } 14776 14777 /** 14778 * Return if the padding as been set thru relative values 14779 * {@link #setPaddingRelative(int, int, int, int)} or thru 14780 * @attr ref android.R.styleable#View_paddingStart or 14781 * @attr ref android.R.styleable#View_paddingEnd 14782 * 14783 * @return true if the padding is relative or false if it is not. 14784 */ 14785 public boolean isPaddingRelative() { 14786 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 14787 } 14788 14789 /** 14790 * @hide 14791 */ 14792 public void resetPaddingToInitialValues() { 14793 if (isRtlCompatibilityMode()) { 14794 mPaddingLeft = mUserPaddingLeftInitial; 14795 mPaddingRight = mUserPaddingRightInitial; 14796 } else { 14797 if (isLayoutRtl()) { 14798 mPaddingLeft = mUserPaddingRightInitial; 14799 mPaddingRight = mUserPaddingLeftInitial; 14800 } else { 14801 mPaddingLeft = mUserPaddingLeftInitial; 14802 mPaddingRight = mUserPaddingRightInitial; 14803 } 14804 } 14805 } 14806 14807 /** 14808 * @hide 14809 */ 14810 public Insets getOpticalInsets() { 14811 if (mLayoutInsets == null) { 14812 mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets(); 14813 } 14814 return mLayoutInsets; 14815 } 14816 14817 /** 14818 * @hide 14819 */ 14820 public void setLayoutInsets(Insets layoutInsets) { 14821 mLayoutInsets = layoutInsets; 14822 } 14823 14824 /** 14825 * Changes the selection state of this view. A view can be selected or not. 14826 * Note that selection is not the same as focus. Views are typically 14827 * selected in the context of an AdapterView like ListView or GridView; 14828 * the selected view is the view that is highlighted. 14829 * 14830 * @param selected true if the view must be selected, false otherwise 14831 */ 14832 public void setSelected(boolean selected) { 14833 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 14834 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 14835 if (!selected) resetPressedState(); 14836 invalidate(true); 14837 refreshDrawableState(); 14838 dispatchSetSelected(selected); 14839 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 14840 notifyAccessibilityStateChanged(); 14841 } 14842 } 14843 } 14844 14845 /** 14846 * Dispatch setSelected to all of this View's children. 14847 * 14848 * @see #setSelected(boolean) 14849 * 14850 * @param selected The new selected state 14851 */ 14852 protected void dispatchSetSelected(boolean selected) { 14853 } 14854 14855 /** 14856 * Indicates the selection state of this view. 14857 * 14858 * @return true if the view is selected, false otherwise 14859 */ 14860 @ViewDebug.ExportedProperty 14861 public boolean isSelected() { 14862 return (mPrivateFlags & PFLAG_SELECTED) != 0; 14863 } 14864 14865 /** 14866 * Changes the activated state of this view. A view can be activated or not. 14867 * Note that activation is not the same as selection. Selection is 14868 * a transient property, representing the view (hierarchy) the user is 14869 * currently interacting with. Activation is a longer-term state that the 14870 * user can move views in and out of. For example, in a list view with 14871 * single or multiple selection enabled, the views in the current selection 14872 * set are activated. (Um, yeah, we are deeply sorry about the terminology 14873 * here.) The activated state is propagated down to children of the view it 14874 * is set on. 14875 * 14876 * @param activated true if the view must be activated, false otherwise 14877 */ 14878 public void setActivated(boolean activated) { 14879 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 14880 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 14881 invalidate(true); 14882 refreshDrawableState(); 14883 dispatchSetActivated(activated); 14884 } 14885 } 14886 14887 /** 14888 * Dispatch setActivated to all of this View's children. 14889 * 14890 * @see #setActivated(boolean) 14891 * 14892 * @param activated The new activated state 14893 */ 14894 protected void dispatchSetActivated(boolean activated) { 14895 } 14896 14897 /** 14898 * Indicates the activation state of this view. 14899 * 14900 * @return true if the view is activated, false otherwise 14901 */ 14902 @ViewDebug.ExportedProperty 14903 public boolean isActivated() { 14904 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 14905 } 14906 14907 /** 14908 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 14909 * observer can be used to get notifications when global events, like 14910 * layout, happen. 14911 * 14912 * The returned ViewTreeObserver observer is not guaranteed to remain 14913 * valid for the lifetime of this View. If the caller of this method keeps 14914 * a long-lived reference to ViewTreeObserver, it should always check for 14915 * the return value of {@link ViewTreeObserver#isAlive()}. 14916 * 14917 * @return The ViewTreeObserver for this view's hierarchy. 14918 */ 14919 public ViewTreeObserver getViewTreeObserver() { 14920 if (mAttachInfo != null) { 14921 return mAttachInfo.mTreeObserver; 14922 } 14923 if (mFloatingTreeObserver == null) { 14924 mFloatingTreeObserver = new ViewTreeObserver(); 14925 } 14926 return mFloatingTreeObserver; 14927 } 14928 14929 /** 14930 * <p>Finds the topmost view in the current view hierarchy.</p> 14931 * 14932 * @return the topmost view containing this view 14933 */ 14934 public View getRootView() { 14935 if (mAttachInfo != null) { 14936 final View v = mAttachInfo.mRootView; 14937 if (v != null) { 14938 return v; 14939 } 14940 } 14941 14942 View parent = this; 14943 14944 while (parent.mParent != null && parent.mParent instanceof View) { 14945 parent = (View) parent.mParent; 14946 } 14947 14948 return parent; 14949 } 14950 14951 /** 14952 * <p>Computes the coordinates of this view on the screen. The argument 14953 * must be an array of two integers. After the method returns, the array 14954 * contains the x and y location in that order.</p> 14955 * 14956 * @param location an array of two integers in which to hold the coordinates 14957 */ 14958 public void getLocationOnScreen(int[] location) { 14959 getLocationInWindow(location); 14960 14961 final AttachInfo info = mAttachInfo; 14962 if (info != null) { 14963 location[0] += info.mWindowLeft; 14964 location[1] += info.mWindowTop; 14965 } 14966 } 14967 14968 /** 14969 * <p>Computes the coordinates of this view in its window. The argument 14970 * must be an array of two integers. After the method returns, the array 14971 * contains the x and y location in that order.</p> 14972 * 14973 * @param location an array of two integers in which to hold the coordinates 14974 */ 14975 public void getLocationInWindow(int[] location) { 14976 if (location == null || location.length < 2) { 14977 throw new IllegalArgumentException("location must be an array of two integers"); 14978 } 14979 14980 if (mAttachInfo == null) { 14981 // When the view is not attached to a window, this method does not make sense 14982 location[0] = location[1] = 0; 14983 return; 14984 } 14985 14986 float[] position = mAttachInfo.mTmpTransformLocation; 14987 position[0] = position[1] = 0.0f; 14988 14989 if (!hasIdentityMatrix()) { 14990 getMatrix().mapPoints(position); 14991 } 14992 14993 position[0] += mLeft; 14994 position[1] += mTop; 14995 14996 ViewParent viewParent = mParent; 14997 while (viewParent instanceof View) { 14998 final View view = (View) viewParent; 14999 15000 position[0] -= view.mScrollX; 15001 position[1] -= view.mScrollY; 15002 15003 if (!view.hasIdentityMatrix()) { 15004 view.getMatrix().mapPoints(position); 15005 } 15006 15007 position[0] += view.mLeft; 15008 position[1] += view.mTop; 15009 15010 viewParent = view.mParent; 15011 } 15012 15013 if (viewParent instanceof ViewRootImpl) { 15014 // *cough* 15015 final ViewRootImpl vr = (ViewRootImpl) viewParent; 15016 position[1] -= vr.mCurScrollY; 15017 } 15018 15019 location[0] = (int) (position[0] + 0.5f); 15020 location[1] = (int) (position[1] + 0.5f); 15021 } 15022 15023 /** 15024 * {@hide} 15025 * @param id the id of the view to be found 15026 * @return the view of the specified id, null if cannot be found 15027 */ 15028 protected View findViewTraversal(int id) { 15029 if (id == mID) { 15030 return this; 15031 } 15032 return null; 15033 } 15034 15035 /** 15036 * {@hide} 15037 * @param tag the tag of the view to be found 15038 * @return the view of specified tag, null if cannot be found 15039 */ 15040 protected View findViewWithTagTraversal(Object tag) { 15041 if (tag != null && tag.equals(mTag)) { 15042 return this; 15043 } 15044 return null; 15045 } 15046 15047 /** 15048 * {@hide} 15049 * @param predicate The predicate to evaluate. 15050 * @param childToSkip If not null, ignores this child during the recursive traversal. 15051 * @return The first view that matches the predicate or null. 15052 */ 15053 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 15054 if (predicate.apply(this)) { 15055 return this; 15056 } 15057 return null; 15058 } 15059 15060 /** 15061 * Look for a child view with the given id. If this view has the given 15062 * id, return this view. 15063 * 15064 * @param id The id to search for. 15065 * @return The view that has the given id in the hierarchy or null 15066 */ 15067 public final View findViewById(int id) { 15068 if (id < 0) { 15069 return null; 15070 } 15071 return findViewTraversal(id); 15072 } 15073 15074 /** 15075 * Finds a view by its unuque and stable accessibility id. 15076 * 15077 * @param accessibilityId The searched accessibility id. 15078 * @return The found view. 15079 */ 15080 final View findViewByAccessibilityId(int accessibilityId) { 15081 if (accessibilityId < 0) { 15082 return null; 15083 } 15084 return findViewByAccessibilityIdTraversal(accessibilityId); 15085 } 15086 15087 /** 15088 * Performs the traversal to find a view by its unuque and stable accessibility id. 15089 * 15090 * <strong>Note:</strong>This method does not stop at the root namespace 15091 * boundary since the user can touch the screen at an arbitrary location 15092 * potentially crossing the root namespace bounday which will send an 15093 * accessibility event to accessibility services and they should be able 15094 * to obtain the event source. Also accessibility ids are guaranteed to be 15095 * unique in the window. 15096 * 15097 * @param accessibilityId The accessibility id. 15098 * @return The found view. 15099 */ 15100 View findViewByAccessibilityIdTraversal(int accessibilityId) { 15101 if (getAccessibilityViewId() == accessibilityId) { 15102 return this; 15103 } 15104 return null; 15105 } 15106 15107 /** 15108 * Look for a child view with the given tag. If this view has the given 15109 * tag, return this view. 15110 * 15111 * @param tag The tag to search for, using "tag.equals(getTag())". 15112 * @return The View that has the given tag in the hierarchy or null 15113 */ 15114 public final View findViewWithTag(Object tag) { 15115 if (tag == null) { 15116 return null; 15117 } 15118 return findViewWithTagTraversal(tag); 15119 } 15120 15121 /** 15122 * {@hide} 15123 * Look for a child view that matches the specified predicate. 15124 * If this view matches the predicate, return this view. 15125 * 15126 * @param predicate The predicate to evaluate. 15127 * @return The first view that matches the predicate or null. 15128 */ 15129 public final View findViewByPredicate(Predicate<View> predicate) { 15130 return findViewByPredicateTraversal(predicate, null); 15131 } 15132 15133 /** 15134 * {@hide} 15135 * Look for a child view that matches the specified predicate, 15136 * starting with the specified view and its descendents and then 15137 * recusively searching the ancestors and siblings of that view 15138 * until this view is reached. 15139 * 15140 * This method is useful in cases where the predicate does not match 15141 * a single unique view (perhaps multiple views use the same id) 15142 * and we are trying to find the view that is "closest" in scope to the 15143 * starting view. 15144 * 15145 * @param start The view to start from. 15146 * @param predicate The predicate to evaluate. 15147 * @return The first view that matches the predicate or null. 15148 */ 15149 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 15150 View childToSkip = null; 15151 for (;;) { 15152 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 15153 if (view != null || start == this) { 15154 return view; 15155 } 15156 15157 ViewParent parent = start.getParent(); 15158 if (parent == null || !(parent instanceof View)) { 15159 return null; 15160 } 15161 15162 childToSkip = start; 15163 start = (View) parent; 15164 } 15165 } 15166 15167 /** 15168 * Sets the identifier for this view. The identifier does not have to be 15169 * unique in this view's hierarchy. The identifier should be a positive 15170 * number. 15171 * 15172 * @see #NO_ID 15173 * @see #getId() 15174 * @see #findViewById(int) 15175 * 15176 * @param id a number used to identify the view 15177 * 15178 * @attr ref android.R.styleable#View_id 15179 */ 15180 public void setId(int id) { 15181 mID = id; 15182 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 15183 mID = generateViewId(); 15184 } 15185 } 15186 15187 /** 15188 * {@hide} 15189 * 15190 * @param isRoot true if the view belongs to the root namespace, false 15191 * otherwise 15192 */ 15193 public void setIsRootNamespace(boolean isRoot) { 15194 if (isRoot) { 15195 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 15196 } else { 15197 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 15198 } 15199 } 15200 15201 /** 15202 * {@hide} 15203 * 15204 * @return true if the view belongs to the root namespace, false otherwise 15205 */ 15206 public boolean isRootNamespace() { 15207 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 15208 } 15209 15210 /** 15211 * Returns this view's identifier. 15212 * 15213 * @return a positive integer used to identify the view or {@link #NO_ID} 15214 * if the view has no ID 15215 * 15216 * @see #setId(int) 15217 * @see #findViewById(int) 15218 * @attr ref android.R.styleable#View_id 15219 */ 15220 @ViewDebug.CapturedViewProperty 15221 public int getId() { 15222 return mID; 15223 } 15224 15225 /** 15226 * Returns this view's tag. 15227 * 15228 * @return the Object stored in this view as a tag 15229 * 15230 * @see #setTag(Object) 15231 * @see #getTag(int) 15232 */ 15233 @ViewDebug.ExportedProperty 15234 public Object getTag() { 15235 return mTag; 15236 } 15237 15238 /** 15239 * Sets the tag associated with this view. A tag can be used to mark 15240 * a view in its hierarchy and does not have to be unique within the 15241 * hierarchy. Tags can also be used to store data within a view without 15242 * resorting to another data structure. 15243 * 15244 * @param tag an Object to tag the view with 15245 * 15246 * @see #getTag() 15247 * @see #setTag(int, Object) 15248 */ 15249 public void setTag(final Object tag) { 15250 mTag = tag; 15251 } 15252 15253 /** 15254 * Returns the tag associated with this view and the specified key. 15255 * 15256 * @param key The key identifying the tag 15257 * 15258 * @return the Object stored in this view as a tag 15259 * 15260 * @see #setTag(int, Object) 15261 * @see #getTag() 15262 */ 15263 public Object getTag(int key) { 15264 if (mKeyedTags != null) return mKeyedTags.get(key); 15265 return null; 15266 } 15267 15268 /** 15269 * Sets a tag associated with this view and a key. A tag can be used 15270 * to mark a view in its hierarchy and does not have to be unique within 15271 * the hierarchy. Tags can also be used to store data within a view 15272 * without resorting to another data structure. 15273 * 15274 * The specified key should be an id declared in the resources of the 15275 * application to ensure it is unique (see the <a 15276 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 15277 * Keys identified as belonging to 15278 * the Android framework or not associated with any package will cause 15279 * an {@link IllegalArgumentException} to be thrown. 15280 * 15281 * @param key The key identifying the tag 15282 * @param tag An Object to tag the view with 15283 * 15284 * @throws IllegalArgumentException If they specified key is not valid 15285 * 15286 * @see #setTag(Object) 15287 * @see #getTag(int) 15288 */ 15289 public void setTag(int key, final Object tag) { 15290 // If the package id is 0x00 or 0x01, it's either an undefined package 15291 // or a framework id 15292 if ((key >>> 24) < 2) { 15293 throw new IllegalArgumentException("The key must be an application-specific " 15294 + "resource id."); 15295 } 15296 15297 setKeyedTag(key, tag); 15298 } 15299 15300 /** 15301 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 15302 * framework id. 15303 * 15304 * @hide 15305 */ 15306 public void setTagInternal(int key, Object tag) { 15307 if ((key >>> 24) != 0x1) { 15308 throw new IllegalArgumentException("The key must be a framework-specific " 15309 + "resource id."); 15310 } 15311 15312 setKeyedTag(key, tag); 15313 } 15314 15315 private void setKeyedTag(int key, Object tag) { 15316 if (mKeyedTags == null) { 15317 mKeyedTags = new SparseArray<Object>(); 15318 } 15319 15320 mKeyedTags.put(key, tag); 15321 } 15322 15323 /** 15324 * Prints information about this view in the log output, with the tag 15325 * {@link #VIEW_LOG_TAG}. 15326 * 15327 * @hide 15328 */ 15329 public void debug() { 15330 debug(0); 15331 } 15332 15333 /** 15334 * Prints information about this view in the log output, with the tag 15335 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 15336 * indentation defined by the <code>depth</code>. 15337 * 15338 * @param depth the indentation level 15339 * 15340 * @hide 15341 */ 15342 protected void debug(int depth) { 15343 String output = debugIndent(depth - 1); 15344 15345 output += "+ " + this; 15346 int id = getId(); 15347 if (id != -1) { 15348 output += " (id=" + id + ")"; 15349 } 15350 Object tag = getTag(); 15351 if (tag != null) { 15352 output += " (tag=" + tag + ")"; 15353 } 15354 Log.d(VIEW_LOG_TAG, output); 15355 15356 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 15357 output = debugIndent(depth) + " FOCUSED"; 15358 Log.d(VIEW_LOG_TAG, output); 15359 } 15360 15361 output = debugIndent(depth); 15362 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 15363 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 15364 + "} "; 15365 Log.d(VIEW_LOG_TAG, output); 15366 15367 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 15368 || mPaddingBottom != 0) { 15369 output = debugIndent(depth); 15370 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 15371 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 15372 Log.d(VIEW_LOG_TAG, output); 15373 } 15374 15375 output = debugIndent(depth); 15376 output += "mMeasureWidth=" + mMeasuredWidth + 15377 " mMeasureHeight=" + mMeasuredHeight; 15378 Log.d(VIEW_LOG_TAG, output); 15379 15380 output = debugIndent(depth); 15381 if (mLayoutParams == null) { 15382 output += "BAD! no layout params"; 15383 } else { 15384 output = mLayoutParams.debug(output); 15385 } 15386 Log.d(VIEW_LOG_TAG, output); 15387 15388 output = debugIndent(depth); 15389 output += "flags={"; 15390 output += View.printFlags(mViewFlags); 15391 output += "}"; 15392 Log.d(VIEW_LOG_TAG, output); 15393 15394 output = debugIndent(depth); 15395 output += "privateFlags={"; 15396 output += View.printPrivateFlags(mPrivateFlags); 15397 output += "}"; 15398 Log.d(VIEW_LOG_TAG, output); 15399 } 15400 15401 /** 15402 * Creates a string of whitespaces used for indentation. 15403 * 15404 * @param depth the indentation level 15405 * @return a String containing (depth * 2 + 3) * 2 white spaces 15406 * 15407 * @hide 15408 */ 15409 protected static String debugIndent(int depth) { 15410 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 15411 for (int i = 0; i < (depth * 2) + 3; i++) { 15412 spaces.append(' ').append(' '); 15413 } 15414 return spaces.toString(); 15415 } 15416 15417 /** 15418 * <p>Return the offset of the widget's text baseline from the widget's top 15419 * boundary. If this widget does not support baseline alignment, this 15420 * method returns -1. </p> 15421 * 15422 * @return the offset of the baseline within the widget's bounds or -1 15423 * if baseline alignment is not supported 15424 */ 15425 @ViewDebug.ExportedProperty(category = "layout") 15426 public int getBaseline() { 15427 return -1; 15428 } 15429 15430 /** 15431 * Call this when something has changed which has invalidated the 15432 * layout of this view. This will schedule a layout pass of the view 15433 * tree. 15434 */ 15435 public void requestLayout() { 15436 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 15437 mPrivateFlags |= PFLAG_INVALIDATED; 15438 15439 if (mParent != null && !mParent.isLayoutRequested()) { 15440 mParent.requestLayout(); 15441 } 15442 } 15443 15444 /** 15445 * Forces this view to be laid out during the next layout pass. 15446 * This method does not call requestLayout() or forceLayout() 15447 * on the parent. 15448 */ 15449 public void forceLayout() { 15450 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 15451 mPrivateFlags |= PFLAG_INVALIDATED; 15452 } 15453 15454 /** 15455 * <p> 15456 * This is called to find out how big a view should be. The parent 15457 * supplies constraint information in the width and height parameters. 15458 * </p> 15459 * 15460 * <p> 15461 * The actual measurement work of a view is performed in 15462 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 15463 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 15464 * </p> 15465 * 15466 * 15467 * @param widthMeasureSpec Horizontal space requirements as imposed by the 15468 * parent 15469 * @param heightMeasureSpec Vertical space requirements as imposed by the 15470 * parent 15471 * 15472 * @see #onMeasure(int, int) 15473 */ 15474 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 15475 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 15476 widthMeasureSpec != mOldWidthMeasureSpec || 15477 heightMeasureSpec != mOldHeightMeasureSpec) { 15478 15479 // first clears the measured dimension flag 15480 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 15481 15482 resolveRtlPropertiesIfNeeded(); 15483 15484 // measure ourselves, this should set the measured dimension flag back 15485 onMeasure(widthMeasureSpec, heightMeasureSpec); 15486 15487 // flag not set, setMeasuredDimension() was not invoked, we raise 15488 // an exception to warn the developer 15489 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 15490 throw new IllegalStateException("onMeasure() did not set the" 15491 + " measured dimension by calling" 15492 + " setMeasuredDimension()"); 15493 } 15494 15495 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 15496 } 15497 15498 mOldWidthMeasureSpec = widthMeasureSpec; 15499 mOldHeightMeasureSpec = heightMeasureSpec; 15500 } 15501 15502 /** 15503 * <p> 15504 * Measure the view and its content to determine the measured width and the 15505 * measured height. This method is invoked by {@link #measure(int, int)} and 15506 * should be overriden by subclasses to provide accurate and efficient 15507 * measurement of their contents. 15508 * </p> 15509 * 15510 * <p> 15511 * <strong>CONTRACT:</strong> When overriding this method, you 15512 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 15513 * measured width and height of this view. Failure to do so will trigger an 15514 * <code>IllegalStateException</code>, thrown by 15515 * {@link #measure(int, int)}. Calling the superclass' 15516 * {@link #onMeasure(int, int)} is a valid use. 15517 * </p> 15518 * 15519 * <p> 15520 * The base class implementation of measure defaults to the background size, 15521 * unless a larger size is allowed by the MeasureSpec. Subclasses should 15522 * override {@link #onMeasure(int, int)} to provide better measurements of 15523 * their content. 15524 * </p> 15525 * 15526 * <p> 15527 * If this method is overridden, it is the subclass's responsibility to make 15528 * sure the measured height and width are at least the view's minimum height 15529 * and width ({@link #getSuggestedMinimumHeight()} and 15530 * {@link #getSuggestedMinimumWidth()}). 15531 * </p> 15532 * 15533 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 15534 * The requirements are encoded with 15535 * {@link android.view.View.MeasureSpec}. 15536 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 15537 * The requirements are encoded with 15538 * {@link android.view.View.MeasureSpec}. 15539 * 15540 * @see #getMeasuredWidth() 15541 * @see #getMeasuredHeight() 15542 * @see #setMeasuredDimension(int, int) 15543 * @see #getSuggestedMinimumHeight() 15544 * @see #getSuggestedMinimumWidth() 15545 * @see android.view.View.MeasureSpec#getMode(int) 15546 * @see android.view.View.MeasureSpec#getSize(int) 15547 */ 15548 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 15549 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 15550 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 15551 } 15552 15553 /** 15554 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 15555 * measured width and measured height. Failing to do so will trigger an 15556 * exception at measurement time.</p> 15557 * 15558 * @param measuredWidth The measured width of this view. May be a complex 15559 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 15560 * {@link #MEASURED_STATE_TOO_SMALL}. 15561 * @param measuredHeight The measured height of this view. May be a complex 15562 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 15563 * {@link #MEASURED_STATE_TOO_SMALL}. 15564 */ 15565 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 15566 mMeasuredWidth = measuredWidth; 15567 mMeasuredHeight = measuredHeight; 15568 15569 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 15570 } 15571 15572 /** 15573 * Merge two states as returned by {@link #getMeasuredState()}. 15574 * @param curState The current state as returned from a view or the result 15575 * of combining multiple views. 15576 * @param newState The new view state to combine. 15577 * @return Returns a new integer reflecting the combination of the two 15578 * states. 15579 */ 15580 public static int combineMeasuredStates(int curState, int newState) { 15581 return curState | newState; 15582 } 15583 15584 /** 15585 * Version of {@link #resolveSizeAndState(int, int, int)} 15586 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 15587 */ 15588 public static int resolveSize(int size, int measureSpec) { 15589 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 15590 } 15591 15592 /** 15593 * Utility to reconcile a desired size and state, with constraints imposed 15594 * by a MeasureSpec. Will take the desired size, unless a different size 15595 * is imposed by the constraints. The returned value is a compound integer, 15596 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 15597 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 15598 * size is smaller than the size the view wants to be. 15599 * 15600 * @param size How big the view wants to be 15601 * @param measureSpec Constraints imposed by the parent 15602 * @return Size information bit mask as defined by 15603 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 15604 */ 15605 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 15606 int result = size; 15607 int specMode = MeasureSpec.getMode(measureSpec); 15608 int specSize = MeasureSpec.getSize(measureSpec); 15609 switch (specMode) { 15610 case MeasureSpec.UNSPECIFIED: 15611 result = size; 15612 break; 15613 case MeasureSpec.AT_MOST: 15614 if (specSize < size) { 15615 result = specSize | MEASURED_STATE_TOO_SMALL; 15616 } else { 15617 result = size; 15618 } 15619 break; 15620 case MeasureSpec.EXACTLY: 15621 result = specSize; 15622 break; 15623 } 15624 return result | (childMeasuredState&MEASURED_STATE_MASK); 15625 } 15626 15627 /** 15628 * Utility to return a default size. Uses the supplied size if the 15629 * MeasureSpec imposed no constraints. Will get larger if allowed 15630 * by the MeasureSpec. 15631 * 15632 * @param size Default size for this view 15633 * @param measureSpec Constraints imposed by the parent 15634 * @return The size this view should be. 15635 */ 15636 public static int getDefaultSize(int size, int measureSpec) { 15637 int result = size; 15638 int specMode = MeasureSpec.getMode(measureSpec); 15639 int specSize = MeasureSpec.getSize(measureSpec); 15640 15641 switch (specMode) { 15642 case MeasureSpec.UNSPECIFIED: 15643 result = size; 15644 break; 15645 case MeasureSpec.AT_MOST: 15646 case MeasureSpec.EXACTLY: 15647 result = specSize; 15648 break; 15649 } 15650 return result; 15651 } 15652 15653 /** 15654 * Returns the suggested minimum height that the view should use. This 15655 * returns the maximum of the view's minimum height 15656 * and the background's minimum height 15657 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 15658 * <p> 15659 * When being used in {@link #onMeasure(int, int)}, the caller should still 15660 * ensure the returned height is within the requirements of the parent. 15661 * 15662 * @return The suggested minimum height of the view. 15663 */ 15664 protected int getSuggestedMinimumHeight() { 15665 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 15666 15667 } 15668 15669 /** 15670 * Returns the suggested minimum width that the view should use. This 15671 * returns the maximum of the view's minimum width) 15672 * and the background's minimum width 15673 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 15674 * <p> 15675 * When being used in {@link #onMeasure(int, int)}, the caller should still 15676 * ensure the returned width is within the requirements of the parent. 15677 * 15678 * @return The suggested minimum width of the view. 15679 */ 15680 protected int getSuggestedMinimumWidth() { 15681 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 15682 } 15683 15684 /** 15685 * Returns the minimum height of the view. 15686 * 15687 * @return the minimum height the view will try to be. 15688 * 15689 * @see #setMinimumHeight(int) 15690 * 15691 * @attr ref android.R.styleable#View_minHeight 15692 */ 15693 public int getMinimumHeight() { 15694 return mMinHeight; 15695 } 15696 15697 /** 15698 * Sets the minimum height of the view. It is not guaranteed the view will 15699 * be able to achieve this minimum height (for example, if its parent layout 15700 * constrains it with less available height). 15701 * 15702 * @param minHeight The minimum height the view will try to be. 15703 * 15704 * @see #getMinimumHeight() 15705 * 15706 * @attr ref android.R.styleable#View_minHeight 15707 */ 15708 public void setMinimumHeight(int minHeight) { 15709 mMinHeight = minHeight; 15710 requestLayout(); 15711 } 15712 15713 /** 15714 * Returns the minimum width of the view. 15715 * 15716 * @return the minimum width the view will try to be. 15717 * 15718 * @see #setMinimumWidth(int) 15719 * 15720 * @attr ref android.R.styleable#View_minWidth 15721 */ 15722 public int getMinimumWidth() { 15723 return mMinWidth; 15724 } 15725 15726 /** 15727 * Sets the minimum width of the view. It is not guaranteed the view will 15728 * be able to achieve this minimum width (for example, if its parent layout 15729 * constrains it with less available width). 15730 * 15731 * @param minWidth The minimum width the view will try to be. 15732 * 15733 * @see #getMinimumWidth() 15734 * 15735 * @attr ref android.R.styleable#View_minWidth 15736 */ 15737 public void setMinimumWidth(int minWidth) { 15738 mMinWidth = minWidth; 15739 requestLayout(); 15740 15741 } 15742 15743 /** 15744 * Get the animation currently associated with this view. 15745 * 15746 * @return The animation that is currently playing or 15747 * scheduled to play for this view. 15748 */ 15749 public Animation getAnimation() { 15750 return mCurrentAnimation; 15751 } 15752 15753 /** 15754 * Start the specified animation now. 15755 * 15756 * @param animation the animation to start now 15757 */ 15758 public void startAnimation(Animation animation) { 15759 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 15760 setAnimation(animation); 15761 invalidateParentCaches(); 15762 invalidate(true); 15763 } 15764 15765 /** 15766 * Cancels any animations for this view. 15767 */ 15768 public void clearAnimation() { 15769 if (mCurrentAnimation != null) { 15770 mCurrentAnimation.detach(); 15771 } 15772 mCurrentAnimation = null; 15773 invalidateParentIfNeeded(); 15774 } 15775 15776 /** 15777 * Sets the next animation to play for this view. 15778 * If you want the animation to play immediately, use 15779 * {@link #startAnimation(android.view.animation.Animation)} instead. 15780 * This method provides allows fine-grained 15781 * control over the start time and invalidation, but you 15782 * must make sure that 1) the animation has a start time set, and 15783 * 2) the view's parent (which controls animations on its children) 15784 * will be invalidated when the animation is supposed to 15785 * start. 15786 * 15787 * @param animation The next animation, or null. 15788 */ 15789 public void setAnimation(Animation animation) { 15790 mCurrentAnimation = animation; 15791 15792 if (animation != null) { 15793 // If the screen is off assume the animation start time is now instead of 15794 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 15795 // would cause the animation to start when the screen turns back on 15796 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 15797 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 15798 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 15799 } 15800 animation.reset(); 15801 } 15802 } 15803 15804 /** 15805 * Invoked by a parent ViewGroup to notify the start of the animation 15806 * currently associated with this view. If you override this method, 15807 * always call super.onAnimationStart(); 15808 * 15809 * @see #setAnimation(android.view.animation.Animation) 15810 * @see #getAnimation() 15811 */ 15812 protected void onAnimationStart() { 15813 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 15814 } 15815 15816 /** 15817 * Invoked by a parent ViewGroup to notify the end of the animation 15818 * currently associated with this view. If you override this method, 15819 * always call super.onAnimationEnd(); 15820 * 15821 * @see #setAnimation(android.view.animation.Animation) 15822 * @see #getAnimation() 15823 */ 15824 protected void onAnimationEnd() { 15825 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 15826 } 15827 15828 /** 15829 * Invoked if there is a Transform that involves alpha. Subclass that can 15830 * draw themselves with the specified alpha should return true, and then 15831 * respect that alpha when their onDraw() is called. If this returns false 15832 * then the view may be redirected to draw into an offscreen buffer to 15833 * fulfill the request, which will look fine, but may be slower than if the 15834 * subclass handles it internally. The default implementation returns false. 15835 * 15836 * @param alpha The alpha (0..255) to apply to the view's drawing 15837 * @return true if the view can draw with the specified alpha. 15838 */ 15839 protected boolean onSetAlpha(int alpha) { 15840 return false; 15841 } 15842 15843 /** 15844 * This is used by the RootView to perform an optimization when 15845 * the view hierarchy contains one or several SurfaceView. 15846 * SurfaceView is always considered transparent, but its children are not, 15847 * therefore all View objects remove themselves from the global transparent 15848 * region (passed as a parameter to this function). 15849 * 15850 * @param region The transparent region for this ViewAncestor (window). 15851 * 15852 * @return Returns true if the effective visibility of the view at this 15853 * point is opaque, regardless of the transparent region; returns false 15854 * if it is possible for underlying windows to be seen behind the view. 15855 * 15856 * {@hide} 15857 */ 15858 public boolean gatherTransparentRegion(Region region) { 15859 final AttachInfo attachInfo = mAttachInfo; 15860 if (region != null && attachInfo != null) { 15861 final int pflags = mPrivateFlags; 15862 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 15863 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 15864 // remove it from the transparent region. 15865 final int[] location = attachInfo.mTransparentLocation; 15866 getLocationInWindow(location); 15867 region.op(location[0], location[1], location[0] + mRight - mLeft, 15868 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 15869 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 15870 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 15871 // exists, so we remove the background drawable's non-transparent 15872 // parts from this transparent region. 15873 applyDrawableToTransparentRegion(mBackground, region); 15874 } 15875 } 15876 return true; 15877 } 15878 15879 /** 15880 * Play a sound effect for this view. 15881 * 15882 * <p>The framework will play sound effects for some built in actions, such as 15883 * clicking, but you may wish to play these effects in your widget, 15884 * for instance, for internal navigation. 15885 * 15886 * <p>The sound effect will only be played if sound effects are enabled by the user, and 15887 * {@link #isSoundEffectsEnabled()} is true. 15888 * 15889 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 15890 */ 15891 public void playSoundEffect(int soundConstant) { 15892 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 15893 return; 15894 } 15895 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 15896 } 15897 15898 /** 15899 * BZZZTT!!1! 15900 * 15901 * <p>Provide haptic feedback to the user for this view. 15902 * 15903 * <p>The framework will provide haptic feedback for some built in actions, 15904 * such as long presses, but you may wish to provide feedback for your 15905 * own widget. 15906 * 15907 * <p>The feedback will only be performed if 15908 * {@link #isHapticFeedbackEnabled()} is true. 15909 * 15910 * @param feedbackConstant One of the constants defined in 15911 * {@link HapticFeedbackConstants} 15912 */ 15913 public boolean performHapticFeedback(int feedbackConstant) { 15914 return performHapticFeedback(feedbackConstant, 0); 15915 } 15916 15917 /** 15918 * BZZZTT!!1! 15919 * 15920 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 15921 * 15922 * @param feedbackConstant One of the constants defined in 15923 * {@link HapticFeedbackConstants} 15924 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 15925 */ 15926 public boolean performHapticFeedback(int feedbackConstant, int flags) { 15927 if (mAttachInfo == null) { 15928 return false; 15929 } 15930 //noinspection SimplifiableIfStatement 15931 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 15932 && !isHapticFeedbackEnabled()) { 15933 return false; 15934 } 15935 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 15936 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 15937 } 15938 15939 /** 15940 * Request that the visibility of the status bar or other screen/window 15941 * decorations be changed. 15942 * 15943 * <p>This method is used to put the over device UI into temporary modes 15944 * where the user's attention is focused more on the application content, 15945 * by dimming or hiding surrounding system affordances. This is typically 15946 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 15947 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 15948 * to be placed behind the action bar (and with these flags other system 15949 * affordances) so that smooth transitions between hiding and showing them 15950 * can be done. 15951 * 15952 * <p>Two representative examples of the use of system UI visibility is 15953 * implementing a content browsing application (like a magazine reader) 15954 * and a video playing application. 15955 * 15956 * <p>The first code shows a typical implementation of a View in a content 15957 * browsing application. In this implementation, the application goes 15958 * into a content-oriented mode by hiding the status bar and action bar, 15959 * and putting the navigation elements into lights out mode. The user can 15960 * then interact with content while in this mode. Such an application should 15961 * provide an easy way for the user to toggle out of the mode (such as to 15962 * check information in the status bar or access notifications). In the 15963 * implementation here, this is done simply by tapping on the content. 15964 * 15965 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 15966 * content} 15967 * 15968 * <p>This second code sample shows a typical implementation of a View 15969 * in a video playing application. In this situation, while the video is 15970 * playing the application would like to go into a complete full-screen mode, 15971 * to use as much of the display as possible for the video. When in this state 15972 * the user can not interact with the application; the system intercepts 15973 * touching on the screen to pop the UI out of full screen mode. See 15974 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 15975 * 15976 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 15977 * content} 15978 * 15979 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 15980 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 15981 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 15982 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 15983 */ 15984 public void setSystemUiVisibility(int visibility) { 15985 if (visibility != mSystemUiVisibility) { 15986 mSystemUiVisibility = visibility; 15987 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 15988 mParent.recomputeViewAttributes(this); 15989 } 15990 } 15991 } 15992 15993 /** 15994 * Returns the last {@link #setSystemUiVisibility(int) that this view has requested. 15995 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 15996 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 15997 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 15998 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 15999 */ 16000 public int getSystemUiVisibility() { 16001 return mSystemUiVisibility; 16002 } 16003 16004 /** 16005 * Returns the current system UI visibility that is currently set for 16006 * the entire window. This is the combination of the 16007 * {@link #setSystemUiVisibility(int)} values supplied by all of the 16008 * views in the window. 16009 */ 16010 public int getWindowSystemUiVisibility() { 16011 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 16012 } 16013 16014 /** 16015 * Override to find out when the window's requested system UI visibility 16016 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 16017 * This is different from the callbacks recieved through 16018 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 16019 * in that this is only telling you about the local request of the window, 16020 * not the actual values applied by the system. 16021 */ 16022 public void onWindowSystemUiVisibilityChanged(int visible) { 16023 } 16024 16025 /** 16026 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 16027 * the view hierarchy. 16028 */ 16029 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 16030 onWindowSystemUiVisibilityChanged(visible); 16031 } 16032 16033 /** 16034 * Set a listener to receive callbacks when the visibility of the system bar changes. 16035 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 16036 */ 16037 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 16038 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 16039 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 16040 mParent.recomputeViewAttributes(this); 16041 } 16042 } 16043 16044 /** 16045 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 16046 * the view hierarchy. 16047 */ 16048 public void dispatchSystemUiVisibilityChanged(int visibility) { 16049 ListenerInfo li = mListenerInfo; 16050 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 16051 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 16052 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 16053 } 16054 } 16055 16056 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 16057 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 16058 if (val != mSystemUiVisibility) { 16059 setSystemUiVisibility(val); 16060 return true; 16061 } 16062 return false; 16063 } 16064 16065 /** @hide */ 16066 public void setDisabledSystemUiVisibility(int flags) { 16067 if (mAttachInfo != null) { 16068 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 16069 mAttachInfo.mDisabledSystemUiVisibility = flags; 16070 if (mParent != null) { 16071 mParent.recomputeViewAttributes(this); 16072 } 16073 } 16074 } 16075 } 16076 16077 /** 16078 * Creates an image that the system displays during the drag and drop 16079 * operation. This is called a "drag shadow". The default implementation 16080 * for a DragShadowBuilder based on a View returns an image that has exactly the same 16081 * appearance as the given View. The default also positions the center of the drag shadow 16082 * directly under the touch point. If no View is provided (the constructor with no parameters 16083 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 16084 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 16085 * default is an invisible drag shadow. 16086 * <p> 16087 * You are not required to use the View you provide to the constructor as the basis of the 16088 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 16089 * anything you want as the drag shadow. 16090 * </p> 16091 * <p> 16092 * You pass a DragShadowBuilder object to the system when you start the drag. The system 16093 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 16094 * size and position of the drag shadow. It uses this data to construct a 16095 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 16096 * so that your application can draw the shadow image in the Canvas. 16097 * </p> 16098 * 16099 * <div class="special reference"> 16100 * <h3>Developer Guides</h3> 16101 * <p>For a guide to implementing drag and drop features, read the 16102 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 16103 * </div> 16104 */ 16105 public static class DragShadowBuilder { 16106 private final WeakReference<View> mView; 16107 16108 /** 16109 * Constructs a shadow image builder based on a View. By default, the resulting drag 16110 * shadow will have the same appearance and dimensions as the View, with the touch point 16111 * over the center of the View. 16112 * @param view A View. Any View in scope can be used. 16113 */ 16114 public DragShadowBuilder(View view) { 16115 mView = new WeakReference<View>(view); 16116 } 16117 16118 /** 16119 * Construct a shadow builder object with no associated View. This 16120 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 16121 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 16122 * to supply the drag shadow's dimensions and appearance without 16123 * reference to any View object. If they are not overridden, then the result is an 16124 * invisible drag shadow. 16125 */ 16126 public DragShadowBuilder() { 16127 mView = new WeakReference<View>(null); 16128 } 16129 16130 /** 16131 * Returns the View object that had been passed to the 16132 * {@link #View.DragShadowBuilder(View)} 16133 * constructor. If that View parameter was {@code null} or if the 16134 * {@link #View.DragShadowBuilder()} 16135 * constructor was used to instantiate the builder object, this method will return 16136 * null. 16137 * 16138 * @return The View object associate with this builder object. 16139 */ 16140 @SuppressWarnings({"JavadocReference"}) 16141 final public View getView() { 16142 return mView.get(); 16143 } 16144 16145 /** 16146 * Provides the metrics for the shadow image. These include the dimensions of 16147 * the shadow image, and the point within that shadow that should 16148 * be centered under the touch location while dragging. 16149 * <p> 16150 * The default implementation sets the dimensions of the shadow to be the 16151 * same as the dimensions of the View itself and centers the shadow under 16152 * the touch point. 16153 * </p> 16154 * 16155 * @param shadowSize A {@link android.graphics.Point} containing the width and height 16156 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 16157 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 16158 * image. 16159 * 16160 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 16161 * shadow image that should be underneath the touch point during the drag and drop 16162 * operation. Your application must set {@link android.graphics.Point#x} to the 16163 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 16164 */ 16165 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 16166 final View view = mView.get(); 16167 if (view != null) { 16168 shadowSize.set(view.getWidth(), view.getHeight()); 16169 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 16170 } else { 16171 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 16172 } 16173 } 16174 16175 /** 16176 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 16177 * based on the dimensions it received from the 16178 * {@link #onProvideShadowMetrics(Point, Point)} callback. 16179 * 16180 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 16181 */ 16182 public void onDrawShadow(Canvas canvas) { 16183 final View view = mView.get(); 16184 if (view != null) { 16185 view.draw(canvas); 16186 } else { 16187 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 16188 } 16189 } 16190 } 16191 16192 /** 16193 * Starts a drag and drop operation. When your application calls this method, it passes a 16194 * {@link android.view.View.DragShadowBuilder} object to the system. The 16195 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 16196 * to get metrics for the drag shadow, and then calls the object's 16197 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 16198 * <p> 16199 * Once the system has the drag shadow, it begins the drag and drop operation by sending 16200 * drag events to all the View objects in your application that are currently visible. It does 16201 * this either by calling the View object's drag listener (an implementation of 16202 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 16203 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 16204 * Both are passed a {@link android.view.DragEvent} object that has a 16205 * {@link android.view.DragEvent#getAction()} value of 16206 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 16207 * </p> 16208 * <p> 16209 * Your application can invoke startDrag() on any attached View object. The View object does not 16210 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 16211 * be related to the View the user selected for dragging. 16212 * </p> 16213 * @param data A {@link android.content.ClipData} object pointing to the data to be 16214 * transferred by the drag and drop operation. 16215 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 16216 * drag shadow. 16217 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 16218 * drop operation. This Object is put into every DragEvent object sent by the system during the 16219 * current drag. 16220 * <p> 16221 * myLocalState is a lightweight mechanism for the sending information from the dragged View 16222 * to the target Views. For example, it can contain flags that differentiate between a 16223 * a copy operation and a move operation. 16224 * </p> 16225 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 16226 * so the parameter should be set to 0. 16227 * @return {@code true} if the method completes successfully, or 16228 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 16229 * do a drag, and so no drag operation is in progress. 16230 */ 16231 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 16232 Object myLocalState, int flags) { 16233 if (ViewDebug.DEBUG_DRAG) { 16234 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 16235 } 16236 boolean okay = false; 16237 16238 Point shadowSize = new Point(); 16239 Point shadowTouchPoint = new Point(); 16240 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 16241 16242 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 16243 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 16244 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 16245 } 16246 16247 if (ViewDebug.DEBUG_DRAG) { 16248 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 16249 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 16250 } 16251 Surface surface = new Surface(); 16252 try { 16253 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 16254 flags, shadowSize.x, shadowSize.y, surface); 16255 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 16256 + " surface=" + surface); 16257 if (token != null) { 16258 Canvas canvas = surface.lockCanvas(null); 16259 try { 16260 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 16261 shadowBuilder.onDrawShadow(canvas); 16262 } finally { 16263 surface.unlockCanvasAndPost(canvas); 16264 } 16265 16266 final ViewRootImpl root = getViewRootImpl(); 16267 16268 // Cache the local state object for delivery with DragEvents 16269 root.setLocalDragState(myLocalState); 16270 16271 // repurpose 'shadowSize' for the last touch point 16272 root.getLastTouchPoint(shadowSize); 16273 16274 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 16275 shadowSize.x, shadowSize.y, 16276 shadowTouchPoint.x, shadowTouchPoint.y, data); 16277 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 16278 16279 // Off and running! Release our local surface instance; the drag 16280 // shadow surface is now managed by the system process. 16281 surface.release(); 16282 } 16283 } catch (Exception e) { 16284 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 16285 surface.destroy(); 16286 } 16287 16288 return okay; 16289 } 16290 16291 /** 16292 * Handles drag events sent by the system following a call to 16293 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 16294 *<p> 16295 * When the system calls this method, it passes a 16296 * {@link android.view.DragEvent} object. A call to 16297 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 16298 * in DragEvent. The method uses these to determine what is happening in the drag and drop 16299 * operation. 16300 * @param event The {@link android.view.DragEvent} sent by the system. 16301 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 16302 * in DragEvent, indicating the type of drag event represented by this object. 16303 * @return {@code true} if the method was successful, otherwise {@code false}. 16304 * <p> 16305 * The method should return {@code true} in response to an action type of 16306 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 16307 * operation. 16308 * </p> 16309 * <p> 16310 * The method should also return {@code true} in response to an action type of 16311 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 16312 * {@code false} if it didn't. 16313 * </p> 16314 */ 16315 public boolean onDragEvent(DragEvent event) { 16316 return false; 16317 } 16318 16319 /** 16320 * Detects if this View is enabled and has a drag event listener. 16321 * If both are true, then it calls the drag event listener with the 16322 * {@link android.view.DragEvent} it received. If the drag event listener returns 16323 * {@code true}, then dispatchDragEvent() returns {@code true}. 16324 * <p> 16325 * For all other cases, the method calls the 16326 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 16327 * method and returns its result. 16328 * </p> 16329 * <p> 16330 * This ensures that a drag event is always consumed, even if the View does not have a drag 16331 * event listener. However, if the View has a listener and the listener returns true, then 16332 * onDragEvent() is not called. 16333 * </p> 16334 */ 16335 public boolean dispatchDragEvent(DragEvent event) { 16336 //noinspection SimplifiableIfStatement 16337 ListenerInfo li = mListenerInfo; 16338 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 16339 && li.mOnDragListener.onDrag(this, event)) { 16340 return true; 16341 } 16342 return onDragEvent(event); 16343 } 16344 16345 boolean canAcceptDrag() { 16346 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 16347 } 16348 16349 /** 16350 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 16351 * it is ever exposed at all. 16352 * @hide 16353 */ 16354 public void onCloseSystemDialogs(String reason) { 16355 } 16356 16357 /** 16358 * Given a Drawable whose bounds have been set to draw into this view, 16359 * update a Region being computed for 16360 * {@link #gatherTransparentRegion(android.graphics.Region)} so 16361 * that any non-transparent parts of the Drawable are removed from the 16362 * given transparent region. 16363 * 16364 * @param dr The Drawable whose transparency is to be applied to the region. 16365 * @param region A Region holding the current transparency information, 16366 * where any parts of the region that are set are considered to be 16367 * transparent. On return, this region will be modified to have the 16368 * transparency information reduced by the corresponding parts of the 16369 * Drawable that are not transparent. 16370 * {@hide} 16371 */ 16372 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 16373 if (DBG) { 16374 Log.i("View", "Getting transparent region for: " + this); 16375 } 16376 final Region r = dr.getTransparentRegion(); 16377 final Rect db = dr.getBounds(); 16378 final AttachInfo attachInfo = mAttachInfo; 16379 if (r != null && attachInfo != null) { 16380 final int w = getRight()-getLeft(); 16381 final int h = getBottom()-getTop(); 16382 if (db.left > 0) { 16383 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 16384 r.op(0, 0, db.left, h, Region.Op.UNION); 16385 } 16386 if (db.right < w) { 16387 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 16388 r.op(db.right, 0, w, h, Region.Op.UNION); 16389 } 16390 if (db.top > 0) { 16391 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 16392 r.op(0, 0, w, db.top, Region.Op.UNION); 16393 } 16394 if (db.bottom < h) { 16395 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 16396 r.op(0, db.bottom, w, h, Region.Op.UNION); 16397 } 16398 final int[] location = attachInfo.mTransparentLocation; 16399 getLocationInWindow(location); 16400 r.translate(location[0], location[1]); 16401 region.op(r, Region.Op.INTERSECT); 16402 } else { 16403 region.op(db, Region.Op.DIFFERENCE); 16404 } 16405 } 16406 16407 private void checkForLongClick(int delayOffset) { 16408 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 16409 mHasPerformedLongPress = false; 16410 16411 if (mPendingCheckForLongPress == null) { 16412 mPendingCheckForLongPress = new CheckForLongPress(); 16413 } 16414 mPendingCheckForLongPress.rememberWindowAttachCount(); 16415 postDelayed(mPendingCheckForLongPress, 16416 ViewConfiguration.getLongPressTimeout() - delayOffset); 16417 } 16418 } 16419 16420 /** 16421 * Inflate a view from an XML resource. This convenience method wraps the {@link 16422 * LayoutInflater} class, which provides a full range of options for view inflation. 16423 * 16424 * @param context The Context object for your activity or application. 16425 * @param resource The resource ID to inflate 16426 * @param root A view group that will be the parent. Used to properly inflate the 16427 * layout_* parameters. 16428 * @see LayoutInflater 16429 */ 16430 public static View inflate(Context context, int resource, ViewGroup root) { 16431 LayoutInflater factory = LayoutInflater.from(context); 16432 return factory.inflate(resource, root); 16433 } 16434 16435 /** 16436 * Scroll the view with standard behavior for scrolling beyond the normal 16437 * content boundaries. Views that call this method should override 16438 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 16439 * results of an over-scroll operation. 16440 * 16441 * Views can use this method to handle any touch or fling-based scrolling. 16442 * 16443 * @param deltaX Change in X in pixels 16444 * @param deltaY Change in Y in pixels 16445 * @param scrollX Current X scroll value in pixels before applying deltaX 16446 * @param scrollY Current Y scroll value in pixels before applying deltaY 16447 * @param scrollRangeX Maximum content scroll range along the X axis 16448 * @param scrollRangeY Maximum content scroll range along the Y axis 16449 * @param maxOverScrollX Number of pixels to overscroll by in either direction 16450 * along the X axis. 16451 * @param maxOverScrollY Number of pixels to overscroll by in either direction 16452 * along the Y axis. 16453 * @param isTouchEvent true if this scroll operation is the result of a touch event. 16454 * @return true if scrolling was clamped to an over-scroll boundary along either 16455 * axis, false otherwise. 16456 */ 16457 @SuppressWarnings({"UnusedParameters"}) 16458 protected boolean overScrollBy(int deltaX, int deltaY, 16459 int scrollX, int scrollY, 16460 int scrollRangeX, int scrollRangeY, 16461 int maxOverScrollX, int maxOverScrollY, 16462 boolean isTouchEvent) { 16463 final int overScrollMode = mOverScrollMode; 16464 final boolean canScrollHorizontal = 16465 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 16466 final boolean canScrollVertical = 16467 computeVerticalScrollRange() > computeVerticalScrollExtent(); 16468 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 16469 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 16470 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 16471 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 16472 16473 int newScrollX = scrollX + deltaX; 16474 if (!overScrollHorizontal) { 16475 maxOverScrollX = 0; 16476 } 16477 16478 int newScrollY = scrollY + deltaY; 16479 if (!overScrollVertical) { 16480 maxOverScrollY = 0; 16481 } 16482 16483 // Clamp values if at the limits and record 16484 final int left = -maxOverScrollX; 16485 final int right = maxOverScrollX + scrollRangeX; 16486 final int top = -maxOverScrollY; 16487 final int bottom = maxOverScrollY + scrollRangeY; 16488 16489 boolean clampedX = false; 16490 if (newScrollX > right) { 16491 newScrollX = right; 16492 clampedX = true; 16493 } else if (newScrollX < left) { 16494 newScrollX = left; 16495 clampedX = true; 16496 } 16497 16498 boolean clampedY = false; 16499 if (newScrollY > bottom) { 16500 newScrollY = bottom; 16501 clampedY = true; 16502 } else if (newScrollY < top) { 16503 newScrollY = top; 16504 clampedY = true; 16505 } 16506 16507 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 16508 16509 return clampedX || clampedY; 16510 } 16511 16512 /** 16513 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 16514 * respond to the results of an over-scroll operation. 16515 * 16516 * @param scrollX New X scroll value in pixels 16517 * @param scrollY New Y scroll value in pixels 16518 * @param clampedX True if scrollX was clamped to an over-scroll boundary 16519 * @param clampedY True if scrollY was clamped to an over-scroll boundary 16520 */ 16521 protected void onOverScrolled(int scrollX, int scrollY, 16522 boolean clampedX, boolean clampedY) { 16523 // Intentionally empty. 16524 } 16525 16526 /** 16527 * Returns the over-scroll mode for this view. The result will be 16528 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16529 * (allow over-scrolling only if the view content is larger than the container), 16530 * or {@link #OVER_SCROLL_NEVER}. 16531 * 16532 * @return This view's over-scroll mode. 16533 */ 16534 public int getOverScrollMode() { 16535 return mOverScrollMode; 16536 } 16537 16538 /** 16539 * Set the over-scroll mode for this view. Valid over-scroll modes are 16540 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16541 * (allow over-scrolling only if the view content is larger than the container), 16542 * or {@link #OVER_SCROLL_NEVER}. 16543 * 16544 * Setting the over-scroll mode of a view will have an effect only if the 16545 * view is capable of scrolling. 16546 * 16547 * @param overScrollMode The new over-scroll mode for this view. 16548 */ 16549 public void setOverScrollMode(int overScrollMode) { 16550 if (overScrollMode != OVER_SCROLL_ALWAYS && 16551 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 16552 overScrollMode != OVER_SCROLL_NEVER) { 16553 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 16554 } 16555 mOverScrollMode = overScrollMode; 16556 } 16557 16558 /** 16559 * Gets a scale factor that determines the distance the view should scroll 16560 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 16561 * @return The vertical scroll scale factor. 16562 * @hide 16563 */ 16564 protected float getVerticalScrollFactor() { 16565 if (mVerticalScrollFactor == 0) { 16566 TypedValue outValue = new TypedValue(); 16567 if (!mContext.getTheme().resolveAttribute( 16568 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 16569 throw new IllegalStateException( 16570 "Expected theme to define listPreferredItemHeight."); 16571 } 16572 mVerticalScrollFactor = outValue.getDimension( 16573 mContext.getResources().getDisplayMetrics()); 16574 } 16575 return mVerticalScrollFactor; 16576 } 16577 16578 /** 16579 * Gets a scale factor that determines the distance the view should scroll 16580 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 16581 * @return The horizontal scroll scale factor. 16582 * @hide 16583 */ 16584 protected float getHorizontalScrollFactor() { 16585 // TODO: Should use something else. 16586 return getVerticalScrollFactor(); 16587 } 16588 16589 /** 16590 * Return the value specifying the text direction or policy that was set with 16591 * {@link #setTextDirection(int)}. 16592 * 16593 * @return the defined text direction. It can be one of: 16594 * 16595 * {@link #TEXT_DIRECTION_INHERIT}, 16596 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16597 * {@link #TEXT_DIRECTION_ANY_RTL}, 16598 * {@link #TEXT_DIRECTION_LTR}, 16599 * {@link #TEXT_DIRECTION_RTL}, 16600 * {@link #TEXT_DIRECTION_LOCALE} 16601 * 16602 * @hide 16603 */ 16604 @ViewDebug.ExportedProperty(category = "text", mapping = { 16605 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 16606 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 16607 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 16608 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 16609 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 16610 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 16611 }) 16612 public int getRawTextDirection() { 16613 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 16614 } 16615 16616 /** 16617 * Set the text direction. 16618 * 16619 * @param textDirection the direction to set. Should be one of: 16620 * 16621 * {@link #TEXT_DIRECTION_INHERIT}, 16622 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16623 * {@link #TEXT_DIRECTION_ANY_RTL}, 16624 * {@link #TEXT_DIRECTION_LTR}, 16625 * {@link #TEXT_DIRECTION_RTL}, 16626 * {@link #TEXT_DIRECTION_LOCALE} 16627 * 16628 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 16629 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 16630 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 16631 */ 16632 public void setTextDirection(int textDirection) { 16633 if (getRawTextDirection() != textDirection) { 16634 // Reset the current text direction and the resolved one 16635 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 16636 resetResolvedTextDirection(); 16637 // Set the new text direction 16638 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 16639 // Do resolution 16640 resolveTextDirection(); 16641 // Notify change 16642 onRtlPropertiesChanged(getLayoutDirection()); 16643 // Refresh 16644 requestLayout(); 16645 invalidate(true); 16646 } 16647 } 16648 16649 /** 16650 * Return the resolved text direction. 16651 * 16652 * @return the resolved text direction. Returns one of: 16653 * 16654 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16655 * {@link #TEXT_DIRECTION_ANY_RTL}, 16656 * {@link #TEXT_DIRECTION_LTR}, 16657 * {@link #TEXT_DIRECTION_RTL}, 16658 * {@link #TEXT_DIRECTION_LOCALE} 16659 */ 16660 public int getTextDirection() { 16661 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 16662 } 16663 16664 /** 16665 * Resolve the text direction. 16666 * 16667 * @return true if resolution has been done, false otherwise. 16668 * 16669 * @hide 16670 */ 16671 public boolean resolveTextDirection() { 16672 // Reset any previous text direction resolution 16673 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 16674 16675 if (hasRtlSupport()) { 16676 // Set resolved text direction flag depending on text direction flag 16677 final int textDirection = getRawTextDirection(); 16678 switch(textDirection) { 16679 case TEXT_DIRECTION_INHERIT: 16680 if (!canResolveTextDirection()) { 16681 // We cannot do the resolution if there is no parent, so use the default one 16682 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16683 // Resolution will need to happen again later 16684 return false; 16685 } 16686 16687 View parent = ((View) mParent); 16688 // Parent has not yet resolved, so we still return the default 16689 if (!parent.isTextDirectionResolved()) { 16690 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16691 // Resolution will need to happen again later 16692 return false; 16693 } 16694 16695 // Set current resolved direction to the same value as the parent's one 16696 final int parentResolvedDirection = parent.getTextDirection(); 16697 switch (parentResolvedDirection) { 16698 case TEXT_DIRECTION_FIRST_STRONG: 16699 case TEXT_DIRECTION_ANY_RTL: 16700 case TEXT_DIRECTION_LTR: 16701 case TEXT_DIRECTION_RTL: 16702 case TEXT_DIRECTION_LOCALE: 16703 mPrivateFlags2 |= 16704 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 16705 break; 16706 default: 16707 // Default resolved direction is "first strong" heuristic 16708 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16709 } 16710 break; 16711 case TEXT_DIRECTION_FIRST_STRONG: 16712 case TEXT_DIRECTION_ANY_RTL: 16713 case TEXT_DIRECTION_LTR: 16714 case TEXT_DIRECTION_RTL: 16715 case TEXT_DIRECTION_LOCALE: 16716 // Resolved direction is the same as text direction 16717 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 16718 break; 16719 default: 16720 // Default resolved direction is "first strong" heuristic 16721 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16722 } 16723 } else { 16724 // Default resolved direction is "first strong" heuristic 16725 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16726 } 16727 16728 // Set to resolved 16729 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 16730 return true; 16731 } 16732 16733 /** 16734 * Check if text direction resolution can be done. 16735 * 16736 * @return true if text direction resolution can be done otherwise return false. 16737 */ 16738 private boolean canResolveTextDirection() { 16739 switch (getRawTextDirection()) { 16740 case TEXT_DIRECTION_INHERIT: 16741 return (mParent != null) && (mParent instanceof View) && 16742 ((View) mParent).canResolveTextDirection(); 16743 default: 16744 return true; 16745 } 16746 } 16747 16748 /** 16749 * Reset resolved text direction. Text direction will be resolved during a call to 16750 * {@link #onMeasure(int, int)}. 16751 * 16752 * @hide 16753 */ 16754 public void resetResolvedTextDirection() { 16755 // Reset any previous text direction resolution 16756 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 16757 // Set to default value 16758 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16759 } 16760 16761 /** 16762 * @return true if text direction is inherited. 16763 * 16764 * @hide 16765 */ 16766 public boolean isTextDirectionInherited() { 16767 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 16768 } 16769 16770 /** 16771 * @return true if text direction is resolved. 16772 */ 16773 private boolean isTextDirectionResolved() { 16774 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 16775 } 16776 16777 /** 16778 * Return the value specifying the text alignment or policy that was set with 16779 * {@link #setTextAlignment(int)}. 16780 * 16781 * @return the defined text alignment. It can be one of: 16782 * 16783 * {@link #TEXT_ALIGNMENT_INHERIT}, 16784 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16785 * {@link #TEXT_ALIGNMENT_CENTER}, 16786 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16787 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16788 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16789 * {@link #TEXT_ALIGNMENT_VIEW_END} 16790 * 16791 * @hide 16792 */ 16793 @ViewDebug.ExportedProperty(category = "text", mapping = { 16794 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 16795 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 16796 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 16797 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 16798 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 16799 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 16800 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 16801 }) 16802 public int getRawTextAlignment() { 16803 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 16804 } 16805 16806 /** 16807 * Set the text alignment. 16808 * 16809 * @param textAlignment The text alignment to set. Should be one of 16810 * 16811 * {@link #TEXT_ALIGNMENT_INHERIT}, 16812 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16813 * {@link #TEXT_ALIGNMENT_CENTER}, 16814 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16815 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16816 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16817 * {@link #TEXT_ALIGNMENT_VIEW_END} 16818 * 16819 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 16820 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 16821 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 16822 * 16823 * @attr ref android.R.styleable#View_textAlignment 16824 */ 16825 public void setTextAlignment(int textAlignment) { 16826 if (textAlignment != getRawTextAlignment()) { 16827 // Reset the current and resolved text alignment 16828 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 16829 resetResolvedTextAlignment(); 16830 // Set the new text alignment 16831 mPrivateFlags2 |= 16832 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 16833 // Do resolution 16834 resolveTextAlignment(); 16835 // Notify change 16836 onRtlPropertiesChanged(getLayoutDirection()); 16837 // Refresh 16838 requestLayout(); 16839 invalidate(true); 16840 } 16841 } 16842 16843 /** 16844 * Return the resolved text alignment. 16845 * 16846 * @return the resolved text alignment. Returns one of: 16847 * 16848 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16849 * {@link #TEXT_ALIGNMENT_CENTER}, 16850 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16851 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16852 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16853 * {@link #TEXT_ALIGNMENT_VIEW_END} 16854 */ 16855 @ViewDebug.ExportedProperty(category = "text", mapping = { 16856 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 16857 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 16858 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 16859 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 16860 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 16861 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 16862 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 16863 }) 16864 public int getTextAlignment() { 16865 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 16866 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 16867 } 16868 16869 /** 16870 * Resolve the text alignment. 16871 * 16872 * @return true if resolution has been done, false otherwise. 16873 * 16874 * @hide 16875 */ 16876 public boolean resolveTextAlignment() { 16877 // Reset any previous text alignment resolution 16878 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 16879 16880 if (hasRtlSupport()) { 16881 // Set resolved text alignment flag depending on text alignment flag 16882 final int textAlignment = getRawTextAlignment(); 16883 switch (textAlignment) { 16884 case TEXT_ALIGNMENT_INHERIT: 16885 // Check if we can resolve the text alignment 16886 if (!canResolveTextAlignment()) { 16887 // We cannot do the resolution if there is no parent so use the default 16888 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16889 // Resolution will need to happen again later 16890 return false; 16891 } 16892 View parent = (View) mParent; 16893 16894 // Parent has not yet resolved, so we still return the default 16895 if (!parent.isTextAlignmentResolved()) { 16896 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16897 // Resolution will need to happen again later 16898 return false; 16899 } 16900 16901 final int parentResolvedTextAlignment = parent.getTextAlignment(); 16902 switch (parentResolvedTextAlignment) { 16903 case TEXT_ALIGNMENT_GRAVITY: 16904 case TEXT_ALIGNMENT_TEXT_START: 16905 case TEXT_ALIGNMENT_TEXT_END: 16906 case TEXT_ALIGNMENT_CENTER: 16907 case TEXT_ALIGNMENT_VIEW_START: 16908 case TEXT_ALIGNMENT_VIEW_END: 16909 // Resolved text alignment is the same as the parent resolved 16910 // text alignment 16911 mPrivateFlags2 |= 16912 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 16913 break; 16914 default: 16915 // Use default resolved text alignment 16916 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16917 } 16918 break; 16919 case TEXT_ALIGNMENT_GRAVITY: 16920 case TEXT_ALIGNMENT_TEXT_START: 16921 case TEXT_ALIGNMENT_TEXT_END: 16922 case TEXT_ALIGNMENT_CENTER: 16923 case TEXT_ALIGNMENT_VIEW_START: 16924 case TEXT_ALIGNMENT_VIEW_END: 16925 // Resolved text alignment is the same as text alignment 16926 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 16927 break; 16928 default: 16929 // Use default resolved text alignment 16930 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16931 } 16932 } else { 16933 // Use default resolved text alignment 16934 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16935 } 16936 16937 // Set the resolved 16938 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 16939 return true; 16940 } 16941 16942 /** 16943 * Check if text alignment resolution can be done. 16944 * 16945 * @return true if text alignment resolution can be done otherwise return false. 16946 */ 16947 private boolean canResolveTextAlignment() { 16948 switch (getRawTextAlignment()) { 16949 case TEXT_DIRECTION_INHERIT: 16950 return (mParent != null) && (mParent instanceof View) && 16951 ((View) mParent).canResolveTextAlignment(); 16952 default: 16953 return true; 16954 } 16955 } 16956 16957 /** 16958 * Reset resolved text alignment. Text alignment will be resolved during a call to 16959 * {@link #onMeasure(int, int)}. 16960 * 16961 * @hide 16962 */ 16963 public void resetResolvedTextAlignment() { 16964 // Reset any previous text alignment resolution 16965 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 16966 // Set to default 16967 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16968 } 16969 16970 /** 16971 * @return true if text alignment is inherited. 16972 * 16973 * @hide 16974 */ 16975 public boolean isTextAlignmentInherited() { 16976 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 16977 } 16978 16979 /** 16980 * @return true if text alignment is resolved. 16981 */ 16982 private boolean isTextAlignmentResolved() { 16983 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 16984 } 16985 16986 /** 16987 * Generate a value suitable for use in {@link #setId(int)}. 16988 * This value will not collide with ID values generated at build time by aapt for R.id. 16989 * 16990 * @return a generated ID value 16991 */ 16992 public static int generateViewId() { 16993 for (;;) { 16994 final int result = sNextGeneratedId.get(); 16995 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 16996 int newValue = result + 1; 16997 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 16998 if (sNextGeneratedId.compareAndSet(result, newValue)) { 16999 return result; 17000 } 17001 } 17002 } 17003 17004 // 17005 // Properties 17006 // 17007 /** 17008 * A Property wrapper around the <code>alpha</code> functionality handled by the 17009 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 17010 */ 17011 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 17012 @Override 17013 public void setValue(View object, float value) { 17014 object.setAlpha(value); 17015 } 17016 17017 @Override 17018 public Float get(View object) { 17019 return object.getAlpha(); 17020 } 17021 }; 17022 17023 /** 17024 * A Property wrapper around the <code>translationX</code> functionality handled by the 17025 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 17026 */ 17027 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 17028 @Override 17029 public void setValue(View object, float value) { 17030 object.setTranslationX(value); 17031 } 17032 17033 @Override 17034 public Float get(View object) { 17035 return object.getTranslationX(); 17036 } 17037 }; 17038 17039 /** 17040 * A Property wrapper around the <code>translationY</code> functionality handled by the 17041 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 17042 */ 17043 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 17044 @Override 17045 public void setValue(View object, float value) { 17046 object.setTranslationY(value); 17047 } 17048 17049 @Override 17050 public Float get(View object) { 17051 return object.getTranslationY(); 17052 } 17053 }; 17054 17055 /** 17056 * A Property wrapper around the <code>x</code> functionality handled by the 17057 * {@link View#setX(float)} and {@link View#getX()} methods. 17058 */ 17059 public static final Property<View, Float> X = new FloatProperty<View>("x") { 17060 @Override 17061 public void setValue(View object, float value) { 17062 object.setX(value); 17063 } 17064 17065 @Override 17066 public Float get(View object) { 17067 return object.getX(); 17068 } 17069 }; 17070 17071 /** 17072 * A Property wrapper around the <code>y</code> functionality handled by the 17073 * {@link View#setY(float)} and {@link View#getY()} methods. 17074 */ 17075 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 17076 @Override 17077 public void setValue(View object, float value) { 17078 object.setY(value); 17079 } 17080 17081 @Override 17082 public Float get(View object) { 17083 return object.getY(); 17084 } 17085 }; 17086 17087 /** 17088 * A Property wrapper around the <code>rotation</code> functionality handled by the 17089 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 17090 */ 17091 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 17092 @Override 17093 public void setValue(View object, float value) { 17094 object.setRotation(value); 17095 } 17096 17097 @Override 17098 public Float get(View object) { 17099 return object.getRotation(); 17100 } 17101 }; 17102 17103 /** 17104 * A Property wrapper around the <code>rotationX</code> functionality handled by the 17105 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 17106 */ 17107 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 17108 @Override 17109 public void setValue(View object, float value) { 17110 object.setRotationX(value); 17111 } 17112 17113 @Override 17114 public Float get(View object) { 17115 return object.getRotationX(); 17116 } 17117 }; 17118 17119 /** 17120 * A Property wrapper around the <code>rotationY</code> functionality handled by the 17121 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 17122 */ 17123 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 17124 @Override 17125 public void setValue(View object, float value) { 17126 object.setRotationY(value); 17127 } 17128 17129 @Override 17130 public Float get(View object) { 17131 return object.getRotationY(); 17132 } 17133 }; 17134 17135 /** 17136 * A Property wrapper around the <code>scaleX</code> functionality handled by the 17137 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 17138 */ 17139 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 17140 @Override 17141 public void setValue(View object, float value) { 17142 object.setScaleX(value); 17143 } 17144 17145 @Override 17146 public Float get(View object) { 17147 return object.getScaleX(); 17148 } 17149 }; 17150 17151 /** 17152 * A Property wrapper around the <code>scaleY</code> functionality handled by the 17153 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 17154 */ 17155 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 17156 @Override 17157 public void setValue(View object, float value) { 17158 object.setScaleY(value); 17159 } 17160 17161 @Override 17162 public Float get(View object) { 17163 return object.getScaleY(); 17164 } 17165 }; 17166 17167 /** 17168 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 17169 * Each MeasureSpec represents a requirement for either the width or the height. 17170 * A MeasureSpec is comprised of a size and a mode. There are three possible 17171 * modes: 17172 * <dl> 17173 * <dt>UNSPECIFIED</dt> 17174 * <dd> 17175 * The parent has not imposed any constraint on the child. It can be whatever size 17176 * it wants. 17177 * </dd> 17178 * 17179 * <dt>EXACTLY</dt> 17180 * <dd> 17181 * The parent has determined an exact size for the child. The child is going to be 17182 * given those bounds regardless of how big it wants to be. 17183 * </dd> 17184 * 17185 * <dt>AT_MOST</dt> 17186 * <dd> 17187 * The child can be as large as it wants up to the specified size. 17188 * </dd> 17189 * </dl> 17190 * 17191 * MeasureSpecs are implemented as ints to reduce object allocation. This class 17192 * is provided to pack and unpack the <size, mode> tuple into the int. 17193 */ 17194 public static class MeasureSpec { 17195 private static final int MODE_SHIFT = 30; 17196 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 17197 17198 /** 17199 * Measure specification mode: The parent has not imposed any constraint 17200 * on the child. It can be whatever size it wants. 17201 */ 17202 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 17203 17204 /** 17205 * Measure specification mode: The parent has determined an exact size 17206 * for the child. The child is going to be given those bounds regardless 17207 * of how big it wants to be. 17208 */ 17209 public static final int EXACTLY = 1 << MODE_SHIFT; 17210 17211 /** 17212 * Measure specification mode: The child can be as large as it wants up 17213 * to the specified size. 17214 */ 17215 public static final int AT_MOST = 2 << MODE_SHIFT; 17216 17217 /** 17218 * Creates a measure specification based on the supplied size and mode. 17219 * 17220 * The mode must always be one of the following: 17221 * <ul> 17222 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 17223 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 17224 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 17225 * </ul> 17226 * 17227 * @param size the size of the measure specification 17228 * @param mode the mode of the measure specification 17229 * @return the measure specification based on size and mode 17230 */ 17231 public static int makeMeasureSpec(int size, int mode) { 17232 return size + mode; 17233 } 17234 17235 /** 17236 * Extracts the mode from the supplied measure specification. 17237 * 17238 * @param measureSpec the measure specification to extract the mode from 17239 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 17240 * {@link android.view.View.MeasureSpec#AT_MOST} or 17241 * {@link android.view.View.MeasureSpec#EXACTLY} 17242 */ 17243 public static int getMode(int measureSpec) { 17244 return (measureSpec & MODE_MASK); 17245 } 17246 17247 /** 17248 * Extracts the size from the supplied measure specification. 17249 * 17250 * @param measureSpec the measure specification to extract the size from 17251 * @return the size in pixels defined in the supplied measure specification 17252 */ 17253 public static int getSize(int measureSpec) { 17254 return (measureSpec & ~MODE_MASK); 17255 } 17256 17257 /** 17258 * Returns a String representation of the specified measure 17259 * specification. 17260 * 17261 * @param measureSpec the measure specification to convert to a String 17262 * @return a String with the following format: "MeasureSpec: MODE SIZE" 17263 */ 17264 public static String toString(int measureSpec) { 17265 int mode = getMode(measureSpec); 17266 int size = getSize(measureSpec); 17267 17268 StringBuilder sb = new StringBuilder("MeasureSpec: "); 17269 17270 if (mode == UNSPECIFIED) 17271 sb.append("UNSPECIFIED "); 17272 else if (mode == EXACTLY) 17273 sb.append("EXACTLY "); 17274 else if (mode == AT_MOST) 17275 sb.append("AT_MOST "); 17276 else 17277 sb.append(mode).append(" "); 17278 17279 sb.append(size); 17280 return sb.toString(); 17281 } 17282 } 17283 17284 class CheckForLongPress implements Runnable { 17285 17286 private int mOriginalWindowAttachCount; 17287 17288 public void run() { 17289 if (isPressed() && (mParent != null) 17290 && mOriginalWindowAttachCount == mWindowAttachCount) { 17291 if (performLongClick()) { 17292 mHasPerformedLongPress = true; 17293 } 17294 } 17295 } 17296 17297 public void rememberWindowAttachCount() { 17298 mOriginalWindowAttachCount = mWindowAttachCount; 17299 } 17300 } 17301 17302 private final class CheckForTap implements Runnable { 17303 public void run() { 17304 mPrivateFlags &= ~PFLAG_PREPRESSED; 17305 setPressed(true); 17306 checkForLongClick(ViewConfiguration.getTapTimeout()); 17307 } 17308 } 17309 17310 private final class PerformClick implements Runnable { 17311 public void run() { 17312 performClick(); 17313 } 17314 } 17315 17316 /** @hide */ 17317 public void hackTurnOffWindowResizeAnim(boolean off) { 17318 mAttachInfo.mTurnOffWindowResizeAnim = off; 17319 } 17320 17321 /** 17322 * This method returns a ViewPropertyAnimator object, which can be used to animate 17323 * specific properties on this View. 17324 * 17325 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 17326 */ 17327 public ViewPropertyAnimator animate() { 17328 if (mAnimator == null) { 17329 mAnimator = new ViewPropertyAnimator(this); 17330 } 17331 return mAnimator; 17332 } 17333 17334 /** 17335 * Interface definition for a callback to be invoked when a hardware key event is 17336 * dispatched to this view. The callback will be invoked before the key event is 17337 * given to the view. This is only useful for hardware keyboards; a software input 17338 * method has no obligation to trigger this listener. 17339 */ 17340 public interface OnKeyListener { 17341 /** 17342 * Called when a hardware key is dispatched to a view. This allows listeners to 17343 * get a chance to respond before the target view. 17344 * <p>Key presses in software keyboards will generally NOT trigger this method, 17345 * although some may elect to do so in some situations. Do not assume a 17346 * software input method has to be key-based; even if it is, it may use key presses 17347 * in a different way than you expect, so there is no way to reliably catch soft 17348 * input key presses. 17349 * 17350 * @param v The view the key has been dispatched to. 17351 * @param keyCode The code for the physical key that was pressed 17352 * @param event The KeyEvent object containing full information about 17353 * the event. 17354 * @return True if the listener has consumed the event, false otherwise. 17355 */ 17356 boolean onKey(View v, int keyCode, KeyEvent event); 17357 } 17358 17359 /** 17360 * Interface definition for a callback to be invoked when a touch event is 17361 * dispatched to this view. The callback will be invoked before the touch 17362 * event is given to the view. 17363 */ 17364 public interface OnTouchListener { 17365 /** 17366 * Called when a touch event is dispatched to a view. This allows listeners to 17367 * get a chance to respond before the target view. 17368 * 17369 * @param v The view the touch event has been dispatched to. 17370 * @param event The MotionEvent object containing full information about 17371 * the event. 17372 * @return True if the listener has consumed the event, false otherwise. 17373 */ 17374 boolean onTouch(View v, MotionEvent event); 17375 } 17376 17377 /** 17378 * Interface definition for a callback to be invoked when a hover event is 17379 * dispatched to this view. The callback will be invoked before the hover 17380 * event is given to the view. 17381 */ 17382 public interface OnHoverListener { 17383 /** 17384 * Called when a hover event is dispatched to a view. This allows listeners to 17385 * get a chance to respond before the target view. 17386 * 17387 * @param v The view the hover event has been dispatched to. 17388 * @param event The MotionEvent object containing full information about 17389 * the event. 17390 * @return True if the listener has consumed the event, false otherwise. 17391 */ 17392 boolean onHover(View v, MotionEvent event); 17393 } 17394 17395 /** 17396 * Interface definition for a callback to be invoked when a generic motion event is 17397 * dispatched to this view. The callback will be invoked before the generic motion 17398 * event is given to the view. 17399 */ 17400 public interface OnGenericMotionListener { 17401 /** 17402 * Called when a generic motion event is dispatched to a view. This allows listeners to 17403 * get a chance to respond before the target view. 17404 * 17405 * @param v The view the generic motion event has been dispatched to. 17406 * @param event The MotionEvent object containing full information about 17407 * the event. 17408 * @return True if the listener has consumed the event, false otherwise. 17409 */ 17410 boolean onGenericMotion(View v, MotionEvent event); 17411 } 17412 17413 /** 17414 * Interface definition for a callback to be invoked when a view has been clicked and held. 17415 */ 17416 public interface OnLongClickListener { 17417 /** 17418 * Called when a view has been clicked and held. 17419 * 17420 * @param v The view that was clicked and held. 17421 * 17422 * @return true if the callback consumed the long click, false otherwise. 17423 */ 17424 boolean onLongClick(View v); 17425 } 17426 17427 /** 17428 * Interface definition for a callback to be invoked when a drag is being dispatched 17429 * to this view. The callback will be invoked before the hosting view's own 17430 * onDrag(event) method. If the listener wants to fall back to the hosting view's 17431 * onDrag(event) behavior, it should return 'false' from this callback. 17432 * 17433 * <div class="special reference"> 17434 * <h3>Developer Guides</h3> 17435 * <p>For a guide to implementing drag and drop features, read the 17436 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17437 * </div> 17438 */ 17439 public interface OnDragListener { 17440 /** 17441 * Called when a drag event is dispatched to a view. This allows listeners 17442 * to get a chance to override base View behavior. 17443 * 17444 * @param v The View that received the drag event. 17445 * @param event The {@link android.view.DragEvent} object for the drag event. 17446 * @return {@code true} if the drag event was handled successfully, or {@code false} 17447 * if the drag event was not handled. Note that {@code false} will trigger the View 17448 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 17449 */ 17450 boolean onDrag(View v, DragEvent event); 17451 } 17452 17453 /** 17454 * Interface definition for a callback to be invoked when the focus state of 17455 * a view changed. 17456 */ 17457 public interface OnFocusChangeListener { 17458 /** 17459 * Called when the focus state of a view has changed. 17460 * 17461 * @param v The view whose state has changed. 17462 * @param hasFocus The new focus state of v. 17463 */ 17464 void onFocusChange(View v, boolean hasFocus); 17465 } 17466 17467 /** 17468 * Interface definition for a callback to be invoked when a view is clicked. 17469 */ 17470 public interface OnClickListener { 17471 /** 17472 * Called when a view has been clicked. 17473 * 17474 * @param v The view that was clicked. 17475 */ 17476 void onClick(View v); 17477 } 17478 17479 /** 17480 * Interface definition for a callback to be invoked when the context menu 17481 * for this view is being built. 17482 */ 17483 public interface OnCreateContextMenuListener { 17484 /** 17485 * Called when the context menu for this view is being built. It is not 17486 * safe to hold onto the menu after this method returns. 17487 * 17488 * @param menu The context menu that is being built 17489 * @param v The view for which the context menu is being built 17490 * @param menuInfo Extra information about the item for which the 17491 * context menu should be shown. This information will vary 17492 * depending on the class of v. 17493 */ 17494 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 17495 } 17496 17497 /** 17498 * Interface definition for a callback to be invoked when the status bar changes 17499 * visibility. This reports <strong>global</strong> changes to the system UI 17500 * state, not what the application is requesting. 17501 * 17502 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 17503 */ 17504 public interface OnSystemUiVisibilityChangeListener { 17505 /** 17506 * Called when the status bar changes visibility because of a call to 17507 * {@link View#setSystemUiVisibility(int)}. 17508 * 17509 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17510 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 17511 * This tells you the <strong>global</strong> state of these UI visibility 17512 * flags, not what your app is currently applying. 17513 */ 17514 public void onSystemUiVisibilityChange(int visibility); 17515 } 17516 17517 /** 17518 * Interface definition for a callback to be invoked when this view is attached 17519 * or detached from its window. 17520 */ 17521 public interface OnAttachStateChangeListener { 17522 /** 17523 * Called when the view is attached to a window. 17524 * @param v The view that was attached 17525 */ 17526 public void onViewAttachedToWindow(View v); 17527 /** 17528 * Called when the view is detached from a window. 17529 * @param v The view that was detached 17530 */ 17531 public void onViewDetachedFromWindow(View v); 17532 } 17533 17534 private final class UnsetPressedState implements Runnable { 17535 public void run() { 17536 setPressed(false); 17537 } 17538 } 17539 17540 /** 17541 * Base class for derived classes that want to save and restore their own 17542 * state in {@link android.view.View#onSaveInstanceState()}. 17543 */ 17544 public static class BaseSavedState extends AbsSavedState { 17545 /** 17546 * Constructor used when reading from a parcel. Reads the state of the superclass. 17547 * 17548 * @param source 17549 */ 17550 public BaseSavedState(Parcel source) { 17551 super(source); 17552 } 17553 17554 /** 17555 * Constructor called by derived classes when creating their SavedState objects 17556 * 17557 * @param superState The state of the superclass of this view 17558 */ 17559 public BaseSavedState(Parcelable superState) { 17560 super(superState); 17561 } 17562 17563 public static final Parcelable.Creator<BaseSavedState> CREATOR = 17564 new Parcelable.Creator<BaseSavedState>() { 17565 public BaseSavedState createFromParcel(Parcel in) { 17566 return new BaseSavedState(in); 17567 } 17568 17569 public BaseSavedState[] newArray(int size) { 17570 return new BaseSavedState[size]; 17571 } 17572 }; 17573 } 17574 17575 /** 17576 * A set of information given to a view when it is attached to its parent 17577 * window. 17578 */ 17579 static class AttachInfo { 17580 interface Callbacks { 17581 void playSoundEffect(int effectId); 17582 boolean performHapticFeedback(int effectId, boolean always); 17583 } 17584 17585 /** 17586 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 17587 * to a Handler. This class contains the target (View) to invalidate and 17588 * the coordinates of the dirty rectangle. 17589 * 17590 * For performance purposes, this class also implements a pool of up to 17591 * POOL_LIMIT objects that get reused. This reduces memory allocations 17592 * whenever possible. 17593 */ 17594 static class InvalidateInfo implements Poolable<InvalidateInfo> { 17595 private static final int POOL_LIMIT = 10; 17596 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 17597 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 17598 public InvalidateInfo newInstance() { 17599 return new InvalidateInfo(); 17600 } 17601 17602 public void onAcquired(InvalidateInfo element) { 17603 } 17604 17605 public void onReleased(InvalidateInfo element) { 17606 element.target = null; 17607 } 17608 }, POOL_LIMIT) 17609 ); 17610 17611 private InvalidateInfo mNext; 17612 private boolean mIsPooled; 17613 17614 View target; 17615 17616 int left; 17617 int top; 17618 int right; 17619 int bottom; 17620 17621 public void setNextPoolable(InvalidateInfo element) { 17622 mNext = element; 17623 } 17624 17625 public InvalidateInfo getNextPoolable() { 17626 return mNext; 17627 } 17628 17629 static InvalidateInfo acquire() { 17630 return sPool.acquire(); 17631 } 17632 17633 void release() { 17634 sPool.release(this); 17635 } 17636 17637 public boolean isPooled() { 17638 return mIsPooled; 17639 } 17640 17641 public void setPooled(boolean isPooled) { 17642 mIsPooled = isPooled; 17643 } 17644 } 17645 17646 final IWindowSession mSession; 17647 17648 final IWindow mWindow; 17649 17650 final IBinder mWindowToken; 17651 17652 final Display mDisplay; 17653 17654 final Callbacks mRootCallbacks; 17655 17656 HardwareCanvas mHardwareCanvas; 17657 17658 /** 17659 * The top view of the hierarchy. 17660 */ 17661 View mRootView; 17662 17663 IBinder mPanelParentWindowToken; 17664 Surface mSurface; 17665 17666 boolean mHardwareAccelerated; 17667 boolean mHardwareAccelerationRequested; 17668 HardwareRenderer mHardwareRenderer; 17669 17670 boolean mScreenOn; 17671 17672 /** 17673 * Scale factor used by the compatibility mode 17674 */ 17675 float mApplicationScale; 17676 17677 /** 17678 * Indicates whether the application is in compatibility mode 17679 */ 17680 boolean mScalingRequired; 17681 17682 /** 17683 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 17684 */ 17685 boolean mTurnOffWindowResizeAnim; 17686 17687 /** 17688 * Left position of this view's window 17689 */ 17690 int mWindowLeft; 17691 17692 /** 17693 * Top position of this view's window 17694 */ 17695 int mWindowTop; 17696 17697 /** 17698 * Indicates whether views need to use 32-bit drawing caches 17699 */ 17700 boolean mUse32BitDrawingCache; 17701 17702 /** 17703 * For windows that are full-screen but using insets to layout inside 17704 * of the screen decorations, these are the current insets for the 17705 * content of the window. 17706 */ 17707 final Rect mContentInsets = new Rect(); 17708 17709 /** 17710 * For windows that are full-screen but using insets to layout inside 17711 * of the screen decorations, these are the current insets for the 17712 * actual visible parts of the window. 17713 */ 17714 final Rect mVisibleInsets = new Rect(); 17715 17716 /** 17717 * The internal insets given by this window. This value is 17718 * supplied by the client (through 17719 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 17720 * be given to the window manager when changed to be used in laying 17721 * out windows behind it. 17722 */ 17723 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 17724 = new ViewTreeObserver.InternalInsetsInfo(); 17725 17726 /** 17727 * All views in the window's hierarchy that serve as scroll containers, 17728 * used to determine if the window can be resized or must be panned 17729 * to adjust for a soft input area. 17730 */ 17731 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 17732 17733 final KeyEvent.DispatcherState mKeyDispatchState 17734 = new KeyEvent.DispatcherState(); 17735 17736 /** 17737 * Indicates whether the view's window currently has the focus. 17738 */ 17739 boolean mHasWindowFocus; 17740 17741 /** 17742 * The current visibility of the window. 17743 */ 17744 int mWindowVisibility; 17745 17746 /** 17747 * Indicates the time at which drawing started to occur. 17748 */ 17749 long mDrawingTime; 17750 17751 /** 17752 * Indicates whether or not ignoring the DIRTY_MASK flags. 17753 */ 17754 boolean mIgnoreDirtyState; 17755 17756 /** 17757 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 17758 * to avoid clearing that flag prematurely. 17759 */ 17760 boolean mSetIgnoreDirtyState = false; 17761 17762 /** 17763 * Indicates whether the view's window is currently in touch mode. 17764 */ 17765 boolean mInTouchMode; 17766 17767 /** 17768 * Indicates that ViewAncestor should trigger a global layout change 17769 * the next time it performs a traversal 17770 */ 17771 boolean mRecomputeGlobalAttributes; 17772 17773 /** 17774 * Always report new attributes at next traversal. 17775 */ 17776 boolean mForceReportNewAttributes; 17777 17778 /** 17779 * Set during a traveral if any views want to keep the screen on. 17780 */ 17781 boolean mKeepScreenOn; 17782 17783 /** 17784 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 17785 */ 17786 int mSystemUiVisibility; 17787 17788 /** 17789 * Hack to force certain system UI visibility flags to be cleared. 17790 */ 17791 int mDisabledSystemUiVisibility; 17792 17793 /** 17794 * Last global system UI visibility reported by the window manager. 17795 */ 17796 int mGlobalSystemUiVisibility; 17797 17798 /** 17799 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 17800 * attached. 17801 */ 17802 boolean mHasSystemUiListeners; 17803 17804 /** 17805 * Set if the visibility of any views has changed. 17806 */ 17807 boolean mViewVisibilityChanged; 17808 17809 /** 17810 * Set to true if a view has been scrolled. 17811 */ 17812 boolean mViewScrollChanged; 17813 17814 /** 17815 * Global to the view hierarchy used as a temporary for dealing with 17816 * x/y points in the transparent region computations. 17817 */ 17818 final int[] mTransparentLocation = new int[2]; 17819 17820 /** 17821 * Global to the view hierarchy used as a temporary for dealing with 17822 * x/y points in the ViewGroup.invalidateChild implementation. 17823 */ 17824 final int[] mInvalidateChildLocation = new int[2]; 17825 17826 17827 /** 17828 * Global to the view hierarchy used as a temporary for dealing with 17829 * x/y location when view is transformed. 17830 */ 17831 final float[] mTmpTransformLocation = new float[2]; 17832 17833 /** 17834 * The view tree observer used to dispatch global events like 17835 * layout, pre-draw, touch mode change, etc. 17836 */ 17837 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 17838 17839 /** 17840 * A Canvas used by the view hierarchy to perform bitmap caching. 17841 */ 17842 Canvas mCanvas; 17843 17844 /** 17845 * The view root impl. 17846 */ 17847 final ViewRootImpl mViewRootImpl; 17848 17849 /** 17850 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 17851 * handler can be used to pump events in the UI events queue. 17852 */ 17853 final Handler mHandler; 17854 17855 /** 17856 * Temporary for use in computing invalidate rectangles while 17857 * calling up the hierarchy. 17858 */ 17859 final Rect mTmpInvalRect = new Rect(); 17860 17861 /** 17862 * Temporary for use in computing hit areas with transformed views 17863 */ 17864 final RectF mTmpTransformRect = new RectF(); 17865 17866 /** 17867 * Temporary for use in transforming invalidation rect 17868 */ 17869 final Matrix mTmpMatrix = new Matrix(); 17870 17871 /** 17872 * Temporary for use in transforming invalidation rect 17873 */ 17874 final Transformation mTmpTransformation = new Transformation(); 17875 17876 /** 17877 * Temporary list for use in collecting focusable descendents of a view. 17878 */ 17879 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 17880 17881 /** 17882 * The id of the window for accessibility purposes. 17883 */ 17884 int mAccessibilityWindowId = View.NO_ID; 17885 17886 /** 17887 * Whether to ingore not exposed for accessibility Views when 17888 * reporting the view tree to accessibility services. 17889 */ 17890 boolean mIncludeNotImportantViews; 17891 17892 /** 17893 * The drawable for highlighting accessibility focus. 17894 */ 17895 Drawable mAccessibilityFocusDrawable; 17896 17897 /** 17898 * Show where the margins, bounds and layout bounds are for each view. 17899 */ 17900 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 17901 17902 /** 17903 * Point used to compute visible regions. 17904 */ 17905 final Point mPoint = new Point(); 17906 17907 /** 17908 * Creates a new set of attachment information with the specified 17909 * events handler and thread. 17910 * 17911 * @param handler the events handler the view must use 17912 */ 17913 AttachInfo(IWindowSession session, IWindow window, Display display, 17914 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 17915 mSession = session; 17916 mWindow = window; 17917 mWindowToken = window.asBinder(); 17918 mDisplay = display; 17919 mViewRootImpl = viewRootImpl; 17920 mHandler = handler; 17921 mRootCallbacks = effectPlayer; 17922 } 17923 } 17924 17925 /** 17926 * <p>ScrollabilityCache holds various fields used by a View when scrolling 17927 * is supported. This avoids keeping too many unused fields in most 17928 * instances of View.</p> 17929 */ 17930 private static class ScrollabilityCache implements Runnable { 17931 17932 /** 17933 * Scrollbars are not visible 17934 */ 17935 public static final int OFF = 0; 17936 17937 /** 17938 * Scrollbars are visible 17939 */ 17940 public static final int ON = 1; 17941 17942 /** 17943 * Scrollbars are fading away 17944 */ 17945 public static final int FADING = 2; 17946 17947 public boolean fadeScrollBars; 17948 17949 public int fadingEdgeLength; 17950 public int scrollBarDefaultDelayBeforeFade; 17951 public int scrollBarFadeDuration; 17952 17953 public int scrollBarSize; 17954 public ScrollBarDrawable scrollBar; 17955 public float[] interpolatorValues; 17956 public View host; 17957 17958 public final Paint paint; 17959 public final Matrix matrix; 17960 public Shader shader; 17961 17962 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 17963 17964 private static final float[] OPAQUE = { 255 }; 17965 private static final float[] TRANSPARENT = { 0.0f }; 17966 17967 /** 17968 * When fading should start. This time moves into the future every time 17969 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 17970 */ 17971 public long fadeStartTime; 17972 17973 17974 /** 17975 * The current state of the scrollbars: ON, OFF, or FADING 17976 */ 17977 public int state = OFF; 17978 17979 private int mLastColor; 17980 17981 public ScrollabilityCache(ViewConfiguration configuration, View host) { 17982 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 17983 scrollBarSize = configuration.getScaledScrollBarSize(); 17984 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 17985 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 17986 17987 paint = new Paint(); 17988 matrix = new Matrix(); 17989 // use use a height of 1, and then wack the matrix each time we 17990 // actually use it. 17991 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 17992 paint.setShader(shader); 17993 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 17994 17995 this.host = host; 17996 } 17997 17998 public void setFadeColor(int color) { 17999 if (color != mLastColor) { 18000 mLastColor = color; 18001 18002 if (color != 0) { 18003 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 18004 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 18005 paint.setShader(shader); 18006 // Restore the default transfer mode (src_over) 18007 paint.setXfermode(null); 18008 } else { 18009 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 18010 paint.setShader(shader); 18011 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 18012 } 18013 } 18014 } 18015 18016 public void run() { 18017 long now = AnimationUtils.currentAnimationTimeMillis(); 18018 if (now >= fadeStartTime) { 18019 18020 // the animation fades the scrollbars out by changing 18021 // the opacity (alpha) from fully opaque to fully 18022 // transparent 18023 int nextFrame = (int) now; 18024 int framesCount = 0; 18025 18026 Interpolator interpolator = scrollBarInterpolator; 18027 18028 // Start opaque 18029 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 18030 18031 // End transparent 18032 nextFrame += scrollBarFadeDuration; 18033 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 18034 18035 state = FADING; 18036 18037 // Kick off the fade animation 18038 host.invalidate(true); 18039 } 18040 } 18041 } 18042 18043 /** 18044 * Resuable callback for sending 18045 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 18046 */ 18047 private class SendViewScrolledAccessibilityEvent implements Runnable { 18048 public volatile boolean mIsPending; 18049 18050 public void run() { 18051 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 18052 mIsPending = false; 18053 } 18054 } 18055 18056 /** 18057 * <p> 18058 * This class represents a delegate that can be registered in a {@link View} 18059 * to enhance accessibility support via composition rather via inheritance. 18060 * It is specifically targeted to widget developers that extend basic View 18061 * classes i.e. classes in package android.view, that would like their 18062 * applications to be backwards compatible. 18063 * </p> 18064 * <div class="special reference"> 18065 * <h3>Developer Guides</h3> 18066 * <p>For more information about making applications accessible, read the 18067 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 18068 * developer guide.</p> 18069 * </div> 18070 * <p> 18071 * A scenario in which a developer would like to use an accessibility delegate 18072 * is overriding a method introduced in a later API version then the minimal API 18073 * version supported by the application. For example, the method 18074 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 18075 * in API version 4 when the accessibility APIs were first introduced. If a 18076 * developer would like his application to run on API version 4 devices (assuming 18077 * all other APIs used by the application are version 4 or lower) and take advantage 18078 * of this method, instead of overriding the method which would break the application's 18079 * backwards compatibility, he can override the corresponding method in this 18080 * delegate and register the delegate in the target View if the API version of 18081 * the system is high enough i.e. the API version is same or higher to the API 18082 * version that introduced 18083 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 18084 * </p> 18085 * <p> 18086 * Here is an example implementation: 18087 * </p> 18088 * <code><pre><p> 18089 * if (Build.VERSION.SDK_INT >= 14) { 18090 * // If the API version is equal of higher than the version in 18091 * // which onInitializeAccessibilityNodeInfo was introduced we 18092 * // register a delegate with a customized implementation. 18093 * View view = findViewById(R.id.view_id); 18094 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 18095 * public void onInitializeAccessibilityNodeInfo(View host, 18096 * AccessibilityNodeInfo info) { 18097 * // Let the default implementation populate the info. 18098 * super.onInitializeAccessibilityNodeInfo(host, info); 18099 * // Set some other information. 18100 * info.setEnabled(host.isEnabled()); 18101 * } 18102 * }); 18103 * } 18104 * </code></pre></p> 18105 * <p> 18106 * This delegate contains methods that correspond to the accessibility methods 18107 * in View. If a delegate has been specified the implementation in View hands 18108 * off handling to the corresponding method in this delegate. The default 18109 * implementation the delegate methods behaves exactly as the corresponding 18110 * method in View for the case of no accessibility delegate been set. Hence, 18111 * to customize the behavior of a View method, clients can override only the 18112 * corresponding delegate method without altering the behavior of the rest 18113 * accessibility related methods of the host view. 18114 * </p> 18115 */ 18116 public static class AccessibilityDelegate { 18117 18118 /** 18119 * Sends an accessibility event of the given type. If accessibility is not 18120 * enabled this method has no effect. 18121 * <p> 18122 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 18123 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 18124 * been set. 18125 * </p> 18126 * 18127 * @param host The View hosting the delegate. 18128 * @param eventType The type of the event to send. 18129 * 18130 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 18131 */ 18132 public void sendAccessibilityEvent(View host, int eventType) { 18133 host.sendAccessibilityEventInternal(eventType); 18134 } 18135 18136 /** 18137 * Performs the specified accessibility action on the view. For 18138 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 18139 * <p> 18140 * The default implementation behaves as 18141 * {@link View#performAccessibilityAction(int, Bundle) 18142 * View#performAccessibilityAction(int, Bundle)} for the case of 18143 * no accessibility delegate been set. 18144 * </p> 18145 * 18146 * @param action The action to perform. 18147 * @return Whether the action was performed. 18148 * 18149 * @see View#performAccessibilityAction(int, Bundle) 18150 * View#performAccessibilityAction(int, Bundle) 18151 */ 18152 public boolean performAccessibilityAction(View host, int action, Bundle args) { 18153 return host.performAccessibilityActionInternal(action, args); 18154 } 18155 18156 /** 18157 * Sends an accessibility event. This method behaves exactly as 18158 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 18159 * empty {@link AccessibilityEvent} and does not perform a check whether 18160 * accessibility is enabled. 18161 * <p> 18162 * The default implementation behaves as 18163 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18164 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 18165 * the case of no accessibility delegate been set. 18166 * </p> 18167 * 18168 * @param host The View hosting the delegate. 18169 * @param event The event to send. 18170 * 18171 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18172 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18173 */ 18174 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 18175 host.sendAccessibilityEventUncheckedInternal(event); 18176 } 18177 18178 /** 18179 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 18180 * to its children for adding their text content to the event. 18181 * <p> 18182 * The default implementation behaves as 18183 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18184 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 18185 * the case of no accessibility delegate been set. 18186 * </p> 18187 * 18188 * @param host The View hosting the delegate. 18189 * @param event The event. 18190 * @return True if the event population was completed. 18191 * 18192 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18193 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18194 */ 18195 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18196 return host.dispatchPopulateAccessibilityEventInternal(event); 18197 } 18198 18199 /** 18200 * Gives a chance to the host View to populate the accessibility event with its 18201 * text content. 18202 * <p> 18203 * The default implementation behaves as 18204 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 18205 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 18206 * the case of no accessibility delegate been set. 18207 * </p> 18208 * 18209 * @param host The View hosting the delegate. 18210 * @param event The accessibility event which to populate. 18211 * 18212 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 18213 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 18214 */ 18215 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18216 host.onPopulateAccessibilityEventInternal(event); 18217 } 18218 18219 /** 18220 * Initializes an {@link AccessibilityEvent} with information about the 18221 * the host View which is the event source. 18222 * <p> 18223 * The default implementation behaves as 18224 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 18225 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 18226 * the case of no accessibility delegate been set. 18227 * </p> 18228 * 18229 * @param host The View hosting the delegate. 18230 * @param event The event to initialize. 18231 * 18232 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 18233 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 18234 */ 18235 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 18236 host.onInitializeAccessibilityEventInternal(event); 18237 } 18238 18239 /** 18240 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 18241 * <p> 18242 * The default implementation behaves as 18243 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18244 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 18245 * the case of no accessibility delegate been set. 18246 * </p> 18247 * 18248 * @param host The View hosting the delegate. 18249 * @param info The instance to initialize. 18250 * 18251 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18252 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18253 */ 18254 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 18255 host.onInitializeAccessibilityNodeInfoInternal(info); 18256 } 18257 18258 /** 18259 * Called when a child of the host View has requested sending an 18260 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 18261 * to augment the event. 18262 * <p> 18263 * The default implementation behaves as 18264 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18265 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 18266 * the case of no accessibility delegate been set. 18267 * </p> 18268 * 18269 * @param host The View hosting the delegate. 18270 * @param child The child which requests sending the event. 18271 * @param event The event to be sent. 18272 * @return True if the event should be sent 18273 * 18274 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18275 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18276 */ 18277 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 18278 AccessibilityEvent event) { 18279 return host.onRequestSendAccessibilityEventInternal(child, event); 18280 } 18281 18282 /** 18283 * Gets the provider for managing a virtual view hierarchy rooted at this View 18284 * and reported to {@link android.accessibilityservice.AccessibilityService}s 18285 * that explore the window content. 18286 * <p> 18287 * The default implementation behaves as 18288 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 18289 * the case of no accessibility delegate been set. 18290 * </p> 18291 * 18292 * @return The provider. 18293 * 18294 * @see AccessibilityNodeProvider 18295 */ 18296 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 18297 return null; 18298 } 18299 } 18300 18301 private class MatchIdPredicate implements Predicate<View> { 18302 public int mId; 18303 18304 @Override 18305 public boolean apply(View view) { 18306 return (view.mID == mId); 18307 } 18308 } 18309 18310 private class MatchLabelForPredicate implements Predicate<View> { 18311 private int mLabeledId; 18312 18313 @Override 18314 public boolean apply(View view) { 18315 return (view.mLabelForId == mLabeledId); 18316 } 18317 } 18318 18319 /** 18320 * Dump all private flags in readable format, useful for documentation and 18321 * sanity checking. 18322 */ 18323 private static void dumpFlags() { 18324 final HashMap<String, String> found = Maps.newHashMap(); 18325 try { 18326 for (Field field : View.class.getDeclaredFields()) { 18327 final int modifiers = field.getModifiers(); 18328 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 18329 if (field.getType().equals(int.class)) { 18330 final int value = field.getInt(null); 18331 dumpFlag(found, field.getName(), value); 18332 } else if (field.getType().equals(int[].class)) { 18333 final int[] values = (int[]) field.get(null); 18334 for (int i = 0; i < values.length; i++) { 18335 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 18336 } 18337 } 18338 } 18339 } 18340 } catch (IllegalAccessException e) { 18341 throw new RuntimeException(e); 18342 } 18343 18344 final ArrayList<String> keys = Lists.newArrayList(); 18345 keys.addAll(found.keySet()); 18346 Collections.sort(keys); 18347 for (String key : keys) { 18348 Log.d(VIEW_LOG_TAG, found.get(key)); 18349 } 18350 } 18351 18352 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 18353 // Sort flags by prefix, then by bits, always keeping unique keys 18354 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 18355 final int prefix = name.indexOf('_'); 18356 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 18357 final String output = bits + " " + name; 18358 found.put(key, output); 18359 } 18360} 18361