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