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