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