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