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