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