blob: 6ff0fc83c22d534e52d88579d8bd603c63b7c18b [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 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002603
2604 if (mAttachInfo != null) {
2605 mAttachInfo.mKeyDispatchState.reset(this);
2606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 }
2608
2609 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002610 * {@inheritDoc}
2611 */
2612 public void sendAccessibilityEvent(int eventType) {
2613 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
2614 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
2615 }
2616 }
2617
2618 /**
2619 * {@inheritDoc}
2620 */
2621 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
2622 event.setClassName(getClass().getName());
2623 event.setPackageName(getContext().getPackageName());
2624 event.setEnabled(isEnabled());
2625 event.setContentDescription(mContentDescription);
2626
2627 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
2628 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
2629 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
2630 event.setItemCount(focusablesTempList.size());
2631 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
2632 focusablesTempList.clear();
2633 }
2634
2635 dispatchPopulateAccessibilityEvent(event);
2636
2637 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
2638 }
2639
2640 /**
2641 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
2642 * to be populated.
2643 *
2644 * @param event The event.
2645 *
2646 * @return True if the event population was completed.
2647 */
2648 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2649 return false;
2650 }
2651
2652 /**
2653 * Gets the {@link View} description. It briefly describes the view and is
2654 * primarily used for accessibility support. Set this property to enable
2655 * better accessibility support for your application. This is especially
2656 * true for views that do not have textual representation (For example,
2657 * ImageButton).
2658 *
2659 * @return The content descriptiopn.
2660 *
2661 * @attr ref android.R.styleable#View_contentDescription
2662 */
2663 public CharSequence getContentDescription() {
2664 return mContentDescription;
2665 }
2666
2667 /**
2668 * Sets the {@link View} description. It briefly describes the view and is
2669 * primarily used for accessibility support. Set this property to enable
2670 * better accessibility support for your application. This is especially
2671 * true for views that do not have textual representation (For example,
2672 * ImageButton).
2673 *
2674 * @param contentDescription The content description.
2675 *
2676 * @attr ref android.R.styleable#View_contentDescription
2677 */
2678 public void setContentDescription(CharSequence contentDescription) {
2679 mContentDescription = contentDescription;
2680 }
2681
2682 /**
Romain Guya2431d02009-04-30 16:30:00 -07002683 * Invoked whenever this view loses focus, either by losing window focus or by losing
2684 * focus within its window. This method can be used to clear any state tied to the
2685 * focus. For instance, if a button is held pressed with the trackball and the window
2686 * loses focus, this method can be used to cancel the press.
2687 *
2688 * Subclasses of View overriding this method should always call super.onFocusLost().
2689 *
2690 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07002691 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07002692 *
2693 * @hide pending API council approval
2694 */
2695 protected void onFocusLost() {
2696 resetPressedState();
2697 }
2698
2699 private void resetPressedState() {
2700 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
2701 return;
2702 }
2703
2704 if (isPressed()) {
2705 setPressed(false);
2706
2707 if (!mHasPerformedLongPress) {
2708 if (mPendingCheckForLongPress != null) {
2709 removeCallbacks(mPendingCheckForLongPress);
2710 }
2711 }
2712 }
2713 }
2714
2715 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 * Returns true if this view has focus
2717 *
2718 * @return True if this view has focus, false otherwise.
2719 */
2720 @ViewDebug.ExportedProperty
2721 public boolean isFocused() {
2722 return (mPrivateFlags & FOCUSED) != 0;
2723 }
2724
2725 /**
2726 * Find the view in the hierarchy rooted at this view that currently has
2727 * focus.
2728 *
2729 * @return The view that currently has focus, or null if no focused view can
2730 * be found.
2731 */
2732 public View findFocus() {
2733 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
2734 }
2735
2736 /**
2737 * Change whether this view is one of the set of scrollable containers in
2738 * its window. This will be used to determine whether the window can
2739 * resize or must pan when a soft input area is open -- scrollable
2740 * containers allow the window to use resize mode since the container
2741 * will appropriately shrink.
2742 */
2743 public void setScrollContainer(boolean isScrollContainer) {
2744 if (isScrollContainer) {
2745 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
2746 mAttachInfo.mScrollContainers.add(this);
2747 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
2748 }
2749 mPrivateFlags |= SCROLL_CONTAINER;
2750 } else {
2751 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
2752 mAttachInfo.mScrollContainers.remove(this);
2753 }
2754 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
2755 }
2756 }
2757
2758 /**
2759 * Returns the quality of the drawing cache.
2760 *
2761 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
2762 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
2763 *
2764 * @see #setDrawingCacheQuality(int)
2765 * @see #setDrawingCacheEnabled(boolean)
2766 * @see #isDrawingCacheEnabled()
2767 *
2768 * @attr ref android.R.styleable#View_drawingCacheQuality
2769 */
2770 public int getDrawingCacheQuality() {
2771 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
2772 }
2773
2774 /**
2775 * Set the drawing cache quality of this view. This value is used only when the
2776 * drawing cache is enabled
2777 *
2778 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
2779 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
2780 *
2781 * @see #getDrawingCacheQuality()
2782 * @see #setDrawingCacheEnabled(boolean)
2783 * @see #isDrawingCacheEnabled()
2784 *
2785 * @attr ref android.R.styleable#View_drawingCacheQuality
2786 */
2787 public void setDrawingCacheQuality(int quality) {
2788 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
2789 }
2790
2791 /**
2792 * Returns whether the screen should remain on, corresponding to the current
2793 * value of {@link #KEEP_SCREEN_ON}.
2794 *
2795 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
2796 *
2797 * @see #setKeepScreenOn(boolean)
2798 *
2799 * @attr ref android.R.styleable#View_keepScreenOn
2800 */
2801 public boolean getKeepScreenOn() {
2802 return (mViewFlags & KEEP_SCREEN_ON) != 0;
2803 }
2804
2805 /**
2806 * Controls whether the screen should remain on, modifying the
2807 * value of {@link #KEEP_SCREEN_ON}.
2808 *
2809 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
2810 *
2811 * @see #getKeepScreenOn()
2812 *
2813 * @attr ref android.R.styleable#View_keepScreenOn
2814 */
2815 public void setKeepScreenOn(boolean keepScreenOn) {
2816 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
2817 }
2818
2819 /**
2820 * @return The user specified next focus ID.
2821 *
2822 * @attr ref android.R.styleable#View_nextFocusLeft
2823 */
2824 public int getNextFocusLeftId() {
2825 return mNextFocusLeftId;
2826 }
2827
2828 /**
2829 * Set the id of the view to use for the next focus
2830 *
2831 * @param nextFocusLeftId
2832 *
2833 * @attr ref android.R.styleable#View_nextFocusLeft
2834 */
2835 public void setNextFocusLeftId(int nextFocusLeftId) {
2836 mNextFocusLeftId = nextFocusLeftId;
2837 }
2838
2839 /**
2840 * @return The user specified next focus ID.
2841 *
2842 * @attr ref android.R.styleable#View_nextFocusRight
2843 */
2844 public int getNextFocusRightId() {
2845 return mNextFocusRightId;
2846 }
2847
2848 /**
2849 * Set the id of the view to use for the next focus
2850 *
2851 * @param nextFocusRightId
2852 *
2853 * @attr ref android.R.styleable#View_nextFocusRight
2854 */
2855 public void setNextFocusRightId(int nextFocusRightId) {
2856 mNextFocusRightId = nextFocusRightId;
2857 }
2858
2859 /**
2860 * @return The user specified next focus ID.
2861 *
2862 * @attr ref android.R.styleable#View_nextFocusUp
2863 */
2864 public int getNextFocusUpId() {
2865 return mNextFocusUpId;
2866 }
2867
2868 /**
2869 * Set the id of the view to use for the next focus
2870 *
2871 * @param nextFocusUpId
2872 *
2873 * @attr ref android.R.styleable#View_nextFocusUp
2874 */
2875 public void setNextFocusUpId(int nextFocusUpId) {
2876 mNextFocusUpId = nextFocusUpId;
2877 }
2878
2879 /**
2880 * @return The user specified next focus ID.
2881 *
2882 * @attr ref android.R.styleable#View_nextFocusDown
2883 */
2884 public int getNextFocusDownId() {
2885 return mNextFocusDownId;
2886 }
2887
2888 /**
2889 * Set the id of the view to use for the next focus
2890 *
2891 * @param nextFocusDownId
2892 *
2893 * @attr ref android.R.styleable#View_nextFocusDown
2894 */
2895 public void setNextFocusDownId(int nextFocusDownId) {
2896 mNextFocusDownId = nextFocusDownId;
2897 }
2898
2899 /**
2900 * Returns the visibility of this view and all of its ancestors
2901 *
2902 * @return True if this view and all of its ancestors are {@link #VISIBLE}
2903 */
2904 public boolean isShown() {
2905 View current = this;
2906 //noinspection ConstantConditions
2907 do {
2908 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
2909 return false;
2910 }
2911 ViewParent parent = current.mParent;
2912 if (parent == null) {
2913 return false; // We are not attached to the view root
2914 }
2915 if (!(parent instanceof View)) {
2916 return true;
2917 }
2918 current = (View) parent;
2919 } while (current != null);
2920
2921 return false;
2922 }
2923
2924 /**
2925 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
2926 * is set
2927 *
2928 * @param insets Insets for system windows
2929 *
2930 * @return True if this view applied the insets, false otherwise
2931 */
2932 protected boolean fitSystemWindows(Rect insets) {
2933 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
2934 mPaddingLeft = insets.left;
2935 mPaddingTop = insets.top;
2936 mPaddingRight = insets.right;
2937 mPaddingBottom = insets.bottom;
2938 requestLayout();
2939 return true;
2940 }
2941 return false;
2942 }
2943
2944 /**
2945 * Returns the visibility status for this view.
2946 *
2947 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
2948 * @attr ref android.R.styleable#View_visibility
2949 */
2950 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002951 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
2952 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
2953 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 })
2955 public int getVisibility() {
2956 return mViewFlags & VISIBILITY_MASK;
2957 }
2958
2959 /**
2960 * Set the enabled state of this view.
2961 *
2962 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
2963 * @attr ref android.R.styleable#View_visibility
2964 */
2965 @RemotableViewMethod
2966 public void setVisibility(int visibility) {
2967 setFlags(visibility, VISIBILITY_MASK);
2968 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
2969 }
2970
2971 /**
2972 * Returns the enabled status for this view. The interpretation of the
2973 * enabled state varies by subclass.
2974 *
2975 * @return True if this view is enabled, false otherwise.
2976 */
2977 @ViewDebug.ExportedProperty
2978 public boolean isEnabled() {
2979 return (mViewFlags & ENABLED_MASK) == ENABLED;
2980 }
2981
2982 /**
2983 * Set the enabled state of this view. The interpretation of the enabled
2984 * state varies by subclass.
2985 *
2986 * @param enabled True if this view is enabled, false otherwise.
2987 */
2988 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07002989 if (enabled == isEnabled()) return;
2990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
2992
2993 /*
2994 * The View most likely has to change its appearance, so refresh
2995 * the drawable state.
2996 */
2997 refreshDrawableState();
2998
2999 // Invalidate too, since the default behavior for views is to be
3000 // be drawn at 50% alpha rather than to change the drawable.
3001 invalidate();
3002 }
3003
3004 /**
3005 * Set whether this view can receive the focus.
3006 *
3007 * Setting this to false will also ensure that this view is not focusable
3008 * in touch mode.
3009 *
3010 * @param focusable If true, this view can receive the focus.
3011 *
3012 * @see #setFocusableInTouchMode(boolean)
3013 * @attr ref android.R.styleable#View_focusable
3014 */
3015 public void setFocusable(boolean focusable) {
3016 if (!focusable) {
3017 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3018 }
3019 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3020 }
3021
3022 /**
3023 * Set whether this view can receive focus while in touch mode.
3024 *
3025 * Setting this to true will also ensure that this view is focusable.
3026 *
3027 * @param focusableInTouchMode If true, this view can receive the focus while
3028 * in touch mode.
3029 *
3030 * @see #setFocusable(boolean)
3031 * @attr ref android.R.styleable#View_focusableInTouchMode
3032 */
3033 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3034 // Focusable in touch mode should always be set before the focusable flag
3035 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3036 // which, in touch mode, will not successfully request focus on this view
3037 // because the focusable in touch mode flag is not set
3038 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3039 if (focusableInTouchMode) {
3040 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3041 }
3042 }
3043
3044 /**
3045 * Set whether this view should have sound effects enabled for events such as
3046 * clicking and touching.
3047 *
3048 * <p>You may wish to disable sound effects for a view if you already play sounds,
3049 * for instance, a dial key that plays dtmf tones.
3050 *
3051 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3052 * @see #isSoundEffectsEnabled()
3053 * @see #playSoundEffect(int)
3054 * @attr ref android.R.styleable#View_soundEffectsEnabled
3055 */
3056 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3057 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3058 }
3059
3060 /**
3061 * @return whether this view should have sound effects enabled for events such as
3062 * clicking and touching.
3063 *
3064 * @see #setSoundEffectsEnabled(boolean)
3065 * @see #playSoundEffect(int)
3066 * @attr ref android.R.styleable#View_soundEffectsEnabled
3067 */
3068 @ViewDebug.ExportedProperty
3069 public boolean isSoundEffectsEnabled() {
3070 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3071 }
3072
3073 /**
3074 * Set whether this view should have haptic feedback for events such as
3075 * long presses.
3076 *
3077 * <p>You may wish to disable haptic feedback if your view already controls
3078 * its own haptic feedback.
3079 *
3080 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3081 * @see #isHapticFeedbackEnabled()
3082 * @see #performHapticFeedback(int)
3083 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3084 */
3085 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3086 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3087 }
3088
3089 /**
3090 * @return whether this view should have haptic feedback enabled for events
3091 * long presses.
3092 *
3093 * @see #setHapticFeedbackEnabled(boolean)
3094 * @see #performHapticFeedback(int)
3095 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3096 */
3097 @ViewDebug.ExportedProperty
3098 public boolean isHapticFeedbackEnabled() {
3099 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3100 }
3101
3102 /**
3103 * If this view doesn't do any drawing on its own, set this flag to
3104 * allow further optimizations. By default, this flag is not set on
3105 * View, but could be set on some View subclasses such as ViewGroup.
3106 *
3107 * Typically, if you override {@link #onDraw} you should clear this flag.
3108 *
3109 * @param willNotDraw whether or not this View draw on its own
3110 */
3111 public void setWillNotDraw(boolean willNotDraw) {
3112 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3113 }
3114
3115 /**
3116 * Returns whether or not this View draws on its own.
3117 *
3118 * @return true if this view has nothing to draw, false otherwise
3119 */
3120 @ViewDebug.ExportedProperty
3121 public boolean willNotDraw() {
3122 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3123 }
3124
3125 /**
3126 * When a View's drawing cache is enabled, drawing is redirected to an
3127 * offscreen bitmap. Some views, like an ImageView, must be able to
3128 * bypass this mechanism if they already draw a single bitmap, to avoid
3129 * unnecessary usage of the memory.
3130 *
3131 * @param willNotCacheDrawing true if this view does not cache its
3132 * drawing, false otherwise
3133 */
3134 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3135 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3136 }
3137
3138 /**
3139 * Returns whether or not this View can cache its drawing or not.
3140 *
3141 * @return true if this view does not cache its drawing, false otherwise
3142 */
3143 @ViewDebug.ExportedProperty
3144 public boolean willNotCacheDrawing() {
3145 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3146 }
3147
3148 /**
3149 * Indicates whether this view reacts to click events or not.
3150 *
3151 * @return true if the view is clickable, false otherwise
3152 *
3153 * @see #setClickable(boolean)
3154 * @attr ref android.R.styleable#View_clickable
3155 */
3156 @ViewDebug.ExportedProperty
3157 public boolean isClickable() {
3158 return (mViewFlags & CLICKABLE) == CLICKABLE;
3159 }
3160
3161 /**
3162 * Enables or disables click events for this view. When a view
3163 * is clickable it will change its state to "pressed" on every click.
3164 * Subclasses should set the view clickable to visually react to
3165 * user's clicks.
3166 *
3167 * @param clickable true to make the view clickable, false otherwise
3168 *
3169 * @see #isClickable()
3170 * @attr ref android.R.styleable#View_clickable
3171 */
3172 public void setClickable(boolean clickable) {
3173 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3174 }
3175
3176 /**
3177 * Indicates whether this view reacts to long click events or not.
3178 *
3179 * @return true if the view is long clickable, false otherwise
3180 *
3181 * @see #setLongClickable(boolean)
3182 * @attr ref android.R.styleable#View_longClickable
3183 */
3184 public boolean isLongClickable() {
3185 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3186 }
3187
3188 /**
3189 * Enables or disables long click events for this view. When a view is long
3190 * clickable it reacts to the user holding down the button for a longer
3191 * duration than a tap. This event can either launch the listener or a
3192 * context menu.
3193 *
3194 * @param longClickable true to make the view long clickable, false otherwise
3195 * @see #isLongClickable()
3196 * @attr ref android.R.styleable#View_longClickable
3197 */
3198 public void setLongClickable(boolean longClickable) {
3199 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3200 }
3201
3202 /**
3203 * Sets the pressed that for this view.
3204 *
3205 * @see #isClickable()
3206 * @see #setClickable(boolean)
3207 *
3208 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3209 * the View's internal state from a previously set "pressed" state.
3210 */
3211 public void setPressed(boolean pressed) {
3212 if (pressed) {
3213 mPrivateFlags |= PRESSED;
3214 } else {
3215 mPrivateFlags &= ~PRESSED;
3216 }
3217 refreshDrawableState();
3218 dispatchSetPressed(pressed);
3219 }
3220
3221 /**
3222 * Dispatch setPressed to all of this View's children.
3223 *
3224 * @see #setPressed(boolean)
3225 *
3226 * @param pressed The new pressed state
3227 */
3228 protected void dispatchSetPressed(boolean pressed) {
3229 }
3230
3231 /**
3232 * Indicates whether the view is currently in pressed state. Unless
3233 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3234 * the pressed state.
3235 *
3236 * @see #setPressed
3237 * @see #isClickable()
3238 * @see #setClickable(boolean)
3239 *
3240 * @return true if the view is currently pressed, false otherwise
3241 */
3242 public boolean isPressed() {
3243 return (mPrivateFlags & PRESSED) == PRESSED;
3244 }
3245
3246 /**
3247 * Indicates whether this view will save its state (that is,
3248 * whether its {@link #onSaveInstanceState} method will be called).
3249 *
3250 * @return Returns true if the view state saving is enabled, else false.
3251 *
3252 * @see #setSaveEnabled(boolean)
3253 * @attr ref android.R.styleable#View_saveEnabled
3254 */
3255 public boolean isSaveEnabled() {
3256 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3257 }
3258
3259 /**
3260 * Controls whether the saving of this view's state is
3261 * enabled (that is, whether its {@link #onSaveInstanceState} method
3262 * will be called). Note that even if freezing is enabled, the
3263 * view still must have an id assigned to it (via {@link #setId setId()})
3264 * for its state to be saved. This flag can only disable the
3265 * saving of this view; any child views may still have their state saved.
3266 *
3267 * @param enabled Set to false to <em>disable</em> state saving, or true
3268 * (the default) to allow it.
3269 *
3270 * @see #isSaveEnabled()
3271 * @see #setId(int)
3272 * @see #onSaveInstanceState()
3273 * @attr ref android.R.styleable#View_saveEnabled
3274 */
3275 public void setSaveEnabled(boolean enabled) {
3276 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3277 }
3278
3279
3280 /**
3281 * Returns whether this View is able to take focus.
3282 *
3283 * @return True if this view can take focus, or false otherwise.
3284 * @attr ref android.R.styleable#View_focusable
3285 */
3286 @ViewDebug.ExportedProperty
3287 public final boolean isFocusable() {
3288 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3289 }
3290
3291 /**
3292 * When a view is focusable, it may not want to take focus when in touch mode.
3293 * For example, a button would like focus when the user is navigating via a D-pad
3294 * so that the user can click on it, but once the user starts touching the screen,
3295 * the button shouldn't take focus
3296 * @return Whether the view is focusable in touch mode.
3297 * @attr ref android.R.styleable#View_focusableInTouchMode
3298 */
3299 @ViewDebug.ExportedProperty
3300 public final boolean isFocusableInTouchMode() {
3301 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3302 }
3303
3304 /**
3305 * Find the nearest view in the specified direction that can take focus.
3306 * This does not actually give focus to that view.
3307 *
3308 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3309 *
3310 * @return The nearest focusable in the specified direction, or null if none
3311 * can be found.
3312 */
3313 public View focusSearch(int direction) {
3314 if (mParent != null) {
3315 return mParent.focusSearch(this, direction);
3316 } else {
3317 return null;
3318 }
3319 }
3320
3321 /**
3322 * This method is the last chance for the focused view and its ancestors to
3323 * respond to an arrow key. This is called when the focused view did not
3324 * consume the key internally, nor could the view system find a new view in
3325 * the requested direction to give focus to.
3326 *
3327 * @param focused The currently focused view.
3328 * @param direction The direction focus wants to move. One of FOCUS_UP,
3329 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3330 * @return True if the this view consumed this unhandled move.
3331 */
3332 public boolean dispatchUnhandledMove(View focused, int direction) {
3333 return false;
3334 }
3335
3336 /**
3337 * If a user manually specified the next view id for a particular direction,
3338 * use the root to look up the view. Once a view is found, it is cached
3339 * for future lookups.
3340 * @param root The root view of the hierarchy containing this view.
3341 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3342 * @return The user specified next view, or null if there is none.
3343 */
3344 View findUserSetNextFocus(View root, int direction) {
3345 switch (direction) {
3346 case FOCUS_LEFT:
3347 if (mNextFocusLeftId == View.NO_ID) return null;
3348 return findViewShouldExist(root, mNextFocusLeftId);
3349 case FOCUS_RIGHT:
3350 if (mNextFocusRightId == View.NO_ID) return null;
3351 return findViewShouldExist(root, mNextFocusRightId);
3352 case FOCUS_UP:
3353 if (mNextFocusUpId == View.NO_ID) return null;
3354 return findViewShouldExist(root, mNextFocusUpId);
3355 case FOCUS_DOWN:
3356 if (mNextFocusDownId == View.NO_ID) return null;
3357 return findViewShouldExist(root, mNextFocusDownId);
3358 }
3359 return null;
3360 }
3361
3362 private static View findViewShouldExist(View root, int childViewId) {
3363 View result = root.findViewById(childViewId);
3364 if (result == null) {
3365 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
3366 + "by user for id " + childViewId);
3367 }
3368 return result;
3369 }
3370
3371 /**
3372 * Find and return all focusable views that are descendants of this view,
3373 * possibly including this view if it is focusable itself.
3374 *
3375 * @param direction The direction of the focus
3376 * @return A list of focusable views
3377 */
3378 public ArrayList<View> getFocusables(int direction) {
3379 ArrayList<View> result = new ArrayList<View>(24);
3380 addFocusables(result, direction);
3381 return result;
3382 }
3383
3384 /**
3385 * Add any focusable views that are descendants of this view (possibly
3386 * including this view if it is focusable itself) to views. If we are in touch mode,
3387 * only add views that are also focusable in touch mode.
3388 *
3389 * @param views Focusable views found so far
3390 * @param direction The direction of the focus
3391 */
3392 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003393 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
3394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395
svetoslavganov75986cf2009-05-14 22:28:01 -07003396 /**
3397 * Adds any focusable views that are descendants of this view (possibly
3398 * including this view if it is focusable itself) to views. This method
3399 * adds all focusable views regardless if we are in touch mode or
3400 * only views focusable in touch mode if we are in touch mode depending on
3401 * the focusable mode paramater.
3402 *
3403 * @param views Focusable views found so far or null if all we are interested is
3404 * the number of focusables.
3405 * @param direction The direction of the focus.
3406 * @param focusableMode The type of focusables to be added.
3407 *
3408 * @see #FOCUSABLES_ALL
3409 * @see #FOCUSABLES_TOUCH_MODE
3410 */
3411 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
3412 if (!isFocusable()) {
3413 return;
3414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415
svetoslavganov75986cf2009-05-14 22:28:01 -07003416 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
3417 isInTouchMode() && !isFocusableInTouchMode()) {
3418 return;
3419 }
3420
3421 if (views != null) {
3422 views.add(this);
3423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 }
3425
3426 /**
3427 * Find and return all touchable views that are descendants of this view,
3428 * possibly including this view if it is touchable itself.
3429 *
3430 * @return A list of touchable views
3431 */
3432 public ArrayList<View> getTouchables() {
3433 ArrayList<View> result = new ArrayList<View>();
3434 addTouchables(result);
3435 return result;
3436 }
3437
3438 /**
3439 * Add any touchable views that are descendants of this view (possibly
3440 * including this view if it is touchable itself) to views.
3441 *
3442 * @param views Touchable views found so far
3443 */
3444 public void addTouchables(ArrayList<View> views) {
3445 final int viewFlags = mViewFlags;
3446
3447 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
3448 && (viewFlags & ENABLED_MASK) == ENABLED) {
3449 views.add(this);
3450 }
3451 }
3452
3453 /**
3454 * Call this to try to give focus to a specific view or to one of its
3455 * descendants.
3456 *
3457 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3458 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3459 * while the device is in touch mode.
3460 *
3461 * See also {@link #focusSearch}, which is what you call to say that you
3462 * have focus, and you want your parent to look for the next one.
3463 *
3464 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
3465 * {@link #FOCUS_DOWN} and <code>null</code>.
3466 *
3467 * @return Whether this view or one of its descendants actually took focus.
3468 */
3469 public final boolean requestFocus() {
3470 return requestFocus(View.FOCUS_DOWN);
3471 }
3472
3473
3474 /**
3475 * Call this to try to give focus to a specific view or to one of its
3476 * descendants and give it a hint about what direction focus is heading.
3477 *
3478 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3479 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3480 * while the device is in touch mode.
3481 *
3482 * See also {@link #focusSearch}, which is what you call to say that you
3483 * have focus, and you want your parent to look for the next one.
3484 *
3485 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
3486 * <code>null</code> set for the previously focused rectangle.
3487 *
3488 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3489 * @return Whether this view or one of its descendants actually took focus.
3490 */
3491 public final boolean requestFocus(int direction) {
3492 return requestFocus(direction, null);
3493 }
3494
3495 /**
3496 * Call this to try to give focus to a specific view or to one of its descendants
3497 * and give it hints about the direction and a specific rectangle that the focus
3498 * is coming from. The rectangle can help give larger views a finer grained hint
3499 * about where focus is coming from, and therefore, where to show selection, or
3500 * forward focus change internally.
3501 *
3502 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3503 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3504 * while the device is in touch mode.
3505 *
3506 * A View will not take focus if it is not visible.
3507 *
3508 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
3509 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
3510 *
3511 * See also {@link #focusSearch}, which is what you call to say that you
3512 * have focus, and you want your parent to look for the next one.
3513 *
3514 * You may wish to override this method if your custom {@link View} has an internal
3515 * {@link View} that it wishes to forward the request to.
3516 *
3517 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3518 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
3519 * to give a finer grained hint about where focus is coming from. May be null
3520 * if there is no hint.
3521 * @return Whether this view or one of its descendants actually took focus.
3522 */
3523 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
3524 // need to be focusable
3525 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
3526 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3527 return false;
3528 }
3529
3530 // need to be focusable in touch mode if in touch mode
3531 if (isInTouchMode() &&
3532 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
3533 return false;
3534 }
3535
3536 // need to not have any parents blocking us
3537 if (hasAncestorThatBlocksDescendantFocus()) {
3538 return false;
3539 }
3540
3541 handleFocusGainInternal(direction, previouslyFocusedRect);
3542 return true;
3543 }
3544
3545 /**
3546 * Call this to try to give focus to a specific view or to one of its descendants. This is a
3547 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
3548 * touch mode to request focus when they are touched.
3549 *
3550 * @return Whether this view or one of its descendants actually took focus.
3551 *
3552 * @see #isInTouchMode()
3553 *
3554 */
3555 public final boolean requestFocusFromTouch() {
3556 // Leave touch mode if we need to
3557 if (isInTouchMode()) {
3558 View root = getRootView();
3559 if (root != null) {
3560 ViewRoot viewRoot = (ViewRoot)root.getParent();
3561 if (viewRoot != null) {
3562 viewRoot.ensureTouchMode(false);
3563 }
3564 }
3565 }
3566 return requestFocus(View.FOCUS_DOWN);
3567 }
3568
3569 /**
3570 * @return Whether any ancestor of this view blocks descendant focus.
3571 */
3572 private boolean hasAncestorThatBlocksDescendantFocus() {
3573 ViewParent ancestor = mParent;
3574 while (ancestor instanceof ViewGroup) {
3575 final ViewGroup vgAncestor = (ViewGroup) ancestor;
3576 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
3577 return true;
3578 } else {
3579 ancestor = vgAncestor.getParent();
3580 }
3581 }
3582 return false;
3583 }
3584
3585 /**
3586 * This is called when a container is going to temporarily detach a child
3587 * that currently has focus, with
3588 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
3589 * It will either be followed by {@link #onFinishTemporaryDetach()} or
3590 * {@link #onDetachedFromWindow()} when the container is done. Generally
3591 * this is currently only done ListView for a view with focus.
3592 */
3593 public void onStartTemporaryDetach() {
3594 }
Romain Guy8506ab42009-06-11 17:35:47 -07003595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 /**
3597 * Called after {@link #onStartTemporaryDetach} when the container is done
3598 * changing the view.
3599 */
3600 public void onFinishTemporaryDetach() {
3601 }
Romain Guy8506ab42009-06-11 17:35:47 -07003602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003603 /**
3604 * capture information of this view for later analysis: developement only
3605 * check dynamic switch to make sure we only dump view
3606 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
3607 */
3608 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003609 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 return;
3611 }
3612 ViewDebug.dumpCapturedView(subTag, v);
3613 }
3614
3615 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003616 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
3617 * for this view's window. Returns null if the view is not currently attached
3618 * to the window. Normally you will not need to use this directly, but
3619 * just use the standard high-level event callbacks like {@link #onKeyDown}.
3620 */
3621 public KeyEvent.DispatcherState getKeyDispatcherState() {
3622 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
3623 }
3624
3625 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 * Dispatch a key event before it is processed by any input method
3627 * associated with the view hierarchy. This can be used to intercept
3628 * key events in special situations before the IME consumes them; a
3629 * typical example would be handling the BACK key to update the application's
3630 * UI instead of allowing the IME to see it and close itself.
3631 *
3632 * @param event The key event to be dispatched.
3633 * @return True if the event was handled, false otherwise.
3634 */
3635 public boolean dispatchKeyEventPreIme(KeyEvent event) {
3636 return onKeyPreIme(event.getKeyCode(), event);
3637 }
3638
3639 /**
3640 * Dispatch a key event to the next view on the focus path. This path runs
3641 * from the top of the view tree down to the currently focused view. If this
3642 * view has focus, it will dispatch to itself. Otherwise it will dispatch
3643 * the next node down the focus path. This method also fires any key
3644 * listeners.
3645 *
3646 * @param event The key event to be dispatched.
3647 * @return True if the event was handled, false otherwise.
3648 */
3649 public boolean dispatchKeyEvent(KeyEvent event) {
3650 // If any attached key listener a first crack at the event.
3651 //noinspection SimplifiableIfStatement
3652
3653 if (android.util.Config.LOGV) {
3654 captureViewInfo("captureViewKeyEvent", this);
3655 }
3656
3657 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
3658 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
3659 return true;
3660 }
3661
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003662 return event.dispatch(this, mAttachInfo != null
3663 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 }
3665
3666 /**
3667 * Dispatches a key shortcut event.
3668 *
3669 * @param event The key event to be dispatched.
3670 * @return True if the event was handled by the view, false otherwise.
3671 */
3672 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
3673 return onKeyShortcut(event.getKeyCode(), event);
3674 }
3675
3676 /**
3677 * Pass the touch screen motion event down to the target view, or this
3678 * view if it is the target.
3679 *
3680 * @param event The motion event to be dispatched.
3681 * @return True if the event was handled by the view, false otherwise.
3682 */
3683 public boolean dispatchTouchEvent(MotionEvent event) {
3684 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
3685 mOnTouchListener.onTouch(this, event)) {
3686 return true;
3687 }
3688 return onTouchEvent(event);
3689 }
3690
3691 /**
3692 * Pass a trackball motion event down to the focused view.
3693 *
3694 * @param event The motion event to be dispatched.
3695 * @return True if the event was handled by the view, false otherwise.
3696 */
3697 public boolean dispatchTrackballEvent(MotionEvent event) {
3698 //Log.i("view", "view=" + this + ", " + event.toString());
3699 return onTrackballEvent(event);
3700 }
3701
3702 /**
3703 * Called when the window containing this view gains or loses window focus.
3704 * ViewGroups should override to route to their children.
3705 *
3706 * @param hasFocus True if the window containing this view now has focus,
3707 * false otherwise.
3708 */
3709 public void dispatchWindowFocusChanged(boolean hasFocus) {
3710 onWindowFocusChanged(hasFocus);
3711 }
3712
3713 /**
3714 * Called when the window containing this view gains or loses focus. Note
3715 * that this is separate from view focus: to receive key events, both
3716 * your view and its window must have focus. If a window is displayed
3717 * on top of yours that takes input focus, then your own window will lose
3718 * focus but the view focus will remain unchanged.
3719 *
3720 * @param hasWindowFocus True if the window containing this view now has
3721 * focus, false otherwise.
3722 */
3723 public void onWindowFocusChanged(boolean hasWindowFocus) {
3724 InputMethodManager imm = InputMethodManager.peekInstance();
3725 if (!hasWindowFocus) {
3726 if (isPressed()) {
3727 setPressed(false);
3728 }
3729 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
3730 imm.focusOut(this);
3731 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003732 if (mPendingCheckForLongPress != null) {
3733 removeCallbacks(mPendingCheckForLongPress);
3734 }
Romain Guya2431d02009-04-30 16:30:00 -07003735 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
3737 imm.focusIn(this);
3738 }
3739 refreshDrawableState();
3740 }
3741
3742 /**
3743 * Returns true if this view is in a window that currently has window focus.
3744 * Note that this is not the same as the view itself having focus.
3745 *
3746 * @return True if this view is in a window that currently has window focus.
3747 */
3748 public boolean hasWindowFocus() {
3749 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
3750 }
3751
3752 /**
3753 * Dispatch a window visibility change down the view hierarchy.
3754 * ViewGroups should override to route to their children.
3755 *
3756 * @param visibility The new visibility of the window.
3757 *
3758 * @see #onWindowVisibilityChanged
3759 */
3760 public void dispatchWindowVisibilityChanged(int visibility) {
3761 onWindowVisibilityChanged(visibility);
3762 }
3763
3764 /**
3765 * Called when the window containing has change its visibility
3766 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
3767 * that this tells you whether or not your window is being made visible
3768 * to the window manager; this does <em>not</em> tell you whether or not
3769 * your window is obscured by other windows on the screen, even if it
3770 * is itself visible.
3771 *
3772 * @param visibility The new visibility of the window.
3773 */
3774 protected void onWindowVisibilityChanged(int visibility) {
3775 }
3776
3777 /**
3778 * Returns the current visibility of the window this view is attached to
3779 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
3780 *
3781 * @return Returns the current visibility of the view's window.
3782 */
3783 public int getWindowVisibility() {
3784 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
3785 }
3786
3787 /**
3788 * Retrieve the overall visible display size in which the window this view is
3789 * attached to has been positioned in. This takes into account screen
3790 * decorations above the window, for both cases where the window itself
3791 * is being position inside of them or the window is being placed under
3792 * then and covered insets are used for the window to position its content
3793 * inside. In effect, this tells you the available area where content can
3794 * be placed and remain visible to users.
3795 *
3796 * <p>This function requires an IPC back to the window manager to retrieve
3797 * the requested information, so should not be used in performance critical
3798 * code like drawing.
3799 *
3800 * @param outRect Filled in with the visible display frame. If the view
3801 * is not attached to a window, this is simply the raw display size.
3802 */
3803 public void getWindowVisibleDisplayFrame(Rect outRect) {
3804 if (mAttachInfo != null) {
3805 try {
3806 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
3807 } catch (RemoteException e) {
3808 return;
3809 }
3810 // XXX This is really broken, and probably all needs to be done
3811 // in the window manager, and we need to know more about whether
3812 // we want the area behind or in front of the IME.
3813 final Rect insets = mAttachInfo.mVisibleInsets;
3814 outRect.left += insets.left;
3815 outRect.top += insets.top;
3816 outRect.right -= insets.right;
3817 outRect.bottom -= insets.bottom;
3818 return;
3819 }
3820 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
3821 outRect.set(0, 0, d.getWidth(), d.getHeight());
3822 }
3823
3824 /**
3825 * Private function to aggregate all per-view attributes in to the view
3826 * root.
3827 */
3828 void dispatchCollectViewAttributes(int visibility) {
3829 performCollectViewAttributes(visibility);
3830 }
3831
3832 void performCollectViewAttributes(int visibility) {
3833 //noinspection PointlessBitwiseExpression
3834 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
3835 == (VISIBLE | KEEP_SCREEN_ON)) {
3836 mAttachInfo.mKeepScreenOn = true;
3837 }
3838 }
3839
3840 void needGlobalAttributesUpdate(boolean force) {
3841 AttachInfo ai = mAttachInfo;
3842 if (ai != null) {
3843 if (ai.mKeepScreenOn || force) {
3844 ai.mRecomputeGlobalAttributes = true;
3845 }
3846 }
3847 }
3848
3849 /**
3850 * Returns whether the device is currently in touch mode. Touch mode is entered
3851 * once the user begins interacting with the device by touch, and affects various
3852 * things like whether focus is always visible to the user.
3853 *
3854 * @return Whether the device is in touch mode.
3855 */
3856 @ViewDebug.ExportedProperty
3857 public boolean isInTouchMode() {
3858 if (mAttachInfo != null) {
3859 return mAttachInfo.mInTouchMode;
3860 } else {
3861 return ViewRoot.isInTouchMode();
3862 }
3863 }
3864
3865 /**
3866 * Returns the context the view is running in, through which it can
3867 * access the current theme, resources, etc.
3868 *
3869 * @return The view's Context.
3870 */
3871 @ViewDebug.CapturedViewProperty
3872 public final Context getContext() {
3873 return mContext;
3874 }
3875
3876 /**
3877 * Handle a key event before it is processed by any input method
3878 * associated with the view hierarchy. This can be used to intercept
3879 * key events in special situations before the IME consumes them; a
3880 * typical example would be handling the BACK key to update the application's
3881 * UI instead of allowing the IME to see it and close itself.
3882 *
3883 * @param keyCode The value in event.getKeyCode().
3884 * @param event Description of the key event.
3885 * @return If you handled the event, return true. If you want to allow the
3886 * event to be handled by the next receiver, return false.
3887 */
3888 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
3889 return false;
3890 }
3891
3892 /**
3893 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
3894 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
3895 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
3896 * is released, if the view is enabled and clickable.
3897 *
3898 * @param keyCode A key code that represents the button pressed, from
3899 * {@link android.view.KeyEvent}.
3900 * @param event The KeyEvent object that defines the button action.
3901 */
3902 public boolean onKeyDown(int keyCode, KeyEvent event) {
3903 boolean result = false;
3904
3905 switch (keyCode) {
3906 case KeyEvent.KEYCODE_DPAD_CENTER:
3907 case KeyEvent.KEYCODE_ENTER: {
3908 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3909 return true;
3910 }
3911 // Long clickable items don't necessarily have to be clickable
3912 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
3913 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
3914 (event.getRepeatCount() == 0)) {
3915 setPressed(true);
3916 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
3917 postCheckForLongClick();
3918 }
3919 return true;
3920 }
3921 break;
3922 }
3923 }
3924 return result;
3925 }
3926
3927 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003928 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
3929 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
3930 * the event).
3931 */
3932 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
3933 return false;
3934 }
3935
3936 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
3938 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
3939 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
3940 * {@link KeyEvent#KEYCODE_ENTER} is released.
3941 *
3942 * @param keyCode A key code that represents the button pressed, from
3943 * {@link android.view.KeyEvent}.
3944 * @param event The KeyEvent object that defines the button action.
3945 */
3946 public boolean onKeyUp(int keyCode, KeyEvent event) {
3947 boolean result = false;
3948
3949 switch (keyCode) {
3950 case KeyEvent.KEYCODE_DPAD_CENTER:
3951 case KeyEvent.KEYCODE_ENTER: {
3952 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3953 return true;
3954 }
3955 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
3956 setPressed(false);
3957
3958 if (!mHasPerformedLongPress) {
3959 // This is a tap, so remove the longpress check
3960 if (mPendingCheckForLongPress != null) {
3961 removeCallbacks(mPendingCheckForLongPress);
3962 }
3963
3964 result = performClick();
3965 }
3966 }
3967 break;
3968 }
3969 }
3970 return result;
3971 }
3972
3973 /**
3974 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
3975 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
3976 * the event).
3977 *
3978 * @param keyCode A key code that represents the button pressed, from
3979 * {@link android.view.KeyEvent}.
3980 * @param repeatCount The number of times the action was made.
3981 * @param event The KeyEvent object that defines the button action.
3982 */
3983 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
3984 return false;
3985 }
3986
3987 /**
3988 * Called when an unhandled key shortcut event occurs.
3989 *
3990 * @param keyCode The value in event.getKeyCode().
3991 * @param event Description of the key event.
3992 * @return If you handled the event, return true. If you want to allow the
3993 * event to be handled by the next receiver, return false.
3994 */
3995 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
3996 return false;
3997 }
3998
3999 /**
4000 * Check whether the called view is a text editor, in which case it
4001 * would make sense to automatically display a soft input window for
4002 * it. Subclasses should override this if they implement
4003 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004004 * a call on that method would return a non-null InputConnection, and
4005 * they are really a first-class editor that the user would normally
4006 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004007 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004008 * <p>The default implementation always returns false. This does
4009 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4010 * will not be called or the user can not otherwise perform edits on your
4011 * view; it is just a hint to the system that this is not the primary
4012 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004013 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 * @return Returns true if this view is a text editor, else false.
4015 */
4016 public boolean onCheckIsTextEditor() {
4017 return false;
4018 }
Romain Guy8506ab42009-06-11 17:35:47 -07004019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 /**
4021 * Create a new InputConnection for an InputMethod to interact
4022 * with the view. The default implementation returns null, since it doesn't
4023 * support input methods. You can override this to implement such support.
4024 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004025 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 * <p>When implementing this, you probably also want to implement
4027 * {@link #onCheckIsTextEditor()} to indicate you will return a
4028 * non-null InputConnection.
4029 *
4030 * @param outAttrs Fill in with attribute information about the connection.
4031 */
4032 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4033 return null;
4034 }
4035
4036 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004037 * Called by the {@link android.view.inputmethod.InputMethodManager}
4038 * when a view who is not the current
4039 * input connection target is trying to make a call on the manager. The
4040 * default implementation returns false; you can override this to return
4041 * true for certain views if you are performing InputConnection proxying
4042 * to them.
4043 * @param view The View that is making the InputMethodManager call.
4044 * @return Return true to allow the call, false to reject.
4045 */
4046 public boolean checkInputConnectionProxy(View view) {
4047 return false;
4048 }
Romain Guy8506ab42009-06-11 17:35:47 -07004049
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004050 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 * Show the context menu for this view. It is not safe to hold on to the
4052 * menu after returning from this method.
4053 *
4054 * @param menu The context menu to populate
4055 */
4056 public void createContextMenu(ContextMenu menu) {
4057 ContextMenuInfo menuInfo = getContextMenuInfo();
4058
4059 // Sets the current menu info so all items added to menu will have
4060 // my extra info set.
4061 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4062
4063 onCreateContextMenu(menu);
4064 if (mOnCreateContextMenuListener != null) {
4065 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4066 }
4067
4068 // Clear the extra information so subsequent items that aren't mine don't
4069 // have my extra info.
4070 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4071
4072 if (mParent != null) {
4073 mParent.createContextMenu(menu);
4074 }
4075 }
4076
4077 /**
4078 * Views should implement this if they have extra information to associate
4079 * with the context menu. The return result is supplied as a parameter to
4080 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4081 * callback.
4082 *
4083 * @return Extra information about the item for which the context menu
4084 * should be shown. This information will vary across different
4085 * subclasses of View.
4086 */
4087 protected ContextMenuInfo getContextMenuInfo() {
4088 return null;
4089 }
4090
4091 /**
4092 * Views should implement this if the view itself is going to add items to
4093 * the context menu.
4094 *
4095 * @param menu the context menu to populate
4096 */
4097 protected void onCreateContextMenu(ContextMenu menu) {
4098 }
4099
4100 /**
4101 * Implement this method to handle trackball motion events. The
4102 * <em>relative</em> movement of the trackball since the last event
4103 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4104 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4105 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4106 * they will often be fractional values, representing the more fine-grained
4107 * movement information available from a trackball).
4108 *
4109 * @param event The motion event.
4110 * @return True if the event was handled, false otherwise.
4111 */
4112 public boolean onTrackballEvent(MotionEvent event) {
4113 return false;
4114 }
4115
4116 /**
4117 * Implement this method to handle touch screen motion events.
4118 *
4119 * @param event The motion event.
4120 * @return True if the event was handled, false otherwise.
4121 */
4122 public boolean onTouchEvent(MotionEvent event) {
4123 final int viewFlags = mViewFlags;
4124
4125 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4126 // A disabled view that is clickable still consumes the touch
4127 // events, it just doesn't respond to them.
4128 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4129 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4130 }
4131
4132 if (mTouchDelegate != null) {
4133 if (mTouchDelegate.onTouchEvent(event)) {
4134 return true;
4135 }
4136 }
4137
4138 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4139 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4140 switch (event.getAction()) {
4141 case MotionEvent.ACTION_UP:
4142 if ((mPrivateFlags & PRESSED) != 0) {
4143 // take focus if we don't have it already and we should in
4144 // touch mode.
4145 boolean focusTaken = false;
4146 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4147 focusTaken = requestFocus();
4148 }
4149
4150 if (!mHasPerformedLongPress) {
4151 // This is a tap, so remove the longpress check
4152 if (mPendingCheckForLongPress != null) {
4153 removeCallbacks(mPendingCheckForLongPress);
4154 }
4155
4156 // Only perform take click actions if we were in the pressed state
4157 if (!focusTaken) {
4158 performClick();
4159 }
4160 }
4161
4162 if (mUnsetPressedState == null) {
4163 mUnsetPressedState = new UnsetPressedState();
4164 }
4165
4166 if (!post(mUnsetPressedState)) {
4167 // If the post failed, unpress right now
4168 mUnsetPressedState.run();
4169 }
4170 }
4171 break;
4172
4173 case MotionEvent.ACTION_DOWN:
4174 mPrivateFlags |= PRESSED;
4175 refreshDrawableState();
4176 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
4177 postCheckForLongClick();
4178 }
4179 break;
4180
4181 case MotionEvent.ACTION_CANCEL:
4182 mPrivateFlags &= ~PRESSED;
4183 refreshDrawableState();
4184 break;
4185
4186 case MotionEvent.ACTION_MOVE:
4187 final int x = (int) event.getX();
4188 final int y = (int) event.getY();
4189
4190 // Be lenient about moving outside of buttons
4191 int slop = ViewConfiguration.get(mContext).getScaledTouchSlop();
4192 if ((x < 0 - slop) || (x >= getWidth() + slop) ||
4193 (y < 0 - slop) || (y >= getHeight() + slop)) {
4194 // Outside button
4195 if ((mPrivateFlags & PRESSED) != 0) {
4196 // Remove any future long press checks
4197 if (mPendingCheckForLongPress != null) {
4198 removeCallbacks(mPendingCheckForLongPress);
4199 }
4200
4201 // Need to switch from pressed to not pressed
4202 mPrivateFlags &= ~PRESSED;
4203 refreshDrawableState();
4204 }
4205 } else {
4206 // Inside button
4207 if ((mPrivateFlags & PRESSED) == 0) {
4208 // Need to switch from not pressed to pressed
4209 mPrivateFlags |= PRESSED;
4210 refreshDrawableState();
4211 }
4212 }
4213 break;
4214 }
4215 return true;
4216 }
4217
4218 return false;
4219 }
4220
4221 /**
4222 * Cancels a pending long press. Your subclass can use this if you
4223 * want the context menu to come up if the user presses and holds
4224 * at the same place, but you don't want it to come up if they press
4225 * and then move around enough to cause scrolling.
4226 */
4227 public void cancelLongPress() {
4228 if (mPendingCheckForLongPress != null) {
4229 removeCallbacks(mPendingCheckForLongPress);
4230 }
4231 }
4232
4233 /**
4234 * Sets the TouchDelegate for this View.
4235 */
4236 public void setTouchDelegate(TouchDelegate delegate) {
4237 mTouchDelegate = delegate;
4238 }
4239
4240 /**
4241 * Gets the TouchDelegate for this View.
4242 */
4243 public TouchDelegate getTouchDelegate() {
4244 return mTouchDelegate;
4245 }
4246
4247 /**
4248 * Set flags controlling behavior of this view.
4249 *
4250 * @param flags Constant indicating the value which should be set
4251 * @param mask Constant indicating the bit range that should be changed
4252 */
4253 void setFlags(int flags, int mask) {
4254 int old = mViewFlags;
4255 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4256
4257 int changed = mViewFlags ^ old;
4258 if (changed == 0) {
4259 return;
4260 }
4261 int privateFlags = mPrivateFlags;
4262
4263 /* Check if the FOCUSABLE bit has changed */
4264 if (((changed & FOCUSABLE_MASK) != 0) &&
4265 ((privateFlags & HAS_BOUNDS) !=0)) {
4266 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4267 && ((privateFlags & FOCUSED) != 0)) {
4268 /* Give up focus if we are no longer focusable */
4269 clearFocus();
4270 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4271 && ((privateFlags & FOCUSED) == 0)) {
4272 /*
4273 * Tell the view system that we are now available to take focus
4274 * if no one else already has it.
4275 */
4276 if (mParent != null) mParent.focusableViewAvailable(this);
4277 }
4278 }
4279
4280 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4281 if ((changed & VISIBILITY_MASK) != 0) {
4282 /*
4283 * If this view is becoming visible, set the DRAWN flag so that
4284 * the next invalidate() will not be skipped.
4285 */
4286 mPrivateFlags |= DRAWN;
4287
4288 needGlobalAttributesUpdate(true);
4289
4290 // a view becoming visible is worth notifying the parent
4291 // about in case nothing has focus. even if this specific view
4292 // isn't focusable, it may contain something that is, so let
4293 // the root view try to give this focus if nothing else does.
4294 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4295 mParent.focusableViewAvailable(this);
4296 }
4297 }
4298 }
4299
4300 /* Check if the GONE bit has changed */
4301 if ((changed & GONE) != 0) {
4302 needGlobalAttributesUpdate(false);
4303 requestLayout();
4304 invalidate();
4305
4306 if (((mViewFlags & VISIBILITY_MASK) == GONE) && hasFocus()) {
4307 clearFocus();
4308 }
4309 if (mAttachInfo != null) {
4310 mAttachInfo.mViewVisibilityChanged = true;
4311 }
4312 }
4313
4314 /* Check if the VISIBLE bit has changed */
4315 if ((changed & INVISIBLE) != 0) {
4316 needGlobalAttributesUpdate(false);
4317 invalidate();
4318
4319 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
4320 // root view becoming invisible shouldn't clear focus
4321 if (getRootView() != this) {
4322 clearFocus();
4323 }
4324 }
4325 if (mAttachInfo != null) {
4326 mAttachInfo.mViewVisibilityChanged = true;
4327 }
4328 }
4329
4330 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
4331 destroyDrawingCache();
4332 }
4333
4334 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
4335 destroyDrawingCache();
4336 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4337 }
4338
4339 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
4340 destroyDrawingCache();
4341 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4342 }
4343
4344 if ((changed & DRAW_MASK) != 0) {
4345 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
4346 if (mBGDrawable != null) {
4347 mPrivateFlags &= ~SKIP_DRAW;
4348 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
4349 } else {
4350 mPrivateFlags |= SKIP_DRAW;
4351 }
4352 } else {
4353 mPrivateFlags &= ~SKIP_DRAW;
4354 }
4355 requestLayout();
4356 invalidate();
4357 }
4358
4359 if ((changed & KEEP_SCREEN_ON) != 0) {
4360 if (mParent != null) {
4361 mParent.recomputeViewAttributes(this);
4362 }
4363 }
4364 }
4365
4366 /**
4367 * Change the view's z order in the tree, so it's on top of other sibling
4368 * views
4369 */
4370 public void bringToFront() {
4371 if (mParent != null) {
4372 mParent.bringChildToFront(this);
4373 }
4374 }
4375
4376 /**
4377 * This is called in response to an internal scroll in this view (i.e., the
4378 * view scrolled its own contents). This is typically as a result of
4379 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
4380 * called.
4381 *
4382 * @param l Current horizontal scroll origin.
4383 * @param t Current vertical scroll origin.
4384 * @param oldl Previous horizontal scroll origin.
4385 * @param oldt Previous vertical scroll origin.
4386 */
4387 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4388 mBackgroundSizeChanged = true;
4389
4390 final AttachInfo ai = mAttachInfo;
4391 if (ai != null) {
4392 ai.mViewScrollChanged = true;
4393 }
4394 }
4395
4396 /**
4397 * This is called during layout when the size of this view has changed. If
4398 * you were just added to the view hierarchy, you're called with the old
4399 * values of 0.
4400 *
4401 * @param w Current width of this view.
4402 * @param h Current height of this view.
4403 * @param oldw Old width of this view.
4404 * @param oldh Old height of this view.
4405 */
4406 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
4407 }
4408
4409 /**
4410 * Called by draw to draw the child views. This may be overridden
4411 * by derived classes to gain control just before its children are drawn
4412 * (but after its own view has been drawn).
4413 * @param canvas the canvas on which to draw the view
4414 */
4415 protected void dispatchDraw(Canvas canvas) {
4416 }
4417
4418 /**
4419 * Gets the parent of this view. Note that the parent is a
4420 * ViewParent and not necessarily a View.
4421 *
4422 * @return Parent of this view.
4423 */
4424 public final ViewParent getParent() {
4425 return mParent;
4426 }
4427
4428 /**
4429 * Return the scrolled left position of this view. This is the left edge of
4430 * the displayed part of your view. You do not need to draw any pixels
4431 * farther left, since those are outside of the frame of your view on
4432 * screen.
4433 *
4434 * @return The left edge of the displayed part of your view, in pixels.
4435 */
4436 public final int getScrollX() {
4437 return mScrollX;
4438 }
4439
4440 /**
4441 * Return the scrolled top position of this view. This is the top edge of
4442 * the displayed part of your view. You do not need to draw any pixels above
4443 * it, since those are outside of the frame of your view on screen.
4444 *
4445 * @return The top edge of the displayed part of your view, in pixels.
4446 */
4447 public final int getScrollY() {
4448 return mScrollY;
4449 }
4450
4451 /**
4452 * Return the width of the your view.
4453 *
4454 * @return The width of your view, in pixels.
4455 */
4456 @ViewDebug.ExportedProperty
4457 public final int getWidth() {
4458 return mRight - mLeft;
4459 }
4460
4461 /**
4462 * Return the height of your view.
4463 *
4464 * @return The height of your view, in pixels.
4465 */
4466 @ViewDebug.ExportedProperty
4467 public final int getHeight() {
4468 return mBottom - mTop;
4469 }
4470
4471 /**
4472 * Return the visible drawing bounds of your view. Fills in the output
4473 * rectangle with the values from getScrollX(), getScrollY(),
4474 * getWidth(), and getHeight().
4475 *
4476 * @param outRect The (scrolled) drawing bounds of the view.
4477 */
4478 public void getDrawingRect(Rect outRect) {
4479 outRect.left = mScrollX;
4480 outRect.top = mScrollY;
4481 outRect.right = mScrollX + (mRight - mLeft);
4482 outRect.bottom = mScrollY + (mBottom - mTop);
4483 }
4484
4485 /**
4486 * The width of this view as measured in the most recent call to measure().
4487 * This should be used during measurement and layout calculations only. Use
4488 * {@link #getWidth()} to see how wide a view is after layout.
4489 *
4490 * @return The measured width of this view.
4491 */
4492 public final int getMeasuredWidth() {
4493 return mMeasuredWidth;
4494 }
4495
4496 /**
4497 * The height of this view as measured in the most recent call to measure().
4498 * This should be used during measurement and layout calculations only. Use
4499 * {@link #getHeight()} to see how tall a view is after layout.
4500 *
4501 * @return The measured height of this view.
4502 */
4503 public final int getMeasuredHeight() {
4504 return mMeasuredHeight;
4505 }
4506
4507 /**
4508 * Top position of this view relative to its parent.
4509 *
4510 * @return The top of this view, in pixels.
4511 */
4512 @ViewDebug.CapturedViewProperty
4513 public final int getTop() {
4514 return mTop;
4515 }
4516
4517 /**
4518 * Bottom position of this view relative to its parent.
4519 *
4520 * @return The bottom of this view, in pixels.
4521 */
4522 @ViewDebug.CapturedViewProperty
4523 public final int getBottom() {
4524 return mBottom;
4525 }
4526
4527 /**
4528 * Left position of this view relative to its parent.
4529 *
4530 * @return The left edge of this view, in pixels.
4531 */
4532 @ViewDebug.CapturedViewProperty
4533 public final int getLeft() {
4534 return mLeft;
4535 }
4536
4537 /**
4538 * Right position of this view relative to its parent.
4539 *
4540 * @return The right edge of this view, in pixels.
4541 */
4542 @ViewDebug.CapturedViewProperty
4543 public final int getRight() {
4544 return mRight;
4545 }
4546
4547 /**
4548 * Hit rectangle in parent's coordinates
4549 *
4550 * @param outRect The hit rectangle of the view.
4551 */
4552 public void getHitRect(Rect outRect) {
4553 outRect.set(mLeft, mTop, mRight, mBottom);
4554 }
4555
4556 /**
4557 * When a view has focus and the user navigates away from it, the next view is searched for
4558 * starting from the rectangle filled in by this method.
4559 *
4560 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
4561 * view maintains some idea of internal selection, such as a cursor, or a selected row
4562 * or column, you should override this method and fill in a more specific rectangle.
4563 *
4564 * @param r The rectangle to fill in, in this view's coordinates.
4565 */
4566 public void getFocusedRect(Rect r) {
4567 getDrawingRect(r);
4568 }
4569
4570 /**
4571 * If some part of this view is not clipped by any of its parents, then
4572 * return that area in r in global (root) coordinates. To convert r to local
4573 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
4574 * -globalOffset.y)) If the view is completely clipped or translated out,
4575 * return false.
4576 *
4577 * @param r If true is returned, r holds the global coordinates of the
4578 * visible portion of this view.
4579 * @param globalOffset If true is returned, globalOffset holds the dx,dy
4580 * between this view and its root. globalOffet may be null.
4581 * @return true if r is non-empty (i.e. part of the view is visible at the
4582 * root level.
4583 */
4584 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
4585 int width = mRight - mLeft;
4586 int height = mBottom - mTop;
4587 if (width > 0 && height > 0) {
4588 r.set(0, 0, width, height);
4589 if (globalOffset != null) {
4590 globalOffset.set(-mScrollX, -mScrollY);
4591 }
4592 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
4593 }
4594 return false;
4595 }
4596
4597 public final boolean getGlobalVisibleRect(Rect r) {
4598 return getGlobalVisibleRect(r, null);
4599 }
4600
4601 public final boolean getLocalVisibleRect(Rect r) {
4602 Point offset = new Point();
4603 if (getGlobalVisibleRect(r, offset)) {
4604 r.offset(-offset.x, -offset.y); // make r local
4605 return true;
4606 }
4607 return false;
4608 }
4609
4610 /**
4611 * Offset this view's vertical location by the specified number of pixels.
4612 *
4613 * @param offset the number of pixels to offset the view by
4614 */
4615 public void offsetTopAndBottom(int offset) {
4616 mTop += offset;
4617 mBottom += offset;
4618 }
4619
4620 /**
4621 * Offset this view's horizontal location by the specified amount of pixels.
4622 *
4623 * @param offset the numer of pixels to offset the view by
4624 */
4625 public void offsetLeftAndRight(int offset) {
4626 mLeft += offset;
4627 mRight += offset;
4628 }
4629
4630 /**
4631 * Get the LayoutParams associated with this view. All views should have
4632 * layout parameters. These supply parameters to the <i>parent</i> of this
4633 * view specifying how it should be arranged. There are many subclasses of
4634 * ViewGroup.LayoutParams, and these correspond to the different subclasses
4635 * of ViewGroup that are responsible for arranging their children.
4636 * @return The LayoutParams associated with this view
4637 */
4638 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
4639 public ViewGroup.LayoutParams getLayoutParams() {
4640 return mLayoutParams;
4641 }
4642
4643 /**
4644 * Set the layout parameters associated with this view. These supply
4645 * parameters to the <i>parent</i> of this view specifying how it should be
4646 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
4647 * correspond to the different subclasses of ViewGroup that are responsible
4648 * for arranging their children.
4649 *
4650 * @param params the layout parameters for this view
4651 */
4652 public void setLayoutParams(ViewGroup.LayoutParams params) {
4653 if (params == null) {
4654 throw new NullPointerException("params == null");
4655 }
4656 mLayoutParams = params;
4657 requestLayout();
4658 }
4659
4660 /**
4661 * Set the scrolled position of your view. This will cause a call to
4662 * {@link #onScrollChanged(int, int, int, int)} and the view will be
4663 * invalidated.
4664 * @param x the x position to scroll to
4665 * @param y the y position to scroll to
4666 */
4667 public void scrollTo(int x, int y) {
4668 if (mScrollX != x || mScrollY != y) {
4669 int oldX = mScrollX;
4670 int oldY = mScrollY;
4671 mScrollX = x;
4672 mScrollY = y;
4673 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
4674 invalidate();
4675 }
4676 }
4677
4678 /**
4679 * Move the scrolled position of your view. This will cause a call to
4680 * {@link #onScrollChanged(int, int, int, int)} and the view will be
4681 * invalidated.
4682 * @param x the amount of pixels to scroll by horizontally
4683 * @param y the amount of pixels to scroll by vertically
4684 */
4685 public void scrollBy(int x, int y) {
4686 scrollTo(mScrollX + x, mScrollY + y);
4687 }
4688
4689 /**
4690 * Mark the the area defined by dirty as needing to be drawn. If the view is
4691 * visible, {@link #onDraw} will be called at some point in the future.
4692 * This must be called from a UI thread. To call from a non-UI thread, call
4693 * {@link #postInvalidate()}.
4694 *
4695 * WARNING: This method is destructive to dirty.
4696 * @param dirty the rectangle representing the bounds of the dirty region
4697 */
4698 public void invalidate(Rect dirty) {
4699 if (ViewDebug.TRACE_HIERARCHY) {
4700 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
4701 }
4702
4703 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
4704 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4705 final ViewParent p = mParent;
4706 final AttachInfo ai = mAttachInfo;
4707 if (p != null && ai != null) {
4708 final int scrollX = mScrollX;
4709 final int scrollY = mScrollY;
4710 final Rect r = ai.mTmpInvalRect;
4711 r.set(dirty.left - scrollX, dirty.top - scrollY,
4712 dirty.right - scrollX, dirty.bottom - scrollY);
4713 mParent.invalidateChild(this, r);
4714 }
4715 }
4716 }
4717
4718 /**
4719 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
4720 * The coordinates of the dirty rect are relative to the view.
4721 * If the view is visible, {@link #onDraw} will be called at some point
4722 * in the future. This must be called from a UI thread. To call
4723 * from a non-UI thread, call {@link #postInvalidate()}.
4724 * @param l the left position of the dirty region
4725 * @param t the top position of the dirty region
4726 * @param r the right position of the dirty region
4727 * @param b the bottom position of the dirty region
4728 */
4729 public void invalidate(int l, int t, int r, int b) {
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 &= ~DRAWING_CACHE_VALID;
4736 final ViewParent p = mParent;
4737 final AttachInfo ai = mAttachInfo;
4738 if (p != null && ai != null && l < r && t < b) {
4739 final int scrollX = mScrollX;
4740 final int scrollY = mScrollY;
4741 final Rect tmpr = ai.mTmpInvalRect;
4742 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
4743 p.invalidateChild(this, tmpr);
4744 }
4745 }
4746 }
4747
4748 /**
4749 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
4750 * be called at some point in the future. This must be called from a
4751 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
4752 */
4753 public void invalidate() {
4754 if (ViewDebug.TRACE_HIERARCHY) {
4755 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
4756 }
4757
4758 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
4759 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
4760 final ViewParent p = mParent;
4761 final AttachInfo ai = mAttachInfo;
4762 if (p != null && ai != null) {
4763 final Rect r = ai.mTmpInvalRect;
4764 r.set(0, 0, mRight - mLeft, mBottom - mTop);
4765 // Don't call invalidate -- we don't want to internally scroll
4766 // our own bounds
4767 p.invalidateChild(this, r);
4768 }
4769 }
4770 }
4771
4772 /**
Romain Guy24443ea2009-05-11 11:56:30 -07004773 * Indicates whether this View is opaque. An opaque View guarantees that it will
4774 * draw all the pixels overlapping its bounds using a fully opaque color.
4775 *
4776 * Subclasses of View should override this method whenever possible to indicate
4777 * whether an instance is opaque. Opaque Views are treated in a special way by
4778 * the View hierarchy, possibly allowing it to perform optimizations during
4779 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07004780 *
Romain Guy24443ea2009-05-11 11:56:30 -07004781 * @return True if this View is guaranteed to be fully opaque, false otherwise.
4782 *
4783 * @hide Pending API council approval
4784 */
Romain Guy83b21072009-05-12 10:54:51 -07004785 @ViewDebug.ExportedProperty
Romain Guy24443ea2009-05-11 11:56:30 -07004786 public boolean isOpaque() {
Romain Guy8f1344f52009-05-15 16:03:59 -07004787 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK;
4788 }
4789
4790 private void computeOpaqueFlags() {
4791 // Opaque if:
4792 // - Has a background
4793 // - Background is opaque
4794 // - Doesn't have scrollbars or scrollbars are inside overlay
4795
4796 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
4797 mPrivateFlags |= OPAQUE_BACKGROUND;
4798 } else {
4799 mPrivateFlags &= ~OPAQUE_BACKGROUND;
4800 }
4801
4802 final int flags = mViewFlags;
4803 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
4804 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
4805 mPrivateFlags |= OPAQUE_SCROLLBARS;
4806 } else {
4807 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
4808 }
4809 }
4810
4811 /**
4812 * @hide
4813 */
4814 protected boolean hasOpaqueScrollbars() {
4815 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07004816 }
4817
4818 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004819 * @return A handler associated with the thread running the View. This
4820 * handler can be used to pump events in the UI events queue.
4821 */
4822 public Handler getHandler() {
4823 if (mAttachInfo != null) {
4824 return mAttachInfo.mHandler;
4825 }
4826 return null;
4827 }
4828
4829 /**
4830 * Causes the Runnable to be added to the message queue.
4831 * The runnable will be run on the user interface thread.
4832 *
4833 * @param action The Runnable that will be executed.
4834 *
4835 * @return Returns true if the Runnable was successfully placed in to the
4836 * message queue. Returns false on failure, usually because the
4837 * looper processing the message queue is exiting.
4838 */
4839 public boolean post(Runnable action) {
4840 Handler handler;
4841 if (mAttachInfo != null) {
4842 handler = mAttachInfo.mHandler;
4843 } else {
4844 // Assume that post will succeed later
4845 ViewRoot.getRunQueue().post(action);
4846 return true;
4847 }
4848
4849 return handler.post(action);
4850 }
4851
4852 /**
4853 * Causes the Runnable to be added to the message queue, to be run
4854 * after the specified amount of time elapses.
4855 * The runnable will be run on the user interface thread.
4856 *
4857 * @param action The Runnable that will be executed.
4858 * @param delayMillis The delay (in milliseconds) until the Runnable
4859 * will be executed.
4860 *
4861 * @return true if the Runnable was successfully placed in to the
4862 * message queue. Returns false on failure, usually because the
4863 * looper processing the message queue is exiting. Note that a
4864 * result of true does not mean the Runnable will be processed --
4865 * if the looper is quit before the delivery time of the message
4866 * occurs then the message will be dropped.
4867 */
4868 public boolean postDelayed(Runnable action, long delayMillis) {
4869 Handler handler;
4870 if (mAttachInfo != null) {
4871 handler = mAttachInfo.mHandler;
4872 } else {
4873 // Assume that post will succeed later
4874 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
4875 return true;
4876 }
4877
4878 return handler.postDelayed(action, delayMillis);
4879 }
4880
4881 /**
4882 * Removes the specified Runnable from the message queue.
4883 *
4884 * @param action The Runnable to remove from the message handling queue
4885 *
4886 * @return true if this view could ask the Handler to remove the Runnable,
4887 * false otherwise. When the returned value is true, the Runnable
4888 * may or may not have been actually removed from the message queue
4889 * (for instance, if the Runnable was not in the queue already.)
4890 */
4891 public boolean removeCallbacks(Runnable action) {
4892 Handler handler;
4893 if (mAttachInfo != null) {
4894 handler = mAttachInfo.mHandler;
4895 } else {
4896 // Assume that post will succeed later
4897 ViewRoot.getRunQueue().removeCallbacks(action);
4898 return true;
4899 }
4900
4901 handler.removeCallbacks(action);
4902 return true;
4903 }
4904
4905 /**
4906 * Cause an invalidate to happen on a subsequent cycle through the event loop.
4907 * Use this to invalidate the View from a non-UI thread.
4908 *
4909 * @see #invalidate()
4910 */
4911 public void postInvalidate() {
4912 postInvalidateDelayed(0);
4913 }
4914
4915 /**
4916 * Cause an invalidate of the specified area to happen on a subsequent cycle
4917 * through the event loop. Use this to invalidate the View from a non-UI thread.
4918 *
4919 * @param left The left coordinate of the rectangle to invalidate.
4920 * @param top The top coordinate of the rectangle to invalidate.
4921 * @param right The right coordinate of the rectangle to invalidate.
4922 * @param bottom The bottom coordinate of the rectangle to invalidate.
4923 *
4924 * @see #invalidate(int, int, int, int)
4925 * @see #invalidate(Rect)
4926 */
4927 public void postInvalidate(int left, int top, int right, int bottom) {
4928 postInvalidateDelayed(0, left, top, right, bottom);
4929 }
4930
4931 /**
4932 * Cause an invalidate to happen on a subsequent cycle through the event
4933 * loop. Waits for the specified amount of time.
4934 *
4935 * @param delayMilliseconds the duration in milliseconds to delay the
4936 * invalidation by
4937 */
4938 public void postInvalidateDelayed(long delayMilliseconds) {
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 Message msg = Message.obtain();
4943 msg.what = AttachInfo.INVALIDATE_MSG;
4944 msg.obj = this;
4945 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
4946 }
4947 }
4948
4949 /**
4950 * Cause an invalidate of the specified area to happen on a subsequent cycle
4951 * through the event loop. Waits for the specified amount of time.
4952 *
4953 * @param delayMilliseconds the duration in milliseconds to delay the
4954 * invalidation by
4955 * @param left The left coordinate of the rectangle to invalidate.
4956 * @param top The top coordinate of the rectangle to invalidate.
4957 * @param right The right coordinate of the rectangle to invalidate.
4958 * @param bottom The bottom coordinate of the rectangle to invalidate.
4959 */
4960 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
4961 int right, int bottom) {
4962
4963 // We try only with the AttachInfo because there's no point in invalidating
4964 // if we are not attached to our window
4965 if (mAttachInfo != null) {
4966 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
4967 info.target = this;
4968 info.left = left;
4969 info.top = top;
4970 info.right = right;
4971 info.bottom = bottom;
4972
4973 final Message msg = Message.obtain();
4974 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
4975 msg.obj = info;
4976 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
4977 }
4978 }
4979
4980 /**
4981 * Called by a parent to request that a child update its values for mScrollX
4982 * and mScrollY if necessary. This will typically be done if the child is
4983 * animating a scroll using a {@link android.widget.Scroller Scroller}
4984 * object.
4985 */
4986 public void computeScroll() {
4987 }
4988
4989 /**
4990 * <p>Indicate whether the horizontal edges are faded when the view is
4991 * scrolled horizontally.</p>
4992 *
4993 * @return true if the horizontal edges should are faded on scroll, false
4994 * otherwise
4995 *
4996 * @see #setHorizontalFadingEdgeEnabled(boolean)
4997 * @attr ref android.R.styleable#View_fadingEdge
4998 */
4999 public boolean isHorizontalFadingEdgeEnabled() {
5000 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
5001 }
5002
5003 /**
5004 * <p>Define whether the horizontal edges should be faded when this view
5005 * is scrolled horizontally.</p>
5006 *
5007 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
5008 * be faded when the view is scrolled
5009 * horizontally
5010 *
5011 * @see #isHorizontalFadingEdgeEnabled()
5012 * @attr ref android.R.styleable#View_fadingEdge
5013 */
5014 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
5015 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
5016 if (horizontalFadingEdgeEnabled) {
5017 initScrollCache();
5018 }
5019
5020 mViewFlags ^= FADING_EDGE_HORIZONTAL;
5021 }
5022 }
5023
5024 /**
5025 * <p>Indicate whether the vertical edges are faded when the view is
5026 * scrolled horizontally.</p>
5027 *
5028 * @return true if the vertical edges should are faded on scroll, false
5029 * otherwise
5030 *
5031 * @see #setVerticalFadingEdgeEnabled(boolean)
5032 * @attr ref android.R.styleable#View_fadingEdge
5033 */
5034 public boolean isVerticalFadingEdgeEnabled() {
5035 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
5036 }
5037
5038 /**
5039 * <p>Define whether the vertical edges should be faded when this view
5040 * is scrolled vertically.</p>
5041 *
5042 * @param verticalFadingEdgeEnabled true if the vertical edges should
5043 * be faded when the view is scrolled
5044 * vertically
5045 *
5046 * @see #isVerticalFadingEdgeEnabled()
5047 * @attr ref android.R.styleable#View_fadingEdge
5048 */
5049 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
5050 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
5051 if (verticalFadingEdgeEnabled) {
5052 initScrollCache();
5053 }
5054
5055 mViewFlags ^= FADING_EDGE_VERTICAL;
5056 }
5057 }
5058
5059 /**
5060 * Returns the strength, or intensity, of the top faded edge. The strength is
5061 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5062 * returns 0.0 or 1.0 but no value in between.
5063 *
5064 * Subclasses should override this method to provide a smoother fade transition
5065 * when scrolling occurs.
5066 *
5067 * @return the intensity of the top fade as a float between 0.0f and 1.0f
5068 */
5069 protected float getTopFadingEdgeStrength() {
5070 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
5071 }
5072
5073 /**
5074 * Returns the strength, or intensity, of the bottom faded edge. The strength is
5075 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5076 * returns 0.0 or 1.0 but no value in between.
5077 *
5078 * Subclasses should override this method to provide a smoother fade transition
5079 * when scrolling occurs.
5080 *
5081 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
5082 */
5083 protected float getBottomFadingEdgeStrength() {
5084 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
5085 computeVerticalScrollRange() ? 1.0f : 0.0f;
5086 }
5087
5088 /**
5089 * Returns the strength, or intensity, of the left faded edge. The strength is
5090 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5091 * returns 0.0 or 1.0 but no value in between.
5092 *
5093 * Subclasses should override this method to provide a smoother fade transition
5094 * when scrolling occurs.
5095 *
5096 * @return the intensity of the left fade as a float between 0.0f and 1.0f
5097 */
5098 protected float getLeftFadingEdgeStrength() {
5099 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
5100 }
5101
5102 /**
5103 * Returns the strength, or intensity, of the right faded edge. The strength is
5104 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5105 * returns 0.0 or 1.0 but no value in between.
5106 *
5107 * Subclasses should override this method to provide a smoother fade transition
5108 * when scrolling occurs.
5109 *
5110 * @return the intensity of the right fade as a float between 0.0f and 1.0f
5111 */
5112 protected float getRightFadingEdgeStrength() {
5113 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
5114 computeHorizontalScrollRange() ? 1.0f : 0.0f;
5115 }
5116
5117 /**
5118 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
5119 * scrollbar is not drawn by default.</p>
5120 *
5121 * @return true if the horizontal scrollbar should be painted, false
5122 * otherwise
5123 *
5124 * @see #setHorizontalScrollBarEnabled(boolean)
5125 */
5126 public boolean isHorizontalScrollBarEnabled() {
5127 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
5128 }
5129
5130 /**
5131 * <p>Define whether the horizontal scrollbar should be drawn or not. The
5132 * scrollbar is not drawn by default.</p>
5133 *
5134 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
5135 * be painted
5136 *
5137 * @see #isHorizontalScrollBarEnabled()
5138 */
5139 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
5140 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
5141 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07005142 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005143 recomputePadding();
5144 }
5145 }
5146
5147 /**
5148 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
5149 * scrollbar is not drawn by default.</p>
5150 *
5151 * @return true if the vertical scrollbar should be painted, false
5152 * otherwise
5153 *
5154 * @see #setVerticalScrollBarEnabled(boolean)
5155 */
5156 public boolean isVerticalScrollBarEnabled() {
5157 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
5158 }
5159
5160 /**
5161 * <p>Define whether the vertical scrollbar should be drawn or not. The
5162 * scrollbar is not drawn by default.</p>
5163 *
5164 * @param verticalScrollBarEnabled true if the vertical scrollbar should
5165 * be painted
5166 *
5167 * @see #isVerticalScrollBarEnabled()
5168 */
5169 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
5170 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
5171 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07005172 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 recomputePadding();
5174 }
5175 }
5176
5177 private void recomputePadding() {
5178 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
5179 }
5180
5181 /**
5182 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
5183 * inset. When inset, they add to the padding of the view. And the scrollbars
5184 * can be drawn inside the padding area or on the edge of the view. For example,
5185 * if a view has a background drawable and you want to draw the scrollbars
5186 * inside the padding specified by the drawable, you can use
5187 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
5188 * appear at the edge of the view, ignoring the padding, then you can use
5189 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
5190 * @param style the style of the scrollbars. Should be one of
5191 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
5192 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
5193 * @see #SCROLLBARS_INSIDE_OVERLAY
5194 * @see #SCROLLBARS_INSIDE_INSET
5195 * @see #SCROLLBARS_OUTSIDE_OVERLAY
5196 * @see #SCROLLBARS_OUTSIDE_INSET
5197 */
5198 public void setScrollBarStyle(int style) {
5199 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
5200 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07005201 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005202 recomputePadding();
5203 }
5204 }
5205
5206 /**
5207 * <p>Returns the current scrollbar style.</p>
5208 * @return the current scrollbar style
5209 * @see #SCROLLBARS_INSIDE_OVERLAY
5210 * @see #SCROLLBARS_INSIDE_INSET
5211 * @see #SCROLLBARS_OUTSIDE_OVERLAY
5212 * @see #SCROLLBARS_OUTSIDE_INSET
5213 */
5214 public int getScrollBarStyle() {
5215 return mViewFlags & SCROLLBARS_STYLE_MASK;
5216 }
5217
5218 /**
5219 * <p>Compute the horizontal range that the horizontal scrollbar
5220 * represents.</p>
5221 *
5222 * <p>The range is expressed in arbitrary units that must be the same as the
5223 * units used by {@link #computeHorizontalScrollExtent()} and
5224 * {@link #computeHorizontalScrollOffset()}.</p>
5225 *
5226 * <p>The default range is the drawing width of this view.</p>
5227 *
5228 * @return the total horizontal range represented by the horizontal
5229 * scrollbar
5230 *
5231 * @see #computeHorizontalScrollExtent()
5232 * @see #computeHorizontalScrollOffset()
5233 * @see android.widget.ScrollBarDrawable
5234 */
5235 protected int computeHorizontalScrollRange() {
5236 return getWidth();
5237 }
5238
5239 /**
5240 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
5241 * within the horizontal range. This value is used to compute the position
5242 * of the thumb within the scrollbar's track.</p>
5243 *
5244 * <p>The range is expressed in arbitrary units that must be the same as the
5245 * units used by {@link #computeHorizontalScrollRange()} and
5246 * {@link #computeHorizontalScrollExtent()}.</p>
5247 *
5248 * <p>The default offset is the scroll offset of this view.</p>
5249 *
5250 * @return the horizontal offset of the scrollbar's thumb
5251 *
5252 * @see #computeHorizontalScrollRange()
5253 * @see #computeHorizontalScrollExtent()
5254 * @see android.widget.ScrollBarDrawable
5255 */
5256 protected int computeHorizontalScrollOffset() {
5257 return mScrollX;
5258 }
5259
5260 /**
5261 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
5262 * within the horizontal range. This value is used to compute the length
5263 * of the thumb within the scrollbar's track.</p>
5264 *
5265 * <p>The range is expressed in arbitrary units that must be the same as the
5266 * units used by {@link #computeHorizontalScrollRange()} and
5267 * {@link #computeHorizontalScrollOffset()}.</p>
5268 *
5269 * <p>The default extent is the drawing width of this view.</p>
5270 *
5271 * @return the horizontal extent of the scrollbar's thumb
5272 *
5273 * @see #computeHorizontalScrollRange()
5274 * @see #computeHorizontalScrollOffset()
5275 * @see android.widget.ScrollBarDrawable
5276 */
5277 protected int computeHorizontalScrollExtent() {
5278 return getWidth();
5279 }
5280
5281 /**
5282 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
5283 *
5284 * <p>The range is expressed in arbitrary units that must be the same as the
5285 * units used by {@link #computeVerticalScrollExtent()} and
5286 * {@link #computeVerticalScrollOffset()}.</p>
5287 *
5288 * @return the total vertical range represented by the vertical scrollbar
5289 *
5290 * <p>The default range is the drawing height of this view.</p>
5291 *
5292 * @see #computeVerticalScrollExtent()
5293 * @see #computeVerticalScrollOffset()
5294 * @see android.widget.ScrollBarDrawable
5295 */
5296 protected int computeVerticalScrollRange() {
5297 return getHeight();
5298 }
5299
5300 /**
5301 * <p>Compute the vertical offset of the vertical scrollbar's thumb
5302 * within the horizontal range. This value is used to compute the position
5303 * of the thumb within the scrollbar's track.</p>
5304 *
5305 * <p>The range is expressed in arbitrary units that must be the same as the
5306 * units used by {@link #computeVerticalScrollRange()} and
5307 * {@link #computeVerticalScrollExtent()}.</p>
5308 *
5309 * <p>The default offset is the scroll offset of this view.</p>
5310 *
5311 * @return the vertical offset of the scrollbar's thumb
5312 *
5313 * @see #computeVerticalScrollRange()
5314 * @see #computeVerticalScrollExtent()
5315 * @see android.widget.ScrollBarDrawable
5316 */
5317 protected int computeVerticalScrollOffset() {
5318 return mScrollY;
5319 }
5320
5321 /**
5322 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
5323 * within the vertical range. This value is used to compute the length
5324 * of the thumb within the scrollbar's track.</p>
5325 *
5326 * <p>The range is expressed in arbitrary units that must be the same as the
5327 * units used by {@link #computeHorizontalScrollRange()} and
5328 * {@link #computeVerticalScrollOffset()}.</p>
5329 *
5330 * <p>The default extent is the drawing height of this view.</p>
5331 *
5332 * @return the vertical extent of the scrollbar's thumb
5333 *
5334 * @see #computeVerticalScrollRange()
5335 * @see #computeVerticalScrollOffset()
5336 * @see android.widget.ScrollBarDrawable
5337 */
5338 protected int computeVerticalScrollExtent() {
5339 return getHeight();
5340 }
5341
5342 /**
5343 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
5344 * scrollbars are painted only if they have been awakened first.</p>
5345 *
5346 * @param canvas the canvas on which to draw the scrollbars
5347 */
5348 private void onDrawScrollBars(Canvas canvas) {
5349 // scrollbars are drawn only when the animation is running
5350 final ScrollabilityCache cache = mScrollCache;
5351 if (cache != null) {
5352 final int viewFlags = mViewFlags;
5353
5354 final boolean drawHorizontalScrollBar =
5355 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
5356 final boolean drawVerticalScrollBar =
5357 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
5358 && !isVerticalScrollBarHidden();
5359
5360 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
5361 final int width = mRight - mLeft;
5362 final int height = mBottom - mTop;
5363
5364 final ScrollBarDrawable scrollBar = cache.scrollBar;
5365 int size = scrollBar.getSize(false);
5366 if (size <= 0) {
5367 size = cache.scrollBarSize;
5368 }
5369
Mike Reede8853fc2009-09-04 14:01:48 -04005370 final int scrollX = mScrollX;
5371 final int scrollY = mScrollY;
5372 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
5373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 if (drawHorizontalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04005375 scrollBar.setParameters(
5376 computeHorizontalScrollRange(),
5377 computeHorizontalScrollOffset(),
5378 computeHorizontalScrollExtent(), false);
5379 final int top = scrollY + height - size - (mUserPaddingBottom & inside);
5380 final int verticalScrollBarGap = drawVerticalScrollBar ?
5381 getVerticalScrollbarWidth() : 0;
5382 onDrawHorizontalScrollBar(canvas, scrollBar,
5383 scrollX + (mPaddingLeft & inside),
5384 top,
5385 scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap,
5386 top + size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 }
5388
5389 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04005390 scrollBar.setParameters(computeVerticalScrollRange(),
5391 computeVerticalScrollOffset(),
5392 computeVerticalScrollExtent(), true);
5393 // TODO: Deal with RTL languages to position scrollbar on left
5394 final int left = scrollX + width - size - (mUserPaddingRight & inside);
5395 onDrawVerticalScrollBar(canvas, scrollBar,
5396 left,
5397 scrollY + (mPaddingTop & inside),
5398 left + size,
5399 scrollY + height - (mUserPaddingBottom & inside));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005400 }
5401 }
5402 }
5403 }
Romain Guy8506ab42009-06-11 17:35:47 -07005404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005405 /**
Romain Guy8506ab42009-06-11 17:35:47 -07005406 * 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 -08005407 * FastScroller is visible.
5408 * @return whether to temporarily hide the vertical scrollbar
5409 * @hide
5410 */
5411 protected boolean isVerticalScrollBarHidden() {
5412 return false;
5413 }
5414
5415 /**
5416 * <p>Draw the horizontal scrollbar if
5417 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
5418 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419 * @param canvas the canvas on which to draw the scrollbar
5420 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005421 *
5422 * @see #isHorizontalScrollBarEnabled()
5423 * @see #computeHorizontalScrollRange()
5424 * @see #computeHorizontalScrollExtent()
5425 * @see #computeHorizontalScrollOffset()
5426 * @see android.widget.ScrollBarDrawable
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005427 * @hide
5428 */
Mike Reede8853fc2009-09-04 14:01:48 -04005429 protected void onDrawHorizontalScrollBar(Canvas canvas,
5430 Drawable scrollBar,
5431 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005432 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005433 scrollBar.draw(canvas);
5434 }
Mike Reede8853fc2009-09-04 14:01:48 -04005435
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005436 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005437 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
5438 * returns true.</p>
5439 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005440 * @param canvas the canvas on which to draw the scrollbar
5441 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005442 *
5443 * @see #isVerticalScrollBarEnabled()
5444 * @see #computeVerticalScrollRange()
5445 * @see #computeVerticalScrollExtent()
5446 * @see #computeVerticalScrollOffset()
5447 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04005448 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005449 */
Mike Reede8853fc2009-09-04 14:01:48 -04005450 protected void onDrawVerticalScrollBar(Canvas canvas,
5451 Drawable scrollBar,
5452 int l, int t, int r, int b) {
5453 scrollBar.setBounds(l, t, r, b);
5454 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 }
5456
5457 /**
5458 * Implement this to do your drawing.
5459 *
5460 * @param canvas the canvas on which the background will be drawn
5461 */
5462 protected void onDraw(Canvas canvas) {
5463 }
5464
5465 /*
5466 * Caller is responsible for calling requestLayout if necessary.
5467 * (This allows addViewInLayout to not request a new layout.)
5468 */
5469 void assignParent(ViewParent parent) {
5470 if (mParent == null) {
5471 mParent = parent;
5472 } else if (parent == null) {
5473 mParent = null;
5474 } else {
5475 throw new RuntimeException("view " + this + " being added, but"
5476 + " it already has a parent");
5477 }
5478 }
5479
5480 /**
5481 * This is called when the view is attached to a window. At this point it
5482 * has a Surface and will start drawing. Note that this function is
5483 * guaranteed to be called before {@link #onDraw}, however it may be called
5484 * any time before the first onDraw -- including before or after
5485 * {@link #onMeasure}.
5486 *
5487 * @see #onDetachedFromWindow()
5488 */
5489 protected void onAttachedToWindow() {
5490 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
5491 mParent.requestTransparentRegion(this);
5492 }
5493 }
5494
5495 /**
5496 * This is called when the view is detached from a window. At this point it
5497 * no longer has a surface for drawing.
5498 *
5499 * @see #onAttachedToWindow()
5500 */
5501 protected void onDetachedFromWindow() {
5502 if (mPendingCheckForLongPress != null) {
5503 removeCallbacks(mPendingCheckForLongPress);
5504 }
5505 destroyDrawingCache();
5506 }
5507
5508 /**
5509 * @return The number of times this view has been attached to a window
5510 */
5511 protected int getWindowAttachCount() {
5512 return mWindowAttachCount;
5513 }
5514
5515 /**
5516 * Retrieve a unique token identifying the window this view is attached to.
5517 * @return Return the window's token for use in
5518 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
5519 */
5520 public IBinder getWindowToken() {
5521 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
5522 }
5523
5524 /**
5525 * Retrieve a unique token identifying the top-level "real" window of
5526 * the window that this view is attached to. That is, this is like
5527 * {@link #getWindowToken}, except if the window this view in is a panel
5528 * window (attached to another containing window), then the token of
5529 * the containing window is returned instead.
5530 *
5531 * @return Returns the associated window token, either
5532 * {@link #getWindowToken()} or the containing window's token.
5533 */
5534 public IBinder getApplicationWindowToken() {
5535 AttachInfo ai = mAttachInfo;
5536 if (ai != null) {
5537 IBinder appWindowToken = ai.mPanelParentWindowToken;
5538 if (appWindowToken == null) {
5539 appWindowToken = ai.mWindowToken;
5540 }
5541 return appWindowToken;
5542 }
5543 return null;
5544 }
5545
5546 /**
5547 * Retrieve private session object this view hierarchy is using to
5548 * communicate with the window manager.
5549 * @return the session object to communicate with the window manager
5550 */
5551 /*package*/ IWindowSession getWindowSession() {
5552 return mAttachInfo != null ? mAttachInfo.mSession : null;
5553 }
5554
5555 /**
5556 * @param info the {@link android.view.View.AttachInfo} to associated with
5557 * this view
5558 */
5559 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
5560 //System.out.println("Attached! " + this);
5561 mAttachInfo = info;
5562 mWindowAttachCount++;
5563 if (mFloatingTreeObserver != null) {
5564 info.mTreeObserver.merge(mFloatingTreeObserver);
5565 mFloatingTreeObserver = null;
5566 }
5567 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
5568 mAttachInfo.mScrollContainers.add(this);
5569 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
5570 }
5571 performCollectViewAttributes(visibility);
5572 onAttachedToWindow();
5573 int vis = info.mWindowVisibility;
5574 if (vis != GONE) {
5575 onWindowVisibilityChanged(vis);
5576 }
5577 }
5578
5579 void dispatchDetachedFromWindow() {
5580 //System.out.println("Detached! " + this);
5581 AttachInfo info = mAttachInfo;
5582 if (info != null) {
5583 int vis = info.mWindowVisibility;
5584 if (vis != GONE) {
5585 onWindowVisibilityChanged(GONE);
5586 }
5587 }
5588
5589 onDetachedFromWindow();
5590 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
5591 mAttachInfo.mScrollContainers.remove(this);
5592 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
5593 }
5594 mAttachInfo = null;
5595 }
5596
5597 /**
5598 * Store this view hierarchy's frozen state into the given container.
5599 *
5600 * @param container The SparseArray in which to save the view's state.
5601 *
5602 * @see #restoreHierarchyState
5603 * @see #dispatchSaveInstanceState
5604 * @see #onSaveInstanceState
5605 */
5606 public void saveHierarchyState(SparseArray<Parcelable> container) {
5607 dispatchSaveInstanceState(container);
5608 }
5609
5610 /**
5611 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
5612 * May be overridden to modify how freezing happens to a view's children; for example, some
5613 * views may want to not store state for their children.
5614 *
5615 * @param container The SparseArray in which to save the view's state.
5616 *
5617 * @see #dispatchRestoreInstanceState
5618 * @see #saveHierarchyState
5619 * @see #onSaveInstanceState
5620 */
5621 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
5622 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
5623 mPrivateFlags &= ~SAVE_STATE_CALLED;
5624 Parcelable state = onSaveInstanceState();
5625 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
5626 throw new IllegalStateException(
5627 "Derived class did not call super.onSaveInstanceState()");
5628 }
5629 if (state != null) {
5630 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
5631 // + ": " + state);
5632 container.put(mID, state);
5633 }
5634 }
5635 }
5636
5637 /**
5638 * Hook allowing a view to generate a representation of its internal state
5639 * that can later be used to create a new instance with that same state.
5640 * This state should only contain information that is not persistent or can
5641 * not be reconstructed later. For example, you will never store your
5642 * current position on screen because that will be computed again when a
5643 * new instance of the view is placed in its view hierarchy.
5644 * <p>
5645 * Some examples of things you may store here: the current cursor position
5646 * in a text view (but usually not the text itself since that is stored in a
5647 * content provider or other persistent storage), the currently selected
5648 * item in a list view.
5649 *
5650 * @return Returns a Parcelable object containing the view's current dynamic
5651 * state, or null if there is nothing interesting to save. The
5652 * default implementation returns null.
5653 * @see #onRestoreInstanceState
5654 * @see #saveHierarchyState
5655 * @see #dispatchSaveInstanceState
5656 * @see #setSaveEnabled(boolean)
5657 */
5658 protected Parcelable onSaveInstanceState() {
5659 mPrivateFlags |= SAVE_STATE_CALLED;
5660 return BaseSavedState.EMPTY_STATE;
5661 }
5662
5663 /**
5664 * Restore this view hierarchy's frozen state from the given container.
5665 *
5666 * @param container The SparseArray which holds previously frozen states.
5667 *
5668 * @see #saveHierarchyState
5669 * @see #dispatchRestoreInstanceState
5670 * @see #onRestoreInstanceState
5671 */
5672 public void restoreHierarchyState(SparseArray<Parcelable> container) {
5673 dispatchRestoreInstanceState(container);
5674 }
5675
5676 /**
5677 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
5678 * children. May be overridden to modify how restoreing happens to a view's children; for
5679 * example, some views may want to not store state for their children.
5680 *
5681 * @param container The SparseArray which holds previously saved state.
5682 *
5683 * @see #dispatchSaveInstanceState
5684 * @see #restoreHierarchyState
5685 * @see #onRestoreInstanceState
5686 */
5687 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
5688 if (mID != NO_ID) {
5689 Parcelable state = container.get(mID);
5690 if (state != null) {
5691 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
5692 // + ": " + state);
5693 mPrivateFlags &= ~SAVE_STATE_CALLED;
5694 onRestoreInstanceState(state);
5695 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
5696 throw new IllegalStateException(
5697 "Derived class did not call super.onRestoreInstanceState()");
5698 }
5699 }
5700 }
5701 }
5702
5703 /**
5704 * Hook allowing a view to re-apply a representation of its internal state that had previously
5705 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
5706 * null state.
5707 *
5708 * @param state The frozen state that had previously been returned by
5709 * {@link #onSaveInstanceState}.
5710 *
5711 * @see #onSaveInstanceState
5712 * @see #restoreHierarchyState
5713 * @see #dispatchRestoreInstanceState
5714 */
5715 protected void onRestoreInstanceState(Parcelable state) {
5716 mPrivateFlags |= SAVE_STATE_CALLED;
5717 if (state != BaseSavedState.EMPTY_STATE && state != null) {
5718 throw new IllegalArgumentException("Wrong state class -- expecting View State");
5719 }
5720 }
5721
5722 /**
5723 * <p>Return the time at which the drawing of the view hierarchy started.</p>
5724 *
5725 * @return the drawing start time in milliseconds
5726 */
5727 public long getDrawingTime() {
5728 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
5729 }
5730
5731 /**
5732 * <p>Enables or disables the duplication of the parent's state into this view. When
5733 * duplication is enabled, this view gets its drawable state from its parent rather
5734 * than from its own internal properties.</p>
5735 *
5736 * <p>Note: in the current implementation, setting this property to true after the
5737 * view was added to a ViewGroup might have no effect at all. This property should
5738 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
5739 *
5740 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
5741 * property is enabled, an exception will be thrown.</p>
5742 *
5743 * @param enabled True to enable duplication of the parent's drawable state, false
5744 * to disable it.
5745 *
5746 * @see #getDrawableState()
5747 * @see #isDuplicateParentStateEnabled()
5748 */
5749 public void setDuplicateParentStateEnabled(boolean enabled) {
5750 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
5751 }
5752
5753 /**
5754 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
5755 *
5756 * @return True if this view's drawable state is duplicated from the parent,
5757 * false otherwise
5758 *
5759 * @see #getDrawableState()
5760 * @see #setDuplicateParentStateEnabled(boolean)
5761 */
5762 public boolean isDuplicateParentStateEnabled() {
5763 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
5764 }
5765
5766 /**
5767 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
5768 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
5769 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
5770 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
5771 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
5772 * null.</p>
5773 *
5774 * @param enabled true to enable the drawing cache, false otherwise
5775 *
5776 * @see #isDrawingCacheEnabled()
5777 * @see #getDrawingCache()
5778 * @see #buildDrawingCache()
5779 */
5780 public void setDrawingCacheEnabled(boolean enabled) {
5781 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
5782 }
5783
5784 /**
5785 * <p>Indicates whether the drawing cache is enabled for this view.</p>
5786 *
5787 * @return true if the drawing cache is enabled
5788 *
5789 * @see #setDrawingCacheEnabled(boolean)
5790 * @see #getDrawingCache()
5791 */
5792 @ViewDebug.ExportedProperty
5793 public boolean isDrawingCacheEnabled() {
5794 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
5795 }
5796
5797 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07005798 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
5799 *
5800 * @return A non-scaled bitmap representing this view or null if cache is disabled.
5801 *
5802 * @see #getDrawingCache(boolean)
5803 */
5804 public Bitmap getDrawingCache() {
5805 return getDrawingCache(false);
5806 }
5807
5808 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
5810 * is null when caching is disabled. If caching is enabled and the cache is not ready,
5811 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
5812 * draw from the cache when the cache is enabled. To benefit from the cache, you must
5813 * request the drawing cache by calling this method and draw it on screen if the
5814 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07005815 *
5816 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
5817 * this method will create a bitmap of the same size as this view. Because this bitmap
5818 * will be drawn scaled by the parent ViewGroup, the result on screen might show
5819 * scaling artifacts. To avoid such artifacts, you should call this method by setting
5820 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
5821 * size than the view. This implies that your application must be able to handle this
5822 * size.</p>
5823 *
5824 * @param autoScale Indicates whether the generated bitmap should be scaled based on
5825 * the current density of the screen when the application is in compatibility
5826 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005827 *
Romain Guyfbd8f692009-06-26 14:51:58 -07005828 * @return A bitmap representing this view or null if cache is disabled.
5829 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005830 * @see #setDrawingCacheEnabled(boolean)
5831 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07005832 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005833 * @see #destroyDrawingCache()
5834 */
Romain Guyfbd8f692009-06-26 14:51:58 -07005835 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
5837 return null;
5838 }
5839 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07005840 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841 }
Romain Guyfbd8f692009-06-26 14:51:58 -07005842 return autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) :
5843 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 }
5845
5846 /**
5847 * <p>Frees the resources used by the drawing cache. If you call
5848 * {@link #buildDrawingCache()} manually without calling
5849 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
5850 * should cleanup the cache with this method afterwards.</p>
5851 *
5852 * @see #setDrawingCacheEnabled(boolean)
5853 * @see #buildDrawingCache()
5854 * @see #getDrawingCache()
5855 */
5856 public void destroyDrawingCache() {
5857 if (mDrawingCache != null) {
5858 final Bitmap bitmap = mDrawingCache.get();
5859 if (bitmap != null) bitmap.recycle();
5860 mDrawingCache = null;
5861 }
Romain Guyfbd8f692009-06-26 14:51:58 -07005862 if (mUnscaledDrawingCache != null) {
5863 final Bitmap bitmap = mUnscaledDrawingCache.get();
5864 if (bitmap != null) bitmap.recycle();
5865 mUnscaledDrawingCache = null;
5866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 }
5868
5869 /**
5870 * Setting a solid background color for the drawing cache's bitmaps will improve
5871 * perfromance and memory usage. Note, though that this should only be used if this
5872 * view will always be drawn on top of a solid color.
5873 *
5874 * @param color The background color to use for the drawing cache's bitmap
5875 *
5876 * @see #setDrawingCacheEnabled(boolean)
5877 * @see #buildDrawingCache()
5878 * @see #getDrawingCache()
5879 */
5880 public void setDrawingCacheBackgroundColor(int color) {
5881 mDrawingCacheBackgroundColor = color;
5882 }
5883
5884 /**
5885 * @see #setDrawingCacheBackgroundColor(int)
5886 *
5887 * @return The background color to used for the drawing cache's bitmap
5888 */
5889 public int getDrawingCacheBackgroundColor() {
5890 return mDrawingCacheBackgroundColor;
5891 }
5892
5893 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07005894 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
5895 *
5896 * @see #buildDrawingCache(boolean)
5897 */
5898 public void buildDrawingCache() {
5899 buildDrawingCache(false);
5900 }
5901
5902 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005903 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
5904 *
5905 * <p>If you call {@link #buildDrawingCache()} manually without calling
5906 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
5907 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07005908 *
5909 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
5910 * this method will create a bitmap of the same size as this view. Because this bitmap
5911 * will be drawn scaled by the parent ViewGroup, the result on screen might show
5912 * scaling artifacts. To avoid such artifacts, you should call this method by setting
5913 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
5914 * size than the view. This implies that your application must be able to handle this
5915 * size.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005916 *
5917 * @see #getDrawingCache()
5918 * @see #destroyDrawingCache()
5919 */
Romain Guyfbd8f692009-06-26 14:51:58 -07005920 public void buildDrawingCache(boolean autoScale) {
5921 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
5922 (mDrawingCache == null || mDrawingCache.get() == null) :
5923 (mUnscaledDrawingCache == null || mUnscaledDrawingCache.get() == null))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005924
5925 if (ViewDebug.TRACE_HIERARCHY) {
5926 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
5927 }
Romain Guy13922e02009-05-12 17:56:14 -07005928 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005929 EventLog.writeEvent(60002, hashCode());
5930 }
5931
Romain Guy8506ab42009-06-11 17:35:47 -07005932 int width = mRight - mLeft;
5933 int height = mBottom - mTop;
5934
5935 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07005936 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07005937
Romain Guye1123222009-06-29 14:24:56 -07005938 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07005939 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
5940 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07005941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942
5943 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
5944 final boolean opaque = drawingCacheBackgroundColor != 0 ||
5945 (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE);
5946
5947 if (width <= 0 || height <= 0 ||
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07005948 (width * height * (opaque ? 2 : 4) > // Projected bitmap size in bytes
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005949 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
5950 destroyDrawingCache();
5951 return;
5952 }
5953
5954 boolean clear = true;
Romain Guyfbd8f692009-06-26 14:51:58 -07005955 Bitmap bitmap = autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) :
5956 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957
5958 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
5959
5960 Bitmap.Config quality;
5961 if (!opaque) {
5962 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
5963 case DRAWING_CACHE_QUALITY_AUTO:
5964 quality = Bitmap.Config.ARGB_8888;
5965 break;
5966 case DRAWING_CACHE_QUALITY_LOW:
5967 quality = Bitmap.Config.ARGB_4444;
5968 break;
5969 case DRAWING_CACHE_QUALITY_HIGH:
5970 quality = Bitmap.Config.ARGB_8888;
5971 break;
5972 default:
5973 quality = Bitmap.Config.ARGB_8888;
5974 break;
5975 }
5976 } else {
5977 quality = Bitmap.Config.RGB_565;
5978 }
5979
5980 // Try to cleanup memory
5981 if (bitmap != null) bitmap.recycle();
5982
5983 try {
5984 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07005985 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07005986 if (autoScale) {
5987 mDrawingCache = new SoftReference<Bitmap>(bitmap);
5988 } else {
5989 mUnscaledDrawingCache = new SoftReference<Bitmap>(bitmap);
5990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 } catch (OutOfMemoryError e) {
5992 // If there is not enough memory to create the bitmap cache, just
5993 // ignore the issue as bitmap caches are not required to draw the
5994 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07005995 if (autoScale) {
5996 mDrawingCache = null;
5997 } else {
5998 mUnscaledDrawingCache = null;
5999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006000 return;
6001 }
6002
6003 clear = drawingCacheBackgroundColor != 0;
6004 }
6005
6006 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 if (attachInfo != null) {
6008 canvas = attachInfo.mCanvas;
6009 if (canvas == null) {
6010 canvas = new Canvas();
6011 }
6012 canvas.setBitmap(bitmap);
6013 // Temporarily clobber the cached Canvas in case one of our children
6014 // is also using a drawing cache. Without this, the children would
6015 // steal the canvas by attaching their own bitmap to it and bad, bad
6016 // thing would happen (invisible views, corrupted drawings, etc.)
6017 attachInfo.mCanvas = null;
6018 } else {
6019 // This case should hopefully never or seldom happen
6020 canvas = new Canvas(bitmap);
6021 }
6022
6023 if (clear) {
6024 bitmap.eraseColor(drawingCacheBackgroundColor);
6025 }
6026
6027 computeScroll();
6028 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07006029
Romain Guye1123222009-06-29 14:24:56 -07006030 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07006031 final float scale = attachInfo.mApplicationScale;
6032 canvas.scale(scale, scale);
6033 }
6034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 canvas.translate(-mScrollX, -mScrollY);
6036
Romain Guy5bcdff42009-05-14 21:27:18 -07006037 mPrivateFlags |= DRAWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038
6039 // Fast path for layouts with no backgrounds
6040 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
6041 if (ViewDebug.TRACE_HIERARCHY) {
6042 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
6043 }
Romain Guy5bcdff42009-05-14 21:27:18 -07006044 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 dispatchDraw(canvas);
6046 } else {
6047 draw(canvas);
6048 }
6049
6050 canvas.restoreToCount(restoreCount);
6051
6052 if (attachInfo != null) {
6053 // Restore the cached Canvas for our siblings
6054 attachInfo.mCanvas = canvas;
6055 }
6056 mPrivateFlags |= DRAWING_CACHE_VALID;
6057 }
6058 }
6059
6060 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006061 * Create a snapshot of the view into a bitmap. We should probably make
6062 * some form of this public, but should think about the API.
6063 */
Romain Guya2431d02009-04-30 16:30:00 -07006064 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006065 int width = mRight - mLeft;
6066 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006067
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006068 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07006069 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006070 width = (int) ((width * scale) + 0.5f);
6071 height = (int) ((height * scale) + 0.5f);
6072
Romain Guy8c11e312009-09-14 15:15:30 -07006073 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006074 if (bitmap == null) {
6075 throw new OutOfMemoryError();
6076 }
6077
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006078 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
6079
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006080 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006081 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();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006103 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006104 canvas.translate(-mScrollX, -mScrollY);
6105
Romain Guy5bcdff42009-05-14 21:27:18 -07006106 // Temporarily remove the dirty mask
6107 int flags = mPrivateFlags;
6108 mPrivateFlags &= ~DIRTY_MASK;
6109
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006110 // Fast path for layouts with no backgrounds
6111 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
6112 dispatchDraw(canvas);
6113 } else {
6114 draw(canvas);
6115 }
6116
Romain Guy5bcdff42009-05-14 21:27:18 -07006117 mPrivateFlags = flags;
6118
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006119 canvas.restoreToCount(restoreCount);
6120
6121 if (attachInfo != null) {
6122 // Restore the cached Canvas for our siblings
6123 attachInfo.mCanvas = canvas;
6124 }
Romain Guy8506ab42009-06-11 17:35:47 -07006125
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006126 return bitmap;
6127 }
6128
6129 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006130 * Indicates whether this View is currently in edit mode. A View is usually
6131 * in edit mode when displayed within a developer tool. For instance, if
6132 * this View is being drawn by a visual user interface builder, this method
6133 * should return true.
6134 *
6135 * Subclasses should check the return value of this method to provide
6136 * different behaviors if their normal behavior might interfere with the
6137 * host environment. For instance: the class spawns a thread in its
6138 * constructor, the drawing code relies on device-specific features, etc.
6139 *
6140 * This method is usually checked in the drawing code of custom widgets.
6141 *
6142 * @return True if this View is in edit mode, false otherwise.
6143 */
6144 public boolean isInEditMode() {
6145 return false;
6146 }
6147
6148 /**
6149 * If the View draws content inside its padding and enables fading edges,
6150 * it needs to support padding offsets. Padding offsets are added to the
6151 * fading edges to extend the length of the fade so that it covers pixels
6152 * drawn inside the padding.
6153 *
6154 * Subclasses of this class should override this method if they need
6155 * to draw content inside the padding.
6156 *
6157 * @return True if padding offset must be applied, false otherwise.
6158 *
6159 * @see #getLeftPaddingOffset()
6160 * @see #getRightPaddingOffset()
6161 * @see #getTopPaddingOffset()
6162 * @see #getBottomPaddingOffset()
6163 *
6164 * @since CURRENT
6165 */
6166 protected boolean isPaddingOffsetRequired() {
6167 return false;
6168 }
6169
6170 /**
6171 * Amount by which to extend the left fading region. Called only when
6172 * {@link #isPaddingOffsetRequired()} returns true.
6173 *
6174 * @return The left padding offset in pixels.
6175 *
6176 * @see #isPaddingOffsetRequired()
6177 *
6178 * @since CURRENT
6179 */
6180 protected int getLeftPaddingOffset() {
6181 return 0;
6182 }
6183
6184 /**
6185 * Amount by which to extend the right fading region. Called only when
6186 * {@link #isPaddingOffsetRequired()} returns true.
6187 *
6188 * @return The right padding offset in pixels.
6189 *
6190 * @see #isPaddingOffsetRequired()
6191 *
6192 * @since CURRENT
6193 */
6194 protected int getRightPaddingOffset() {
6195 return 0;
6196 }
6197
6198 /**
6199 * Amount by which to extend the top fading region. Called only when
6200 * {@link #isPaddingOffsetRequired()} returns true.
6201 *
6202 * @return The top padding offset in pixels.
6203 *
6204 * @see #isPaddingOffsetRequired()
6205 *
6206 * @since CURRENT
6207 */
6208 protected int getTopPaddingOffset() {
6209 return 0;
6210 }
6211
6212 /**
6213 * Amount by which to extend the bottom fading region. Called only when
6214 * {@link #isPaddingOffsetRequired()} returns true.
6215 *
6216 * @return The bottom padding offset in pixels.
6217 *
6218 * @see #isPaddingOffsetRequired()
6219 *
6220 * @since CURRENT
6221 */
6222 protected int getBottomPaddingOffset() {
6223 return 0;
6224 }
6225
6226 /**
6227 * Manually render this view (and all of its children) to the given Canvas.
6228 * The view must have already done a full layout before this function is
6229 * called. When implementing a view, do not override this method; instead,
6230 * you should implement {@link #onDraw}.
6231 *
6232 * @param canvas The Canvas to which the View is rendered.
6233 */
6234 public void draw(Canvas canvas) {
6235 if (ViewDebug.TRACE_HIERARCHY) {
6236 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
6237 }
6238
Romain Guy5bcdff42009-05-14 21:27:18 -07006239 final int privateFlags = mPrivateFlags;
6240 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
6241 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
6242 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07006243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 /*
6245 * Draw traversal performs several drawing steps which must be executed
6246 * in the appropriate order:
6247 *
6248 * 1. Draw the background
6249 * 2. If necessary, save the canvas' layers to prepare for fading
6250 * 3. Draw view's content
6251 * 4. Draw children
6252 * 5. If necessary, draw the fading edges and restore layers
6253 * 6. Draw decorations (scrollbars for instance)
6254 */
6255
6256 // Step 1, draw the background, if needed
6257 int saveCount;
6258
Romain Guy24443ea2009-05-11 11:56:30 -07006259 if (!dirtyOpaque) {
6260 final Drawable background = mBGDrawable;
6261 if (background != null) {
6262 final int scrollX = mScrollX;
6263 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264
Romain Guy24443ea2009-05-11 11:56:30 -07006265 if (mBackgroundSizeChanged) {
6266 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
6267 mBackgroundSizeChanged = false;
6268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269
Romain Guy24443ea2009-05-11 11:56:30 -07006270 if ((scrollX | scrollY) == 0) {
6271 background.draw(canvas);
6272 } else {
6273 canvas.translate(scrollX, scrollY);
6274 background.draw(canvas);
6275 canvas.translate(-scrollX, -scrollY);
6276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 }
6278 }
6279
6280 // skip step 2 & 5 if possible (common case)
6281 final int viewFlags = mViewFlags;
6282 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
6283 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
6284 if (!verticalEdges && !horizontalEdges) {
6285 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07006286 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006287
6288 // Step 4, draw the children
6289 dispatchDraw(canvas);
6290
6291 // Step 6, draw decorations (scrollbars)
6292 onDrawScrollBars(canvas);
6293
6294 // we're done...
6295 return;
6296 }
6297
6298 /*
6299 * Here we do the full fledged routine...
6300 * (this is an uncommon case where speed matters less,
6301 * this is why we repeat some of the tests that have been
6302 * done above)
6303 */
6304
6305 boolean drawTop = false;
6306 boolean drawBottom = false;
6307 boolean drawLeft = false;
6308 boolean drawRight = false;
6309
6310 float topFadeStrength = 0.0f;
6311 float bottomFadeStrength = 0.0f;
6312 float leftFadeStrength = 0.0f;
6313 float rightFadeStrength = 0.0f;
6314
6315 // Step 2, save the canvas' layers
6316 int paddingLeft = mPaddingLeft;
6317 int paddingTop = mPaddingTop;
6318
6319 final boolean offsetRequired = isPaddingOffsetRequired();
6320 if (offsetRequired) {
6321 paddingLeft += getLeftPaddingOffset();
6322 paddingTop += getTopPaddingOffset();
6323 }
6324
6325 int left = mScrollX + paddingLeft;
6326 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
6327 int top = mScrollY + paddingTop;
6328 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
6329
6330 if (offsetRequired) {
6331 right += getRightPaddingOffset();
6332 bottom += getBottomPaddingOffset();
6333 }
6334
6335 final ScrollabilityCache scrollabilityCache = mScrollCache;
6336 int length = scrollabilityCache.fadingEdgeLength;
6337
6338 // clip the fade length if top and bottom fades overlap
6339 // overlapping fades produce odd-looking artifacts
6340 if (verticalEdges && (top + length > bottom - length)) {
6341 length = (bottom - top) / 2;
6342 }
6343
6344 // also clip horizontal fades if necessary
6345 if (horizontalEdges && (left + length > right - length)) {
6346 length = (right - left) / 2;
6347 }
6348
6349 if (verticalEdges) {
6350 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
6351 drawTop = topFadeStrength >= 0.0f;
6352 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
6353 drawBottom = bottomFadeStrength >= 0.0f;
6354 }
6355
6356 if (horizontalEdges) {
6357 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
6358 drawLeft = leftFadeStrength >= 0.0f;
6359 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
6360 drawRight = rightFadeStrength >= 0.0f;
6361 }
6362
6363 saveCount = canvas.getSaveCount();
6364
6365 int solidColor = getSolidColor();
6366 if (solidColor == 0) {
6367 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
6368
6369 if (drawTop) {
6370 canvas.saveLayer(left, top, right, top + length, null, flags);
6371 }
6372
6373 if (drawBottom) {
6374 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
6375 }
6376
6377 if (drawLeft) {
6378 canvas.saveLayer(left, top, left + length, bottom, null, flags);
6379 }
6380
6381 if (drawRight) {
6382 canvas.saveLayer(right - length, top, right, bottom, null, flags);
6383 }
6384 } else {
6385 scrollabilityCache.setFadeColor(solidColor);
6386 }
6387
6388 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07006389 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390
6391 // Step 4, draw the children
6392 dispatchDraw(canvas);
6393
6394 // Step 5, draw the fade effect and restore layers
6395 final Paint p = scrollabilityCache.paint;
6396 final Matrix matrix = scrollabilityCache.matrix;
6397 final Shader fade = scrollabilityCache.shader;
6398 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
6399
6400 if (drawTop) {
6401 matrix.setScale(1, fadeHeight * topFadeStrength);
6402 matrix.postTranslate(left, top);
6403 fade.setLocalMatrix(matrix);
6404 canvas.drawRect(left, top, right, top + length, p);
6405 }
6406
6407 if (drawBottom) {
6408 matrix.setScale(1, fadeHeight * bottomFadeStrength);
6409 matrix.postRotate(180);
6410 matrix.postTranslate(left, bottom);
6411 fade.setLocalMatrix(matrix);
6412 canvas.drawRect(left, bottom - length, right, bottom, p);
6413 }
6414
6415 if (drawLeft) {
6416 matrix.setScale(1, fadeHeight * leftFadeStrength);
6417 matrix.postRotate(-90);
6418 matrix.postTranslate(left, top);
6419 fade.setLocalMatrix(matrix);
6420 canvas.drawRect(left, top, left + length, bottom, p);
6421 }
6422
6423 if (drawRight) {
6424 matrix.setScale(1, fadeHeight * rightFadeStrength);
6425 matrix.postRotate(90);
6426 matrix.postTranslate(right, top);
6427 fade.setLocalMatrix(matrix);
6428 canvas.drawRect(right - length, top, right, bottom, p);
6429 }
6430
6431 canvas.restoreToCount(saveCount);
6432
6433 // Step 6, draw decorations (scrollbars)
6434 onDrawScrollBars(canvas);
6435 }
6436
6437 /**
6438 * Override this if your view is known to always be drawn on top of a solid color background,
6439 * and needs to draw fading edges. Returning a non-zero color enables the view system to
6440 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
6441 * should be set to 0xFF.
6442 *
6443 * @see #setVerticalFadingEdgeEnabled
6444 * @see #setHorizontalFadingEdgeEnabled
6445 *
6446 * @return The known solid color background for this view, or 0 if the color may vary
6447 */
6448 public int getSolidColor() {
6449 return 0;
6450 }
6451
6452 /**
6453 * Build a human readable string representation of the specified view flags.
6454 *
6455 * @param flags the view flags to convert to a string
6456 * @return a String representing the supplied flags
6457 */
6458 private static String printFlags(int flags) {
6459 String output = "";
6460 int numFlags = 0;
6461 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
6462 output += "TAKES_FOCUS";
6463 numFlags++;
6464 }
6465
6466 switch (flags & VISIBILITY_MASK) {
6467 case INVISIBLE:
6468 if (numFlags > 0) {
6469 output += " ";
6470 }
6471 output += "INVISIBLE";
6472 // USELESS HERE numFlags++;
6473 break;
6474 case GONE:
6475 if (numFlags > 0) {
6476 output += " ";
6477 }
6478 output += "GONE";
6479 // USELESS HERE numFlags++;
6480 break;
6481 default:
6482 break;
6483 }
6484 return output;
6485 }
6486
6487 /**
6488 * Build a human readable string representation of the specified private
6489 * view flags.
6490 *
6491 * @param privateFlags the private view flags to convert to a string
6492 * @return a String representing the supplied flags
6493 */
6494 private static String printPrivateFlags(int privateFlags) {
6495 String output = "";
6496 int numFlags = 0;
6497
6498 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
6499 output += "WANTS_FOCUS";
6500 numFlags++;
6501 }
6502
6503 if ((privateFlags & FOCUSED) == FOCUSED) {
6504 if (numFlags > 0) {
6505 output += " ";
6506 }
6507 output += "FOCUSED";
6508 numFlags++;
6509 }
6510
6511 if ((privateFlags & SELECTED) == SELECTED) {
6512 if (numFlags > 0) {
6513 output += " ";
6514 }
6515 output += "SELECTED";
6516 numFlags++;
6517 }
6518
6519 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
6520 if (numFlags > 0) {
6521 output += " ";
6522 }
6523 output += "IS_ROOT_NAMESPACE";
6524 numFlags++;
6525 }
6526
6527 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
6528 if (numFlags > 0) {
6529 output += " ";
6530 }
6531 output += "HAS_BOUNDS";
6532 numFlags++;
6533 }
6534
6535 if ((privateFlags & DRAWN) == DRAWN) {
6536 if (numFlags > 0) {
6537 output += " ";
6538 }
6539 output += "DRAWN";
6540 // USELESS HERE numFlags++;
6541 }
6542 return output;
6543 }
6544
6545 /**
6546 * <p>Indicates whether or not this view's layout will be requested during
6547 * the next hierarchy layout pass.</p>
6548 *
6549 * @return true if the layout will be forced during next layout pass
6550 */
6551 public boolean isLayoutRequested() {
6552 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
6553 }
6554
6555 /**
6556 * Assign a size and position to a view and all of its
6557 * descendants
6558 *
6559 * <p>This is the second phase of the layout mechanism.
6560 * (The first is measuring). In this phase, each parent calls
6561 * layout on all of its children to position them.
6562 * This is typically done using the child measurements
6563 * that were stored in the measure pass().
6564 *
6565 * Derived classes with children should override
6566 * onLayout. In that method, they should
6567 * call layout on each of their their children.
6568 *
6569 * @param l Left position, relative to parent
6570 * @param t Top position, relative to parent
6571 * @param r Right position, relative to parent
6572 * @param b Bottom position, relative to parent
6573 */
6574 public final void layout(int l, int t, int r, int b) {
6575 boolean changed = setFrame(l, t, r, b);
6576 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
6577 if (ViewDebug.TRACE_HIERARCHY) {
6578 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
6579 }
6580
6581 onLayout(changed, l, t, r, b);
6582 mPrivateFlags &= ~LAYOUT_REQUIRED;
6583 }
6584 mPrivateFlags &= ~FORCE_LAYOUT;
6585 }
6586
6587 /**
6588 * Called from layout when this view should
6589 * assign a size and position to each of its children.
6590 *
6591 * Derived classes with children should override
6592 * this method and call layout on each of
6593 * their their children.
6594 * @param changed This is a new size or position for this view
6595 * @param left Left position, relative to parent
6596 * @param top Top position, relative to parent
6597 * @param right Right position, relative to parent
6598 * @param bottom Bottom position, relative to parent
6599 */
6600 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
6601 }
6602
6603 /**
6604 * Assign a size and position to this view.
6605 *
6606 * This is called from layout.
6607 *
6608 * @param left Left position, relative to parent
6609 * @param top Top position, relative to parent
6610 * @param right Right position, relative to parent
6611 * @param bottom Bottom position, relative to parent
6612 * @return true if the new size and position are different than the
6613 * previous ones
6614 * {@hide}
6615 */
6616 protected boolean setFrame(int left, int top, int right, int bottom) {
6617 boolean changed = false;
6618
6619 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07006620 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621 + right + "," + bottom + ")");
6622 }
6623
6624 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
6625 changed = true;
6626
6627 // Remember our drawn bit
6628 int drawn = mPrivateFlags & DRAWN;
6629
6630 // Invalidate our old position
6631 invalidate();
6632
6633
6634 int oldWidth = mRight - mLeft;
6635 int oldHeight = mBottom - mTop;
6636
6637 mLeft = left;
6638 mTop = top;
6639 mRight = right;
6640 mBottom = bottom;
6641
6642 mPrivateFlags |= HAS_BOUNDS;
6643
6644 int newWidth = right - left;
6645 int newHeight = bottom - top;
6646
6647 if (newWidth != oldWidth || newHeight != oldHeight) {
6648 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
6649 }
6650
6651 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
6652 // If we are visible, force the DRAWN bit to on so that
6653 // this invalidate will go through (at least to our parent).
6654 // This is because someone may have invalidated this view
6655 // before this call to setFrame came in, therby clearing
6656 // the DRAWN bit.
6657 mPrivateFlags |= DRAWN;
6658 invalidate();
6659 }
6660
6661 // Reset drawn bit to original value (invalidate turns it off)
6662 mPrivateFlags |= drawn;
6663
6664 mBackgroundSizeChanged = true;
6665 }
6666 return changed;
6667 }
6668
6669 /**
6670 * Finalize inflating a view from XML. This is called as the last phase
6671 * of inflation, after all child views have been added.
6672 *
6673 * <p>Even if the subclass overrides onFinishInflate, they should always be
6674 * sure to call the super method, so that we get called.
6675 */
6676 protected void onFinishInflate() {
6677 }
6678
6679 /**
6680 * Returns the resources associated with this view.
6681 *
6682 * @return Resources object.
6683 */
6684 public Resources getResources() {
6685 return mResources;
6686 }
6687
6688 /**
6689 * Invalidates the specified Drawable.
6690 *
6691 * @param drawable the drawable to invalidate
6692 */
6693 public void invalidateDrawable(Drawable drawable) {
6694 if (verifyDrawable(drawable)) {
6695 final Rect dirty = drawable.getBounds();
6696 final int scrollX = mScrollX;
6697 final int scrollY = mScrollY;
6698
6699 invalidate(dirty.left + scrollX, dirty.top + scrollY,
6700 dirty.right + scrollX, dirty.bottom + scrollY);
6701 }
6702 }
6703
6704 /**
6705 * Schedules an action on a drawable to occur at a specified time.
6706 *
6707 * @param who the recipient of the action
6708 * @param what the action to run on the drawable
6709 * @param when the time at which the action must occur. Uses the
6710 * {@link SystemClock#uptimeMillis} timebase.
6711 */
6712 public void scheduleDrawable(Drawable who, Runnable what, long when) {
6713 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
6714 mAttachInfo.mHandler.postAtTime(what, who, when);
6715 }
6716 }
6717
6718 /**
6719 * Cancels a scheduled action on a drawable.
6720 *
6721 * @param who the recipient of the action
6722 * @param what the action to cancel
6723 */
6724 public void unscheduleDrawable(Drawable who, Runnable what) {
6725 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
6726 mAttachInfo.mHandler.removeCallbacks(what, who);
6727 }
6728 }
6729
6730 /**
6731 * Unschedule any events associated with the given Drawable. This can be
6732 * used when selecting a new Drawable into a view, so that the previous
6733 * one is completely unscheduled.
6734 *
6735 * @param who The Drawable to unschedule.
6736 *
6737 * @see #drawableStateChanged
6738 */
6739 public void unscheduleDrawable(Drawable who) {
6740 if (mAttachInfo != null) {
6741 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
6742 }
6743 }
6744
6745 /**
6746 * If your view subclass is displaying its own Drawable objects, it should
6747 * override this function and return true for any Drawable it is
6748 * displaying. This allows animations for those drawables to be
6749 * scheduled.
6750 *
6751 * <p>Be sure to call through to the super class when overriding this
6752 * function.
6753 *
6754 * @param who The Drawable to verify. Return true if it is one you are
6755 * displaying, else return the result of calling through to the
6756 * super class.
6757 *
6758 * @return boolean If true than the Drawable is being displayed in the
6759 * view; else false and it is not allowed to animate.
6760 *
6761 * @see #unscheduleDrawable
6762 * @see #drawableStateChanged
6763 */
6764 protected boolean verifyDrawable(Drawable who) {
6765 return who == mBGDrawable;
6766 }
6767
6768 /**
6769 * This function is called whenever the state of the view changes in such
6770 * a way that it impacts the state of drawables being shown.
6771 *
6772 * <p>Be sure to call through to the superclass when overriding this
6773 * function.
6774 *
6775 * @see Drawable#setState
6776 */
6777 protected void drawableStateChanged() {
6778 Drawable d = mBGDrawable;
6779 if (d != null && d.isStateful()) {
6780 d.setState(getDrawableState());
6781 }
6782 }
6783
6784 /**
6785 * Call this to force a view to update its drawable state. This will cause
6786 * drawableStateChanged to be called on this view. Views that are interested
6787 * in the new state should call getDrawableState.
6788 *
6789 * @see #drawableStateChanged
6790 * @see #getDrawableState
6791 */
6792 public void refreshDrawableState() {
6793 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
6794 drawableStateChanged();
6795
6796 ViewParent parent = mParent;
6797 if (parent != null) {
6798 parent.childDrawableStateChanged(this);
6799 }
6800 }
6801
6802 /**
6803 * Return an array of resource IDs of the drawable states representing the
6804 * current state of the view.
6805 *
6806 * @return The current drawable state
6807 *
6808 * @see Drawable#setState
6809 * @see #drawableStateChanged
6810 * @see #onCreateDrawableState
6811 */
6812 public final int[] getDrawableState() {
6813 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
6814 return mDrawableState;
6815 } else {
6816 mDrawableState = onCreateDrawableState(0);
6817 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
6818 return mDrawableState;
6819 }
6820 }
6821
6822 /**
6823 * Generate the new {@link android.graphics.drawable.Drawable} state for
6824 * this view. This is called by the view
6825 * system when the cached Drawable state is determined to be invalid. To
6826 * retrieve the current state, you should use {@link #getDrawableState}.
6827 *
6828 * @param extraSpace if non-zero, this is the number of extra entries you
6829 * would like in the returned array in which you can place your own
6830 * states.
6831 *
6832 * @return Returns an array holding the current {@link Drawable} state of
6833 * the view.
6834 *
6835 * @see #mergeDrawableStates
6836 */
6837 protected int[] onCreateDrawableState(int extraSpace) {
6838 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
6839 mParent instanceof View) {
6840 return ((View) mParent).onCreateDrawableState(extraSpace);
6841 }
6842
6843 int[] drawableState;
6844
6845 int privateFlags = mPrivateFlags;
6846
6847 int viewStateIndex = (((privateFlags & PRESSED) != 0) ? 1 : 0);
6848
6849 viewStateIndex = (viewStateIndex << 1)
6850 + (((mViewFlags & ENABLED_MASK) == ENABLED) ? 1 : 0);
6851
6852 viewStateIndex = (viewStateIndex << 1) + (isFocused() ? 1 : 0);
6853
6854 viewStateIndex = (viewStateIndex << 1)
6855 + (((privateFlags & SELECTED) != 0) ? 1 : 0);
6856
6857 final boolean hasWindowFocus = hasWindowFocus();
6858 viewStateIndex = (viewStateIndex << 1) + (hasWindowFocus ? 1 : 0);
6859
6860 drawableState = VIEW_STATE_SETS[viewStateIndex];
6861
6862 //noinspection ConstantIfStatement
6863 if (false) {
6864 Log.i("View", "drawableStateIndex=" + viewStateIndex);
6865 Log.i("View", toString()
6866 + " pressed=" + ((privateFlags & PRESSED) != 0)
6867 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
6868 + " fo=" + hasFocus()
6869 + " sl=" + ((privateFlags & SELECTED) != 0)
6870 + " wf=" + hasWindowFocus
6871 + ": " + Arrays.toString(drawableState));
6872 }
6873
6874 if (extraSpace == 0) {
6875 return drawableState;
6876 }
6877
6878 final int[] fullState;
6879 if (drawableState != null) {
6880 fullState = new int[drawableState.length + extraSpace];
6881 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
6882 } else {
6883 fullState = new int[extraSpace];
6884 }
6885
6886 return fullState;
6887 }
6888
6889 /**
6890 * Merge your own state values in <var>additionalState</var> into the base
6891 * state values <var>baseState</var> that were returned by
6892 * {@link #onCreateDrawableState}.
6893 *
6894 * @param baseState The base state values returned by
6895 * {@link #onCreateDrawableState}, which will be modified to also hold your
6896 * own additional state values.
6897 *
6898 * @param additionalState The additional state values you would like
6899 * added to <var>baseState</var>; this array is not modified.
6900 *
6901 * @return As a convenience, the <var>baseState</var> array you originally
6902 * passed into the function is returned.
6903 *
6904 * @see #onCreateDrawableState
6905 */
6906 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
6907 final int N = baseState.length;
6908 int i = N - 1;
6909 while (i >= 0 && baseState[i] == 0) {
6910 i--;
6911 }
6912 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
6913 return baseState;
6914 }
6915
6916 /**
6917 * Sets the background color for this view.
6918 * @param color the color of the background
6919 */
6920 public void setBackgroundColor(int color) {
6921 setBackgroundDrawable(new ColorDrawable(color));
6922 }
6923
6924 /**
6925 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07006926 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006927 * @param resid The identifier of the resource.
6928 * @attr ref android.R.styleable#View_background
6929 */
6930 public void setBackgroundResource(int resid) {
6931 if (resid != 0 && resid == mBackgroundResource) {
6932 return;
6933 }
6934
6935 Drawable d= null;
6936 if (resid != 0) {
6937 d = mResources.getDrawable(resid);
6938 }
6939 setBackgroundDrawable(d);
6940
6941 mBackgroundResource = resid;
6942 }
6943
6944 /**
6945 * Set the background to a given Drawable, or remove the background. If the
6946 * background has padding, this View's padding is set to the background's
6947 * padding. However, when a background is removed, this View's padding isn't
6948 * touched. If setting the padding is desired, please use
6949 * {@link #setPadding(int, int, int, int)}.
6950 *
6951 * @param d The Drawable to use as the background, or null to remove the
6952 * background
6953 */
6954 public void setBackgroundDrawable(Drawable d) {
6955 boolean requestLayout = false;
6956
6957 mBackgroundResource = 0;
6958
6959 /*
6960 * Regardless of whether we're setting a new background or not, we want
6961 * to clear the previous drawable.
6962 */
6963 if (mBGDrawable != null) {
6964 mBGDrawable.setCallback(null);
6965 unscheduleDrawable(mBGDrawable);
6966 }
6967
6968 if (d != null) {
6969 Rect padding = sThreadLocal.get();
6970 if (padding == null) {
6971 padding = new Rect();
6972 sThreadLocal.set(padding);
6973 }
6974 if (d.getPadding(padding)) {
6975 setPadding(padding.left, padding.top, padding.right, padding.bottom);
6976 }
6977
6978 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
6979 // if it has a different minimum size, we should layout again
6980 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
6981 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
6982 requestLayout = true;
6983 }
6984
6985 d.setCallback(this);
6986 if (d.isStateful()) {
6987 d.setState(getDrawableState());
6988 }
6989 d.setVisible(getVisibility() == VISIBLE, false);
6990 mBGDrawable = d;
6991
6992 if ((mPrivateFlags & SKIP_DRAW) != 0) {
6993 mPrivateFlags &= ~SKIP_DRAW;
6994 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6995 requestLayout = true;
6996 }
6997 } else {
6998 /* Remove the background */
6999 mBGDrawable = null;
7000
7001 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
7002 /*
7003 * This view ONLY drew the background before and we're removing
7004 * the background, so now it won't draw anything
7005 * (hence we SKIP_DRAW)
7006 */
7007 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
7008 mPrivateFlags |= SKIP_DRAW;
7009 }
7010
7011 /*
7012 * When the background is set, we try to apply its padding to this
7013 * View. When the background is removed, we don't touch this View's
7014 * padding. This is noted in the Javadocs. Hence, we don't need to
7015 * requestLayout(), the invalidate() below is sufficient.
7016 */
7017
7018 // The old background's minimum size could have affected this
7019 // View's layout, so let's requestLayout
7020 requestLayout = true;
7021 }
7022
Romain Guy8f1344f52009-05-15 16:03:59 -07007023 computeOpaqueFlags();
7024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007025 if (requestLayout) {
7026 requestLayout();
7027 }
7028
7029 mBackgroundSizeChanged = true;
7030 invalidate();
7031 }
7032
7033 /**
7034 * Gets the background drawable
7035 * @return The drawable used as the background for this view, if any.
7036 */
7037 public Drawable getBackground() {
7038 return mBGDrawable;
7039 }
7040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 /**
7042 * Sets the padding. The view may add on the space required to display
7043 * the scrollbars, depending on the style and visibility of the scrollbars.
7044 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
7045 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
7046 * from the values set in this call.
7047 *
7048 * @attr ref android.R.styleable#View_padding
7049 * @attr ref android.R.styleable#View_paddingBottom
7050 * @attr ref android.R.styleable#View_paddingLeft
7051 * @attr ref android.R.styleable#View_paddingRight
7052 * @attr ref android.R.styleable#View_paddingTop
7053 * @param left the left padding in pixels
7054 * @param top the top padding in pixels
7055 * @param right the right padding in pixels
7056 * @param bottom the bottom padding in pixels
7057 */
7058 public void setPadding(int left, int top, int right, int bottom) {
7059 boolean changed = false;
7060
7061 mUserPaddingRight = right;
7062 mUserPaddingBottom = bottom;
7063
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007064 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07007065
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007066 // Common case is there are no scroll bars.
7067 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
7068 // TODO: Deal with RTL languages to adjust left padding instead of right.
7069 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
7070 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
7071 ? 0 : getVerticalScrollbarWidth();
7072 }
7073 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
7074 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
7075 ? 0 : getHorizontalScrollbarHeight();
7076 }
7077 }
Romain Guy8506ab42009-06-11 17:35:47 -07007078
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007079 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007080 changed = true;
7081 mPaddingLeft = left;
7082 }
7083 if (mPaddingTop != top) {
7084 changed = true;
7085 mPaddingTop = top;
7086 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007087 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007088 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007089 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007090 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007091 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007093 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 }
7095
7096 if (changed) {
7097 requestLayout();
7098 }
7099 }
7100
7101 /**
7102 * Returns the top padding of this view.
7103 *
7104 * @return the top padding in pixels
7105 */
7106 public int getPaddingTop() {
7107 return mPaddingTop;
7108 }
7109
7110 /**
7111 * Returns the bottom padding of this view. If there are inset and enabled
7112 * scrollbars, this value may include the space required to display the
7113 * scrollbars as well.
7114 *
7115 * @return the bottom padding in pixels
7116 */
7117 public int getPaddingBottom() {
7118 return mPaddingBottom;
7119 }
7120
7121 /**
7122 * Returns the left padding of this view. If there are inset and enabled
7123 * scrollbars, this value may include the space required to display the
7124 * scrollbars as well.
7125 *
7126 * @return the left padding in pixels
7127 */
7128 public int getPaddingLeft() {
7129 return mPaddingLeft;
7130 }
7131
7132 /**
7133 * Returns the right padding of this view. If there are inset and enabled
7134 * scrollbars, this value may include the space required to display the
7135 * scrollbars as well.
7136 *
7137 * @return the right padding in pixels
7138 */
7139 public int getPaddingRight() {
7140 return mPaddingRight;
7141 }
7142
7143 /**
7144 * Changes the selection state of this view. A view can be selected or not.
7145 * Note that selection is not the same as focus. Views are typically
7146 * selected in the context of an AdapterView like ListView or GridView;
7147 * the selected view is the view that is highlighted.
7148 *
7149 * @param selected true if the view must be selected, false otherwise
7150 */
7151 public void setSelected(boolean selected) {
7152 if (((mPrivateFlags & SELECTED) != 0) != selected) {
7153 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07007154 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007155 invalidate();
7156 refreshDrawableState();
7157 dispatchSetSelected(selected);
7158 }
7159 }
7160
7161 /**
7162 * Dispatch setSelected to all of this View's children.
7163 *
7164 * @see #setSelected(boolean)
7165 *
7166 * @param selected The new selected state
7167 */
7168 protected void dispatchSetSelected(boolean selected) {
7169 }
7170
7171 /**
7172 * Indicates the selection state of this view.
7173 *
7174 * @return true if the view is selected, false otherwise
7175 */
7176 @ViewDebug.ExportedProperty
7177 public boolean isSelected() {
7178 return (mPrivateFlags & SELECTED) != 0;
7179 }
7180
7181 /**
7182 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
7183 * observer can be used to get notifications when global events, like
7184 * layout, happen.
7185 *
7186 * The returned ViewTreeObserver observer is not guaranteed to remain
7187 * valid for the lifetime of this View. If the caller of this method keeps
7188 * a long-lived reference to ViewTreeObserver, it should always check for
7189 * the return value of {@link ViewTreeObserver#isAlive()}.
7190 *
7191 * @return The ViewTreeObserver for this view's hierarchy.
7192 */
7193 public ViewTreeObserver getViewTreeObserver() {
7194 if (mAttachInfo != null) {
7195 return mAttachInfo.mTreeObserver;
7196 }
7197 if (mFloatingTreeObserver == null) {
7198 mFloatingTreeObserver = new ViewTreeObserver();
7199 }
7200 return mFloatingTreeObserver;
7201 }
7202
7203 /**
7204 * <p>Finds the topmost view in the current view hierarchy.</p>
7205 *
7206 * @return the topmost view containing this view
7207 */
7208 public View getRootView() {
7209 if (mAttachInfo != null) {
7210 final View v = mAttachInfo.mRootView;
7211 if (v != null) {
7212 return v;
7213 }
7214 }
Romain Guy8506ab42009-06-11 17:35:47 -07007215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007216 View parent = this;
7217
7218 while (parent.mParent != null && parent.mParent instanceof View) {
7219 parent = (View) parent.mParent;
7220 }
7221
7222 return parent;
7223 }
7224
7225 /**
7226 * <p>Computes the coordinates of this view on the screen. The argument
7227 * must be an array of two integers. After the method returns, the array
7228 * contains the x and y location in that order.</p>
7229 *
7230 * @param location an array of two integers in which to hold the coordinates
7231 */
7232 public void getLocationOnScreen(int[] location) {
7233 getLocationInWindow(location);
7234
7235 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07007236 if (info != null) {
7237 location[0] += info.mWindowLeft;
7238 location[1] += info.mWindowTop;
7239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007240 }
7241
7242 /**
7243 * <p>Computes the coordinates of this view in its window. The argument
7244 * must be an array of two integers. After the method returns, the array
7245 * contains the x and y location in that order.</p>
7246 *
7247 * @param location an array of two integers in which to hold the coordinates
7248 */
7249 public void getLocationInWindow(int[] location) {
7250 if (location == null || location.length < 2) {
7251 throw new IllegalArgumentException("location must be an array of "
7252 + "two integers");
7253 }
7254
7255 location[0] = mLeft;
7256 location[1] = mTop;
7257
7258 ViewParent viewParent = mParent;
7259 while (viewParent instanceof View) {
7260 final View view = (View)viewParent;
7261 location[0] += view.mLeft - view.mScrollX;
7262 location[1] += view.mTop - view.mScrollY;
7263 viewParent = view.mParent;
7264 }
Romain Guy8506ab42009-06-11 17:35:47 -07007265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007266 if (viewParent instanceof ViewRoot) {
7267 // *cough*
7268 final ViewRoot vr = (ViewRoot)viewParent;
7269 location[1] -= vr.mCurScrollY;
7270 }
7271 }
7272
7273 /**
7274 * {@hide}
7275 * @param id the id of the view to be found
7276 * @return the view of the specified id, null if cannot be found
7277 */
7278 protected View findViewTraversal(int id) {
7279 if (id == mID) {
7280 return this;
7281 }
7282 return null;
7283 }
7284
7285 /**
7286 * {@hide}
7287 * @param tag the tag of the view to be found
7288 * @return the view of specified tag, null if cannot be found
7289 */
7290 protected View findViewWithTagTraversal(Object tag) {
7291 if (tag != null && tag.equals(mTag)) {
7292 return this;
7293 }
7294 return null;
7295 }
7296
7297 /**
7298 * Look for a child view with the given id. If this view has the given
7299 * id, return this view.
7300 *
7301 * @param id The id to search for.
7302 * @return The view that has the given id in the hierarchy or null
7303 */
7304 public final View findViewById(int id) {
7305 if (id < 0) {
7306 return null;
7307 }
7308 return findViewTraversal(id);
7309 }
7310
7311 /**
7312 * Look for a child view with the given tag. If this view has the given
7313 * tag, return this view.
7314 *
7315 * @param tag The tag to search for, using "tag.equals(getTag())".
7316 * @return The View that has the given tag in the hierarchy or null
7317 */
7318 public final View findViewWithTag(Object tag) {
7319 if (tag == null) {
7320 return null;
7321 }
7322 return findViewWithTagTraversal(tag);
7323 }
7324
7325 /**
7326 * Sets the identifier for this view. The identifier does not have to be
7327 * unique in this view's hierarchy. The identifier should be a positive
7328 * number.
7329 *
7330 * @see #NO_ID
7331 * @see #getId
7332 * @see #findViewById
7333 *
7334 * @param id a number used to identify the view
7335 *
7336 * @attr ref android.R.styleable#View_id
7337 */
7338 public void setId(int id) {
7339 mID = id;
7340 }
7341
7342 /**
7343 * {@hide}
7344 *
7345 * @param isRoot true if the view belongs to the root namespace, false
7346 * otherwise
7347 */
7348 public void setIsRootNamespace(boolean isRoot) {
7349 if (isRoot) {
7350 mPrivateFlags |= IS_ROOT_NAMESPACE;
7351 } else {
7352 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
7353 }
7354 }
7355
7356 /**
7357 * {@hide}
7358 *
7359 * @return true if the view belongs to the root namespace, false otherwise
7360 */
7361 public boolean isRootNamespace() {
7362 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
7363 }
7364
7365 /**
7366 * Returns this view's identifier.
7367 *
7368 * @return a positive integer used to identify the view or {@link #NO_ID}
7369 * if the view has no ID
7370 *
7371 * @see #setId
7372 * @see #findViewById
7373 * @attr ref android.R.styleable#View_id
7374 */
7375 @ViewDebug.CapturedViewProperty
7376 public int getId() {
7377 return mID;
7378 }
7379
7380 /**
7381 * Returns this view's tag.
7382 *
7383 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07007384 *
7385 * @see #setTag(Object)
7386 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007387 */
7388 @ViewDebug.ExportedProperty
7389 public Object getTag() {
7390 return mTag;
7391 }
7392
7393 /**
7394 * Sets the tag associated with this view. A tag can be used to mark
7395 * a view in its hierarchy and does not have to be unique within the
7396 * hierarchy. Tags can also be used to store data within a view without
7397 * resorting to another data structure.
7398 *
7399 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07007400 *
7401 * @see #getTag()
7402 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007403 */
7404 public void setTag(final Object tag) {
7405 mTag = tag;
7406 }
7407
7408 /**
Romain Guyd90a3312009-05-06 14:54:28 -07007409 * Returns the tag associated with this view and the specified key.
7410 *
7411 * @param key The key identifying the tag
7412 *
7413 * @return the Object stored in this view as a tag
7414 *
7415 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07007416 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07007417 */
7418 public Object getTag(int key) {
7419 SparseArray<Object> tags = null;
7420 synchronized (sTagsLock) {
7421 if (sTags != null) {
7422 tags = sTags.get(this);
7423 }
7424 }
7425
7426 if (tags != null) return tags.get(key);
7427 return null;
7428 }
7429
7430 /**
7431 * Sets a tag associated with this view and a key. A tag can be used
7432 * to mark a view in its hierarchy and does not have to be unique within
7433 * the hierarchy. Tags can also be used to store data within a view
7434 * without resorting to another data structure.
7435 *
7436 * The specified key should be an id declared in the resources of the
7437 * application to ensure it is unique. Keys identified as belonging to
7438 * the Android framework or not associated with any package will cause
7439 * an {@link IllegalArgumentException} to be thrown.
7440 *
7441 * @param key The key identifying the tag
7442 * @param tag An Object to tag the view with
7443 *
7444 * @throws IllegalArgumentException If they specified key is not valid
7445 *
7446 * @see #setTag(Object)
7447 * @see #getTag(int)
7448 */
7449 public void setTag(int key, final Object tag) {
7450 // If the package id is 0x00 or 0x01, it's either an undefined package
7451 // or a framework id
7452 if ((key >>> 24) < 2) {
7453 throw new IllegalArgumentException("The key must be an application-specific "
7454 + "resource id.");
7455 }
7456
7457 setTagInternal(this, key, tag);
7458 }
7459
7460 /**
7461 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
7462 * framework id.
7463 *
7464 * @hide
7465 */
7466 public void setTagInternal(int key, Object tag) {
7467 if ((key >>> 24) != 0x1) {
7468 throw new IllegalArgumentException("The key must be a framework-specific "
7469 + "resource id.");
7470 }
7471
Romain Guy8506ab42009-06-11 17:35:47 -07007472 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07007473 }
7474
7475 private static void setTagInternal(View view, int key, Object tag) {
7476 SparseArray<Object> tags = null;
7477 synchronized (sTagsLock) {
7478 if (sTags == null) {
7479 sTags = new WeakHashMap<View, SparseArray<Object>>();
7480 } else {
7481 tags = sTags.get(view);
7482 }
7483 }
7484
7485 if (tags == null) {
7486 tags = new SparseArray<Object>(2);
7487 synchronized (sTagsLock) {
7488 sTags.put(view, tags);
7489 }
7490 }
7491
7492 tags.put(key, tag);
7493 }
7494
7495 /**
Romain Guy13922e02009-05-12 17:56:14 -07007496 * @param consistency The type of consistency. See ViewDebug for more information.
7497 *
7498 * @hide
7499 */
7500 protected boolean dispatchConsistencyCheck(int consistency) {
7501 return onConsistencyCheck(consistency);
7502 }
7503
7504 /**
7505 * Method that subclasses should implement to check their consistency. The type of
7506 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07007507 *
Romain Guy13922e02009-05-12 17:56:14 -07007508 * @param consistency The type of consistency. See ViewDebug for more information.
7509 *
7510 * @throws IllegalStateException if the view is in an inconsistent state.
7511 *
7512 * @hide
7513 */
7514 protected boolean onConsistencyCheck(int consistency) {
7515 boolean result = true;
7516
7517 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
7518 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
7519
7520 if (checkLayout) {
7521 if (getParent() == null) {
7522 result = false;
7523 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
7524 "View " + this + " does not have a parent.");
7525 }
7526
7527 if (mAttachInfo == null) {
7528 result = false;
7529 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
7530 "View " + this + " is not attached to a window.");
7531 }
7532 }
7533
7534 if (checkDrawing) {
7535 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
7536 // from their draw() method
7537
7538 if ((mPrivateFlags & DRAWN) != DRAWN &&
7539 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
7540 result = false;
7541 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
7542 "View " + this + " was invalidated but its drawing cache is valid.");
7543 }
7544 }
7545
7546 return result;
7547 }
7548
7549 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007550 * Prints information about this view in the log output, with the tag
7551 * {@link #VIEW_LOG_TAG}.
7552 *
7553 * @hide
7554 */
7555 public void debug() {
7556 debug(0);
7557 }
7558
7559 /**
7560 * Prints information about this view in the log output, with the tag
7561 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
7562 * indentation defined by the <code>depth</code>.
7563 *
7564 * @param depth the indentation level
7565 *
7566 * @hide
7567 */
7568 protected void debug(int depth) {
7569 String output = debugIndent(depth - 1);
7570
7571 output += "+ " + this;
7572 int id = getId();
7573 if (id != -1) {
7574 output += " (id=" + id + ")";
7575 }
7576 Object tag = getTag();
7577 if (tag != null) {
7578 output += " (tag=" + tag + ")";
7579 }
7580 Log.d(VIEW_LOG_TAG, output);
7581
7582 if ((mPrivateFlags & FOCUSED) != 0) {
7583 output = debugIndent(depth) + " FOCUSED";
7584 Log.d(VIEW_LOG_TAG, output);
7585 }
7586
7587 output = debugIndent(depth);
7588 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
7589 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
7590 + "} ";
7591 Log.d(VIEW_LOG_TAG, output);
7592
7593 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
7594 || mPaddingBottom != 0) {
7595 output = debugIndent(depth);
7596 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
7597 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
7598 Log.d(VIEW_LOG_TAG, output);
7599 }
7600
7601 output = debugIndent(depth);
7602 output += "mMeasureWidth=" + mMeasuredWidth +
7603 " mMeasureHeight=" + mMeasuredHeight;
7604 Log.d(VIEW_LOG_TAG, output);
7605
7606 output = debugIndent(depth);
7607 if (mLayoutParams == null) {
7608 output += "BAD! no layout params";
7609 } else {
7610 output = mLayoutParams.debug(output);
7611 }
7612 Log.d(VIEW_LOG_TAG, output);
7613
7614 output = debugIndent(depth);
7615 output += "flags={";
7616 output += View.printFlags(mViewFlags);
7617 output += "}";
7618 Log.d(VIEW_LOG_TAG, output);
7619
7620 output = debugIndent(depth);
7621 output += "privateFlags={";
7622 output += View.printPrivateFlags(mPrivateFlags);
7623 output += "}";
7624 Log.d(VIEW_LOG_TAG, output);
7625 }
7626
7627 /**
7628 * Creates an string of whitespaces used for indentation.
7629 *
7630 * @param depth the indentation level
7631 * @return a String containing (depth * 2 + 3) * 2 white spaces
7632 *
7633 * @hide
7634 */
7635 protected static String debugIndent(int depth) {
7636 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
7637 for (int i = 0; i < (depth * 2) + 3; i++) {
7638 spaces.append(' ').append(' ');
7639 }
7640 return spaces.toString();
7641 }
7642
7643 /**
7644 * <p>Return the offset of the widget's text baseline from the widget's top
7645 * boundary. If this widget does not support baseline alignment, this
7646 * method returns -1. </p>
7647 *
7648 * @return the offset of the baseline within the widget's bounds or -1
7649 * if baseline alignment is not supported
7650 */
7651 @ViewDebug.ExportedProperty
7652 public int getBaseline() {
7653 return -1;
7654 }
7655
7656 /**
7657 * Call this when something has changed which has invalidated the
7658 * layout of this view. This will schedule a layout pass of the view
7659 * tree.
7660 */
7661 public void requestLayout() {
7662 if (ViewDebug.TRACE_HIERARCHY) {
7663 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
7664 }
7665
7666 mPrivateFlags |= FORCE_LAYOUT;
7667
7668 if (mParent != null && !mParent.isLayoutRequested()) {
7669 mParent.requestLayout();
7670 }
7671 }
7672
7673 /**
7674 * Forces this view to be laid out during the next layout pass.
7675 * This method does not call requestLayout() or forceLayout()
7676 * on the parent.
7677 */
7678 public void forceLayout() {
7679 mPrivateFlags |= FORCE_LAYOUT;
7680 }
7681
7682 /**
7683 * <p>
7684 * This is called to find out how big a view should be. The parent
7685 * supplies constraint information in the width and height parameters.
7686 * </p>
7687 *
7688 * <p>
7689 * The actual mesurement work of a view is performed in
7690 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
7691 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
7692 * </p>
7693 *
7694 *
7695 * @param widthMeasureSpec Horizontal space requirements as imposed by the
7696 * parent
7697 * @param heightMeasureSpec Vertical space requirements as imposed by the
7698 * parent
7699 *
7700 * @see #onMeasure(int, int)
7701 */
7702 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
7703 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
7704 widthMeasureSpec != mOldWidthMeasureSpec ||
7705 heightMeasureSpec != mOldHeightMeasureSpec) {
7706
7707 // first clears the measured dimension flag
7708 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
7709
7710 if (ViewDebug.TRACE_HIERARCHY) {
7711 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
7712 }
7713
7714 // measure ourselves, this should set the measured dimension flag back
7715 onMeasure(widthMeasureSpec, heightMeasureSpec);
7716
7717 // flag not set, setMeasuredDimension() was not invoked, we raise
7718 // an exception to warn the developer
7719 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
7720 throw new IllegalStateException("onMeasure() did not set the"
7721 + " measured dimension by calling"
7722 + " setMeasuredDimension()");
7723 }
7724
7725 mPrivateFlags |= LAYOUT_REQUIRED;
7726 }
7727
7728 mOldWidthMeasureSpec = widthMeasureSpec;
7729 mOldHeightMeasureSpec = heightMeasureSpec;
7730 }
7731
7732 /**
7733 * <p>
7734 * Measure the view and its content to determine the measured width and the
7735 * measured height. This method is invoked by {@link #measure(int, int)} and
7736 * should be overriden by subclasses to provide accurate and efficient
7737 * measurement of their contents.
7738 * </p>
7739 *
7740 * <p>
7741 * <strong>CONTRACT:</strong> When overriding this method, you
7742 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
7743 * measured width and height of this view. Failure to do so will trigger an
7744 * <code>IllegalStateException</code>, thrown by
7745 * {@link #measure(int, int)}. Calling the superclass'
7746 * {@link #onMeasure(int, int)} is a valid use.
7747 * </p>
7748 *
7749 * <p>
7750 * The base class implementation of measure defaults to the background size,
7751 * unless a larger size is allowed by the MeasureSpec. Subclasses should
7752 * override {@link #onMeasure(int, int)} to provide better measurements of
7753 * their content.
7754 * </p>
7755 *
7756 * <p>
7757 * If this method is overridden, it is the subclass's responsibility to make
7758 * sure the measured height and width are at least the view's minimum height
7759 * and width ({@link #getSuggestedMinimumHeight()} and
7760 * {@link #getSuggestedMinimumWidth()}).
7761 * </p>
7762 *
7763 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
7764 * The requirements are encoded with
7765 * {@link android.view.View.MeasureSpec}.
7766 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
7767 * The requirements are encoded with
7768 * {@link android.view.View.MeasureSpec}.
7769 *
7770 * @see #getMeasuredWidth()
7771 * @see #getMeasuredHeight()
7772 * @see #setMeasuredDimension(int, int)
7773 * @see #getSuggestedMinimumHeight()
7774 * @see #getSuggestedMinimumWidth()
7775 * @see android.view.View.MeasureSpec#getMode(int)
7776 * @see android.view.View.MeasureSpec#getSize(int)
7777 */
7778 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
7779 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
7780 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
7781 }
7782
7783 /**
7784 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
7785 * measured width and measured height. Failing to do so will trigger an
7786 * exception at measurement time.</p>
7787 *
7788 * @param measuredWidth the measured width of this view
7789 * @param measuredHeight the measured height of this view
7790 */
7791 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
7792 mMeasuredWidth = measuredWidth;
7793 mMeasuredHeight = measuredHeight;
7794
7795 mPrivateFlags |= MEASURED_DIMENSION_SET;
7796 }
7797
7798 /**
7799 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
7800 * Will take the desired size, unless a different size is imposed by the constraints.
7801 *
7802 * @param size How big the view wants to be
7803 * @param measureSpec Constraints imposed by the parent
7804 * @return The size this view should be.
7805 */
7806 public static int resolveSize(int size, int measureSpec) {
7807 int result = size;
7808 int specMode = MeasureSpec.getMode(measureSpec);
7809 int specSize = MeasureSpec.getSize(measureSpec);
7810 switch (specMode) {
7811 case MeasureSpec.UNSPECIFIED:
7812 result = size;
7813 break;
7814 case MeasureSpec.AT_MOST:
7815 result = Math.min(size, specSize);
7816 break;
7817 case MeasureSpec.EXACTLY:
7818 result = specSize;
7819 break;
7820 }
7821 return result;
7822 }
7823
7824 /**
7825 * Utility to return a default size. Uses the supplied size if the
7826 * MeasureSpec imposed no contraints. Will get larger if allowed
7827 * by the MeasureSpec.
7828 *
7829 * @param size Default size for this view
7830 * @param measureSpec Constraints imposed by the parent
7831 * @return The size this view should be.
7832 */
7833 public static int getDefaultSize(int size, int measureSpec) {
7834 int result = size;
7835 int specMode = MeasureSpec.getMode(measureSpec);
7836 int specSize = MeasureSpec.getSize(measureSpec);
7837
7838 switch (specMode) {
7839 case MeasureSpec.UNSPECIFIED:
7840 result = size;
7841 break;
7842 case MeasureSpec.AT_MOST:
7843 case MeasureSpec.EXACTLY:
7844 result = specSize;
7845 break;
7846 }
7847 return result;
7848 }
7849
7850 /**
7851 * Returns the suggested minimum height that the view should use. This
7852 * returns the maximum of the view's minimum height
7853 * and the background's minimum height
7854 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
7855 * <p>
7856 * When being used in {@link #onMeasure(int, int)}, the caller should still
7857 * ensure the returned height is within the requirements of the parent.
7858 *
7859 * @return The suggested minimum height of the view.
7860 */
7861 protected int getSuggestedMinimumHeight() {
7862 int suggestedMinHeight = mMinHeight;
7863
7864 if (mBGDrawable != null) {
7865 final int bgMinHeight = mBGDrawable.getMinimumHeight();
7866 if (suggestedMinHeight < bgMinHeight) {
7867 suggestedMinHeight = bgMinHeight;
7868 }
7869 }
7870
7871 return suggestedMinHeight;
7872 }
7873
7874 /**
7875 * Returns the suggested minimum width that the view should use. This
7876 * returns the maximum of the view's minimum width)
7877 * and the background's minimum width
7878 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
7879 * <p>
7880 * When being used in {@link #onMeasure(int, int)}, the caller should still
7881 * ensure the returned width is within the requirements of the parent.
7882 *
7883 * @return The suggested minimum width of the view.
7884 */
7885 protected int getSuggestedMinimumWidth() {
7886 int suggestedMinWidth = mMinWidth;
7887
7888 if (mBGDrawable != null) {
7889 final int bgMinWidth = mBGDrawable.getMinimumWidth();
7890 if (suggestedMinWidth < bgMinWidth) {
7891 suggestedMinWidth = bgMinWidth;
7892 }
7893 }
7894
7895 return suggestedMinWidth;
7896 }
7897
7898 /**
7899 * Sets the minimum height of the view. It is not guaranteed the view will
7900 * be able to achieve this minimum height (for example, if its parent layout
7901 * constrains it with less available height).
7902 *
7903 * @param minHeight The minimum height the view will try to be.
7904 */
7905 public void setMinimumHeight(int minHeight) {
7906 mMinHeight = minHeight;
7907 }
7908
7909 /**
7910 * Sets the minimum width of the view. It is not guaranteed the view will
7911 * be able to achieve this minimum width (for example, if its parent layout
7912 * constrains it with less available width).
7913 *
7914 * @param minWidth The minimum width the view will try to be.
7915 */
7916 public void setMinimumWidth(int minWidth) {
7917 mMinWidth = minWidth;
7918 }
7919
7920 /**
7921 * Get the animation currently associated with this view.
7922 *
7923 * @return The animation that is currently playing or
7924 * scheduled to play for this view.
7925 */
7926 public Animation getAnimation() {
7927 return mCurrentAnimation;
7928 }
7929
7930 /**
7931 * Start the specified animation now.
7932 *
7933 * @param animation the animation to start now
7934 */
7935 public void startAnimation(Animation animation) {
7936 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
7937 setAnimation(animation);
7938 invalidate();
7939 }
7940
7941 /**
7942 * Cancels any animations for this view.
7943 */
7944 public void clearAnimation() {
7945 mCurrentAnimation = null;
7946 }
7947
7948 /**
7949 * Sets the next animation to play for this view.
7950 * If you want the animation to play immediately, use
7951 * startAnimation. This method provides allows fine-grained
7952 * control over the start time and invalidation, but you
7953 * must make sure that 1) the animation has a start time set, and
7954 * 2) the view will be invalidated when the animation is supposed to
7955 * start.
7956 *
7957 * @param animation The next animation, or null.
7958 */
7959 public void setAnimation(Animation animation) {
7960 mCurrentAnimation = animation;
7961 if (animation != null) {
7962 animation.reset();
7963 }
7964 }
7965
7966 /**
7967 * Invoked by a parent ViewGroup to notify the start of the animation
7968 * currently associated with this view. If you override this method,
7969 * always call super.onAnimationStart();
7970 *
7971 * @see #setAnimation(android.view.animation.Animation)
7972 * @see #getAnimation()
7973 */
7974 protected void onAnimationStart() {
7975 mPrivateFlags |= ANIMATION_STARTED;
7976 }
7977
7978 /**
7979 * Invoked by a parent ViewGroup to notify the end of the animation
7980 * currently associated with this view. If you override this method,
7981 * always call super.onAnimationEnd();
7982 *
7983 * @see #setAnimation(android.view.animation.Animation)
7984 * @see #getAnimation()
7985 */
7986 protected void onAnimationEnd() {
7987 mPrivateFlags &= ~ANIMATION_STARTED;
7988 }
7989
7990 /**
7991 * Invoked if there is a Transform that involves alpha. Subclass that can
7992 * draw themselves with the specified alpha should return true, and then
7993 * respect that alpha when their onDraw() is called. If this returns false
7994 * then the view may be redirected to draw into an offscreen buffer to
7995 * fulfill the request, which will look fine, but may be slower than if the
7996 * subclass handles it internally. The default implementation returns false.
7997 *
7998 * @param alpha The alpha (0..255) to apply to the view's drawing
7999 * @return true if the view can draw with the specified alpha.
8000 */
8001 protected boolean onSetAlpha(int alpha) {
8002 return false;
8003 }
8004
8005 /**
8006 * This is used by the RootView to perform an optimization when
8007 * the view hierarchy contains one or several SurfaceView.
8008 * SurfaceView is always considered transparent, but its children are not,
8009 * therefore all View objects remove themselves from the global transparent
8010 * region (passed as a parameter to this function).
8011 *
8012 * @param region The transparent region for this ViewRoot (window).
8013 *
8014 * @return Returns true if the effective visibility of the view at this
8015 * point is opaque, regardless of the transparent region; returns false
8016 * if it is possible for underlying windows to be seen behind the view.
8017 *
8018 * {@hide}
8019 */
8020 public boolean gatherTransparentRegion(Region region) {
8021 final AttachInfo attachInfo = mAttachInfo;
8022 if (region != null && attachInfo != null) {
8023 final int pflags = mPrivateFlags;
8024 if ((pflags & SKIP_DRAW) == 0) {
8025 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
8026 // remove it from the transparent region.
8027 final int[] location = attachInfo.mTransparentLocation;
8028 getLocationInWindow(location);
8029 region.op(location[0], location[1], location[0] + mRight - mLeft,
8030 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
8031 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
8032 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
8033 // exists, so we remove the background drawable's non-transparent
8034 // parts from this transparent region.
8035 applyDrawableToTransparentRegion(mBGDrawable, region);
8036 }
8037 }
8038 return true;
8039 }
8040
8041 /**
8042 * Play a sound effect for this view.
8043 *
8044 * <p>The framework will play sound effects for some built in actions, such as
8045 * clicking, but you may wish to play these effects in your widget,
8046 * for instance, for internal navigation.
8047 *
8048 * <p>The sound effect will only be played if sound effects are enabled by the user, and
8049 * {@link #isSoundEffectsEnabled()} is true.
8050 *
8051 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
8052 */
8053 public void playSoundEffect(int soundConstant) {
8054 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
8055 return;
8056 }
8057 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
8058 }
8059
8060 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008061 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07008062 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008063 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 *
8065 * <p>The framework will provide haptic feedback for some built in actions,
8066 * such as long presses, but you may wish to provide feedback for your
8067 * own widget.
8068 *
8069 * <p>The feedback will only be performed if
8070 * {@link #isHapticFeedbackEnabled()} is true.
8071 *
8072 * @param feedbackConstant One of the constants defined in
8073 * {@link HapticFeedbackConstants}
8074 */
8075 public boolean performHapticFeedback(int feedbackConstant) {
8076 return performHapticFeedback(feedbackConstant, 0);
8077 }
8078
8079 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008080 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07008081 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008082 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008083 *
8084 * @param feedbackConstant One of the constants defined in
8085 * {@link HapticFeedbackConstants}
8086 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
8087 */
8088 public boolean performHapticFeedback(int feedbackConstant, int flags) {
8089 if (mAttachInfo == null) {
8090 return false;
8091 }
8092 if ((flags&HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
8093 && !isHapticFeedbackEnabled()) {
8094 return false;
8095 }
8096 return mAttachInfo.mRootCallbacks.performHapticFeedback(
8097 feedbackConstant,
8098 (flags&HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
8099 }
8100
8101 /**
8102 * Given a Drawable whose bounds have been set to draw into this view,
8103 * update a Region being computed for {@link #gatherTransparentRegion} so
8104 * that any non-transparent parts of the Drawable are removed from the
8105 * given transparent region.
8106 *
8107 * @param dr The Drawable whose transparency is to be applied to the region.
8108 * @param region A Region holding the current transparency information,
8109 * where any parts of the region that are set are considered to be
8110 * transparent. On return, this region will be modified to have the
8111 * transparency information reduced by the corresponding parts of the
8112 * Drawable that are not transparent.
8113 * {@hide}
8114 */
8115 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
8116 if (DBG) {
8117 Log.i("View", "Getting transparent region for: " + this);
8118 }
8119 final Region r = dr.getTransparentRegion();
8120 final Rect db = dr.getBounds();
8121 final AttachInfo attachInfo = mAttachInfo;
8122 if (r != null && attachInfo != null) {
8123 final int w = getRight()-getLeft();
8124 final int h = getBottom()-getTop();
8125 if (db.left > 0) {
8126 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
8127 r.op(0, 0, db.left, h, Region.Op.UNION);
8128 }
8129 if (db.right < w) {
8130 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
8131 r.op(db.right, 0, w, h, Region.Op.UNION);
8132 }
8133 if (db.top > 0) {
8134 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
8135 r.op(0, 0, w, db.top, Region.Op.UNION);
8136 }
8137 if (db.bottom < h) {
8138 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
8139 r.op(0, db.bottom, w, h, Region.Op.UNION);
8140 }
8141 final int[] location = attachInfo.mTransparentLocation;
8142 getLocationInWindow(location);
8143 r.translate(location[0], location[1]);
8144 region.op(r, Region.Op.INTERSECT);
8145 } else {
8146 region.op(db, Region.Op.DIFFERENCE);
8147 }
8148 }
8149
8150 private void postCheckForLongClick() {
8151 mHasPerformedLongPress = false;
8152
8153 if (mPendingCheckForLongPress == null) {
8154 mPendingCheckForLongPress = new CheckForLongPress();
8155 }
8156 mPendingCheckForLongPress.rememberWindowAttachCount();
8157 postDelayed(mPendingCheckForLongPress, ViewConfiguration.getLongPressTimeout());
8158 }
8159
8160 private static int[] stateSetUnion(final int[] stateSet1,
8161 final int[] stateSet2) {
8162 final int stateSet1Length = stateSet1.length;
8163 final int stateSet2Length = stateSet2.length;
8164 final int[] newSet = new int[stateSet1Length + stateSet2Length];
8165 int k = 0;
8166 int i = 0;
8167 int j = 0;
8168 // This is a merge of the two input state sets and assumes that the
8169 // input sets are sorted by the order imposed by ViewDrawableStates.
8170 for (int viewState : R.styleable.ViewDrawableStates) {
8171 if (i < stateSet1Length && stateSet1[i] == viewState) {
8172 newSet[k++] = viewState;
8173 i++;
8174 } else if (j < stateSet2Length && stateSet2[j] == viewState) {
8175 newSet[k++] = viewState;
8176 j++;
8177 }
8178 if (k > 1) {
8179 assert(newSet[k - 1] > newSet[k - 2]);
8180 }
8181 }
8182 return newSet;
8183 }
8184
8185 /**
8186 * Inflate a view from an XML resource. This convenience method wraps the {@link
8187 * LayoutInflater} class, which provides a full range of options for view inflation.
8188 *
8189 * @param context The Context object for your activity or application.
8190 * @param resource The resource ID to inflate
8191 * @param root A view group that will be the parent. Used to properly inflate the
8192 * layout_* parameters.
8193 * @see LayoutInflater
8194 */
8195 public static View inflate(Context context, int resource, ViewGroup root) {
8196 LayoutInflater factory = LayoutInflater.from(context);
8197 return factory.inflate(resource, root);
8198 }
8199
8200 /**
8201 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
8202 * Each MeasureSpec represents a requirement for either the width or the height.
8203 * A MeasureSpec is comprised of a size and a mode. There are three possible
8204 * modes:
8205 * <dl>
8206 * <dt>UNSPECIFIED</dt>
8207 * <dd>
8208 * The parent has not imposed any constraint on the child. It can be whatever size
8209 * it wants.
8210 * </dd>
8211 *
8212 * <dt>EXACTLY</dt>
8213 * <dd>
8214 * The parent has determined an exact size for the child. The child is going to be
8215 * given those bounds regardless of how big it wants to be.
8216 * </dd>
8217 *
8218 * <dt>AT_MOST</dt>
8219 * <dd>
8220 * The child can be as large as it wants up to the specified size.
8221 * </dd>
8222 * </dl>
8223 *
8224 * MeasureSpecs are implemented as ints to reduce object allocation. This class
8225 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
8226 */
8227 public static class MeasureSpec {
8228 private static final int MODE_SHIFT = 30;
8229 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
8230
8231 /**
8232 * Measure specification mode: The parent has not imposed any constraint
8233 * on the child. It can be whatever size it wants.
8234 */
8235 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
8236
8237 /**
8238 * Measure specification mode: The parent has determined an exact size
8239 * for the child. The child is going to be given those bounds regardless
8240 * of how big it wants to be.
8241 */
8242 public static final int EXACTLY = 1 << MODE_SHIFT;
8243
8244 /**
8245 * Measure specification mode: The child can be as large as it wants up
8246 * to the specified size.
8247 */
8248 public static final int AT_MOST = 2 << MODE_SHIFT;
8249
8250 /**
8251 * Creates a measure specification based on the supplied size and mode.
8252 *
8253 * The mode must always be one of the following:
8254 * <ul>
8255 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
8256 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
8257 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
8258 * </ul>
8259 *
8260 * @param size the size of the measure specification
8261 * @param mode the mode of the measure specification
8262 * @return the measure specification based on size and mode
8263 */
8264 public static int makeMeasureSpec(int size, int mode) {
8265 return size + mode;
8266 }
8267
8268 /**
8269 * Extracts the mode from the supplied measure specification.
8270 *
8271 * @param measureSpec the measure specification to extract the mode from
8272 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
8273 * {@link android.view.View.MeasureSpec#AT_MOST} or
8274 * {@link android.view.View.MeasureSpec#EXACTLY}
8275 */
8276 public static int getMode(int measureSpec) {
8277 return (measureSpec & MODE_MASK);
8278 }
8279
8280 /**
8281 * Extracts the size from the supplied measure specification.
8282 *
8283 * @param measureSpec the measure specification to extract the size from
8284 * @return the size in pixels defined in the supplied measure specification
8285 */
8286 public static int getSize(int measureSpec) {
8287 return (measureSpec & ~MODE_MASK);
8288 }
8289
8290 /**
8291 * Returns a String representation of the specified measure
8292 * specification.
8293 *
8294 * @param measureSpec the measure specification to convert to a String
8295 * @return a String with the following format: "MeasureSpec: MODE SIZE"
8296 */
8297 public static String toString(int measureSpec) {
8298 int mode = getMode(measureSpec);
8299 int size = getSize(measureSpec);
8300
8301 StringBuilder sb = new StringBuilder("MeasureSpec: ");
8302
8303 if (mode == UNSPECIFIED)
8304 sb.append("UNSPECIFIED ");
8305 else if (mode == EXACTLY)
8306 sb.append("EXACTLY ");
8307 else if (mode == AT_MOST)
8308 sb.append("AT_MOST ");
8309 else
8310 sb.append(mode).append(" ");
8311
8312 sb.append(size);
8313 return sb.toString();
8314 }
8315 }
8316
8317 class CheckForLongPress implements Runnable {
8318
8319 private int mOriginalWindowAttachCount;
8320
8321 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -07008322 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008323 && mOriginalWindowAttachCount == mWindowAttachCount) {
8324 if (performLongClick()) {
8325 mHasPerformedLongPress = true;
8326 }
8327 }
8328 }
8329
8330 public void rememberWindowAttachCount() {
8331 mOriginalWindowAttachCount = mWindowAttachCount;
8332 }
8333 }
8334
8335 /**
8336 * Interface definition for a callback to be invoked when a key event is
8337 * dispatched to this view. The callback will be invoked before the key
8338 * event is given to the view.
8339 */
8340 public interface OnKeyListener {
8341 /**
8342 * Called when a key is dispatched to a view. This allows listeners to
8343 * get a chance to respond before the target view.
8344 *
8345 * @param v The view the key has been dispatched to.
8346 * @param keyCode The code for the physical key that was pressed
8347 * @param event The KeyEvent object containing full information about
8348 * the event.
8349 * @return True if the listener has consumed the event, false otherwise.
8350 */
8351 boolean onKey(View v, int keyCode, KeyEvent event);
8352 }
8353
8354 /**
8355 * Interface definition for a callback to be invoked when a touch event is
8356 * dispatched to this view. The callback will be invoked before the touch
8357 * event is given to the view.
8358 */
8359 public interface OnTouchListener {
8360 /**
8361 * Called when a touch event is dispatched to a view. This allows listeners to
8362 * get a chance to respond before the target view.
8363 *
8364 * @param v The view the touch event has been dispatched to.
8365 * @param event The MotionEvent object containing full information about
8366 * the event.
8367 * @return True if the listener has consumed the event, false otherwise.
8368 */
8369 boolean onTouch(View v, MotionEvent event);
8370 }
8371
8372 /**
8373 * Interface definition for a callback to be invoked when a view has been clicked and held.
8374 */
8375 public interface OnLongClickListener {
8376 /**
8377 * Called when a view has been clicked and held.
8378 *
8379 * @param v The view that was clicked and held.
8380 *
8381 * return True if the callback consumed the long click, false otherwise
8382 */
8383 boolean onLongClick(View v);
8384 }
8385
8386 /**
8387 * Interface definition for a callback to be invoked when the focus state of
8388 * a view changed.
8389 */
8390 public interface OnFocusChangeListener {
8391 /**
8392 * Called when the focus state of a view has changed.
8393 *
8394 * @param v The view whose state has changed.
8395 * @param hasFocus The new focus state of v.
8396 */
8397 void onFocusChange(View v, boolean hasFocus);
8398 }
8399
8400 /**
8401 * Interface definition for a callback to be invoked when a view is clicked.
8402 */
8403 public interface OnClickListener {
8404 /**
8405 * Called when a view has been clicked.
8406 *
8407 * @param v The view that was clicked.
8408 */
8409 void onClick(View v);
8410 }
8411
8412 /**
8413 * Interface definition for a callback to be invoked when the context menu
8414 * for this view is being built.
8415 */
8416 public interface OnCreateContextMenuListener {
8417 /**
8418 * Called when the context menu for this view is being built. It is not
8419 * safe to hold onto the menu after this method returns.
8420 *
8421 * @param menu The context menu that is being built
8422 * @param v The view for which the context menu is being built
8423 * @param menuInfo Extra information about the item for which the
8424 * context menu should be shown. This information will vary
8425 * depending on the class of v.
8426 */
8427 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
8428 }
8429
8430 private final class UnsetPressedState implements Runnable {
8431 public void run() {
8432 setPressed(false);
8433 }
8434 }
8435
8436 /**
8437 * Base class for derived classes that want to save and restore their own
8438 * state in {@link android.view.View#onSaveInstanceState()}.
8439 */
8440 public static class BaseSavedState extends AbsSavedState {
8441 /**
8442 * Constructor used when reading from a parcel. Reads the state of the superclass.
8443 *
8444 * @param source
8445 */
8446 public BaseSavedState(Parcel source) {
8447 super(source);
8448 }
8449
8450 /**
8451 * Constructor called by derived classes when creating their SavedState objects
8452 *
8453 * @param superState The state of the superclass of this view
8454 */
8455 public BaseSavedState(Parcelable superState) {
8456 super(superState);
8457 }
8458
8459 public static final Parcelable.Creator<BaseSavedState> CREATOR =
8460 new Parcelable.Creator<BaseSavedState>() {
8461 public BaseSavedState createFromParcel(Parcel in) {
8462 return new BaseSavedState(in);
8463 }
8464
8465 public BaseSavedState[] newArray(int size) {
8466 return new BaseSavedState[size];
8467 }
8468 };
8469 }
8470
8471 /**
8472 * A set of information given to a view when it is attached to its parent
8473 * window.
8474 */
8475 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476 interface Callbacks {
8477 void playSoundEffect(int effectId);
8478 boolean performHapticFeedback(int effectId, boolean always);
8479 }
8480
8481 /**
8482 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
8483 * to a Handler. This class contains the target (View) to invalidate and
8484 * the coordinates of the dirty rectangle.
8485 *
8486 * For performance purposes, this class also implements a pool of up to
8487 * POOL_LIMIT objects that get reused. This reduces memory allocations
8488 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008489 */
Romain Guyd928d682009-03-31 17:52:16 -07008490 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008491 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -07008492 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
8493 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -07008494 public InvalidateInfo newInstance() {
8495 return new InvalidateInfo();
8496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008497
Romain Guyd928d682009-03-31 17:52:16 -07008498 public void onAcquired(InvalidateInfo element) {
8499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008500
Romain Guyd928d682009-03-31 17:52:16 -07008501 public void onReleased(InvalidateInfo element) {
8502 }
8503 }, POOL_LIMIT)
8504 );
8505
8506 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008507
8508 View target;
8509
8510 int left;
8511 int top;
8512 int right;
8513 int bottom;
8514
Romain Guyd928d682009-03-31 17:52:16 -07008515 public void setNextPoolable(InvalidateInfo element) {
8516 mNext = element;
8517 }
8518
8519 public InvalidateInfo getNextPoolable() {
8520 return mNext;
8521 }
8522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008523 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -07008524 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008525 }
8526
8527 void release() {
Romain Guyd928d682009-03-31 17:52:16 -07008528 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008529 }
8530 }
8531
8532 final IWindowSession mSession;
8533
8534 final IWindow mWindow;
8535
8536 final IBinder mWindowToken;
8537
8538 final Callbacks mRootCallbacks;
8539
8540 /**
8541 * The top view of the hierarchy.
8542 */
8543 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -07008544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008545 IBinder mPanelParentWindowToken;
8546 Surface mSurface;
8547
8548 /**
Romain Guy8506ab42009-06-11 17:35:47 -07008549 * Scale factor used by the compatibility mode
8550 */
8551 float mApplicationScale;
8552
8553 /**
8554 * Indicates whether the application is in compatibility mode
8555 */
8556 boolean mScalingRequired;
8557
8558 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008559 * Left position of this view's window
8560 */
8561 int mWindowLeft;
8562
8563 /**
8564 * Top position of this view's window
8565 */
8566 int mWindowTop;
8567
8568 /**
8569 * For windows that are full-screen but using insets to layout inside
8570 * of the screen decorations, these are the current insets for the
8571 * content of the window.
8572 */
8573 final Rect mContentInsets = new Rect();
8574
8575 /**
8576 * For windows that are full-screen but using insets to layout inside
8577 * of the screen decorations, these are the current insets for the
8578 * actual visible parts of the window.
8579 */
8580 final Rect mVisibleInsets = new Rect();
8581
8582 /**
8583 * The internal insets given by this window. This value is
8584 * supplied by the client (through
8585 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
8586 * be given to the window manager when changed to be used in laying
8587 * out windows behind it.
8588 */
8589 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
8590 = new ViewTreeObserver.InternalInsetsInfo();
8591
8592 /**
8593 * All views in the window's hierarchy that serve as scroll containers,
8594 * used to determine if the window can be resized or must be panned
8595 * to adjust for a soft input area.
8596 */
8597 final ArrayList<View> mScrollContainers = new ArrayList<View>();
8598
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07008599 final KeyEvent.DispatcherState mKeyDispatchState
8600 = new KeyEvent.DispatcherState();
8601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008602 /**
8603 * Indicates whether the view's window currently has the focus.
8604 */
8605 boolean mHasWindowFocus;
8606
8607 /**
8608 * The current visibility of the window.
8609 */
8610 int mWindowVisibility;
8611
8612 /**
8613 * Indicates the time at which drawing started to occur.
8614 */
8615 long mDrawingTime;
8616
8617 /**
Romain Guy5bcdff42009-05-14 21:27:18 -07008618 * Indicates whether or not ignoring the DIRTY_MASK flags.
8619 */
8620 boolean mIgnoreDirtyState;
8621
8622 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008623 * Indicates whether the view's window is currently in touch mode.
8624 */
8625 boolean mInTouchMode;
8626
8627 /**
8628 * Indicates that ViewRoot should trigger a global layout change
8629 * the next time it performs a traversal
8630 */
8631 boolean mRecomputeGlobalAttributes;
8632
8633 /**
8634 * Set to true when attributes (like mKeepScreenOn) need to be
8635 * recomputed.
8636 */
8637 boolean mAttributesChanged;
8638
8639 /**
8640 * Set during a traveral if any views want to keep the screen on.
8641 */
8642 boolean mKeepScreenOn;
8643
8644 /**
8645 * Set if the visibility of any views has changed.
8646 */
8647 boolean mViewVisibilityChanged;
8648
8649 /**
8650 * Set to true if a view has been scrolled.
8651 */
8652 boolean mViewScrollChanged;
8653
8654 /**
8655 * Global to the view hierarchy used as a temporary for dealing with
8656 * x/y points in the transparent region computations.
8657 */
8658 final int[] mTransparentLocation = new int[2];
8659
8660 /**
8661 * Global to the view hierarchy used as a temporary for dealing with
8662 * x/y points in the ViewGroup.invalidateChild implementation.
8663 */
8664 final int[] mInvalidateChildLocation = new int[2];
8665
8666 /**
8667 * The view tree observer used to dispatch global events like
8668 * layout, pre-draw, touch mode change, etc.
8669 */
8670 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
8671
8672 /**
8673 * A Canvas used by the view hierarchy to perform bitmap caching.
8674 */
8675 Canvas mCanvas;
8676
8677 /**
8678 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
8679 * handler can be used to pump events in the UI events queue.
8680 */
8681 final Handler mHandler;
8682
8683 /**
8684 * Identifier for messages requesting the view to be invalidated.
8685 * Such messages should be sent to {@link #mHandler}.
8686 */
8687 static final int INVALIDATE_MSG = 0x1;
8688
8689 /**
8690 * Identifier for messages requesting the view to invalidate a region.
8691 * Such messages should be sent to {@link #mHandler}.
8692 */
8693 static final int INVALIDATE_RECT_MSG = 0x2;
8694
8695 /**
8696 * Temporary for use in computing invalidate rectangles while
8697 * calling up the hierarchy.
8698 */
8699 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -07008700
8701 /**
8702 * Temporary list for use in collecting focusable descendents of a view.
8703 */
8704 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
8705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706 /**
8707 * Creates a new set of attachment information with the specified
8708 * events handler and thread.
8709 *
8710 * @param handler the events handler the view must use
8711 */
8712 AttachInfo(IWindowSession session, IWindow window,
8713 Handler handler, Callbacks effectPlayer) {
8714 mSession = session;
8715 mWindow = window;
8716 mWindowToken = window.asBinder();
8717 mHandler = handler;
8718 mRootCallbacks = effectPlayer;
8719 }
8720 }
8721
8722 /**
8723 * <p>ScrollabilityCache holds various fields used by a View when scrolling
8724 * is supported. This avoids keeping too many unused fields in most
8725 * instances of View.</p>
8726 */
8727 private static class ScrollabilityCache {
8728 public int fadingEdgeLength;
8729
8730 public int scrollBarSize;
8731 public ScrollBarDrawable scrollBar;
8732
8733 public final Paint paint;
8734 public final Matrix matrix;
8735 public Shader shader;
8736
8737 private int mLastColor;
8738
8739 public ScrollabilityCache(ViewConfiguration configuration) {
8740 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
8741 scrollBarSize = configuration.getScaledScrollBarSize();
8742
8743 paint = new Paint();
8744 matrix = new Matrix();
8745 // use use a height of 1, and then wack the matrix each time we
8746 // actually use it.
8747 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -07008748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008749 paint.setShader(shader);
8750 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
8751 }
Romain Guy8506ab42009-06-11 17:35:47 -07008752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008753 public void setFadeColor(int color) {
8754 if (color != 0 && color != mLastColor) {
8755 mLastColor = color;
8756 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -07008757
Romain Guye55e1a72009-08-27 10:42:26 -07008758 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
8759 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -07008760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008761 paint.setShader(shader);
8762 // Restore the default transfer mode (src_over)
8763 paint.setXfermode(null);
8764 }
8765 }
8766 }
8767}