View.java revision fbd8f69a84163ef1cf52b07966320caf448c2bc9
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 com.android.internal.R; 20import com.android.internal.view.menu.MenuBuilder; 21 22import android.content.Context; 23import android.content.res.Resources; 24import android.content.res.TypedArray; 25import android.graphics.Bitmap; 26import android.graphics.Canvas; 27import android.graphics.LinearGradient; 28import android.graphics.Matrix; 29import android.graphics.Paint; 30import android.graphics.PixelFormat; 31import android.graphics.Point; 32import android.graphics.PorterDuff; 33import android.graphics.PorterDuffXfermode; 34import android.graphics.Rect; 35import android.graphics.Region; 36import android.graphics.Shader; 37import android.graphics.drawable.ColorDrawable; 38import android.graphics.drawable.Drawable; 39import android.os.Handler; 40import android.os.IBinder; 41import android.os.Message; 42import android.os.Parcel; 43import android.os.Parcelable; 44import android.os.RemoteException; 45import android.os.SystemClock; 46import android.os.SystemProperties; 47import android.util.AttributeSet; 48import android.util.Config; 49import android.util.EventLog; 50import android.util.Log; 51import android.util.Pool; 52import android.util.Poolable; 53import android.util.PoolableManager; 54import android.util.Pools; 55import android.util.SparseArray; 56import android.view.ContextMenu.ContextMenuInfo; 57import android.view.accessibility.AccessibilityEvent; 58import android.view.accessibility.AccessibilityEventSource; 59import android.view.accessibility.AccessibilityManager; 60import android.view.animation.Animation; 61import android.view.inputmethod.EditorInfo; 62import android.view.inputmethod.InputConnection; 63import android.view.inputmethod.InputMethodManager; 64import android.widget.ScrollBarDrawable; 65 66import java.lang.ref.SoftReference; 67import java.lang.reflect.InvocationTargetException; 68import java.lang.reflect.Method; 69import java.util.ArrayList; 70import java.util.Arrays; 71import java.util.WeakHashMap; 72 73/** 74 * <p> 75 * This class represents the basic building block for user interface components. A View 76 * occupies a rectangular area on the screen and is responsible for drawing and 77 * event handling. View is the base class for <em>widgets</em>, which are 78 * used to create interactive UI components (buttons, text fields, etc.). The 79 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 80 * are invisible containers that hold other Views (or other ViewGroups) and define 81 * their layout properties. 82 * </p> 83 * 84 * <div class="special"> 85 * <p>For an introduction to using this class to develop your 86 * application's user interface, read the Developer Guide documentation on 87 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics 88 * include: 89 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a> 90 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a> 91 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a> 92 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a> 93 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a> 94 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a> 95 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a> 96 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>. 97 * </p> 98 * </div> 99 * 100 * <a name="Using"></a> 101 * <h3>Using Views</h3> 102 * <p> 103 * All of the views in a window are arranged in a single tree. You can add views 104 * either from code or by specifying a tree of views in one or more XML layout 105 * files. There are many specialized subclasses of views that act as controls or 106 * are capable of displaying text, images, or other content. 107 * </p> 108 * <p> 109 * Once you have created a tree of views, there are typically a few types of 110 * common operations you may wish to perform: 111 * <ul> 112 * <li><strong>Set properties:</strong> for example setting the text of a 113 * {@link android.widget.TextView}. The available properties and the methods 114 * that set them will vary among the different subclasses of views. Note that 115 * properties that are known at build time can be set in the XML layout 116 * files.</li> 117 * <li><strong>Set focus:</strong> The framework will handled moving focus in 118 * response to user input. To force focus to a specific view, call 119 * {@link #requestFocus}.</li> 120 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 121 * that will be notified when something interesting happens to the view. For 122 * example, all views will let you set a listener to be notified when the view 123 * gains or loses focus. You can register such a listener using 124 * {@link #setOnFocusChangeListener}. Other view subclasses offer more 125 * specialized listeners. For example, a Button exposes a listener to notify 126 * clients when the button is clicked.</li> 127 * <li><strong>Set visibility:</strong> You can hide or show views using 128 * {@link #setVisibility}.</li> 129 * </ul> 130 * </p> 131 * <p><em> 132 * Note: The Android framework is responsible for measuring, laying out and 133 * drawing views. You should not call methods that perform these actions on 134 * views yourself unless you are actually implementing a 135 * {@link android.view.ViewGroup}. 136 * </em></p> 137 * 138 * <a name="Lifecycle"></a> 139 * <h3>Implementing a Custom View</h3> 140 * 141 * <p> 142 * To implement a custom view, you will usually begin by providing overrides for 143 * some of the standard methods that the framework calls on all views. You do 144 * not need to override all of these methods. In fact, you can start by just 145 * overriding {@link #onDraw(android.graphics.Canvas)}. 146 * <table border="2" width="85%" align="center" cellpadding="5"> 147 * <thead> 148 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 149 * </thead> 150 * 151 * <tbody> 152 * <tr> 153 * <td rowspan="2">Creation</td> 154 * <td>Constructors</td> 155 * <td>There is a form of the constructor that are called when the view 156 * is created from code and a form that is called when the view is 157 * inflated from a layout file. The second form should parse and apply 158 * any attributes defined in the layout file. 159 * </td> 160 * </tr> 161 * <tr> 162 * <td><code>{@link #onFinishInflate()}</code></td> 163 * <td>Called after a view and all of its children has been inflated 164 * from XML.</td> 165 * </tr> 166 * 167 * <tr> 168 * <td rowspan="3">Layout</td> 169 * <td><code>{@link #onMeasure}</code></td> 170 * <td>Called to determine the size requirements for this view and all 171 * of its children. 172 * </td> 173 * </tr> 174 * <tr> 175 * <td><code>{@link #onLayout}</code></td> 176 * <td>Called when this view should assign a size and position to all 177 * of its children. 178 * </td> 179 * </tr> 180 * <tr> 181 * <td><code>{@link #onSizeChanged}</code></td> 182 * <td>Called when the size of this view has changed. 183 * </td> 184 * </tr> 185 * 186 * <tr> 187 * <td>Drawing</td> 188 * <td><code>{@link #onDraw}</code></td> 189 * <td>Called when the view should render its content. 190 * </td> 191 * </tr> 192 * 193 * <tr> 194 * <td rowspan="4">Event processing</td> 195 * <td><code>{@link #onKeyDown}</code></td> 196 * <td>Called when a new key event occurs. 197 * </td> 198 * </tr> 199 * <tr> 200 * <td><code>{@link #onKeyUp}</code></td> 201 * <td>Called when a key up event occurs. 202 * </td> 203 * </tr> 204 * <tr> 205 * <td><code>{@link #onTrackballEvent}</code></td> 206 * <td>Called when a trackball motion event occurs. 207 * </td> 208 * </tr> 209 * <tr> 210 * <td><code>{@link #onTouchEvent}</code></td> 211 * <td>Called when a touch screen motion event occurs. 212 * </td> 213 * </tr> 214 * 215 * <tr> 216 * <td rowspan="2">Focus</td> 217 * <td><code>{@link #onFocusChanged}</code></td> 218 * <td>Called when the view gains or loses focus. 219 * </td> 220 * </tr> 221 * 222 * <tr> 223 * <td><code>{@link #onWindowFocusChanged}</code></td> 224 * <td>Called when the window containing the view gains or loses focus. 225 * </td> 226 * </tr> 227 * 228 * <tr> 229 * <td rowspan="3">Attaching</td> 230 * <td><code>{@link #onAttachedToWindow()}</code></td> 231 * <td>Called when the view is attached to a window. 232 * </td> 233 * </tr> 234 * 235 * <tr> 236 * <td><code>{@link #onDetachedFromWindow}</code></td> 237 * <td>Called when the view is detached from its window. 238 * </td> 239 * </tr> 240 * 241 * <tr> 242 * <td><code>{@link #onWindowVisibilityChanged}</code></td> 243 * <td>Called when the visibility of the window containing the view 244 * has changed. 245 * </td> 246 * </tr> 247 * </tbody> 248 * 249 * </table> 250 * </p> 251 * 252 * <a name="IDs"></a> 253 * <h3>IDs</h3> 254 * Views may have an integer id associated with them. These ids are typically 255 * assigned in the layout XML files, and are used to find specific views within 256 * the view tree. A common pattern is to: 257 * <ul> 258 * <li>Define a Button in the layout file and assign it a unique ID. 259 * <pre> 260 * <Button id="@+id/my_button" 261 * android:layout_width="wrap_content" 262 * android:layout_height="wrap_content" 263 * android:text="@string/my_button_text"/> 264 * </pre></li> 265 * <li>From the onCreate method of an Activity, find the Button 266 * <pre class="prettyprint"> 267 * Button myButton = (Button) findViewById(R.id.my_button); 268 * </pre></li> 269 * </ul> 270 * <p> 271 * View IDs need not be unique throughout the tree, but it is good practice to 272 * ensure that they are at least unique within the part of the tree you are 273 * searching. 274 * </p> 275 * 276 * <a name="Position"></a> 277 * <h3>Position</h3> 278 * <p> 279 * The geometry of a view is that of a rectangle. A view has a location, 280 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 281 * two dimensions, expressed as a width and a height. The unit for location 282 * and dimensions is the pixel. 283 * </p> 284 * 285 * <p> 286 * It is possible to retrieve the location of a view by invoking the methods 287 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 288 * coordinate of the rectangle representing the view. The latter returns the 289 * top, or Y, coordinate of the rectangle representing the view. These methods 290 * both return the location of the view relative to its parent. For instance, 291 * when getLeft() returns 20, that means the view is located 20 pixels to the 292 * right of the left edge of its direct parent. 293 * </p> 294 * 295 * <p> 296 * In addition, several convenience methods are offered to avoid unnecessary 297 * computations, namely {@link #getRight()} and {@link #getBottom()}. 298 * These methods return the coordinates of the right and bottom edges of the 299 * rectangle representing the view. For instance, calling {@link #getRight()} 300 * is similar to the following computation: <code>getLeft() + getWidth()</code> 301 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 302 * </p> 303 * 304 * <a name="SizePaddingMargins"></a> 305 * <h3>Size, padding and margins</h3> 306 * <p> 307 * The size of a view is expressed with a width and a height. A view actually 308 * possess two pairs of width and height values. 309 * </p> 310 * 311 * <p> 312 * The first pair is known as <em>measured width</em> and 313 * <em>measured height</em>. These dimensions define how big a view wants to be 314 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 315 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 316 * and {@link #getMeasuredHeight()}. 317 * </p> 318 * 319 * <p> 320 * The second pair is simply known as <em>width</em> and <em>height</em>, or 321 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 322 * dimensions define the actual size of the view on screen, at drawing time and 323 * after layout. These values may, but do not have to, be different from the 324 * measured width and height. The width and height can be obtained by calling 325 * {@link #getWidth()} and {@link #getHeight()}. 326 * </p> 327 * 328 * <p> 329 * To measure its dimensions, a view takes into account its padding. The padding 330 * is expressed in pixels for the left, top, right and bottom parts of the view. 331 * Padding can be used to offset the content of the view by a specific amount of 332 * pixels. For instance, a left padding of 2 will push the view's content by 333 * 2 pixels to the right of the left edge. Padding can be set using the 334 * {@link #setPadding(int, int, int, int)} method and queried by calling 335 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 336 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}. 337 * </p> 338 * 339 * <p> 340 * Even though a view can define a padding, it does not provide any support for 341 * margins. However, view groups provide such a support. Refer to 342 * {@link android.view.ViewGroup} and 343 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 344 * </p> 345 * 346 * <a name="Layout"></a> 347 * <h3>Layout</h3> 348 * <p> 349 * Layout is a two pass process: a measure pass and a layout pass. The measuring 350 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 351 * of the view tree. Each view pushes dimension specifications down the tree 352 * during the recursion. At the end of the measure pass, every view has stored 353 * its measurements. The second pass happens in 354 * {@link #layout(int,int,int,int)} and is also top-down. During 355 * this pass each parent is responsible for positioning all of its children 356 * using the sizes computed in the measure pass. 357 * </p> 358 * 359 * <p> 360 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 361 * {@link #getMeasuredHeight()} values must be set, along with those for all of 362 * that view's descendants. A view's measured width and measured height values 363 * must respect the constraints imposed by the view's parents. This guarantees 364 * that at the end of the measure pass, all parents accept all of their 365 * children's measurements. A parent view may call measure() more than once on 366 * its children. For example, the parent may measure each child once with 367 * unspecified dimensions to find out how big they want to be, then call 368 * measure() on them again with actual numbers if the sum of all the children's 369 * unconstrained sizes is too big or too small. 370 * </p> 371 * 372 * <p> 373 * The measure pass uses two classes to communicate dimensions. The 374 * {@link MeasureSpec} class is used by views to tell their parents how they 375 * want to be measured and positioned. The base LayoutParams class just 376 * describes how big the view wants to be for both width and height. For each 377 * dimension, it can specify one of: 378 * <ul> 379 * <li> an exact number 380 * <li>FILL_PARENT, which means the view wants to be as big as its parent 381 * (minus padding) 382 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 383 * enclose its content (plus padding). 384 * </ul> 385 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 386 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 387 * an X and Y value. 388 * </p> 389 * 390 * <p> 391 * MeasureSpecs are used to push requirements down the tree from parent to 392 * child. A MeasureSpec can be in one of three modes: 393 * <ul> 394 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 395 * of a child view. For example, a LinearLayout may call measure() on its child 396 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 397 * tall the child view wants to be given a width of 240 pixels. 398 * <li>EXACTLY: This is used by the parent to impose an exact size on the 399 * child. The child must use this size, and guarantee that all of its 400 * descendants will fit within this size. 401 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 402 * child. The child must gurantee that it and all of its descendants will fit 403 * within this size. 404 * </ul> 405 * </p> 406 * 407 * <p> 408 * To intiate a layout, call {@link #requestLayout}. This method is typically 409 * called by a view on itself when it believes that is can no longer fit within 410 * its current bounds. 411 * </p> 412 * 413 * <a name="Drawing"></a> 414 * <h3>Drawing</h3> 415 * <p> 416 * Drawing is handled by walking the tree and rendering each view that 417 * intersects the the invalid region. Because the tree is traversed in-order, 418 * this means that parents will draw before (i.e., behind) their children, with 419 * siblings drawn in the order they appear in the tree. 420 * If you set a background drawable for a View, then the View will draw it for you 421 * before calling back to its <code>onDraw()</code> method. 422 * </p> 423 * 424 * <p> 425 * Note that the framework will not draw views that are not in the invalid region. 426 * </p> 427 * 428 * <p> 429 * To force a view to draw, call {@link #invalidate()}. 430 * </p> 431 * 432 * <a name="EventHandlingThreading"></a> 433 * <h3>Event Handling and Threading</h3> 434 * <p> 435 * The basic cycle of a view is as follows: 436 * <ol> 437 * <li>An event comes in and is dispatched to the appropriate view. The view 438 * handles the event and notifies any listeners.</li> 439 * <li>If in the course of processing the event, the view's bounds may need 440 * to be changed, the view will call {@link #requestLayout()}.</li> 441 * <li>Similarly, if in the course of processing the event the view's appearance 442 * may need to be changed, the view will call {@link #invalidate()}.</li> 443 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 444 * the framework will take care of measuring, laying out, and drawing the tree 445 * as appropriate.</li> 446 * </ol> 447 * </p> 448 * 449 * <p><em>Note: The entire view tree is single threaded. You must always be on 450 * the UI thread when calling any method on any view.</em> 451 * If you are doing work on other threads and want to update the state of a view 452 * from that thread, you should use a {@link Handler}. 453 * </p> 454 * 455 * <a name="FocusHandling"></a> 456 * <h3>Focus Handling</h3> 457 * <p> 458 * The framework will handle routine focus movement in response to user input. 459 * This includes changing the focus as views are removed or hidden, or as new 460 * views become available. Views indicate their willingness to take focus 461 * through the {@link #isFocusable} method. To change whether a view can take 462 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 463 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 464 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 465 * </p> 466 * <p> 467 * Focus movement is based on an algorithm which finds the nearest neighbor in a 468 * given direction. In rare cases, the default algorithm may not match the 469 * intended behavior of the developer. In these situations, you can provide 470 * explicit overrides by using these XML attributes in the layout file: 471 * <pre> 472 * nextFocusDown 473 * nextFocusLeft 474 * nextFocusRight 475 * nextFocusUp 476 * </pre> 477 * </p> 478 * 479 * 480 * <p> 481 * To get a particular view to take focus, call {@link #requestFocus()}. 482 * </p> 483 * 484 * <a name="TouchMode"></a> 485 * <h3>Touch Mode</h3> 486 * <p> 487 * When a user is navigating a user interface via directional keys such as a D-pad, it is 488 * necessary to give focus to actionable items such as buttons so the user can see 489 * what will take input. If the device has touch capabilities, however, and the user 490 * begins interacting with the interface by touching it, it is no longer necessary to 491 * always highlight, or give focus to, a particular view. This motivates a mode 492 * for interaction named 'touch mode'. 493 * </p> 494 * <p> 495 * For a touch capable device, once the user touches the screen, the device 496 * will enter touch mode. From this point onward, only views for which 497 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 498 * Other views that are touchable, like buttons, will not take focus when touched; they will 499 * only fire the on click listeners. 500 * </p> 501 * <p> 502 * Any time a user hits a directional key, such as a D-pad direction, the view device will 503 * exit touch mode, and find a view to take focus, so that the user may resume interacting 504 * with the user interface without touching the screen again. 505 * </p> 506 * <p> 507 * The touch mode state is maintained across {@link android.app.Activity}s. Call 508 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 509 * </p> 510 * 511 * <a name="Scrolling"></a> 512 * <h3>Scrolling</h3> 513 * <p> 514 * The framework provides basic support for views that wish to internally 515 * scroll their content. This includes keeping track of the X and Y scroll 516 * offset as well as mechanisms for drawing scrollbars. See 517 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)} for more details. 518 * </p> 519 * 520 * <a name="Tags"></a> 521 * <h3>Tags</h3> 522 * <p> 523 * Unlike IDs, tags are not used to identify views. Tags are essentially an 524 * extra piece of information that can be associated with a view. They are most 525 * often used as a convenience to store data related to views in the views 526 * themselves rather than by putting them in a separate structure. 527 * </p> 528 * 529 * <a name="Animation"></a> 530 * <h3>Animation</h3> 531 * <p> 532 * You can attach an {@link Animation} object to a view using 533 * {@link #setAnimation(Animation)} or 534 * {@link #startAnimation(Animation)}. The animation can alter the scale, 535 * rotation, translation and alpha of a view over time. If the animation is 536 * attached to a view that has children, the animation will affect the entire 537 * subtree rooted by that node. When an animation is started, the framework will 538 * take care of redrawing the appropriate views until the animation completes. 539 * </p> 540 * 541 * @attr ref android.R.styleable#View_background 542 * @attr ref android.R.styleable#View_clickable 543 * @attr ref android.R.styleable#View_contentDescription 544 * @attr ref android.R.styleable#View_drawingCacheQuality 545 * @attr ref android.R.styleable#View_duplicateParentState 546 * @attr ref android.R.styleable#View_id 547 * @attr ref android.R.styleable#View_fadingEdge 548 * @attr ref android.R.styleable#View_fadingEdgeLength 549 * @attr ref android.R.styleable#View_fitsSystemWindows 550 * @attr ref android.R.styleable#View_isScrollContainer 551 * @attr ref android.R.styleable#View_focusable 552 * @attr ref android.R.styleable#View_focusableInTouchMode 553 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 554 * @attr ref android.R.styleable#View_keepScreenOn 555 * @attr ref android.R.styleable#View_longClickable 556 * @attr ref android.R.styleable#View_minHeight 557 * @attr ref android.R.styleable#View_minWidth 558 * @attr ref android.R.styleable#View_nextFocusDown 559 * @attr ref android.R.styleable#View_nextFocusLeft 560 * @attr ref android.R.styleable#View_nextFocusRight 561 * @attr ref android.R.styleable#View_nextFocusUp 562 * @attr ref android.R.styleable#View_onClick 563 * @attr ref android.R.styleable#View_padding 564 * @attr ref android.R.styleable#View_paddingBottom 565 * @attr ref android.R.styleable#View_paddingLeft 566 * @attr ref android.R.styleable#View_paddingRight 567 * @attr ref android.R.styleable#View_paddingTop 568 * @attr ref android.R.styleable#View_saveEnabled 569 * @attr ref android.R.styleable#View_scrollX 570 * @attr ref android.R.styleable#View_scrollY 571 * @attr ref android.R.styleable#View_scrollbarSize 572 * @attr ref android.R.styleable#View_scrollbarStyle 573 * @attr ref android.R.styleable#View_scrollbars 574 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 575 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 576 * @attr ref android.R.styleable#View_scrollbarThumbVertical 577 * @attr ref android.R.styleable#View_scrollbarTrackVertical 578 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 579 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 580 * @attr ref android.R.styleable#View_soundEffectsEnabled 581 * @attr ref android.R.styleable#View_tag 582 * @attr ref android.R.styleable#View_visibility 583 * 584 * @see android.view.ViewGroup 585 */ 586public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource { 587 private static final boolean DBG = false; 588 589 /** 590 * The logging tag used by this class with android.util.Log. 591 */ 592 protected static final String VIEW_LOG_TAG = "View"; 593 594 /** 595 * Used to mark a View that has no ID. 596 */ 597 public static final int NO_ID = -1; 598 599 /** 600 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 601 * calling setFlags. 602 */ 603 private static final int NOT_FOCUSABLE = 0x00000000; 604 605 /** 606 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 607 * setFlags. 608 */ 609 private static final int FOCUSABLE = 0x00000001; 610 611 /** 612 * Mask for use with setFlags indicating bits used for focus. 613 */ 614 private static final int FOCUSABLE_MASK = 0x00000001; 615 616 /** 617 * This view will adjust its padding to fit sytem windows (e.g. status bar) 618 */ 619 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 620 621 /** 622 * This view is visible. Use with {@link #setVisibility}. 623 */ 624 public static final int VISIBLE = 0x00000000; 625 626 /** 627 * This view is invisible, but it still takes up space for layout purposes. 628 * Use with {@link #setVisibility}. 629 */ 630 public static final int INVISIBLE = 0x00000004; 631 632 /** 633 * This view is invisible, and it doesn't take any space for layout 634 * purposes. Use with {@link #setVisibility}. 635 */ 636 public static final int GONE = 0x00000008; 637 638 /** 639 * Mask for use with setFlags indicating bits used for visibility. 640 * {@hide} 641 */ 642 static final int VISIBILITY_MASK = 0x0000000C; 643 644 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 645 646 /** 647 * This view is enabled. Intrepretation varies by subclass. 648 * Use with ENABLED_MASK when calling setFlags. 649 * {@hide} 650 */ 651 static final int ENABLED = 0x00000000; 652 653 /** 654 * This view is disabled. Intrepretation varies by subclass. 655 * Use with ENABLED_MASK when calling setFlags. 656 * {@hide} 657 */ 658 static final int DISABLED = 0x00000020; 659 660 /** 661 * Mask for use with setFlags indicating bits used for indicating whether 662 * this view is enabled 663 * {@hide} 664 */ 665 static final int ENABLED_MASK = 0x00000020; 666 667 /** 668 * This view won't draw. {@link #onDraw} won't be called and further 669 * optimizations 670 * will be performed. It is okay to have this flag set and a background. 671 * Use with DRAW_MASK when calling setFlags. 672 * {@hide} 673 */ 674 static final int WILL_NOT_DRAW = 0x00000080; 675 676 /** 677 * Mask for use with setFlags indicating bits used for indicating whether 678 * this view is will draw 679 * {@hide} 680 */ 681 static final int DRAW_MASK = 0x00000080; 682 683 /** 684 * <p>This view doesn't show scrollbars.</p> 685 * {@hide} 686 */ 687 static final int SCROLLBARS_NONE = 0x00000000; 688 689 /** 690 * <p>This view shows horizontal scrollbars.</p> 691 * {@hide} 692 */ 693 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 694 695 /** 696 * <p>This view shows vertical scrollbars.</p> 697 * {@hide} 698 */ 699 static final int SCROLLBARS_VERTICAL = 0x00000200; 700 701 /** 702 * <p>Mask for use with setFlags indicating bits used for indicating which 703 * scrollbars are enabled.</p> 704 * {@hide} 705 */ 706 static final int SCROLLBARS_MASK = 0x00000300; 707 708 // note 0x00000400 and 0x00000800 are now available for next flags... 709 710 /** 711 * <p>This view doesn't show fading edges.</p> 712 * {@hide} 713 */ 714 static final int FADING_EDGE_NONE = 0x00000000; 715 716 /** 717 * <p>This view shows horizontal fading edges.</p> 718 * {@hide} 719 */ 720 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 721 722 /** 723 * <p>This view shows vertical fading edges.</p> 724 * {@hide} 725 */ 726 static final int FADING_EDGE_VERTICAL = 0x00002000; 727 728 /** 729 * <p>Mask for use with setFlags indicating bits used for indicating which 730 * fading edges are enabled.</p> 731 * {@hide} 732 */ 733 static final int FADING_EDGE_MASK = 0x00003000; 734 735 /** 736 * <p>Indicates this view can be clicked. When clickable, a View reacts 737 * to clicks by notifying the OnClickListener.<p> 738 * {@hide} 739 */ 740 static final int CLICKABLE = 0x00004000; 741 742 /** 743 * <p>Indicates this view is caching its drawing into a bitmap.</p> 744 * {@hide} 745 */ 746 static final int DRAWING_CACHE_ENABLED = 0x00008000; 747 748 /** 749 * <p>Indicates that no icicle should be saved for this view.<p> 750 * {@hide} 751 */ 752 static final int SAVE_DISABLED = 0x000010000; 753 754 /** 755 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 756 * property.</p> 757 * {@hide} 758 */ 759 static final int SAVE_DISABLED_MASK = 0x000010000; 760 761 /** 762 * <p>Indicates that no drawing cache should ever be created for this view.<p> 763 * {@hide} 764 */ 765 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 766 767 /** 768 * <p>Indicates this view can take / keep focus when int touch mode.</p> 769 * {@hide} 770 */ 771 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 772 773 /** 774 * <p>Enables low quality mode for the drawing cache.</p> 775 */ 776 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 777 778 /** 779 * <p>Enables high quality mode for the drawing cache.</p> 780 */ 781 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 782 783 /** 784 * <p>Enables automatic quality mode for the drawing cache.</p> 785 */ 786 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 787 788 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 789 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 790 }; 791 792 /** 793 * <p>Mask for use with setFlags indicating bits used for the cache 794 * quality property.</p> 795 * {@hide} 796 */ 797 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 798 799 /** 800 * <p> 801 * Indicates this view can be long clicked. When long clickable, a View 802 * reacts to long clicks by notifying the OnLongClickListener or showing a 803 * context menu. 804 * </p> 805 * {@hide} 806 */ 807 static final int LONG_CLICKABLE = 0x00200000; 808 809 /** 810 * <p>Indicates that this view gets its drawable states from its direct parent 811 * and ignores its original internal states.</p> 812 * 813 * @hide 814 */ 815 static final int DUPLICATE_PARENT_STATE = 0x00400000; 816 817 /** 818 * The scrollbar style to display the scrollbars inside the content area, 819 * without increasing the padding. The scrollbars will be overlaid with 820 * translucency on the view's content. 821 */ 822 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 823 824 /** 825 * The scrollbar style to display the scrollbars inside the padded area, 826 * increasing the padding of the view. The scrollbars will not overlap the 827 * content area of the view. 828 */ 829 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 830 831 /** 832 * The scrollbar style to display the scrollbars at the edge of the view, 833 * without increasing the padding. The scrollbars will be overlaid with 834 * translucency. 835 */ 836 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 837 838 /** 839 * The scrollbar style to display the scrollbars at the edge of the view, 840 * increasing the padding of the view. The scrollbars will only overlap the 841 * background, if any. 842 */ 843 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 844 845 /** 846 * Mask to check if the scrollbar style is overlay or inset. 847 * {@hide} 848 */ 849 static final int SCROLLBARS_INSET_MASK = 0x01000000; 850 851 /** 852 * Mask to check if the scrollbar style is inside or outside. 853 * {@hide} 854 */ 855 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 856 857 /** 858 * Mask for scrollbar style. 859 * {@hide} 860 */ 861 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 862 863 /** 864 * View flag indicating that the screen should remain on while the 865 * window containing this view is visible to the user. This effectively 866 * takes care of automatically setting the WindowManager's 867 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 868 */ 869 public static final int KEEP_SCREEN_ON = 0x04000000; 870 871 /** 872 * View flag indicating whether this view should have sound effects enabled 873 * for events such as clicking and touching. 874 */ 875 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 876 877 /** 878 * View flag indicating whether this view should have haptic feedback 879 * enabled for events such as long presses. 880 */ 881 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 882 883 /** 884 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 885 * should add all focusable Views regardless if they are focusable in touch mode. 886 */ 887 public static final int FOCUSABLES_ALL = 0x00000000; 888 889 /** 890 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 891 * should add only Views focusable in touch mode. 892 */ 893 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 894 895 /** 896 * Use with {@link #focusSearch}. Move focus to the previous selectable 897 * item. 898 */ 899 public static final int FOCUS_BACKWARD = 0x00000001; 900 901 /** 902 * Use with {@link #focusSearch}. Move focus to the next selectable 903 * item. 904 */ 905 public static final int FOCUS_FORWARD = 0x00000002; 906 907 /** 908 * Use with {@link #focusSearch}. Move focus to the left. 909 */ 910 public static final int FOCUS_LEFT = 0x00000011; 911 912 /** 913 * Use with {@link #focusSearch}. Move focus up. 914 */ 915 public static final int FOCUS_UP = 0x00000021; 916 917 /** 918 * Use with {@link #focusSearch}. Move focus to the right. 919 */ 920 public static final int FOCUS_RIGHT = 0x00000042; 921 922 /** 923 * Use with {@link #focusSearch}. Move focus down. 924 */ 925 public static final int FOCUS_DOWN = 0x00000082; 926 927 /** 928 * Base View state sets 929 */ 930 // Singles 931 /** 932 * Indicates the view has no states set. States are used with 933 * {@link android.graphics.drawable.Drawable} to change the drawing of the 934 * view depending on its state. 935 * 936 * @see android.graphics.drawable.Drawable 937 * @see #getDrawableState() 938 */ 939 protected static final int[] EMPTY_STATE_SET = {}; 940 /** 941 * Indicates the view is enabled. States are used with 942 * {@link android.graphics.drawable.Drawable} to change the drawing of the 943 * view depending on its state. 944 * 945 * @see android.graphics.drawable.Drawable 946 * @see #getDrawableState() 947 */ 948 protected static final int[] ENABLED_STATE_SET = {R.attr.state_enabled}; 949 /** 950 * Indicates the view is focused. States are used with 951 * {@link android.graphics.drawable.Drawable} to change the drawing of the 952 * view depending on its state. 953 * 954 * @see android.graphics.drawable.Drawable 955 * @see #getDrawableState() 956 */ 957 protected static final int[] FOCUSED_STATE_SET = {R.attr.state_focused}; 958 /** 959 * Indicates the view is selected. States are used with 960 * {@link android.graphics.drawable.Drawable} to change the drawing of the 961 * view depending on its state. 962 * 963 * @see android.graphics.drawable.Drawable 964 * @see #getDrawableState() 965 */ 966 protected static final int[] SELECTED_STATE_SET = {R.attr.state_selected}; 967 /** 968 * Indicates the view is pressed. States are used with 969 * {@link android.graphics.drawable.Drawable} to change the drawing of the 970 * view depending on its state. 971 * 972 * @see android.graphics.drawable.Drawable 973 * @see #getDrawableState() 974 * @hide 975 */ 976 protected static final int[] PRESSED_STATE_SET = {R.attr.state_pressed}; 977 /** 978 * Indicates the view's window has focus. States are used with 979 * {@link android.graphics.drawable.Drawable} to change the drawing of the 980 * view depending on its state. 981 * 982 * @see android.graphics.drawable.Drawable 983 * @see #getDrawableState() 984 */ 985 protected static final int[] WINDOW_FOCUSED_STATE_SET = 986 {R.attr.state_window_focused}; 987 // Doubles 988 /** 989 * Indicates the view is enabled and has the focus. 990 * 991 * @see #ENABLED_STATE_SET 992 * @see #FOCUSED_STATE_SET 993 */ 994 protected static final int[] ENABLED_FOCUSED_STATE_SET = 995 stateSetUnion(ENABLED_STATE_SET, FOCUSED_STATE_SET); 996 /** 997 * Indicates the view is enabled and selected. 998 * 999 * @see #ENABLED_STATE_SET 1000 * @see #SELECTED_STATE_SET 1001 */ 1002 protected static final int[] ENABLED_SELECTED_STATE_SET = 1003 stateSetUnion(ENABLED_STATE_SET, SELECTED_STATE_SET); 1004 /** 1005 * Indicates the view is enabled and that its window has focus. 1006 * 1007 * @see #ENABLED_STATE_SET 1008 * @see #WINDOW_FOCUSED_STATE_SET 1009 */ 1010 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET = 1011 stateSetUnion(ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1012 /** 1013 * Indicates the view is focused and selected. 1014 * 1015 * @see #FOCUSED_STATE_SET 1016 * @see #SELECTED_STATE_SET 1017 */ 1018 protected static final int[] FOCUSED_SELECTED_STATE_SET = 1019 stateSetUnion(FOCUSED_STATE_SET, SELECTED_STATE_SET); 1020 /** 1021 * Indicates the view has the focus and that its window has the focus. 1022 * 1023 * @see #FOCUSED_STATE_SET 1024 * @see #WINDOW_FOCUSED_STATE_SET 1025 */ 1026 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET = 1027 stateSetUnion(FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1028 /** 1029 * Indicates the view is selected and that its window has the focus. 1030 * 1031 * @see #SELECTED_STATE_SET 1032 * @see #WINDOW_FOCUSED_STATE_SET 1033 */ 1034 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET = 1035 stateSetUnion(SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1036 // Triples 1037 /** 1038 * Indicates the view is enabled, focused and selected. 1039 * 1040 * @see #ENABLED_STATE_SET 1041 * @see #FOCUSED_STATE_SET 1042 * @see #SELECTED_STATE_SET 1043 */ 1044 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET = 1045 stateSetUnion(ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET); 1046 /** 1047 * Indicates the view is enabled, focused and its window has the focus. 1048 * 1049 * @see #ENABLED_STATE_SET 1050 * @see #FOCUSED_STATE_SET 1051 * @see #WINDOW_FOCUSED_STATE_SET 1052 */ 1053 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = 1054 stateSetUnion(ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1055 /** 1056 * Indicates the view is enabled, selected and its window has the focus. 1057 * 1058 * @see #ENABLED_STATE_SET 1059 * @see #SELECTED_STATE_SET 1060 * @see #WINDOW_FOCUSED_STATE_SET 1061 */ 1062 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = 1063 stateSetUnion(ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1064 /** 1065 * Indicates the view is focused, selected and its window has the focus. 1066 * 1067 * @see #FOCUSED_STATE_SET 1068 * @see #SELECTED_STATE_SET 1069 * @see #WINDOW_FOCUSED_STATE_SET 1070 */ 1071 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = 1072 stateSetUnion(FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1073 /** 1074 * Indicates the view is enabled, focused, selected and its window 1075 * has the focus. 1076 * 1077 * @see #ENABLED_STATE_SET 1078 * @see #FOCUSED_STATE_SET 1079 * @see #SELECTED_STATE_SET 1080 * @see #WINDOW_FOCUSED_STATE_SET 1081 */ 1082 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = 1083 stateSetUnion(ENABLED_FOCUSED_SELECTED_STATE_SET, 1084 WINDOW_FOCUSED_STATE_SET); 1085 1086 /** 1087 * Indicates the view is pressed and its window has the focus. 1088 * 1089 * @see #PRESSED_STATE_SET 1090 * @see #WINDOW_FOCUSED_STATE_SET 1091 */ 1092 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET = 1093 stateSetUnion(PRESSED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1094 1095 /** 1096 * Indicates the view is pressed and selected. 1097 * 1098 * @see #PRESSED_STATE_SET 1099 * @see #SELECTED_STATE_SET 1100 */ 1101 protected static final int[] PRESSED_SELECTED_STATE_SET = 1102 stateSetUnion(PRESSED_STATE_SET, SELECTED_STATE_SET); 1103 1104 /** 1105 * Indicates the view is pressed, selected and its window has the focus. 1106 * 1107 * @see #PRESSED_STATE_SET 1108 * @see #SELECTED_STATE_SET 1109 * @see #WINDOW_FOCUSED_STATE_SET 1110 */ 1111 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = 1112 stateSetUnion(PRESSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1113 1114 /** 1115 * Indicates the view is pressed and focused. 1116 * 1117 * @see #PRESSED_STATE_SET 1118 * @see #FOCUSED_STATE_SET 1119 */ 1120 protected static final int[] PRESSED_FOCUSED_STATE_SET = 1121 stateSetUnion(PRESSED_STATE_SET, FOCUSED_STATE_SET); 1122 1123 /** 1124 * Indicates the view is pressed, focused and its window has the focus. 1125 * 1126 * @see #PRESSED_STATE_SET 1127 * @see #FOCUSED_STATE_SET 1128 * @see #WINDOW_FOCUSED_STATE_SET 1129 */ 1130 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = 1131 stateSetUnion(PRESSED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1132 1133 /** 1134 * Indicates the view is pressed, focused and selected. 1135 * 1136 * @see #PRESSED_STATE_SET 1137 * @see #SELECTED_STATE_SET 1138 * @see #FOCUSED_STATE_SET 1139 */ 1140 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET = 1141 stateSetUnion(PRESSED_FOCUSED_STATE_SET, SELECTED_STATE_SET); 1142 1143 /** 1144 * Indicates the view is pressed, focused, selected and its window has the focus. 1145 * 1146 * @see #PRESSED_STATE_SET 1147 * @see #FOCUSED_STATE_SET 1148 * @see #SELECTED_STATE_SET 1149 * @see #WINDOW_FOCUSED_STATE_SET 1150 */ 1151 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = 1152 stateSetUnion(PRESSED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1153 1154 /** 1155 * Indicates the view is pressed and enabled. 1156 * 1157 * @see #PRESSED_STATE_SET 1158 * @see #ENABLED_STATE_SET 1159 */ 1160 protected static final int[] PRESSED_ENABLED_STATE_SET = 1161 stateSetUnion(PRESSED_STATE_SET, ENABLED_STATE_SET); 1162 1163 /** 1164 * Indicates the view is pressed, enabled and its window has the focus. 1165 * 1166 * @see #PRESSED_STATE_SET 1167 * @see #ENABLED_STATE_SET 1168 * @see #WINDOW_FOCUSED_STATE_SET 1169 */ 1170 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = 1171 stateSetUnion(PRESSED_ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1172 1173 /** 1174 * Indicates the view is pressed, enabled and selected. 1175 * 1176 * @see #PRESSED_STATE_SET 1177 * @see #ENABLED_STATE_SET 1178 * @see #SELECTED_STATE_SET 1179 */ 1180 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET = 1181 stateSetUnion(PRESSED_ENABLED_STATE_SET, SELECTED_STATE_SET); 1182 1183 /** 1184 * Indicates the view is pressed, enabled, selected and its window has the 1185 * focus. 1186 * 1187 * @see #PRESSED_STATE_SET 1188 * @see #ENABLED_STATE_SET 1189 * @see #SELECTED_STATE_SET 1190 * @see #WINDOW_FOCUSED_STATE_SET 1191 */ 1192 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = 1193 stateSetUnion(PRESSED_ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1194 1195 /** 1196 * Indicates the view is pressed, enabled and focused. 1197 * 1198 * @see #PRESSED_STATE_SET 1199 * @see #ENABLED_STATE_SET 1200 * @see #FOCUSED_STATE_SET 1201 */ 1202 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET = 1203 stateSetUnion(PRESSED_ENABLED_STATE_SET, FOCUSED_STATE_SET); 1204 1205 /** 1206 * Indicates the view is pressed, enabled, focused and its window has the 1207 * focus. 1208 * 1209 * @see #PRESSED_STATE_SET 1210 * @see #ENABLED_STATE_SET 1211 * @see #FOCUSED_STATE_SET 1212 * @see #WINDOW_FOCUSED_STATE_SET 1213 */ 1214 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = 1215 stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1216 1217 /** 1218 * Indicates the view is pressed, enabled, focused and selected. 1219 * 1220 * @see #PRESSED_STATE_SET 1221 * @see #ENABLED_STATE_SET 1222 * @see #SELECTED_STATE_SET 1223 * @see #FOCUSED_STATE_SET 1224 */ 1225 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = 1226 stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET); 1227 1228 /** 1229 * Indicates the view is pressed, enabled, focused, selected and its window 1230 * has the focus. 1231 * 1232 * @see #PRESSED_STATE_SET 1233 * @see #ENABLED_STATE_SET 1234 * @see #SELECTED_STATE_SET 1235 * @see #FOCUSED_STATE_SET 1236 * @see #WINDOW_FOCUSED_STATE_SET 1237 */ 1238 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = 1239 stateSetUnion(PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET); 1240 1241 /** 1242 * The order here is very important to {@link #getDrawableState()} 1243 */ 1244 private static final int[][] VIEW_STATE_SETS = { 1245 EMPTY_STATE_SET, // 0 0 0 0 0 1246 WINDOW_FOCUSED_STATE_SET, // 0 0 0 0 1 1247 SELECTED_STATE_SET, // 0 0 0 1 0 1248 SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 0 1 1 1249 FOCUSED_STATE_SET, // 0 0 1 0 0 1250 FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 0 1 1251 FOCUSED_SELECTED_STATE_SET, // 0 0 1 1 0 1252 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 1 1 1253 ENABLED_STATE_SET, // 0 1 0 0 0 1254 ENABLED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 0 1 1255 ENABLED_SELECTED_STATE_SET, // 0 1 0 1 0 1256 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 1 1 1257 ENABLED_FOCUSED_STATE_SET, // 0 1 1 0 0 1258 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 0 1 1259 ENABLED_FOCUSED_SELECTED_STATE_SET, // 0 1 1 1 0 1260 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 1 1 1261 PRESSED_STATE_SET, // 1 0 0 0 0 1262 PRESSED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 0 1 1263 PRESSED_SELECTED_STATE_SET, // 1 0 0 1 0 1264 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 1 1 1265 PRESSED_FOCUSED_STATE_SET, // 1 0 1 0 0 1266 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 0 1 1267 PRESSED_FOCUSED_SELECTED_STATE_SET, // 1 0 1 1 0 1268 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 1 1 1269 PRESSED_ENABLED_STATE_SET, // 1 1 0 0 0 1270 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 0 1 1271 PRESSED_ENABLED_SELECTED_STATE_SET, // 1 1 0 1 0 1272 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 1 1 1273 PRESSED_ENABLED_FOCUSED_STATE_SET, // 1 1 1 0 0 1274 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 0 1 1275 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, // 1 1 1 1 0 1276 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 1 1 1277 }; 1278 1279 /** 1280 * Used by views that contain lists of items. This state indicates that 1281 * the view is showing the last item. 1282 * @hide 1283 */ 1284 protected static final int[] LAST_STATE_SET = {R.attr.state_last}; 1285 /** 1286 * Used by views that contain lists of items. This state indicates that 1287 * the view is showing the first item. 1288 * @hide 1289 */ 1290 protected static final int[] FIRST_STATE_SET = {R.attr.state_first}; 1291 /** 1292 * Used by views that contain lists of items. This state indicates that 1293 * the view is showing the middle item. 1294 * @hide 1295 */ 1296 protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle}; 1297 /** 1298 * Used by views that contain lists of items. This state indicates that 1299 * the view is showing only one item. 1300 * @hide 1301 */ 1302 protected static final int[] SINGLE_STATE_SET = {R.attr.state_single}; 1303 /** 1304 * Used by views that contain lists of items. This state indicates that 1305 * the view is pressed and showing the last item. 1306 * @hide 1307 */ 1308 protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed}; 1309 /** 1310 * Used by views that contain lists of items. This state indicates that 1311 * the view is pressed and showing the first item. 1312 * @hide 1313 */ 1314 protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed}; 1315 /** 1316 * Used by views that contain lists of items. This state indicates that 1317 * the view is pressed and showing the middle item. 1318 * @hide 1319 */ 1320 protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed}; 1321 /** 1322 * Used by views that contain lists of items. This state indicates that 1323 * the view is pressed and showing only one item. 1324 * @hide 1325 */ 1326 protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed}; 1327 1328 /** 1329 * Temporary Rect currently for use in setBackground(). This will probably 1330 * be extended in the future to hold our own class with more than just 1331 * a Rect. :) 1332 */ 1333 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1334 1335 /** 1336 * Map used to store views' tags. 1337 */ 1338 private static WeakHashMap<View, SparseArray<Object>> sTags; 1339 1340 /** 1341 * Lock used to access sTags. 1342 */ 1343 private static final Object sTagsLock = new Object(); 1344 1345 /** 1346 * The animation currently associated with this view. 1347 * @hide 1348 */ 1349 protected Animation mCurrentAnimation = null; 1350 1351 /** 1352 * Width as measured during measure pass. 1353 * {@hide} 1354 */ 1355 @ViewDebug.ExportedProperty 1356 protected int mMeasuredWidth; 1357 1358 /** 1359 * Height as measured during measure pass. 1360 * {@hide} 1361 */ 1362 @ViewDebug.ExportedProperty 1363 protected int mMeasuredHeight; 1364 1365 /** 1366 * The view's identifier. 1367 * {@hide} 1368 * 1369 * @see #setId(int) 1370 * @see #getId() 1371 */ 1372 @ViewDebug.ExportedProperty(resolveId = true) 1373 int mID = NO_ID; 1374 1375 /** 1376 * The view's tag. 1377 * {@hide} 1378 * 1379 * @see #setTag(Object) 1380 * @see #getTag() 1381 */ 1382 protected Object mTag; 1383 1384 // for mPrivateFlags: 1385 /** {@hide} */ 1386 static final int WANTS_FOCUS = 0x00000001; 1387 /** {@hide} */ 1388 static final int FOCUSED = 0x00000002; 1389 /** {@hide} */ 1390 static final int SELECTED = 0x00000004; 1391 /** {@hide} */ 1392 static final int IS_ROOT_NAMESPACE = 0x00000008; 1393 /** {@hide} */ 1394 static final int HAS_BOUNDS = 0x00000010; 1395 /** {@hide} */ 1396 static final int DRAWN = 0x00000020; 1397 /** 1398 * When this flag is set, this view is running an animation on behalf of its 1399 * children and should therefore not cancel invalidate requests, even if they 1400 * lie outside of this view's bounds. 1401 * 1402 * {@hide} 1403 */ 1404 static final int DRAW_ANIMATION = 0x00000040; 1405 /** {@hide} */ 1406 static final int SKIP_DRAW = 0x00000080; 1407 /** {@hide} */ 1408 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1409 /** {@hide} */ 1410 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1411 /** {@hide} */ 1412 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1413 /** {@hide} */ 1414 static final int MEASURED_DIMENSION_SET = 0x00000800; 1415 /** {@hide} */ 1416 static final int FORCE_LAYOUT = 0x00001000; 1417 1418 private static final int LAYOUT_REQUIRED = 0x00002000; 1419 1420 private static final int PRESSED = 0x00004000; 1421 1422 /** {@hide} */ 1423 static final int DRAWING_CACHE_VALID = 0x00008000; 1424 /** 1425 * Flag used to indicate that this view should be drawn once more (and only once 1426 * more) after its animation has completed. 1427 * {@hide} 1428 */ 1429 static final int ANIMATION_STARTED = 0x00010000; 1430 1431 private static final int SAVE_STATE_CALLED = 0x00020000; 1432 1433 /** 1434 * Indicates that the View returned true when onSetAlpha() was called and that 1435 * the alpha must be restored. 1436 * {@hide} 1437 */ 1438 static final int ALPHA_SET = 0x00040000; 1439 1440 /** 1441 * Set by {@link #setScrollContainer(boolean)}. 1442 */ 1443 static final int SCROLL_CONTAINER = 0x00080000; 1444 1445 /** 1446 * Set by {@link #setScrollContainer(boolean)}. 1447 */ 1448 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1449 1450 /** 1451 * View flag indicating whether this view was invalidated (fully or partially.) 1452 * 1453 * @hide 1454 */ 1455 static final int DIRTY = 0x00200000; 1456 1457 /** 1458 * View flag indicating whether this view was invalidated by an opaque 1459 * invalidate request. 1460 * 1461 * @hide 1462 */ 1463 static final int DIRTY_OPAQUE = 0x00400000; 1464 1465 /** 1466 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1467 * 1468 * @hide 1469 */ 1470 static final int DIRTY_MASK = 0x00600000; 1471 1472 /** 1473 * Indicates whether the background is opaque. 1474 * 1475 * @hide 1476 */ 1477 static final int OPAQUE_BACKGROUND = 0x00800000; 1478 1479 /** 1480 * Indicates whether the scrollbars are opaque. 1481 * 1482 * @hide 1483 */ 1484 static final int OPAQUE_SCROLLBARS = 0x01000000; 1485 1486 /** 1487 * Indicates whether the view is opaque. 1488 * 1489 * @hide 1490 */ 1491 static final int OPAQUE_MASK = 0x01800000; 1492 1493 /** 1494 * The parent this view is attached to. 1495 * {@hide} 1496 * 1497 * @see #getParent() 1498 */ 1499 protected ViewParent mParent; 1500 1501 /** 1502 * {@hide} 1503 */ 1504 AttachInfo mAttachInfo; 1505 1506 /** 1507 * {@hide} 1508 */ 1509 @ViewDebug.ExportedProperty(flagMapping = { 1510 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 1511 name = "FORCE_LAYOUT"), 1512 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 1513 name = "LAYOUT_REQUIRED"), 1514 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 1515 name = "DRAWING_CACHE_INVALID", outputIf = false), 1516 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 1517 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 1518 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 1519 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 1520 }) 1521 int mPrivateFlags; 1522 1523 /** 1524 * Count of how many windows this view has been attached to. 1525 */ 1526 int mWindowAttachCount; 1527 1528 /** 1529 * The layout parameters associated with this view and used by the parent 1530 * {@link android.view.ViewGroup} to determine how this view should be 1531 * laid out. 1532 * {@hide} 1533 */ 1534 protected ViewGroup.LayoutParams mLayoutParams; 1535 1536 /** 1537 * The view flags hold various views states. 1538 * {@hide} 1539 */ 1540 @ViewDebug.ExportedProperty 1541 int mViewFlags; 1542 1543 /** 1544 * The distance in pixels from the left edge of this view's parent 1545 * to the left edge of this view. 1546 * {@hide} 1547 */ 1548 @ViewDebug.ExportedProperty 1549 protected int mLeft; 1550 /** 1551 * The distance in pixels from the left edge of this view's parent 1552 * to the right edge of this view. 1553 * {@hide} 1554 */ 1555 @ViewDebug.ExportedProperty 1556 protected int mRight; 1557 /** 1558 * The distance in pixels from the top edge of this view's parent 1559 * to the top edge of this view. 1560 * {@hide} 1561 */ 1562 @ViewDebug.ExportedProperty 1563 protected int mTop; 1564 /** 1565 * The distance in pixels from the top edge of this view's parent 1566 * to the bottom edge of this view. 1567 * {@hide} 1568 */ 1569 @ViewDebug.ExportedProperty 1570 protected int mBottom; 1571 1572 /** 1573 * The offset, in pixels, by which the content of this view is scrolled 1574 * horizontally. 1575 * {@hide} 1576 */ 1577 @ViewDebug.ExportedProperty 1578 protected int mScrollX; 1579 /** 1580 * The offset, in pixels, by which the content of this view is scrolled 1581 * vertically. 1582 * {@hide} 1583 */ 1584 @ViewDebug.ExportedProperty 1585 protected int mScrollY; 1586 1587 /** 1588 * The left padding in pixels, that is the distance in pixels between the 1589 * left edge of this view and the left edge of its content. 1590 * {@hide} 1591 */ 1592 @ViewDebug.ExportedProperty 1593 protected int mPaddingLeft; 1594 /** 1595 * The right padding in pixels, that is the distance in pixels between the 1596 * right edge of this view and the right edge of its content. 1597 * {@hide} 1598 */ 1599 @ViewDebug.ExportedProperty 1600 protected int mPaddingRight; 1601 /** 1602 * The top padding in pixels, that is the distance in pixels between the 1603 * top edge of this view and the top edge of its content. 1604 * {@hide} 1605 */ 1606 @ViewDebug.ExportedProperty 1607 protected int mPaddingTop; 1608 /** 1609 * The bottom padding in pixels, that is the distance in pixels between the 1610 * bottom edge of this view and the bottom edge of its content. 1611 * {@hide} 1612 */ 1613 @ViewDebug.ExportedProperty 1614 protected int mPaddingBottom; 1615 1616 /** 1617 * Briefly describes the view and is primarily used for accessibility support. 1618 */ 1619 private CharSequence mContentDescription; 1620 1621 /** 1622 * Cache the paddingRight set by the user to append to the scrollbar's size. 1623 */ 1624 @ViewDebug.ExportedProperty 1625 int mUserPaddingRight; 1626 1627 /** 1628 * Cache the paddingBottom set by the user to append to the scrollbar's size. 1629 */ 1630 @ViewDebug.ExportedProperty 1631 int mUserPaddingBottom; 1632 1633 /** 1634 * @hide 1635 */ 1636 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 1637 /** 1638 * @hide 1639 */ 1640 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 1641 1642 private Resources mResources = null; 1643 1644 private Drawable mBGDrawable; 1645 1646 private int mBackgroundResource; 1647 private boolean mBackgroundSizeChanged; 1648 1649 /** 1650 * Listener used to dispatch focus change events. 1651 * This field should be made private, so it is hidden from the SDK. 1652 * {@hide} 1653 */ 1654 protected OnFocusChangeListener mOnFocusChangeListener; 1655 1656 /** 1657 * Listener used to dispatch click events. 1658 * This field should be made private, so it is hidden from the SDK. 1659 * {@hide} 1660 */ 1661 protected OnClickListener mOnClickListener; 1662 1663 /** 1664 * Listener used to dispatch long click events. 1665 * This field should be made private, so it is hidden from the SDK. 1666 * {@hide} 1667 */ 1668 protected OnLongClickListener mOnLongClickListener; 1669 1670 /** 1671 * Listener used to build the context menu. 1672 * This field should be made private, so it is hidden from the SDK. 1673 * {@hide} 1674 */ 1675 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 1676 1677 private OnKeyListener mOnKeyListener; 1678 1679 private OnTouchListener mOnTouchListener; 1680 1681 /** 1682 * The application environment this view lives in. 1683 * This field should be made private, so it is hidden from the SDK. 1684 * {@hide} 1685 */ 1686 protected Context mContext; 1687 1688 private ScrollabilityCache mScrollCache; 1689 1690 private int[] mDrawableState = null; 1691 1692 private SoftReference<Bitmap> mDrawingCache; 1693 private SoftReference<Bitmap> mUnscaledDrawingCache; 1694 1695 /** 1696 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 1697 * the user may specify which view to go to next. 1698 */ 1699 private int mNextFocusLeftId = View.NO_ID; 1700 1701 /** 1702 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 1703 * the user may specify which view to go to next. 1704 */ 1705 private int mNextFocusRightId = View.NO_ID; 1706 1707 /** 1708 * When this view has focus and the next focus is {@link #FOCUS_UP}, 1709 * the user may specify which view to go to next. 1710 */ 1711 private int mNextFocusUpId = View.NO_ID; 1712 1713 /** 1714 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 1715 * the user may specify which view to go to next. 1716 */ 1717 private int mNextFocusDownId = View.NO_ID; 1718 1719 private CheckForLongPress mPendingCheckForLongPress; 1720 private UnsetPressedState mUnsetPressedState; 1721 1722 /** 1723 * Whether the long press's action has been invoked. The tap's action is invoked on the 1724 * up event while a long press is invoked as soon as the long press duration is reached, so 1725 * a long press could be performed before the tap is checked, in which case the tap's action 1726 * should not be invoked. 1727 */ 1728 private boolean mHasPerformedLongPress; 1729 1730 /** 1731 * The minimum height of the view. We'll try our best to have the height 1732 * of this view to at least this amount. 1733 */ 1734 @ViewDebug.ExportedProperty 1735 private int mMinHeight; 1736 1737 /** 1738 * The minimum width of the view. We'll try our best to have the width 1739 * of this view to at least this amount. 1740 */ 1741 @ViewDebug.ExportedProperty 1742 private int mMinWidth; 1743 1744 /** 1745 * The delegate to handle touch events that are physically in this view 1746 * but should be handled by another view. 1747 */ 1748 private TouchDelegate mTouchDelegate = null; 1749 1750 /** 1751 * Solid color to use as a background when creating the drawing cache. Enables 1752 * the cache to use 16 bit bitmaps instead of 32 bit. 1753 */ 1754 private int mDrawingCacheBackgroundColor = 0; 1755 1756 /** 1757 * Special tree observer used when mAttachInfo is null. 1758 */ 1759 private ViewTreeObserver mFloatingTreeObserver; 1760 1761 // Used for debug only 1762 static long sInstanceCount = 0; 1763 1764 /** 1765 * Simple constructor to use when creating a view from code. 1766 * 1767 * @param context The Context the view is running in, through which it can 1768 * access the current theme, resources, etc. 1769 */ 1770 public View(Context context) { 1771 mContext = context; 1772 mResources = context != null ? context.getResources() : null; 1773 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 1774 ++sInstanceCount; 1775 } 1776 1777 /** 1778 * Constructor that is called when inflating a view from XML. This is called 1779 * when a view is being constructed from an XML file, supplying attributes 1780 * that were specified in the XML file. This version uses a default style of 1781 * 0, so the only attribute values applied are those in the Context's Theme 1782 * and the given AttributeSet. 1783 * 1784 * <p> 1785 * The method onFinishInflate() will be called after all children have been 1786 * added. 1787 * 1788 * @param context The Context the view is running in, through which it can 1789 * access the current theme, resources, etc. 1790 * @param attrs The attributes of the XML tag that is inflating the view. 1791 * @see #View(Context, AttributeSet, int) 1792 */ 1793 public View(Context context, AttributeSet attrs) { 1794 this(context, attrs, 0); 1795 } 1796 1797 /** 1798 * Perform inflation from XML and apply a class-specific base style. This 1799 * constructor of View allows subclasses to use their own base style when 1800 * they are inflating. For example, a Button class's constructor would call 1801 * this version of the super class constructor and supply 1802 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 1803 * the theme's button style to modify all of the base view attributes (in 1804 * particular its background) as well as the Button class's attributes. 1805 * 1806 * @param context The Context the view is running in, through which it can 1807 * access the current theme, resources, etc. 1808 * @param attrs The attributes of the XML tag that is inflating the view. 1809 * @param defStyle The default style to apply to this view. If 0, no style 1810 * will be applied (beyond what is included in the theme). This may 1811 * either be an attribute resource, whose value will be retrieved 1812 * from the current theme, or an explicit style resource. 1813 * @see #View(Context, AttributeSet) 1814 */ 1815 public View(Context context, AttributeSet attrs, int defStyle) { 1816 this(context); 1817 1818 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 1819 defStyle, 0); 1820 1821 Drawable background = null; 1822 1823 int leftPadding = -1; 1824 int topPadding = -1; 1825 int rightPadding = -1; 1826 int bottomPadding = -1; 1827 1828 int padding = -1; 1829 1830 int viewFlagValues = 0; 1831 int viewFlagMasks = 0; 1832 1833 boolean setScrollContainer = false; 1834 1835 int x = 0; 1836 int y = 0; 1837 1838 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 1839 1840 final int N = a.getIndexCount(); 1841 for (int i = 0; i < N; i++) { 1842 int attr = a.getIndex(i); 1843 switch (attr) { 1844 case com.android.internal.R.styleable.View_background: 1845 background = a.getDrawable(attr); 1846 break; 1847 case com.android.internal.R.styleable.View_padding: 1848 padding = a.getDimensionPixelSize(attr, -1); 1849 break; 1850 case com.android.internal.R.styleable.View_paddingLeft: 1851 leftPadding = a.getDimensionPixelSize(attr, -1); 1852 break; 1853 case com.android.internal.R.styleable.View_paddingTop: 1854 topPadding = a.getDimensionPixelSize(attr, -1); 1855 break; 1856 case com.android.internal.R.styleable.View_paddingRight: 1857 rightPadding = a.getDimensionPixelSize(attr, -1); 1858 break; 1859 case com.android.internal.R.styleable.View_paddingBottom: 1860 bottomPadding = a.getDimensionPixelSize(attr, -1); 1861 break; 1862 case com.android.internal.R.styleable.View_scrollX: 1863 x = a.getDimensionPixelOffset(attr, 0); 1864 break; 1865 case com.android.internal.R.styleable.View_scrollY: 1866 y = a.getDimensionPixelOffset(attr, 0); 1867 break; 1868 case com.android.internal.R.styleable.View_id: 1869 mID = a.getResourceId(attr, NO_ID); 1870 break; 1871 case com.android.internal.R.styleable.View_tag: 1872 mTag = a.getText(attr); 1873 break; 1874 case com.android.internal.R.styleable.View_fitsSystemWindows: 1875 if (a.getBoolean(attr, false)) { 1876 viewFlagValues |= FITS_SYSTEM_WINDOWS; 1877 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 1878 } 1879 break; 1880 case com.android.internal.R.styleable.View_focusable: 1881 if (a.getBoolean(attr, false)) { 1882 viewFlagValues |= FOCUSABLE; 1883 viewFlagMasks |= FOCUSABLE_MASK; 1884 } 1885 break; 1886 case com.android.internal.R.styleable.View_focusableInTouchMode: 1887 if (a.getBoolean(attr, false)) { 1888 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 1889 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 1890 } 1891 break; 1892 case com.android.internal.R.styleable.View_clickable: 1893 if (a.getBoolean(attr, false)) { 1894 viewFlagValues |= CLICKABLE; 1895 viewFlagMasks |= CLICKABLE; 1896 } 1897 break; 1898 case com.android.internal.R.styleable.View_longClickable: 1899 if (a.getBoolean(attr, false)) { 1900 viewFlagValues |= LONG_CLICKABLE; 1901 viewFlagMasks |= LONG_CLICKABLE; 1902 } 1903 break; 1904 case com.android.internal.R.styleable.View_saveEnabled: 1905 if (!a.getBoolean(attr, true)) { 1906 viewFlagValues |= SAVE_DISABLED; 1907 viewFlagMasks |= SAVE_DISABLED_MASK; 1908 } 1909 break; 1910 case com.android.internal.R.styleable.View_duplicateParentState: 1911 if (a.getBoolean(attr, false)) { 1912 viewFlagValues |= DUPLICATE_PARENT_STATE; 1913 viewFlagMasks |= DUPLICATE_PARENT_STATE; 1914 } 1915 break; 1916 case com.android.internal.R.styleable.View_visibility: 1917 final int visibility = a.getInt(attr, 0); 1918 if (visibility != 0) { 1919 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 1920 viewFlagMasks |= VISIBILITY_MASK; 1921 } 1922 break; 1923 case com.android.internal.R.styleable.View_drawingCacheQuality: 1924 final int cacheQuality = a.getInt(attr, 0); 1925 if (cacheQuality != 0) { 1926 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 1927 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 1928 } 1929 break; 1930 case com.android.internal.R.styleable.View_contentDescription: 1931 mContentDescription = a.getString(attr); 1932 break; 1933 case com.android.internal.R.styleable.View_soundEffectsEnabled: 1934 if (!a.getBoolean(attr, true)) { 1935 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 1936 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 1937 } 1938 break; 1939 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 1940 if (!a.getBoolean(attr, true)) { 1941 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 1942 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 1943 } 1944 break; 1945 case R.styleable.View_scrollbars: 1946 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 1947 if (scrollbars != SCROLLBARS_NONE) { 1948 viewFlagValues |= scrollbars; 1949 viewFlagMasks |= SCROLLBARS_MASK; 1950 initializeScrollbars(a); 1951 } 1952 break; 1953 case R.styleable.View_fadingEdge: 1954 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 1955 if (fadingEdge != FADING_EDGE_NONE) { 1956 viewFlagValues |= fadingEdge; 1957 viewFlagMasks |= FADING_EDGE_MASK; 1958 initializeFadingEdge(a); 1959 } 1960 break; 1961 case R.styleable.View_scrollbarStyle: 1962 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 1963 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 1964 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 1965 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 1966 } 1967 break; 1968 case R.styleable.View_isScrollContainer: 1969 setScrollContainer = true; 1970 if (a.getBoolean(attr, false)) { 1971 setScrollContainer(true); 1972 } 1973 break; 1974 case com.android.internal.R.styleable.View_keepScreenOn: 1975 if (a.getBoolean(attr, false)) { 1976 viewFlagValues |= KEEP_SCREEN_ON; 1977 viewFlagMasks |= KEEP_SCREEN_ON; 1978 } 1979 break; 1980 case R.styleable.View_nextFocusLeft: 1981 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 1982 break; 1983 case R.styleable.View_nextFocusRight: 1984 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 1985 break; 1986 case R.styleable.View_nextFocusUp: 1987 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 1988 break; 1989 case R.styleable.View_nextFocusDown: 1990 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 1991 break; 1992 case R.styleable.View_minWidth: 1993 mMinWidth = a.getDimensionPixelSize(attr, 0); 1994 break; 1995 case R.styleable.View_minHeight: 1996 mMinHeight = a.getDimensionPixelSize(attr, 0); 1997 break; 1998 case R.styleable.View_onClick: 1999 final String handlerName = a.getString(attr); 2000 if (handlerName != null) { 2001 setOnClickListener(new OnClickListener() { 2002 private Method mHandler; 2003 2004 public void onClick(View v) { 2005 if (mHandler == null) { 2006 try { 2007 mHandler = getContext().getClass().getMethod(handlerName, 2008 View.class); 2009 } catch (NoSuchMethodException e) { 2010 throw new IllegalStateException("Could not find a method " + 2011 handlerName + "(View) in the activity", e); 2012 } 2013 } 2014 2015 try { 2016 mHandler.invoke(getContext(), View.this); 2017 } catch (IllegalAccessException e) { 2018 throw new IllegalStateException("Could not execute non " 2019 + "public method of the activity", e); 2020 } catch (InvocationTargetException e) { 2021 throw new IllegalStateException("Could not execute " 2022 + "method of the activity", e); 2023 } 2024 } 2025 }); 2026 } 2027 break; 2028 } 2029 } 2030 2031 if (background != null) { 2032 setBackgroundDrawable(background); 2033 } 2034 2035 if (padding >= 0) { 2036 leftPadding = padding; 2037 topPadding = padding; 2038 rightPadding = padding; 2039 bottomPadding = padding; 2040 } 2041 2042 // If the user specified the padding (either with android:padding or 2043 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 2044 // use the default padding or the padding from the background drawable 2045 // (stored at this point in mPadding*) 2046 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 2047 topPadding >= 0 ? topPadding : mPaddingTop, 2048 rightPadding >= 0 ? rightPadding : mPaddingRight, 2049 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 2050 2051 if (viewFlagMasks != 0) { 2052 setFlags(viewFlagValues, viewFlagMasks); 2053 } 2054 2055 // Needs to be called after mViewFlags is set 2056 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2057 recomputePadding(); 2058 } 2059 2060 if (x != 0 || y != 0) { 2061 scrollTo(x, y); 2062 } 2063 2064 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 2065 setScrollContainer(true); 2066 } 2067 2068 computeOpaqueFlags(); 2069 2070 a.recycle(); 2071 } 2072 2073 /** 2074 * Non-public constructor for use in testing 2075 */ 2076 View() { 2077 } 2078 2079 @Override 2080 protected void finalize() throws Throwable { 2081 super.finalize(); 2082 --sInstanceCount; 2083 } 2084 2085 /** 2086 * <p> 2087 * Initializes the fading edges from a given set of styled attributes. This 2088 * method should be called by subclasses that need fading edges and when an 2089 * instance of these subclasses is created programmatically rather than 2090 * being inflated from XML. This method is automatically called when the XML 2091 * is inflated. 2092 * </p> 2093 * 2094 * @param a the styled attributes set to initialize the fading edges from 2095 */ 2096 protected void initializeFadingEdge(TypedArray a) { 2097 initScrollCache(); 2098 2099 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 2100 R.styleable.View_fadingEdgeLength, 2101 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 2102 } 2103 2104 /** 2105 * Returns the size of the vertical faded edges used to indicate that more 2106 * content in this view is visible. 2107 * 2108 * @return The size in pixels of the vertical faded edge or 0 if vertical 2109 * faded edges are not enabled for this view. 2110 * @attr ref android.R.styleable#View_fadingEdgeLength 2111 */ 2112 public int getVerticalFadingEdgeLength() { 2113 if (isVerticalFadingEdgeEnabled()) { 2114 ScrollabilityCache cache = mScrollCache; 2115 if (cache != null) { 2116 return cache.fadingEdgeLength; 2117 } 2118 } 2119 return 0; 2120 } 2121 2122 /** 2123 * Set the size of the faded edge used to indicate that more content in this 2124 * view is available. Will not change whether the fading edge is enabled; use 2125 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled} 2126 * to enable the fading edge for the vertical or horizontal fading edges. 2127 * 2128 * @param length The size in pixels of the faded edge used to indicate that more 2129 * content in this view is visible. 2130 */ 2131 public void setFadingEdgeLength(int length) { 2132 initScrollCache(); 2133 mScrollCache.fadingEdgeLength = length; 2134 } 2135 2136 /** 2137 * Returns the size of the horizontal faded edges used to indicate that more 2138 * content in this view is visible. 2139 * 2140 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 2141 * faded edges are not enabled for this view. 2142 * @attr ref android.R.styleable#View_fadingEdgeLength 2143 */ 2144 public int getHorizontalFadingEdgeLength() { 2145 if (isHorizontalFadingEdgeEnabled()) { 2146 ScrollabilityCache cache = mScrollCache; 2147 if (cache != null) { 2148 return cache.fadingEdgeLength; 2149 } 2150 } 2151 return 0; 2152 } 2153 2154 /** 2155 * Returns the width of the vertical scrollbar. 2156 * 2157 * @return The width in pixels of the vertical scrollbar or 0 if there 2158 * is no vertical scrollbar. 2159 */ 2160 public int getVerticalScrollbarWidth() { 2161 ScrollabilityCache cache = mScrollCache; 2162 if (cache != null) { 2163 ScrollBarDrawable scrollBar = cache.scrollBar; 2164 if (scrollBar != null) { 2165 int size = scrollBar.getSize(true); 2166 if (size <= 0) { 2167 size = cache.scrollBarSize; 2168 } 2169 return size; 2170 } 2171 return 0; 2172 } 2173 return 0; 2174 } 2175 2176 /** 2177 * Returns the height of the horizontal scrollbar. 2178 * 2179 * @return The height in pixels of the horizontal scrollbar or 0 if 2180 * there is no horizontal scrollbar. 2181 */ 2182 protected int getHorizontalScrollbarHeight() { 2183 ScrollabilityCache cache = mScrollCache; 2184 if (cache != null) { 2185 ScrollBarDrawable scrollBar = cache.scrollBar; 2186 if (scrollBar != null) { 2187 int size = scrollBar.getSize(false); 2188 if (size <= 0) { 2189 size = cache.scrollBarSize; 2190 } 2191 return size; 2192 } 2193 return 0; 2194 } 2195 return 0; 2196 } 2197 2198 /** 2199 * <p> 2200 * Initializes the scrollbars from a given set of styled attributes. This 2201 * method should be called by subclasses that need scrollbars and when an 2202 * instance of these subclasses is created programmatically rather than 2203 * being inflated from XML. This method is automatically called when the XML 2204 * is inflated. 2205 * </p> 2206 * 2207 * @param a the styled attributes set to initialize the scrollbars from 2208 */ 2209 protected void initializeScrollbars(TypedArray a) { 2210 initScrollCache(); 2211 2212 if (mScrollCache.scrollBar == null) { 2213 mScrollCache.scrollBar = new ScrollBarDrawable(); 2214 } 2215 2216 final ScrollabilityCache scrollabilityCache = mScrollCache; 2217 2218 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 2219 com.android.internal.R.styleable.View_scrollbarSize, 2220 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 2221 2222 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 2223 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 2224 2225 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 2226 if (thumb != null) { 2227 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 2228 } 2229 2230 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 2231 false); 2232 if (alwaysDraw) { 2233 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 2234 } 2235 2236 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 2237 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 2238 2239 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 2240 if (thumb != null) { 2241 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 2242 } 2243 2244 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 2245 false); 2246 if (alwaysDraw) { 2247 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 2248 } 2249 2250 // Re-apply user/background padding so that scrollbar(s) get added 2251 recomputePadding(); 2252 } 2253 2254 /** 2255 * <p> 2256 * Initalizes the scrollability cache if necessary. 2257 * </p> 2258 */ 2259 private void initScrollCache() { 2260 if (mScrollCache == null) { 2261 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext)); 2262 } 2263 } 2264 2265 /** 2266 * Register a callback to be invoked when focus of this view changed. 2267 * 2268 * @param l The callback that will run. 2269 */ 2270 public void setOnFocusChangeListener(OnFocusChangeListener l) { 2271 mOnFocusChangeListener = l; 2272 } 2273 2274 /** 2275 * Returns the focus-change callback registered for this view. 2276 * 2277 * @return The callback, or null if one is not registered. 2278 */ 2279 public OnFocusChangeListener getOnFocusChangeListener() { 2280 return mOnFocusChangeListener; 2281 } 2282 2283 /** 2284 * Register a callback to be invoked when this view is clicked. If this view is not 2285 * clickable, it becomes clickable. 2286 * 2287 * @param l The callback that will run 2288 * 2289 * @see #setClickable(boolean) 2290 */ 2291 public void setOnClickListener(OnClickListener l) { 2292 if (!isClickable()) { 2293 setClickable(true); 2294 } 2295 mOnClickListener = l; 2296 } 2297 2298 /** 2299 * Register a callback to be invoked when this view is clicked and held. If this view is not 2300 * long clickable, it becomes long clickable. 2301 * 2302 * @param l The callback that will run 2303 * 2304 * @see #setLongClickable(boolean) 2305 */ 2306 public void setOnLongClickListener(OnLongClickListener l) { 2307 if (!isLongClickable()) { 2308 setLongClickable(true); 2309 } 2310 mOnLongClickListener = l; 2311 } 2312 2313 /** 2314 * Register a callback to be invoked when the context menu for this view is 2315 * being built. If this view is not long clickable, it becomes long clickable. 2316 * 2317 * @param l The callback that will run 2318 * 2319 */ 2320 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 2321 if (!isLongClickable()) { 2322 setLongClickable(true); 2323 } 2324 mOnCreateContextMenuListener = l; 2325 } 2326 2327 /** 2328 * Call this view's OnClickListener, if it is defined. 2329 * 2330 * @return True there was an assigned OnClickListener that was called, false 2331 * otherwise is returned. 2332 */ 2333 public boolean performClick() { 2334 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 2335 2336 if (mOnClickListener != null) { 2337 playSoundEffect(SoundEffectConstants.CLICK); 2338 mOnClickListener.onClick(this); 2339 return true; 2340 } 2341 2342 return false; 2343 } 2344 2345 /** 2346 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu 2347 * if the OnLongClickListener did not consume the event. 2348 * 2349 * @return True there was an assigned OnLongClickListener that was called, false 2350 * otherwise is returned. 2351 */ 2352 public boolean performLongClick() { 2353 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 2354 2355 boolean handled = false; 2356 if (mOnLongClickListener != null) { 2357 handled = mOnLongClickListener.onLongClick(View.this); 2358 } 2359 if (!handled) { 2360 handled = showContextMenu(); 2361 } 2362 if (handled) { 2363 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 2364 } 2365 return handled; 2366 } 2367 2368 /** 2369 * Bring up the context menu for this view. 2370 * 2371 * @return Whether a context menu was displayed. 2372 */ 2373 public boolean showContextMenu() { 2374 return getParent().showContextMenuForChild(this); 2375 } 2376 2377 /** 2378 * Register a callback to be invoked when a key is pressed in this view. 2379 * @param l the key listener to attach to this view 2380 */ 2381 public void setOnKeyListener(OnKeyListener l) { 2382 mOnKeyListener = l; 2383 } 2384 2385 /** 2386 * Register a callback to be invoked when a touch event is sent to this view. 2387 * @param l the touch listener to attach to this view 2388 */ 2389 public void setOnTouchListener(OnTouchListener l) { 2390 mOnTouchListener = l; 2391 } 2392 2393 /** 2394 * Give this view focus. This will cause {@link #onFocusChanged} to be called. 2395 * 2396 * Note: this does not check whether this {@link View} should get focus, it just 2397 * gives it focus no matter what. It should only be called internally by framework 2398 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 2399 * 2400 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN, 2401 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which 2402 * focus moved when requestFocus() is called. It may not always 2403 * apply, in which case use the default View.FOCUS_DOWN. 2404 * @param previouslyFocusedRect The rectangle of the view that had focus 2405 * prior in this View's coordinate system. 2406 */ 2407 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 2408 if (DBG) { 2409 System.out.println(this + " requestFocus()"); 2410 } 2411 2412 if ((mPrivateFlags & FOCUSED) == 0) { 2413 mPrivateFlags |= FOCUSED; 2414 2415 if (mParent != null) { 2416 mParent.requestChildFocus(this, this); 2417 } 2418 2419 onFocusChanged(true, direction, previouslyFocusedRect); 2420 refreshDrawableState(); 2421 } 2422 } 2423 2424 /** 2425 * Request that a rectangle of this view be visible on the screen, 2426 * scrolling if necessary just enough. 2427 * 2428 * <p>A View should call this if it maintains some notion of which part 2429 * of its content is interesting. For example, a text editing view 2430 * should call this when its cursor moves. 2431 * 2432 * @param rectangle The rectangle. 2433 * @return Whether any parent scrolled. 2434 */ 2435 public boolean requestRectangleOnScreen(Rect rectangle) { 2436 return requestRectangleOnScreen(rectangle, false); 2437 } 2438 2439 /** 2440 * Request that a rectangle of this view be visible on the screen, 2441 * scrolling if necessary just enough. 2442 * 2443 * <p>A View should call this if it maintains some notion of which part 2444 * of its content is interesting. For example, a text editing view 2445 * should call this when its cursor moves. 2446 * 2447 * <p>When <code>immediate</code> is set to true, scrolling will not be 2448 * animated. 2449 * 2450 * @param rectangle The rectangle. 2451 * @param immediate True to forbid animated scrolling, false otherwise 2452 * @return Whether any parent scrolled. 2453 */ 2454 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 2455 View child = this; 2456 ViewParent parent = mParent; 2457 boolean scrolled = false; 2458 while (parent != null) { 2459 scrolled |= parent.requestChildRectangleOnScreen(child, 2460 rectangle, immediate); 2461 2462 // offset rect so next call has the rectangle in the 2463 // coordinate system of its direct child. 2464 rectangle.offset(child.getLeft(), child.getTop()); 2465 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 2466 2467 if (!(parent instanceof View)) { 2468 break; 2469 } 2470 2471 child = (View) parent; 2472 parent = child.getParent(); 2473 } 2474 return scrolled; 2475 } 2476 2477 /** 2478 * Called when this view wants to give up focus. This will cause 2479 * {@link #onFocusChanged} to be called. 2480 */ 2481 public void clearFocus() { 2482 if (DBG) { 2483 System.out.println(this + " clearFocus()"); 2484 } 2485 2486 if ((mPrivateFlags & FOCUSED) != 0) { 2487 mPrivateFlags &= ~FOCUSED; 2488 2489 if (mParent != null) { 2490 mParent.clearChildFocus(this); 2491 } 2492 2493 onFocusChanged(false, 0, null); 2494 refreshDrawableState(); 2495 } 2496 } 2497 2498 /** 2499 * Called to clear the focus of a view that is about to be removed. 2500 * Doesn't call clearChildFocus, which prevents this view from taking 2501 * focus again before it has been removed from the parent 2502 */ 2503 void clearFocusForRemoval() { 2504 if ((mPrivateFlags & FOCUSED) != 0) { 2505 mPrivateFlags &= ~FOCUSED; 2506 2507 onFocusChanged(false, 0, null); 2508 refreshDrawableState(); 2509 } 2510 } 2511 2512 /** 2513 * Called internally by the view system when a new view is getting focus. 2514 * This is what clears the old focus. 2515 */ 2516 void unFocus() { 2517 if (DBG) { 2518 System.out.println(this + " unFocus()"); 2519 } 2520 2521 if ((mPrivateFlags & FOCUSED) != 0) { 2522 mPrivateFlags &= ~FOCUSED; 2523 2524 onFocusChanged(false, 0, null); 2525 refreshDrawableState(); 2526 } 2527 } 2528 2529 /** 2530 * Returns true if this view has focus iteself, or is the ancestor of the 2531 * view that has focus. 2532 * 2533 * @return True if this view has or contains focus, false otherwise. 2534 */ 2535 @ViewDebug.ExportedProperty 2536 public boolean hasFocus() { 2537 return (mPrivateFlags & FOCUSED) != 0; 2538 } 2539 2540 /** 2541 * Returns true if this view is focusable or if it contains a reachable View 2542 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 2543 * is a View whose parents do not block descendants focus. 2544 * 2545 * Only {@link #VISIBLE} views are considered focusable. 2546 * 2547 * @return True if the view is focusable or if the view contains a focusable 2548 * View, false otherwise. 2549 * 2550 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 2551 */ 2552 public boolean hasFocusable() { 2553 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 2554 } 2555 2556 /** 2557 * Called by the view system when the focus state of this view changes. 2558 * When the focus change event is caused by directional navigation, direction 2559 * and previouslyFocusedRect provide insight into where the focus is coming from. 2560 * When overriding, be sure to call up through to the super class so that 2561 * the standard focus handling will occur. 2562 * 2563 * @param gainFocus True if the View has focus; false otherwise. 2564 * @param direction The direction focus has moved when requestFocus() 2565 * is called to give this view focus. Values are 2566 * View.FOCUS_UP, View.FOCUS_DOWN, View.FOCUS_LEFT or 2567 * View.FOCUS_RIGHT. It may not always apply, in which 2568 * case use the default. 2569 * @param previouslyFocusedRect The rectangle, in this view's coordinate 2570 * system, of the previously focused view. If applicable, this will be 2571 * passed in as finer grained information about where the focus is coming 2572 * from (in addition to direction). Will be <code>null</code> otherwise. 2573 */ 2574 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 2575 if (gainFocus) { 2576 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 2577 } 2578 2579 InputMethodManager imm = InputMethodManager.peekInstance(); 2580 if (!gainFocus) { 2581 if (isPressed()) { 2582 setPressed(false); 2583 } 2584 if (imm != null && mAttachInfo != null 2585 && mAttachInfo.mHasWindowFocus) { 2586 imm.focusOut(this); 2587 } 2588 onFocusLost(); 2589 } else if (imm != null && mAttachInfo != null 2590 && mAttachInfo.mHasWindowFocus) { 2591 imm.focusIn(this); 2592 } 2593 2594 invalidate(); 2595 if (mOnFocusChangeListener != null) { 2596 mOnFocusChangeListener.onFocusChange(this, gainFocus); 2597 } 2598 } 2599 2600 /** 2601 * {@inheritDoc} 2602 */ 2603 public void sendAccessibilityEvent(int eventType) { 2604 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 2605 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 2606 } 2607 } 2608 2609 /** 2610 * {@inheritDoc} 2611 */ 2612 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 2613 event.setClassName(getClass().getName()); 2614 event.setPackageName(getContext().getPackageName()); 2615 event.setEnabled(isEnabled()); 2616 event.setContentDescription(mContentDescription); 2617 2618 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 2619 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 2620 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 2621 event.setItemCount(focusablesTempList.size()); 2622 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 2623 focusablesTempList.clear(); 2624 } 2625 2626 dispatchPopulateAccessibilityEvent(event); 2627 2628 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event); 2629 } 2630 2631 /** 2632 * Dispatches an {@link AccessibilityEvent} to the {@link View} children 2633 * to be populated. 2634 * 2635 * @param event The event. 2636 * 2637 * @return True if the event population was completed. 2638 */ 2639 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 2640 return false; 2641 } 2642 2643 /** 2644 * Gets the {@link View} description. It briefly describes the view and is 2645 * primarily used for accessibility support. Set this property to enable 2646 * better accessibility support for your application. This is especially 2647 * true for views that do not have textual representation (For example, 2648 * ImageButton). 2649 * 2650 * @return The content descriptiopn. 2651 * 2652 * @attr ref android.R.styleable#View_contentDescription 2653 */ 2654 public CharSequence getContentDescription() { 2655 return mContentDescription; 2656 } 2657 2658 /** 2659 * Sets the {@link View} description. It briefly describes the view and is 2660 * primarily used for accessibility support. Set this property to enable 2661 * better accessibility support for your application. This is especially 2662 * true for views that do not have textual representation (For example, 2663 * ImageButton). 2664 * 2665 * @param contentDescription The content description. 2666 * 2667 * @attr ref android.R.styleable#View_contentDescription 2668 */ 2669 public void setContentDescription(CharSequence contentDescription) { 2670 mContentDescription = contentDescription; 2671 } 2672 2673 /** 2674 * Invoked whenever this view loses focus, either by losing window focus or by losing 2675 * focus within its window. This method can be used to clear any state tied to the 2676 * focus. For instance, if a button is held pressed with the trackball and the window 2677 * loses focus, this method can be used to cancel the press. 2678 * 2679 * Subclasses of View overriding this method should always call super.onFocusLost(). 2680 * 2681 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 2682 * @see #onWindowFocusChanged(boolean) 2683 * 2684 * @hide pending API council approval 2685 */ 2686 protected void onFocusLost() { 2687 resetPressedState(); 2688 } 2689 2690 private void resetPressedState() { 2691 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 2692 return; 2693 } 2694 2695 if (isPressed()) { 2696 setPressed(false); 2697 2698 if (!mHasPerformedLongPress) { 2699 if (mPendingCheckForLongPress != null) { 2700 removeCallbacks(mPendingCheckForLongPress); 2701 } 2702 } 2703 } 2704 } 2705 2706 /** 2707 * Returns true if this view has focus 2708 * 2709 * @return True if this view has focus, false otherwise. 2710 */ 2711 @ViewDebug.ExportedProperty 2712 public boolean isFocused() { 2713 return (mPrivateFlags & FOCUSED) != 0; 2714 } 2715 2716 /** 2717 * Find the view in the hierarchy rooted at this view that currently has 2718 * focus. 2719 * 2720 * @return The view that currently has focus, or null if no focused view can 2721 * be found. 2722 */ 2723 public View findFocus() { 2724 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 2725 } 2726 2727 /** 2728 * Change whether this view is one of the set of scrollable containers in 2729 * its window. This will be used to determine whether the window can 2730 * resize or must pan when a soft input area is open -- scrollable 2731 * containers allow the window to use resize mode since the container 2732 * will appropriately shrink. 2733 */ 2734 public void setScrollContainer(boolean isScrollContainer) { 2735 if (isScrollContainer) { 2736 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 2737 mAttachInfo.mScrollContainers.add(this); 2738 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 2739 } 2740 mPrivateFlags |= SCROLL_CONTAINER; 2741 } else { 2742 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 2743 mAttachInfo.mScrollContainers.remove(this); 2744 } 2745 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 2746 } 2747 } 2748 2749 /** 2750 * Returns the quality of the drawing cache. 2751 * 2752 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 2753 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 2754 * 2755 * @see #setDrawingCacheQuality(int) 2756 * @see #setDrawingCacheEnabled(boolean) 2757 * @see #isDrawingCacheEnabled() 2758 * 2759 * @attr ref android.R.styleable#View_drawingCacheQuality 2760 */ 2761 public int getDrawingCacheQuality() { 2762 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 2763 } 2764 2765 /** 2766 * Set the drawing cache quality of this view. This value is used only when the 2767 * drawing cache is enabled 2768 * 2769 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 2770 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 2771 * 2772 * @see #getDrawingCacheQuality() 2773 * @see #setDrawingCacheEnabled(boolean) 2774 * @see #isDrawingCacheEnabled() 2775 * 2776 * @attr ref android.R.styleable#View_drawingCacheQuality 2777 */ 2778 public void setDrawingCacheQuality(int quality) { 2779 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 2780 } 2781 2782 /** 2783 * Returns whether the screen should remain on, corresponding to the current 2784 * value of {@link #KEEP_SCREEN_ON}. 2785 * 2786 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 2787 * 2788 * @see #setKeepScreenOn(boolean) 2789 * 2790 * @attr ref android.R.styleable#View_keepScreenOn 2791 */ 2792 public boolean getKeepScreenOn() { 2793 return (mViewFlags & KEEP_SCREEN_ON) != 0; 2794 } 2795 2796 /** 2797 * Controls whether the screen should remain on, modifying the 2798 * value of {@link #KEEP_SCREEN_ON}. 2799 * 2800 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 2801 * 2802 * @see #getKeepScreenOn() 2803 * 2804 * @attr ref android.R.styleable#View_keepScreenOn 2805 */ 2806 public void setKeepScreenOn(boolean keepScreenOn) { 2807 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 2808 } 2809 2810 /** 2811 * @return The user specified next focus ID. 2812 * 2813 * @attr ref android.R.styleable#View_nextFocusLeft 2814 */ 2815 public int getNextFocusLeftId() { 2816 return mNextFocusLeftId; 2817 } 2818 2819 /** 2820 * Set the id of the view to use for the next focus 2821 * 2822 * @param nextFocusLeftId 2823 * 2824 * @attr ref android.R.styleable#View_nextFocusLeft 2825 */ 2826 public void setNextFocusLeftId(int nextFocusLeftId) { 2827 mNextFocusLeftId = nextFocusLeftId; 2828 } 2829 2830 /** 2831 * @return The user specified next focus ID. 2832 * 2833 * @attr ref android.R.styleable#View_nextFocusRight 2834 */ 2835 public int getNextFocusRightId() { 2836 return mNextFocusRightId; 2837 } 2838 2839 /** 2840 * Set the id of the view to use for the next focus 2841 * 2842 * @param nextFocusRightId 2843 * 2844 * @attr ref android.R.styleable#View_nextFocusRight 2845 */ 2846 public void setNextFocusRightId(int nextFocusRightId) { 2847 mNextFocusRightId = nextFocusRightId; 2848 } 2849 2850 /** 2851 * @return The user specified next focus ID. 2852 * 2853 * @attr ref android.R.styleable#View_nextFocusUp 2854 */ 2855 public int getNextFocusUpId() { 2856 return mNextFocusUpId; 2857 } 2858 2859 /** 2860 * Set the id of the view to use for the next focus 2861 * 2862 * @param nextFocusUpId 2863 * 2864 * @attr ref android.R.styleable#View_nextFocusUp 2865 */ 2866 public void setNextFocusUpId(int nextFocusUpId) { 2867 mNextFocusUpId = nextFocusUpId; 2868 } 2869 2870 /** 2871 * @return The user specified next focus ID. 2872 * 2873 * @attr ref android.R.styleable#View_nextFocusDown 2874 */ 2875 public int getNextFocusDownId() { 2876 return mNextFocusDownId; 2877 } 2878 2879 /** 2880 * Set the id of the view to use for the next focus 2881 * 2882 * @param nextFocusDownId 2883 * 2884 * @attr ref android.R.styleable#View_nextFocusDown 2885 */ 2886 public void setNextFocusDownId(int nextFocusDownId) { 2887 mNextFocusDownId = nextFocusDownId; 2888 } 2889 2890 /** 2891 * Returns the visibility of this view and all of its ancestors 2892 * 2893 * @return True if this view and all of its ancestors are {@link #VISIBLE} 2894 */ 2895 public boolean isShown() { 2896 View current = this; 2897 //noinspection ConstantConditions 2898 do { 2899 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 2900 return false; 2901 } 2902 ViewParent parent = current.mParent; 2903 if (parent == null) { 2904 return false; // We are not attached to the view root 2905 } 2906 if (!(parent instanceof View)) { 2907 return true; 2908 } 2909 current = (View) parent; 2910 } while (current != null); 2911 2912 return false; 2913 } 2914 2915 /** 2916 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 2917 * is set 2918 * 2919 * @param insets Insets for system windows 2920 * 2921 * @return True if this view applied the insets, false otherwise 2922 */ 2923 protected boolean fitSystemWindows(Rect insets) { 2924 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 2925 mPaddingLeft = insets.left; 2926 mPaddingTop = insets.top; 2927 mPaddingRight = insets.right; 2928 mPaddingBottom = insets.bottom; 2929 requestLayout(); 2930 return true; 2931 } 2932 return false; 2933 } 2934 2935 /** 2936 * Returns the visibility status for this view. 2937 * 2938 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 2939 * @attr ref android.R.styleable#View_visibility 2940 */ 2941 @ViewDebug.ExportedProperty(mapping = { 2942 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 2943 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 2944 @ViewDebug.IntToString(from = GONE, to = "GONE") 2945 }) 2946 public int getVisibility() { 2947 return mViewFlags & VISIBILITY_MASK; 2948 } 2949 2950 /** 2951 * Set the enabled state of this view. 2952 * 2953 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 2954 * @attr ref android.R.styleable#View_visibility 2955 */ 2956 @RemotableViewMethod 2957 public void setVisibility(int visibility) { 2958 setFlags(visibility, VISIBILITY_MASK); 2959 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 2960 } 2961 2962 /** 2963 * Returns the enabled status for this view. The interpretation of the 2964 * enabled state varies by subclass. 2965 * 2966 * @return True if this view is enabled, false otherwise. 2967 */ 2968 @ViewDebug.ExportedProperty 2969 public boolean isEnabled() { 2970 return (mViewFlags & ENABLED_MASK) == ENABLED; 2971 } 2972 2973 /** 2974 * Set the enabled state of this view. The interpretation of the enabled 2975 * state varies by subclass. 2976 * 2977 * @param enabled True if this view is enabled, false otherwise. 2978 */ 2979 public void setEnabled(boolean enabled) { 2980 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 2981 2982 /* 2983 * The View most likely has to change its appearance, so refresh 2984 * the drawable state. 2985 */ 2986 refreshDrawableState(); 2987 2988 // Invalidate too, since the default behavior for views is to be 2989 // be drawn at 50% alpha rather than to change the drawable. 2990 invalidate(); 2991 } 2992 2993 /** 2994 * Set whether this view can receive the focus. 2995 * 2996 * Setting this to false will also ensure that this view is not focusable 2997 * in touch mode. 2998 * 2999 * @param focusable If true, this view can receive the focus. 3000 * 3001 * @see #setFocusableInTouchMode(boolean) 3002 * @attr ref android.R.styleable#View_focusable 3003 */ 3004 public void setFocusable(boolean focusable) { 3005 if (!focusable) { 3006 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 3007 } 3008 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 3009 } 3010 3011 /** 3012 * Set whether this view can receive focus while in touch mode. 3013 * 3014 * Setting this to true will also ensure that this view is focusable. 3015 * 3016 * @param focusableInTouchMode If true, this view can receive the focus while 3017 * in touch mode. 3018 * 3019 * @see #setFocusable(boolean) 3020 * @attr ref android.R.styleable#View_focusableInTouchMode 3021 */ 3022 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 3023 // Focusable in touch mode should always be set before the focusable flag 3024 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 3025 // which, in touch mode, will not successfully request focus on this view 3026 // because the focusable in touch mode flag is not set 3027 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 3028 if (focusableInTouchMode) { 3029 setFlags(FOCUSABLE, FOCUSABLE_MASK); 3030 } 3031 } 3032 3033 /** 3034 * Set whether this view should have sound effects enabled for events such as 3035 * clicking and touching. 3036 * 3037 * <p>You may wish to disable sound effects for a view if you already play sounds, 3038 * for instance, a dial key that plays dtmf tones. 3039 * 3040 * @param soundEffectsEnabled whether sound effects are enabled for this view. 3041 * @see #isSoundEffectsEnabled() 3042 * @see #playSoundEffect(int) 3043 * @attr ref android.R.styleable#View_soundEffectsEnabled 3044 */ 3045 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 3046 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 3047 } 3048 3049 /** 3050 * @return whether this view should have sound effects enabled for events such as 3051 * clicking and touching. 3052 * 3053 * @see #setSoundEffectsEnabled(boolean) 3054 * @see #playSoundEffect(int) 3055 * @attr ref android.R.styleable#View_soundEffectsEnabled 3056 */ 3057 @ViewDebug.ExportedProperty 3058 public boolean isSoundEffectsEnabled() { 3059 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 3060 } 3061 3062 /** 3063 * Set whether this view should have haptic feedback for events such as 3064 * long presses. 3065 * 3066 * <p>You may wish to disable haptic feedback if your view already controls 3067 * its own haptic feedback. 3068 * 3069 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 3070 * @see #isHapticFeedbackEnabled() 3071 * @see #performHapticFeedback(int) 3072 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 3073 */ 3074 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 3075 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 3076 } 3077 3078 /** 3079 * @return whether this view should have haptic feedback enabled for events 3080 * long presses. 3081 * 3082 * @see #setHapticFeedbackEnabled(boolean) 3083 * @see #performHapticFeedback(int) 3084 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 3085 */ 3086 @ViewDebug.ExportedProperty 3087 public boolean isHapticFeedbackEnabled() { 3088 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 3089 } 3090 3091 /** 3092 * If this view doesn't do any drawing on its own, set this flag to 3093 * allow further optimizations. By default, this flag is not set on 3094 * View, but could be set on some View subclasses such as ViewGroup. 3095 * 3096 * Typically, if you override {@link #onDraw} you should clear this flag. 3097 * 3098 * @param willNotDraw whether or not this View draw on its own 3099 */ 3100 public void setWillNotDraw(boolean willNotDraw) { 3101 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 3102 } 3103 3104 /** 3105 * Returns whether or not this View draws on its own. 3106 * 3107 * @return true if this view has nothing to draw, false otherwise 3108 */ 3109 @ViewDebug.ExportedProperty 3110 public boolean willNotDraw() { 3111 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 3112 } 3113 3114 /** 3115 * When a View's drawing cache is enabled, drawing is redirected to an 3116 * offscreen bitmap. Some views, like an ImageView, must be able to 3117 * bypass this mechanism if they already draw a single bitmap, to avoid 3118 * unnecessary usage of the memory. 3119 * 3120 * @param willNotCacheDrawing true if this view does not cache its 3121 * drawing, false otherwise 3122 */ 3123 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 3124 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 3125 } 3126 3127 /** 3128 * Returns whether or not this View can cache its drawing or not. 3129 * 3130 * @return true if this view does not cache its drawing, false otherwise 3131 */ 3132 @ViewDebug.ExportedProperty 3133 public boolean willNotCacheDrawing() { 3134 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 3135 } 3136 3137 /** 3138 * Indicates whether this view reacts to click events or not. 3139 * 3140 * @return true if the view is clickable, false otherwise 3141 * 3142 * @see #setClickable(boolean) 3143 * @attr ref android.R.styleable#View_clickable 3144 */ 3145 @ViewDebug.ExportedProperty 3146 public boolean isClickable() { 3147 return (mViewFlags & CLICKABLE) == CLICKABLE; 3148 } 3149 3150 /** 3151 * Enables or disables click events for this view. When a view 3152 * is clickable it will change its state to "pressed" on every click. 3153 * Subclasses should set the view clickable to visually react to 3154 * user's clicks. 3155 * 3156 * @param clickable true to make the view clickable, false otherwise 3157 * 3158 * @see #isClickable() 3159 * @attr ref android.R.styleable#View_clickable 3160 */ 3161 public void setClickable(boolean clickable) { 3162 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 3163 } 3164 3165 /** 3166 * Indicates whether this view reacts to long click events or not. 3167 * 3168 * @return true if the view is long clickable, false otherwise 3169 * 3170 * @see #setLongClickable(boolean) 3171 * @attr ref android.R.styleable#View_longClickable 3172 */ 3173 public boolean isLongClickable() { 3174 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 3175 } 3176 3177 /** 3178 * Enables or disables long click events for this view. When a view is long 3179 * clickable it reacts to the user holding down the button for a longer 3180 * duration than a tap. This event can either launch the listener or a 3181 * context menu. 3182 * 3183 * @param longClickable true to make the view long clickable, false otherwise 3184 * @see #isLongClickable() 3185 * @attr ref android.R.styleable#View_longClickable 3186 */ 3187 public void setLongClickable(boolean longClickable) { 3188 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 3189 } 3190 3191 /** 3192 * Sets the pressed that for this view. 3193 * 3194 * @see #isClickable() 3195 * @see #setClickable(boolean) 3196 * 3197 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 3198 * the View's internal state from a previously set "pressed" state. 3199 */ 3200 public void setPressed(boolean pressed) { 3201 if (pressed) { 3202 mPrivateFlags |= PRESSED; 3203 } else { 3204 mPrivateFlags &= ~PRESSED; 3205 } 3206 refreshDrawableState(); 3207 dispatchSetPressed(pressed); 3208 } 3209 3210 /** 3211 * Dispatch setPressed to all of this View's children. 3212 * 3213 * @see #setPressed(boolean) 3214 * 3215 * @param pressed The new pressed state 3216 */ 3217 protected void dispatchSetPressed(boolean pressed) { 3218 } 3219 3220 /** 3221 * Indicates whether the view is currently in pressed state. Unless 3222 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 3223 * the pressed state. 3224 * 3225 * @see #setPressed 3226 * @see #isClickable() 3227 * @see #setClickable(boolean) 3228 * 3229 * @return true if the view is currently pressed, false otherwise 3230 */ 3231 public boolean isPressed() { 3232 return (mPrivateFlags & PRESSED) == PRESSED; 3233 } 3234 3235 /** 3236 * Indicates whether this view will save its state (that is, 3237 * whether its {@link #onSaveInstanceState} method will be called). 3238 * 3239 * @return Returns true if the view state saving is enabled, else false. 3240 * 3241 * @see #setSaveEnabled(boolean) 3242 * @attr ref android.R.styleable#View_saveEnabled 3243 */ 3244 public boolean isSaveEnabled() { 3245 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 3246 } 3247 3248 /** 3249 * Controls whether the saving of this view's state is 3250 * enabled (that is, whether its {@link #onSaveInstanceState} method 3251 * will be called). Note that even if freezing is enabled, the 3252 * view still must have an id assigned to it (via {@link #setId setId()}) 3253 * for its state to be saved. This flag can only disable the 3254 * saving of this view; any child views may still have their state saved. 3255 * 3256 * @param enabled Set to false to <em>disable</em> state saving, or true 3257 * (the default) to allow it. 3258 * 3259 * @see #isSaveEnabled() 3260 * @see #setId(int) 3261 * @see #onSaveInstanceState() 3262 * @attr ref android.R.styleable#View_saveEnabled 3263 */ 3264 public void setSaveEnabled(boolean enabled) { 3265 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 3266 } 3267 3268 3269 /** 3270 * Returns whether this View is able to take focus. 3271 * 3272 * @return True if this view can take focus, or false otherwise. 3273 * @attr ref android.R.styleable#View_focusable 3274 */ 3275 @ViewDebug.ExportedProperty 3276 public final boolean isFocusable() { 3277 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 3278 } 3279 3280 /** 3281 * When a view is focusable, it may not want to take focus when in touch mode. 3282 * For example, a button would like focus when the user is navigating via a D-pad 3283 * so that the user can click on it, but once the user starts touching the screen, 3284 * the button shouldn't take focus 3285 * @return Whether the view is focusable in touch mode. 3286 * @attr ref android.R.styleable#View_focusableInTouchMode 3287 */ 3288 @ViewDebug.ExportedProperty 3289 public final boolean isFocusableInTouchMode() { 3290 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 3291 } 3292 3293 /** 3294 * Find the nearest view in the specified direction that can take focus. 3295 * This does not actually give focus to that view. 3296 * 3297 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 3298 * 3299 * @return The nearest focusable in the specified direction, or null if none 3300 * can be found. 3301 */ 3302 public View focusSearch(int direction) { 3303 if (mParent != null) { 3304 return mParent.focusSearch(this, direction); 3305 } else { 3306 return null; 3307 } 3308 } 3309 3310 /** 3311 * This method is the last chance for the focused view and its ancestors to 3312 * respond to an arrow key. This is called when the focused view did not 3313 * consume the key internally, nor could the view system find a new view in 3314 * the requested direction to give focus to. 3315 * 3316 * @param focused The currently focused view. 3317 * @param direction The direction focus wants to move. One of FOCUS_UP, 3318 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 3319 * @return True if the this view consumed this unhandled move. 3320 */ 3321 public boolean dispatchUnhandledMove(View focused, int direction) { 3322 return false; 3323 } 3324 3325 /** 3326 * If a user manually specified the next view id for a particular direction, 3327 * use the root to look up the view. Once a view is found, it is cached 3328 * for future lookups. 3329 * @param root The root view of the hierarchy containing this view. 3330 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 3331 * @return The user specified next view, or null if there is none. 3332 */ 3333 View findUserSetNextFocus(View root, int direction) { 3334 switch (direction) { 3335 case FOCUS_LEFT: 3336 if (mNextFocusLeftId == View.NO_ID) return null; 3337 return findViewShouldExist(root, mNextFocusLeftId); 3338 case FOCUS_RIGHT: 3339 if (mNextFocusRightId == View.NO_ID) return null; 3340 return findViewShouldExist(root, mNextFocusRightId); 3341 case FOCUS_UP: 3342 if (mNextFocusUpId == View.NO_ID) return null; 3343 return findViewShouldExist(root, mNextFocusUpId); 3344 case FOCUS_DOWN: 3345 if (mNextFocusDownId == View.NO_ID) return null; 3346 return findViewShouldExist(root, mNextFocusDownId); 3347 } 3348 return null; 3349 } 3350 3351 private static View findViewShouldExist(View root, int childViewId) { 3352 View result = root.findViewById(childViewId); 3353 if (result == null) { 3354 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 3355 + "by user for id " + childViewId); 3356 } 3357 return result; 3358 } 3359 3360 /** 3361 * Find and return all focusable views that are descendants of this view, 3362 * possibly including this view if it is focusable itself. 3363 * 3364 * @param direction The direction of the focus 3365 * @return A list of focusable views 3366 */ 3367 public ArrayList<View> getFocusables(int direction) { 3368 ArrayList<View> result = new ArrayList<View>(24); 3369 addFocusables(result, direction); 3370 return result; 3371 } 3372 3373 /** 3374 * Add any focusable views that are descendants of this view (possibly 3375 * including this view if it is focusable itself) to views. If we are in touch mode, 3376 * only add views that are also focusable in touch mode. 3377 * 3378 * @param views Focusable views found so far 3379 * @param direction The direction of the focus 3380 */ 3381 public void addFocusables(ArrayList<View> views, int direction) { 3382 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 3383 } 3384 3385 /** 3386 * Adds any focusable views that are descendants of this view (possibly 3387 * including this view if it is focusable itself) to views. This method 3388 * adds all focusable views regardless if we are in touch mode or 3389 * only views focusable in touch mode if we are in touch mode depending on 3390 * the focusable mode paramater. 3391 * 3392 * @param views Focusable views found so far or null if all we are interested is 3393 * the number of focusables. 3394 * @param direction The direction of the focus. 3395 * @param focusableMode The type of focusables to be added. 3396 * 3397 * @see #FOCUSABLES_ALL 3398 * @see #FOCUSABLES_TOUCH_MODE 3399 */ 3400 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 3401 if (!isFocusable()) { 3402 return; 3403 } 3404 3405 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 3406 isInTouchMode() && !isFocusableInTouchMode()) { 3407 return; 3408 } 3409 3410 if (views != null) { 3411 views.add(this); 3412 } 3413 } 3414 3415 /** 3416 * Find and return all touchable views that are descendants of this view, 3417 * possibly including this view if it is touchable itself. 3418 * 3419 * @return A list of touchable views 3420 */ 3421 public ArrayList<View> getTouchables() { 3422 ArrayList<View> result = new ArrayList<View>(); 3423 addTouchables(result); 3424 return result; 3425 } 3426 3427 /** 3428 * Add any touchable views that are descendants of this view (possibly 3429 * including this view if it is touchable itself) to views. 3430 * 3431 * @param views Touchable views found so far 3432 */ 3433 public void addTouchables(ArrayList<View> views) { 3434 final int viewFlags = mViewFlags; 3435 3436 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 3437 && (viewFlags & ENABLED_MASK) == ENABLED) { 3438 views.add(this); 3439 } 3440 } 3441 3442 /** 3443 * Call this to try to give focus to a specific view or to one of its 3444 * descendants. 3445 * 3446 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false), 3447 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode}) 3448 * while the device is in touch mode. 3449 * 3450 * See also {@link #focusSearch}, which is what you call to say that you 3451 * have focus, and you want your parent to look for the next one. 3452 * 3453 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 3454 * {@link #FOCUS_DOWN} and <code>null</code>. 3455 * 3456 * @return Whether this view or one of its descendants actually took focus. 3457 */ 3458 public final boolean requestFocus() { 3459 return requestFocus(View.FOCUS_DOWN); 3460 } 3461 3462 3463 /** 3464 * Call this to try to give focus to a specific view or to one of its 3465 * descendants and give it a hint about what direction focus is heading. 3466 * 3467 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false), 3468 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode}) 3469 * while the device is in touch mode. 3470 * 3471 * See also {@link #focusSearch}, which is what you call to say that you 3472 * have focus, and you want your parent to look for the next one. 3473 * 3474 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 3475 * <code>null</code> set for the previously focused rectangle. 3476 * 3477 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 3478 * @return Whether this view or one of its descendants actually took focus. 3479 */ 3480 public final boolean requestFocus(int direction) { 3481 return requestFocus(direction, null); 3482 } 3483 3484 /** 3485 * Call this to try to give focus to a specific view or to one of its descendants 3486 * and give it hints about the direction and a specific rectangle that the focus 3487 * is coming from. The rectangle can help give larger views a finer grained hint 3488 * about where focus is coming from, and therefore, where to show selection, or 3489 * forward focus change internally. 3490 * 3491 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false), 3492 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode}) 3493 * while the device is in touch mode. 3494 * 3495 * A View will not take focus if it is not visible. 3496 * 3497 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()} 3498 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 3499 * 3500 * See also {@link #focusSearch}, which is what you call to say that you 3501 * have focus, and you want your parent to look for the next one. 3502 * 3503 * You may wish to override this method if your custom {@link View} has an internal 3504 * {@link View} that it wishes to forward the request to. 3505 * 3506 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 3507 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 3508 * to give a finer grained hint about where focus is coming from. May be null 3509 * if there is no hint. 3510 * @return Whether this view or one of its descendants actually took focus. 3511 */ 3512 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 3513 // need to be focusable 3514 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 3515 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 3516 return false; 3517 } 3518 3519 // need to be focusable in touch mode if in touch mode 3520 if (isInTouchMode() && 3521 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 3522 return false; 3523 } 3524 3525 // need to not have any parents blocking us 3526 if (hasAncestorThatBlocksDescendantFocus()) { 3527 return false; 3528 } 3529 3530 handleFocusGainInternal(direction, previouslyFocusedRect); 3531 return true; 3532 } 3533 3534 /** 3535 * Call this to try to give focus to a specific view or to one of its descendants. This is a 3536 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 3537 * touch mode to request focus when they are touched. 3538 * 3539 * @return Whether this view or one of its descendants actually took focus. 3540 * 3541 * @see #isInTouchMode() 3542 * 3543 */ 3544 public final boolean requestFocusFromTouch() { 3545 // Leave touch mode if we need to 3546 if (isInTouchMode()) { 3547 View root = getRootView(); 3548 if (root != null) { 3549 ViewRoot viewRoot = (ViewRoot)root.getParent(); 3550 if (viewRoot != null) { 3551 viewRoot.ensureTouchMode(false); 3552 } 3553 } 3554 } 3555 return requestFocus(View.FOCUS_DOWN); 3556 } 3557 3558 /** 3559 * @return Whether any ancestor of this view blocks descendant focus. 3560 */ 3561 private boolean hasAncestorThatBlocksDescendantFocus() { 3562 ViewParent ancestor = mParent; 3563 while (ancestor instanceof ViewGroup) { 3564 final ViewGroup vgAncestor = (ViewGroup) ancestor; 3565 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 3566 return true; 3567 } else { 3568 ancestor = vgAncestor.getParent(); 3569 } 3570 } 3571 return false; 3572 } 3573 3574 /** 3575 * This is called when a container is going to temporarily detach a child 3576 * that currently has focus, with 3577 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 3578 * It will either be followed by {@link #onFinishTemporaryDetach()} or 3579 * {@link #onDetachedFromWindow()} when the container is done. Generally 3580 * this is currently only done ListView for a view with focus. 3581 */ 3582 public void onStartTemporaryDetach() { 3583 } 3584 3585 /** 3586 * Called after {@link #onStartTemporaryDetach} when the container is done 3587 * changing the view. 3588 */ 3589 public void onFinishTemporaryDetach() { 3590 } 3591 3592 /** 3593 * capture information of this view for later analysis: developement only 3594 * check dynamic switch to make sure we only dump view 3595 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set 3596 */ 3597 private static void captureViewInfo(String subTag, View v) { 3598 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) { 3599 return; 3600 } 3601 ViewDebug.dumpCapturedView(subTag, v); 3602 } 3603 3604 /** 3605 * Dispatch a key event before it is processed by any input method 3606 * associated with the view hierarchy. This can be used to intercept 3607 * key events in special situations before the IME consumes them; a 3608 * typical example would be handling the BACK key to update the application's 3609 * UI instead of allowing the IME to see it and close itself. 3610 * 3611 * @param event The key event to be dispatched. 3612 * @return True if the event was handled, false otherwise. 3613 */ 3614 public boolean dispatchKeyEventPreIme(KeyEvent event) { 3615 return onKeyPreIme(event.getKeyCode(), event); 3616 } 3617 3618 /** 3619 * Dispatch a key event to the next view on the focus path. This path runs 3620 * from the top of the view tree down to the currently focused view. If this 3621 * view has focus, it will dispatch to itself. Otherwise it will dispatch 3622 * the next node down the focus path. This method also fires any key 3623 * listeners. 3624 * 3625 * @param event The key event to be dispatched. 3626 * @return True if the event was handled, false otherwise. 3627 */ 3628 public boolean dispatchKeyEvent(KeyEvent event) { 3629 // If any attached key listener a first crack at the event. 3630 //noinspection SimplifiableIfStatement 3631 3632 if (android.util.Config.LOGV) { 3633 captureViewInfo("captureViewKeyEvent", this); 3634 } 3635 3636 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 3637 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 3638 return true; 3639 } 3640 3641 return event.dispatch(this); 3642 } 3643 3644 /** 3645 * Dispatches a key shortcut event. 3646 * 3647 * @param event The key event to be dispatched. 3648 * @return True if the event was handled by the view, false otherwise. 3649 */ 3650 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 3651 return onKeyShortcut(event.getKeyCode(), event); 3652 } 3653 3654 /** 3655 * Pass the touch screen motion event down to the target view, or this 3656 * view if it is the target. 3657 * 3658 * @param event The motion event to be dispatched. 3659 * @return True if the event was handled by the view, false otherwise. 3660 */ 3661 public boolean dispatchTouchEvent(MotionEvent event) { 3662 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && 3663 mOnTouchListener.onTouch(this, event)) { 3664 return true; 3665 } 3666 return onTouchEvent(event); 3667 } 3668 3669 /** 3670 * Pass a trackball motion event down to the focused view. 3671 * 3672 * @param event The motion event to be dispatched. 3673 * @return True if the event was handled by the view, false otherwise. 3674 */ 3675 public boolean dispatchTrackballEvent(MotionEvent event) { 3676 //Log.i("view", "view=" + this + ", " + event.toString()); 3677 return onTrackballEvent(event); 3678 } 3679 3680 /** 3681 * Called when the window containing this view gains or loses window focus. 3682 * ViewGroups should override to route to their children. 3683 * 3684 * @param hasFocus True if the window containing this view now has focus, 3685 * false otherwise. 3686 */ 3687 public void dispatchWindowFocusChanged(boolean hasFocus) { 3688 onWindowFocusChanged(hasFocus); 3689 } 3690 3691 /** 3692 * Called when the window containing this view gains or loses focus. Note 3693 * that this is separate from view focus: to receive key events, both 3694 * your view and its window must have focus. If a window is displayed 3695 * on top of yours that takes input focus, then your own window will lose 3696 * focus but the view focus will remain unchanged. 3697 * 3698 * @param hasWindowFocus True if the window containing this view now has 3699 * focus, false otherwise. 3700 */ 3701 public void onWindowFocusChanged(boolean hasWindowFocus) { 3702 InputMethodManager imm = InputMethodManager.peekInstance(); 3703 if (!hasWindowFocus) { 3704 if (isPressed()) { 3705 setPressed(false); 3706 } 3707 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 3708 imm.focusOut(this); 3709 } 3710 if (mPendingCheckForLongPress != null) { 3711 removeCallbacks(mPendingCheckForLongPress); 3712 } 3713 onFocusLost(); 3714 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 3715 imm.focusIn(this); 3716 } 3717 refreshDrawableState(); 3718 } 3719 3720 /** 3721 * Returns true if this view is in a window that currently has window focus. 3722 * Note that this is not the same as the view itself having focus. 3723 * 3724 * @return True if this view is in a window that currently has window focus. 3725 */ 3726 public boolean hasWindowFocus() { 3727 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 3728 } 3729 3730 /** 3731 * Dispatch a window visibility change down the view hierarchy. 3732 * ViewGroups should override to route to their children. 3733 * 3734 * @param visibility The new visibility of the window. 3735 * 3736 * @see #onWindowVisibilityChanged 3737 */ 3738 public void dispatchWindowVisibilityChanged(int visibility) { 3739 onWindowVisibilityChanged(visibility); 3740 } 3741 3742 /** 3743 * Called when the window containing has change its visibility 3744 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 3745 * that this tells you whether or not your window is being made visible 3746 * to the window manager; this does <em>not</em> tell you whether or not 3747 * your window is obscured by other windows on the screen, even if it 3748 * is itself visible. 3749 * 3750 * @param visibility The new visibility of the window. 3751 */ 3752 protected void onWindowVisibilityChanged(int visibility) { 3753 } 3754 3755 /** 3756 * Returns the current visibility of the window this view is attached to 3757 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 3758 * 3759 * @return Returns the current visibility of the view's window. 3760 */ 3761 public int getWindowVisibility() { 3762 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 3763 } 3764 3765 /** 3766 * Retrieve the overall visible display size in which the window this view is 3767 * attached to has been positioned in. This takes into account screen 3768 * decorations above the window, for both cases where the window itself 3769 * is being position inside of them or the window is being placed under 3770 * then and covered insets are used for the window to position its content 3771 * inside. In effect, this tells you the available area where content can 3772 * be placed and remain visible to users. 3773 * 3774 * <p>This function requires an IPC back to the window manager to retrieve 3775 * the requested information, so should not be used in performance critical 3776 * code like drawing. 3777 * 3778 * @param outRect Filled in with the visible display frame. If the view 3779 * is not attached to a window, this is simply the raw display size. 3780 */ 3781 public void getWindowVisibleDisplayFrame(Rect outRect) { 3782 if (mAttachInfo != null) { 3783 try { 3784 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 3785 } catch (RemoteException e) { 3786 return; 3787 } 3788 // XXX This is really broken, and probably all needs to be done 3789 // in the window manager, and we need to know more about whether 3790 // we want the area behind or in front of the IME. 3791 final Rect insets = mAttachInfo.mVisibleInsets; 3792 outRect.left += insets.left; 3793 outRect.top += insets.top; 3794 outRect.right -= insets.right; 3795 outRect.bottom -= insets.bottom; 3796 return; 3797 } 3798 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 3799 outRect.set(0, 0, d.getWidth(), d.getHeight()); 3800 } 3801 3802 /** 3803 * Private function to aggregate all per-view attributes in to the view 3804 * root. 3805 */ 3806 void dispatchCollectViewAttributes(int visibility) { 3807 performCollectViewAttributes(visibility); 3808 } 3809 3810 void performCollectViewAttributes(int visibility) { 3811 //noinspection PointlessBitwiseExpression 3812 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON)) 3813 == (VISIBLE | KEEP_SCREEN_ON)) { 3814 mAttachInfo.mKeepScreenOn = true; 3815 } 3816 } 3817 3818 void needGlobalAttributesUpdate(boolean force) { 3819 AttachInfo ai = mAttachInfo; 3820 if (ai != null) { 3821 if (ai.mKeepScreenOn || force) { 3822 ai.mRecomputeGlobalAttributes = true; 3823 } 3824 } 3825 } 3826 3827 /** 3828 * Returns whether the device is currently in touch mode. Touch mode is entered 3829 * once the user begins interacting with the device by touch, and affects various 3830 * things like whether focus is always visible to the user. 3831 * 3832 * @return Whether the device is in touch mode. 3833 */ 3834 @ViewDebug.ExportedProperty 3835 public boolean isInTouchMode() { 3836 if (mAttachInfo != null) { 3837 return mAttachInfo.mInTouchMode; 3838 } else { 3839 return ViewRoot.isInTouchMode(); 3840 } 3841 } 3842 3843 /** 3844 * Returns the context the view is running in, through which it can 3845 * access the current theme, resources, etc. 3846 * 3847 * @return The view's Context. 3848 */ 3849 @ViewDebug.CapturedViewProperty 3850 public final Context getContext() { 3851 return mContext; 3852 } 3853 3854 /** 3855 * Handle a key event before it is processed by any input method 3856 * associated with the view hierarchy. This can be used to intercept 3857 * key events in special situations before the IME consumes them; a 3858 * typical example would be handling the BACK key to update the application's 3859 * UI instead of allowing the IME to see it and close itself. 3860 * 3861 * @param keyCode The value in event.getKeyCode(). 3862 * @param event Description of the key event. 3863 * @return If you handled the event, return true. If you want to allow the 3864 * event to be handled by the next receiver, return false. 3865 */ 3866 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 3867 return false; 3868 } 3869 3870 /** 3871 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 3872 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view 3873 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 3874 * is released, if the view is enabled and clickable. 3875 * 3876 * @param keyCode A key code that represents the button pressed, from 3877 * {@link android.view.KeyEvent}. 3878 * @param event The KeyEvent object that defines the button action. 3879 */ 3880 public boolean onKeyDown(int keyCode, KeyEvent event) { 3881 boolean result = false; 3882 3883 switch (keyCode) { 3884 case KeyEvent.KEYCODE_DPAD_CENTER: 3885 case KeyEvent.KEYCODE_ENTER: { 3886 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 3887 return true; 3888 } 3889 // Long clickable items don't necessarily have to be clickable 3890 if (((mViewFlags & CLICKABLE) == CLICKABLE || 3891 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 3892 (event.getRepeatCount() == 0)) { 3893 setPressed(true); 3894 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 3895 postCheckForLongClick(); 3896 } 3897 return true; 3898 } 3899 break; 3900 } 3901 } 3902 return result; 3903 } 3904 3905 /** 3906 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 3907 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view 3908 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 3909 * {@link KeyEvent#KEYCODE_ENTER} is released. 3910 * 3911 * @param keyCode A key code that represents the button pressed, from 3912 * {@link android.view.KeyEvent}. 3913 * @param event The KeyEvent object that defines the button action. 3914 */ 3915 public boolean onKeyUp(int keyCode, KeyEvent event) { 3916 boolean result = false; 3917 3918 switch (keyCode) { 3919 case KeyEvent.KEYCODE_DPAD_CENTER: 3920 case KeyEvent.KEYCODE_ENTER: { 3921 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 3922 return true; 3923 } 3924 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 3925 setPressed(false); 3926 3927 if (!mHasPerformedLongPress) { 3928 // This is a tap, so remove the longpress check 3929 if (mPendingCheckForLongPress != null) { 3930 removeCallbacks(mPendingCheckForLongPress); 3931 } 3932 3933 result = performClick(); 3934 } 3935 } 3936 break; 3937 } 3938 } 3939 return result; 3940 } 3941 3942 /** 3943 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 3944 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 3945 * the event). 3946 * 3947 * @param keyCode A key code that represents the button pressed, from 3948 * {@link android.view.KeyEvent}. 3949 * @param repeatCount The number of times the action was made. 3950 * @param event The KeyEvent object that defines the button action. 3951 */ 3952 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 3953 return false; 3954 } 3955 3956 /** 3957 * Called when an unhandled key shortcut event occurs. 3958 * 3959 * @param keyCode The value in event.getKeyCode(). 3960 * @param event Description of the key event. 3961 * @return If you handled the event, return true. If you want to allow the 3962 * event to be handled by the next receiver, return false. 3963 */ 3964 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 3965 return false; 3966 } 3967 3968 /** 3969 * Check whether the called view is a text editor, in which case it 3970 * would make sense to automatically display a soft input window for 3971 * it. Subclasses should override this if they implement 3972 * {@link #onCreateInputConnection(EditorInfo)} to return true if 3973 * a call on that method would return a non-null InputConnection, and 3974 * they are really a first-class editor that the user would normally 3975 * start typing on when the go into a window containing your view. 3976 * 3977 * <p>The default implementation always returns false. This does 3978 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 3979 * will not be called or the user can not otherwise perform edits on your 3980 * view; it is just a hint to the system that this is not the primary 3981 * purpose of this view. 3982 * 3983 * @return Returns true if this view is a text editor, else false. 3984 */ 3985 public boolean onCheckIsTextEditor() { 3986 return false; 3987 } 3988 3989 /** 3990 * Create a new InputConnection for an InputMethod to interact 3991 * with the view. The default implementation returns null, since it doesn't 3992 * support input methods. You can override this to implement such support. 3993 * This is only needed for views that take focus and text input. 3994 * 3995 * <p>When implementing this, you probably also want to implement 3996 * {@link #onCheckIsTextEditor()} to indicate you will return a 3997 * non-null InputConnection. 3998 * 3999 * @param outAttrs Fill in with attribute information about the connection. 4000 */ 4001 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 4002 return null; 4003 } 4004 4005 /** 4006 * Called by the {@link android.view.inputmethod.InputMethodManager} 4007 * when a view who is not the current 4008 * input connection target is trying to make a call on the manager. The 4009 * default implementation returns false; you can override this to return 4010 * true for certain views if you are performing InputConnection proxying 4011 * to them. 4012 * @param view The View that is making the InputMethodManager call. 4013 * @return Return true to allow the call, false to reject. 4014 */ 4015 public boolean checkInputConnectionProxy(View view) { 4016 return false; 4017 } 4018 4019 /** 4020 * Show the context menu for this view. It is not safe to hold on to the 4021 * menu after returning from this method. 4022 * 4023 * @param menu The context menu to populate 4024 */ 4025 public void createContextMenu(ContextMenu menu) { 4026 ContextMenuInfo menuInfo = getContextMenuInfo(); 4027 4028 // Sets the current menu info so all items added to menu will have 4029 // my extra info set. 4030 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 4031 4032 onCreateContextMenu(menu); 4033 if (mOnCreateContextMenuListener != null) { 4034 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 4035 } 4036 4037 // Clear the extra information so subsequent items that aren't mine don't 4038 // have my extra info. 4039 ((MenuBuilder)menu).setCurrentMenuInfo(null); 4040 4041 if (mParent != null) { 4042 mParent.createContextMenu(menu); 4043 } 4044 } 4045 4046 /** 4047 * Views should implement this if they have extra information to associate 4048 * with the context menu. The return result is supplied as a parameter to 4049 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 4050 * callback. 4051 * 4052 * @return Extra information about the item for which the context menu 4053 * should be shown. This information will vary across different 4054 * subclasses of View. 4055 */ 4056 protected ContextMenuInfo getContextMenuInfo() { 4057 return null; 4058 } 4059 4060 /** 4061 * Views should implement this if the view itself is going to add items to 4062 * the context menu. 4063 * 4064 * @param menu the context menu to populate 4065 */ 4066 protected void onCreateContextMenu(ContextMenu menu) { 4067 } 4068 4069 /** 4070 * Implement this method to handle trackball motion events. The 4071 * <em>relative</em> movement of the trackball since the last event 4072 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 4073 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 4074 * that a movement of 1 corresponds to the user pressing one DPAD key (so 4075 * they will often be fractional values, representing the more fine-grained 4076 * movement information available from a trackball). 4077 * 4078 * @param event The motion event. 4079 * @return True if the event was handled, false otherwise. 4080 */ 4081 public boolean onTrackballEvent(MotionEvent event) { 4082 return false; 4083 } 4084 4085 /** 4086 * Implement this method to handle touch screen motion events. 4087 * 4088 * @param event The motion event. 4089 * @return True if the event was handled, false otherwise. 4090 */ 4091 public boolean onTouchEvent(MotionEvent event) { 4092 final int viewFlags = mViewFlags; 4093 4094 if ((viewFlags & ENABLED_MASK) == DISABLED) { 4095 // A disabled view that is clickable still consumes the touch 4096 // events, it just doesn't respond to them. 4097 return (((viewFlags & CLICKABLE) == CLICKABLE || 4098 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 4099 } 4100 4101 if (mTouchDelegate != null) { 4102 if (mTouchDelegate.onTouchEvent(event)) { 4103 return true; 4104 } 4105 } 4106 4107 if (((viewFlags & CLICKABLE) == CLICKABLE || 4108 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 4109 switch (event.getAction()) { 4110 case MotionEvent.ACTION_UP: 4111 if ((mPrivateFlags & PRESSED) != 0) { 4112 // take focus if we don't have it already and we should in 4113 // touch mode. 4114 boolean focusTaken = false; 4115 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 4116 focusTaken = requestFocus(); 4117 } 4118 4119 if (!mHasPerformedLongPress) { 4120 // This is a tap, so remove the longpress check 4121 if (mPendingCheckForLongPress != null) { 4122 removeCallbacks(mPendingCheckForLongPress); 4123 } 4124 4125 // Only perform take click actions if we were in the pressed state 4126 if (!focusTaken) { 4127 performClick(); 4128 } 4129 } 4130 4131 if (mUnsetPressedState == null) { 4132 mUnsetPressedState = new UnsetPressedState(); 4133 } 4134 4135 if (!post(mUnsetPressedState)) { 4136 // If the post failed, unpress right now 4137 mUnsetPressedState.run(); 4138 } 4139 } 4140 break; 4141 4142 case MotionEvent.ACTION_DOWN: 4143 mPrivateFlags |= PRESSED; 4144 refreshDrawableState(); 4145 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 4146 postCheckForLongClick(); 4147 } 4148 break; 4149 4150 case MotionEvent.ACTION_CANCEL: 4151 mPrivateFlags &= ~PRESSED; 4152 refreshDrawableState(); 4153 break; 4154 4155 case MotionEvent.ACTION_MOVE: 4156 final int x = (int) event.getX(); 4157 final int y = (int) event.getY(); 4158 4159 // Be lenient about moving outside of buttons 4160 int slop = ViewConfiguration.get(mContext).getScaledTouchSlop(); 4161 if ((x < 0 - slop) || (x >= getWidth() + slop) || 4162 (y < 0 - slop) || (y >= getHeight() + slop)) { 4163 // Outside button 4164 if ((mPrivateFlags & PRESSED) != 0) { 4165 // Remove any future long press checks 4166 if (mPendingCheckForLongPress != null) { 4167 removeCallbacks(mPendingCheckForLongPress); 4168 } 4169 4170 // Need to switch from pressed to not pressed 4171 mPrivateFlags &= ~PRESSED; 4172 refreshDrawableState(); 4173 } 4174 } else { 4175 // Inside button 4176 if ((mPrivateFlags & PRESSED) == 0) { 4177 // Need to switch from not pressed to pressed 4178 mPrivateFlags |= PRESSED; 4179 refreshDrawableState(); 4180 } 4181 } 4182 break; 4183 } 4184 return true; 4185 } 4186 4187 return false; 4188 } 4189 4190 /** 4191 * Cancels a pending long press. Your subclass can use this if you 4192 * want the context menu to come up if the user presses and holds 4193 * at the same place, but you don't want it to come up if they press 4194 * and then move around enough to cause scrolling. 4195 */ 4196 public void cancelLongPress() { 4197 if (mPendingCheckForLongPress != null) { 4198 removeCallbacks(mPendingCheckForLongPress); 4199 } 4200 } 4201 4202 /** 4203 * Sets the TouchDelegate for this View. 4204 */ 4205 public void setTouchDelegate(TouchDelegate delegate) { 4206 mTouchDelegate = delegate; 4207 } 4208 4209 /** 4210 * Gets the TouchDelegate for this View. 4211 */ 4212 public TouchDelegate getTouchDelegate() { 4213 return mTouchDelegate; 4214 } 4215 4216 /** 4217 * Set flags controlling behavior of this view. 4218 * 4219 * @param flags Constant indicating the value which should be set 4220 * @param mask Constant indicating the bit range that should be changed 4221 */ 4222 void setFlags(int flags, int mask) { 4223 int old = mViewFlags; 4224 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 4225 4226 int changed = mViewFlags ^ old; 4227 if (changed == 0) { 4228 return; 4229 } 4230 int privateFlags = mPrivateFlags; 4231 4232 /* Check if the FOCUSABLE bit has changed */ 4233 if (((changed & FOCUSABLE_MASK) != 0) && 4234 ((privateFlags & HAS_BOUNDS) !=0)) { 4235 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 4236 && ((privateFlags & FOCUSED) != 0)) { 4237 /* Give up focus if we are no longer focusable */ 4238 clearFocus(); 4239 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 4240 && ((privateFlags & FOCUSED) == 0)) { 4241 /* 4242 * Tell the view system that we are now available to take focus 4243 * if no one else already has it. 4244 */ 4245 if (mParent != null) mParent.focusableViewAvailable(this); 4246 } 4247 } 4248 4249 if ((flags & VISIBILITY_MASK) == VISIBLE) { 4250 if ((changed & VISIBILITY_MASK) != 0) { 4251 /* 4252 * If this view is becoming visible, set the DRAWN flag so that 4253 * the next invalidate() will not be skipped. 4254 */ 4255 mPrivateFlags |= DRAWN; 4256 4257 needGlobalAttributesUpdate(true); 4258 4259 // a view becoming visible is worth notifying the parent 4260 // about in case nothing has focus. even if this specific view 4261 // isn't focusable, it may contain something that is, so let 4262 // the root view try to give this focus if nothing else does. 4263 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 4264 mParent.focusableViewAvailable(this); 4265 } 4266 } 4267 } 4268 4269 /* Check if the GONE bit has changed */ 4270 if ((changed & GONE) != 0) { 4271 needGlobalAttributesUpdate(false); 4272 requestLayout(); 4273 invalidate(); 4274 4275 if (((mViewFlags & VISIBILITY_MASK) == GONE) && hasFocus()) { 4276 clearFocus(); 4277 } 4278 if (mAttachInfo != null) { 4279 mAttachInfo.mViewVisibilityChanged = true; 4280 } 4281 } 4282 4283 /* Check if the VISIBLE bit has changed */ 4284 if ((changed & INVISIBLE) != 0) { 4285 needGlobalAttributesUpdate(false); 4286 invalidate(); 4287 4288 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 4289 // root view becoming invisible shouldn't clear focus 4290 if (getRootView() != this) { 4291 clearFocus(); 4292 } 4293 } 4294 if (mAttachInfo != null) { 4295 mAttachInfo.mViewVisibilityChanged = true; 4296 } 4297 } 4298 4299 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 4300 destroyDrawingCache(); 4301 } 4302 4303 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 4304 destroyDrawingCache(); 4305 mPrivateFlags &= ~DRAWING_CACHE_VALID; 4306 } 4307 4308 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 4309 destroyDrawingCache(); 4310 mPrivateFlags &= ~DRAWING_CACHE_VALID; 4311 } 4312 4313 if ((changed & DRAW_MASK) != 0) { 4314 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 4315 if (mBGDrawable != null) { 4316 mPrivateFlags &= ~SKIP_DRAW; 4317 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 4318 } else { 4319 mPrivateFlags |= SKIP_DRAW; 4320 } 4321 } else { 4322 mPrivateFlags &= ~SKIP_DRAW; 4323 } 4324 requestLayout(); 4325 invalidate(); 4326 } 4327 4328 if ((changed & KEEP_SCREEN_ON) != 0) { 4329 if (mParent != null) { 4330 mParent.recomputeViewAttributes(this); 4331 } 4332 } 4333 } 4334 4335 /** 4336 * Change the view's z order in the tree, so it's on top of other sibling 4337 * views 4338 */ 4339 public void bringToFront() { 4340 if (mParent != null) { 4341 mParent.bringChildToFront(this); 4342 } 4343 } 4344 4345 /** 4346 * This is called in response to an internal scroll in this view (i.e., the 4347 * view scrolled its own contents). This is typically as a result of 4348 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 4349 * called. 4350 * 4351 * @param l Current horizontal scroll origin. 4352 * @param t Current vertical scroll origin. 4353 * @param oldl Previous horizontal scroll origin. 4354 * @param oldt Previous vertical scroll origin. 4355 */ 4356 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 4357 mBackgroundSizeChanged = true; 4358 4359 final AttachInfo ai = mAttachInfo; 4360 if (ai != null) { 4361 ai.mViewScrollChanged = true; 4362 } 4363 } 4364 4365 /** 4366 * This is called during layout when the size of this view has changed. If 4367 * you were just added to the view hierarchy, you're called with the old 4368 * values of 0. 4369 * 4370 * @param w Current width of this view. 4371 * @param h Current height of this view. 4372 * @param oldw Old width of this view. 4373 * @param oldh Old height of this view. 4374 */ 4375 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 4376 } 4377 4378 /** 4379 * Called by draw to draw the child views. This may be overridden 4380 * by derived classes to gain control just before its children are drawn 4381 * (but after its own view has been drawn). 4382 * @param canvas the canvas on which to draw the view 4383 */ 4384 protected void dispatchDraw(Canvas canvas) { 4385 } 4386 4387 /** 4388 * Gets the parent of this view. Note that the parent is a 4389 * ViewParent and not necessarily a View. 4390 * 4391 * @return Parent of this view. 4392 */ 4393 public final ViewParent getParent() { 4394 return mParent; 4395 } 4396 4397 /** 4398 * Return the scrolled left position of this view. This is the left edge of 4399 * the displayed part of your view. You do not need to draw any pixels 4400 * farther left, since those are outside of the frame of your view on 4401 * screen. 4402 * 4403 * @return The left edge of the displayed part of your view, in pixels. 4404 */ 4405 public final int getScrollX() { 4406 return mScrollX; 4407 } 4408 4409 /** 4410 * Return the scrolled top position of this view. This is the top edge of 4411 * the displayed part of your view. You do not need to draw any pixels above 4412 * it, since those are outside of the frame of your view on screen. 4413 * 4414 * @return The top edge of the displayed part of your view, in pixels. 4415 */ 4416 public final int getScrollY() { 4417 return mScrollY; 4418 } 4419 4420 /** 4421 * Return the width of the your view. 4422 * 4423 * @return The width of your view, in pixels. 4424 */ 4425 @ViewDebug.ExportedProperty 4426 public final int getWidth() { 4427 return mRight - mLeft; 4428 } 4429 4430 /** 4431 * Return the height of your view. 4432 * 4433 * @return The height of your view, in pixels. 4434 */ 4435 @ViewDebug.ExportedProperty 4436 public final int getHeight() { 4437 return mBottom - mTop; 4438 } 4439 4440 /** 4441 * Return the visible drawing bounds of your view. Fills in the output 4442 * rectangle with the values from getScrollX(), getScrollY(), 4443 * getWidth(), and getHeight(). 4444 * 4445 * @param outRect The (scrolled) drawing bounds of the view. 4446 */ 4447 public void getDrawingRect(Rect outRect) { 4448 outRect.left = mScrollX; 4449 outRect.top = mScrollY; 4450 outRect.right = mScrollX + (mRight - mLeft); 4451 outRect.bottom = mScrollY + (mBottom - mTop); 4452 } 4453 4454 /** 4455 * The width of this view as measured in the most recent call to measure(). 4456 * This should be used during measurement and layout calculations only. Use 4457 * {@link #getWidth()} to see how wide a view is after layout. 4458 * 4459 * @return The measured width of this view. 4460 */ 4461 public final int getMeasuredWidth() { 4462 return mMeasuredWidth; 4463 } 4464 4465 /** 4466 * The height of this view as measured in the most recent call to measure(). 4467 * This should be used during measurement and layout calculations only. Use 4468 * {@link #getHeight()} to see how tall a view is after layout. 4469 * 4470 * @return The measured height of this view. 4471 */ 4472 public final int getMeasuredHeight() { 4473 return mMeasuredHeight; 4474 } 4475 4476 /** 4477 * Top position of this view relative to its parent. 4478 * 4479 * @return The top of this view, in pixels. 4480 */ 4481 @ViewDebug.CapturedViewProperty 4482 public final int getTop() { 4483 return mTop; 4484 } 4485 4486 /** 4487 * Bottom position of this view relative to its parent. 4488 * 4489 * @return The bottom of this view, in pixels. 4490 */ 4491 @ViewDebug.CapturedViewProperty 4492 public final int getBottom() { 4493 return mBottom; 4494 } 4495 4496 /** 4497 * Left position of this view relative to its parent. 4498 * 4499 * @return The left edge of this view, in pixels. 4500 */ 4501 @ViewDebug.CapturedViewProperty 4502 public final int getLeft() { 4503 return mLeft; 4504 } 4505 4506 /** 4507 * Right position of this view relative to its parent. 4508 * 4509 * @return The right edge of this view, in pixels. 4510 */ 4511 @ViewDebug.CapturedViewProperty 4512 public final int getRight() { 4513 return mRight; 4514 } 4515 4516 /** 4517 * Hit rectangle in parent's coordinates 4518 * 4519 * @param outRect The hit rectangle of the view. 4520 */ 4521 public void getHitRect(Rect outRect) { 4522 outRect.set(mLeft, mTop, mRight, mBottom); 4523 } 4524 4525 /** 4526 * When a view has focus and the user navigates away from it, the next view is searched for 4527 * starting from the rectangle filled in by this method. 4528 * 4529 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your 4530 * view maintains some idea of internal selection, such as a cursor, or a selected row 4531 * or column, you should override this method and fill in a more specific rectangle. 4532 * 4533 * @param r The rectangle to fill in, in this view's coordinates. 4534 */ 4535 public void getFocusedRect(Rect r) { 4536 getDrawingRect(r); 4537 } 4538 4539 /** 4540 * If some part of this view is not clipped by any of its parents, then 4541 * return that area in r in global (root) coordinates. To convert r to local 4542 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x, 4543 * -globalOffset.y)) If the view is completely clipped or translated out, 4544 * return false. 4545 * 4546 * @param r If true is returned, r holds the global coordinates of the 4547 * visible portion of this view. 4548 * @param globalOffset If true is returned, globalOffset holds the dx,dy 4549 * between this view and its root. globalOffet may be null. 4550 * @return true if r is non-empty (i.e. part of the view is visible at the 4551 * root level. 4552 */ 4553 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 4554 int width = mRight - mLeft; 4555 int height = mBottom - mTop; 4556 if (width > 0 && height > 0) { 4557 r.set(0, 0, width, height); 4558 if (globalOffset != null) { 4559 globalOffset.set(-mScrollX, -mScrollY); 4560 } 4561 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 4562 } 4563 return false; 4564 } 4565 4566 public final boolean getGlobalVisibleRect(Rect r) { 4567 return getGlobalVisibleRect(r, null); 4568 } 4569 4570 public final boolean getLocalVisibleRect(Rect r) { 4571 Point offset = new Point(); 4572 if (getGlobalVisibleRect(r, offset)) { 4573 r.offset(-offset.x, -offset.y); // make r local 4574 return true; 4575 } 4576 return false; 4577 } 4578 4579 /** 4580 * Offset this view's vertical location by the specified number of pixels. 4581 * 4582 * @param offset the number of pixels to offset the view by 4583 */ 4584 public void offsetTopAndBottom(int offset) { 4585 mTop += offset; 4586 mBottom += offset; 4587 } 4588 4589 /** 4590 * Offset this view's horizontal location by the specified amount of pixels. 4591 * 4592 * @param offset the numer of pixels to offset the view by 4593 */ 4594 public void offsetLeftAndRight(int offset) { 4595 mLeft += offset; 4596 mRight += offset; 4597 } 4598 4599 /** 4600 * Get the LayoutParams associated with this view. All views should have 4601 * layout parameters. These supply parameters to the <i>parent</i> of this 4602 * view specifying how it should be arranged. There are many subclasses of 4603 * ViewGroup.LayoutParams, and these correspond to the different subclasses 4604 * of ViewGroup that are responsible for arranging their children. 4605 * @return The LayoutParams associated with this view 4606 */ 4607 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 4608 public ViewGroup.LayoutParams getLayoutParams() { 4609 return mLayoutParams; 4610 } 4611 4612 /** 4613 * Set the layout parameters associated with this view. These supply 4614 * parameters to the <i>parent</i> of this view specifying how it should be 4615 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 4616 * correspond to the different subclasses of ViewGroup that are responsible 4617 * for arranging their children. 4618 * 4619 * @param params the layout parameters for this view 4620 */ 4621 public void setLayoutParams(ViewGroup.LayoutParams params) { 4622 if (params == null) { 4623 throw new NullPointerException("params == null"); 4624 } 4625 mLayoutParams = params; 4626 requestLayout(); 4627 } 4628 4629 /** 4630 * Set the scrolled position of your view. This will cause a call to 4631 * {@link #onScrollChanged(int, int, int, int)} and the view will be 4632 * invalidated. 4633 * @param x the x position to scroll to 4634 * @param y the y position to scroll to 4635 */ 4636 public void scrollTo(int x, int y) { 4637 if (mScrollX != x || mScrollY != y) { 4638 int oldX = mScrollX; 4639 int oldY = mScrollY; 4640 mScrollX = x; 4641 mScrollY = y; 4642 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 4643 invalidate(); 4644 } 4645 } 4646 4647 /** 4648 * Move the scrolled position of your view. This will cause a call to 4649 * {@link #onScrollChanged(int, int, int, int)} and the view will be 4650 * invalidated. 4651 * @param x the amount of pixels to scroll by horizontally 4652 * @param y the amount of pixels to scroll by vertically 4653 */ 4654 public void scrollBy(int x, int y) { 4655 scrollTo(mScrollX + x, mScrollY + y); 4656 } 4657 4658 /** 4659 * Mark the the area defined by dirty as needing to be drawn. If the view is 4660 * visible, {@link #onDraw} will be called at some point in the future. 4661 * This must be called from a UI thread. To call from a non-UI thread, call 4662 * {@link #postInvalidate()}. 4663 * 4664 * WARNING: This method is destructive to dirty. 4665 * @param dirty the rectangle representing the bounds of the dirty region 4666 */ 4667 public void invalidate(Rect dirty) { 4668 if (ViewDebug.TRACE_HIERARCHY) { 4669 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 4670 } 4671 4672 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) { 4673 mPrivateFlags &= ~DRAWING_CACHE_VALID; 4674 final ViewParent p = mParent; 4675 final AttachInfo ai = mAttachInfo; 4676 if (p != null && ai != null) { 4677 final int scrollX = mScrollX; 4678 final int scrollY = mScrollY; 4679 final Rect r = ai.mTmpInvalRect; 4680 r.set(dirty.left - scrollX, dirty.top - scrollY, 4681 dirty.right - scrollX, dirty.bottom - scrollY); 4682 mParent.invalidateChild(this, r); 4683 } 4684 } 4685 } 4686 4687 /** 4688 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn. 4689 * The coordinates of the dirty rect are relative to the view. 4690 * If the view is visible, {@link #onDraw} will be called at some point 4691 * in the future. This must be called from a UI thread. To call 4692 * from a non-UI thread, call {@link #postInvalidate()}. 4693 * @param l the left position of the dirty region 4694 * @param t the top position of the dirty region 4695 * @param r the right position of the dirty region 4696 * @param b the bottom position of the dirty region 4697 */ 4698 public void invalidate(int l, int t, int r, int b) { 4699 if (ViewDebug.TRACE_HIERARCHY) { 4700 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 4701 } 4702 4703 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) { 4704 mPrivateFlags &= ~DRAWING_CACHE_VALID; 4705 final ViewParent p = mParent; 4706 final AttachInfo ai = mAttachInfo; 4707 if (p != null && ai != null && l < r && t < b) { 4708 final int scrollX = mScrollX; 4709 final int scrollY = mScrollY; 4710 final Rect tmpr = ai.mTmpInvalRect; 4711 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 4712 p.invalidateChild(this, tmpr); 4713 } 4714 } 4715 } 4716 4717 /** 4718 * Invalidate the whole view. If the view is visible, {@link #onDraw} will 4719 * be called at some point in the future. This must be called from a 4720 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 4721 */ 4722 public void invalidate() { 4723 if (ViewDebug.TRACE_HIERARCHY) { 4724 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 4725 } 4726 4727 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) { 4728 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID; 4729 final ViewParent p = mParent; 4730 final AttachInfo ai = mAttachInfo; 4731 if (p != null && ai != null) { 4732 final Rect r = ai.mTmpInvalRect; 4733 r.set(0, 0, mRight - mLeft, mBottom - mTop); 4734 // Don't call invalidate -- we don't want to internally scroll 4735 // our own bounds 4736 p.invalidateChild(this, r); 4737 } 4738 } 4739 } 4740 4741 /** 4742 * Indicates whether this View is opaque. An opaque View guarantees that it will 4743 * draw all the pixels overlapping its bounds using a fully opaque color. 4744 * 4745 * Subclasses of View should override this method whenever possible to indicate 4746 * whether an instance is opaque. Opaque Views are treated in a special way by 4747 * the View hierarchy, possibly allowing it to perform optimizations during 4748 * invalidate/draw passes. 4749 * 4750 * @return True if this View is guaranteed to be fully opaque, false otherwise. 4751 * 4752 * @hide Pending API council approval 4753 */ 4754 @ViewDebug.ExportedProperty 4755 public boolean isOpaque() { 4756 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK; 4757 } 4758 4759 private void computeOpaqueFlags() { 4760 // Opaque if: 4761 // - Has a background 4762 // - Background is opaque 4763 // - Doesn't have scrollbars or scrollbars are inside overlay 4764 4765 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 4766 mPrivateFlags |= OPAQUE_BACKGROUND; 4767 } else { 4768 mPrivateFlags &= ~OPAQUE_BACKGROUND; 4769 } 4770 4771 final int flags = mViewFlags; 4772 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 4773 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 4774 mPrivateFlags |= OPAQUE_SCROLLBARS; 4775 } else { 4776 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 4777 } 4778 } 4779 4780 /** 4781 * @hide 4782 */ 4783 protected boolean hasOpaqueScrollbars() { 4784 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 4785 } 4786 4787 /** 4788 * @return A handler associated with the thread running the View. This 4789 * handler can be used to pump events in the UI events queue. 4790 */ 4791 public Handler getHandler() { 4792 if (mAttachInfo != null) { 4793 return mAttachInfo.mHandler; 4794 } 4795 return null; 4796 } 4797 4798 /** 4799 * Causes the Runnable to be added to the message queue. 4800 * The runnable will be run on the user interface thread. 4801 * 4802 * @param action The Runnable that will be executed. 4803 * 4804 * @return Returns true if the Runnable was successfully placed in to the 4805 * message queue. Returns false on failure, usually because the 4806 * looper processing the message queue is exiting. 4807 */ 4808 public boolean post(Runnable action) { 4809 Handler handler; 4810 if (mAttachInfo != null) { 4811 handler = mAttachInfo.mHandler; 4812 } else { 4813 // Assume that post will succeed later 4814 ViewRoot.getRunQueue().post(action); 4815 return true; 4816 } 4817 4818 return handler.post(action); 4819 } 4820 4821 /** 4822 * Causes the Runnable to be added to the message queue, to be run 4823 * after the specified amount of time elapses. 4824 * The runnable will be run on the user interface thread. 4825 * 4826 * @param action The Runnable that will be executed. 4827 * @param delayMillis The delay (in milliseconds) until the Runnable 4828 * will be executed. 4829 * 4830 * @return true if the Runnable was successfully placed in to the 4831 * message queue. Returns false on failure, usually because the 4832 * looper processing the message queue is exiting. Note that a 4833 * result of true does not mean the Runnable will be processed -- 4834 * if the looper is quit before the delivery time of the message 4835 * occurs then the message will be dropped. 4836 */ 4837 public boolean postDelayed(Runnable action, long delayMillis) { 4838 Handler handler; 4839 if (mAttachInfo != null) { 4840 handler = mAttachInfo.mHandler; 4841 } else { 4842 // Assume that post will succeed later 4843 ViewRoot.getRunQueue().postDelayed(action, delayMillis); 4844 return true; 4845 } 4846 4847 return handler.postDelayed(action, delayMillis); 4848 } 4849 4850 /** 4851 * Removes the specified Runnable from the message queue. 4852 * 4853 * @param action The Runnable to remove from the message handling queue 4854 * 4855 * @return true if this view could ask the Handler to remove the Runnable, 4856 * false otherwise. When the returned value is true, the Runnable 4857 * may or may not have been actually removed from the message queue 4858 * (for instance, if the Runnable was not in the queue already.) 4859 */ 4860 public boolean removeCallbacks(Runnable action) { 4861 Handler handler; 4862 if (mAttachInfo != null) { 4863 handler = mAttachInfo.mHandler; 4864 } else { 4865 // Assume that post will succeed later 4866 ViewRoot.getRunQueue().removeCallbacks(action); 4867 return true; 4868 } 4869 4870 handler.removeCallbacks(action); 4871 return true; 4872 } 4873 4874 /** 4875 * Cause an invalidate to happen on a subsequent cycle through the event loop. 4876 * Use this to invalidate the View from a non-UI thread. 4877 * 4878 * @see #invalidate() 4879 */ 4880 public void postInvalidate() { 4881 postInvalidateDelayed(0); 4882 } 4883 4884 /** 4885 * Cause an invalidate of the specified area to happen on a subsequent cycle 4886 * through the event loop. Use this to invalidate the View from a non-UI thread. 4887 * 4888 * @param left The left coordinate of the rectangle to invalidate. 4889 * @param top The top coordinate of the rectangle to invalidate. 4890 * @param right The right coordinate of the rectangle to invalidate. 4891 * @param bottom The bottom coordinate of the rectangle to invalidate. 4892 * 4893 * @see #invalidate(int, int, int, int) 4894 * @see #invalidate(Rect) 4895 */ 4896 public void postInvalidate(int left, int top, int right, int bottom) { 4897 postInvalidateDelayed(0, left, top, right, bottom); 4898 } 4899 4900 /** 4901 * Cause an invalidate to happen on a subsequent cycle through the event 4902 * loop. Waits for the specified amount of time. 4903 * 4904 * @param delayMilliseconds the duration in milliseconds to delay the 4905 * invalidation by 4906 */ 4907 public void postInvalidateDelayed(long delayMilliseconds) { 4908 // We try only with the AttachInfo because there's no point in invalidating 4909 // if we are not attached to our window 4910 if (mAttachInfo != null) { 4911 Message msg = Message.obtain(); 4912 msg.what = AttachInfo.INVALIDATE_MSG; 4913 msg.obj = this; 4914 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 4915 } 4916 } 4917 4918 /** 4919 * Cause an invalidate of the specified area to happen on a subsequent cycle 4920 * through the event loop. Waits for the specified amount of time. 4921 * 4922 * @param delayMilliseconds the duration in milliseconds to delay the 4923 * invalidation by 4924 * @param left The left coordinate of the rectangle to invalidate. 4925 * @param top The top coordinate of the rectangle to invalidate. 4926 * @param right The right coordinate of the rectangle to invalidate. 4927 * @param bottom The bottom coordinate of the rectangle to invalidate. 4928 */ 4929 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 4930 int right, int bottom) { 4931 4932 // We try only with the AttachInfo because there's no point in invalidating 4933 // if we are not attached to our window 4934 if (mAttachInfo != null) { 4935 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 4936 info.target = this; 4937 info.left = left; 4938 info.top = top; 4939 info.right = right; 4940 info.bottom = bottom; 4941 4942 final Message msg = Message.obtain(); 4943 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 4944 msg.obj = info; 4945 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 4946 } 4947 } 4948 4949 /** 4950 * Called by a parent to request that a child update its values for mScrollX 4951 * and mScrollY if necessary. This will typically be done if the child is 4952 * animating a scroll using a {@link android.widget.Scroller Scroller} 4953 * object. 4954 */ 4955 public void computeScroll() { 4956 } 4957 4958 /** 4959 * <p>Indicate whether the horizontal edges are faded when the view is 4960 * scrolled horizontally.</p> 4961 * 4962 * @return true if the horizontal edges should are faded on scroll, false 4963 * otherwise 4964 * 4965 * @see #setHorizontalFadingEdgeEnabled(boolean) 4966 * @attr ref android.R.styleable#View_fadingEdge 4967 */ 4968 public boolean isHorizontalFadingEdgeEnabled() { 4969 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 4970 } 4971 4972 /** 4973 * <p>Define whether the horizontal edges should be faded when this view 4974 * is scrolled horizontally.</p> 4975 * 4976 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 4977 * be faded when the view is scrolled 4978 * horizontally 4979 * 4980 * @see #isHorizontalFadingEdgeEnabled() 4981 * @attr ref android.R.styleable#View_fadingEdge 4982 */ 4983 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 4984 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 4985 if (horizontalFadingEdgeEnabled) { 4986 initScrollCache(); 4987 } 4988 4989 mViewFlags ^= FADING_EDGE_HORIZONTAL; 4990 } 4991 } 4992 4993 /** 4994 * <p>Indicate whether the vertical edges are faded when the view is 4995 * scrolled horizontally.</p> 4996 * 4997 * @return true if the vertical edges should are faded on scroll, false 4998 * otherwise 4999 * 5000 * @see #setVerticalFadingEdgeEnabled(boolean) 5001 * @attr ref android.R.styleable#View_fadingEdge 5002 */ 5003 public boolean isVerticalFadingEdgeEnabled() { 5004 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 5005 } 5006 5007 /** 5008 * <p>Define whether the vertical edges should be faded when this view 5009 * is scrolled vertically.</p> 5010 * 5011 * @param verticalFadingEdgeEnabled true if the vertical edges should 5012 * be faded when the view is scrolled 5013 * vertically 5014 * 5015 * @see #isVerticalFadingEdgeEnabled() 5016 * @attr ref android.R.styleable#View_fadingEdge 5017 */ 5018 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 5019 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 5020 if (verticalFadingEdgeEnabled) { 5021 initScrollCache(); 5022 } 5023 5024 mViewFlags ^= FADING_EDGE_VERTICAL; 5025 } 5026 } 5027 5028 /** 5029 * Returns the strength, or intensity, of the top faded edge. The strength is 5030 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 5031 * returns 0.0 or 1.0 but no value in between. 5032 * 5033 * Subclasses should override this method to provide a smoother fade transition 5034 * when scrolling occurs. 5035 * 5036 * @return the intensity of the top fade as a float between 0.0f and 1.0f 5037 */ 5038 protected float getTopFadingEdgeStrength() { 5039 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 5040 } 5041 5042 /** 5043 * Returns the strength, or intensity, of the bottom faded edge. The strength is 5044 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 5045 * returns 0.0 or 1.0 but no value in between. 5046 * 5047 * Subclasses should override this method to provide a smoother fade transition 5048 * when scrolling occurs. 5049 * 5050 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 5051 */ 5052 protected float getBottomFadingEdgeStrength() { 5053 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 5054 computeVerticalScrollRange() ? 1.0f : 0.0f; 5055 } 5056 5057 /** 5058 * Returns the strength, or intensity, of the left faded edge. The strength is 5059 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 5060 * returns 0.0 or 1.0 but no value in between. 5061 * 5062 * Subclasses should override this method to provide a smoother fade transition 5063 * when scrolling occurs. 5064 * 5065 * @return the intensity of the left fade as a float between 0.0f and 1.0f 5066 */ 5067 protected float getLeftFadingEdgeStrength() { 5068 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 5069 } 5070 5071 /** 5072 * Returns the strength, or intensity, of the right faded edge. The strength is 5073 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 5074 * returns 0.0 or 1.0 but no value in between. 5075 * 5076 * Subclasses should override this method to provide a smoother fade transition 5077 * when scrolling occurs. 5078 * 5079 * @return the intensity of the right fade as a float between 0.0f and 1.0f 5080 */ 5081 protected float getRightFadingEdgeStrength() { 5082 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 5083 computeHorizontalScrollRange() ? 1.0f : 0.0f; 5084 } 5085 5086 /** 5087 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 5088 * scrollbar is not drawn by default.</p> 5089 * 5090 * @return true if the horizontal scrollbar should be painted, false 5091 * otherwise 5092 * 5093 * @see #setHorizontalScrollBarEnabled(boolean) 5094 */ 5095 public boolean isHorizontalScrollBarEnabled() { 5096 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 5097 } 5098 5099 /** 5100 * <p>Define whether the horizontal scrollbar should be drawn or not. The 5101 * scrollbar is not drawn by default.</p> 5102 * 5103 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 5104 * be painted 5105 * 5106 * @see #isHorizontalScrollBarEnabled() 5107 */ 5108 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 5109 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 5110 mViewFlags ^= SCROLLBARS_HORIZONTAL; 5111 computeOpaqueFlags(); 5112 recomputePadding(); 5113 } 5114 } 5115 5116 /** 5117 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 5118 * scrollbar is not drawn by default.</p> 5119 * 5120 * @return true if the vertical scrollbar should be painted, false 5121 * otherwise 5122 * 5123 * @see #setVerticalScrollBarEnabled(boolean) 5124 */ 5125 public boolean isVerticalScrollBarEnabled() { 5126 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 5127 } 5128 5129 /** 5130 * <p>Define whether the vertical scrollbar should be drawn or not. The 5131 * scrollbar is not drawn by default.</p> 5132 * 5133 * @param verticalScrollBarEnabled true if the vertical scrollbar should 5134 * be painted 5135 * 5136 * @see #isVerticalScrollBarEnabled() 5137 */ 5138 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 5139 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 5140 mViewFlags ^= SCROLLBARS_VERTICAL; 5141 computeOpaqueFlags(); 5142 recomputePadding(); 5143 } 5144 } 5145 5146 private void recomputePadding() { 5147 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 5148 } 5149 5150 /** 5151 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 5152 * inset. When inset, they add to the padding of the view. And the scrollbars 5153 * can be drawn inside the padding area or on the edge of the view. For example, 5154 * if a view has a background drawable and you want to draw the scrollbars 5155 * inside the padding specified by the drawable, you can use 5156 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 5157 * appear at the edge of the view, ignoring the padding, then you can use 5158 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 5159 * @param style the style of the scrollbars. Should be one of 5160 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 5161 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 5162 * @see #SCROLLBARS_INSIDE_OVERLAY 5163 * @see #SCROLLBARS_INSIDE_INSET 5164 * @see #SCROLLBARS_OUTSIDE_OVERLAY 5165 * @see #SCROLLBARS_OUTSIDE_INSET 5166 */ 5167 public void setScrollBarStyle(int style) { 5168 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 5169 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 5170 computeOpaqueFlags(); 5171 recomputePadding(); 5172 } 5173 } 5174 5175 /** 5176 * <p>Returns the current scrollbar style.</p> 5177 * @return the current scrollbar style 5178 * @see #SCROLLBARS_INSIDE_OVERLAY 5179 * @see #SCROLLBARS_INSIDE_INSET 5180 * @see #SCROLLBARS_OUTSIDE_OVERLAY 5181 * @see #SCROLLBARS_OUTSIDE_INSET 5182 */ 5183 public int getScrollBarStyle() { 5184 return mViewFlags & SCROLLBARS_STYLE_MASK; 5185 } 5186 5187 /** 5188 * <p>Compute the horizontal range that the horizontal scrollbar 5189 * represents.</p> 5190 * 5191 * <p>The range is expressed in arbitrary units that must be the same as the 5192 * units used by {@link #computeHorizontalScrollExtent()} and 5193 * {@link #computeHorizontalScrollOffset()}.</p> 5194 * 5195 * <p>The default range is the drawing width of this view.</p> 5196 * 5197 * @return the total horizontal range represented by the horizontal 5198 * scrollbar 5199 * 5200 * @see #computeHorizontalScrollExtent() 5201 * @see #computeHorizontalScrollOffset() 5202 * @see android.widget.ScrollBarDrawable 5203 */ 5204 protected int computeHorizontalScrollRange() { 5205 return getWidth(); 5206 } 5207 5208 /** 5209 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 5210 * within the horizontal range. This value is used to compute the position 5211 * of the thumb within the scrollbar's track.</p> 5212 * 5213 * <p>The range is expressed in arbitrary units that must be the same as the 5214 * units used by {@link #computeHorizontalScrollRange()} and 5215 * {@link #computeHorizontalScrollExtent()}.</p> 5216 * 5217 * <p>The default offset is the scroll offset of this view.</p> 5218 * 5219 * @return the horizontal offset of the scrollbar's thumb 5220 * 5221 * @see #computeHorizontalScrollRange() 5222 * @see #computeHorizontalScrollExtent() 5223 * @see android.widget.ScrollBarDrawable 5224 */ 5225 protected int computeHorizontalScrollOffset() { 5226 return mScrollX; 5227 } 5228 5229 /** 5230 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 5231 * within the horizontal range. This value is used to compute the length 5232 * of the thumb within the scrollbar's track.</p> 5233 * 5234 * <p>The range is expressed in arbitrary units that must be the same as the 5235 * units used by {@link #computeHorizontalScrollRange()} and 5236 * {@link #computeHorizontalScrollOffset()}.</p> 5237 * 5238 * <p>The default extent is the drawing width of this view.</p> 5239 * 5240 * @return the horizontal extent of the scrollbar's thumb 5241 * 5242 * @see #computeHorizontalScrollRange() 5243 * @see #computeHorizontalScrollOffset() 5244 * @see android.widget.ScrollBarDrawable 5245 */ 5246 protected int computeHorizontalScrollExtent() { 5247 return getWidth(); 5248 } 5249 5250 /** 5251 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 5252 * 5253 * <p>The range is expressed in arbitrary units that must be the same as the 5254 * units used by {@link #computeVerticalScrollExtent()} and 5255 * {@link #computeVerticalScrollOffset()}.</p> 5256 * 5257 * @return the total vertical range represented by the vertical scrollbar 5258 * 5259 * <p>The default range is the drawing height of this view.</p> 5260 * 5261 * @see #computeVerticalScrollExtent() 5262 * @see #computeVerticalScrollOffset() 5263 * @see android.widget.ScrollBarDrawable 5264 */ 5265 protected int computeVerticalScrollRange() { 5266 return getHeight(); 5267 } 5268 5269 /** 5270 * <p>Compute the vertical offset of the vertical scrollbar's thumb 5271 * within the horizontal range. This value is used to compute the position 5272 * of the thumb within the scrollbar's track.</p> 5273 * 5274 * <p>The range is expressed in arbitrary units that must be the same as the 5275 * units used by {@link #computeVerticalScrollRange()} and 5276 * {@link #computeVerticalScrollExtent()}.</p> 5277 * 5278 * <p>The default offset is the scroll offset of this view.</p> 5279 * 5280 * @return the vertical offset of the scrollbar's thumb 5281 * 5282 * @see #computeVerticalScrollRange() 5283 * @see #computeVerticalScrollExtent() 5284 * @see android.widget.ScrollBarDrawable 5285 */ 5286 protected int computeVerticalScrollOffset() { 5287 return mScrollY; 5288 } 5289 5290 /** 5291 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 5292 * within the vertical range. This value is used to compute the length 5293 * of the thumb within the scrollbar's track.</p> 5294 * 5295 * <p>The range is expressed in arbitrary units that must be the same as the 5296 * units used by {@link #computeHorizontalScrollRange()} and 5297 * {@link #computeVerticalScrollOffset()}.</p> 5298 * 5299 * <p>The default extent is the drawing height of this view.</p> 5300 * 5301 * @return the vertical extent of the scrollbar's thumb 5302 * 5303 * @see #computeVerticalScrollRange() 5304 * @see #computeVerticalScrollOffset() 5305 * @see android.widget.ScrollBarDrawable 5306 */ 5307 protected int computeVerticalScrollExtent() { 5308 return getHeight(); 5309 } 5310 5311 /** 5312 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 5313 * scrollbars are painted only if they have been awakened first.</p> 5314 * 5315 * @param canvas the canvas on which to draw the scrollbars 5316 */ 5317 private void onDrawScrollBars(Canvas canvas) { 5318 // scrollbars are drawn only when the animation is running 5319 final ScrollabilityCache cache = mScrollCache; 5320 if (cache != null) { 5321 final int viewFlags = mViewFlags; 5322 5323 final boolean drawHorizontalScrollBar = 5324 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 5325 final boolean drawVerticalScrollBar = 5326 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 5327 && !isVerticalScrollBarHidden(); 5328 5329 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 5330 final int width = mRight - mLeft; 5331 final int height = mBottom - mTop; 5332 5333 final ScrollBarDrawable scrollBar = cache.scrollBar; 5334 int size = scrollBar.getSize(false); 5335 if (size <= 0) { 5336 size = cache.scrollBarSize; 5337 } 5338 5339 if (drawHorizontalScrollBar) { 5340 onDrawHorizontalScrollBar(canvas, scrollBar, width, height, size); 5341 } 5342 5343 if (drawVerticalScrollBar) { 5344 onDrawVerticalScrollBar(canvas, scrollBar, width, height, size); 5345 } 5346 } 5347 } 5348 } 5349 5350 /** 5351 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 5352 * FastScroller is visible. 5353 * @return whether to temporarily hide the vertical scrollbar 5354 * @hide 5355 */ 5356 protected boolean isVerticalScrollBarHidden() { 5357 return false; 5358 } 5359 5360 /** 5361 * <p>Draw the horizontal scrollbar if 5362 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 5363 * 5364 * <p>The length of the scrollbar and its thumb is computed according to the 5365 * values returned by {@link #computeHorizontalScrollRange()}, 5366 * {@link #computeHorizontalScrollExtent()} and 5367 * {@link #computeHorizontalScrollOffset()}. Refer to 5368 * {@link android.widget.ScrollBarDrawable} for more information about how 5369 * these values relate to each other.</p> 5370 * 5371 * @param canvas the canvas on which to draw the scrollbar 5372 * @param scrollBar the scrollbar's drawable 5373 * @param width the width of the drawing surface 5374 * @param height the height of the drawing surface 5375 * @param size the size of the scrollbar 5376 * 5377 * @see #isHorizontalScrollBarEnabled() 5378 * @see #computeHorizontalScrollRange() 5379 * @see #computeHorizontalScrollExtent() 5380 * @see #computeHorizontalScrollOffset() 5381 * @see android.widget.ScrollBarDrawable 5382 */ 5383 private void onDrawHorizontalScrollBar(Canvas canvas, ScrollBarDrawable scrollBar, int width, 5384 int height, int size) { 5385 5386 final int viewFlags = mViewFlags; 5387 final int scrollX = mScrollX; 5388 final int scrollY = mScrollY; 5389 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 5390 final int top = scrollY + height - size - (mUserPaddingBottom & inside); 5391 5392 final int verticalScrollBarGap = 5393 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL ? 5394 getVerticalScrollbarWidth() : 0; 5395 5396 scrollBar.setBounds(scrollX + (mPaddingLeft & inside), top, 5397 scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap, top + size); 5398 scrollBar.setParameters( 5399 computeHorizontalScrollRange(), 5400 computeHorizontalScrollOffset(), 5401 computeHorizontalScrollExtent(), false); 5402 scrollBar.draw(canvas); 5403 } 5404 5405 /** 5406 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 5407 * returns true.</p> 5408 * 5409 * <p>The length of the scrollbar and its thumb is computed according to the 5410 * values returned by {@link #computeVerticalScrollRange()}, 5411 * {@link #computeVerticalScrollExtent()} and 5412 * {@link #computeVerticalScrollOffset()}. Refer to 5413 * {@link android.widget.ScrollBarDrawable} for more information about how 5414 * these values relate to each other.</p> 5415 * 5416 * @param canvas the canvas on which to draw the scrollbar 5417 * @param scrollBar the scrollbar's drawable 5418 * @param width the width of the drawing surface 5419 * @param height the height of the drawing surface 5420 * @param size the size of the scrollbar 5421 * 5422 * @see #isVerticalScrollBarEnabled() 5423 * @see #computeVerticalScrollRange() 5424 * @see #computeVerticalScrollExtent() 5425 * @see #computeVerticalScrollOffset() 5426 * @see android.widget.ScrollBarDrawable 5427 */ 5428 private void onDrawVerticalScrollBar(Canvas canvas, ScrollBarDrawable scrollBar, int width, 5429 int height, int size) { 5430 5431 final int scrollX = mScrollX; 5432 final int scrollY = mScrollY; 5433 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 5434 // TODO: Deal with RTL languages to position scrollbar on left 5435 final int left = scrollX + width - size - (mUserPaddingRight & inside); 5436 5437 scrollBar.setBounds(left, scrollY + (mPaddingTop & inside), 5438 left + size, scrollY + height - (mUserPaddingBottom & inside)); 5439 scrollBar.setParameters( 5440 computeVerticalScrollRange(), 5441 computeVerticalScrollOffset(), 5442 computeVerticalScrollExtent(), true); 5443 scrollBar.draw(canvas); 5444 } 5445 5446 /** 5447 * Implement this to do your drawing. 5448 * 5449 * @param canvas the canvas on which the background will be drawn 5450 */ 5451 protected void onDraw(Canvas canvas) { 5452 } 5453 5454 /* 5455 * Caller is responsible for calling requestLayout if necessary. 5456 * (This allows addViewInLayout to not request a new layout.) 5457 */ 5458 void assignParent(ViewParent parent) { 5459 if (mParent == null) { 5460 mParent = parent; 5461 } else if (parent == null) { 5462 mParent = null; 5463 } else { 5464 throw new RuntimeException("view " + this + " being added, but" 5465 + " it already has a parent"); 5466 } 5467 } 5468 5469 /** 5470 * This is called when the view is attached to a window. At this point it 5471 * has a Surface and will start drawing. Note that this function is 5472 * guaranteed to be called before {@link #onDraw}, however it may be called 5473 * any time before the first onDraw -- including before or after 5474 * {@link #onMeasure}. 5475 * 5476 * @see #onDetachedFromWindow() 5477 */ 5478 protected void onAttachedToWindow() { 5479 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 5480 mParent.requestTransparentRegion(this); 5481 } 5482 } 5483 5484 /** 5485 * This is called when the view is detached from a window. At this point it 5486 * no longer has a surface for drawing. 5487 * 5488 * @see #onAttachedToWindow() 5489 */ 5490 protected void onDetachedFromWindow() { 5491 if (mPendingCheckForLongPress != null) { 5492 removeCallbacks(mPendingCheckForLongPress); 5493 } 5494 destroyDrawingCache(); 5495 } 5496 5497 /** 5498 * @return The number of times this view has been attached to a window 5499 */ 5500 protected int getWindowAttachCount() { 5501 return mWindowAttachCount; 5502 } 5503 5504 /** 5505 * Retrieve a unique token identifying the window this view is attached to. 5506 * @return Return the window's token for use in 5507 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 5508 */ 5509 public IBinder getWindowToken() { 5510 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 5511 } 5512 5513 /** 5514 * Retrieve a unique token identifying the top-level "real" window of 5515 * the window that this view is attached to. That is, this is like 5516 * {@link #getWindowToken}, except if the window this view in is a panel 5517 * window (attached to another containing window), then the token of 5518 * the containing window is returned instead. 5519 * 5520 * @return Returns the associated window token, either 5521 * {@link #getWindowToken()} or the containing window's token. 5522 */ 5523 public IBinder getApplicationWindowToken() { 5524 AttachInfo ai = mAttachInfo; 5525 if (ai != null) { 5526 IBinder appWindowToken = ai.mPanelParentWindowToken; 5527 if (appWindowToken == null) { 5528 appWindowToken = ai.mWindowToken; 5529 } 5530 return appWindowToken; 5531 } 5532 return null; 5533 } 5534 5535 /** 5536 * Retrieve private session object this view hierarchy is using to 5537 * communicate with the window manager. 5538 * @return the session object to communicate with the window manager 5539 */ 5540 /*package*/ IWindowSession getWindowSession() { 5541 return mAttachInfo != null ? mAttachInfo.mSession : null; 5542 } 5543 5544 /** 5545 * @param info the {@link android.view.View.AttachInfo} to associated with 5546 * this view 5547 */ 5548 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 5549 //System.out.println("Attached! " + this); 5550 mAttachInfo = info; 5551 mWindowAttachCount++; 5552 if (mFloatingTreeObserver != null) { 5553 info.mTreeObserver.merge(mFloatingTreeObserver); 5554 mFloatingTreeObserver = null; 5555 } 5556 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 5557 mAttachInfo.mScrollContainers.add(this); 5558 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 5559 } 5560 performCollectViewAttributes(visibility); 5561 onAttachedToWindow(); 5562 int vis = info.mWindowVisibility; 5563 if (vis != GONE) { 5564 onWindowVisibilityChanged(vis); 5565 } 5566 } 5567 5568 void dispatchDetachedFromWindow() { 5569 //System.out.println("Detached! " + this); 5570 AttachInfo info = mAttachInfo; 5571 if (info != null) { 5572 int vis = info.mWindowVisibility; 5573 if (vis != GONE) { 5574 onWindowVisibilityChanged(GONE); 5575 } 5576 } 5577 5578 onDetachedFromWindow(); 5579 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 5580 mAttachInfo.mScrollContainers.remove(this); 5581 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 5582 } 5583 mAttachInfo = null; 5584 } 5585 5586 /** 5587 * Store this view hierarchy's frozen state into the given container. 5588 * 5589 * @param container The SparseArray in which to save the view's state. 5590 * 5591 * @see #restoreHierarchyState 5592 * @see #dispatchSaveInstanceState 5593 * @see #onSaveInstanceState 5594 */ 5595 public void saveHierarchyState(SparseArray<Parcelable> container) { 5596 dispatchSaveInstanceState(container); 5597 } 5598 5599 /** 5600 * Called by {@link #saveHierarchyState} to store the state for this view and its children. 5601 * May be overridden to modify how freezing happens to a view's children; for example, some 5602 * views may want to not store state for their children. 5603 * 5604 * @param container The SparseArray in which to save the view's state. 5605 * 5606 * @see #dispatchRestoreInstanceState 5607 * @see #saveHierarchyState 5608 * @see #onSaveInstanceState 5609 */ 5610 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 5611 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 5612 mPrivateFlags &= ~SAVE_STATE_CALLED; 5613 Parcelable state = onSaveInstanceState(); 5614 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 5615 throw new IllegalStateException( 5616 "Derived class did not call super.onSaveInstanceState()"); 5617 } 5618 if (state != null) { 5619 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 5620 // + ": " + state); 5621 container.put(mID, state); 5622 } 5623 } 5624 } 5625 5626 /** 5627 * Hook allowing a view to generate a representation of its internal state 5628 * that can later be used to create a new instance with that same state. 5629 * This state should only contain information that is not persistent or can 5630 * not be reconstructed later. For example, you will never store your 5631 * current position on screen because that will be computed again when a 5632 * new instance of the view is placed in its view hierarchy. 5633 * <p> 5634 * Some examples of things you may store here: the current cursor position 5635 * in a text view (but usually not the text itself since that is stored in a 5636 * content provider or other persistent storage), the currently selected 5637 * item in a list view. 5638 * 5639 * @return Returns a Parcelable object containing the view's current dynamic 5640 * state, or null if there is nothing interesting to save. The 5641 * default implementation returns null. 5642 * @see #onRestoreInstanceState 5643 * @see #saveHierarchyState 5644 * @see #dispatchSaveInstanceState 5645 * @see #setSaveEnabled(boolean) 5646 */ 5647 protected Parcelable onSaveInstanceState() { 5648 mPrivateFlags |= SAVE_STATE_CALLED; 5649 return BaseSavedState.EMPTY_STATE; 5650 } 5651 5652 /** 5653 * Restore this view hierarchy's frozen state from the given container. 5654 * 5655 * @param container The SparseArray which holds previously frozen states. 5656 * 5657 * @see #saveHierarchyState 5658 * @see #dispatchRestoreInstanceState 5659 * @see #onRestoreInstanceState 5660 */ 5661 public void restoreHierarchyState(SparseArray<Parcelable> container) { 5662 dispatchRestoreInstanceState(container); 5663 } 5664 5665 /** 5666 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its 5667 * children. May be overridden to modify how restoreing happens to a view's children; for 5668 * example, some views may want to not store state for their children. 5669 * 5670 * @param container The SparseArray which holds previously saved state. 5671 * 5672 * @see #dispatchSaveInstanceState 5673 * @see #restoreHierarchyState 5674 * @see #onRestoreInstanceState 5675 */ 5676 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 5677 if (mID != NO_ID) { 5678 Parcelable state = container.get(mID); 5679 if (state != null) { 5680 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 5681 // + ": " + state); 5682 mPrivateFlags &= ~SAVE_STATE_CALLED; 5683 onRestoreInstanceState(state); 5684 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 5685 throw new IllegalStateException( 5686 "Derived class did not call super.onRestoreInstanceState()"); 5687 } 5688 } 5689 } 5690 } 5691 5692 /** 5693 * Hook allowing a view to re-apply a representation of its internal state that had previously 5694 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 5695 * null state. 5696 * 5697 * @param state The frozen state that had previously been returned by 5698 * {@link #onSaveInstanceState}. 5699 * 5700 * @see #onSaveInstanceState 5701 * @see #restoreHierarchyState 5702 * @see #dispatchRestoreInstanceState 5703 */ 5704 protected void onRestoreInstanceState(Parcelable state) { 5705 mPrivateFlags |= SAVE_STATE_CALLED; 5706 if (state != BaseSavedState.EMPTY_STATE && state != null) { 5707 throw new IllegalArgumentException("Wrong state class -- expecting View State"); 5708 } 5709 } 5710 5711 /** 5712 * <p>Return the time at which the drawing of the view hierarchy started.</p> 5713 * 5714 * @return the drawing start time in milliseconds 5715 */ 5716 public long getDrawingTime() { 5717 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 5718 } 5719 5720 /** 5721 * <p>Enables or disables the duplication of the parent's state into this view. When 5722 * duplication is enabled, this view gets its drawable state from its parent rather 5723 * than from its own internal properties.</p> 5724 * 5725 * <p>Note: in the current implementation, setting this property to true after the 5726 * view was added to a ViewGroup might have no effect at all. This property should 5727 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 5728 * 5729 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 5730 * property is enabled, an exception will be thrown.</p> 5731 * 5732 * @param enabled True to enable duplication of the parent's drawable state, false 5733 * to disable it. 5734 * 5735 * @see #getDrawableState() 5736 * @see #isDuplicateParentStateEnabled() 5737 */ 5738 public void setDuplicateParentStateEnabled(boolean enabled) { 5739 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 5740 } 5741 5742 /** 5743 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 5744 * 5745 * @return True if this view's drawable state is duplicated from the parent, 5746 * false otherwise 5747 * 5748 * @see #getDrawableState() 5749 * @see #setDuplicateParentStateEnabled(boolean) 5750 */ 5751 public boolean isDuplicateParentStateEnabled() { 5752 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 5753 } 5754 5755 /** 5756 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 5757 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 5758 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 5759 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 5760 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 5761 * null.</p> 5762 * 5763 * @param enabled true to enable the drawing cache, false otherwise 5764 * 5765 * @see #isDrawingCacheEnabled() 5766 * @see #getDrawingCache() 5767 * @see #buildDrawingCache() 5768 */ 5769 public void setDrawingCacheEnabled(boolean enabled) { 5770 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 5771 } 5772 5773 /** 5774 * <p>Indicates whether the drawing cache is enabled for this view.</p> 5775 * 5776 * @return true if the drawing cache is enabled 5777 * 5778 * @see #setDrawingCacheEnabled(boolean) 5779 * @see #getDrawingCache() 5780 */ 5781 @ViewDebug.ExportedProperty 5782 public boolean isDrawingCacheEnabled() { 5783 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 5784 } 5785 5786 /** 5787 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 5788 * 5789 * @return A non-scaled bitmap representing this view or null if cache is disabled. 5790 * 5791 * @see #getDrawingCache(boolean) 5792 */ 5793 public Bitmap getDrawingCache() { 5794 return getDrawingCache(false); 5795 } 5796 5797 /** 5798 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 5799 * is null when caching is disabled. If caching is enabled and the cache is not ready, 5800 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 5801 * draw from the cache when the cache is enabled. To benefit from the cache, you must 5802 * request the drawing cache by calling this method and draw it on screen if the 5803 * returned bitmap is not null.</p> 5804 * 5805 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 5806 * this method will create a bitmap of the same size as this view. Because this bitmap 5807 * will be drawn scaled by the parent ViewGroup, the result on screen might show 5808 * scaling artifacts. To avoid such artifacts, you should call this method by setting 5809 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 5810 * size than the view. This implies that your application must be able to handle this 5811 * size.</p> 5812 * 5813 * @param autoScale Indicates whether the generated bitmap should be scaled based on 5814 * the current density of the screen when the application is in compatibility 5815 * mode. 5816 * 5817 * @return A bitmap representing this view or null if cache is disabled. 5818 * 5819 * @see #setDrawingCacheEnabled(boolean) 5820 * @see #isDrawingCacheEnabled() 5821 * @see #buildDrawingCache(boolean) 5822 * @see #destroyDrawingCache() 5823 */ 5824 public Bitmap getDrawingCache(boolean autoScale) { 5825 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 5826 return null; 5827 } 5828 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 5829 buildDrawingCache(autoScale); 5830 } 5831 return autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) : 5832 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get()); 5833 } 5834 5835 /** 5836 * <p>Frees the resources used by the drawing cache. If you call 5837 * {@link #buildDrawingCache()} manually without calling 5838 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 5839 * should cleanup the cache with this method afterwards.</p> 5840 * 5841 * @see #setDrawingCacheEnabled(boolean) 5842 * @see #buildDrawingCache() 5843 * @see #getDrawingCache() 5844 */ 5845 public void destroyDrawingCache() { 5846 if (mDrawingCache != null) { 5847 final Bitmap bitmap = mDrawingCache.get(); 5848 if (bitmap != null) bitmap.recycle(); 5849 mDrawingCache = null; 5850 } 5851 if (mUnscaledDrawingCache != null) { 5852 final Bitmap bitmap = mUnscaledDrawingCache.get(); 5853 if (bitmap != null) bitmap.recycle(); 5854 mUnscaledDrawingCache = null; 5855 } 5856 } 5857 5858 /** 5859 * Setting a solid background color for the drawing cache's bitmaps will improve 5860 * perfromance and memory usage. Note, though that this should only be used if this 5861 * view will always be drawn on top of a solid color. 5862 * 5863 * @param color The background color to use for the drawing cache's bitmap 5864 * 5865 * @see #setDrawingCacheEnabled(boolean) 5866 * @see #buildDrawingCache() 5867 * @see #getDrawingCache() 5868 */ 5869 public void setDrawingCacheBackgroundColor(int color) { 5870 mDrawingCacheBackgroundColor = color; 5871 } 5872 5873 /** 5874 * @see #setDrawingCacheBackgroundColor(int) 5875 * 5876 * @return The background color to used for the drawing cache's bitmap 5877 */ 5878 public int getDrawingCacheBackgroundColor() { 5879 return mDrawingCacheBackgroundColor; 5880 } 5881 5882 /** 5883 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 5884 * 5885 * @see #buildDrawingCache(boolean) 5886 */ 5887 public void buildDrawingCache() { 5888 buildDrawingCache(false); 5889 } 5890 5891 /** 5892 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 5893 * 5894 * <p>If you call {@link #buildDrawingCache()} manually without calling 5895 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 5896 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 5897 * 5898 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 5899 * this method will create a bitmap of the same size as this view. Because this bitmap 5900 * will be drawn scaled by the parent ViewGroup, the result on screen might show 5901 * scaling artifacts. To avoid such artifacts, you should call this method by setting 5902 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 5903 * size than the view. This implies that your application must be able to handle this 5904 * size.</p> 5905 * 5906 * @see #getDrawingCache() 5907 * @see #destroyDrawingCache() 5908 */ 5909 public void buildDrawingCache(boolean autoScale) { 5910 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 5911 (mDrawingCache == null || mDrawingCache.get() == null) : 5912 (mUnscaledDrawingCache == null || mUnscaledDrawingCache.get() == null))) { 5913 5914 if (ViewDebug.TRACE_HIERARCHY) { 5915 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 5916 } 5917 if (Config.DEBUG && ViewDebug.profileDrawing) { 5918 EventLog.writeEvent(60002, hashCode()); 5919 } 5920 5921 int width = mRight - mLeft; 5922 int height = mBottom - mTop; 5923 5924 final AttachInfo attachInfo = mAttachInfo; 5925 5926 if (autoScale && attachInfo != null && attachInfo.mScalingRequired) { 5927 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 5928 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 5929 } 5930 5931 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 5932 final boolean opaque = drawingCacheBackgroundColor != 0 || 5933 (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE); 5934 5935 if (width <= 0 || height <= 0 || 5936 (width * height * (opaque ? 2 : 4) > // Projected bitmap size in bytes 5937 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 5938 destroyDrawingCache(); 5939 return; 5940 } 5941 5942 boolean clear = true; 5943 Bitmap bitmap = autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) : 5944 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get()); 5945 5946 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 5947 5948 Bitmap.Config quality; 5949 if (!opaque) { 5950 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 5951 case DRAWING_CACHE_QUALITY_AUTO: 5952 quality = Bitmap.Config.ARGB_8888; 5953 break; 5954 case DRAWING_CACHE_QUALITY_LOW: 5955 quality = Bitmap.Config.ARGB_4444; 5956 break; 5957 case DRAWING_CACHE_QUALITY_HIGH: 5958 quality = Bitmap.Config.ARGB_8888; 5959 break; 5960 default: 5961 quality = Bitmap.Config.ARGB_8888; 5962 break; 5963 } 5964 } else { 5965 quality = Bitmap.Config.RGB_565; 5966 } 5967 5968 // Try to cleanup memory 5969 if (bitmap != null) bitmap.recycle(); 5970 5971 try { 5972 bitmap = Bitmap.createBitmap(width, height, quality); 5973 if (autoScale) { 5974 mDrawingCache = new SoftReference<Bitmap>(bitmap); 5975 } else { 5976 mUnscaledDrawingCache = new SoftReference<Bitmap>(bitmap); 5977 } 5978 } catch (OutOfMemoryError e) { 5979 // If there is not enough memory to create the bitmap cache, just 5980 // ignore the issue as bitmap caches are not required to draw the 5981 // view hierarchy 5982 if (autoScale) { 5983 mDrawingCache = null; 5984 } else { 5985 mUnscaledDrawingCache = null; 5986 } 5987 return; 5988 } 5989 5990 clear = drawingCacheBackgroundColor != 0; 5991 } 5992 5993 Canvas canvas; 5994 if (attachInfo != null) { 5995 canvas = attachInfo.mCanvas; 5996 if (canvas == null) { 5997 canvas = new Canvas(); 5998 } 5999 canvas.setBitmap(bitmap); 6000 // Temporarily clobber the cached Canvas in case one of our children 6001 // is also using a drawing cache. Without this, the children would 6002 // steal the canvas by attaching their own bitmap to it and bad, bad 6003 // thing would happen (invisible views, corrupted drawings, etc.) 6004 attachInfo.mCanvas = null; 6005 } else { 6006 // This case should hopefully never or seldom happen 6007 canvas = new Canvas(bitmap); 6008 } 6009 6010 if (clear) { 6011 bitmap.eraseColor(drawingCacheBackgroundColor); 6012 } 6013 6014 computeScroll(); 6015 final int restoreCount = canvas.save(); 6016 6017 if (autoScale && attachInfo.mScalingRequired) { 6018 final float scale = attachInfo.mApplicationScale; 6019 canvas.scale(scale, scale); 6020 } 6021 6022 canvas.translate(-mScrollX, -mScrollY); 6023 6024 mPrivateFlags |= DRAWN; 6025 6026 // Fast path for layouts with no backgrounds 6027 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 6028 if (ViewDebug.TRACE_HIERARCHY) { 6029 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 6030 } 6031 mPrivateFlags &= ~DIRTY_MASK; 6032 dispatchDraw(canvas); 6033 } else { 6034 draw(canvas); 6035 } 6036 6037 canvas.restoreToCount(restoreCount); 6038 6039 if (attachInfo != null) { 6040 // Restore the cached Canvas for our siblings 6041 attachInfo.mCanvas = canvas; 6042 } 6043 mPrivateFlags |= DRAWING_CACHE_VALID; 6044 } 6045 } 6046 6047 /** 6048 * Create a snapshot of the view into a bitmap. We should probably make 6049 * some form of this public, but should think about the API. 6050 */ 6051 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor) { 6052 final int width = mRight - mLeft; 6053 final int height = mBottom - mTop; 6054 6055 Bitmap bitmap = Bitmap.createBitmap(width, height, quality); 6056 if (bitmap == null) { 6057 throw new OutOfMemoryError(); 6058 } 6059 6060 Canvas canvas; 6061 final AttachInfo attachInfo = mAttachInfo; 6062 if (attachInfo != null) { 6063 canvas = attachInfo.mCanvas; 6064 if (canvas == null) { 6065 canvas = new Canvas(); 6066 } 6067 canvas.setBitmap(bitmap); 6068 // Temporarily clobber the cached Canvas in case one of our children 6069 // is also using a drawing cache. Without this, the children would 6070 // steal the canvas by attaching their own bitmap to it and bad, bad 6071 // things would happen (invisible views, corrupted drawings, etc.) 6072 attachInfo.mCanvas = null; 6073 } else { 6074 // This case should hopefully never or seldom happen 6075 canvas = new Canvas(bitmap); 6076 } 6077 6078 if ((backgroundColor & 0xff000000) != 0) { 6079 bitmap.eraseColor(backgroundColor); 6080 } 6081 6082 computeScroll(); 6083 final int restoreCount = canvas.save(); 6084 canvas.translate(-mScrollX, -mScrollY); 6085 6086 // Temporarily remove the dirty mask 6087 int flags = mPrivateFlags; 6088 mPrivateFlags &= ~DIRTY_MASK; 6089 6090 // Fast path for layouts with no backgrounds 6091 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 6092 dispatchDraw(canvas); 6093 } else { 6094 draw(canvas); 6095 } 6096 6097 mPrivateFlags = flags; 6098 6099 canvas.restoreToCount(restoreCount); 6100 6101 if (attachInfo != null) { 6102 // Restore the cached Canvas for our siblings 6103 attachInfo.mCanvas = canvas; 6104 } 6105 6106 return bitmap; 6107 } 6108 6109 /** 6110 * Indicates whether this View is currently in edit mode. A View is usually 6111 * in edit mode when displayed within a developer tool. For instance, if 6112 * this View is being drawn by a visual user interface builder, this method 6113 * should return true. 6114 * 6115 * Subclasses should check the return value of this method to provide 6116 * different behaviors if their normal behavior might interfere with the 6117 * host environment. For instance: the class spawns a thread in its 6118 * constructor, the drawing code relies on device-specific features, etc. 6119 * 6120 * This method is usually checked in the drawing code of custom widgets. 6121 * 6122 * @return True if this View is in edit mode, false otherwise. 6123 */ 6124 public boolean isInEditMode() { 6125 return false; 6126 } 6127 6128 /** 6129 * If the View draws content inside its padding and enables fading edges, 6130 * it needs to support padding offsets. Padding offsets are added to the 6131 * fading edges to extend the length of the fade so that it covers pixels 6132 * drawn inside the padding. 6133 * 6134 * Subclasses of this class should override this method if they need 6135 * to draw content inside the padding. 6136 * 6137 * @return True if padding offset must be applied, false otherwise. 6138 * 6139 * @see #getLeftPaddingOffset() 6140 * @see #getRightPaddingOffset() 6141 * @see #getTopPaddingOffset() 6142 * @see #getBottomPaddingOffset() 6143 * 6144 * @since CURRENT 6145 */ 6146 protected boolean isPaddingOffsetRequired() { 6147 return false; 6148 } 6149 6150 /** 6151 * Amount by which to extend the left fading region. Called only when 6152 * {@link #isPaddingOffsetRequired()} returns true. 6153 * 6154 * @return The left padding offset in pixels. 6155 * 6156 * @see #isPaddingOffsetRequired() 6157 * 6158 * @since CURRENT 6159 */ 6160 protected int getLeftPaddingOffset() { 6161 return 0; 6162 } 6163 6164 /** 6165 * Amount by which to extend the right fading region. Called only when 6166 * {@link #isPaddingOffsetRequired()} returns true. 6167 * 6168 * @return The right padding offset in pixels. 6169 * 6170 * @see #isPaddingOffsetRequired() 6171 * 6172 * @since CURRENT 6173 */ 6174 protected int getRightPaddingOffset() { 6175 return 0; 6176 } 6177 6178 /** 6179 * Amount by which to extend the top fading region. Called only when 6180 * {@link #isPaddingOffsetRequired()} returns true. 6181 * 6182 * @return The top padding offset in pixels. 6183 * 6184 * @see #isPaddingOffsetRequired() 6185 * 6186 * @since CURRENT 6187 */ 6188 protected int getTopPaddingOffset() { 6189 return 0; 6190 } 6191 6192 /** 6193 * Amount by which to extend the bottom fading region. Called only when 6194 * {@link #isPaddingOffsetRequired()} returns true. 6195 * 6196 * @return The bottom padding offset in pixels. 6197 * 6198 * @see #isPaddingOffsetRequired() 6199 * 6200 * @since CURRENT 6201 */ 6202 protected int getBottomPaddingOffset() { 6203 return 0; 6204 } 6205 6206 /** 6207 * Manually render this view (and all of its children) to the given Canvas. 6208 * The view must have already done a full layout before this function is 6209 * called. When implementing a view, do not override this method; instead, 6210 * you should implement {@link #onDraw}. 6211 * 6212 * @param canvas The Canvas to which the View is rendered. 6213 */ 6214 public void draw(Canvas canvas) { 6215 if (ViewDebug.TRACE_HIERARCHY) { 6216 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 6217 } 6218 6219 final int privateFlags = mPrivateFlags; 6220 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 6221 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 6222 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 6223 6224 /* 6225 * Draw traversal performs several drawing steps which must be executed 6226 * in the appropriate order: 6227 * 6228 * 1. Draw the background 6229 * 2. If necessary, save the canvas' layers to prepare for fading 6230 * 3. Draw view's content 6231 * 4. Draw children 6232 * 5. If necessary, draw the fading edges and restore layers 6233 * 6. Draw decorations (scrollbars for instance) 6234 */ 6235 6236 // Step 1, draw the background, if needed 6237 int saveCount; 6238 6239 if (!dirtyOpaque) { 6240 final Drawable background = mBGDrawable; 6241 if (background != null) { 6242 final int scrollX = mScrollX; 6243 final int scrollY = mScrollY; 6244 6245 if (mBackgroundSizeChanged) { 6246 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 6247 mBackgroundSizeChanged = false; 6248 } 6249 6250 if ((scrollX | scrollY) == 0) { 6251 background.draw(canvas); 6252 } else { 6253 canvas.translate(scrollX, scrollY); 6254 background.draw(canvas); 6255 canvas.translate(-scrollX, -scrollY); 6256 } 6257 } 6258 } 6259 6260 // skip step 2 & 5 if possible (common case) 6261 final int viewFlags = mViewFlags; 6262 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 6263 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 6264 if (!verticalEdges && !horizontalEdges) { 6265 // Step 3, draw the content 6266 if (!dirtyOpaque) onDraw(canvas); 6267 6268 // Step 4, draw the children 6269 dispatchDraw(canvas); 6270 6271 // Step 6, draw decorations (scrollbars) 6272 onDrawScrollBars(canvas); 6273 6274 // we're done... 6275 return; 6276 } 6277 6278 /* 6279 * Here we do the full fledged routine... 6280 * (this is an uncommon case where speed matters less, 6281 * this is why we repeat some of the tests that have been 6282 * done above) 6283 */ 6284 6285 boolean drawTop = false; 6286 boolean drawBottom = false; 6287 boolean drawLeft = false; 6288 boolean drawRight = false; 6289 6290 float topFadeStrength = 0.0f; 6291 float bottomFadeStrength = 0.0f; 6292 float leftFadeStrength = 0.0f; 6293 float rightFadeStrength = 0.0f; 6294 6295 // Step 2, save the canvas' layers 6296 int paddingLeft = mPaddingLeft; 6297 int paddingTop = mPaddingTop; 6298 6299 final boolean offsetRequired = isPaddingOffsetRequired(); 6300 if (offsetRequired) { 6301 paddingLeft += getLeftPaddingOffset(); 6302 paddingTop += getTopPaddingOffset(); 6303 } 6304 6305 int left = mScrollX + paddingLeft; 6306 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 6307 int top = mScrollY + paddingTop; 6308 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop; 6309 6310 if (offsetRequired) { 6311 right += getRightPaddingOffset(); 6312 bottom += getBottomPaddingOffset(); 6313 } 6314 6315 final ScrollabilityCache scrollabilityCache = mScrollCache; 6316 int length = scrollabilityCache.fadingEdgeLength; 6317 6318 // clip the fade length if top and bottom fades overlap 6319 // overlapping fades produce odd-looking artifacts 6320 if (verticalEdges && (top + length > bottom - length)) { 6321 length = (bottom - top) / 2; 6322 } 6323 6324 // also clip horizontal fades if necessary 6325 if (horizontalEdges && (left + length > right - length)) { 6326 length = (right - left) / 2; 6327 } 6328 6329 if (verticalEdges) { 6330 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 6331 drawTop = topFadeStrength >= 0.0f; 6332 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 6333 drawBottom = bottomFadeStrength >= 0.0f; 6334 } 6335 6336 if (horizontalEdges) { 6337 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 6338 drawLeft = leftFadeStrength >= 0.0f; 6339 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 6340 drawRight = rightFadeStrength >= 0.0f; 6341 } 6342 6343 saveCount = canvas.getSaveCount(); 6344 6345 int solidColor = getSolidColor(); 6346 if (solidColor == 0) { 6347 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 6348 6349 if (drawTop) { 6350 canvas.saveLayer(left, top, right, top + length, null, flags); 6351 } 6352 6353 if (drawBottom) { 6354 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 6355 } 6356 6357 if (drawLeft) { 6358 canvas.saveLayer(left, top, left + length, bottom, null, flags); 6359 } 6360 6361 if (drawRight) { 6362 canvas.saveLayer(right - length, top, right, bottom, null, flags); 6363 } 6364 } else { 6365 scrollabilityCache.setFadeColor(solidColor); 6366 } 6367 6368 // Step 3, draw the content 6369 if (!dirtyOpaque) onDraw(canvas); 6370 6371 // Step 4, draw the children 6372 dispatchDraw(canvas); 6373 6374 // Step 5, draw the fade effect and restore layers 6375 final Paint p = scrollabilityCache.paint; 6376 final Matrix matrix = scrollabilityCache.matrix; 6377 final Shader fade = scrollabilityCache.shader; 6378 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 6379 6380 if (drawTop) { 6381 matrix.setScale(1, fadeHeight * topFadeStrength); 6382 matrix.postTranslate(left, top); 6383 fade.setLocalMatrix(matrix); 6384 canvas.drawRect(left, top, right, top + length, p); 6385 } 6386 6387 if (drawBottom) { 6388 matrix.setScale(1, fadeHeight * bottomFadeStrength); 6389 matrix.postRotate(180); 6390 matrix.postTranslate(left, bottom); 6391 fade.setLocalMatrix(matrix); 6392 canvas.drawRect(left, bottom - length, right, bottom, p); 6393 } 6394 6395 if (drawLeft) { 6396 matrix.setScale(1, fadeHeight * leftFadeStrength); 6397 matrix.postRotate(-90); 6398 matrix.postTranslate(left, top); 6399 fade.setLocalMatrix(matrix); 6400 canvas.drawRect(left, top, left + length, bottom, p); 6401 } 6402 6403 if (drawRight) { 6404 matrix.setScale(1, fadeHeight * rightFadeStrength); 6405 matrix.postRotate(90); 6406 matrix.postTranslate(right, top); 6407 fade.setLocalMatrix(matrix); 6408 canvas.drawRect(right - length, top, right, bottom, p); 6409 } 6410 6411 canvas.restoreToCount(saveCount); 6412 6413 // Step 6, draw decorations (scrollbars) 6414 onDrawScrollBars(canvas); 6415 } 6416 6417 /** 6418 * Override this if your view is known to always be drawn on top of a solid color background, 6419 * and needs to draw fading edges. Returning a non-zero color enables the view system to 6420 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 6421 * should be set to 0xFF. 6422 * 6423 * @see #setVerticalFadingEdgeEnabled 6424 * @see #setHorizontalFadingEdgeEnabled 6425 * 6426 * @return The known solid color background for this view, or 0 if the color may vary 6427 */ 6428 public int getSolidColor() { 6429 return 0; 6430 } 6431 6432 /** 6433 * Build a human readable string representation of the specified view flags. 6434 * 6435 * @param flags the view flags to convert to a string 6436 * @return a String representing the supplied flags 6437 */ 6438 private static String printFlags(int flags) { 6439 String output = ""; 6440 int numFlags = 0; 6441 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 6442 output += "TAKES_FOCUS"; 6443 numFlags++; 6444 } 6445 6446 switch (flags & VISIBILITY_MASK) { 6447 case INVISIBLE: 6448 if (numFlags > 0) { 6449 output += " "; 6450 } 6451 output += "INVISIBLE"; 6452 // USELESS HERE numFlags++; 6453 break; 6454 case GONE: 6455 if (numFlags > 0) { 6456 output += " "; 6457 } 6458 output += "GONE"; 6459 // USELESS HERE numFlags++; 6460 break; 6461 default: 6462 break; 6463 } 6464 return output; 6465 } 6466 6467 /** 6468 * Build a human readable string representation of the specified private 6469 * view flags. 6470 * 6471 * @param privateFlags the private view flags to convert to a string 6472 * @return a String representing the supplied flags 6473 */ 6474 private static String printPrivateFlags(int privateFlags) { 6475 String output = ""; 6476 int numFlags = 0; 6477 6478 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 6479 output += "WANTS_FOCUS"; 6480 numFlags++; 6481 } 6482 6483 if ((privateFlags & FOCUSED) == FOCUSED) { 6484 if (numFlags > 0) { 6485 output += " "; 6486 } 6487 output += "FOCUSED"; 6488 numFlags++; 6489 } 6490 6491 if ((privateFlags & SELECTED) == SELECTED) { 6492 if (numFlags > 0) { 6493 output += " "; 6494 } 6495 output += "SELECTED"; 6496 numFlags++; 6497 } 6498 6499 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 6500 if (numFlags > 0) { 6501 output += " "; 6502 } 6503 output += "IS_ROOT_NAMESPACE"; 6504 numFlags++; 6505 } 6506 6507 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 6508 if (numFlags > 0) { 6509 output += " "; 6510 } 6511 output += "HAS_BOUNDS"; 6512 numFlags++; 6513 } 6514 6515 if ((privateFlags & DRAWN) == DRAWN) { 6516 if (numFlags > 0) { 6517 output += " "; 6518 } 6519 output += "DRAWN"; 6520 // USELESS HERE numFlags++; 6521 } 6522 return output; 6523 } 6524 6525 /** 6526 * <p>Indicates whether or not this view's layout will be requested during 6527 * the next hierarchy layout pass.</p> 6528 * 6529 * @return true if the layout will be forced during next layout pass 6530 */ 6531 public boolean isLayoutRequested() { 6532 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 6533 } 6534 6535 /** 6536 * Assign a size and position to a view and all of its 6537 * descendants 6538 * 6539 * <p>This is the second phase of the layout mechanism. 6540 * (The first is measuring). In this phase, each parent calls 6541 * layout on all of its children to position them. 6542 * This is typically done using the child measurements 6543 * that were stored in the measure pass(). 6544 * 6545 * Derived classes with children should override 6546 * onLayout. In that method, they should 6547 * call layout on each of their their children. 6548 * 6549 * @param l Left position, relative to parent 6550 * @param t Top position, relative to parent 6551 * @param r Right position, relative to parent 6552 * @param b Bottom position, relative to parent 6553 */ 6554 public final void layout(int l, int t, int r, int b) { 6555 boolean changed = setFrame(l, t, r, b); 6556 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 6557 if (ViewDebug.TRACE_HIERARCHY) { 6558 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 6559 } 6560 6561 onLayout(changed, l, t, r, b); 6562 mPrivateFlags &= ~LAYOUT_REQUIRED; 6563 } 6564 mPrivateFlags &= ~FORCE_LAYOUT; 6565 } 6566 6567 /** 6568 * Called from layout when this view should 6569 * assign a size and position to each of its children. 6570 * 6571 * Derived classes with children should override 6572 * this method and call layout on each of 6573 * their their children. 6574 * @param changed This is a new size or position for this view 6575 * @param left Left position, relative to parent 6576 * @param top Top position, relative to parent 6577 * @param right Right position, relative to parent 6578 * @param bottom Bottom position, relative to parent 6579 */ 6580 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 6581 } 6582 6583 /** 6584 * Assign a size and position to this view. 6585 * 6586 * This is called from layout. 6587 * 6588 * @param left Left position, relative to parent 6589 * @param top Top position, relative to parent 6590 * @param right Right position, relative to parent 6591 * @param bottom Bottom position, relative to parent 6592 * @return true if the new size and position are different than the 6593 * previous ones 6594 * {@hide} 6595 */ 6596 protected boolean setFrame(int left, int top, int right, int bottom) { 6597 boolean changed = false; 6598 6599 if (DBG) { 6600 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 6601 + right + "," + bottom + ")"); 6602 } 6603 6604 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 6605 changed = true; 6606 6607 // Remember our drawn bit 6608 int drawn = mPrivateFlags & DRAWN; 6609 6610 // Invalidate our old position 6611 invalidate(); 6612 6613 6614 int oldWidth = mRight - mLeft; 6615 int oldHeight = mBottom - mTop; 6616 6617 mLeft = left; 6618 mTop = top; 6619 mRight = right; 6620 mBottom = bottom; 6621 6622 mPrivateFlags |= HAS_BOUNDS; 6623 6624 int newWidth = right - left; 6625 int newHeight = bottom - top; 6626 6627 if (newWidth != oldWidth || newHeight != oldHeight) { 6628 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 6629 } 6630 6631 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 6632 // If we are visible, force the DRAWN bit to on so that 6633 // this invalidate will go through (at least to our parent). 6634 // This is because someone may have invalidated this view 6635 // before this call to setFrame came in, therby clearing 6636 // the DRAWN bit. 6637 mPrivateFlags |= DRAWN; 6638 invalidate(); 6639 } 6640 6641 // Reset drawn bit to original value (invalidate turns it off) 6642 mPrivateFlags |= drawn; 6643 6644 mBackgroundSizeChanged = true; 6645 } 6646 return changed; 6647 } 6648 6649 /** 6650 * Finalize inflating a view from XML. This is called as the last phase 6651 * of inflation, after all child views have been added. 6652 * 6653 * <p>Even if the subclass overrides onFinishInflate, they should always be 6654 * sure to call the super method, so that we get called. 6655 */ 6656 protected void onFinishInflate() { 6657 } 6658 6659 /** 6660 * Returns the resources associated with this view. 6661 * 6662 * @return Resources object. 6663 */ 6664 public Resources getResources() { 6665 return mResources; 6666 } 6667 6668 /** 6669 * Invalidates the specified Drawable. 6670 * 6671 * @param drawable the drawable to invalidate 6672 */ 6673 public void invalidateDrawable(Drawable drawable) { 6674 if (verifyDrawable(drawable)) { 6675 final Rect dirty = drawable.getBounds(); 6676 final int scrollX = mScrollX; 6677 final int scrollY = mScrollY; 6678 6679 invalidate(dirty.left + scrollX, dirty.top + scrollY, 6680 dirty.right + scrollX, dirty.bottom + scrollY); 6681 } 6682 } 6683 6684 /** 6685 * Schedules an action on a drawable to occur at a specified time. 6686 * 6687 * @param who the recipient of the action 6688 * @param what the action to run on the drawable 6689 * @param when the time at which the action must occur. Uses the 6690 * {@link SystemClock#uptimeMillis} timebase. 6691 */ 6692 public void scheduleDrawable(Drawable who, Runnable what, long when) { 6693 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 6694 mAttachInfo.mHandler.postAtTime(what, who, when); 6695 } 6696 } 6697 6698 /** 6699 * Cancels a scheduled action on a drawable. 6700 * 6701 * @param who the recipient of the action 6702 * @param what the action to cancel 6703 */ 6704 public void unscheduleDrawable(Drawable who, Runnable what) { 6705 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 6706 mAttachInfo.mHandler.removeCallbacks(what, who); 6707 } 6708 } 6709 6710 /** 6711 * Unschedule any events associated with the given Drawable. This can be 6712 * used when selecting a new Drawable into a view, so that the previous 6713 * one is completely unscheduled. 6714 * 6715 * @param who The Drawable to unschedule. 6716 * 6717 * @see #drawableStateChanged 6718 */ 6719 public void unscheduleDrawable(Drawable who) { 6720 if (mAttachInfo != null) { 6721 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 6722 } 6723 } 6724 6725 /** 6726 * If your view subclass is displaying its own Drawable objects, it should 6727 * override this function and return true for any Drawable it is 6728 * displaying. This allows animations for those drawables to be 6729 * scheduled. 6730 * 6731 * <p>Be sure to call through to the super class when overriding this 6732 * function. 6733 * 6734 * @param who The Drawable to verify. Return true if it is one you are 6735 * displaying, else return the result of calling through to the 6736 * super class. 6737 * 6738 * @return boolean If true than the Drawable is being displayed in the 6739 * view; else false and it is not allowed to animate. 6740 * 6741 * @see #unscheduleDrawable 6742 * @see #drawableStateChanged 6743 */ 6744 protected boolean verifyDrawable(Drawable who) { 6745 return who == mBGDrawable; 6746 } 6747 6748 /** 6749 * This function is called whenever the state of the view changes in such 6750 * a way that it impacts the state of drawables being shown. 6751 * 6752 * <p>Be sure to call through to the superclass when overriding this 6753 * function. 6754 * 6755 * @see Drawable#setState 6756 */ 6757 protected void drawableStateChanged() { 6758 Drawable d = mBGDrawable; 6759 if (d != null && d.isStateful()) { 6760 d.setState(getDrawableState()); 6761 } 6762 } 6763 6764 /** 6765 * Call this to force a view to update its drawable state. This will cause 6766 * drawableStateChanged to be called on this view. Views that are interested 6767 * in the new state should call getDrawableState. 6768 * 6769 * @see #drawableStateChanged 6770 * @see #getDrawableState 6771 */ 6772 public void refreshDrawableState() { 6773 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 6774 drawableStateChanged(); 6775 6776 ViewParent parent = mParent; 6777 if (parent != null) { 6778 parent.childDrawableStateChanged(this); 6779 } 6780 } 6781 6782 /** 6783 * Return an array of resource IDs of the drawable states representing the 6784 * current state of the view. 6785 * 6786 * @return The current drawable state 6787 * 6788 * @see Drawable#setState 6789 * @see #drawableStateChanged 6790 * @see #onCreateDrawableState 6791 */ 6792 public final int[] getDrawableState() { 6793 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 6794 return mDrawableState; 6795 } else { 6796 mDrawableState = onCreateDrawableState(0); 6797 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 6798 return mDrawableState; 6799 } 6800 } 6801 6802 /** 6803 * Generate the new {@link android.graphics.drawable.Drawable} state for 6804 * this view. This is called by the view 6805 * system when the cached Drawable state is determined to be invalid. To 6806 * retrieve the current state, you should use {@link #getDrawableState}. 6807 * 6808 * @param extraSpace if non-zero, this is the number of extra entries you 6809 * would like in the returned array in which you can place your own 6810 * states. 6811 * 6812 * @return Returns an array holding the current {@link Drawable} state of 6813 * the view. 6814 * 6815 * @see #mergeDrawableStates 6816 */ 6817 protected int[] onCreateDrawableState(int extraSpace) { 6818 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 6819 mParent instanceof View) { 6820 return ((View) mParent).onCreateDrawableState(extraSpace); 6821 } 6822 6823 int[] drawableState; 6824 6825 int privateFlags = mPrivateFlags; 6826 6827 int viewStateIndex = (((privateFlags & PRESSED) != 0) ? 1 : 0); 6828 6829 viewStateIndex = (viewStateIndex << 1) 6830 + (((mViewFlags & ENABLED_MASK) == ENABLED) ? 1 : 0); 6831 6832 viewStateIndex = (viewStateIndex << 1) + (isFocused() ? 1 : 0); 6833 6834 viewStateIndex = (viewStateIndex << 1) 6835 + (((privateFlags & SELECTED) != 0) ? 1 : 0); 6836 6837 final boolean hasWindowFocus = hasWindowFocus(); 6838 viewStateIndex = (viewStateIndex << 1) + (hasWindowFocus ? 1 : 0); 6839 6840 drawableState = VIEW_STATE_SETS[viewStateIndex]; 6841 6842 //noinspection ConstantIfStatement 6843 if (false) { 6844 Log.i("View", "drawableStateIndex=" + viewStateIndex); 6845 Log.i("View", toString() 6846 + " pressed=" + ((privateFlags & PRESSED) != 0) 6847 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 6848 + " fo=" + hasFocus() 6849 + " sl=" + ((privateFlags & SELECTED) != 0) 6850 + " wf=" + hasWindowFocus 6851 + ": " + Arrays.toString(drawableState)); 6852 } 6853 6854 if (extraSpace == 0) { 6855 return drawableState; 6856 } 6857 6858 final int[] fullState; 6859 if (drawableState != null) { 6860 fullState = new int[drawableState.length + extraSpace]; 6861 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 6862 } else { 6863 fullState = new int[extraSpace]; 6864 } 6865 6866 return fullState; 6867 } 6868 6869 /** 6870 * Merge your own state values in <var>additionalState</var> into the base 6871 * state values <var>baseState</var> that were returned by 6872 * {@link #onCreateDrawableState}. 6873 * 6874 * @param baseState The base state values returned by 6875 * {@link #onCreateDrawableState}, which will be modified to also hold your 6876 * own additional state values. 6877 * 6878 * @param additionalState The additional state values you would like 6879 * added to <var>baseState</var>; this array is not modified. 6880 * 6881 * @return As a convenience, the <var>baseState</var> array you originally 6882 * passed into the function is returned. 6883 * 6884 * @see #onCreateDrawableState 6885 */ 6886 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 6887 final int N = baseState.length; 6888 int i = N - 1; 6889 while (i >= 0 && baseState[i] == 0) { 6890 i--; 6891 } 6892 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 6893 return baseState; 6894 } 6895 6896 /** 6897 * Sets the background color for this view. 6898 * @param color the color of the background 6899 */ 6900 public void setBackgroundColor(int color) { 6901 setBackgroundDrawable(new ColorDrawable(color)); 6902 } 6903 6904 /** 6905 * Set the background to a given resource. The resource should refer to 6906 * a Drawable object. 6907 * @param resid The identifier of the resource. 6908 * @attr ref android.R.styleable#View_background 6909 */ 6910 public void setBackgroundResource(int resid) { 6911 if (resid != 0 && resid == mBackgroundResource) { 6912 return; 6913 } 6914 6915 Drawable d= null; 6916 if (resid != 0) { 6917 d = mResources.getDrawable(resid); 6918 } 6919 setBackgroundDrawable(d); 6920 6921 mBackgroundResource = resid; 6922 } 6923 6924 /** 6925 * Set the background to a given Drawable, or remove the background. If the 6926 * background has padding, this View's padding is set to the background's 6927 * padding. However, when a background is removed, this View's padding isn't 6928 * touched. If setting the padding is desired, please use 6929 * {@link #setPadding(int, int, int, int)}. 6930 * 6931 * @param d The Drawable to use as the background, or null to remove the 6932 * background 6933 */ 6934 public void setBackgroundDrawable(Drawable d) { 6935 boolean requestLayout = false; 6936 6937 mBackgroundResource = 0; 6938 6939 /* 6940 * Regardless of whether we're setting a new background or not, we want 6941 * to clear the previous drawable. 6942 */ 6943 if (mBGDrawable != null) { 6944 mBGDrawable.setCallback(null); 6945 unscheduleDrawable(mBGDrawable); 6946 } 6947 6948 if (d != null) { 6949 Rect padding = sThreadLocal.get(); 6950 if (padding == null) { 6951 padding = new Rect(); 6952 sThreadLocal.set(padding); 6953 } 6954 if (d.getPadding(padding)) { 6955 setPadding(padding.left, padding.top, padding.right, padding.bottom); 6956 } 6957 6958 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 6959 // if it has a different minimum size, we should layout again 6960 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 6961 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 6962 requestLayout = true; 6963 } 6964 6965 d.setCallback(this); 6966 if (d.isStateful()) { 6967 d.setState(getDrawableState()); 6968 } 6969 d.setVisible(getVisibility() == VISIBLE, false); 6970 mBGDrawable = d; 6971 6972 if ((mPrivateFlags & SKIP_DRAW) != 0) { 6973 mPrivateFlags &= ~SKIP_DRAW; 6974 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 6975 requestLayout = true; 6976 } 6977 } else { 6978 /* Remove the background */ 6979 mBGDrawable = null; 6980 6981 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 6982 /* 6983 * This view ONLY drew the background before and we're removing 6984 * the background, so now it won't draw anything 6985 * (hence we SKIP_DRAW) 6986 */ 6987 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 6988 mPrivateFlags |= SKIP_DRAW; 6989 } 6990 6991 /* 6992 * When the background is set, we try to apply its padding to this 6993 * View. When the background is removed, we don't touch this View's 6994 * padding. This is noted in the Javadocs. Hence, we don't need to 6995 * requestLayout(), the invalidate() below is sufficient. 6996 */ 6997 6998 // The old background's minimum size could have affected this 6999 // View's layout, so let's requestLayout 7000 requestLayout = true; 7001 } 7002 7003 computeOpaqueFlags(); 7004 7005 if (requestLayout) { 7006 requestLayout(); 7007 } 7008 7009 mBackgroundSizeChanged = true; 7010 invalidate(); 7011 } 7012 7013 /** 7014 * Gets the background drawable 7015 * @return The drawable used as the background for this view, if any. 7016 */ 7017 public Drawable getBackground() { 7018 return mBGDrawable; 7019 } 7020 7021 /** 7022 * Sets the padding. The view may add on the space required to display 7023 * the scrollbars, depending on the style and visibility of the scrollbars. 7024 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 7025 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 7026 * from the values set in this call. 7027 * 7028 * @attr ref android.R.styleable#View_padding 7029 * @attr ref android.R.styleable#View_paddingBottom 7030 * @attr ref android.R.styleable#View_paddingLeft 7031 * @attr ref android.R.styleable#View_paddingRight 7032 * @attr ref android.R.styleable#View_paddingTop 7033 * @param left the left padding in pixels 7034 * @param top the top padding in pixels 7035 * @param right the right padding in pixels 7036 * @param bottom the bottom padding in pixels 7037 */ 7038 public void setPadding(int left, int top, int right, int bottom) { 7039 boolean changed = false; 7040 7041 mUserPaddingRight = right; 7042 mUserPaddingBottom = bottom; 7043 7044 final int viewFlags = mViewFlags; 7045 7046 // Common case is there are no scroll bars. 7047 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 7048 // TODO: Deal with RTL languages to adjust left padding instead of right. 7049 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 7050 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0 7051 ? 0 : getVerticalScrollbarWidth(); 7052 } 7053 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) { 7054 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 7055 ? 0 : getHorizontalScrollbarHeight(); 7056 } 7057 } 7058 7059 if (mPaddingLeft != left) { 7060 changed = true; 7061 mPaddingLeft = left; 7062 } 7063 if (mPaddingTop != top) { 7064 changed = true; 7065 mPaddingTop = top; 7066 } 7067 if (mPaddingRight != right) { 7068 changed = true; 7069 mPaddingRight = right; 7070 } 7071 if (mPaddingBottom != bottom) { 7072 changed = true; 7073 mPaddingBottom = bottom; 7074 } 7075 7076 if (changed) { 7077 requestLayout(); 7078 } 7079 } 7080 7081 /** 7082 * Returns the top padding of this view. 7083 * 7084 * @return the top padding in pixels 7085 */ 7086 public int getPaddingTop() { 7087 return mPaddingTop; 7088 } 7089 7090 /** 7091 * Returns the bottom padding of this view. If there are inset and enabled 7092 * scrollbars, this value may include the space required to display the 7093 * scrollbars as well. 7094 * 7095 * @return the bottom padding in pixels 7096 */ 7097 public int getPaddingBottom() { 7098 return mPaddingBottom; 7099 } 7100 7101 /** 7102 * Returns the left padding of this view. If there are inset and enabled 7103 * scrollbars, this value may include the space required to display the 7104 * scrollbars as well. 7105 * 7106 * @return the left padding in pixels 7107 */ 7108 public int getPaddingLeft() { 7109 return mPaddingLeft; 7110 } 7111 7112 /** 7113 * Returns the right padding of this view. If there are inset and enabled 7114 * scrollbars, this value may include the space required to display the 7115 * scrollbars as well. 7116 * 7117 * @return the right padding in pixels 7118 */ 7119 public int getPaddingRight() { 7120 return mPaddingRight; 7121 } 7122 7123 /** 7124 * Changes the selection state of this view. A view can be selected or not. 7125 * Note that selection is not the same as focus. Views are typically 7126 * selected in the context of an AdapterView like ListView or GridView; 7127 * the selected view is the view that is highlighted. 7128 * 7129 * @param selected true if the view must be selected, false otherwise 7130 */ 7131 public void setSelected(boolean selected) { 7132 if (((mPrivateFlags & SELECTED) != 0) != selected) { 7133 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 7134 if (!selected) resetPressedState(); 7135 invalidate(); 7136 refreshDrawableState(); 7137 dispatchSetSelected(selected); 7138 } 7139 } 7140 7141 /** 7142 * Dispatch setSelected to all of this View's children. 7143 * 7144 * @see #setSelected(boolean) 7145 * 7146 * @param selected The new selected state 7147 */ 7148 protected void dispatchSetSelected(boolean selected) { 7149 } 7150 7151 /** 7152 * Indicates the selection state of this view. 7153 * 7154 * @return true if the view is selected, false otherwise 7155 */ 7156 @ViewDebug.ExportedProperty 7157 public boolean isSelected() { 7158 return (mPrivateFlags & SELECTED) != 0; 7159 } 7160 7161 /** 7162 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 7163 * observer can be used to get notifications when global events, like 7164 * layout, happen. 7165 * 7166 * The returned ViewTreeObserver observer is not guaranteed to remain 7167 * valid for the lifetime of this View. If the caller of this method keeps 7168 * a long-lived reference to ViewTreeObserver, it should always check for 7169 * the return value of {@link ViewTreeObserver#isAlive()}. 7170 * 7171 * @return The ViewTreeObserver for this view's hierarchy. 7172 */ 7173 public ViewTreeObserver getViewTreeObserver() { 7174 if (mAttachInfo != null) { 7175 return mAttachInfo.mTreeObserver; 7176 } 7177 if (mFloatingTreeObserver == null) { 7178 mFloatingTreeObserver = new ViewTreeObserver(); 7179 } 7180 return mFloatingTreeObserver; 7181 } 7182 7183 /** 7184 * <p>Finds the topmost view in the current view hierarchy.</p> 7185 * 7186 * @return the topmost view containing this view 7187 */ 7188 public View getRootView() { 7189 if (mAttachInfo != null) { 7190 final View v = mAttachInfo.mRootView; 7191 if (v != null) { 7192 return v; 7193 } 7194 } 7195 7196 View parent = this; 7197 7198 while (parent.mParent != null && parent.mParent instanceof View) { 7199 parent = (View) parent.mParent; 7200 } 7201 7202 return parent; 7203 } 7204 7205 /** 7206 * <p>Computes the coordinates of this view on the screen. The argument 7207 * must be an array of two integers. After the method returns, the array 7208 * contains the x and y location in that order.</p> 7209 * 7210 * @param location an array of two integers in which to hold the coordinates 7211 */ 7212 public void getLocationOnScreen(int[] location) { 7213 getLocationInWindow(location); 7214 7215 final AttachInfo info = mAttachInfo; 7216 if (info != null) { 7217 location[0] += info.mWindowLeft; 7218 location[1] += info.mWindowTop; 7219 } 7220 } 7221 7222 /** 7223 * <p>Computes the coordinates of this view in its window. The argument 7224 * must be an array of two integers. After the method returns, the array 7225 * contains the x and y location in that order.</p> 7226 * 7227 * @param location an array of two integers in which to hold the coordinates 7228 */ 7229 public void getLocationInWindow(int[] location) { 7230 if (location == null || location.length < 2) { 7231 throw new IllegalArgumentException("location must be an array of " 7232 + "two integers"); 7233 } 7234 7235 location[0] = mLeft; 7236 location[1] = mTop; 7237 7238 ViewParent viewParent = mParent; 7239 while (viewParent instanceof View) { 7240 final View view = (View)viewParent; 7241 location[0] += view.mLeft - view.mScrollX; 7242 location[1] += view.mTop - view.mScrollY; 7243 viewParent = view.mParent; 7244 } 7245 7246 if (viewParent instanceof ViewRoot) { 7247 // *cough* 7248 final ViewRoot vr = (ViewRoot)viewParent; 7249 location[1] -= vr.mCurScrollY; 7250 } 7251 } 7252 7253 /** 7254 * {@hide} 7255 * @param id the id of the view to be found 7256 * @return the view of the specified id, null if cannot be found 7257 */ 7258 protected View findViewTraversal(int id) { 7259 if (id == mID) { 7260 return this; 7261 } 7262 return null; 7263 } 7264 7265 /** 7266 * {@hide} 7267 * @param tag the tag of the view to be found 7268 * @return the view of specified tag, null if cannot be found 7269 */ 7270 protected View findViewWithTagTraversal(Object tag) { 7271 if (tag != null && tag.equals(mTag)) { 7272 return this; 7273 } 7274 return null; 7275 } 7276 7277 /** 7278 * Look for a child view with the given id. If this view has the given 7279 * id, return this view. 7280 * 7281 * @param id The id to search for. 7282 * @return The view that has the given id in the hierarchy or null 7283 */ 7284 public final View findViewById(int id) { 7285 if (id < 0) { 7286 return null; 7287 } 7288 return findViewTraversal(id); 7289 } 7290 7291 /** 7292 * Look for a child view with the given tag. If this view has the given 7293 * tag, return this view. 7294 * 7295 * @param tag The tag to search for, using "tag.equals(getTag())". 7296 * @return The View that has the given tag in the hierarchy or null 7297 */ 7298 public final View findViewWithTag(Object tag) { 7299 if (tag == null) { 7300 return null; 7301 } 7302 return findViewWithTagTraversal(tag); 7303 } 7304 7305 /** 7306 * Sets the identifier for this view. The identifier does not have to be 7307 * unique in this view's hierarchy. The identifier should be a positive 7308 * number. 7309 * 7310 * @see #NO_ID 7311 * @see #getId 7312 * @see #findViewById 7313 * 7314 * @param id a number used to identify the view 7315 * 7316 * @attr ref android.R.styleable#View_id 7317 */ 7318 public void setId(int id) { 7319 mID = id; 7320 } 7321 7322 /** 7323 * {@hide} 7324 * 7325 * @param isRoot true if the view belongs to the root namespace, false 7326 * otherwise 7327 */ 7328 public void setIsRootNamespace(boolean isRoot) { 7329 if (isRoot) { 7330 mPrivateFlags |= IS_ROOT_NAMESPACE; 7331 } else { 7332 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 7333 } 7334 } 7335 7336 /** 7337 * {@hide} 7338 * 7339 * @return true if the view belongs to the root namespace, false otherwise 7340 */ 7341 public boolean isRootNamespace() { 7342 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 7343 } 7344 7345 /** 7346 * Returns this view's identifier. 7347 * 7348 * @return a positive integer used to identify the view or {@link #NO_ID} 7349 * if the view has no ID 7350 * 7351 * @see #setId 7352 * @see #findViewById 7353 * @attr ref android.R.styleable#View_id 7354 */ 7355 @ViewDebug.CapturedViewProperty 7356 public int getId() { 7357 return mID; 7358 } 7359 7360 /** 7361 * Returns this view's tag. 7362 * 7363 * @return the Object stored in this view as a tag 7364 * 7365 * @see #setTag(Object) 7366 * @see #getTag(int) 7367 */ 7368 @ViewDebug.ExportedProperty 7369 public Object getTag() { 7370 return mTag; 7371 } 7372 7373 /** 7374 * Sets the tag associated with this view. A tag can be used to mark 7375 * a view in its hierarchy and does not have to be unique within the 7376 * hierarchy. Tags can also be used to store data within a view without 7377 * resorting to another data structure. 7378 * 7379 * @param tag an Object to tag the view with 7380 * 7381 * @see #getTag() 7382 * @see #setTag(int, Object) 7383 */ 7384 public void setTag(final Object tag) { 7385 mTag = tag; 7386 } 7387 7388 /** 7389 * Returns the tag associated with this view and the specified key. 7390 * 7391 * @param key The key identifying the tag 7392 * 7393 * @return the Object stored in this view as a tag 7394 * 7395 * @see #setTag(int, Object) 7396 * @see #getTag() 7397 */ 7398 public Object getTag(int key) { 7399 SparseArray<Object> tags = null; 7400 synchronized (sTagsLock) { 7401 if (sTags != null) { 7402 tags = sTags.get(this); 7403 } 7404 } 7405 7406 if (tags != null) return tags.get(key); 7407 return null; 7408 } 7409 7410 /** 7411 * Sets a tag associated with this view and a key. A tag can be used 7412 * to mark a view in its hierarchy and does not have to be unique within 7413 * the hierarchy. Tags can also be used to store data within a view 7414 * without resorting to another data structure. 7415 * 7416 * The specified key should be an id declared in the resources of the 7417 * application to ensure it is unique. Keys identified as belonging to 7418 * the Android framework or not associated with any package will cause 7419 * an {@link IllegalArgumentException} to be thrown. 7420 * 7421 * @param key The key identifying the tag 7422 * @param tag An Object to tag the view with 7423 * 7424 * @throws IllegalArgumentException If they specified key is not valid 7425 * 7426 * @see #setTag(Object) 7427 * @see #getTag(int) 7428 */ 7429 public void setTag(int key, final Object tag) { 7430 // If the package id is 0x00 or 0x01, it's either an undefined package 7431 // or a framework id 7432 if ((key >>> 24) < 2) { 7433 throw new IllegalArgumentException("The key must be an application-specific " 7434 + "resource id."); 7435 } 7436 7437 setTagInternal(this, key, tag); 7438 } 7439 7440 /** 7441 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 7442 * framework id. 7443 * 7444 * @hide 7445 */ 7446 public void setTagInternal(int key, Object tag) { 7447 if ((key >>> 24) != 0x1) { 7448 throw new IllegalArgumentException("The key must be a framework-specific " 7449 + "resource id."); 7450 } 7451 7452 setTagInternal(this, key, tag); 7453 } 7454 7455 private static void setTagInternal(View view, int key, Object tag) { 7456 SparseArray<Object> tags = null; 7457 synchronized (sTagsLock) { 7458 if (sTags == null) { 7459 sTags = new WeakHashMap<View, SparseArray<Object>>(); 7460 } else { 7461 tags = sTags.get(view); 7462 } 7463 } 7464 7465 if (tags == null) { 7466 tags = new SparseArray<Object>(2); 7467 synchronized (sTagsLock) { 7468 sTags.put(view, tags); 7469 } 7470 } 7471 7472 tags.put(key, tag); 7473 } 7474 7475 /** 7476 * @param consistency The type of consistency. See ViewDebug for more information. 7477 * 7478 * @hide 7479 */ 7480 protected boolean dispatchConsistencyCheck(int consistency) { 7481 return onConsistencyCheck(consistency); 7482 } 7483 7484 /** 7485 * Method that subclasses should implement to check their consistency. The type of 7486 * consistency check is indicated by the bit field passed as a parameter. 7487 * 7488 * @param consistency The type of consistency. See ViewDebug for more information. 7489 * 7490 * @throws IllegalStateException if the view is in an inconsistent state. 7491 * 7492 * @hide 7493 */ 7494 protected boolean onConsistencyCheck(int consistency) { 7495 boolean result = true; 7496 7497 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 7498 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 7499 7500 if (checkLayout) { 7501 if (getParent() == null) { 7502 result = false; 7503 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 7504 "View " + this + " does not have a parent."); 7505 } 7506 7507 if (mAttachInfo == null) { 7508 result = false; 7509 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 7510 "View " + this + " is not attached to a window."); 7511 } 7512 } 7513 7514 if (checkDrawing) { 7515 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 7516 // from their draw() method 7517 7518 if ((mPrivateFlags & DRAWN) != DRAWN && 7519 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 7520 result = false; 7521 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 7522 "View " + this + " was invalidated but its drawing cache is valid."); 7523 } 7524 } 7525 7526 return result; 7527 } 7528 7529 /** 7530 * Prints information about this view in the log output, with the tag 7531 * {@link #VIEW_LOG_TAG}. 7532 * 7533 * @hide 7534 */ 7535 public void debug() { 7536 debug(0); 7537 } 7538 7539 /** 7540 * Prints information about this view in the log output, with the tag 7541 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 7542 * indentation defined by the <code>depth</code>. 7543 * 7544 * @param depth the indentation level 7545 * 7546 * @hide 7547 */ 7548 protected void debug(int depth) { 7549 String output = debugIndent(depth - 1); 7550 7551 output += "+ " + this; 7552 int id = getId(); 7553 if (id != -1) { 7554 output += " (id=" + id + ")"; 7555 } 7556 Object tag = getTag(); 7557 if (tag != null) { 7558 output += " (tag=" + tag + ")"; 7559 } 7560 Log.d(VIEW_LOG_TAG, output); 7561 7562 if ((mPrivateFlags & FOCUSED) != 0) { 7563 output = debugIndent(depth) + " FOCUSED"; 7564 Log.d(VIEW_LOG_TAG, output); 7565 } 7566 7567 output = debugIndent(depth); 7568 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 7569 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 7570 + "} "; 7571 Log.d(VIEW_LOG_TAG, output); 7572 7573 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 7574 || mPaddingBottom != 0) { 7575 output = debugIndent(depth); 7576 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 7577 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 7578 Log.d(VIEW_LOG_TAG, output); 7579 } 7580 7581 output = debugIndent(depth); 7582 output += "mMeasureWidth=" + mMeasuredWidth + 7583 " mMeasureHeight=" + mMeasuredHeight; 7584 Log.d(VIEW_LOG_TAG, output); 7585 7586 output = debugIndent(depth); 7587 if (mLayoutParams == null) { 7588 output += "BAD! no layout params"; 7589 } else { 7590 output = mLayoutParams.debug(output); 7591 } 7592 Log.d(VIEW_LOG_TAG, output); 7593 7594 output = debugIndent(depth); 7595 output += "flags={"; 7596 output += View.printFlags(mViewFlags); 7597 output += "}"; 7598 Log.d(VIEW_LOG_TAG, output); 7599 7600 output = debugIndent(depth); 7601 output += "privateFlags={"; 7602 output += View.printPrivateFlags(mPrivateFlags); 7603 output += "}"; 7604 Log.d(VIEW_LOG_TAG, output); 7605 } 7606 7607 /** 7608 * Creates an string of whitespaces used for indentation. 7609 * 7610 * @param depth the indentation level 7611 * @return a String containing (depth * 2 + 3) * 2 white spaces 7612 * 7613 * @hide 7614 */ 7615 protected static String debugIndent(int depth) { 7616 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 7617 for (int i = 0; i < (depth * 2) + 3; i++) { 7618 spaces.append(' ').append(' '); 7619 } 7620 return spaces.toString(); 7621 } 7622 7623 /** 7624 * <p>Return the offset of the widget's text baseline from the widget's top 7625 * boundary. If this widget does not support baseline alignment, this 7626 * method returns -1. </p> 7627 * 7628 * @return the offset of the baseline within the widget's bounds or -1 7629 * if baseline alignment is not supported 7630 */ 7631 @ViewDebug.ExportedProperty 7632 public int getBaseline() { 7633 return -1; 7634 } 7635 7636 /** 7637 * Call this when something has changed which has invalidated the 7638 * layout of this view. This will schedule a layout pass of the view 7639 * tree. 7640 */ 7641 public void requestLayout() { 7642 if (ViewDebug.TRACE_HIERARCHY) { 7643 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 7644 } 7645 7646 mPrivateFlags |= FORCE_LAYOUT; 7647 7648 if (mParent != null && !mParent.isLayoutRequested()) { 7649 mParent.requestLayout(); 7650 } 7651 } 7652 7653 /** 7654 * Forces this view to be laid out during the next layout pass. 7655 * This method does not call requestLayout() or forceLayout() 7656 * on the parent. 7657 */ 7658 public void forceLayout() { 7659 mPrivateFlags |= FORCE_LAYOUT; 7660 } 7661 7662 /** 7663 * <p> 7664 * This is called to find out how big a view should be. The parent 7665 * supplies constraint information in the width and height parameters. 7666 * </p> 7667 * 7668 * <p> 7669 * The actual mesurement work of a view is performed in 7670 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 7671 * {@link #onMeasure(int, int)} can and must be overriden by subclasses. 7672 * </p> 7673 * 7674 * 7675 * @param widthMeasureSpec Horizontal space requirements as imposed by the 7676 * parent 7677 * @param heightMeasureSpec Vertical space requirements as imposed by the 7678 * parent 7679 * 7680 * @see #onMeasure(int, int) 7681 */ 7682 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 7683 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 7684 widthMeasureSpec != mOldWidthMeasureSpec || 7685 heightMeasureSpec != mOldHeightMeasureSpec) { 7686 7687 // first clears the measured dimension flag 7688 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 7689 7690 if (ViewDebug.TRACE_HIERARCHY) { 7691 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 7692 } 7693 7694 // measure ourselves, this should set the measured dimension flag back 7695 onMeasure(widthMeasureSpec, heightMeasureSpec); 7696 7697 // flag not set, setMeasuredDimension() was not invoked, we raise 7698 // an exception to warn the developer 7699 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 7700 throw new IllegalStateException("onMeasure() did not set the" 7701 + " measured dimension by calling" 7702 + " setMeasuredDimension()"); 7703 } 7704 7705 mPrivateFlags |= LAYOUT_REQUIRED; 7706 } 7707 7708 mOldWidthMeasureSpec = widthMeasureSpec; 7709 mOldHeightMeasureSpec = heightMeasureSpec; 7710 } 7711 7712 /** 7713 * <p> 7714 * Measure the view and its content to determine the measured width and the 7715 * measured height. This method is invoked by {@link #measure(int, int)} and 7716 * should be overriden by subclasses to provide accurate and efficient 7717 * measurement of their contents. 7718 * </p> 7719 * 7720 * <p> 7721 * <strong>CONTRACT:</strong> When overriding this method, you 7722 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 7723 * measured width and height of this view. Failure to do so will trigger an 7724 * <code>IllegalStateException</code>, thrown by 7725 * {@link #measure(int, int)}. Calling the superclass' 7726 * {@link #onMeasure(int, int)} is a valid use. 7727 * </p> 7728 * 7729 * <p> 7730 * The base class implementation of measure defaults to the background size, 7731 * unless a larger size is allowed by the MeasureSpec. Subclasses should 7732 * override {@link #onMeasure(int, int)} to provide better measurements of 7733 * their content. 7734 * </p> 7735 * 7736 * <p> 7737 * If this method is overridden, it is the subclass's responsibility to make 7738 * sure the measured height and width are at least the view's minimum height 7739 * and width ({@link #getSuggestedMinimumHeight()} and 7740 * {@link #getSuggestedMinimumWidth()}). 7741 * </p> 7742 * 7743 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 7744 * The requirements are encoded with 7745 * {@link android.view.View.MeasureSpec}. 7746 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 7747 * The requirements are encoded with 7748 * {@link android.view.View.MeasureSpec}. 7749 * 7750 * @see #getMeasuredWidth() 7751 * @see #getMeasuredHeight() 7752 * @see #setMeasuredDimension(int, int) 7753 * @see #getSuggestedMinimumHeight() 7754 * @see #getSuggestedMinimumWidth() 7755 * @see android.view.View.MeasureSpec#getMode(int) 7756 * @see android.view.View.MeasureSpec#getSize(int) 7757 */ 7758 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 7759 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 7760 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 7761 } 7762 7763 /** 7764 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 7765 * measured width and measured height. Failing to do so will trigger an 7766 * exception at measurement time.</p> 7767 * 7768 * @param measuredWidth the measured width of this view 7769 * @param measuredHeight the measured height of this view 7770 */ 7771 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 7772 mMeasuredWidth = measuredWidth; 7773 mMeasuredHeight = measuredHeight; 7774 7775 mPrivateFlags |= MEASURED_DIMENSION_SET; 7776 } 7777 7778 /** 7779 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec. 7780 * Will take the desired size, unless a different size is imposed by the constraints. 7781 * 7782 * @param size How big the view wants to be 7783 * @param measureSpec Constraints imposed by the parent 7784 * @return The size this view should be. 7785 */ 7786 public static int resolveSize(int size, int measureSpec) { 7787 int result = size; 7788 int specMode = MeasureSpec.getMode(measureSpec); 7789 int specSize = MeasureSpec.getSize(measureSpec); 7790 switch (specMode) { 7791 case MeasureSpec.UNSPECIFIED: 7792 result = size; 7793 break; 7794 case MeasureSpec.AT_MOST: 7795 result = Math.min(size, specSize); 7796 break; 7797 case MeasureSpec.EXACTLY: 7798 result = specSize; 7799 break; 7800 } 7801 return result; 7802 } 7803 7804 /** 7805 * Utility to return a default size. Uses the supplied size if the 7806 * MeasureSpec imposed no contraints. Will get larger if allowed 7807 * by the MeasureSpec. 7808 * 7809 * @param size Default size for this view 7810 * @param measureSpec Constraints imposed by the parent 7811 * @return The size this view should be. 7812 */ 7813 public static int getDefaultSize(int size, int measureSpec) { 7814 int result = size; 7815 int specMode = MeasureSpec.getMode(measureSpec); 7816 int specSize = MeasureSpec.getSize(measureSpec); 7817 7818 switch (specMode) { 7819 case MeasureSpec.UNSPECIFIED: 7820 result = size; 7821 break; 7822 case MeasureSpec.AT_MOST: 7823 case MeasureSpec.EXACTLY: 7824 result = specSize; 7825 break; 7826 } 7827 return result; 7828 } 7829 7830 /** 7831 * Returns the suggested minimum height that the view should use. This 7832 * returns the maximum of the view's minimum height 7833 * and the background's minimum height 7834 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 7835 * <p> 7836 * When being used in {@link #onMeasure(int, int)}, the caller should still 7837 * ensure the returned height is within the requirements of the parent. 7838 * 7839 * @return The suggested minimum height of the view. 7840 */ 7841 protected int getSuggestedMinimumHeight() { 7842 int suggestedMinHeight = mMinHeight; 7843 7844 if (mBGDrawable != null) { 7845 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 7846 if (suggestedMinHeight < bgMinHeight) { 7847 suggestedMinHeight = bgMinHeight; 7848 } 7849 } 7850 7851 return suggestedMinHeight; 7852 } 7853 7854 /** 7855 * Returns the suggested minimum width that the view should use. This 7856 * returns the maximum of the view's minimum width) 7857 * and the background's minimum width 7858 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 7859 * <p> 7860 * When being used in {@link #onMeasure(int, int)}, the caller should still 7861 * ensure the returned width is within the requirements of the parent. 7862 * 7863 * @return The suggested minimum width of the view. 7864 */ 7865 protected int getSuggestedMinimumWidth() { 7866 int suggestedMinWidth = mMinWidth; 7867 7868 if (mBGDrawable != null) { 7869 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 7870 if (suggestedMinWidth < bgMinWidth) { 7871 suggestedMinWidth = bgMinWidth; 7872 } 7873 } 7874 7875 return suggestedMinWidth; 7876 } 7877 7878 /** 7879 * Sets the minimum height of the view. It is not guaranteed the view will 7880 * be able to achieve this minimum height (for example, if its parent layout 7881 * constrains it with less available height). 7882 * 7883 * @param minHeight The minimum height the view will try to be. 7884 */ 7885 public void setMinimumHeight(int minHeight) { 7886 mMinHeight = minHeight; 7887 } 7888 7889 /** 7890 * Sets the minimum width of the view. It is not guaranteed the view will 7891 * be able to achieve this minimum width (for example, if its parent layout 7892 * constrains it with less available width). 7893 * 7894 * @param minWidth The minimum width the view will try to be. 7895 */ 7896 public void setMinimumWidth(int minWidth) { 7897 mMinWidth = minWidth; 7898 } 7899 7900 /** 7901 * Get the animation currently associated with this view. 7902 * 7903 * @return The animation that is currently playing or 7904 * scheduled to play for this view. 7905 */ 7906 public Animation getAnimation() { 7907 return mCurrentAnimation; 7908 } 7909 7910 /** 7911 * Start the specified animation now. 7912 * 7913 * @param animation the animation to start now 7914 */ 7915 public void startAnimation(Animation animation) { 7916 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 7917 setAnimation(animation); 7918 invalidate(); 7919 } 7920 7921 /** 7922 * Cancels any animations for this view. 7923 */ 7924 public void clearAnimation() { 7925 mCurrentAnimation = null; 7926 } 7927 7928 /** 7929 * Sets the next animation to play for this view. 7930 * If you want the animation to play immediately, use 7931 * startAnimation. This method provides allows fine-grained 7932 * control over the start time and invalidation, but you 7933 * must make sure that 1) the animation has a start time set, and 7934 * 2) the view will be invalidated when the animation is supposed to 7935 * start. 7936 * 7937 * @param animation The next animation, or null. 7938 */ 7939 public void setAnimation(Animation animation) { 7940 mCurrentAnimation = animation; 7941 if (animation != null) { 7942 animation.reset(); 7943 } 7944 } 7945 7946 /** 7947 * Invoked by a parent ViewGroup to notify the start of the animation 7948 * currently associated with this view. If you override this method, 7949 * always call super.onAnimationStart(); 7950 * 7951 * @see #setAnimation(android.view.animation.Animation) 7952 * @see #getAnimation() 7953 */ 7954 protected void onAnimationStart() { 7955 mPrivateFlags |= ANIMATION_STARTED; 7956 } 7957 7958 /** 7959 * Invoked by a parent ViewGroup to notify the end of the animation 7960 * currently associated with this view. If you override this method, 7961 * always call super.onAnimationEnd(); 7962 * 7963 * @see #setAnimation(android.view.animation.Animation) 7964 * @see #getAnimation() 7965 */ 7966 protected void onAnimationEnd() { 7967 mPrivateFlags &= ~ANIMATION_STARTED; 7968 } 7969 7970 /** 7971 * Invoked if there is a Transform that involves alpha. Subclass that can 7972 * draw themselves with the specified alpha should return true, and then 7973 * respect that alpha when their onDraw() is called. If this returns false 7974 * then the view may be redirected to draw into an offscreen buffer to 7975 * fulfill the request, which will look fine, but may be slower than if the 7976 * subclass handles it internally. The default implementation returns false. 7977 * 7978 * @param alpha The alpha (0..255) to apply to the view's drawing 7979 * @return true if the view can draw with the specified alpha. 7980 */ 7981 protected boolean onSetAlpha(int alpha) { 7982 return false; 7983 } 7984 7985 /** 7986 * This is used by the RootView to perform an optimization when 7987 * the view hierarchy contains one or several SurfaceView. 7988 * SurfaceView is always considered transparent, but its children are not, 7989 * therefore all View objects remove themselves from the global transparent 7990 * region (passed as a parameter to this function). 7991 * 7992 * @param region The transparent region for this ViewRoot (window). 7993 * 7994 * @return Returns true if the effective visibility of the view at this 7995 * point is opaque, regardless of the transparent region; returns false 7996 * if it is possible for underlying windows to be seen behind the view. 7997 * 7998 * {@hide} 7999 */ 8000 public boolean gatherTransparentRegion(Region region) { 8001 final AttachInfo attachInfo = mAttachInfo; 8002 if (region != null && attachInfo != null) { 8003 final int pflags = mPrivateFlags; 8004 if ((pflags & SKIP_DRAW) == 0) { 8005 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 8006 // remove it from the transparent region. 8007 final int[] location = attachInfo.mTransparentLocation; 8008 getLocationInWindow(location); 8009 region.op(location[0], location[1], location[0] + mRight - mLeft, 8010 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 8011 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 8012 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 8013 // exists, so we remove the background drawable's non-transparent 8014 // parts from this transparent region. 8015 applyDrawableToTransparentRegion(mBGDrawable, region); 8016 } 8017 } 8018 return true; 8019 } 8020 8021 /** 8022 * Play a sound effect for this view. 8023 * 8024 * <p>The framework will play sound effects for some built in actions, such as 8025 * clicking, but you may wish to play these effects in your widget, 8026 * for instance, for internal navigation. 8027 * 8028 * <p>The sound effect will only be played if sound effects are enabled by the user, and 8029 * {@link #isSoundEffectsEnabled()} is true. 8030 * 8031 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 8032 */ 8033 public void playSoundEffect(int soundConstant) { 8034 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 8035 return; 8036 } 8037 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 8038 } 8039 8040 /** 8041 * BZZZTT!!1! 8042 * 8043 * <p>Provide haptic feedback to the user for this view. 8044 * 8045 * <p>The framework will provide haptic feedback for some built in actions, 8046 * such as long presses, but you may wish to provide feedback for your 8047 * own widget. 8048 * 8049 * <p>The feedback will only be performed if 8050 * {@link #isHapticFeedbackEnabled()} is true. 8051 * 8052 * @param feedbackConstant One of the constants defined in 8053 * {@link HapticFeedbackConstants} 8054 */ 8055 public boolean performHapticFeedback(int feedbackConstant) { 8056 return performHapticFeedback(feedbackConstant, 0); 8057 } 8058 8059 /** 8060 * BZZZTT!!1! 8061 * 8062 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 8063 * 8064 * @param feedbackConstant One of the constants defined in 8065 * {@link HapticFeedbackConstants} 8066 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 8067 */ 8068 public boolean performHapticFeedback(int feedbackConstant, int flags) { 8069 if (mAttachInfo == null) { 8070 return false; 8071 } 8072 if ((flags&HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 8073 && !isHapticFeedbackEnabled()) { 8074 return false; 8075 } 8076 return mAttachInfo.mRootCallbacks.performHapticFeedback( 8077 feedbackConstant, 8078 (flags&HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 8079 } 8080 8081 /** 8082 * Given a Drawable whose bounds have been set to draw into this view, 8083 * update a Region being computed for {@link #gatherTransparentRegion} so 8084 * that any non-transparent parts of the Drawable are removed from the 8085 * given transparent region. 8086 * 8087 * @param dr The Drawable whose transparency is to be applied to the region. 8088 * @param region A Region holding the current transparency information, 8089 * where any parts of the region that are set are considered to be 8090 * transparent. On return, this region will be modified to have the 8091 * transparency information reduced by the corresponding parts of the 8092 * Drawable that are not transparent. 8093 * {@hide} 8094 */ 8095 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 8096 if (DBG) { 8097 Log.i("View", "Getting transparent region for: " + this); 8098 } 8099 final Region r = dr.getTransparentRegion(); 8100 final Rect db = dr.getBounds(); 8101 final AttachInfo attachInfo = mAttachInfo; 8102 if (r != null && attachInfo != null) { 8103 final int w = getRight()-getLeft(); 8104 final int h = getBottom()-getTop(); 8105 if (db.left > 0) { 8106 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 8107 r.op(0, 0, db.left, h, Region.Op.UNION); 8108 } 8109 if (db.right < w) { 8110 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 8111 r.op(db.right, 0, w, h, Region.Op.UNION); 8112 } 8113 if (db.top > 0) { 8114 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 8115 r.op(0, 0, w, db.top, Region.Op.UNION); 8116 } 8117 if (db.bottom < h) { 8118 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 8119 r.op(0, db.bottom, w, h, Region.Op.UNION); 8120 } 8121 final int[] location = attachInfo.mTransparentLocation; 8122 getLocationInWindow(location); 8123 r.translate(location[0], location[1]); 8124 region.op(r, Region.Op.INTERSECT); 8125 } else { 8126 region.op(db, Region.Op.DIFFERENCE); 8127 } 8128 } 8129 8130 private void postCheckForLongClick() { 8131 mHasPerformedLongPress = false; 8132 8133 if (mPendingCheckForLongPress == null) { 8134 mPendingCheckForLongPress = new CheckForLongPress(); 8135 } 8136 mPendingCheckForLongPress.rememberWindowAttachCount(); 8137 postDelayed(mPendingCheckForLongPress, ViewConfiguration.getLongPressTimeout()); 8138 } 8139 8140 private static int[] stateSetUnion(final int[] stateSet1, 8141 final int[] stateSet2) { 8142 final int stateSet1Length = stateSet1.length; 8143 final int stateSet2Length = stateSet2.length; 8144 final int[] newSet = new int[stateSet1Length + stateSet2Length]; 8145 int k = 0; 8146 int i = 0; 8147 int j = 0; 8148 // This is a merge of the two input state sets and assumes that the 8149 // input sets are sorted by the order imposed by ViewDrawableStates. 8150 for (int viewState : R.styleable.ViewDrawableStates) { 8151 if (i < stateSet1Length && stateSet1[i] == viewState) { 8152 newSet[k++] = viewState; 8153 i++; 8154 } else if (j < stateSet2Length && stateSet2[j] == viewState) { 8155 newSet[k++] = viewState; 8156 j++; 8157 } 8158 if (k > 1) { 8159 assert(newSet[k - 1] > newSet[k - 2]); 8160 } 8161 } 8162 return newSet; 8163 } 8164 8165 /** 8166 * Inflate a view from an XML resource. This convenience method wraps the {@link 8167 * LayoutInflater} class, which provides a full range of options for view inflation. 8168 * 8169 * @param context The Context object for your activity or application. 8170 * @param resource The resource ID to inflate 8171 * @param root A view group that will be the parent. Used to properly inflate the 8172 * layout_* parameters. 8173 * @see LayoutInflater 8174 */ 8175 public static View inflate(Context context, int resource, ViewGroup root) { 8176 LayoutInflater factory = LayoutInflater.from(context); 8177 return factory.inflate(resource, root); 8178 } 8179 8180 /** 8181 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 8182 * Each MeasureSpec represents a requirement for either the width or the height. 8183 * A MeasureSpec is comprised of a size and a mode. There are three possible 8184 * modes: 8185 * <dl> 8186 * <dt>UNSPECIFIED</dt> 8187 * <dd> 8188 * The parent has not imposed any constraint on the child. It can be whatever size 8189 * it wants. 8190 * </dd> 8191 * 8192 * <dt>EXACTLY</dt> 8193 * <dd> 8194 * The parent has determined an exact size for the child. The child is going to be 8195 * given those bounds regardless of how big it wants to be. 8196 * </dd> 8197 * 8198 * <dt>AT_MOST</dt> 8199 * <dd> 8200 * The child can be as large as it wants up to the specified size. 8201 * </dd> 8202 * </dl> 8203 * 8204 * MeasureSpecs are implemented as ints to reduce object allocation. This class 8205 * is provided to pack and unpack the <size, mode> tuple into the int. 8206 */ 8207 public static class MeasureSpec { 8208 private static final int MODE_SHIFT = 30; 8209 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 8210 8211 /** 8212 * Measure specification mode: The parent has not imposed any constraint 8213 * on the child. It can be whatever size it wants. 8214 */ 8215 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 8216 8217 /** 8218 * Measure specification mode: The parent has determined an exact size 8219 * for the child. The child is going to be given those bounds regardless 8220 * of how big it wants to be. 8221 */ 8222 public static final int EXACTLY = 1 << MODE_SHIFT; 8223 8224 /** 8225 * Measure specification mode: The child can be as large as it wants up 8226 * to the specified size. 8227 */ 8228 public static final int AT_MOST = 2 << MODE_SHIFT; 8229 8230 /** 8231 * Creates a measure specification based on the supplied size and mode. 8232 * 8233 * The mode must always be one of the following: 8234 * <ul> 8235 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 8236 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 8237 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 8238 * </ul> 8239 * 8240 * @param size the size of the measure specification 8241 * @param mode the mode of the measure specification 8242 * @return the measure specification based on size and mode 8243 */ 8244 public static int makeMeasureSpec(int size, int mode) { 8245 return size + mode; 8246 } 8247 8248 /** 8249 * Extracts the mode from the supplied measure specification. 8250 * 8251 * @param measureSpec the measure specification to extract the mode from 8252 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 8253 * {@link android.view.View.MeasureSpec#AT_MOST} or 8254 * {@link android.view.View.MeasureSpec#EXACTLY} 8255 */ 8256 public static int getMode(int measureSpec) { 8257 return (measureSpec & MODE_MASK); 8258 } 8259 8260 /** 8261 * Extracts the size from the supplied measure specification. 8262 * 8263 * @param measureSpec the measure specification to extract the size from 8264 * @return the size in pixels defined in the supplied measure specification 8265 */ 8266 public static int getSize(int measureSpec) { 8267 return (measureSpec & ~MODE_MASK); 8268 } 8269 8270 /** 8271 * Returns a String representation of the specified measure 8272 * specification. 8273 * 8274 * @param measureSpec the measure specification to convert to a String 8275 * @return a String with the following format: "MeasureSpec: MODE SIZE" 8276 */ 8277 public static String toString(int measureSpec) { 8278 int mode = getMode(measureSpec); 8279 int size = getSize(measureSpec); 8280 8281 StringBuilder sb = new StringBuilder("MeasureSpec: "); 8282 8283 if (mode == UNSPECIFIED) 8284 sb.append("UNSPECIFIED "); 8285 else if (mode == EXACTLY) 8286 sb.append("EXACTLY "); 8287 else if (mode == AT_MOST) 8288 sb.append("AT_MOST "); 8289 else 8290 sb.append(mode).append(" "); 8291 8292 sb.append(size); 8293 return sb.toString(); 8294 } 8295 } 8296 8297 class CheckForLongPress implements Runnable { 8298 8299 private int mOriginalWindowAttachCount; 8300 8301 public void run() { 8302 if (isPressed() && (mParent != null) 8303 && mOriginalWindowAttachCount == mWindowAttachCount) { 8304 if (performLongClick()) { 8305 mHasPerformedLongPress = true; 8306 } 8307 } 8308 } 8309 8310 public void rememberWindowAttachCount() { 8311 mOriginalWindowAttachCount = mWindowAttachCount; 8312 } 8313 } 8314 8315 /** 8316 * Interface definition for a callback to be invoked when a key event is 8317 * dispatched to this view. The callback will be invoked before the key 8318 * event is given to the view. 8319 */ 8320 public interface OnKeyListener { 8321 /** 8322 * Called when a key is dispatched to a view. This allows listeners to 8323 * get a chance to respond before the target view. 8324 * 8325 * @param v The view the key has been dispatched to. 8326 * @param keyCode The code for the physical key that was pressed 8327 * @param event The KeyEvent object containing full information about 8328 * the event. 8329 * @return True if the listener has consumed the event, false otherwise. 8330 */ 8331 boolean onKey(View v, int keyCode, KeyEvent event); 8332 } 8333 8334 /** 8335 * Interface definition for a callback to be invoked when a touch event is 8336 * dispatched to this view. The callback will be invoked before the touch 8337 * event is given to the view. 8338 */ 8339 public interface OnTouchListener { 8340 /** 8341 * Called when a touch event is dispatched to a view. This allows listeners to 8342 * get a chance to respond before the target view. 8343 * 8344 * @param v The view the touch event has been dispatched to. 8345 * @param event The MotionEvent object containing full information about 8346 * the event. 8347 * @return True if the listener has consumed the event, false otherwise. 8348 */ 8349 boolean onTouch(View v, MotionEvent event); 8350 } 8351 8352 /** 8353 * Interface definition for a callback to be invoked when a view has been clicked and held. 8354 */ 8355 public interface OnLongClickListener { 8356 /** 8357 * Called when a view has been clicked and held. 8358 * 8359 * @param v The view that was clicked and held. 8360 * 8361 * return True if the callback consumed the long click, false otherwise 8362 */ 8363 boolean onLongClick(View v); 8364 } 8365 8366 /** 8367 * Interface definition for a callback to be invoked when the focus state of 8368 * a view changed. 8369 */ 8370 public interface OnFocusChangeListener { 8371 /** 8372 * Called when the focus state of a view has changed. 8373 * 8374 * @param v The view whose state has changed. 8375 * @param hasFocus The new focus state of v. 8376 */ 8377 void onFocusChange(View v, boolean hasFocus); 8378 } 8379 8380 /** 8381 * Interface definition for a callback to be invoked when a view is clicked. 8382 */ 8383 public interface OnClickListener { 8384 /** 8385 * Called when a view has been clicked. 8386 * 8387 * @param v The view that was clicked. 8388 */ 8389 void onClick(View v); 8390 } 8391 8392 /** 8393 * Interface definition for a callback to be invoked when the context menu 8394 * for this view is being built. 8395 */ 8396 public interface OnCreateContextMenuListener { 8397 /** 8398 * Called when the context menu for this view is being built. It is not 8399 * safe to hold onto the menu after this method returns. 8400 * 8401 * @param menu The context menu that is being built 8402 * @param v The view for which the context menu is being built 8403 * @param menuInfo Extra information about the item for which the 8404 * context menu should be shown. This information will vary 8405 * depending on the class of v. 8406 */ 8407 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 8408 } 8409 8410 private final class UnsetPressedState implements Runnable { 8411 public void run() { 8412 setPressed(false); 8413 } 8414 } 8415 8416 /** 8417 * Base class for derived classes that want to save and restore their own 8418 * state in {@link android.view.View#onSaveInstanceState()}. 8419 */ 8420 public static class BaseSavedState extends AbsSavedState { 8421 /** 8422 * Constructor used when reading from a parcel. Reads the state of the superclass. 8423 * 8424 * @param source 8425 */ 8426 public BaseSavedState(Parcel source) { 8427 super(source); 8428 } 8429 8430 /** 8431 * Constructor called by derived classes when creating their SavedState objects 8432 * 8433 * @param superState The state of the superclass of this view 8434 */ 8435 public BaseSavedState(Parcelable superState) { 8436 super(superState); 8437 } 8438 8439 public static final Parcelable.Creator<BaseSavedState> CREATOR = 8440 new Parcelable.Creator<BaseSavedState>() { 8441 public BaseSavedState createFromParcel(Parcel in) { 8442 return new BaseSavedState(in); 8443 } 8444 8445 public BaseSavedState[] newArray(int size) { 8446 return new BaseSavedState[size]; 8447 } 8448 }; 8449 } 8450 8451 /** 8452 * A set of information given to a view when it is attached to its parent 8453 * window. 8454 */ 8455 static class AttachInfo { 8456 interface Callbacks { 8457 void playSoundEffect(int effectId); 8458 boolean performHapticFeedback(int effectId, boolean always); 8459 } 8460 8461 /** 8462 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 8463 * to a Handler. This class contains the target (View) to invalidate and 8464 * the coordinates of the dirty rectangle. 8465 * 8466 * For performance purposes, this class also implements a pool of up to 8467 * POOL_LIMIT objects that get reused. This reduces memory allocations 8468 * whenever possible. 8469 */ 8470 static class InvalidateInfo implements Poolable<InvalidateInfo> { 8471 private static final int POOL_LIMIT = 10; 8472 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 8473 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 8474 public InvalidateInfo newInstance() { 8475 return new InvalidateInfo(); 8476 } 8477 8478 public void onAcquired(InvalidateInfo element) { 8479 } 8480 8481 public void onReleased(InvalidateInfo element) { 8482 } 8483 }, POOL_LIMIT) 8484 ); 8485 8486 private InvalidateInfo mNext; 8487 8488 View target; 8489 8490 int left; 8491 int top; 8492 int right; 8493 int bottom; 8494 8495 public void setNextPoolable(InvalidateInfo element) { 8496 mNext = element; 8497 } 8498 8499 public InvalidateInfo getNextPoolable() { 8500 return mNext; 8501 } 8502 8503 static InvalidateInfo acquire() { 8504 return sPool.acquire(); 8505 } 8506 8507 void release() { 8508 sPool.release(this); 8509 } 8510 } 8511 8512 final IWindowSession mSession; 8513 8514 final IWindow mWindow; 8515 8516 final IBinder mWindowToken; 8517 8518 final Callbacks mRootCallbacks; 8519 8520 /** 8521 * The top view of the hierarchy. 8522 */ 8523 View mRootView; 8524 8525 IBinder mPanelParentWindowToken; 8526 Surface mSurface; 8527 8528 /** 8529 * Scale factor used by the compatibility mode 8530 */ 8531 float mApplicationScale; 8532 8533 /** 8534 * Indicates whether the application is in compatibility mode 8535 */ 8536 boolean mScalingRequired; 8537 8538 /** 8539 * Left position of this view's window 8540 */ 8541 int mWindowLeft; 8542 8543 /** 8544 * Top position of this view's window 8545 */ 8546 int mWindowTop; 8547 8548 /** 8549 * For windows that are full-screen but using insets to layout inside 8550 * of the screen decorations, these are the current insets for the 8551 * content of the window. 8552 */ 8553 final Rect mContentInsets = new Rect(); 8554 8555 /** 8556 * For windows that are full-screen but using insets to layout inside 8557 * of the screen decorations, these are the current insets for the 8558 * actual visible parts of the window. 8559 */ 8560 final Rect mVisibleInsets = new Rect(); 8561 8562 /** 8563 * The internal insets given by this window. This value is 8564 * supplied by the client (through 8565 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 8566 * be given to the window manager when changed to be used in laying 8567 * out windows behind it. 8568 */ 8569 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 8570 = new ViewTreeObserver.InternalInsetsInfo(); 8571 8572 /** 8573 * All views in the window's hierarchy that serve as scroll containers, 8574 * used to determine if the window can be resized or must be panned 8575 * to adjust for a soft input area. 8576 */ 8577 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 8578 8579 /** 8580 * Indicates whether the view's window currently has the focus. 8581 */ 8582 boolean mHasWindowFocus; 8583 8584 /** 8585 * The current visibility of the window. 8586 */ 8587 int mWindowVisibility; 8588 8589 /** 8590 * Indicates the time at which drawing started to occur. 8591 */ 8592 long mDrawingTime; 8593 8594 /** 8595 * Indicates whether or not ignoring the DIRTY_MASK flags. 8596 */ 8597 boolean mIgnoreDirtyState; 8598 8599 /** 8600 * Indicates whether the view's window is currently in touch mode. 8601 */ 8602 boolean mInTouchMode; 8603 8604 /** 8605 * Indicates that ViewRoot should trigger a global layout change 8606 * the next time it performs a traversal 8607 */ 8608 boolean mRecomputeGlobalAttributes; 8609 8610 /** 8611 * Set to true when attributes (like mKeepScreenOn) need to be 8612 * recomputed. 8613 */ 8614 boolean mAttributesChanged; 8615 8616 /** 8617 * Set during a traveral if any views want to keep the screen on. 8618 */ 8619 boolean mKeepScreenOn; 8620 8621 /** 8622 * Set if the visibility of any views has changed. 8623 */ 8624 boolean mViewVisibilityChanged; 8625 8626 /** 8627 * Set to true if a view has been scrolled. 8628 */ 8629 boolean mViewScrollChanged; 8630 8631 /** 8632 * Global to the view hierarchy used as a temporary for dealing with 8633 * x/y points in the transparent region computations. 8634 */ 8635 final int[] mTransparentLocation = new int[2]; 8636 8637 /** 8638 * Global to the view hierarchy used as a temporary for dealing with 8639 * x/y points in the ViewGroup.invalidateChild implementation. 8640 */ 8641 final int[] mInvalidateChildLocation = new int[2]; 8642 8643 /** 8644 * The view tree observer used to dispatch global events like 8645 * layout, pre-draw, touch mode change, etc. 8646 */ 8647 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 8648 8649 /** 8650 * A Canvas used by the view hierarchy to perform bitmap caching. 8651 */ 8652 Canvas mCanvas; 8653 8654 /** 8655 * A Handler supplied by a view's {@link android.view.ViewRoot}. This 8656 * handler can be used to pump events in the UI events queue. 8657 */ 8658 final Handler mHandler; 8659 8660 /** 8661 * Identifier for messages requesting the view to be invalidated. 8662 * Such messages should be sent to {@link #mHandler}. 8663 */ 8664 static final int INVALIDATE_MSG = 0x1; 8665 8666 /** 8667 * Identifier for messages requesting the view to invalidate a region. 8668 * Such messages should be sent to {@link #mHandler}. 8669 */ 8670 static final int INVALIDATE_RECT_MSG = 0x2; 8671 8672 /** 8673 * Temporary for use in computing invalidate rectangles while 8674 * calling up the hierarchy. 8675 */ 8676 final Rect mTmpInvalRect = new Rect(); 8677 8678 /** 8679 * Temporary list for use in collecting focusable descendents of a view. 8680 */ 8681 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 8682 8683 /** 8684 * Creates a new set of attachment information with the specified 8685 * events handler and thread. 8686 * 8687 * @param handler the events handler the view must use 8688 */ 8689 AttachInfo(IWindowSession session, IWindow window, 8690 Handler handler, Callbacks effectPlayer) { 8691 mSession = session; 8692 mWindow = window; 8693 mWindowToken = window.asBinder(); 8694 mHandler = handler; 8695 mRootCallbacks = effectPlayer; 8696 } 8697 } 8698 8699 /** 8700 * <p>ScrollabilityCache holds various fields used by a View when scrolling 8701 * is supported. This avoids keeping too many unused fields in most 8702 * instances of View.</p> 8703 */ 8704 private static class ScrollabilityCache { 8705 public int fadingEdgeLength; 8706 8707 public int scrollBarSize; 8708 public ScrollBarDrawable scrollBar; 8709 8710 public final Paint paint; 8711 public final Matrix matrix; 8712 public Shader shader; 8713 8714 private int mLastColor; 8715 8716 public ScrollabilityCache(ViewConfiguration configuration) { 8717 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 8718 scrollBarSize = configuration.getScaledScrollBarSize(); 8719 8720 paint = new Paint(); 8721 matrix = new Matrix(); 8722 // use use a height of 1, and then wack the matrix each time we 8723 // actually use it. 8724 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 8725 8726 paint.setShader(shader); 8727 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 8728 } 8729 8730 public void setFadeColor(int color) { 8731 if (color != 0 && color != mLastColor) { 8732 mLastColor = color; 8733 color |= 0xFF000000; 8734 8735 shader = new LinearGradient(0, 0, 0, 1, color, 0, Shader.TileMode.CLAMP); 8736 8737 paint.setShader(shader); 8738 // Restore the default transfer mode (src_over) 8739 paint.setXfermode(null); 8740 } 8741 } 8742 } 8743} 8744