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