blob: bc494395c0d98f1d7cc5002cdcbec8cf1f88a20c [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;
Adam Powellc9fbaab2010-02-16 17:16:19 -08001507
1508 /**
1509 * Always allow a user to overscroll this view, provided it is a
1510 * view that can scroll.
1511 */
1512 private static final int OVERSCROLL_ALWAYS = 0;
1513
1514 /**
1515 * Allow a user to overscroll this view only if the content is large
1516 * enough to meaningfully scroll, provided it is a view that can scroll.
1517 */
1518 private static final int OVERSCROLL_IF_CONTENT_SCROLLS = 1;
1519
1520 /**
1521 * Never allow a user to overscroll this view.
1522 */
1523 private static final int OVERSCROLL_NEVER = 2;
1524
1525 /**
1526 * Controls the overscroll mode for this view.
1527 * See {@link #overscrollBy(int, int, int, int, int, int, int, int)},
1528 * {@link #OVERSCROLL_ALWAYS}, {@link #OVERSCROLL_IF_CONTENT_SCROLLS},
1529 * and {@link #OVERSCROLL_NEVER}.
1530 */
1531 private int mOverscrollMode = OVERSCROLL_ALWAYS;
Romain Guy8f1344f52009-05-15 16:03:59 -07001532
1533 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 * The parent this view is attached to.
1535 * {@hide}
1536 *
1537 * @see #getParent()
1538 */
1539 protected ViewParent mParent;
1540
1541 /**
1542 * {@hide}
1543 */
1544 AttachInfo mAttachInfo;
1545
1546 /**
1547 * {@hide}
1548 */
Romain Guy809a7f62009-05-14 15:44:42 -07001549 @ViewDebug.ExportedProperty(flagMapping = {
1550 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1551 name = "FORCE_LAYOUT"),
1552 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1553 name = "LAYOUT_REQUIRED"),
1554 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
Romain Guy5bcdff42009-05-14 21:27:18 -07001555 name = "DRAWING_CACHE_INVALID", outputIf = false),
Romain Guy809a7f62009-05-14 15:44:42 -07001556 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1557 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1558 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1559 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1560 })
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 int mPrivateFlags;
1562
1563 /**
1564 * Count of how many windows this view has been attached to.
1565 */
1566 int mWindowAttachCount;
1567
1568 /**
1569 * The layout parameters associated with this view and used by the parent
1570 * {@link android.view.ViewGroup} to determine how this view should be
1571 * laid out.
1572 * {@hide}
1573 */
1574 protected ViewGroup.LayoutParams mLayoutParams;
1575
1576 /**
1577 * The view flags hold various views states.
1578 * {@hide}
1579 */
1580 @ViewDebug.ExportedProperty
1581 int mViewFlags;
1582
1583 /**
1584 * The distance in pixels from the left edge of this view's parent
1585 * to the left edge of this view.
1586 * {@hide}
1587 */
1588 @ViewDebug.ExportedProperty
1589 protected int mLeft;
1590 /**
1591 * The distance in pixels from the left edge of this view's parent
1592 * to the right edge of this view.
1593 * {@hide}
1594 */
1595 @ViewDebug.ExportedProperty
1596 protected int mRight;
1597 /**
1598 * The distance in pixels from the top edge of this view's parent
1599 * to the top edge of this view.
1600 * {@hide}
1601 */
1602 @ViewDebug.ExportedProperty
1603 protected int mTop;
1604 /**
1605 * The distance in pixels from the top edge of this view's parent
1606 * to the bottom edge of this view.
1607 * {@hide}
1608 */
1609 @ViewDebug.ExportedProperty
1610 protected int mBottom;
1611
1612 /**
1613 * The offset, in pixels, by which the content of this view is scrolled
1614 * horizontally.
1615 * {@hide}
1616 */
1617 @ViewDebug.ExportedProperty
1618 protected int mScrollX;
1619 /**
1620 * The offset, in pixels, by which the content of this view is scrolled
1621 * vertically.
1622 * {@hide}
1623 */
1624 @ViewDebug.ExportedProperty
1625 protected int mScrollY;
1626
1627 /**
1628 * The left padding in pixels, that is the distance in pixels between the
1629 * left edge of this view and the left edge of its content.
1630 * {@hide}
1631 */
1632 @ViewDebug.ExportedProperty
1633 protected int mPaddingLeft;
1634 /**
1635 * The right padding in pixels, that is the distance in pixels between the
1636 * right edge of this view and the right edge of its content.
1637 * {@hide}
1638 */
1639 @ViewDebug.ExportedProperty
1640 protected int mPaddingRight;
1641 /**
1642 * The top padding in pixels, that is the distance in pixels between the
1643 * top edge of this view and the top edge of its content.
1644 * {@hide}
1645 */
1646 @ViewDebug.ExportedProperty
1647 protected int mPaddingTop;
1648 /**
1649 * The bottom padding in pixels, that is the distance in pixels between the
1650 * bottom edge of this view and the bottom edge of its content.
1651 * {@hide}
1652 */
1653 @ViewDebug.ExportedProperty
1654 protected int mPaddingBottom;
1655
1656 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07001657 * Briefly describes the view and is primarily used for accessibility support.
1658 */
1659 private CharSequence mContentDescription;
1660
1661 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 * Cache the paddingRight set by the user to append to the scrollbar's size.
1663 */
1664 @ViewDebug.ExportedProperty
1665 int mUserPaddingRight;
1666
1667 /**
1668 * Cache the paddingBottom set by the user to append to the scrollbar's size.
1669 */
1670 @ViewDebug.ExportedProperty
1671 int mUserPaddingBottom;
1672
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001673 /**
1674 * @hide
1675 */
1676 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1677 /**
1678 * @hide
1679 */
1680 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681
1682 private Resources mResources = null;
1683
1684 private Drawable mBGDrawable;
1685
1686 private int mBackgroundResource;
1687 private boolean mBackgroundSizeChanged;
1688
1689 /**
1690 * Listener used to dispatch focus change events.
1691 * This field should be made private, so it is hidden from the SDK.
1692 * {@hide}
1693 */
1694 protected OnFocusChangeListener mOnFocusChangeListener;
1695
1696 /**
1697 * Listener used to dispatch click events.
1698 * This field should be made private, so it is hidden from the SDK.
1699 * {@hide}
1700 */
1701 protected OnClickListener mOnClickListener;
1702
1703 /**
1704 * Listener used to dispatch long click events.
1705 * This field should be made private, so it is hidden from the SDK.
1706 * {@hide}
1707 */
1708 protected OnLongClickListener mOnLongClickListener;
1709
1710 /**
1711 * Listener used to build the context menu.
1712 * This field should be made private, so it is hidden from the SDK.
1713 * {@hide}
1714 */
1715 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
1716
1717 private OnKeyListener mOnKeyListener;
1718
1719 private OnTouchListener mOnTouchListener;
1720
1721 /**
1722 * The application environment this view lives in.
1723 * This field should be made private, so it is hidden from the SDK.
1724 * {@hide}
1725 */
1726 protected Context mContext;
1727
1728 private ScrollabilityCache mScrollCache;
1729
1730 private int[] mDrawableState = null;
1731
1732 private SoftReference<Bitmap> mDrawingCache;
Romain Guyfbd8f692009-06-26 14:51:58 -07001733 private SoftReference<Bitmap> mUnscaledDrawingCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734
1735 /**
1736 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
1737 * the user may specify which view to go to next.
1738 */
1739 private int mNextFocusLeftId = View.NO_ID;
1740
1741 /**
1742 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
1743 * the user may specify which view to go to next.
1744 */
1745 private int mNextFocusRightId = View.NO_ID;
1746
1747 /**
1748 * When this view has focus and the next focus is {@link #FOCUS_UP},
1749 * the user may specify which view to go to next.
1750 */
1751 private int mNextFocusUpId = View.NO_ID;
1752
1753 /**
1754 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
1755 * the user may specify which view to go to next.
1756 */
1757 private int mNextFocusDownId = View.NO_ID;
1758
1759 private CheckForLongPress mPendingCheckForLongPress;
Adam Powelle14579b2009-12-16 18:39:52 -08001760 private CheckForTap mPendingCheckForTap = null;
1761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 private UnsetPressedState mUnsetPressedState;
1763
1764 /**
1765 * Whether the long press's action has been invoked. The tap's action is invoked on the
1766 * up event while a long press is invoked as soon as the long press duration is reached, so
1767 * a long press could be performed before the tap is checked, in which case the tap's action
1768 * should not be invoked.
1769 */
1770 private boolean mHasPerformedLongPress;
1771
1772 /**
1773 * The minimum height of the view. We'll try our best to have the height
1774 * of this view to at least this amount.
1775 */
1776 @ViewDebug.ExportedProperty
1777 private int mMinHeight;
1778
1779 /**
1780 * The minimum width of the view. We'll try our best to have the width
1781 * of this view to at least this amount.
1782 */
1783 @ViewDebug.ExportedProperty
1784 private int mMinWidth;
1785
1786 /**
1787 * The delegate to handle touch events that are physically in this view
1788 * but should be handled by another view.
1789 */
1790 private TouchDelegate mTouchDelegate = null;
1791
1792 /**
1793 * Solid color to use as a background when creating the drawing cache. Enables
1794 * the cache to use 16 bit bitmaps instead of 32 bit.
1795 */
1796 private int mDrawingCacheBackgroundColor = 0;
1797
1798 /**
1799 * Special tree observer used when mAttachInfo is null.
1800 */
1801 private ViewTreeObserver mFloatingTreeObserver;
Adam Powelle14579b2009-12-16 18:39:52 -08001802
1803 /**
1804 * Cache the touch slop from the context that created the view.
1805 */
1806 private int mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807
1808 // Used for debug only
1809 static long sInstanceCount = 0;
1810
1811 /**
1812 * Simple constructor to use when creating a view from code.
1813 *
1814 * @param context The Context the view is running in, through which it can
1815 * access the current theme, resources, etc.
1816 */
1817 public View(Context context) {
1818 mContext = context;
1819 mResources = context != null ? context.getResources() : null;
Romain Guy8f1344f52009-05-15 16:03:59 -07001820 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 ++sInstanceCount;
Adam Powelle14579b2009-12-16 18:39:52 -08001822 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 }
1824
1825 /**
1826 * Constructor that is called when inflating a view from XML. This is called
1827 * when a view is being constructed from an XML file, supplying attributes
1828 * that were specified in the XML file. This version uses a default style of
1829 * 0, so the only attribute values applied are those in the Context's Theme
1830 * and the given AttributeSet.
1831 *
1832 * <p>
1833 * The method onFinishInflate() will be called after all children have been
1834 * added.
1835 *
1836 * @param context The Context the view is running in, through which it can
1837 * access the current theme, resources, etc.
1838 * @param attrs The attributes of the XML tag that is inflating the view.
1839 * @see #View(Context, AttributeSet, int)
1840 */
1841 public View(Context context, AttributeSet attrs) {
1842 this(context, attrs, 0);
1843 }
1844
1845 /**
1846 * Perform inflation from XML and apply a class-specific base style. This
1847 * constructor of View allows subclasses to use their own base style when
1848 * they are inflating. For example, a Button class's constructor would call
1849 * this version of the super class constructor and supply
1850 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
1851 * the theme's button style to modify all of the base view attributes (in
1852 * particular its background) as well as the Button class's attributes.
1853 *
1854 * @param context The Context the view is running in, through which it can
1855 * access the current theme, resources, etc.
1856 * @param attrs The attributes of the XML tag that is inflating the view.
1857 * @param defStyle The default style to apply to this view. If 0, no style
1858 * will be applied (beyond what is included in the theme). This may
1859 * either be an attribute resource, whose value will be retrieved
1860 * from the current theme, or an explicit style resource.
1861 * @see #View(Context, AttributeSet)
1862 */
1863 public View(Context context, AttributeSet attrs, int defStyle) {
1864 this(context);
1865
1866 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
1867 defStyle, 0);
1868
1869 Drawable background = null;
1870
1871 int leftPadding = -1;
1872 int topPadding = -1;
1873 int rightPadding = -1;
1874 int bottomPadding = -1;
1875
1876 int padding = -1;
1877
1878 int viewFlagValues = 0;
1879 int viewFlagMasks = 0;
1880
1881 boolean setScrollContainer = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 int x = 0;
1884 int y = 0;
1885
1886 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
1887
1888 final int N = a.getIndexCount();
1889 for (int i = 0; i < N; i++) {
1890 int attr = a.getIndex(i);
1891 switch (attr) {
1892 case com.android.internal.R.styleable.View_background:
1893 background = a.getDrawable(attr);
1894 break;
1895 case com.android.internal.R.styleable.View_padding:
1896 padding = a.getDimensionPixelSize(attr, -1);
1897 break;
1898 case com.android.internal.R.styleable.View_paddingLeft:
1899 leftPadding = a.getDimensionPixelSize(attr, -1);
1900 break;
1901 case com.android.internal.R.styleable.View_paddingTop:
1902 topPadding = a.getDimensionPixelSize(attr, -1);
1903 break;
1904 case com.android.internal.R.styleable.View_paddingRight:
1905 rightPadding = a.getDimensionPixelSize(attr, -1);
1906 break;
1907 case com.android.internal.R.styleable.View_paddingBottom:
1908 bottomPadding = a.getDimensionPixelSize(attr, -1);
1909 break;
1910 case com.android.internal.R.styleable.View_scrollX:
1911 x = a.getDimensionPixelOffset(attr, 0);
1912 break;
1913 case com.android.internal.R.styleable.View_scrollY:
1914 y = a.getDimensionPixelOffset(attr, 0);
1915 break;
1916 case com.android.internal.R.styleable.View_id:
1917 mID = a.getResourceId(attr, NO_ID);
1918 break;
1919 case com.android.internal.R.styleable.View_tag:
1920 mTag = a.getText(attr);
1921 break;
1922 case com.android.internal.R.styleable.View_fitsSystemWindows:
1923 if (a.getBoolean(attr, false)) {
1924 viewFlagValues |= FITS_SYSTEM_WINDOWS;
1925 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
1926 }
1927 break;
1928 case com.android.internal.R.styleable.View_focusable:
1929 if (a.getBoolean(attr, false)) {
1930 viewFlagValues |= FOCUSABLE;
1931 viewFlagMasks |= FOCUSABLE_MASK;
1932 }
1933 break;
1934 case com.android.internal.R.styleable.View_focusableInTouchMode:
1935 if (a.getBoolean(attr, false)) {
1936 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
1937 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
1938 }
1939 break;
1940 case com.android.internal.R.styleable.View_clickable:
1941 if (a.getBoolean(attr, false)) {
1942 viewFlagValues |= CLICKABLE;
1943 viewFlagMasks |= CLICKABLE;
1944 }
1945 break;
1946 case com.android.internal.R.styleable.View_longClickable:
1947 if (a.getBoolean(attr, false)) {
1948 viewFlagValues |= LONG_CLICKABLE;
1949 viewFlagMasks |= LONG_CLICKABLE;
1950 }
1951 break;
1952 case com.android.internal.R.styleable.View_saveEnabled:
1953 if (!a.getBoolean(attr, true)) {
1954 viewFlagValues |= SAVE_DISABLED;
1955 viewFlagMasks |= SAVE_DISABLED_MASK;
1956 }
1957 break;
1958 case com.android.internal.R.styleable.View_duplicateParentState:
1959 if (a.getBoolean(attr, false)) {
1960 viewFlagValues |= DUPLICATE_PARENT_STATE;
1961 viewFlagMasks |= DUPLICATE_PARENT_STATE;
1962 }
1963 break;
1964 case com.android.internal.R.styleable.View_visibility:
1965 final int visibility = a.getInt(attr, 0);
1966 if (visibility != 0) {
1967 viewFlagValues |= VISIBILITY_FLAGS[visibility];
1968 viewFlagMasks |= VISIBILITY_MASK;
1969 }
1970 break;
1971 case com.android.internal.R.styleable.View_drawingCacheQuality:
1972 final int cacheQuality = a.getInt(attr, 0);
1973 if (cacheQuality != 0) {
1974 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
1975 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
1976 }
1977 break;
svetoslavganov75986cf2009-05-14 22:28:01 -07001978 case com.android.internal.R.styleable.View_contentDescription:
1979 mContentDescription = a.getString(attr);
1980 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 case com.android.internal.R.styleable.View_soundEffectsEnabled:
1982 if (!a.getBoolean(attr, true)) {
1983 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
1984 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
1985 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07001986 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
1988 if (!a.getBoolean(attr, true)) {
1989 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
1990 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
1991 }
Karl Rosaen61ab2702009-06-23 11:10:25 -07001992 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 case R.styleable.View_scrollbars:
1994 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
1995 if (scrollbars != SCROLLBARS_NONE) {
1996 viewFlagValues |= scrollbars;
1997 viewFlagMasks |= SCROLLBARS_MASK;
1998 initializeScrollbars(a);
1999 }
2000 break;
2001 case R.styleable.View_fadingEdge:
2002 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2003 if (fadingEdge != FADING_EDGE_NONE) {
2004 viewFlagValues |= fadingEdge;
2005 viewFlagMasks |= FADING_EDGE_MASK;
2006 initializeFadingEdge(a);
2007 }
2008 break;
2009 case R.styleable.View_scrollbarStyle:
2010 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2011 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2012 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2013 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2014 }
2015 break;
2016 case R.styleable.View_isScrollContainer:
2017 setScrollContainer = true;
2018 if (a.getBoolean(attr, false)) {
2019 setScrollContainer(true);
2020 }
2021 break;
2022 case com.android.internal.R.styleable.View_keepScreenOn:
2023 if (a.getBoolean(attr, false)) {
2024 viewFlagValues |= KEEP_SCREEN_ON;
2025 viewFlagMasks |= KEEP_SCREEN_ON;
2026 }
2027 break;
2028 case R.styleable.View_nextFocusLeft:
2029 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2030 break;
2031 case R.styleable.View_nextFocusRight:
2032 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2033 break;
2034 case R.styleable.View_nextFocusUp:
2035 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2036 break;
2037 case R.styleable.View_nextFocusDown:
2038 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2039 break;
2040 case R.styleable.View_minWidth:
2041 mMinWidth = a.getDimensionPixelSize(attr, 0);
2042 break;
2043 case R.styleable.View_minHeight:
2044 mMinHeight = a.getDimensionPixelSize(attr, 0);
2045 break;
Romain Guy9a817362009-05-01 10:57:14 -07002046 case R.styleable.View_onClick:
Romain Guy870e09f2009-07-06 16:35:25 -07002047 if (context.isRestricted()) {
2048 throw new IllegalStateException("The android:onClick attribute cannot "
2049 + "be used within a restricted context");
2050 }
2051
Romain Guy9a817362009-05-01 10:57:14 -07002052 final String handlerName = a.getString(attr);
2053 if (handlerName != null) {
2054 setOnClickListener(new OnClickListener() {
2055 private Method mHandler;
2056
2057 public void onClick(View v) {
2058 if (mHandler == null) {
2059 try {
2060 mHandler = getContext().getClass().getMethod(handlerName,
2061 View.class);
2062 } catch (NoSuchMethodException e) {
2063 throw new IllegalStateException("Could not find a method " +
2064 handlerName + "(View) in the activity", e);
2065 }
2066 }
2067
2068 try {
2069 mHandler.invoke(getContext(), View.this);
2070 } catch (IllegalAccessException e) {
2071 throw new IllegalStateException("Could not execute non "
2072 + "public method of the activity", e);
2073 } catch (InvocationTargetException e) {
2074 throw new IllegalStateException("Could not execute "
2075 + "method of the activity", e);
2076 }
2077 }
2078 });
2079 }
2080 break;
Adam Powellc9fbaab2010-02-16 17:16:19 -08002081 case R.styleable.View_overscrollMode:
2082 mOverscrollMode = a.getInt(attr, OVERSCROLL_ALWAYS);
2083 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 }
2085 }
2086
2087 if (background != null) {
2088 setBackgroundDrawable(background);
2089 }
2090
2091 if (padding >= 0) {
2092 leftPadding = padding;
2093 topPadding = padding;
2094 rightPadding = padding;
2095 bottomPadding = padding;
2096 }
2097
2098 // If the user specified the padding (either with android:padding or
2099 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2100 // use the default padding or the padding from the background drawable
2101 // (stored at this point in mPadding*)
2102 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2103 topPadding >= 0 ? topPadding : mPaddingTop,
2104 rightPadding >= 0 ? rightPadding : mPaddingRight,
2105 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2106
2107 if (viewFlagMasks != 0) {
2108 setFlags(viewFlagValues, viewFlagMasks);
2109 }
2110
2111 // Needs to be called after mViewFlags is set
2112 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2113 recomputePadding();
2114 }
2115
2116 if (x != 0 || y != 0) {
2117 scrollTo(x, y);
2118 }
2119
2120 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2121 setScrollContainer(true);
2122 }
Romain Guy8f1344f52009-05-15 16:03:59 -07002123
2124 computeOpaqueFlags();
2125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 a.recycle();
2127 }
2128
2129 /**
2130 * Non-public constructor for use in testing
2131 */
2132 View() {
2133 }
2134
2135 @Override
2136 protected void finalize() throws Throwable {
2137 super.finalize();
2138 --sInstanceCount;
2139 }
2140
2141 /**
2142 * <p>
2143 * Initializes the fading edges from a given set of styled attributes. This
2144 * method should be called by subclasses that need fading edges and when an
2145 * instance of these subclasses is created programmatically rather than
2146 * being inflated from XML. This method is automatically called when the XML
2147 * is inflated.
2148 * </p>
2149 *
2150 * @param a the styled attributes set to initialize the fading edges from
2151 */
2152 protected void initializeFadingEdge(TypedArray a) {
2153 initScrollCache();
2154
2155 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2156 R.styleable.View_fadingEdgeLength,
2157 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2158 }
2159
2160 /**
2161 * Returns the size of the vertical faded edges used to indicate that more
2162 * content in this view is visible.
2163 *
2164 * @return The size in pixels of the vertical faded edge or 0 if vertical
2165 * faded edges are not enabled for this view.
2166 * @attr ref android.R.styleable#View_fadingEdgeLength
2167 */
2168 public int getVerticalFadingEdgeLength() {
2169 if (isVerticalFadingEdgeEnabled()) {
2170 ScrollabilityCache cache = mScrollCache;
2171 if (cache != null) {
2172 return cache.fadingEdgeLength;
2173 }
2174 }
2175 return 0;
2176 }
2177
2178 /**
2179 * Set the size of the faded edge used to indicate that more content in this
2180 * view is available. Will not change whether the fading edge is enabled; use
2181 * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2182 * to enable the fading edge for the vertical or horizontal fading edges.
2183 *
2184 * @param length The size in pixels of the faded edge used to indicate that more
2185 * content in this view is visible.
2186 */
2187 public void setFadingEdgeLength(int length) {
2188 initScrollCache();
2189 mScrollCache.fadingEdgeLength = length;
2190 }
2191
2192 /**
2193 * Returns the size of the horizontal faded edges used to indicate that more
2194 * content in this view is visible.
2195 *
2196 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2197 * faded edges are not enabled for this view.
2198 * @attr ref android.R.styleable#View_fadingEdgeLength
2199 */
2200 public int getHorizontalFadingEdgeLength() {
2201 if (isHorizontalFadingEdgeEnabled()) {
2202 ScrollabilityCache cache = mScrollCache;
2203 if (cache != null) {
2204 return cache.fadingEdgeLength;
2205 }
2206 }
2207 return 0;
2208 }
2209
2210 /**
2211 * Returns the width of the vertical scrollbar.
2212 *
2213 * @return The width in pixels of the vertical scrollbar or 0 if there
2214 * is no vertical scrollbar.
2215 */
2216 public int getVerticalScrollbarWidth() {
2217 ScrollabilityCache cache = mScrollCache;
2218 if (cache != null) {
2219 ScrollBarDrawable scrollBar = cache.scrollBar;
2220 if (scrollBar != null) {
2221 int size = scrollBar.getSize(true);
2222 if (size <= 0) {
2223 size = cache.scrollBarSize;
2224 }
2225 return size;
2226 }
2227 return 0;
2228 }
2229 return 0;
2230 }
2231
2232 /**
2233 * Returns the height of the horizontal scrollbar.
2234 *
2235 * @return The height in pixels of the horizontal scrollbar or 0 if
2236 * there is no horizontal scrollbar.
2237 */
2238 protected int getHorizontalScrollbarHeight() {
2239 ScrollabilityCache cache = mScrollCache;
2240 if (cache != null) {
2241 ScrollBarDrawable scrollBar = cache.scrollBar;
2242 if (scrollBar != null) {
2243 int size = scrollBar.getSize(false);
2244 if (size <= 0) {
2245 size = cache.scrollBarSize;
2246 }
2247 return size;
2248 }
2249 return 0;
2250 }
2251 return 0;
2252 }
2253
2254 /**
2255 * <p>
2256 * Initializes the scrollbars from a given set of styled attributes. This
2257 * method should be called by subclasses that need scrollbars and when an
2258 * instance of these subclasses is created programmatically rather than
2259 * being inflated from XML. This method is automatically called when the XML
2260 * is inflated.
2261 * </p>
2262 *
2263 * @param a the styled attributes set to initialize the scrollbars from
2264 */
2265 protected void initializeScrollbars(TypedArray a) {
2266 initScrollCache();
2267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 final ScrollabilityCache scrollabilityCache = mScrollCache;
Mike Cleronf116bf82009-09-27 19:14:12 -07002269
2270 if (scrollabilityCache.scrollBar == null) {
2271 scrollabilityCache.scrollBar = new ScrollBarDrawable();
2272 }
2273
2274 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275
Mike Cleronf116bf82009-09-27 19:14:12 -07002276 if (!fadeScrollbars) {
2277 scrollabilityCache.state = ScrollabilityCache.ON;
2278 }
2279 scrollabilityCache.fadeScrollBars = fadeScrollbars;
2280
2281
2282 scrollabilityCache.scrollBarFadeDuration = a.getInt(
2283 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2284 .getScrollBarFadeDuration());
2285 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2286 R.styleable.View_scrollbarDefaultDelayBeforeFade,
2287 ViewConfiguration.getScrollDefaultDelay());
2288
2289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2291 com.android.internal.R.styleable.View_scrollbarSize,
2292 ViewConfiguration.get(mContext).getScaledScrollBarSize());
2293
2294 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2295 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2296
2297 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2298 if (thumb != null) {
2299 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2300 }
2301
2302 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2303 false);
2304 if (alwaysDraw) {
2305 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2306 }
2307
2308 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2309 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2310
2311 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2312 if (thumb != null) {
2313 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2314 }
2315
2316 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2317 false);
2318 if (alwaysDraw) {
2319 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2320 }
2321
2322 // Re-apply user/background padding so that scrollbar(s) get added
2323 recomputePadding();
2324 }
2325
2326 /**
2327 * <p>
2328 * Initalizes the scrollability cache if necessary.
2329 * </p>
2330 */
2331 private void initScrollCache() {
2332 if (mScrollCache == null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07002333 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 }
2335 }
2336
2337 /**
2338 * Register a callback to be invoked when focus of this view changed.
2339 *
2340 * @param l The callback that will run.
2341 */
2342 public void setOnFocusChangeListener(OnFocusChangeListener l) {
2343 mOnFocusChangeListener = l;
2344 }
2345
2346 /**
2347 * Returns the focus-change callback registered for this view.
2348 *
2349 * @return The callback, or null if one is not registered.
2350 */
2351 public OnFocusChangeListener getOnFocusChangeListener() {
2352 return mOnFocusChangeListener;
2353 }
2354
2355 /**
2356 * Register a callback to be invoked when this view is clicked. If this view is not
2357 * clickable, it becomes clickable.
2358 *
2359 * @param l The callback that will run
2360 *
2361 * @see #setClickable(boolean)
2362 */
2363 public void setOnClickListener(OnClickListener l) {
2364 if (!isClickable()) {
2365 setClickable(true);
2366 }
2367 mOnClickListener = l;
2368 }
2369
2370 /**
2371 * Register a callback to be invoked when this view is clicked and held. If this view is not
2372 * long clickable, it becomes long clickable.
2373 *
2374 * @param l The callback that will run
2375 *
2376 * @see #setLongClickable(boolean)
2377 */
2378 public void setOnLongClickListener(OnLongClickListener l) {
2379 if (!isLongClickable()) {
2380 setLongClickable(true);
2381 }
2382 mOnLongClickListener = l;
2383 }
2384
2385 /**
2386 * Register a callback to be invoked when the context menu for this view is
2387 * being built. If this view is not long clickable, it becomes long clickable.
2388 *
2389 * @param l The callback that will run
2390 *
2391 */
2392 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2393 if (!isLongClickable()) {
2394 setLongClickable(true);
2395 }
2396 mOnCreateContextMenuListener = l;
2397 }
2398
2399 /**
2400 * Call this view's OnClickListener, if it is defined.
2401 *
2402 * @return True there was an assigned OnClickListener that was called, false
2403 * otherwise is returned.
2404 */
2405 public boolean performClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002406 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 if (mOnClickListener != null) {
2409 playSoundEffect(SoundEffectConstants.CLICK);
2410 mOnClickListener.onClick(this);
2411 return true;
2412 }
2413
2414 return false;
2415 }
2416
2417 /**
2418 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu
2419 * if the OnLongClickListener did not consume the event.
2420 *
2421 * @return True there was an assigned OnLongClickListener that was called, false
2422 * otherwise is returned.
2423 */
2424 public boolean performLongClick() {
svetoslavganov75986cf2009-05-14 22:28:01 -07002425 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427 boolean handled = false;
2428 if (mOnLongClickListener != null) {
2429 handled = mOnLongClickListener.onLongClick(View.this);
2430 }
2431 if (!handled) {
2432 handled = showContextMenu();
2433 }
2434 if (handled) {
2435 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2436 }
2437 return handled;
2438 }
2439
2440 /**
2441 * Bring up the context menu for this view.
2442 *
2443 * @return Whether a context menu was displayed.
2444 */
2445 public boolean showContextMenu() {
2446 return getParent().showContextMenuForChild(this);
2447 }
2448
2449 /**
2450 * Register a callback to be invoked when a key is pressed in this view.
2451 * @param l the key listener to attach to this view
2452 */
2453 public void setOnKeyListener(OnKeyListener l) {
2454 mOnKeyListener = l;
2455 }
2456
2457 /**
2458 * Register a callback to be invoked when a touch event is sent to this view.
2459 * @param l the touch listener to attach to this view
2460 */
2461 public void setOnTouchListener(OnTouchListener l) {
2462 mOnTouchListener = l;
2463 }
2464
2465 /**
2466 * Give this view focus. This will cause {@link #onFocusChanged} to be called.
2467 *
2468 * Note: this does not check whether this {@link View} should get focus, it just
2469 * gives it focus no matter what. It should only be called internally by framework
2470 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
2471 *
2472 * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
2473 * View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
2474 * focus moved when requestFocus() is called. It may not always
2475 * apply, in which case use the default View.FOCUS_DOWN.
2476 * @param previouslyFocusedRect The rectangle of the view that had focus
2477 * prior in this View's coordinate system.
2478 */
2479 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
2480 if (DBG) {
2481 System.out.println(this + " requestFocus()");
2482 }
2483
2484 if ((mPrivateFlags & FOCUSED) == 0) {
2485 mPrivateFlags |= FOCUSED;
2486
2487 if (mParent != null) {
2488 mParent.requestChildFocus(this, this);
2489 }
2490
2491 onFocusChanged(true, direction, previouslyFocusedRect);
2492 refreshDrawableState();
2493 }
2494 }
2495
2496 /**
2497 * Request that a rectangle of this view be visible on the screen,
2498 * scrolling if necessary just enough.
2499 *
2500 * <p>A View should call this if it maintains some notion of which part
2501 * of its content is interesting. For example, a text editing view
2502 * should call this when its cursor moves.
2503 *
2504 * @param rectangle The rectangle.
2505 * @return Whether any parent scrolled.
2506 */
2507 public boolean requestRectangleOnScreen(Rect rectangle) {
2508 return requestRectangleOnScreen(rectangle, false);
2509 }
2510
2511 /**
2512 * Request that a rectangle of this view be visible on the screen,
2513 * scrolling if necessary just enough.
2514 *
2515 * <p>A View should call this if it maintains some notion of which part
2516 * of its content is interesting. For example, a text editing view
2517 * should call this when its cursor moves.
2518 *
2519 * <p>When <code>immediate</code> is set to true, scrolling will not be
2520 * animated.
2521 *
2522 * @param rectangle The rectangle.
2523 * @param immediate True to forbid animated scrolling, false otherwise
2524 * @return Whether any parent scrolled.
2525 */
2526 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
2527 View child = this;
2528 ViewParent parent = mParent;
2529 boolean scrolled = false;
2530 while (parent != null) {
2531 scrolled |= parent.requestChildRectangleOnScreen(child,
2532 rectangle, immediate);
2533
2534 // offset rect so next call has the rectangle in the
2535 // coordinate system of its direct child.
2536 rectangle.offset(child.getLeft(), child.getTop());
2537 rectangle.offset(-child.getScrollX(), -child.getScrollY());
2538
2539 if (!(parent instanceof View)) {
2540 break;
2541 }
Romain Guy8506ab42009-06-11 17:35:47 -07002542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 child = (View) parent;
2544 parent = child.getParent();
2545 }
2546 return scrolled;
2547 }
2548
2549 /**
2550 * Called when this view wants to give up focus. This will cause
2551 * {@link #onFocusChanged} to be called.
2552 */
2553 public void clearFocus() {
2554 if (DBG) {
2555 System.out.println(this + " clearFocus()");
2556 }
2557
2558 if ((mPrivateFlags & FOCUSED) != 0) {
2559 mPrivateFlags &= ~FOCUSED;
2560
2561 if (mParent != null) {
2562 mParent.clearChildFocus(this);
2563 }
2564
2565 onFocusChanged(false, 0, null);
2566 refreshDrawableState();
2567 }
2568 }
2569
2570 /**
2571 * Called to clear the focus of a view that is about to be removed.
2572 * Doesn't call clearChildFocus, which prevents this view from taking
2573 * focus again before it has been removed from the parent
2574 */
2575 void clearFocusForRemoval() {
2576 if ((mPrivateFlags & FOCUSED) != 0) {
2577 mPrivateFlags &= ~FOCUSED;
2578
2579 onFocusChanged(false, 0, null);
2580 refreshDrawableState();
2581 }
2582 }
2583
2584 /**
2585 * Called internally by the view system when a new view is getting focus.
2586 * This is what clears the old focus.
2587 */
2588 void unFocus() {
2589 if (DBG) {
2590 System.out.println(this + " unFocus()");
2591 }
2592
2593 if ((mPrivateFlags & FOCUSED) != 0) {
2594 mPrivateFlags &= ~FOCUSED;
2595
2596 onFocusChanged(false, 0, null);
2597 refreshDrawableState();
2598 }
2599 }
2600
2601 /**
2602 * Returns true if this view has focus iteself, or is the ancestor of the
2603 * view that has focus.
2604 *
2605 * @return True if this view has or contains focus, false otherwise.
2606 */
2607 @ViewDebug.ExportedProperty
2608 public boolean hasFocus() {
2609 return (mPrivateFlags & FOCUSED) != 0;
2610 }
2611
2612 /**
2613 * Returns true if this view is focusable or if it contains a reachable View
2614 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
2615 * is a View whose parents do not block descendants focus.
2616 *
2617 * Only {@link #VISIBLE} views are considered focusable.
2618 *
2619 * @return True if the view is focusable or if the view contains a focusable
2620 * View, false otherwise.
2621 *
2622 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
2623 */
2624 public boolean hasFocusable() {
2625 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
2626 }
2627
2628 /**
2629 * Called by the view system when the focus state of this view changes.
2630 * When the focus change event is caused by directional navigation, direction
2631 * and previouslyFocusedRect provide insight into where the focus is coming from.
2632 * When overriding, be sure to call up through to the super class so that
2633 * the standard focus handling will occur.
Romain Guy8506ab42009-06-11 17:35:47 -07002634 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 * @param gainFocus True if the View has focus; false otherwise.
2636 * @param direction The direction focus has moved when requestFocus()
2637 * is called to give this view focus. Values are
Romain Guyea4823c2009-12-08 15:03:39 -08002638 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT} or
2639 * {@link #FOCUS_RIGHT}. It may not always apply, in which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 * case use the default.
2641 * @param previouslyFocusedRect The rectangle, in this view's coordinate
2642 * system, of the previously focused view. If applicable, this will be
2643 * passed in as finer grained information about where the focus is coming
2644 * from (in addition to direction). Will be <code>null</code> otherwise.
2645 */
2646 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
svetoslavganov75986cf2009-05-14 22:28:01 -07002647 if (gainFocus) {
2648 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2649 }
2650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 InputMethodManager imm = InputMethodManager.peekInstance();
2652 if (!gainFocus) {
2653 if (isPressed()) {
2654 setPressed(false);
2655 }
2656 if (imm != null && mAttachInfo != null
2657 && mAttachInfo.mHasWindowFocus) {
2658 imm.focusOut(this);
2659 }
Romain Guya2431d02009-04-30 16:30:00 -07002660 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 } else if (imm != null && mAttachInfo != null
2662 && mAttachInfo.mHasWindowFocus) {
2663 imm.focusIn(this);
2664 }
Romain Guy8506ab42009-06-11 17:35:47 -07002665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 invalidate();
2667 if (mOnFocusChangeListener != null) {
2668 mOnFocusChangeListener.onFocusChange(this, gainFocus);
2669 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002670
2671 if (mAttachInfo != null) {
2672 mAttachInfo.mKeyDispatchState.reset(this);
2673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 }
2675
2676 /**
svetoslavganov75986cf2009-05-14 22:28:01 -07002677 * {@inheritDoc}
2678 */
2679 public void sendAccessibilityEvent(int eventType) {
2680 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
2681 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
2682 }
2683 }
2684
2685 /**
2686 * {@inheritDoc}
2687 */
2688 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
2689 event.setClassName(getClass().getName());
2690 event.setPackageName(getContext().getPackageName());
2691 event.setEnabled(isEnabled());
2692 event.setContentDescription(mContentDescription);
2693
2694 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
2695 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
2696 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
2697 event.setItemCount(focusablesTempList.size());
2698 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
2699 focusablesTempList.clear();
2700 }
2701
2702 dispatchPopulateAccessibilityEvent(event);
2703
2704 AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
2705 }
2706
2707 /**
2708 * Dispatches an {@link AccessibilityEvent} to the {@link View} children
2709 * to be populated.
2710 *
2711 * @param event The event.
2712 *
2713 * @return True if the event population was completed.
2714 */
2715 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2716 return false;
2717 }
2718
2719 /**
2720 * Gets the {@link View} description. It briefly describes the view and is
2721 * primarily used for accessibility support. Set this property to enable
2722 * better accessibility support for your application. This is especially
2723 * true for views that do not have textual representation (For example,
2724 * ImageButton).
2725 *
2726 * @return The content descriptiopn.
2727 *
2728 * @attr ref android.R.styleable#View_contentDescription
2729 */
2730 public CharSequence getContentDescription() {
2731 return mContentDescription;
2732 }
2733
2734 /**
2735 * Sets the {@link View} description. It briefly describes the view and is
2736 * primarily used for accessibility support. Set this property to enable
2737 * better accessibility support for your application. This is especially
2738 * true for views that do not have textual representation (For example,
2739 * ImageButton).
2740 *
2741 * @param contentDescription The content description.
2742 *
2743 * @attr ref android.R.styleable#View_contentDescription
2744 */
2745 public void setContentDescription(CharSequence contentDescription) {
2746 mContentDescription = contentDescription;
2747 }
2748
2749 /**
Romain Guya2431d02009-04-30 16:30:00 -07002750 * Invoked whenever this view loses focus, either by losing window focus or by losing
2751 * focus within its window. This method can be used to clear any state tied to the
2752 * focus. For instance, if a button is held pressed with the trackball and the window
2753 * loses focus, this method can be used to cancel the press.
2754 *
2755 * Subclasses of View overriding this method should always call super.onFocusLost().
2756 *
2757 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
Romain Guy8506ab42009-06-11 17:35:47 -07002758 * @see #onWindowFocusChanged(boolean)
Romain Guya2431d02009-04-30 16:30:00 -07002759 *
2760 * @hide pending API council approval
2761 */
2762 protected void onFocusLost() {
2763 resetPressedState();
2764 }
2765
2766 private void resetPressedState() {
2767 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
2768 return;
2769 }
2770
2771 if (isPressed()) {
2772 setPressed(false);
2773
2774 if (!mHasPerformedLongPress) {
Maryam Garrett1549dd12009-12-15 16:06:36 -05002775 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07002776 }
2777 }
2778 }
2779
2780 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 * Returns true if this view has focus
2782 *
2783 * @return True if this view has focus, false otherwise.
2784 */
2785 @ViewDebug.ExportedProperty
2786 public boolean isFocused() {
2787 return (mPrivateFlags & FOCUSED) != 0;
2788 }
2789
2790 /**
2791 * Find the view in the hierarchy rooted at this view that currently has
2792 * focus.
2793 *
2794 * @return The view that currently has focus, or null if no focused view can
2795 * be found.
2796 */
2797 public View findFocus() {
2798 return (mPrivateFlags & FOCUSED) != 0 ? this : null;
2799 }
2800
2801 /**
2802 * Change whether this view is one of the set of scrollable containers in
2803 * its window. This will be used to determine whether the window can
2804 * resize or must pan when a soft input area is open -- scrollable
2805 * containers allow the window to use resize mode since the container
2806 * will appropriately shrink.
2807 */
2808 public void setScrollContainer(boolean isScrollContainer) {
2809 if (isScrollContainer) {
2810 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
2811 mAttachInfo.mScrollContainers.add(this);
2812 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
2813 }
2814 mPrivateFlags |= SCROLL_CONTAINER;
2815 } else {
2816 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
2817 mAttachInfo.mScrollContainers.remove(this);
2818 }
2819 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
2820 }
2821 }
2822
2823 /**
2824 * Returns the quality of the drawing cache.
2825 *
2826 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
2827 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
2828 *
2829 * @see #setDrawingCacheQuality(int)
2830 * @see #setDrawingCacheEnabled(boolean)
2831 * @see #isDrawingCacheEnabled()
2832 *
2833 * @attr ref android.R.styleable#View_drawingCacheQuality
2834 */
2835 public int getDrawingCacheQuality() {
2836 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
2837 }
2838
2839 /**
2840 * Set the drawing cache quality of this view. This value is used only when the
2841 * drawing cache is enabled
2842 *
2843 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
2844 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
2845 *
2846 * @see #getDrawingCacheQuality()
2847 * @see #setDrawingCacheEnabled(boolean)
2848 * @see #isDrawingCacheEnabled()
2849 *
2850 * @attr ref android.R.styleable#View_drawingCacheQuality
2851 */
2852 public void setDrawingCacheQuality(int quality) {
2853 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
2854 }
2855
2856 /**
2857 * Returns whether the screen should remain on, corresponding to the current
2858 * value of {@link #KEEP_SCREEN_ON}.
2859 *
2860 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
2861 *
2862 * @see #setKeepScreenOn(boolean)
2863 *
2864 * @attr ref android.R.styleable#View_keepScreenOn
2865 */
2866 public boolean getKeepScreenOn() {
2867 return (mViewFlags & KEEP_SCREEN_ON) != 0;
2868 }
2869
2870 /**
2871 * Controls whether the screen should remain on, modifying the
2872 * value of {@link #KEEP_SCREEN_ON}.
2873 *
2874 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
2875 *
2876 * @see #getKeepScreenOn()
2877 *
2878 * @attr ref android.R.styleable#View_keepScreenOn
2879 */
2880 public void setKeepScreenOn(boolean keepScreenOn) {
2881 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
2882 }
2883
2884 /**
2885 * @return The user specified next focus ID.
2886 *
2887 * @attr ref android.R.styleable#View_nextFocusLeft
2888 */
2889 public int getNextFocusLeftId() {
2890 return mNextFocusLeftId;
2891 }
2892
2893 /**
2894 * Set the id of the view to use for the next focus
2895 *
2896 * @param nextFocusLeftId
2897 *
2898 * @attr ref android.R.styleable#View_nextFocusLeft
2899 */
2900 public void setNextFocusLeftId(int nextFocusLeftId) {
2901 mNextFocusLeftId = nextFocusLeftId;
2902 }
2903
2904 /**
2905 * @return The user specified next focus ID.
2906 *
2907 * @attr ref android.R.styleable#View_nextFocusRight
2908 */
2909 public int getNextFocusRightId() {
2910 return mNextFocusRightId;
2911 }
2912
2913 /**
2914 * Set the id of the view to use for the next focus
2915 *
2916 * @param nextFocusRightId
2917 *
2918 * @attr ref android.R.styleable#View_nextFocusRight
2919 */
2920 public void setNextFocusRightId(int nextFocusRightId) {
2921 mNextFocusRightId = nextFocusRightId;
2922 }
2923
2924 /**
2925 * @return The user specified next focus ID.
2926 *
2927 * @attr ref android.R.styleable#View_nextFocusUp
2928 */
2929 public int getNextFocusUpId() {
2930 return mNextFocusUpId;
2931 }
2932
2933 /**
2934 * Set the id of the view to use for the next focus
2935 *
2936 * @param nextFocusUpId
2937 *
2938 * @attr ref android.R.styleable#View_nextFocusUp
2939 */
2940 public void setNextFocusUpId(int nextFocusUpId) {
2941 mNextFocusUpId = nextFocusUpId;
2942 }
2943
2944 /**
2945 * @return The user specified next focus ID.
2946 *
2947 * @attr ref android.R.styleable#View_nextFocusDown
2948 */
2949 public int getNextFocusDownId() {
2950 return mNextFocusDownId;
2951 }
2952
2953 /**
2954 * Set the id of the view to use for the next focus
2955 *
2956 * @param nextFocusDownId
2957 *
2958 * @attr ref android.R.styleable#View_nextFocusDown
2959 */
2960 public void setNextFocusDownId(int nextFocusDownId) {
2961 mNextFocusDownId = nextFocusDownId;
2962 }
2963
2964 /**
2965 * Returns the visibility of this view and all of its ancestors
2966 *
2967 * @return True if this view and all of its ancestors are {@link #VISIBLE}
2968 */
2969 public boolean isShown() {
2970 View current = this;
2971 //noinspection ConstantConditions
2972 do {
2973 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
2974 return false;
2975 }
2976 ViewParent parent = current.mParent;
2977 if (parent == null) {
2978 return false; // We are not attached to the view root
2979 }
2980 if (!(parent instanceof View)) {
2981 return true;
2982 }
2983 current = (View) parent;
2984 } while (current != null);
2985
2986 return false;
2987 }
2988
2989 /**
2990 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
2991 * is set
2992 *
2993 * @param insets Insets for system windows
2994 *
2995 * @return True if this view applied the insets, false otherwise
2996 */
2997 protected boolean fitSystemWindows(Rect insets) {
2998 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
2999 mPaddingLeft = insets.left;
3000 mPaddingTop = insets.top;
3001 mPaddingRight = insets.right;
3002 mPaddingBottom = insets.bottom;
3003 requestLayout();
3004 return true;
3005 }
3006 return false;
3007 }
3008
3009 /**
3010 * Returns the visibility status for this view.
3011 *
3012 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3013 * @attr ref android.R.styleable#View_visibility
3014 */
3015 @ViewDebug.ExportedProperty(mapping = {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003016 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
3017 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3018 @ViewDebug.IntToString(from = GONE, to = "GONE")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 })
3020 public int getVisibility() {
3021 return mViewFlags & VISIBILITY_MASK;
3022 }
3023
3024 /**
3025 * Set the enabled state of this view.
3026 *
3027 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3028 * @attr ref android.R.styleable#View_visibility
3029 */
3030 @RemotableViewMethod
3031 public void setVisibility(int visibility) {
3032 setFlags(visibility, VISIBILITY_MASK);
3033 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3034 }
3035
3036 /**
3037 * Returns the enabled status for this view. The interpretation of the
3038 * enabled state varies by subclass.
3039 *
3040 * @return True if this view is enabled, false otherwise.
3041 */
3042 @ViewDebug.ExportedProperty
3043 public boolean isEnabled() {
3044 return (mViewFlags & ENABLED_MASK) == ENABLED;
3045 }
3046
3047 /**
3048 * Set the enabled state of this view. The interpretation of the enabled
3049 * state varies by subclass.
3050 *
3051 * @param enabled True if this view is enabled, false otherwise.
3052 */
Jeff Sharkey2b95c242010-02-08 17:40:30 -08003053 @RemotableViewMethod
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 public void setEnabled(boolean enabled) {
Amith Yamasania2ef00b2009-07-30 16:14:34 -07003055 if (enabled == isEnabled()) return;
3056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3058
3059 /*
3060 * The View most likely has to change its appearance, so refresh
3061 * the drawable state.
3062 */
3063 refreshDrawableState();
3064
3065 // Invalidate too, since the default behavior for views is to be
3066 // be drawn at 50% alpha rather than to change the drawable.
3067 invalidate();
3068 }
3069
3070 /**
3071 * Set whether this view can receive the focus.
3072 *
3073 * Setting this to false will also ensure that this view is not focusable
3074 * in touch mode.
3075 *
3076 * @param focusable If true, this view can receive the focus.
3077 *
3078 * @see #setFocusableInTouchMode(boolean)
3079 * @attr ref android.R.styleable#View_focusable
3080 */
3081 public void setFocusable(boolean focusable) {
3082 if (!focusable) {
3083 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3084 }
3085 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3086 }
3087
3088 /**
3089 * Set whether this view can receive focus while in touch mode.
3090 *
3091 * Setting this to true will also ensure that this view is focusable.
3092 *
3093 * @param focusableInTouchMode If true, this view can receive the focus while
3094 * in touch mode.
3095 *
3096 * @see #setFocusable(boolean)
3097 * @attr ref android.R.styleable#View_focusableInTouchMode
3098 */
3099 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3100 // Focusable in touch mode should always be set before the focusable flag
3101 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3102 // which, in touch mode, will not successfully request focus on this view
3103 // because the focusable in touch mode flag is not set
3104 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3105 if (focusableInTouchMode) {
3106 setFlags(FOCUSABLE, FOCUSABLE_MASK);
3107 }
3108 }
3109
3110 /**
3111 * Set whether this view should have sound effects enabled for events such as
3112 * clicking and touching.
3113 *
3114 * <p>You may wish to disable sound effects for a view if you already play sounds,
3115 * for instance, a dial key that plays dtmf tones.
3116 *
3117 * @param soundEffectsEnabled whether sound effects are enabled for this view.
3118 * @see #isSoundEffectsEnabled()
3119 * @see #playSoundEffect(int)
3120 * @attr ref android.R.styleable#View_soundEffectsEnabled
3121 */
3122 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3123 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3124 }
3125
3126 /**
3127 * @return whether this view should have sound effects enabled for events such as
3128 * clicking and touching.
3129 *
3130 * @see #setSoundEffectsEnabled(boolean)
3131 * @see #playSoundEffect(int)
3132 * @attr ref android.R.styleable#View_soundEffectsEnabled
3133 */
3134 @ViewDebug.ExportedProperty
3135 public boolean isSoundEffectsEnabled() {
3136 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3137 }
3138
3139 /**
3140 * Set whether this view should have haptic feedback for events such as
3141 * long presses.
3142 *
3143 * <p>You may wish to disable haptic feedback if your view already controls
3144 * its own haptic feedback.
3145 *
3146 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3147 * @see #isHapticFeedbackEnabled()
3148 * @see #performHapticFeedback(int)
3149 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3150 */
3151 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3152 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3153 }
3154
3155 /**
3156 * @return whether this view should have haptic feedback enabled for events
3157 * long presses.
3158 *
3159 * @see #setHapticFeedbackEnabled(boolean)
3160 * @see #performHapticFeedback(int)
3161 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3162 */
3163 @ViewDebug.ExportedProperty
3164 public boolean isHapticFeedbackEnabled() {
3165 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3166 }
3167
3168 /**
3169 * If this view doesn't do any drawing on its own, set this flag to
3170 * allow further optimizations. By default, this flag is not set on
3171 * View, but could be set on some View subclasses such as ViewGroup.
3172 *
3173 * Typically, if you override {@link #onDraw} you should clear this flag.
3174 *
3175 * @param willNotDraw whether or not this View draw on its own
3176 */
3177 public void setWillNotDraw(boolean willNotDraw) {
3178 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3179 }
3180
3181 /**
3182 * Returns whether or not this View draws on its own.
3183 *
3184 * @return true if this view has nothing to draw, false otherwise
3185 */
3186 @ViewDebug.ExportedProperty
3187 public boolean willNotDraw() {
3188 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3189 }
3190
3191 /**
3192 * When a View's drawing cache is enabled, drawing is redirected to an
3193 * offscreen bitmap. Some views, like an ImageView, must be able to
3194 * bypass this mechanism if they already draw a single bitmap, to avoid
3195 * unnecessary usage of the memory.
3196 *
3197 * @param willNotCacheDrawing true if this view does not cache its
3198 * drawing, false otherwise
3199 */
3200 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3201 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3202 }
3203
3204 /**
3205 * Returns whether or not this View can cache its drawing or not.
3206 *
3207 * @return true if this view does not cache its drawing, false otherwise
3208 */
3209 @ViewDebug.ExportedProperty
3210 public boolean willNotCacheDrawing() {
3211 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3212 }
3213
3214 /**
3215 * Indicates whether this view reacts to click events or not.
3216 *
3217 * @return true if the view is clickable, false otherwise
3218 *
3219 * @see #setClickable(boolean)
3220 * @attr ref android.R.styleable#View_clickable
3221 */
3222 @ViewDebug.ExportedProperty
3223 public boolean isClickable() {
3224 return (mViewFlags & CLICKABLE) == CLICKABLE;
3225 }
3226
3227 /**
3228 * Enables or disables click events for this view. When a view
3229 * is clickable it will change its state to "pressed" on every click.
3230 * Subclasses should set the view clickable to visually react to
3231 * user's clicks.
3232 *
3233 * @param clickable true to make the view clickable, false otherwise
3234 *
3235 * @see #isClickable()
3236 * @attr ref android.R.styleable#View_clickable
3237 */
3238 public void setClickable(boolean clickable) {
3239 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3240 }
3241
3242 /**
3243 * Indicates whether this view reacts to long click events or not.
3244 *
3245 * @return true if the view is long clickable, false otherwise
3246 *
3247 * @see #setLongClickable(boolean)
3248 * @attr ref android.R.styleable#View_longClickable
3249 */
3250 public boolean isLongClickable() {
3251 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3252 }
3253
3254 /**
3255 * Enables or disables long click events for this view. When a view is long
3256 * clickable it reacts to the user holding down the button for a longer
3257 * duration than a tap. This event can either launch the listener or a
3258 * context menu.
3259 *
3260 * @param longClickable true to make the view long clickable, false otherwise
3261 * @see #isLongClickable()
3262 * @attr ref android.R.styleable#View_longClickable
3263 */
3264 public void setLongClickable(boolean longClickable) {
3265 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3266 }
3267
3268 /**
3269 * Sets the pressed that for this view.
3270 *
3271 * @see #isClickable()
3272 * @see #setClickable(boolean)
3273 *
3274 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3275 * the View's internal state from a previously set "pressed" state.
3276 */
3277 public void setPressed(boolean pressed) {
3278 if (pressed) {
3279 mPrivateFlags |= PRESSED;
3280 } else {
3281 mPrivateFlags &= ~PRESSED;
3282 }
3283 refreshDrawableState();
3284 dispatchSetPressed(pressed);
3285 }
3286
3287 /**
3288 * Dispatch setPressed to all of this View's children.
3289 *
3290 * @see #setPressed(boolean)
3291 *
3292 * @param pressed The new pressed state
3293 */
3294 protected void dispatchSetPressed(boolean pressed) {
3295 }
3296
3297 /**
3298 * Indicates whether the view is currently in pressed state. Unless
3299 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3300 * the pressed state.
3301 *
3302 * @see #setPressed
3303 * @see #isClickable()
3304 * @see #setClickable(boolean)
3305 *
3306 * @return true if the view is currently pressed, false otherwise
3307 */
3308 public boolean isPressed() {
3309 return (mPrivateFlags & PRESSED) == PRESSED;
3310 }
3311
3312 /**
3313 * Indicates whether this view will save its state (that is,
3314 * whether its {@link #onSaveInstanceState} method will be called).
3315 *
3316 * @return Returns true if the view state saving is enabled, else false.
3317 *
3318 * @see #setSaveEnabled(boolean)
3319 * @attr ref android.R.styleable#View_saveEnabled
3320 */
3321 public boolean isSaveEnabled() {
3322 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3323 }
3324
3325 /**
3326 * Controls whether the saving of this view's state is
3327 * enabled (that is, whether its {@link #onSaveInstanceState} method
3328 * will be called). Note that even if freezing is enabled, the
3329 * view still must have an id assigned to it (via {@link #setId setId()})
3330 * for its state to be saved. This flag can only disable the
3331 * saving of this view; any child views may still have their state saved.
3332 *
3333 * @param enabled Set to false to <em>disable</em> state saving, or true
3334 * (the default) to allow it.
3335 *
3336 * @see #isSaveEnabled()
3337 * @see #setId(int)
3338 * @see #onSaveInstanceState()
3339 * @attr ref android.R.styleable#View_saveEnabled
3340 */
3341 public void setSaveEnabled(boolean enabled) {
3342 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3343 }
3344
3345
3346 /**
3347 * Returns whether this View is able to take focus.
3348 *
3349 * @return True if this view can take focus, or false otherwise.
3350 * @attr ref android.R.styleable#View_focusable
3351 */
3352 @ViewDebug.ExportedProperty
3353 public final boolean isFocusable() {
3354 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
3355 }
3356
3357 /**
3358 * When a view is focusable, it may not want to take focus when in touch mode.
3359 * For example, a button would like focus when the user is navigating via a D-pad
3360 * so that the user can click on it, but once the user starts touching the screen,
3361 * the button shouldn't take focus
3362 * @return Whether the view is focusable in touch mode.
3363 * @attr ref android.R.styleable#View_focusableInTouchMode
3364 */
3365 @ViewDebug.ExportedProperty
3366 public final boolean isFocusableInTouchMode() {
3367 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
3368 }
3369
3370 /**
3371 * Find the nearest view in the specified direction that can take focus.
3372 * This does not actually give focus to that view.
3373 *
3374 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3375 *
3376 * @return The nearest focusable in the specified direction, or null if none
3377 * can be found.
3378 */
3379 public View focusSearch(int direction) {
3380 if (mParent != null) {
3381 return mParent.focusSearch(this, direction);
3382 } else {
3383 return null;
3384 }
3385 }
3386
3387 /**
3388 * This method is the last chance for the focused view and its ancestors to
3389 * respond to an arrow key. This is called when the focused view did not
3390 * consume the key internally, nor could the view system find a new view in
3391 * the requested direction to give focus to.
3392 *
3393 * @param focused The currently focused view.
3394 * @param direction The direction focus wants to move. One of FOCUS_UP,
3395 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
3396 * @return True if the this view consumed this unhandled move.
3397 */
3398 public boolean dispatchUnhandledMove(View focused, int direction) {
3399 return false;
3400 }
3401
3402 /**
3403 * If a user manually specified the next view id for a particular direction,
3404 * use the root to look up the view. Once a view is found, it is cached
3405 * for future lookups.
3406 * @param root The root view of the hierarchy containing this view.
3407 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3408 * @return The user specified next view, or null if there is none.
3409 */
3410 View findUserSetNextFocus(View root, int direction) {
3411 switch (direction) {
3412 case FOCUS_LEFT:
3413 if (mNextFocusLeftId == View.NO_ID) return null;
3414 return findViewShouldExist(root, mNextFocusLeftId);
3415 case FOCUS_RIGHT:
3416 if (mNextFocusRightId == View.NO_ID) return null;
3417 return findViewShouldExist(root, mNextFocusRightId);
3418 case FOCUS_UP:
3419 if (mNextFocusUpId == View.NO_ID) return null;
3420 return findViewShouldExist(root, mNextFocusUpId);
3421 case FOCUS_DOWN:
3422 if (mNextFocusDownId == View.NO_ID) return null;
3423 return findViewShouldExist(root, mNextFocusDownId);
3424 }
3425 return null;
3426 }
3427
3428 private static View findViewShouldExist(View root, int childViewId) {
3429 View result = root.findViewById(childViewId);
3430 if (result == null) {
3431 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
3432 + "by user for id " + childViewId);
3433 }
3434 return result;
3435 }
3436
3437 /**
3438 * Find and return all focusable views that are descendants of this view,
3439 * possibly including this view if it is focusable itself.
3440 *
3441 * @param direction The direction of the focus
3442 * @return A list of focusable views
3443 */
3444 public ArrayList<View> getFocusables(int direction) {
3445 ArrayList<View> result = new ArrayList<View>(24);
3446 addFocusables(result, direction);
3447 return result;
3448 }
3449
3450 /**
3451 * Add any focusable views that are descendants of this view (possibly
3452 * including this view if it is focusable itself) to views. If we are in touch mode,
3453 * only add views that are also focusable in touch mode.
3454 *
3455 * @param views Focusable views found so far
3456 * @param direction The direction of the focus
3457 */
3458 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -07003459 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
3460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461
svetoslavganov75986cf2009-05-14 22:28:01 -07003462 /**
3463 * Adds any focusable views that are descendants of this view (possibly
3464 * including this view if it is focusable itself) to views. This method
3465 * adds all focusable views regardless if we are in touch mode or
3466 * only views focusable in touch mode if we are in touch mode depending on
3467 * the focusable mode paramater.
3468 *
3469 * @param views Focusable views found so far or null if all we are interested is
3470 * the number of focusables.
3471 * @param direction The direction of the focus.
3472 * @param focusableMode The type of focusables to be added.
3473 *
3474 * @see #FOCUSABLES_ALL
3475 * @see #FOCUSABLES_TOUCH_MODE
3476 */
3477 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
3478 if (!isFocusable()) {
3479 return;
3480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481
svetoslavganov75986cf2009-05-14 22:28:01 -07003482 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
3483 isInTouchMode() && !isFocusableInTouchMode()) {
3484 return;
3485 }
3486
3487 if (views != null) {
3488 views.add(this);
3489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 }
3491
3492 /**
3493 * Find and return all touchable views that are descendants of this view,
3494 * possibly including this view if it is touchable itself.
3495 *
3496 * @return A list of touchable views
3497 */
3498 public ArrayList<View> getTouchables() {
3499 ArrayList<View> result = new ArrayList<View>();
3500 addTouchables(result);
3501 return result;
3502 }
3503
3504 /**
3505 * Add any touchable views that are descendants of this view (possibly
3506 * including this view if it is touchable itself) to views.
3507 *
3508 * @param views Touchable views found so far
3509 */
3510 public void addTouchables(ArrayList<View> views) {
3511 final int viewFlags = mViewFlags;
3512
3513 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
3514 && (viewFlags & ENABLED_MASK) == ENABLED) {
3515 views.add(this);
3516 }
3517 }
3518
3519 /**
3520 * Call this to try to give focus to a specific view or to one of its
3521 * descendants.
3522 *
3523 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3524 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3525 * while the device is in touch mode.
3526 *
3527 * See also {@link #focusSearch}, which is what you call to say that you
3528 * have focus, and you want your parent to look for the next one.
3529 *
3530 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
3531 * {@link #FOCUS_DOWN} and <code>null</code>.
3532 *
3533 * @return Whether this view or one of its descendants actually took focus.
3534 */
3535 public final boolean requestFocus() {
3536 return requestFocus(View.FOCUS_DOWN);
3537 }
3538
3539
3540 /**
3541 * Call this to try to give focus to a specific view or to one of its
3542 * descendants and give it a hint about what direction focus is heading.
3543 *
3544 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3545 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3546 * while the device is in touch mode.
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 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
3552 * <code>null</code> set for the previously focused rectangle.
3553 *
3554 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3555 * @return Whether this view or one of its descendants actually took focus.
3556 */
3557 public final boolean requestFocus(int direction) {
3558 return requestFocus(direction, null);
3559 }
3560
3561 /**
3562 * Call this to try to give focus to a specific view or to one of its descendants
3563 * and give it hints about the direction and a specific rectangle that the focus
3564 * is coming from. The rectangle can help give larger views a finer grained hint
3565 * about where focus is coming from, and therefore, where to show selection, or
3566 * forward focus change internally.
3567 *
3568 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
3569 * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
3570 * while the device is in touch mode.
3571 *
3572 * A View will not take focus if it is not visible.
3573 *
3574 * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
3575 * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
3576 *
3577 * See also {@link #focusSearch}, which is what you call to say that you
3578 * have focus, and you want your parent to look for the next one.
3579 *
3580 * You may wish to override this method if your custom {@link View} has an internal
3581 * {@link View} that it wishes to forward the request to.
3582 *
3583 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
3584 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
3585 * to give a finer grained hint about where focus is coming from. May be null
3586 * if there is no hint.
3587 * @return Whether this view or one of its descendants actually took focus.
3588 */
3589 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
3590 // need to be focusable
3591 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
3592 (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3593 return false;
3594 }
3595
3596 // need to be focusable in touch mode if in touch mode
3597 if (isInTouchMode() &&
3598 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
3599 return false;
3600 }
3601
3602 // need to not have any parents blocking us
3603 if (hasAncestorThatBlocksDescendantFocus()) {
3604 return false;
3605 }
3606
3607 handleFocusGainInternal(direction, previouslyFocusedRect);
3608 return true;
3609 }
3610
3611 /**
3612 * Call this to try to give focus to a specific view or to one of its descendants. This is a
3613 * special variant of {@link #requestFocus() } that will allow views that are not focuable in
3614 * touch mode to request focus when they are touched.
3615 *
3616 * @return Whether this view or one of its descendants actually took focus.
3617 *
3618 * @see #isInTouchMode()
3619 *
3620 */
3621 public final boolean requestFocusFromTouch() {
3622 // Leave touch mode if we need to
3623 if (isInTouchMode()) {
3624 View root = getRootView();
3625 if (root != null) {
3626 ViewRoot viewRoot = (ViewRoot)root.getParent();
3627 if (viewRoot != null) {
3628 viewRoot.ensureTouchMode(false);
3629 }
3630 }
3631 }
3632 return requestFocus(View.FOCUS_DOWN);
3633 }
3634
3635 /**
3636 * @return Whether any ancestor of this view blocks descendant focus.
3637 */
3638 private boolean hasAncestorThatBlocksDescendantFocus() {
3639 ViewParent ancestor = mParent;
3640 while (ancestor instanceof ViewGroup) {
3641 final ViewGroup vgAncestor = (ViewGroup) ancestor;
3642 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
3643 return true;
3644 } else {
3645 ancestor = vgAncestor.getParent();
3646 }
3647 }
3648 return false;
3649 }
3650
3651 /**
3652 * This is called when a container is going to temporarily detach a child
3653 * that currently has focus, with
3654 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
3655 * It will either be followed by {@link #onFinishTemporaryDetach()} or
3656 * {@link #onDetachedFromWindow()} when the container is done. Generally
3657 * this is currently only done ListView for a view with focus.
3658 */
3659 public void onStartTemporaryDetach() {
3660 }
Romain Guy8506ab42009-06-11 17:35:47 -07003661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 /**
3663 * Called after {@link #onStartTemporaryDetach} when the container is done
3664 * changing the view.
3665 */
3666 public void onFinishTemporaryDetach() {
3667 }
Romain Guy8506ab42009-06-11 17:35:47 -07003668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 /**
3670 * capture information of this view for later analysis: developement only
3671 * check dynamic switch to make sure we only dump view
3672 * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
3673 */
3674 private static void captureViewInfo(String subTag, View v) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003675 if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 return;
3677 }
3678 ViewDebug.dumpCapturedView(subTag, v);
3679 }
3680
3681 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003682 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
3683 * for this view's window. Returns null if the view is not currently attached
3684 * to the window. Normally you will not need to use this directly, but
3685 * just use the standard high-level event callbacks like {@link #onKeyDown}.
3686 */
3687 public KeyEvent.DispatcherState getKeyDispatcherState() {
3688 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
3689 }
3690
3691 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 * Dispatch a key event before it is processed by any input method
3693 * associated with the view hierarchy. This can be used to intercept
3694 * key events in special situations before the IME consumes them; a
3695 * typical example would be handling the BACK key to update the application's
3696 * UI instead of allowing the IME to see it and close itself.
3697 *
3698 * @param event The key event to be dispatched.
3699 * @return True if the event was handled, false otherwise.
3700 */
3701 public boolean dispatchKeyEventPreIme(KeyEvent event) {
3702 return onKeyPreIme(event.getKeyCode(), event);
3703 }
3704
3705 /**
3706 * Dispatch a key event to the next view on the focus path. This path runs
3707 * from the top of the view tree down to the currently focused view. If this
3708 * view has focus, it will dispatch to itself. Otherwise it will dispatch
3709 * the next node down the focus path. This method also fires any key
3710 * listeners.
3711 *
3712 * @param event The key event to be dispatched.
3713 * @return True if the event was handled, false otherwise.
3714 */
3715 public boolean dispatchKeyEvent(KeyEvent event) {
3716 // If any attached key listener a first crack at the event.
3717 //noinspection SimplifiableIfStatement
3718
3719 if (android.util.Config.LOGV) {
3720 captureViewInfo("captureViewKeyEvent", this);
3721 }
3722
3723 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
3724 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
3725 return true;
3726 }
3727
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003728 return event.dispatch(this, mAttachInfo != null
3729 ? mAttachInfo.mKeyDispatchState : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 }
3731
3732 /**
3733 * Dispatches a key shortcut event.
3734 *
3735 * @param event The key event to be dispatched.
3736 * @return True if the event was handled by the view, false otherwise.
3737 */
3738 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
3739 return onKeyShortcut(event.getKeyCode(), event);
3740 }
3741
3742 /**
3743 * Pass the touch screen motion event down to the target view, or this
3744 * view if it is the target.
3745 *
3746 * @param event The motion event to be dispatched.
3747 * @return True if the event was handled by the view, false otherwise.
3748 */
3749 public boolean dispatchTouchEvent(MotionEvent event) {
3750 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
3751 mOnTouchListener.onTouch(this, event)) {
3752 return true;
3753 }
3754 return onTouchEvent(event);
3755 }
3756
3757 /**
3758 * Pass a trackball motion event down to the focused view.
3759 *
3760 * @param event The motion event to be dispatched.
3761 * @return True if the event was handled by the view, false otherwise.
3762 */
3763 public boolean dispatchTrackballEvent(MotionEvent event) {
3764 //Log.i("view", "view=" + this + ", " + event.toString());
3765 return onTrackballEvent(event);
3766 }
3767
3768 /**
3769 * Called when the window containing this view gains or loses window focus.
3770 * ViewGroups should override to route to their children.
3771 *
3772 * @param hasFocus True if the window containing this view now has focus,
3773 * false otherwise.
3774 */
3775 public void dispatchWindowFocusChanged(boolean hasFocus) {
3776 onWindowFocusChanged(hasFocus);
3777 }
3778
3779 /**
3780 * Called when the window containing this view gains or loses focus. Note
3781 * that this is separate from view focus: to receive key events, both
3782 * your view and its window must have focus. If a window is displayed
3783 * on top of yours that takes input focus, then your own window will lose
3784 * focus but the view focus will remain unchanged.
3785 *
3786 * @param hasWindowFocus True if the window containing this view now has
3787 * focus, false otherwise.
3788 */
3789 public void onWindowFocusChanged(boolean hasWindowFocus) {
3790 InputMethodManager imm = InputMethodManager.peekInstance();
3791 if (!hasWindowFocus) {
3792 if (isPressed()) {
3793 setPressed(false);
3794 }
3795 if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
3796 imm.focusOut(this);
3797 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05003798 removeLongPressCallback();
Romain Guya2431d02009-04-30 16:30:00 -07003799 onFocusLost();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
3801 imm.focusIn(this);
3802 }
3803 refreshDrawableState();
3804 }
3805
3806 /**
3807 * Returns true if this view is in a window that currently has window focus.
3808 * Note that this is not the same as the view itself having focus.
3809 *
3810 * @return True if this view is in a window that currently has window focus.
3811 */
3812 public boolean hasWindowFocus() {
3813 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
3814 }
3815
3816 /**
Adam Powell326d8082009-12-09 15:10:07 -08003817 * Dispatch a view visibility change down the view hierarchy.
3818 * ViewGroups should override to route to their children.
3819 * @param changedView The view whose visibility changed. Could be 'this' or
3820 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08003821 * @param visibility The new visibility of changedView: {@link #VISIBLE},
3822 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08003823 */
3824 protected void dispatchVisibilityChanged(View changedView, int visibility) {
3825 onVisibilityChanged(changedView, visibility);
3826 }
3827
3828 /**
3829 * Called when the visibility of the view or an ancestor of the view is changed.
3830 * @param changedView The view whose visibility changed. Could be 'this' or
3831 * an ancestor view.
Romain Guy43c9cdf2010-01-27 13:53:55 -08003832 * @param visibility The new visibility of changedView: {@link #VISIBLE},
3833 * {@link #INVISIBLE} or {@link #GONE}.
Adam Powell326d8082009-12-09 15:10:07 -08003834 */
3835 protected void onVisibilityChanged(View changedView, int visibility) {
3836 }
3837
3838 /**
Romain Guy43c9cdf2010-01-27 13:53:55 -08003839 * Dispatch a hint about whether this view is displayed. For instance, when
3840 * a View moves out of the screen, it might receives a display hint indicating
3841 * the view is not displayed. Applications should not <em>rely</em> on this hint
3842 * as there is no guarantee that they will receive one.
3843 *
3844 * @param hint A hint about whether or not this view is displayed:
3845 * {@link #VISIBLE} or {@link #INVISIBLE}.
3846 */
3847 public void dispatchDisplayHint(int hint) {
3848 onDisplayHint(hint);
3849 }
3850
3851 /**
3852 * Gives this view a hint about whether is displayed or not. For instance, when
3853 * a View moves out of the screen, it might receives a display hint indicating
3854 * the view is not displayed. Applications should not <em>rely</em> on this hint
3855 * as there is no guarantee that they will receive one.
3856 *
3857 * @param hint A hint about whether or not this view is displayed:
3858 * {@link #VISIBLE} or {@link #INVISIBLE}.
3859 */
3860 protected void onDisplayHint(int hint) {
3861 }
3862
3863 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 * Dispatch a window visibility change down the view hierarchy.
3865 * ViewGroups should override to route to their children.
3866 *
3867 * @param visibility The new visibility of the window.
3868 *
3869 * @see #onWindowVisibilityChanged
3870 */
3871 public void dispatchWindowVisibilityChanged(int visibility) {
3872 onWindowVisibilityChanged(visibility);
3873 }
3874
3875 /**
3876 * Called when the window containing has change its visibility
3877 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
3878 * that this tells you whether or not your window is being made visible
3879 * to the window manager; this does <em>not</em> tell you whether or not
3880 * your window is obscured by other windows on the screen, even if it
3881 * is itself visible.
3882 *
3883 * @param visibility The new visibility of the window.
3884 */
3885 protected void onWindowVisibilityChanged(int visibility) {
3886 }
3887
3888 /**
3889 * Returns the current visibility of the window this view is attached to
3890 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
3891 *
3892 * @return Returns the current visibility of the view's window.
3893 */
3894 public int getWindowVisibility() {
3895 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
3896 }
3897
3898 /**
3899 * Retrieve the overall visible display size in which the window this view is
3900 * attached to has been positioned in. This takes into account screen
3901 * decorations above the window, for both cases where the window itself
3902 * is being position inside of them or the window is being placed under
3903 * then and covered insets are used for the window to position its content
3904 * inside. In effect, this tells you the available area where content can
3905 * be placed and remain visible to users.
3906 *
3907 * <p>This function requires an IPC back to the window manager to retrieve
3908 * the requested information, so should not be used in performance critical
3909 * code like drawing.
3910 *
3911 * @param outRect Filled in with the visible display frame. If the view
3912 * is not attached to a window, this is simply the raw display size.
3913 */
3914 public void getWindowVisibleDisplayFrame(Rect outRect) {
3915 if (mAttachInfo != null) {
3916 try {
3917 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
3918 } catch (RemoteException e) {
3919 return;
3920 }
3921 // XXX This is really broken, and probably all needs to be done
3922 // in the window manager, and we need to know more about whether
3923 // we want the area behind or in front of the IME.
3924 final Rect insets = mAttachInfo.mVisibleInsets;
3925 outRect.left += insets.left;
3926 outRect.top += insets.top;
3927 outRect.right -= insets.right;
3928 outRect.bottom -= insets.bottom;
3929 return;
3930 }
3931 Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
3932 outRect.set(0, 0, d.getWidth(), d.getHeight());
3933 }
3934
3935 /**
3936 * Private function to aggregate all per-view attributes in to the view
3937 * root.
3938 */
3939 void dispatchCollectViewAttributes(int visibility) {
3940 performCollectViewAttributes(visibility);
3941 }
3942
3943 void performCollectViewAttributes(int visibility) {
3944 //noinspection PointlessBitwiseExpression
3945 if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
3946 == (VISIBLE | KEEP_SCREEN_ON)) {
3947 mAttachInfo.mKeepScreenOn = true;
3948 }
3949 }
3950
3951 void needGlobalAttributesUpdate(boolean force) {
3952 AttachInfo ai = mAttachInfo;
3953 if (ai != null) {
3954 if (ai.mKeepScreenOn || force) {
3955 ai.mRecomputeGlobalAttributes = true;
3956 }
3957 }
3958 }
3959
3960 /**
3961 * Returns whether the device is currently in touch mode. Touch mode is entered
3962 * once the user begins interacting with the device by touch, and affects various
3963 * things like whether focus is always visible to the user.
3964 *
3965 * @return Whether the device is in touch mode.
3966 */
3967 @ViewDebug.ExportedProperty
3968 public boolean isInTouchMode() {
3969 if (mAttachInfo != null) {
3970 return mAttachInfo.mInTouchMode;
3971 } else {
3972 return ViewRoot.isInTouchMode();
3973 }
3974 }
3975
3976 /**
3977 * Returns the context the view is running in, through which it can
3978 * access the current theme, resources, etc.
3979 *
3980 * @return The view's Context.
3981 */
3982 @ViewDebug.CapturedViewProperty
3983 public final Context getContext() {
3984 return mContext;
3985 }
3986
3987 /**
3988 * Handle a key event before it is processed by any input method
3989 * associated with the view hierarchy. This can be used to intercept
3990 * key events in special situations before the IME consumes them; a
3991 * typical example would be handling the BACK key to update the application's
3992 * UI instead of allowing the IME to see it and close itself.
3993 *
3994 * @param keyCode The value in event.getKeyCode().
3995 * @param event Description of the key event.
3996 * @return If you handled the event, return true. If you want to allow the
3997 * event to be handled by the next receiver, return false.
3998 */
3999 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4000 return false;
4001 }
4002
4003 /**
4004 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4005 * KeyEvent.Callback.onKeyMultiple()}: perform press of the view
4006 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4007 * is released, if the view is enabled and clickable.
4008 *
4009 * @param keyCode A key code that represents the button pressed, from
4010 * {@link android.view.KeyEvent}.
4011 * @param event The KeyEvent object that defines the button action.
4012 */
4013 public boolean onKeyDown(int keyCode, KeyEvent event) {
4014 boolean result = false;
4015
4016 switch (keyCode) {
4017 case KeyEvent.KEYCODE_DPAD_CENTER:
4018 case KeyEvent.KEYCODE_ENTER: {
4019 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4020 return true;
4021 }
4022 // Long clickable items don't necessarily have to be clickable
4023 if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4024 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4025 (event.getRepeatCount() == 0)) {
4026 setPressed(true);
4027 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
Adam Powelle14579b2009-12-16 18:39:52 -08004028 postCheckForLongClick(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 }
4030 return true;
4031 }
4032 break;
4033 }
4034 }
4035 return result;
4036 }
4037
4038 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07004039 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4040 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4041 * the event).
4042 */
4043 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4044 return false;
4045 }
4046
4047 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4049 * KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
4050 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4051 * {@link KeyEvent#KEYCODE_ENTER} is released.
4052 *
4053 * @param keyCode A key code that represents the button pressed, from
4054 * {@link android.view.KeyEvent}.
4055 * @param event The KeyEvent object that defines the button action.
4056 */
4057 public boolean onKeyUp(int keyCode, KeyEvent event) {
4058 boolean result = false;
4059
4060 switch (keyCode) {
4061 case KeyEvent.KEYCODE_DPAD_CENTER:
4062 case KeyEvent.KEYCODE_ENTER: {
4063 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4064 return true;
4065 }
4066 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4067 setPressed(false);
4068
4069 if (!mHasPerformedLongPress) {
4070 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004071 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072
4073 result = performClick();
4074 }
4075 }
4076 break;
4077 }
4078 }
4079 return result;
4080 }
4081
4082 /**
4083 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4084 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4085 * the event).
4086 *
4087 * @param keyCode A key code that represents the button pressed, from
4088 * {@link android.view.KeyEvent}.
4089 * @param repeatCount The number of times the action was made.
4090 * @param event The KeyEvent object that defines the button action.
4091 */
4092 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4093 return false;
4094 }
4095
4096 /**
4097 * Called when an unhandled key shortcut event occurs.
4098 *
4099 * @param keyCode The value in event.getKeyCode().
4100 * @param event Description of the key event.
4101 * @return If you handled the event, return true. If you want to allow the
4102 * event to be handled by the next receiver, return false.
4103 */
4104 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4105 return false;
4106 }
4107
4108 /**
4109 * Check whether the called view is a text editor, in which case it
4110 * would make sense to automatically display a soft input window for
4111 * it. Subclasses should override this if they implement
4112 * {@link #onCreateInputConnection(EditorInfo)} to return true if
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004113 * a call on that method would return a non-null InputConnection, and
4114 * they are really a first-class editor that the user would normally
4115 * start typing on when the go into a window containing your view.
Romain Guy8506ab42009-06-11 17:35:47 -07004116 *
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004117 * <p>The default implementation always returns false. This does
4118 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4119 * will not be called or the user can not otherwise perform edits on your
4120 * view; it is just a hint to the system that this is not the primary
4121 * purpose of this view.
Romain Guy8506ab42009-06-11 17:35:47 -07004122 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 * @return Returns true if this view is a text editor, else false.
4124 */
4125 public boolean onCheckIsTextEditor() {
4126 return false;
4127 }
Romain Guy8506ab42009-06-11 17:35:47 -07004128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 /**
4130 * Create a new InputConnection for an InputMethod to interact
4131 * with the view. The default implementation returns null, since it doesn't
4132 * support input methods. You can override this to implement such support.
4133 * This is only needed for views that take focus and text input.
Romain Guy8506ab42009-06-11 17:35:47 -07004134 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 * <p>When implementing this, you probably also want to implement
4136 * {@link #onCheckIsTextEditor()} to indicate you will return a
4137 * non-null InputConnection.
4138 *
4139 * @param outAttrs Fill in with attribute information about the connection.
4140 */
4141 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4142 return null;
4143 }
4144
4145 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004146 * Called by the {@link android.view.inputmethod.InputMethodManager}
4147 * when a view who is not the current
4148 * input connection target is trying to make a call on the manager. The
4149 * default implementation returns false; you can override this to return
4150 * true for certain views if you are performing InputConnection proxying
4151 * to them.
4152 * @param view The View that is making the InputMethodManager call.
4153 * @return Return true to allow the call, false to reject.
4154 */
4155 public boolean checkInputConnectionProxy(View view) {
4156 return false;
4157 }
Romain Guy8506ab42009-06-11 17:35:47 -07004158
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004159 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 * Show the context menu for this view. It is not safe to hold on to the
4161 * menu after returning from this method.
4162 *
4163 * @param menu The context menu to populate
4164 */
4165 public void createContextMenu(ContextMenu menu) {
4166 ContextMenuInfo menuInfo = getContextMenuInfo();
4167
4168 // Sets the current menu info so all items added to menu will have
4169 // my extra info set.
4170 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4171
4172 onCreateContextMenu(menu);
4173 if (mOnCreateContextMenuListener != null) {
4174 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4175 }
4176
4177 // Clear the extra information so subsequent items that aren't mine don't
4178 // have my extra info.
4179 ((MenuBuilder)menu).setCurrentMenuInfo(null);
4180
4181 if (mParent != null) {
4182 mParent.createContextMenu(menu);
4183 }
4184 }
4185
4186 /**
4187 * Views should implement this if they have extra information to associate
4188 * with the context menu. The return result is supplied as a parameter to
4189 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4190 * callback.
4191 *
4192 * @return Extra information about the item for which the context menu
4193 * should be shown. This information will vary across different
4194 * subclasses of View.
4195 */
4196 protected ContextMenuInfo getContextMenuInfo() {
4197 return null;
4198 }
4199
4200 /**
4201 * Views should implement this if the view itself is going to add items to
4202 * the context menu.
4203 *
4204 * @param menu the context menu to populate
4205 */
4206 protected void onCreateContextMenu(ContextMenu menu) {
4207 }
4208
4209 /**
4210 * Implement this method to handle trackball motion events. The
4211 * <em>relative</em> movement of the trackball since the last event
4212 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4213 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
4214 * that a movement of 1 corresponds to the user pressing one DPAD key (so
4215 * they will often be fractional values, representing the more fine-grained
4216 * movement information available from a trackball).
4217 *
4218 * @param event The motion event.
4219 * @return True if the event was handled, false otherwise.
4220 */
4221 public boolean onTrackballEvent(MotionEvent event) {
4222 return false;
4223 }
4224
4225 /**
4226 * Implement this method to handle touch screen motion events.
4227 *
4228 * @param event The motion event.
4229 * @return True if the event was handled, false otherwise.
4230 */
4231 public boolean onTouchEvent(MotionEvent event) {
4232 final int viewFlags = mViewFlags;
4233
4234 if ((viewFlags & ENABLED_MASK) == DISABLED) {
4235 // A disabled view that is clickable still consumes the touch
4236 // events, it just doesn't respond to them.
4237 return (((viewFlags & CLICKABLE) == CLICKABLE ||
4238 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
4239 }
4240
4241 if (mTouchDelegate != null) {
4242 if (mTouchDelegate.onTouchEvent(event)) {
4243 return true;
4244 }
4245 }
4246
4247 if (((viewFlags & CLICKABLE) == CLICKABLE ||
4248 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
4249 switch (event.getAction()) {
4250 case MotionEvent.ACTION_UP:
Adam Powelle14579b2009-12-16 18:39:52 -08004251 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
4252 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004253 // take focus if we don't have it already and we should in
4254 // touch mode.
4255 boolean focusTaken = false;
4256 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
4257 focusTaken = requestFocus();
4258 }
4259
4260 if (!mHasPerformedLongPress) {
4261 // This is a tap, so remove the longpress check
Maryam Garrett1549dd12009-12-15 16:06:36 -05004262 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004263
4264 // Only perform take click actions if we were in the pressed state
4265 if (!focusTaken) {
4266 performClick();
4267 }
4268 }
4269
4270 if (mUnsetPressedState == null) {
4271 mUnsetPressedState = new UnsetPressedState();
4272 }
4273
Adam Powelle14579b2009-12-16 18:39:52 -08004274 if (prepressed) {
4275 mPrivateFlags |= PRESSED;
4276 refreshDrawableState();
4277 postDelayed(mUnsetPressedState,
4278 ViewConfiguration.getPressedStateDuration());
4279 } else if (!post(mUnsetPressedState)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 // If the post failed, unpress right now
4281 mUnsetPressedState.run();
4282 }
Adam Powelle14579b2009-12-16 18:39:52 -08004283 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 }
4285 break;
4286
4287 case MotionEvent.ACTION_DOWN:
Adam Powelle14579b2009-12-16 18:39:52 -08004288 if (mPendingCheckForTap == null) {
4289 mPendingCheckForTap = new CheckForTap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 }
Adam Powelle14579b2009-12-16 18:39:52 -08004291 mPrivateFlags |= PREPRESSED;
4292 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004293 break;
4294
4295 case MotionEvent.ACTION_CANCEL:
4296 mPrivateFlags &= ~PRESSED;
4297 refreshDrawableState();
Adam Powelle14579b2009-12-16 18:39:52 -08004298 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 break;
4300
4301 case MotionEvent.ACTION_MOVE:
4302 final int x = (int) event.getX();
4303 final int y = (int) event.getY();
4304
4305 // Be lenient about moving outside of buttons
Adam Powelle14579b2009-12-16 18:39:52 -08004306 int slop = mTouchSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 if ((x < 0 - slop) || (x >= getWidth() + slop) ||
4308 (y < 0 - slop) || (y >= getHeight() + slop)) {
4309 // Outside button
Adam Powelle14579b2009-12-16 18:39:52 -08004310 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 if ((mPrivateFlags & PRESSED) != 0) {
Adam Powelle14579b2009-12-16 18:39:52 -08004312 // Remove any future long press/tap checks
Maryam Garrett1549dd12009-12-15 16:06:36 -05004313 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004314
4315 // Need to switch from pressed to not pressed
4316 mPrivateFlags &= ~PRESSED;
4317 refreshDrawableState();
4318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 }
4320 break;
4321 }
4322 return true;
4323 }
4324
4325 return false;
4326 }
4327
4328 /**
Maryam Garrett1549dd12009-12-15 16:06:36 -05004329 * Remove the longpress detection timer.
4330 */
4331 private void removeLongPressCallback() {
4332 if (mPendingCheckForLongPress != null) {
4333 removeCallbacks(mPendingCheckForLongPress);
4334 }
4335 }
Adam Powelle14579b2009-12-16 18:39:52 -08004336
4337 /**
4338 * Remove the tap detection timer.
4339 */
4340 private void removeTapCallback() {
4341 if (mPendingCheckForTap != null) {
4342 mPrivateFlags &= ~PREPRESSED;
4343 removeCallbacks(mPendingCheckForTap);
4344 }
4345 }
Maryam Garrett1549dd12009-12-15 16:06:36 -05004346
4347 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004348 * Cancels a pending long press. Your subclass can use this if you
4349 * want the context menu to come up if the user presses and holds
4350 * at the same place, but you don't want it to come up if they press
4351 * and then move around enough to cause scrolling.
4352 */
4353 public void cancelLongPress() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05004354 removeLongPressCallback();
Adam Powell732ebb12010-02-02 15:28:14 -08004355
4356 /*
4357 * The prepressed state handled by the tap callback is a display
4358 * construct, but the tap callback will post a long press callback
4359 * less its own timeout. Remove it here.
4360 */
4361 removeTapCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 }
4363
4364 /**
4365 * Sets the TouchDelegate for this View.
4366 */
4367 public void setTouchDelegate(TouchDelegate delegate) {
4368 mTouchDelegate = delegate;
4369 }
4370
4371 /**
4372 * Gets the TouchDelegate for this View.
4373 */
4374 public TouchDelegate getTouchDelegate() {
4375 return mTouchDelegate;
4376 }
4377
4378 /**
4379 * Set flags controlling behavior of this view.
4380 *
4381 * @param flags Constant indicating the value which should be set
4382 * @param mask Constant indicating the bit range that should be changed
4383 */
4384 void setFlags(int flags, int mask) {
4385 int old = mViewFlags;
4386 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
4387
4388 int changed = mViewFlags ^ old;
4389 if (changed == 0) {
4390 return;
4391 }
4392 int privateFlags = mPrivateFlags;
4393
4394 /* Check if the FOCUSABLE bit has changed */
4395 if (((changed & FOCUSABLE_MASK) != 0) &&
4396 ((privateFlags & HAS_BOUNDS) !=0)) {
4397 if (((old & FOCUSABLE_MASK) == FOCUSABLE)
4398 && ((privateFlags & FOCUSED) != 0)) {
4399 /* Give up focus if we are no longer focusable */
4400 clearFocus();
4401 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
4402 && ((privateFlags & FOCUSED) == 0)) {
4403 /*
4404 * Tell the view system that we are now available to take focus
4405 * if no one else already has it.
4406 */
4407 if (mParent != null) mParent.focusableViewAvailable(this);
4408 }
4409 }
4410
4411 if ((flags & VISIBILITY_MASK) == VISIBLE) {
4412 if ((changed & VISIBILITY_MASK) != 0) {
4413 /*
4414 * If this view is becoming visible, set the DRAWN flag so that
4415 * the next invalidate() will not be skipped.
4416 */
4417 mPrivateFlags |= DRAWN;
4418
4419 needGlobalAttributesUpdate(true);
4420
4421 // a view becoming visible is worth notifying the parent
4422 // about in case nothing has focus. even if this specific view
4423 // isn't focusable, it may contain something that is, so let
4424 // the root view try to give this focus if nothing else does.
4425 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
4426 mParent.focusableViewAvailable(this);
4427 }
4428 }
4429 }
4430
4431 /* Check if the GONE bit has changed */
4432 if ((changed & GONE) != 0) {
4433 needGlobalAttributesUpdate(false);
4434 requestLayout();
4435 invalidate();
4436
Romain Guyecd80ee2009-12-03 17:13:02 -08004437 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
4438 if (hasFocus()) clearFocus();
4439 destroyDrawingCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004440 }
4441 if (mAttachInfo != null) {
4442 mAttachInfo.mViewVisibilityChanged = true;
4443 }
4444 }
4445
4446 /* Check if the VISIBLE bit has changed */
4447 if ((changed & INVISIBLE) != 0) {
4448 needGlobalAttributesUpdate(false);
4449 invalidate();
4450
4451 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
4452 // root view becoming invisible shouldn't clear focus
4453 if (getRootView() != this) {
4454 clearFocus();
4455 }
4456 }
4457 if (mAttachInfo != null) {
4458 mAttachInfo.mViewVisibilityChanged = true;
4459 }
4460 }
4461
Adam Powell326d8082009-12-09 15:10:07 -08004462 if ((changed & VISIBILITY_MASK) != 0) {
4463 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
4464 }
4465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004466 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
4467 destroyDrawingCache();
4468 }
4469
4470 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
4471 destroyDrawingCache();
4472 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4473 }
4474
4475 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
4476 destroyDrawingCache();
4477 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4478 }
4479
4480 if ((changed & DRAW_MASK) != 0) {
4481 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
4482 if (mBGDrawable != null) {
4483 mPrivateFlags &= ~SKIP_DRAW;
4484 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
4485 } else {
4486 mPrivateFlags |= SKIP_DRAW;
4487 }
4488 } else {
4489 mPrivateFlags &= ~SKIP_DRAW;
4490 }
4491 requestLayout();
4492 invalidate();
4493 }
4494
4495 if ((changed & KEEP_SCREEN_ON) != 0) {
4496 if (mParent != null) {
4497 mParent.recomputeViewAttributes(this);
4498 }
4499 }
4500 }
4501
4502 /**
4503 * Change the view's z order in the tree, so it's on top of other sibling
4504 * views
4505 */
4506 public void bringToFront() {
4507 if (mParent != null) {
4508 mParent.bringChildToFront(this);
4509 }
4510 }
4511
4512 /**
4513 * This is called in response to an internal scroll in this view (i.e., the
4514 * view scrolled its own contents). This is typically as a result of
4515 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
4516 * called.
4517 *
4518 * @param l Current horizontal scroll origin.
4519 * @param t Current vertical scroll origin.
4520 * @param oldl Previous horizontal scroll origin.
4521 * @param oldt Previous vertical scroll origin.
4522 */
4523 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4524 mBackgroundSizeChanged = true;
4525
4526 final AttachInfo ai = mAttachInfo;
4527 if (ai != null) {
4528 ai.mViewScrollChanged = true;
4529 }
4530 }
4531
4532 /**
4533 * This is called during layout when the size of this view has changed. If
4534 * you were just added to the view hierarchy, you're called with the old
4535 * values of 0.
4536 *
4537 * @param w Current width of this view.
4538 * @param h Current height of this view.
4539 * @param oldw Old width of this view.
4540 * @param oldh Old height of this view.
4541 */
4542 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
4543 }
4544
4545 /**
4546 * Called by draw to draw the child views. This may be overridden
4547 * by derived classes to gain control just before its children are drawn
4548 * (but after its own view has been drawn).
4549 * @param canvas the canvas on which to draw the view
4550 */
4551 protected void dispatchDraw(Canvas canvas) {
4552 }
4553
4554 /**
4555 * Gets the parent of this view. Note that the parent is a
4556 * ViewParent and not necessarily a View.
4557 *
4558 * @return Parent of this view.
4559 */
4560 public final ViewParent getParent() {
4561 return mParent;
4562 }
4563
4564 /**
4565 * Return the scrolled left position of this view. This is the left edge of
4566 * the displayed part of your view. You do not need to draw any pixels
4567 * farther left, since those are outside of the frame of your view on
4568 * screen.
4569 *
4570 * @return The left edge of the displayed part of your view, in pixels.
4571 */
4572 public final int getScrollX() {
4573 return mScrollX;
4574 }
4575
4576 /**
4577 * Return the scrolled top position of this view. This is the top edge of
4578 * the displayed part of your view. You do not need to draw any pixels above
4579 * it, since those are outside of the frame of your view on screen.
4580 *
4581 * @return The top edge of the displayed part of your view, in pixels.
4582 */
4583 public final int getScrollY() {
4584 return mScrollY;
4585 }
4586
4587 /**
4588 * Return the width of the your view.
4589 *
4590 * @return The width of your view, in pixels.
4591 */
4592 @ViewDebug.ExportedProperty
4593 public final int getWidth() {
4594 return mRight - mLeft;
4595 }
4596
4597 /**
4598 * Return the height of your view.
4599 *
4600 * @return The height of your view, in pixels.
4601 */
4602 @ViewDebug.ExportedProperty
4603 public final int getHeight() {
4604 return mBottom - mTop;
4605 }
4606
4607 /**
4608 * Return the visible drawing bounds of your view. Fills in the output
4609 * rectangle with the values from getScrollX(), getScrollY(),
4610 * getWidth(), and getHeight().
4611 *
4612 * @param outRect The (scrolled) drawing bounds of the view.
4613 */
4614 public void getDrawingRect(Rect outRect) {
4615 outRect.left = mScrollX;
4616 outRect.top = mScrollY;
4617 outRect.right = mScrollX + (mRight - mLeft);
4618 outRect.bottom = mScrollY + (mBottom - mTop);
4619 }
4620
4621 /**
4622 * The width of this view as measured in the most recent call to measure().
4623 * This should be used during measurement and layout calculations only. Use
4624 * {@link #getWidth()} to see how wide a view is after layout.
4625 *
4626 * @return The measured width of this view.
4627 */
4628 public final int getMeasuredWidth() {
4629 return mMeasuredWidth;
4630 }
4631
4632 /**
4633 * The height of this view as measured in the most recent call to measure().
4634 * This should be used during measurement and layout calculations only. Use
4635 * {@link #getHeight()} to see how tall a view is after layout.
4636 *
4637 * @return The measured height of this view.
4638 */
4639 public final int getMeasuredHeight() {
4640 return mMeasuredHeight;
4641 }
4642
4643 /**
4644 * Top position of this view relative to its parent.
4645 *
4646 * @return The top of this view, in pixels.
4647 */
4648 @ViewDebug.CapturedViewProperty
4649 public final int getTop() {
4650 return mTop;
4651 }
4652
4653 /**
4654 * Bottom position of this view relative to its parent.
4655 *
4656 * @return The bottom of this view, in pixels.
4657 */
4658 @ViewDebug.CapturedViewProperty
4659 public final int getBottom() {
4660 return mBottom;
4661 }
4662
4663 /**
4664 * Left position of this view relative to its parent.
4665 *
4666 * @return The left edge of this view, in pixels.
4667 */
4668 @ViewDebug.CapturedViewProperty
4669 public final int getLeft() {
4670 return mLeft;
4671 }
4672
4673 /**
4674 * Right position of this view relative to its parent.
4675 *
4676 * @return The right edge of this view, in pixels.
4677 */
4678 @ViewDebug.CapturedViewProperty
4679 public final int getRight() {
4680 return mRight;
4681 }
4682
4683 /**
4684 * Hit rectangle in parent's coordinates
4685 *
4686 * @param outRect The hit rectangle of the view.
4687 */
4688 public void getHitRect(Rect outRect) {
4689 outRect.set(mLeft, mTop, mRight, mBottom);
4690 }
4691
4692 /**
4693 * When a view has focus and the user navigates away from it, the next view is searched for
4694 * starting from the rectangle filled in by this method.
4695 *
4696 * By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
4697 * view maintains some idea of internal selection, such as a cursor, or a selected row
4698 * or column, you should override this method and fill in a more specific rectangle.
4699 *
4700 * @param r The rectangle to fill in, in this view's coordinates.
4701 */
4702 public void getFocusedRect(Rect r) {
4703 getDrawingRect(r);
4704 }
4705
4706 /**
4707 * If some part of this view is not clipped by any of its parents, then
4708 * return that area in r in global (root) coordinates. To convert r to local
4709 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
4710 * -globalOffset.y)) If the view is completely clipped or translated out,
4711 * return false.
4712 *
4713 * @param r If true is returned, r holds the global coordinates of the
4714 * visible portion of this view.
4715 * @param globalOffset If true is returned, globalOffset holds the dx,dy
4716 * between this view and its root. globalOffet may be null.
4717 * @return true if r is non-empty (i.e. part of the view is visible at the
4718 * root level.
4719 */
4720 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
4721 int width = mRight - mLeft;
4722 int height = mBottom - mTop;
4723 if (width > 0 && height > 0) {
4724 r.set(0, 0, width, height);
4725 if (globalOffset != null) {
4726 globalOffset.set(-mScrollX, -mScrollY);
4727 }
4728 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
4729 }
4730 return false;
4731 }
4732
4733 public final boolean getGlobalVisibleRect(Rect r) {
4734 return getGlobalVisibleRect(r, null);
4735 }
4736
4737 public final boolean getLocalVisibleRect(Rect r) {
4738 Point offset = new Point();
4739 if (getGlobalVisibleRect(r, offset)) {
4740 r.offset(-offset.x, -offset.y); // make r local
4741 return true;
4742 }
4743 return false;
4744 }
4745
4746 /**
4747 * Offset this view's vertical location by the specified number of pixels.
4748 *
4749 * @param offset the number of pixels to offset the view by
4750 */
4751 public void offsetTopAndBottom(int offset) {
4752 mTop += offset;
4753 mBottom += offset;
4754 }
4755
4756 /**
4757 * Offset this view's horizontal location by the specified amount of pixels.
4758 *
4759 * @param offset the numer of pixels to offset the view by
4760 */
4761 public void offsetLeftAndRight(int offset) {
4762 mLeft += offset;
4763 mRight += offset;
4764 }
4765
4766 /**
4767 * Get the LayoutParams associated with this view. All views should have
4768 * layout parameters. These supply parameters to the <i>parent</i> of this
4769 * view specifying how it should be arranged. There are many subclasses of
4770 * ViewGroup.LayoutParams, and these correspond to the different subclasses
4771 * of ViewGroup that are responsible for arranging their children.
4772 * @return The LayoutParams associated with this view
4773 */
4774 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
4775 public ViewGroup.LayoutParams getLayoutParams() {
4776 return mLayoutParams;
4777 }
4778
4779 /**
4780 * Set the layout parameters associated with this view. These supply
4781 * parameters to the <i>parent</i> of this view specifying how it should be
4782 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
4783 * correspond to the different subclasses of ViewGroup that are responsible
4784 * for arranging their children.
4785 *
4786 * @param params the layout parameters for this view
4787 */
4788 public void setLayoutParams(ViewGroup.LayoutParams params) {
4789 if (params == null) {
4790 throw new NullPointerException("params == null");
4791 }
4792 mLayoutParams = params;
4793 requestLayout();
4794 }
4795
4796 /**
4797 * Set the scrolled position of your view. This will cause a call to
4798 * {@link #onScrollChanged(int, int, int, int)} and the view will be
4799 * invalidated.
4800 * @param x the x position to scroll to
4801 * @param y the y position to scroll to
4802 */
4803 public void scrollTo(int x, int y) {
4804 if (mScrollX != x || mScrollY != y) {
4805 int oldX = mScrollX;
4806 int oldY = mScrollY;
4807 mScrollX = x;
4808 mScrollY = y;
4809 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
Mike Cleronf116bf82009-09-27 19:14:12 -07004810 if (!awakenScrollBars()) {
4811 invalidate();
4812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004813 }
4814 }
4815
4816 /**
4817 * Move the scrolled position of your view. This will cause a call to
4818 * {@link #onScrollChanged(int, int, int, int)} and the view will be
4819 * invalidated.
4820 * @param x the amount of pixels to scroll by horizontally
4821 * @param y the amount of pixels to scroll by vertically
4822 */
4823 public void scrollBy(int x, int y) {
4824 scrollTo(mScrollX + x, mScrollY + y);
4825 }
4826
4827 /**
Mike Cleronf116bf82009-09-27 19:14:12 -07004828 * <p>Trigger the scrollbars to draw. When invoked this method starts an
4829 * animation to fade the scrollbars out after a default delay. If a subclass
4830 * provides animated scrolling, the start delay should equal the duration
4831 * of the scrolling animation.</p>
4832 *
4833 * <p>The animation starts only if at least one of the scrollbars is
4834 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
4835 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
4836 * this method returns true, and false otherwise. If the animation is
4837 * started, this method calls {@link #invalidate()}; in that case the
4838 * caller should not call {@link #invalidate()}.</p>
4839 *
4840 * <p>This method should be invoked every time a subclass directly updates
Mike Cleronfe81d382009-09-28 14:22:16 -07004841 * the scroll parameters.</p>
Mike Cleronf116bf82009-09-27 19:14:12 -07004842 *
4843 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
4844 * and {@link #scrollTo(int, int)}.</p>
4845 *
4846 * @return true if the animation is played, false otherwise
4847 *
4848 * @see #awakenScrollBars(int)
Mike Cleronf116bf82009-09-27 19:14:12 -07004849 * @see #scrollBy(int, int)
4850 * @see #scrollTo(int, int)
4851 * @see #isHorizontalScrollBarEnabled()
4852 * @see #isVerticalScrollBarEnabled()
4853 * @see #setHorizontalScrollBarEnabled(boolean)
4854 * @see #setVerticalScrollBarEnabled(boolean)
4855 */
4856 protected boolean awakenScrollBars() {
4857 return mScrollCache != null &&
Mike Cleron290947b2009-09-29 18:34:32 -07004858 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
Mike Cleronf116bf82009-09-27 19:14:12 -07004859 }
4860
4861 /**
4862 * <p>
4863 * Trigger the scrollbars to draw. When invoked this method starts an
4864 * animation to fade the scrollbars out after a fixed delay. If a subclass
4865 * provides animated scrolling, the start delay should equal the duration of
4866 * the scrolling animation.
4867 * </p>
4868 *
4869 * <p>
4870 * The animation starts only if at least one of the scrollbars is enabled,
4871 * as specified by {@link #isHorizontalScrollBarEnabled()} and
4872 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
4873 * this method returns true, and false otherwise. If the animation is
4874 * started, this method calls {@link #invalidate()}; in that case the caller
4875 * should not call {@link #invalidate()}.
4876 * </p>
4877 *
4878 * <p>
4879 * This method should be invoked everytime a subclass directly updates the
Mike Cleronfe81d382009-09-28 14:22:16 -07004880 * scroll parameters.
Mike Cleronf116bf82009-09-27 19:14:12 -07004881 * </p>
4882 *
4883 * @param startDelay the delay, in milliseconds, after which the animation
4884 * should start; when the delay is 0, the animation starts
4885 * immediately
4886 * @return true if the animation is played, false otherwise
4887 *
Mike Cleronf116bf82009-09-27 19:14:12 -07004888 * @see #scrollBy(int, int)
4889 * @see #scrollTo(int, int)
4890 * @see #isHorizontalScrollBarEnabled()
4891 * @see #isVerticalScrollBarEnabled()
4892 * @see #setHorizontalScrollBarEnabled(boolean)
4893 * @see #setVerticalScrollBarEnabled(boolean)
4894 */
4895 protected boolean awakenScrollBars(int startDelay) {
Mike Cleron290947b2009-09-29 18:34:32 -07004896 return awakenScrollBars(startDelay, true);
4897 }
4898
4899 /**
4900 * <p>
4901 * Trigger the scrollbars to draw. When invoked this method starts an
4902 * animation to fade the scrollbars out after a fixed delay. If a subclass
4903 * provides animated scrolling, the start delay should equal the duration of
4904 * the scrolling animation.
4905 * </p>
4906 *
4907 * <p>
4908 * The animation starts only if at least one of the scrollbars is enabled,
4909 * as specified by {@link #isHorizontalScrollBarEnabled()} and
4910 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
4911 * this method returns true, and false otherwise. If the animation is
4912 * started, this method calls {@link #invalidate()} if the invalidate parameter
4913 * is set to true; in that case the caller
4914 * should not call {@link #invalidate()}.
4915 * </p>
4916 *
4917 * <p>
4918 * This method should be invoked everytime a subclass directly updates the
4919 * scroll parameters.
4920 * </p>
4921 *
4922 * @param startDelay the delay, in milliseconds, after which the animation
4923 * should start; when the delay is 0, the animation starts
4924 * immediately
4925 *
4926 * @param invalidate Wheter this method should call invalidate
4927 *
4928 * @return true if the animation is played, false otherwise
4929 *
4930 * @see #scrollBy(int, int)
4931 * @see #scrollTo(int, int)
4932 * @see #isHorizontalScrollBarEnabled()
4933 * @see #isVerticalScrollBarEnabled()
4934 * @see #setHorizontalScrollBarEnabled(boolean)
4935 * @see #setVerticalScrollBarEnabled(boolean)
4936 */
4937 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
Mike Cleronf116bf82009-09-27 19:14:12 -07004938 final ScrollabilityCache scrollCache = mScrollCache;
4939
4940 if (scrollCache == null || !scrollCache.fadeScrollBars) {
4941 return false;
4942 }
4943
4944 if (scrollCache.scrollBar == null) {
4945 scrollCache.scrollBar = new ScrollBarDrawable();
4946 }
4947
4948 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
4949
Mike Cleron290947b2009-09-29 18:34:32 -07004950 if (invalidate) {
4951 // Invalidate to show the scrollbars
4952 invalidate();
4953 }
Mike Cleronf116bf82009-09-27 19:14:12 -07004954
4955 if (scrollCache.state == ScrollabilityCache.OFF) {
4956 // FIXME: this is copied from WindowManagerService.
4957 // We should get this value from the system when it
4958 // is possible to do so.
4959 final int KEY_REPEAT_FIRST_DELAY = 750;
4960 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
4961 }
4962
4963 // Tell mScrollCache when we should start fading. This may
4964 // extend the fade start time if one was already scheduled
Mike Cleron3ecd58c2009-09-28 11:39:02 -07004965 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
Mike Cleronf116bf82009-09-27 19:14:12 -07004966 scrollCache.fadeStartTime = fadeStartTime;
4967 scrollCache.state = ScrollabilityCache.ON;
4968
4969 // Schedule our fader to run, unscheduling any old ones first
4970 if (mAttachInfo != null) {
4971 mAttachInfo.mHandler.removeCallbacks(scrollCache);
4972 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
4973 }
4974
4975 return true;
4976 }
4977
4978 return false;
4979 }
4980
4981 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004982 * Mark the the area defined by dirty as needing to be drawn. If the view is
4983 * visible, {@link #onDraw} will be called at some point in the future.
4984 * This must be called from a UI thread. To call from a non-UI thread, call
4985 * {@link #postInvalidate()}.
4986 *
4987 * WARNING: This method is destructive to dirty.
4988 * @param dirty the rectangle representing the bounds of the dirty region
4989 */
4990 public void invalidate(Rect dirty) {
4991 if (ViewDebug.TRACE_HIERARCHY) {
4992 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
4993 }
4994
4995 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
4996 mPrivateFlags &= ~DRAWING_CACHE_VALID;
4997 final ViewParent p = mParent;
4998 final AttachInfo ai = mAttachInfo;
4999 if (p != null && ai != null) {
5000 final int scrollX = mScrollX;
5001 final int scrollY = mScrollY;
5002 final Rect r = ai.mTmpInvalRect;
5003 r.set(dirty.left - scrollX, dirty.top - scrollY,
5004 dirty.right - scrollX, dirty.bottom - scrollY);
5005 mParent.invalidateChild(this, r);
5006 }
5007 }
5008 }
5009
5010 /**
5011 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
5012 * The coordinates of the dirty rect are relative to the view.
5013 * If the view is visible, {@link #onDraw} will be called at some point
5014 * in the future. This must be called from a UI thread. To call
5015 * from a non-UI thread, call {@link #postInvalidate()}.
5016 * @param l the left position of the dirty region
5017 * @param t the top position of the dirty region
5018 * @param r the right position of the dirty region
5019 * @param b the bottom position of the dirty region
5020 */
5021 public void invalidate(int l, int t, int r, int b) {
5022 if (ViewDebug.TRACE_HIERARCHY) {
5023 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5024 }
5025
5026 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5027 mPrivateFlags &= ~DRAWING_CACHE_VALID;
5028 final ViewParent p = mParent;
5029 final AttachInfo ai = mAttachInfo;
5030 if (p != null && ai != null && l < r && t < b) {
5031 final int scrollX = mScrollX;
5032 final int scrollY = mScrollY;
5033 final Rect tmpr = ai.mTmpInvalRect;
5034 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
5035 p.invalidateChild(this, tmpr);
5036 }
5037 }
5038 }
5039
5040 /**
5041 * Invalidate the whole view. If the view is visible, {@link #onDraw} will
5042 * be called at some point in the future. This must be called from a
5043 * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
5044 */
5045 public void invalidate() {
5046 if (ViewDebug.TRACE_HIERARCHY) {
5047 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
5048 }
5049
5050 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
5051 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
5052 final ViewParent p = mParent;
5053 final AttachInfo ai = mAttachInfo;
5054 if (p != null && ai != null) {
5055 final Rect r = ai.mTmpInvalRect;
5056 r.set(0, 0, mRight - mLeft, mBottom - mTop);
5057 // Don't call invalidate -- we don't want to internally scroll
5058 // our own bounds
5059 p.invalidateChild(this, r);
5060 }
5061 }
5062 }
5063
5064 /**
Romain Guy24443ea2009-05-11 11:56:30 -07005065 * Indicates whether this View is opaque. An opaque View guarantees that it will
5066 * draw all the pixels overlapping its bounds using a fully opaque color.
5067 *
5068 * Subclasses of View should override this method whenever possible to indicate
5069 * whether an instance is opaque. Opaque Views are treated in a special way by
5070 * the View hierarchy, possibly allowing it to perform optimizations during
5071 * invalidate/draw passes.
Romain Guy8506ab42009-06-11 17:35:47 -07005072 *
Romain Guy24443ea2009-05-11 11:56:30 -07005073 * @return True if this View is guaranteed to be fully opaque, false otherwise.
Romain Guy24443ea2009-05-11 11:56:30 -07005074 */
Romain Guy83b21072009-05-12 10:54:51 -07005075 @ViewDebug.ExportedProperty
Romain Guy24443ea2009-05-11 11:56:30 -07005076 public boolean isOpaque() {
Romain Guy8f1344f52009-05-15 16:03:59 -07005077 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK;
5078 }
5079
5080 private void computeOpaqueFlags() {
5081 // Opaque if:
5082 // - Has a background
5083 // - Background is opaque
5084 // - Doesn't have scrollbars or scrollbars are inside overlay
5085
5086 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
5087 mPrivateFlags |= OPAQUE_BACKGROUND;
5088 } else {
5089 mPrivateFlags &= ~OPAQUE_BACKGROUND;
5090 }
5091
5092 final int flags = mViewFlags;
5093 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
5094 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
5095 mPrivateFlags |= OPAQUE_SCROLLBARS;
5096 } else {
5097 mPrivateFlags &= ~OPAQUE_SCROLLBARS;
5098 }
5099 }
5100
5101 /**
5102 * @hide
5103 */
5104 protected boolean hasOpaqueScrollbars() {
5105 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
Romain Guy24443ea2009-05-11 11:56:30 -07005106 }
5107
5108 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 * @return A handler associated with the thread running the View. This
5110 * handler can be used to pump events in the UI events queue.
5111 */
5112 public Handler getHandler() {
5113 if (mAttachInfo != null) {
5114 return mAttachInfo.mHandler;
5115 }
5116 return null;
5117 }
5118
5119 /**
5120 * Causes the Runnable to be added to the message queue.
5121 * The runnable will be run on the user interface thread.
5122 *
5123 * @param action The Runnable that will be executed.
5124 *
5125 * @return Returns true if the Runnable was successfully placed in to the
5126 * message queue. Returns false on failure, usually because the
5127 * looper processing the message queue is exiting.
5128 */
5129 public boolean post(Runnable action) {
5130 Handler handler;
5131 if (mAttachInfo != null) {
5132 handler = mAttachInfo.mHandler;
5133 } else {
5134 // Assume that post will succeed later
5135 ViewRoot.getRunQueue().post(action);
5136 return true;
5137 }
5138
5139 return handler.post(action);
5140 }
5141
5142 /**
5143 * Causes the Runnable to be added to the message queue, to be run
5144 * after the specified amount of time elapses.
5145 * The runnable will be run on the user interface thread.
5146 *
5147 * @param action The Runnable that will be executed.
5148 * @param delayMillis The delay (in milliseconds) until the Runnable
5149 * will be executed.
5150 *
5151 * @return true if the Runnable was successfully placed in to the
5152 * message queue. Returns false on failure, usually because the
5153 * looper processing the message queue is exiting. Note that a
5154 * result of true does not mean the Runnable will be processed --
5155 * if the looper is quit before the delivery time of the message
5156 * occurs then the message will be dropped.
5157 */
5158 public boolean postDelayed(Runnable action, long delayMillis) {
5159 Handler handler;
5160 if (mAttachInfo != null) {
5161 handler = mAttachInfo.mHandler;
5162 } else {
5163 // Assume that post will succeed later
5164 ViewRoot.getRunQueue().postDelayed(action, delayMillis);
5165 return true;
5166 }
5167
5168 return handler.postDelayed(action, delayMillis);
5169 }
5170
5171 /**
5172 * Removes the specified Runnable from the message queue.
5173 *
5174 * @param action The Runnable to remove from the message handling queue
5175 *
5176 * @return true if this view could ask the Handler to remove the Runnable,
5177 * false otherwise. When the returned value is true, the Runnable
5178 * may or may not have been actually removed from the message queue
5179 * (for instance, if the Runnable was not in the queue already.)
5180 */
5181 public boolean removeCallbacks(Runnable action) {
5182 Handler handler;
5183 if (mAttachInfo != null) {
5184 handler = mAttachInfo.mHandler;
5185 } else {
5186 // Assume that post will succeed later
5187 ViewRoot.getRunQueue().removeCallbacks(action);
5188 return true;
5189 }
5190
5191 handler.removeCallbacks(action);
5192 return true;
5193 }
5194
5195 /**
5196 * Cause an invalidate to happen on a subsequent cycle through the event loop.
5197 * Use this to invalidate the View from a non-UI thread.
5198 *
5199 * @see #invalidate()
5200 */
5201 public void postInvalidate() {
5202 postInvalidateDelayed(0);
5203 }
5204
5205 /**
5206 * Cause an invalidate of the specified area to happen on a subsequent cycle
5207 * through the event loop. Use this to invalidate the View from a non-UI thread.
5208 *
5209 * @param left The left coordinate of the rectangle to invalidate.
5210 * @param top The top coordinate of the rectangle to invalidate.
5211 * @param right The right coordinate of the rectangle to invalidate.
5212 * @param bottom The bottom coordinate of the rectangle to invalidate.
5213 *
5214 * @see #invalidate(int, int, int, int)
5215 * @see #invalidate(Rect)
5216 */
5217 public void postInvalidate(int left, int top, int right, int bottom) {
5218 postInvalidateDelayed(0, left, top, right, bottom);
5219 }
5220
5221 /**
5222 * Cause an invalidate to happen on a subsequent cycle through the event
5223 * loop. Waits for the specified amount of time.
5224 *
5225 * @param delayMilliseconds the duration in milliseconds to delay the
5226 * invalidation by
5227 */
5228 public void postInvalidateDelayed(long delayMilliseconds) {
5229 // We try only with the AttachInfo because there's no point in invalidating
5230 // if we are not attached to our window
5231 if (mAttachInfo != null) {
5232 Message msg = Message.obtain();
5233 msg.what = AttachInfo.INVALIDATE_MSG;
5234 msg.obj = this;
5235 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
5236 }
5237 }
5238
5239 /**
5240 * Cause an invalidate of the specified area to happen on a subsequent cycle
5241 * through the event loop. Waits for the specified amount of time.
5242 *
5243 * @param delayMilliseconds the duration in milliseconds to delay the
5244 * invalidation by
5245 * @param left The left coordinate of the rectangle to invalidate.
5246 * @param top The top coordinate of the rectangle to invalidate.
5247 * @param right The right coordinate of the rectangle to invalidate.
5248 * @param bottom The bottom coordinate of the rectangle to invalidate.
5249 */
5250 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
5251 int right, int bottom) {
5252
5253 // We try only with the AttachInfo because there's no point in invalidating
5254 // if we are not attached to our window
5255 if (mAttachInfo != null) {
5256 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
5257 info.target = this;
5258 info.left = left;
5259 info.top = top;
5260 info.right = right;
5261 info.bottom = bottom;
5262
5263 final Message msg = Message.obtain();
5264 msg.what = AttachInfo.INVALIDATE_RECT_MSG;
5265 msg.obj = info;
5266 mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
5267 }
5268 }
5269
5270 /**
5271 * Called by a parent to request that a child update its values for mScrollX
5272 * and mScrollY if necessary. This will typically be done if the child is
5273 * animating a scroll using a {@link android.widget.Scroller Scroller}
5274 * object.
5275 */
5276 public void computeScroll() {
5277 }
5278
5279 /**
5280 * <p>Indicate whether the horizontal edges are faded when the view is
5281 * scrolled horizontally.</p>
5282 *
5283 * @return true if the horizontal edges should are faded on scroll, false
5284 * otherwise
5285 *
5286 * @see #setHorizontalFadingEdgeEnabled(boolean)
5287 * @attr ref android.R.styleable#View_fadingEdge
5288 */
5289 public boolean isHorizontalFadingEdgeEnabled() {
5290 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
5291 }
5292
5293 /**
5294 * <p>Define whether the horizontal edges should be faded when this view
5295 * is scrolled horizontally.</p>
5296 *
5297 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
5298 * be faded when the view is scrolled
5299 * horizontally
5300 *
5301 * @see #isHorizontalFadingEdgeEnabled()
5302 * @attr ref android.R.styleable#View_fadingEdge
5303 */
5304 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
5305 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
5306 if (horizontalFadingEdgeEnabled) {
5307 initScrollCache();
5308 }
5309
5310 mViewFlags ^= FADING_EDGE_HORIZONTAL;
5311 }
5312 }
5313
5314 /**
5315 * <p>Indicate whether the vertical edges are faded when the view is
5316 * scrolled horizontally.</p>
5317 *
5318 * @return true if the vertical edges should are faded on scroll, false
5319 * otherwise
5320 *
5321 * @see #setVerticalFadingEdgeEnabled(boolean)
5322 * @attr ref android.R.styleable#View_fadingEdge
5323 */
5324 public boolean isVerticalFadingEdgeEnabled() {
5325 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
5326 }
5327
5328 /**
5329 * <p>Define whether the vertical edges should be faded when this view
5330 * is scrolled vertically.</p>
5331 *
5332 * @param verticalFadingEdgeEnabled true if the vertical edges should
5333 * be faded when the view is scrolled
5334 * vertically
5335 *
5336 * @see #isVerticalFadingEdgeEnabled()
5337 * @attr ref android.R.styleable#View_fadingEdge
5338 */
5339 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
5340 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
5341 if (verticalFadingEdgeEnabled) {
5342 initScrollCache();
5343 }
5344
5345 mViewFlags ^= FADING_EDGE_VERTICAL;
5346 }
5347 }
5348
5349 /**
5350 * Returns the strength, or intensity, of the top faded edge. The strength is
5351 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5352 * returns 0.0 or 1.0 but no value in between.
5353 *
5354 * Subclasses should override this method to provide a smoother fade transition
5355 * when scrolling occurs.
5356 *
5357 * @return the intensity of the top fade as a float between 0.0f and 1.0f
5358 */
5359 protected float getTopFadingEdgeStrength() {
5360 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
5361 }
5362
5363 /**
5364 * Returns the strength, or intensity, of the bottom faded edge. The strength is
5365 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5366 * returns 0.0 or 1.0 but no value in between.
5367 *
5368 * Subclasses should override this method to provide a smoother fade transition
5369 * when scrolling occurs.
5370 *
5371 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
5372 */
5373 protected float getBottomFadingEdgeStrength() {
5374 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
5375 computeVerticalScrollRange() ? 1.0f : 0.0f;
5376 }
5377
5378 /**
5379 * Returns the strength, or intensity, of the left faded edge. The strength is
5380 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5381 * returns 0.0 or 1.0 but no value in between.
5382 *
5383 * Subclasses should override this method to provide a smoother fade transition
5384 * when scrolling occurs.
5385 *
5386 * @return the intensity of the left fade as a float between 0.0f and 1.0f
5387 */
5388 protected float getLeftFadingEdgeStrength() {
5389 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
5390 }
5391
5392 /**
5393 * Returns the strength, or intensity, of the right faded edge. The strength is
5394 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
5395 * returns 0.0 or 1.0 but no value in between.
5396 *
5397 * Subclasses should override this method to provide a smoother fade transition
5398 * when scrolling occurs.
5399 *
5400 * @return the intensity of the right fade as a float between 0.0f and 1.0f
5401 */
5402 protected float getRightFadingEdgeStrength() {
5403 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
5404 computeHorizontalScrollRange() ? 1.0f : 0.0f;
5405 }
5406
5407 /**
5408 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
5409 * scrollbar is not drawn by default.</p>
5410 *
5411 * @return true if the horizontal scrollbar should be painted, false
5412 * otherwise
5413 *
5414 * @see #setHorizontalScrollBarEnabled(boolean)
5415 */
5416 public boolean isHorizontalScrollBarEnabled() {
5417 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
5418 }
5419
5420 /**
5421 * <p>Define whether the horizontal scrollbar should be drawn or not. The
5422 * scrollbar is not drawn by default.</p>
5423 *
5424 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
5425 * be painted
5426 *
5427 * @see #isHorizontalScrollBarEnabled()
5428 */
5429 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
5430 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
5431 mViewFlags ^= SCROLLBARS_HORIZONTAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07005432 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005433 recomputePadding();
5434 }
5435 }
5436
5437 /**
5438 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
5439 * scrollbar is not drawn by default.</p>
5440 *
5441 * @return true if the vertical scrollbar should be painted, false
5442 * otherwise
5443 *
5444 * @see #setVerticalScrollBarEnabled(boolean)
5445 */
5446 public boolean isVerticalScrollBarEnabled() {
5447 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
5448 }
5449
5450 /**
5451 * <p>Define whether the vertical scrollbar should be drawn or not. The
5452 * scrollbar is not drawn by default.</p>
5453 *
5454 * @param verticalScrollBarEnabled true if the vertical scrollbar should
5455 * be painted
5456 *
5457 * @see #isVerticalScrollBarEnabled()
5458 */
5459 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
5460 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
5461 mViewFlags ^= SCROLLBARS_VERTICAL;
Romain Guy8f1344f52009-05-15 16:03:59 -07005462 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 recomputePadding();
5464 }
5465 }
5466
5467 private void recomputePadding() {
5468 setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
5469 }
Mike Cleronfe81d382009-09-28 14:22:16 -07005470
5471 /**
5472 * Define whether scrollbars will fade when the view is not scrolling.
5473 *
5474 * @param fadeScrollbars wheter to enable fading
5475 *
5476 */
5477 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
5478 initScrollCache();
5479 final ScrollabilityCache scrollabilityCache = mScrollCache;
5480 scrollabilityCache.fadeScrollBars = fadeScrollbars;
Mike Cleron52f0a642009-09-28 18:21:37 -07005481 if (fadeScrollbars) {
5482 scrollabilityCache.state = ScrollabilityCache.OFF;
5483 } else {
Mike Cleronfe81d382009-09-28 14:22:16 -07005484 scrollabilityCache.state = ScrollabilityCache.ON;
5485 }
5486 }
5487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 /**
Mike Cleron52f0a642009-09-28 18:21:37 -07005489 *
5490 * Returns true if scrollbars will fade when this view is not scrolling
5491 *
5492 * @return true if scrollbar fading is enabled
5493 */
5494 public boolean isScrollbarFadingEnabled() {
5495 return mScrollCache != null && mScrollCache.fadeScrollBars;
5496 }
5497
5498 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
5500 * inset. When inset, they add to the padding of the view. And the scrollbars
5501 * can be drawn inside the padding area or on the edge of the view. For example,
5502 * if a view has a background drawable and you want to draw the scrollbars
5503 * inside the padding specified by the drawable, you can use
5504 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
5505 * appear at the edge of the view, ignoring the padding, then you can use
5506 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
5507 * @param style the style of the scrollbars. Should be one of
5508 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
5509 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
5510 * @see #SCROLLBARS_INSIDE_OVERLAY
5511 * @see #SCROLLBARS_INSIDE_INSET
5512 * @see #SCROLLBARS_OUTSIDE_OVERLAY
5513 * @see #SCROLLBARS_OUTSIDE_INSET
5514 */
5515 public void setScrollBarStyle(int style) {
5516 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
5517 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
Romain Guy8f1344f52009-05-15 16:03:59 -07005518 computeOpaqueFlags();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 recomputePadding();
5520 }
5521 }
5522
5523 /**
5524 * <p>Returns the current scrollbar style.</p>
5525 * @return the current scrollbar style
5526 * @see #SCROLLBARS_INSIDE_OVERLAY
5527 * @see #SCROLLBARS_INSIDE_INSET
5528 * @see #SCROLLBARS_OUTSIDE_OVERLAY
5529 * @see #SCROLLBARS_OUTSIDE_INSET
5530 */
5531 public int getScrollBarStyle() {
5532 return mViewFlags & SCROLLBARS_STYLE_MASK;
5533 }
5534
5535 /**
5536 * <p>Compute the horizontal range that the horizontal scrollbar
5537 * represents.</p>
5538 *
5539 * <p>The range is expressed in arbitrary units that must be the same as the
5540 * units used by {@link #computeHorizontalScrollExtent()} and
5541 * {@link #computeHorizontalScrollOffset()}.</p>
5542 *
5543 * <p>The default range is the drawing width of this view.</p>
5544 *
5545 * @return the total horizontal range represented by the horizontal
5546 * scrollbar
5547 *
5548 * @see #computeHorizontalScrollExtent()
5549 * @see #computeHorizontalScrollOffset()
5550 * @see android.widget.ScrollBarDrawable
5551 */
5552 protected int computeHorizontalScrollRange() {
5553 return getWidth();
5554 }
5555
5556 /**
5557 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
5558 * within the horizontal range. This value is used to compute the position
5559 * of the thumb within the scrollbar's track.</p>
5560 *
5561 * <p>The range is expressed in arbitrary units that must be the same as the
5562 * units used by {@link #computeHorizontalScrollRange()} and
5563 * {@link #computeHorizontalScrollExtent()}.</p>
5564 *
5565 * <p>The default offset is the scroll offset of this view.</p>
5566 *
5567 * @return the horizontal offset of the scrollbar's thumb
5568 *
5569 * @see #computeHorizontalScrollRange()
5570 * @see #computeHorizontalScrollExtent()
5571 * @see android.widget.ScrollBarDrawable
5572 */
5573 protected int computeHorizontalScrollOffset() {
5574 return mScrollX;
5575 }
5576
5577 /**
5578 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
5579 * within the horizontal range. This value is used to compute the length
5580 * of the thumb within the scrollbar's track.</p>
5581 *
5582 * <p>The range is expressed in arbitrary units that must be the same as the
5583 * units used by {@link #computeHorizontalScrollRange()} and
5584 * {@link #computeHorizontalScrollOffset()}.</p>
5585 *
5586 * <p>The default extent is the drawing width of this view.</p>
5587 *
5588 * @return the horizontal extent of the scrollbar's thumb
5589 *
5590 * @see #computeHorizontalScrollRange()
5591 * @see #computeHorizontalScrollOffset()
5592 * @see android.widget.ScrollBarDrawable
5593 */
5594 protected int computeHorizontalScrollExtent() {
5595 return getWidth();
5596 }
5597
5598 /**
5599 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
5600 *
5601 * <p>The range is expressed in arbitrary units that must be the same as the
5602 * units used by {@link #computeVerticalScrollExtent()} and
5603 * {@link #computeVerticalScrollOffset()}.</p>
5604 *
5605 * @return the total vertical range represented by the vertical scrollbar
5606 *
5607 * <p>The default range is the drawing height of this view.</p>
5608 *
5609 * @see #computeVerticalScrollExtent()
5610 * @see #computeVerticalScrollOffset()
5611 * @see android.widget.ScrollBarDrawable
5612 */
5613 protected int computeVerticalScrollRange() {
5614 return getHeight();
5615 }
5616
5617 /**
5618 * <p>Compute the vertical offset of the vertical scrollbar's thumb
5619 * within the horizontal range. This value is used to compute the position
5620 * of the thumb within the scrollbar's track.</p>
5621 *
5622 * <p>The range is expressed in arbitrary units that must be the same as the
5623 * units used by {@link #computeVerticalScrollRange()} and
5624 * {@link #computeVerticalScrollExtent()}.</p>
5625 *
5626 * <p>The default offset is the scroll offset of this view.</p>
5627 *
5628 * @return the vertical offset of the scrollbar's thumb
5629 *
5630 * @see #computeVerticalScrollRange()
5631 * @see #computeVerticalScrollExtent()
5632 * @see android.widget.ScrollBarDrawable
5633 */
5634 protected int computeVerticalScrollOffset() {
5635 return mScrollY;
5636 }
5637
5638 /**
5639 * <p>Compute the vertical extent of the horizontal scrollbar's thumb
5640 * within the vertical range. This value is used to compute the length
5641 * of the thumb within the scrollbar's track.</p>
5642 *
5643 * <p>The range is expressed in arbitrary units that must be the same as the
5644 * units used by {@link #computeHorizontalScrollRange()} and
5645 * {@link #computeVerticalScrollOffset()}.</p>
5646 *
5647 * <p>The default extent is the drawing height of this view.</p>
5648 *
5649 * @return the vertical extent of the scrollbar's thumb
5650 *
5651 * @see #computeVerticalScrollRange()
5652 * @see #computeVerticalScrollOffset()
5653 * @see android.widget.ScrollBarDrawable
5654 */
5655 protected int computeVerticalScrollExtent() {
5656 return getHeight();
5657 }
5658
5659 /**
5660 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
5661 * scrollbars are painted only if they have been awakened first.</p>
5662 *
5663 * @param canvas the canvas on which to draw the scrollbars
Mike Cleronf116bf82009-09-27 19:14:12 -07005664 *
5665 * @see #awakenScrollBars(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 */
Romain Guy1d5b3a62009-11-05 18:44:12 -08005667 protected final void onDrawScrollBars(Canvas canvas) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 // scrollbars are drawn only when the animation is running
5669 final ScrollabilityCache cache = mScrollCache;
5670 if (cache != null) {
Mike Cleronf116bf82009-09-27 19:14:12 -07005671
5672 int state = cache.state;
5673
5674 if (state == ScrollabilityCache.OFF) {
5675 return;
5676 }
5677
5678 boolean invalidate = false;
5679
5680 if (state == ScrollabilityCache.FADING) {
5681 // We're fading -- get our fade interpolation
5682 if (cache.interpolatorValues == null) {
5683 cache.interpolatorValues = new float[1];
5684 }
5685
5686 float[] values = cache.interpolatorValues;
5687
5688 // Stops the animation if we're done
5689 if (cache.scrollBarInterpolator.timeToValues(values) ==
5690 Interpolator.Result.FREEZE_END) {
5691 cache.state = ScrollabilityCache.OFF;
5692 } else {
5693 cache.scrollBar.setAlpha(Math.round(values[0]));
5694 }
5695
5696 // This will make the scroll bars inval themselves after
5697 // drawing. We only want this when we're fading so that
5698 // we prevent excessive redraws
5699 invalidate = true;
5700 } else {
5701 // We're just on -- but we may have been fading before so
5702 // reset alpha
5703 cache.scrollBar.setAlpha(255);
5704 }
5705
5706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 final int viewFlags = mViewFlags;
5708
5709 final boolean drawHorizontalScrollBar =
5710 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
5711 final boolean drawVerticalScrollBar =
5712 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
5713 && !isVerticalScrollBarHidden();
5714
5715 if (drawVerticalScrollBar || drawHorizontalScrollBar) {
5716 final int width = mRight - mLeft;
5717 final int height = mBottom - mTop;
5718
5719 final ScrollBarDrawable scrollBar = cache.scrollBar;
5720 int size = scrollBar.getSize(false);
5721 if (size <= 0) {
5722 size = cache.scrollBarSize;
5723 }
5724
Mike Reede8853fc2009-09-04 14:01:48 -04005725 final int scrollX = mScrollX;
5726 final int scrollY = mScrollY;
5727 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
5728
Mike Cleronf116bf82009-09-27 19:14:12 -07005729 int left, top, right, bottom;
5730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 if (drawHorizontalScrollBar) {
Mike Cleronf116bf82009-09-27 19:14:12 -07005732 scrollBar.setParameters(computeHorizontalScrollRange(),
Mike Reede8853fc2009-09-04 14:01:48 -04005733 computeHorizontalScrollOffset(),
5734 computeHorizontalScrollExtent(), false);
Mike Reede8853fc2009-09-04 14:01:48 -04005735 final int verticalScrollBarGap = drawVerticalScrollBar ?
Mike Cleronf116bf82009-09-27 19:14:12 -07005736 getVerticalScrollbarWidth() : 0;
5737 top = scrollY + height - size - (mUserPaddingBottom & inside);
5738 left = scrollX + (mPaddingLeft & inside);
5739 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
5740 bottom = top + size;
5741 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
5742 if (invalidate) {
5743 invalidate(left, top, right, bottom);
5744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 }
5746
5747 if (drawVerticalScrollBar) {
Mike Reede8853fc2009-09-04 14:01:48 -04005748 scrollBar.setParameters(computeVerticalScrollRange(),
5749 computeVerticalScrollOffset(),
5750 computeVerticalScrollExtent(), true);
5751 // TODO: Deal with RTL languages to position scrollbar on left
Mike Cleronf116bf82009-09-27 19:14:12 -07005752 left = scrollX + width - size - (mUserPaddingRight & inside);
5753 top = scrollY + (mPaddingTop & inside);
5754 right = left + size;
5755 bottom = scrollY + height - (mUserPaddingBottom & inside);
5756 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
5757 if (invalidate) {
5758 invalidate(left, top, right, bottom);
5759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 }
5761 }
5762 }
5763 }
Romain Guy8506ab42009-06-11 17:35:47 -07005764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765 /**
Romain Guy8506ab42009-06-11 17:35:47 -07005766 * 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 -08005767 * FastScroller is visible.
5768 * @return whether to temporarily hide the vertical scrollbar
5769 * @hide
5770 */
5771 protected boolean isVerticalScrollBarHidden() {
5772 return false;
5773 }
5774
5775 /**
5776 * <p>Draw the horizontal scrollbar if
5777 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
5778 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 * @param canvas the canvas on which to draw the scrollbar
5780 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005781 *
5782 * @see #isHorizontalScrollBarEnabled()
5783 * @see #computeHorizontalScrollRange()
5784 * @see #computeHorizontalScrollExtent()
5785 * @see #computeHorizontalScrollOffset()
5786 * @see android.widget.ScrollBarDrawable
Mike Cleronf116bf82009-09-27 19:14:12 -07005787 * @hide
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005788 */
Mike Reede8853fc2009-09-04 14:01:48 -04005789 protected void onDrawHorizontalScrollBar(Canvas canvas,
5790 Drawable scrollBar,
5791 int l, int t, int r, int b) {
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005792 scrollBar.setBounds(l, t, r, b);
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005793 scrollBar.draw(canvas);
5794 }
Mike Reede8853fc2009-09-04 14:01:48 -04005795
Mike Reed4d6fe5f2009-09-03 13:29:05 -04005796 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
5798 * returns true.</p>
5799 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 * @param canvas the canvas on which to draw the scrollbar
5801 * @param scrollBar the scrollbar's drawable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802 *
5803 * @see #isVerticalScrollBarEnabled()
5804 * @see #computeVerticalScrollRange()
5805 * @see #computeVerticalScrollExtent()
5806 * @see #computeVerticalScrollOffset()
5807 * @see android.widget.ScrollBarDrawable
Mike Reede8853fc2009-09-04 14:01:48 -04005808 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 */
Mike Reede8853fc2009-09-04 14:01:48 -04005810 protected void onDrawVerticalScrollBar(Canvas canvas,
5811 Drawable scrollBar,
5812 int l, int t, int r, int b) {
5813 scrollBar.setBounds(l, t, r, b);
5814 scrollBar.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005815 }
5816
5817 /**
5818 * Implement this to do your drawing.
5819 *
5820 * @param canvas the canvas on which the background will be drawn
5821 */
5822 protected void onDraw(Canvas canvas) {
5823 }
5824
5825 /*
5826 * Caller is responsible for calling requestLayout if necessary.
5827 * (This allows addViewInLayout to not request a new layout.)
5828 */
5829 void assignParent(ViewParent parent) {
5830 if (mParent == null) {
5831 mParent = parent;
5832 } else if (parent == null) {
5833 mParent = null;
5834 } else {
5835 throw new RuntimeException("view " + this + " being added, but"
5836 + " it already has a parent");
5837 }
5838 }
5839
5840 /**
5841 * This is called when the view is attached to a window. At this point it
5842 * has a Surface and will start drawing. Note that this function is
5843 * guaranteed to be called before {@link #onDraw}, however it may be called
5844 * any time before the first onDraw -- including before or after
5845 * {@link #onMeasure}.
5846 *
5847 * @see #onDetachedFromWindow()
5848 */
5849 protected void onAttachedToWindow() {
5850 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
5851 mParent.requestTransparentRegion(this);
5852 }
5853 }
5854
5855 /**
5856 * This is called when the view is detached from a window. At this point it
5857 * no longer has a surface for drawing.
5858 *
5859 * @see #onAttachedToWindow()
5860 */
5861 protected void onDetachedFromWindow() {
Maryam Garrett1549dd12009-12-15 16:06:36 -05005862 removeLongPressCallback();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 destroyDrawingCache();
5864 }
5865
5866 /**
5867 * @return The number of times this view has been attached to a window
5868 */
5869 protected int getWindowAttachCount() {
5870 return mWindowAttachCount;
5871 }
5872
5873 /**
5874 * Retrieve a unique token identifying the window this view is attached to.
5875 * @return Return the window's token for use in
5876 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
5877 */
5878 public IBinder getWindowToken() {
5879 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
5880 }
5881
5882 /**
5883 * Retrieve a unique token identifying the top-level "real" window of
5884 * the window that this view is attached to. That is, this is like
5885 * {@link #getWindowToken}, except if the window this view in is a panel
5886 * window (attached to another containing window), then the token of
5887 * the containing window is returned instead.
5888 *
5889 * @return Returns the associated window token, either
5890 * {@link #getWindowToken()} or the containing window's token.
5891 */
5892 public IBinder getApplicationWindowToken() {
5893 AttachInfo ai = mAttachInfo;
5894 if (ai != null) {
5895 IBinder appWindowToken = ai.mPanelParentWindowToken;
5896 if (appWindowToken == null) {
5897 appWindowToken = ai.mWindowToken;
5898 }
5899 return appWindowToken;
5900 }
5901 return null;
5902 }
5903
5904 /**
5905 * Retrieve private session object this view hierarchy is using to
5906 * communicate with the window manager.
5907 * @return the session object to communicate with the window manager
5908 */
5909 /*package*/ IWindowSession getWindowSession() {
5910 return mAttachInfo != null ? mAttachInfo.mSession : null;
5911 }
5912
5913 /**
5914 * @param info the {@link android.view.View.AttachInfo} to associated with
5915 * this view
5916 */
5917 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
5918 //System.out.println("Attached! " + this);
5919 mAttachInfo = info;
5920 mWindowAttachCount++;
5921 if (mFloatingTreeObserver != null) {
5922 info.mTreeObserver.merge(mFloatingTreeObserver);
5923 mFloatingTreeObserver = null;
5924 }
5925 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
5926 mAttachInfo.mScrollContainers.add(this);
5927 mPrivateFlags |= SCROLL_CONTAINER_ADDED;
5928 }
5929 performCollectViewAttributes(visibility);
5930 onAttachedToWindow();
5931 int vis = info.mWindowVisibility;
5932 if (vis != GONE) {
5933 onWindowVisibilityChanged(vis);
5934 }
5935 }
5936
5937 void dispatchDetachedFromWindow() {
5938 //System.out.println("Detached! " + this);
5939 AttachInfo info = mAttachInfo;
5940 if (info != null) {
5941 int vis = info.mWindowVisibility;
5942 if (vis != GONE) {
5943 onWindowVisibilityChanged(GONE);
5944 }
5945 }
5946
5947 onDetachedFromWindow();
5948 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
5949 mAttachInfo.mScrollContainers.remove(this);
5950 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
5951 }
5952 mAttachInfo = null;
5953 }
5954
5955 /**
5956 * Store this view hierarchy's frozen state into the given container.
5957 *
5958 * @param container The SparseArray in which to save the view's state.
5959 *
5960 * @see #restoreHierarchyState
5961 * @see #dispatchSaveInstanceState
5962 * @see #onSaveInstanceState
5963 */
5964 public void saveHierarchyState(SparseArray<Parcelable> container) {
5965 dispatchSaveInstanceState(container);
5966 }
5967
5968 /**
5969 * Called by {@link #saveHierarchyState} to store the state for this view and its children.
5970 * May be overridden to modify how freezing happens to a view's children; for example, some
5971 * views may want to not store state for their children.
5972 *
5973 * @param container The SparseArray in which to save the view's state.
5974 *
5975 * @see #dispatchRestoreInstanceState
5976 * @see #saveHierarchyState
5977 * @see #onSaveInstanceState
5978 */
5979 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
5980 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
5981 mPrivateFlags &= ~SAVE_STATE_CALLED;
5982 Parcelable state = onSaveInstanceState();
5983 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
5984 throw new IllegalStateException(
5985 "Derived class did not call super.onSaveInstanceState()");
5986 }
5987 if (state != null) {
5988 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
5989 // + ": " + state);
5990 container.put(mID, state);
5991 }
5992 }
5993 }
5994
5995 /**
5996 * Hook allowing a view to generate a representation of its internal state
5997 * that can later be used to create a new instance with that same state.
5998 * This state should only contain information that is not persistent or can
5999 * not be reconstructed later. For example, you will never store your
6000 * current position on screen because that will be computed again when a
6001 * new instance of the view is placed in its view hierarchy.
6002 * <p>
6003 * Some examples of things you may store here: the current cursor position
6004 * in a text view (but usually not the text itself since that is stored in a
6005 * content provider or other persistent storage), the currently selected
6006 * item in a list view.
6007 *
6008 * @return Returns a Parcelable object containing the view's current dynamic
6009 * state, or null if there is nothing interesting to save. The
6010 * default implementation returns null.
6011 * @see #onRestoreInstanceState
6012 * @see #saveHierarchyState
6013 * @see #dispatchSaveInstanceState
6014 * @see #setSaveEnabled(boolean)
6015 */
6016 protected Parcelable onSaveInstanceState() {
6017 mPrivateFlags |= SAVE_STATE_CALLED;
6018 return BaseSavedState.EMPTY_STATE;
6019 }
6020
6021 /**
6022 * Restore this view hierarchy's frozen state from the given container.
6023 *
6024 * @param container The SparseArray which holds previously frozen states.
6025 *
6026 * @see #saveHierarchyState
6027 * @see #dispatchRestoreInstanceState
6028 * @see #onRestoreInstanceState
6029 */
6030 public void restoreHierarchyState(SparseArray<Parcelable> container) {
6031 dispatchRestoreInstanceState(container);
6032 }
6033
6034 /**
6035 * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
6036 * children. May be overridden to modify how restoreing happens to a view's children; for
6037 * example, some views may want to not store state for their children.
6038 *
6039 * @param container The SparseArray which holds previously saved state.
6040 *
6041 * @see #dispatchSaveInstanceState
6042 * @see #restoreHierarchyState
6043 * @see #onRestoreInstanceState
6044 */
6045 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
6046 if (mID != NO_ID) {
6047 Parcelable state = container.get(mID);
6048 if (state != null) {
6049 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
6050 // + ": " + state);
6051 mPrivateFlags &= ~SAVE_STATE_CALLED;
6052 onRestoreInstanceState(state);
6053 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
6054 throw new IllegalStateException(
6055 "Derived class did not call super.onRestoreInstanceState()");
6056 }
6057 }
6058 }
6059 }
6060
6061 /**
6062 * Hook allowing a view to re-apply a representation of its internal state that had previously
6063 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
6064 * null state.
6065 *
6066 * @param state The frozen state that had previously been returned by
6067 * {@link #onSaveInstanceState}.
6068 *
6069 * @see #onSaveInstanceState
6070 * @see #restoreHierarchyState
6071 * @see #dispatchRestoreInstanceState
6072 */
6073 protected void onRestoreInstanceState(Parcelable state) {
6074 mPrivateFlags |= SAVE_STATE_CALLED;
6075 if (state != BaseSavedState.EMPTY_STATE && state != null) {
Romain Guy237c1ce2009-12-08 11:30:25 -08006076 throw new IllegalArgumentException("Wrong state class, expecting View State but "
6077 + "received " + state.getClass().toString() + " instead. This usually happens "
6078 + "when two views of different type have the same id in the same hierarchy. "
6079 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
6080 + "other views do not use the same id.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 }
6082 }
6083
6084 /**
6085 * <p>Return the time at which the drawing of the view hierarchy started.</p>
6086 *
6087 * @return the drawing start time in milliseconds
6088 */
6089 public long getDrawingTime() {
6090 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
6091 }
6092
6093 /**
6094 * <p>Enables or disables the duplication of the parent's state into this view. When
6095 * duplication is enabled, this view gets its drawable state from its parent rather
6096 * than from its own internal properties.</p>
6097 *
6098 * <p>Note: in the current implementation, setting this property to true after the
6099 * view was added to a ViewGroup might have no effect at all. This property should
6100 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
6101 *
6102 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
6103 * property is enabled, an exception will be thrown.</p>
6104 *
6105 * @param enabled True to enable duplication of the parent's drawable state, false
6106 * to disable it.
6107 *
6108 * @see #getDrawableState()
6109 * @see #isDuplicateParentStateEnabled()
6110 */
6111 public void setDuplicateParentStateEnabled(boolean enabled) {
6112 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
6113 }
6114
6115 /**
6116 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
6117 *
6118 * @return True if this view's drawable state is duplicated from the parent,
6119 * false otherwise
6120 *
6121 * @see #getDrawableState()
6122 * @see #setDuplicateParentStateEnabled(boolean)
6123 */
6124 public boolean isDuplicateParentStateEnabled() {
6125 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
6126 }
6127
6128 /**
6129 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
6130 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
6131 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
6132 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
6133 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
6134 * null.</p>
6135 *
6136 * @param enabled true to enable the drawing cache, false otherwise
6137 *
6138 * @see #isDrawingCacheEnabled()
6139 * @see #getDrawingCache()
6140 * @see #buildDrawingCache()
6141 */
6142 public void setDrawingCacheEnabled(boolean enabled) {
6143 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
6144 }
6145
6146 /**
6147 * <p>Indicates whether the drawing cache is enabled for this view.</p>
6148 *
6149 * @return true if the drawing cache is enabled
6150 *
6151 * @see #setDrawingCacheEnabled(boolean)
6152 * @see #getDrawingCache()
6153 */
6154 @ViewDebug.ExportedProperty
6155 public boolean isDrawingCacheEnabled() {
6156 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
6157 }
6158
6159 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07006160 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
6161 *
6162 * @return A non-scaled bitmap representing this view or null if cache is disabled.
6163 *
6164 * @see #getDrawingCache(boolean)
6165 */
6166 public Bitmap getDrawingCache() {
6167 return getDrawingCache(false);
6168 }
6169
6170 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
6172 * is null when caching is disabled. If caching is enabled and the cache is not ready,
6173 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
6174 * draw from the cache when the cache is enabled. To benefit from the cache, you must
6175 * request the drawing cache by calling this method and draw it on screen if the
6176 * returned bitmap is not null.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07006177 *
6178 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
6179 * this method will create a bitmap of the same size as this view. Because this bitmap
6180 * will be drawn scaled by the parent ViewGroup, the result on screen might show
6181 * scaling artifacts. To avoid such artifacts, you should call this method by setting
6182 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
6183 * size than the view. This implies that your application must be able to handle this
6184 * size.</p>
6185 *
6186 * @param autoScale Indicates whether the generated bitmap should be scaled based on
6187 * the current density of the screen when the application is in compatibility
6188 * mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 *
Romain Guyfbd8f692009-06-26 14:51:58 -07006190 * @return A bitmap representing this view or null if cache is disabled.
6191 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 * @see #setDrawingCacheEnabled(boolean)
6193 * @see #isDrawingCacheEnabled()
Romain Guyfbd8f692009-06-26 14:51:58 -07006194 * @see #buildDrawingCache(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006195 * @see #destroyDrawingCache()
6196 */
Romain Guyfbd8f692009-06-26 14:51:58 -07006197 public Bitmap getDrawingCache(boolean autoScale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
6199 return null;
6200 }
6201 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
Romain Guyfbd8f692009-06-26 14:51:58 -07006202 buildDrawingCache(autoScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 }
Romain Guyfbd8f692009-06-26 14:51:58 -07006204 return autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) :
6205 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 }
6207
6208 /**
6209 * <p>Frees the resources used by the drawing cache. If you call
6210 * {@link #buildDrawingCache()} manually without calling
6211 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
6212 * should cleanup the cache with this method afterwards.</p>
6213 *
6214 * @see #setDrawingCacheEnabled(boolean)
6215 * @see #buildDrawingCache()
6216 * @see #getDrawingCache()
6217 */
6218 public void destroyDrawingCache() {
6219 if (mDrawingCache != null) {
6220 final Bitmap bitmap = mDrawingCache.get();
6221 if (bitmap != null) bitmap.recycle();
6222 mDrawingCache = null;
6223 }
Romain Guyfbd8f692009-06-26 14:51:58 -07006224 if (mUnscaledDrawingCache != null) {
6225 final Bitmap bitmap = mUnscaledDrawingCache.get();
6226 if (bitmap != null) bitmap.recycle();
6227 mUnscaledDrawingCache = null;
6228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 }
6230
6231 /**
6232 * Setting a solid background color for the drawing cache's bitmaps will improve
6233 * perfromance and memory usage. Note, though that this should only be used if this
6234 * view will always be drawn on top of a solid color.
6235 *
6236 * @param color The background color to use for the drawing cache's bitmap
6237 *
6238 * @see #setDrawingCacheEnabled(boolean)
6239 * @see #buildDrawingCache()
6240 * @see #getDrawingCache()
6241 */
6242 public void setDrawingCacheBackgroundColor(int color) {
Romain Guy52e2ef82010-01-14 12:11:48 -08006243 if (color != mDrawingCacheBackgroundColor) {
6244 mDrawingCacheBackgroundColor = color;
6245 mPrivateFlags &= ~DRAWING_CACHE_VALID;
6246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 }
6248
6249 /**
6250 * @see #setDrawingCacheBackgroundColor(int)
6251 *
6252 * @return The background color to used for the drawing cache's bitmap
6253 */
6254 public int getDrawingCacheBackgroundColor() {
6255 return mDrawingCacheBackgroundColor;
6256 }
6257
6258 /**
Romain Guyfbd8f692009-06-26 14:51:58 -07006259 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
6260 *
6261 * @see #buildDrawingCache(boolean)
6262 */
6263 public void buildDrawingCache() {
6264 buildDrawingCache(false);
6265 }
6266
6267 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
6269 *
6270 * <p>If you call {@link #buildDrawingCache()} manually without calling
6271 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
6272 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
Romain Guyfbd8f692009-06-26 14:51:58 -07006273 *
6274 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
6275 * this method will create a bitmap of the same size as this view. Because this bitmap
6276 * will be drawn scaled by the parent ViewGroup, the result on screen might show
6277 * scaling artifacts. To avoid such artifacts, you should call this method by setting
6278 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
6279 * size than the view. This implies that your application must be able to handle this
6280 * size.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 *
6282 * @see #getDrawingCache()
6283 * @see #destroyDrawingCache()
6284 */
Romain Guyfbd8f692009-06-26 14:51:58 -07006285 public void buildDrawingCache(boolean autoScale) {
6286 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
6287 (mDrawingCache == null || mDrawingCache.get() == null) :
6288 (mUnscaledDrawingCache == null || mUnscaledDrawingCache.get() == null))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006289
6290 if (ViewDebug.TRACE_HIERARCHY) {
6291 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
6292 }
Romain Guy13922e02009-05-12 17:56:14 -07006293 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 EventLog.writeEvent(60002, hashCode());
6295 }
6296
Romain Guy8506ab42009-06-11 17:35:47 -07006297 int width = mRight - mLeft;
6298 int height = mBottom - mTop;
6299
6300 final AttachInfo attachInfo = mAttachInfo;
Romain Guye1123222009-06-29 14:24:56 -07006301 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
Romain Guyfbd8f692009-06-26 14:51:58 -07006302
Romain Guye1123222009-06-29 14:24:56 -07006303 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07006304 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
6305 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
Romain Guy8506ab42009-06-11 17:35:47 -07006306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307
6308 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
Romain Guy35b38ce2009-10-07 13:38:55 -07006309 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
Romain Guya62e4702009-10-08 10:48:54 -07006310 final boolean translucentWindow = attachInfo != null && attachInfo.mTranslucentWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311
6312 if (width <= 0 || height <= 0 ||
Romain Guy35b38ce2009-10-07 13:38:55 -07006313 // Projected bitmap size in bytes
6314 (width * height * (opaque && !translucentWindow ? 2 : 4) >
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006315 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
6316 destroyDrawingCache();
6317 return;
6318 }
6319
6320 boolean clear = true;
Romain Guyfbd8f692009-06-26 14:51:58 -07006321 Bitmap bitmap = autoScale ? (mDrawingCache == null ? null : mDrawingCache.get()) :
6322 (mUnscaledDrawingCache == null ? null : mUnscaledDrawingCache.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323
6324 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 Bitmap.Config quality;
6326 if (!opaque) {
6327 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
6328 case DRAWING_CACHE_QUALITY_AUTO:
6329 quality = Bitmap.Config.ARGB_8888;
6330 break;
6331 case DRAWING_CACHE_QUALITY_LOW:
6332 quality = Bitmap.Config.ARGB_4444;
6333 break;
6334 case DRAWING_CACHE_QUALITY_HIGH:
6335 quality = Bitmap.Config.ARGB_8888;
6336 break;
6337 default:
6338 quality = Bitmap.Config.ARGB_8888;
6339 break;
6340 }
6341 } else {
Romain Guy35b38ce2009-10-07 13:38:55 -07006342 // Optimization for translucent windows
6343 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
6344 quality = translucentWindow ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 }
6346
6347 // Try to cleanup memory
6348 if (bitmap != null) bitmap.recycle();
6349
6350 try {
6351 bitmap = Bitmap.createBitmap(width, height, quality);
Dianne Hackborn11ea3342009-07-22 21:48:55 -07006352 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
Romain Guyfbd8f692009-06-26 14:51:58 -07006353 if (autoScale) {
6354 mDrawingCache = new SoftReference<Bitmap>(bitmap);
6355 } else {
6356 mUnscaledDrawingCache = new SoftReference<Bitmap>(bitmap);
6357 }
Romain Guy35b38ce2009-10-07 13:38:55 -07006358 if (opaque && translucentWindow) bitmap.setHasAlpha(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 } catch (OutOfMemoryError e) {
6360 // If there is not enough memory to create the bitmap cache, just
6361 // ignore the issue as bitmap caches are not required to draw the
6362 // view hierarchy
Romain Guyfbd8f692009-06-26 14:51:58 -07006363 if (autoScale) {
6364 mDrawingCache = null;
6365 } else {
6366 mUnscaledDrawingCache = null;
6367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368 return;
6369 }
6370
6371 clear = drawingCacheBackgroundColor != 0;
6372 }
6373
6374 Canvas canvas;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 if (attachInfo != null) {
6376 canvas = attachInfo.mCanvas;
6377 if (canvas == null) {
6378 canvas = new Canvas();
6379 }
6380 canvas.setBitmap(bitmap);
6381 // Temporarily clobber the cached Canvas in case one of our children
6382 // is also using a drawing cache. Without this, the children would
6383 // steal the canvas by attaching their own bitmap to it and bad, bad
6384 // thing would happen (invisible views, corrupted drawings, etc.)
6385 attachInfo.mCanvas = null;
6386 } else {
6387 // This case should hopefully never or seldom happen
6388 canvas = new Canvas(bitmap);
6389 }
6390
6391 if (clear) {
6392 bitmap.eraseColor(drawingCacheBackgroundColor);
6393 }
6394
6395 computeScroll();
6396 final int restoreCount = canvas.save();
Romain Guyfbd8f692009-06-26 14:51:58 -07006397
Romain Guye1123222009-06-29 14:24:56 -07006398 if (autoScale && scalingRequired) {
Romain Guyfbd8f692009-06-26 14:51:58 -07006399 final float scale = attachInfo.mApplicationScale;
6400 canvas.scale(scale, scale);
6401 }
6402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 canvas.translate(-mScrollX, -mScrollY);
6404
Romain Guy5bcdff42009-05-14 21:27:18 -07006405 mPrivateFlags |= DRAWN;
Romain Guyecd80ee2009-12-03 17:13:02 -08006406 mPrivateFlags |= DRAWING_CACHE_VALID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407
6408 // Fast path for layouts with no backgrounds
6409 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
6410 if (ViewDebug.TRACE_HIERARCHY) {
6411 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
6412 }
Romain Guy5bcdff42009-05-14 21:27:18 -07006413 mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 dispatchDraw(canvas);
6415 } else {
6416 draw(canvas);
6417 }
6418
6419 canvas.restoreToCount(restoreCount);
6420
6421 if (attachInfo != null) {
6422 // Restore the cached Canvas for our siblings
6423 attachInfo.mCanvas = canvas;
6424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 }
6426 }
6427
6428 /**
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006429 * Create a snapshot of the view into a bitmap. We should probably make
6430 * some form of this public, but should think about the API.
6431 */
Romain Guya2431d02009-04-30 16:30:00 -07006432 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor) {
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006433 int width = mRight - mLeft;
6434 int height = mBottom - mTop;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006435
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006436 final AttachInfo attachInfo = mAttachInfo;
Romain Guy8c11e312009-09-14 15:15:30 -07006437 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006438 width = (int) ((width * scale) + 0.5f);
6439 height = (int) ((height * scale) + 0.5f);
6440
Romain Guy8c11e312009-09-14 15:15:30 -07006441 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006442 if (bitmap == null) {
6443 throw new OutOfMemoryError();
6444 }
6445
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006446 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
6447
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006448 Canvas canvas;
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006449 if (attachInfo != null) {
6450 canvas = attachInfo.mCanvas;
6451 if (canvas == null) {
6452 canvas = new Canvas();
6453 }
6454 canvas.setBitmap(bitmap);
6455 // Temporarily clobber the cached Canvas in case one of our children
6456 // is also using a drawing cache. Without this, the children would
6457 // steal the canvas by attaching their own bitmap to it and bad, bad
6458 // things would happen (invisible views, corrupted drawings, etc.)
6459 attachInfo.mCanvas = null;
6460 } else {
6461 // This case should hopefully never or seldom happen
6462 canvas = new Canvas(bitmap);
6463 }
6464
Romain Guy5bcdff42009-05-14 21:27:18 -07006465 if ((backgroundColor & 0xff000000) != 0) {
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006466 bitmap.eraseColor(backgroundColor);
6467 }
6468
6469 computeScroll();
6470 final int restoreCount = canvas.save();
Dianne Hackborn8cae1242009-09-10 14:32:16 -07006471 canvas.scale(scale, scale);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006472 canvas.translate(-mScrollX, -mScrollY);
6473
Romain Guy5bcdff42009-05-14 21:27:18 -07006474 // Temporarily remove the dirty mask
6475 int flags = mPrivateFlags;
6476 mPrivateFlags &= ~DIRTY_MASK;
6477
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006478 // Fast path for layouts with no backgrounds
6479 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
6480 dispatchDraw(canvas);
6481 } else {
6482 draw(canvas);
6483 }
6484
Romain Guy5bcdff42009-05-14 21:27:18 -07006485 mPrivateFlags = flags;
6486
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006487 canvas.restoreToCount(restoreCount);
6488
6489 if (attachInfo != null) {
6490 // Restore the cached Canvas for our siblings
6491 attachInfo.mCanvas = canvas;
6492 }
Romain Guy8506ab42009-06-11 17:35:47 -07006493
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07006494 return bitmap;
6495 }
6496
6497 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 * Indicates whether this View is currently in edit mode. A View is usually
6499 * in edit mode when displayed within a developer tool. For instance, if
6500 * this View is being drawn by a visual user interface builder, this method
6501 * should return true.
6502 *
6503 * Subclasses should check the return value of this method to provide
6504 * different behaviors if their normal behavior might interfere with the
6505 * host environment. For instance: the class spawns a thread in its
6506 * constructor, the drawing code relies on device-specific features, etc.
6507 *
6508 * This method is usually checked in the drawing code of custom widgets.
6509 *
6510 * @return True if this View is in edit mode, false otherwise.
6511 */
6512 public boolean isInEditMode() {
6513 return false;
6514 }
6515
6516 /**
6517 * If the View draws content inside its padding and enables fading edges,
6518 * it needs to support padding offsets. Padding offsets are added to the
6519 * fading edges to extend the length of the fade so that it covers pixels
6520 * drawn inside the padding.
6521 *
6522 * Subclasses of this class should override this method if they need
6523 * to draw content inside the padding.
6524 *
6525 * @return True if padding offset must be applied, false otherwise.
6526 *
6527 * @see #getLeftPaddingOffset()
6528 * @see #getRightPaddingOffset()
6529 * @see #getTopPaddingOffset()
6530 * @see #getBottomPaddingOffset()
6531 *
6532 * @since CURRENT
6533 */
6534 protected boolean isPaddingOffsetRequired() {
6535 return false;
6536 }
6537
6538 /**
6539 * Amount by which to extend the left fading region. Called only when
6540 * {@link #isPaddingOffsetRequired()} returns true.
6541 *
6542 * @return The left padding offset in pixels.
6543 *
6544 * @see #isPaddingOffsetRequired()
6545 *
6546 * @since CURRENT
6547 */
6548 protected int getLeftPaddingOffset() {
6549 return 0;
6550 }
6551
6552 /**
6553 * Amount by which to extend the right fading region. Called only when
6554 * {@link #isPaddingOffsetRequired()} returns true.
6555 *
6556 * @return The right padding offset in pixels.
6557 *
6558 * @see #isPaddingOffsetRequired()
6559 *
6560 * @since CURRENT
6561 */
6562 protected int getRightPaddingOffset() {
6563 return 0;
6564 }
6565
6566 /**
6567 * Amount by which to extend the top fading region. Called only when
6568 * {@link #isPaddingOffsetRequired()} returns true.
6569 *
6570 * @return The top padding offset in pixels.
6571 *
6572 * @see #isPaddingOffsetRequired()
6573 *
6574 * @since CURRENT
6575 */
6576 protected int getTopPaddingOffset() {
6577 return 0;
6578 }
6579
6580 /**
6581 * Amount by which to extend the bottom fading region. Called only when
6582 * {@link #isPaddingOffsetRequired()} returns true.
6583 *
6584 * @return The bottom padding offset in pixels.
6585 *
6586 * @see #isPaddingOffsetRequired()
6587 *
6588 * @since CURRENT
6589 */
6590 protected int getBottomPaddingOffset() {
6591 return 0;
6592 }
6593
6594 /**
6595 * Manually render this view (and all of its children) to the given Canvas.
6596 * The view must have already done a full layout before this function is
6597 * called. When implementing a view, do not override this method; instead,
6598 * you should implement {@link #onDraw}.
6599 *
6600 * @param canvas The Canvas to which the View is rendered.
6601 */
6602 public void draw(Canvas canvas) {
6603 if (ViewDebug.TRACE_HIERARCHY) {
6604 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
6605 }
6606
Romain Guy5bcdff42009-05-14 21:27:18 -07006607 final int privateFlags = mPrivateFlags;
6608 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
6609 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
6610 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
Romain Guy24443ea2009-05-11 11:56:30 -07006611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 /*
6613 * Draw traversal performs several drawing steps which must be executed
6614 * in the appropriate order:
6615 *
6616 * 1. Draw the background
6617 * 2. If necessary, save the canvas' layers to prepare for fading
6618 * 3. Draw view's content
6619 * 4. Draw children
6620 * 5. If necessary, draw the fading edges and restore layers
6621 * 6. Draw decorations (scrollbars for instance)
6622 */
6623
6624 // Step 1, draw the background, if needed
6625 int saveCount;
6626
Romain Guy24443ea2009-05-11 11:56:30 -07006627 if (!dirtyOpaque) {
6628 final Drawable background = mBGDrawable;
6629 if (background != null) {
6630 final int scrollX = mScrollX;
6631 final int scrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632
Romain Guy24443ea2009-05-11 11:56:30 -07006633 if (mBackgroundSizeChanged) {
6634 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
6635 mBackgroundSizeChanged = false;
6636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637
Romain Guy24443ea2009-05-11 11:56:30 -07006638 if ((scrollX | scrollY) == 0) {
6639 background.draw(canvas);
6640 } else {
6641 canvas.translate(scrollX, scrollY);
6642 background.draw(canvas);
6643 canvas.translate(-scrollX, -scrollY);
6644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 }
6646 }
6647
6648 // skip step 2 & 5 if possible (common case)
6649 final int viewFlags = mViewFlags;
6650 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
6651 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
6652 if (!verticalEdges && !horizontalEdges) {
6653 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07006654 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655
6656 // Step 4, draw the children
6657 dispatchDraw(canvas);
6658
6659 // Step 6, draw decorations (scrollbars)
6660 onDrawScrollBars(canvas);
6661
6662 // we're done...
6663 return;
6664 }
6665
6666 /*
6667 * Here we do the full fledged routine...
6668 * (this is an uncommon case where speed matters less,
6669 * this is why we repeat some of the tests that have been
6670 * done above)
6671 */
6672
6673 boolean drawTop = false;
6674 boolean drawBottom = false;
6675 boolean drawLeft = false;
6676 boolean drawRight = false;
6677
6678 float topFadeStrength = 0.0f;
6679 float bottomFadeStrength = 0.0f;
6680 float leftFadeStrength = 0.0f;
6681 float rightFadeStrength = 0.0f;
6682
6683 // Step 2, save the canvas' layers
6684 int paddingLeft = mPaddingLeft;
6685 int paddingTop = mPaddingTop;
6686
6687 final boolean offsetRequired = isPaddingOffsetRequired();
6688 if (offsetRequired) {
6689 paddingLeft += getLeftPaddingOffset();
6690 paddingTop += getTopPaddingOffset();
6691 }
6692
6693 int left = mScrollX + paddingLeft;
6694 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
6695 int top = mScrollY + paddingTop;
6696 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
6697
6698 if (offsetRequired) {
6699 right += getRightPaddingOffset();
6700 bottom += getBottomPaddingOffset();
6701 }
6702
6703 final ScrollabilityCache scrollabilityCache = mScrollCache;
6704 int length = scrollabilityCache.fadingEdgeLength;
6705
6706 // clip the fade length if top and bottom fades overlap
6707 // overlapping fades produce odd-looking artifacts
6708 if (verticalEdges && (top + length > bottom - length)) {
6709 length = (bottom - top) / 2;
6710 }
6711
6712 // also clip horizontal fades if necessary
6713 if (horizontalEdges && (left + length > right - length)) {
6714 length = (right - left) / 2;
6715 }
6716
6717 if (verticalEdges) {
6718 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
6719 drawTop = topFadeStrength >= 0.0f;
6720 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
6721 drawBottom = bottomFadeStrength >= 0.0f;
6722 }
6723
6724 if (horizontalEdges) {
6725 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
6726 drawLeft = leftFadeStrength >= 0.0f;
6727 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
6728 drawRight = rightFadeStrength >= 0.0f;
6729 }
6730
6731 saveCount = canvas.getSaveCount();
6732
6733 int solidColor = getSolidColor();
6734 if (solidColor == 0) {
6735 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
6736
6737 if (drawTop) {
6738 canvas.saveLayer(left, top, right, top + length, null, flags);
6739 }
6740
6741 if (drawBottom) {
6742 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
6743 }
6744
6745 if (drawLeft) {
6746 canvas.saveLayer(left, top, left + length, bottom, null, flags);
6747 }
6748
6749 if (drawRight) {
6750 canvas.saveLayer(right - length, top, right, bottom, null, flags);
6751 }
6752 } else {
6753 scrollabilityCache.setFadeColor(solidColor);
6754 }
6755
6756 // Step 3, draw the content
Romain Guy24443ea2009-05-11 11:56:30 -07006757 if (!dirtyOpaque) onDraw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758
6759 // Step 4, draw the children
6760 dispatchDraw(canvas);
6761
6762 // Step 5, draw the fade effect and restore layers
6763 final Paint p = scrollabilityCache.paint;
6764 final Matrix matrix = scrollabilityCache.matrix;
6765 final Shader fade = scrollabilityCache.shader;
6766 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
6767
6768 if (drawTop) {
6769 matrix.setScale(1, fadeHeight * topFadeStrength);
6770 matrix.postTranslate(left, top);
6771 fade.setLocalMatrix(matrix);
6772 canvas.drawRect(left, top, right, top + length, p);
6773 }
6774
6775 if (drawBottom) {
6776 matrix.setScale(1, fadeHeight * bottomFadeStrength);
6777 matrix.postRotate(180);
6778 matrix.postTranslate(left, bottom);
6779 fade.setLocalMatrix(matrix);
6780 canvas.drawRect(left, bottom - length, right, bottom, p);
6781 }
6782
6783 if (drawLeft) {
6784 matrix.setScale(1, fadeHeight * leftFadeStrength);
6785 matrix.postRotate(-90);
6786 matrix.postTranslate(left, top);
6787 fade.setLocalMatrix(matrix);
6788 canvas.drawRect(left, top, left + length, bottom, p);
6789 }
6790
6791 if (drawRight) {
6792 matrix.setScale(1, fadeHeight * rightFadeStrength);
6793 matrix.postRotate(90);
6794 matrix.postTranslate(right, top);
6795 fade.setLocalMatrix(matrix);
6796 canvas.drawRect(right - length, top, right, bottom, p);
6797 }
6798
6799 canvas.restoreToCount(saveCount);
6800
6801 // Step 6, draw decorations (scrollbars)
6802 onDrawScrollBars(canvas);
6803 }
6804
6805 /**
6806 * Override this if your view is known to always be drawn on top of a solid color background,
6807 * and needs to draw fading edges. Returning a non-zero color enables the view system to
6808 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
6809 * should be set to 0xFF.
6810 *
6811 * @see #setVerticalFadingEdgeEnabled
6812 * @see #setHorizontalFadingEdgeEnabled
6813 *
6814 * @return The known solid color background for this view, or 0 if the color may vary
6815 */
6816 public int getSolidColor() {
6817 return 0;
6818 }
6819
6820 /**
6821 * Build a human readable string representation of the specified view flags.
6822 *
6823 * @param flags the view flags to convert to a string
6824 * @return a String representing the supplied flags
6825 */
6826 private static String printFlags(int flags) {
6827 String output = "";
6828 int numFlags = 0;
6829 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
6830 output += "TAKES_FOCUS";
6831 numFlags++;
6832 }
6833
6834 switch (flags & VISIBILITY_MASK) {
6835 case INVISIBLE:
6836 if (numFlags > 0) {
6837 output += " ";
6838 }
6839 output += "INVISIBLE";
6840 // USELESS HERE numFlags++;
6841 break;
6842 case GONE:
6843 if (numFlags > 0) {
6844 output += " ";
6845 }
6846 output += "GONE";
6847 // USELESS HERE numFlags++;
6848 break;
6849 default:
6850 break;
6851 }
6852 return output;
6853 }
6854
6855 /**
6856 * Build a human readable string representation of the specified private
6857 * view flags.
6858 *
6859 * @param privateFlags the private view flags to convert to a string
6860 * @return a String representing the supplied flags
6861 */
6862 private static String printPrivateFlags(int privateFlags) {
6863 String output = "";
6864 int numFlags = 0;
6865
6866 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
6867 output += "WANTS_FOCUS";
6868 numFlags++;
6869 }
6870
6871 if ((privateFlags & FOCUSED) == FOCUSED) {
6872 if (numFlags > 0) {
6873 output += " ";
6874 }
6875 output += "FOCUSED";
6876 numFlags++;
6877 }
6878
6879 if ((privateFlags & SELECTED) == SELECTED) {
6880 if (numFlags > 0) {
6881 output += " ";
6882 }
6883 output += "SELECTED";
6884 numFlags++;
6885 }
6886
6887 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
6888 if (numFlags > 0) {
6889 output += " ";
6890 }
6891 output += "IS_ROOT_NAMESPACE";
6892 numFlags++;
6893 }
6894
6895 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
6896 if (numFlags > 0) {
6897 output += " ";
6898 }
6899 output += "HAS_BOUNDS";
6900 numFlags++;
6901 }
6902
6903 if ((privateFlags & DRAWN) == DRAWN) {
6904 if (numFlags > 0) {
6905 output += " ";
6906 }
6907 output += "DRAWN";
6908 // USELESS HERE numFlags++;
6909 }
6910 return output;
6911 }
6912
6913 /**
6914 * <p>Indicates whether or not this view's layout will be requested during
6915 * the next hierarchy layout pass.</p>
6916 *
6917 * @return true if the layout will be forced during next layout pass
6918 */
6919 public boolean isLayoutRequested() {
6920 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
6921 }
6922
6923 /**
6924 * Assign a size and position to a view and all of its
6925 * descendants
6926 *
6927 * <p>This is the second phase of the layout mechanism.
6928 * (The first is measuring). In this phase, each parent calls
6929 * layout on all of its children to position them.
6930 * This is typically done using the child measurements
6931 * that were stored in the measure pass().
6932 *
6933 * Derived classes with children should override
6934 * onLayout. In that method, they should
6935 * call layout on each of their their children.
6936 *
6937 * @param l Left position, relative to parent
6938 * @param t Top position, relative to parent
6939 * @param r Right position, relative to parent
6940 * @param b Bottom position, relative to parent
6941 */
6942 public final void layout(int l, int t, int r, int b) {
6943 boolean changed = setFrame(l, t, r, b);
6944 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
6945 if (ViewDebug.TRACE_HIERARCHY) {
6946 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
6947 }
6948
6949 onLayout(changed, l, t, r, b);
6950 mPrivateFlags &= ~LAYOUT_REQUIRED;
6951 }
6952 mPrivateFlags &= ~FORCE_LAYOUT;
6953 }
6954
6955 /**
6956 * Called from layout when this view should
6957 * assign a size and position to each of its children.
6958 *
6959 * Derived classes with children should override
6960 * this method and call layout on each of
6961 * their their children.
6962 * @param changed This is a new size or position for this view
6963 * @param left Left position, relative to parent
6964 * @param top Top position, relative to parent
6965 * @param right Right position, relative to parent
6966 * @param bottom Bottom position, relative to parent
6967 */
6968 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
6969 }
6970
6971 /**
6972 * Assign a size and position to this view.
6973 *
6974 * This is called from layout.
6975 *
6976 * @param left Left position, relative to parent
6977 * @param top Top position, relative to parent
6978 * @param right Right position, relative to parent
6979 * @param bottom Bottom position, relative to parent
6980 * @return true if the new size and position are different than the
6981 * previous ones
6982 * {@hide}
6983 */
6984 protected boolean setFrame(int left, int top, int right, int bottom) {
6985 boolean changed = false;
6986
6987 if (DBG) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07006988 Log.d("View", this + " View.setFrame(" + left + "," + top + ","
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006989 + right + "," + bottom + ")");
6990 }
6991
6992 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
6993 changed = true;
6994
6995 // Remember our drawn bit
6996 int drawn = mPrivateFlags & DRAWN;
6997
6998 // Invalidate our old position
6999 invalidate();
7000
7001
7002 int oldWidth = mRight - mLeft;
7003 int oldHeight = mBottom - mTop;
7004
7005 mLeft = left;
7006 mTop = top;
7007 mRight = right;
7008 mBottom = bottom;
7009
7010 mPrivateFlags |= HAS_BOUNDS;
7011
7012 int newWidth = right - left;
7013 int newHeight = bottom - top;
7014
7015 if (newWidth != oldWidth || newHeight != oldHeight) {
7016 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
7017 }
7018
7019 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
7020 // If we are visible, force the DRAWN bit to on so that
7021 // this invalidate will go through (at least to our parent).
7022 // This is because someone may have invalidated this view
7023 // before this call to setFrame came in, therby clearing
7024 // the DRAWN bit.
7025 mPrivateFlags |= DRAWN;
7026 invalidate();
7027 }
7028
7029 // Reset drawn bit to original value (invalidate turns it off)
7030 mPrivateFlags |= drawn;
7031
7032 mBackgroundSizeChanged = true;
7033 }
7034 return changed;
7035 }
7036
7037 /**
7038 * Finalize inflating a view from XML. This is called as the last phase
7039 * of inflation, after all child views have been added.
7040 *
7041 * <p>Even if the subclass overrides onFinishInflate, they should always be
7042 * sure to call the super method, so that we get called.
7043 */
7044 protected void onFinishInflate() {
7045 }
7046
7047 /**
7048 * Returns the resources associated with this view.
7049 *
7050 * @return Resources object.
7051 */
7052 public Resources getResources() {
7053 return mResources;
7054 }
7055
7056 /**
7057 * Invalidates the specified Drawable.
7058 *
7059 * @param drawable the drawable to invalidate
7060 */
7061 public void invalidateDrawable(Drawable drawable) {
7062 if (verifyDrawable(drawable)) {
7063 final Rect dirty = drawable.getBounds();
7064 final int scrollX = mScrollX;
7065 final int scrollY = mScrollY;
7066
7067 invalidate(dirty.left + scrollX, dirty.top + scrollY,
7068 dirty.right + scrollX, dirty.bottom + scrollY);
7069 }
7070 }
7071
7072 /**
7073 * Schedules an action on a drawable to occur at a specified time.
7074 *
7075 * @param who the recipient of the action
7076 * @param what the action to run on the drawable
7077 * @param when the time at which the action must occur. Uses the
7078 * {@link SystemClock#uptimeMillis} timebase.
7079 */
7080 public void scheduleDrawable(Drawable who, Runnable what, long when) {
7081 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
7082 mAttachInfo.mHandler.postAtTime(what, who, when);
7083 }
7084 }
7085
7086 /**
7087 * Cancels a scheduled action on a drawable.
7088 *
7089 * @param who the recipient of the action
7090 * @param what the action to cancel
7091 */
7092 public void unscheduleDrawable(Drawable who, Runnable what) {
7093 if (verifyDrawable(who) && what != null && mAttachInfo != null) {
7094 mAttachInfo.mHandler.removeCallbacks(what, who);
7095 }
7096 }
7097
7098 /**
7099 * Unschedule any events associated with the given Drawable. This can be
7100 * used when selecting a new Drawable into a view, so that the previous
7101 * one is completely unscheduled.
7102 *
7103 * @param who The Drawable to unschedule.
7104 *
7105 * @see #drawableStateChanged
7106 */
7107 public void unscheduleDrawable(Drawable who) {
7108 if (mAttachInfo != null) {
7109 mAttachInfo.mHandler.removeCallbacksAndMessages(who);
7110 }
7111 }
7112
7113 /**
7114 * If your view subclass is displaying its own Drawable objects, it should
7115 * override this function and return true for any Drawable it is
7116 * displaying. This allows animations for those drawables to be
7117 * scheduled.
7118 *
7119 * <p>Be sure to call through to the super class when overriding this
7120 * function.
7121 *
7122 * @param who The Drawable to verify. Return true if it is one you are
7123 * displaying, else return the result of calling through to the
7124 * super class.
7125 *
7126 * @return boolean If true than the Drawable is being displayed in the
7127 * view; else false and it is not allowed to animate.
7128 *
7129 * @see #unscheduleDrawable
7130 * @see #drawableStateChanged
7131 */
7132 protected boolean verifyDrawable(Drawable who) {
7133 return who == mBGDrawable;
7134 }
7135
7136 /**
7137 * This function is called whenever the state of the view changes in such
7138 * a way that it impacts the state of drawables being shown.
7139 *
7140 * <p>Be sure to call through to the superclass when overriding this
7141 * function.
7142 *
7143 * @see Drawable#setState
7144 */
7145 protected void drawableStateChanged() {
7146 Drawable d = mBGDrawable;
7147 if (d != null && d.isStateful()) {
7148 d.setState(getDrawableState());
7149 }
7150 }
7151
7152 /**
7153 * Call this to force a view to update its drawable state. This will cause
7154 * drawableStateChanged to be called on this view. Views that are interested
7155 * in the new state should call getDrawableState.
7156 *
7157 * @see #drawableStateChanged
7158 * @see #getDrawableState
7159 */
7160 public void refreshDrawableState() {
7161 mPrivateFlags |= DRAWABLE_STATE_DIRTY;
7162 drawableStateChanged();
7163
7164 ViewParent parent = mParent;
7165 if (parent != null) {
7166 parent.childDrawableStateChanged(this);
7167 }
7168 }
7169
7170 /**
7171 * Return an array of resource IDs of the drawable states representing the
7172 * current state of the view.
7173 *
7174 * @return The current drawable state
7175 *
7176 * @see Drawable#setState
7177 * @see #drawableStateChanged
7178 * @see #onCreateDrawableState
7179 */
7180 public final int[] getDrawableState() {
7181 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
7182 return mDrawableState;
7183 } else {
7184 mDrawableState = onCreateDrawableState(0);
7185 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
7186 return mDrawableState;
7187 }
7188 }
7189
7190 /**
7191 * Generate the new {@link android.graphics.drawable.Drawable} state for
7192 * this view. This is called by the view
7193 * system when the cached Drawable state is determined to be invalid. To
7194 * retrieve the current state, you should use {@link #getDrawableState}.
7195 *
7196 * @param extraSpace if non-zero, this is the number of extra entries you
7197 * would like in the returned array in which you can place your own
7198 * states.
7199 *
7200 * @return Returns an array holding the current {@link Drawable} state of
7201 * the view.
7202 *
7203 * @see #mergeDrawableStates
7204 */
7205 protected int[] onCreateDrawableState(int extraSpace) {
7206 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
7207 mParent instanceof View) {
7208 return ((View) mParent).onCreateDrawableState(extraSpace);
7209 }
7210
7211 int[] drawableState;
7212
7213 int privateFlags = mPrivateFlags;
7214
7215 int viewStateIndex = (((privateFlags & PRESSED) != 0) ? 1 : 0);
7216
7217 viewStateIndex = (viewStateIndex << 1)
7218 + (((mViewFlags & ENABLED_MASK) == ENABLED) ? 1 : 0);
7219
7220 viewStateIndex = (viewStateIndex << 1) + (isFocused() ? 1 : 0);
7221
7222 viewStateIndex = (viewStateIndex << 1)
7223 + (((privateFlags & SELECTED) != 0) ? 1 : 0);
7224
7225 final boolean hasWindowFocus = hasWindowFocus();
7226 viewStateIndex = (viewStateIndex << 1) + (hasWindowFocus ? 1 : 0);
7227
7228 drawableState = VIEW_STATE_SETS[viewStateIndex];
7229
7230 //noinspection ConstantIfStatement
7231 if (false) {
7232 Log.i("View", "drawableStateIndex=" + viewStateIndex);
7233 Log.i("View", toString()
7234 + " pressed=" + ((privateFlags & PRESSED) != 0)
7235 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
7236 + " fo=" + hasFocus()
7237 + " sl=" + ((privateFlags & SELECTED) != 0)
7238 + " wf=" + hasWindowFocus
7239 + ": " + Arrays.toString(drawableState));
7240 }
7241
7242 if (extraSpace == 0) {
7243 return drawableState;
7244 }
7245
7246 final int[] fullState;
7247 if (drawableState != null) {
7248 fullState = new int[drawableState.length + extraSpace];
7249 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
7250 } else {
7251 fullState = new int[extraSpace];
7252 }
7253
7254 return fullState;
7255 }
7256
7257 /**
7258 * Merge your own state values in <var>additionalState</var> into the base
7259 * state values <var>baseState</var> that were returned by
7260 * {@link #onCreateDrawableState}.
7261 *
7262 * @param baseState The base state values returned by
7263 * {@link #onCreateDrawableState}, which will be modified to also hold your
7264 * own additional state values.
7265 *
7266 * @param additionalState The additional state values you would like
7267 * added to <var>baseState</var>; this array is not modified.
7268 *
7269 * @return As a convenience, the <var>baseState</var> array you originally
7270 * passed into the function is returned.
7271 *
7272 * @see #onCreateDrawableState
7273 */
7274 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
7275 final int N = baseState.length;
7276 int i = N - 1;
7277 while (i >= 0 && baseState[i] == 0) {
7278 i--;
7279 }
7280 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
7281 return baseState;
7282 }
7283
7284 /**
7285 * Sets the background color for this view.
7286 * @param color the color of the background
7287 */
7288 public void setBackgroundColor(int color) {
7289 setBackgroundDrawable(new ColorDrawable(color));
7290 }
7291
7292 /**
7293 * Set the background to a given resource. The resource should refer to
Wink Saville7cd88e12009-08-04 14:45:10 -07007294 * a Drawable object or 0 to remove the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 * @param resid The identifier of the resource.
7296 * @attr ref android.R.styleable#View_background
7297 */
7298 public void setBackgroundResource(int resid) {
7299 if (resid != 0 && resid == mBackgroundResource) {
7300 return;
7301 }
7302
7303 Drawable d= null;
7304 if (resid != 0) {
7305 d = mResources.getDrawable(resid);
7306 }
7307 setBackgroundDrawable(d);
7308
7309 mBackgroundResource = resid;
7310 }
7311
7312 /**
7313 * Set the background to a given Drawable, or remove the background. If the
7314 * background has padding, this View's padding is set to the background's
7315 * padding. However, when a background is removed, this View's padding isn't
7316 * touched. If setting the padding is desired, please use
7317 * {@link #setPadding(int, int, int, int)}.
7318 *
7319 * @param d The Drawable to use as the background, or null to remove the
7320 * background
7321 */
7322 public void setBackgroundDrawable(Drawable d) {
7323 boolean requestLayout = false;
7324
7325 mBackgroundResource = 0;
7326
7327 /*
7328 * Regardless of whether we're setting a new background or not, we want
7329 * to clear the previous drawable.
7330 */
7331 if (mBGDrawable != null) {
7332 mBGDrawable.setCallback(null);
7333 unscheduleDrawable(mBGDrawable);
7334 }
7335
7336 if (d != null) {
7337 Rect padding = sThreadLocal.get();
7338 if (padding == null) {
7339 padding = new Rect();
7340 sThreadLocal.set(padding);
7341 }
7342 if (d.getPadding(padding)) {
7343 setPadding(padding.left, padding.top, padding.right, padding.bottom);
7344 }
7345
7346 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
7347 // if it has a different minimum size, we should layout again
7348 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
7349 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
7350 requestLayout = true;
7351 }
7352
7353 d.setCallback(this);
7354 if (d.isStateful()) {
7355 d.setState(getDrawableState());
7356 }
7357 d.setVisible(getVisibility() == VISIBLE, false);
7358 mBGDrawable = d;
7359
7360 if ((mPrivateFlags & SKIP_DRAW) != 0) {
7361 mPrivateFlags &= ~SKIP_DRAW;
7362 mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
7363 requestLayout = true;
7364 }
7365 } else {
7366 /* Remove the background */
7367 mBGDrawable = null;
7368
7369 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
7370 /*
7371 * This view ONLY drew the background before and we're removing
7372 * the background, so now it won't draw anything
7373 * (hence we SKIP_DRAW)
7374 */
7375 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
7376 mPrivateFlags |= SKIP_DRAW;
7377 }
7378
7379 /*
7380 * When the background is set, we try to apply its padding to this
7381 * View. When the background is removed, we don't touch this View's
7382 * padding. This is noted in the Javadocs. Hence, we don't need to
7383 * requestLayout(), the invalidate() below is sufficient.
7384 */
7385
7386 // The old background's minimum size could have affected this
7387 // View's layout, so let's requestLayout
7388 requestLayout = true;
7389 }
7390
Romain Guy8f1344f52009-05-15 16:03:59 -07007391 computeOpaqueFlags();
7392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007393 if (requestLayout) {
7394 requestLayout();
7395 }
7396
7397 mBackgroundSizeChanged = true;
7398 invalidate();
7399 }
7400
7401 /**
7402 * Gets the background drawable
7403 * @return The drawable used as the background for this view, if any.
7404 */
7405 public Drawable getBackground() {
7406 return mBGDrawable;
7407 }
7408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007409 /**
7410 * Sets the padding. The view may add on the space required to display
7411 * the scrollbars, depending on the style and visibility of the scrollbars.
7412 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
7413 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
7414 * from the values set in this call.
7415 *
7416 * @attr ref android.R.styleable#View_padding
7417 * @attr ref android.R.styleable#View_paddingBottom
7418 * @attr ref android.R.styleable#View_paddingLeft
7419 * @attr ref android.R.styleable#View_paddingRight
7420 * @attr ref android.R.styleable#View_paddingTop
7421 * @param left the left padding in pixels
7422 * @param top the top padding in pixels
7423 * @param right the right padding in pixels
7424 * @param bottom the bottom padding in pixels
7425 */
7426 public void setPadding(int left, int top, int right, int bottom) {
7427 boolean changed = false;
7428
7429 mUserPaddingRight = right;
7430 mUserPaddingBottom = bottom;
7431
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007432 final int viewFlags = mViewFlags;
Romain Guy8506ab42009-06-11 17:35:47 -07007433
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007434 // Common case is there are no scroll bars.
7435 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
7436 // TODO: Deal with RTL languages to adjust left padding instead of right.
7437 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
7438 right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
7439 ? 0 : getVerticalScrollbarWidth();
7440 }
7441 if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
7442 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
7443 ? 0 : getHorizontalScrollbarHeight();
7444 }
7445 }
Romain Guy8506ab42009-06-11 17:35:47 -07007446
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007447 if (mPaddingLeft != left) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007448 changed = true;
7449 mPaddingLeft = left;
7450 }
7451 if (mPaddingTop != top) {
7452 changed = true;
7453 mPaddingTop = top;
7454 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007455 if (mPaddingRight != right) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007456 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007457 mPaddingRight = right;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007458 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007459 if (mPaddingBottom != bottom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007460 changed = true;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07007461 mPaddingBottom = bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007462 }
7463
7464 if (changed) {
7465 requestLayout();
7466 }
7467 }
7468
7469 /**
7470 * Returns the top padding of this view.
7471 *
7472 * @return the top padding in pixels
7473 */
7474 public int getPaddingTop() {
7475 return mPaddingTop;
7476 }
7477
7478 /**
7479 * Returns the bottom padding of this view. If there are inset and enabled
7480 * scrollbars, this value may include the space required to display the
7481 * scrollbars as well.
7482 *
7483 * @return the bottom padding in pixels
7484 */
7485 public int getPaddingBottom() {
7486 return mPaddingBottom;
7487 }
7488
7489 /**
7490 * Returns the left padding of this view. If there are inset and enabled
7491 * scrollbars, this value may include the space required to display the
7492 * scrollbars as well.
7493 *
7494 * @return the left padding in pixels
7495 */
7496 public int getPaddingLeft() {
7497 return mPaddingLeft;
7498 }
7499
7500 /**
7501 * Returns the right padding of this view. If there are inset and enabled
7502 * scrollbars, this value may include the space required to display the
7503 * scrollbars as well.
7504 *
7505 * @return the right padding in pixels
7506 */
7507 public int getPaddingRight() {
7508 return mPaddingRight;
7509 }
7510
7511 /**
7512 * Changes the selection state of this view. A view can be selected or not.
7513 * Note that selection is not the same as focus. Views are typically
7514 * selected in the context of an AdapterView like ListView or GridView;
7515 * the selected view is the view that is highlighted.
7516 *
7517 * @param selected true if the view must be selected, false otherwise
7518 */
7519 public void setSelected(boolean selected) {
7520 if (((mPrivateFlags & SELECTED) != 0) != selected) {
7521 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
Romain Guya2431d02009-04-30 16:30:00 -07007522 if (!selected) resetPressedState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 invalidate();
7524 refreshDrawableState();
7525 dispatchSetSelected(selected);
7526 }
7527 }
7528
7529 /**
7530 * Dispatch setSelected to all of this View's children.
7531 *
7532 * @see #setSelected(boolean)
7533 *
7534 * @param selected The new selected state
7535 */
7536 protected void dispatchSetSelected(boolean selected) {
7537 }
7538
7539 /**
7540 * Indicates the selection state of this view.
7541 *
7542 * @return true if the view is selected, false otherwise
7543 */
7544 @ViewDebug.ExportedProperty
7545 public boolean isSelected() {
7546 return (mPrivateFlags & SELECTED) != 0;
7547 }
7548
7549 /**
7550 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
7551 * observer can be used to get notifications when global events, like
7552 * layout, happen.
7553 *
7554 * The returned ViewTreeObserver observer is not guaranteed to remain
7555 * valid for the lifetime of this View. If the caller of this method keeps
7556 * a long-lived reference to ViewTreeObserver, it should always check for
7557 * the return value of {@link ViewTreeObserver#isAlive()}.
7558 *
7559 * @return The ViewTreeObserver for this view's hierarchy.
7560 */
7561 public ViewTreeObserver getViewTreeObserver() {
7562 if (mAttachInfo != null) {
7563 return mAttachInfo.mTreeObserver;
7564 }
7565 if (mFloatingTreeObserver == null) {
7566 mFloatingTreeObserver = new ViewTreeObserver();
7567 }
7568 return mFloatingTreeObserver;
7569 }
7570
7571 /**
7572 * <p>Finds the topmost view in the current view hierarchy.</p>
7573 *
7574 * @return the topmost view containing this view
7575 */
7576 public View getRootView() {
7577 if (mAttachInfo != null) {
7578 final View v = mAttachInfo.mRootView;
7579 if (v != null) {
7580 return v;
7581 }
7582 }
Romain Guy8506ab42009-06-11 17:35:47 -07007583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584 View parent = this;
7585
7586 while (parent.mParent != null && parent.mParent instanceof View) {
7587 parent = (View) parent.mParent;
7588 }
7589
7590 return parent;
7591 }
7592
7593 /**
7594 * <p>Computes the coordinates of this view on the screen. The argument
7595 * must be an array of two integers. After the method returns, the array
7596 * contains the x and y location in that order.</p>
7597 *
7598 * @param location an array of two integers in which to hold the coordinates
7599 */
7600 public void getLocationOnScreen(int[] location) {
7601 getLocationInWindow(location);
7602
7603 final AttachInfo info = mAttachInfo;
Romain Guy779398e2009-06-16 13:17:50 -07007604 if (info != null) {
7605 location[0] += info.mWindowLeft;
7606 location[1] += info.mWindowTop;
7607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 }
7609
7610 /**
7611 * <p>Computes the coordinates of this view in its window. The argument
7612 * must be an array of two integers. After the method returns, the array
7613 * contains the x and y location in that order.</p>
7614 *
7615 * @param location an array of two integers in which to hold the coordinates
7616 */
7617 public void getLocationInWindow(int[] location) {
7618 if (location == null || location.length < 2) {
7619 throw new IllegalArgumentException("location must be an array of "
7620 + "two integers");
7621 }
7622
7623 location[0] = mLeft;
7624 location[1] = mTop;
7625
7626 ViewParent viewParent = mParent;
7627 while (viewParent instanceof View) {
7628 final View view = (View)viewParent;
7629 location[0] += view.mLeft - view.mScrollX;
7630 location[1] += view.mTop - view.mScrollY;
7631 viewParent = view.mParent;
7632 }
Romain Guy8506ab42009-06-11 17:35:47 -07007633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007634 if (viewParent instanceof ViewRoot) {
7635 // *cough*
7636 final ViewRoot vr = (ViewRoot)viewParent;
7637 location[1] -= vr.mCurScrollY;
7638 }
7639 }
7640
7641 /**
7642 * {@hide}
7643 * @param id the id of the view to be found
7644 * @return the view of the specified id, null if cannot be found
7645 */
7646 protected View findViewTraversal(int id) {
7647 if (id == mID) {
7648 return this;
7649 }
7650 return null;
7651 }
7652
7653 /**
7654 * {@hide}
7655 * @param tag the tag of the view to be found
7656 * @return the view of specified tag, null if cannot be found
7657 */
7658 protected View findViewWithTagTraversal(Object tag) {
7659 if (tag != null && tag.equals(mTag)) {
7660 return this;
7661 }
7662 return null;
7663 }
7664
7665 /**
7666 * Look for a child view with the given id. If this view has the given
7667 * id, return this view.
7668 *
7669 * @param id The id to search for.
7670 * @return The view that has the given id in the hierarchy or null
7671 */
7672 public final View findViewById(int id) {
7673 if (id < 0) {
7674 return null;
7675 }
7676 return findViewTraversal(id);
7677 }
7678
7679 /**
7680 * Look for a child view with the given tag. If this view has the given
7681 * tag, return this view.
7682 *
7683 * @param tag The tag to search for, using "tag.equals(getTag())".
7684 * @return The View that has the given tag in the hierarchy or null
7685 */
7686 public final View findViewWithTag(Object tag) {
7687 if (tag == null) {
7688 return null;
7689 }
7690 return findViewWithTagTraversal(tag);
7691 }
7692
7693 /**
7694 * Sets the identifier for this view. The identifier does not have to be
7695 * unique in this view's hierarchy. The identifier should be a positive
7696 * number.
7697 *
7698 * @see #NO_ID
7699 * @see #getId
7700 * @see #findViewById
7701 *
7702 * @param id a number used to identify the view
7703 *
7704 * @attr ref android.R.styleable#View_id
7705 */
7706 public void setId(int id) {
7707 mID = id;
7708 }
7709
7710 /**
7711 * {@hide}
7712 *
7713 * @param isRoot true if the view belongs to the root namespace, false
7714 * otherwise
7715 */
7716 public void setIsRootNamespace(boolean isRoot) {
7717 if (isRoot) {
7718 mPrivateFlags |= IS_ROOT_NAMESPACE;
7719 } else {
7720 mPrivateFlags &= ~IS_ROOT_NAMESPACE;
7721 }
7722 }
7723
7724 /**
7725 * {@hide}
7726 *
7727 * @return true if the view belongs to the root namespace, false otherwise
7728 */
7729 public boolean isRootNamespace() {
7730 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
7731 }
7732
7733 /**
7734 * Returns this view's identifier.
7735 *
7736 * @return a positive integer used to identify the view or {@link #NO_ID}
7737 * if the view has no ID
7738 *
7739 * @see #setId
7740 * @see #findViewById
7741 * @attr ref android.R.styleable#View_id
7742 */
7743 @ViewDebug.CapturedViewProperty
7744 public int getId() {
7745 return mID;
7746 }
7747
7748 /**
7749 * Returns this view's tag.
7750 *
7751 * @return the Object stored in this view as a tag
Romain Guyd90a3312009-05-06 14:54:28 -07007752 *
7753 * @see #setTag(Object)
7754 * @see #getTag(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007755 */
7756 @ViewDebug.ExportedProperty
7757 public Object getTag() {
7758 return mTag;
7759 }
7760
7761 /**
7762 * Sets the tag associated with this view. A tag can be used to mark
7763 * a view in its hierarchy and does not have to be unique within the
7764 * hierarchy. Tags can also be used to store data within a view without
7765 * resorting to another data structure.
7766 *
7767 * @param tag an Object to tag the view with
Romain Guyd90a3312009-05-06 14:54:28 -07007768 *
7769 * @see #getTag()
7770 * @see #setTag(int, Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 */
7772 public void setTag(final Object tag) {
7773 mTag = tag;
7774 }
7775
7776 /**
Romain Guyd90a3312009-05-06 14:54:28 -07007777 * Returns the tag associated with this view and the specified key.
7778 *
7779 * @param key The key identifying the tag
7780 *
7781 * @return the Object stored in this view as a tag
7782 *
7783 * @see #setTag(int, Object)
Romain Guy8506ab42009-06-11 17:35:47 -07007784 * @see #getTag()
Romain Guyd90a3312009-05-06 14:54:28 -07007785 */
7786 public Object getTag(int key) {
7787 SparseArray<Object> tags = null;
7788 synchronized (sTagsLock) {
7789 if (sTags != null) {
7790 tags = sTags.get(this);
7791 }
7792 }
7793
7794 if (tags != null) return tags.get(key);
7795 return null;
7796 }
7797
7798 /**
7799 * Sets a tag associated with this view and a key. A tag can be used
7800 * to mark a view in its hierarchy and does not have to be unique within
7801 * the hierarchy. Tags can also be used to store data within a view
7802 * without resorting to another data structure.
7803 *
7804 * The specified key should be an id declared in the resources of the
7805 * application to ensure it is unique. Keys identified as belonging to
7806 * the Android framework or not associated with any package will cause
7807 * an {@link IllegalArgumentException} to be thrown.
7808 *
7809 * @param key The key identifying the tag
7810 * @param tag An Object to tag the view with
7811 *
7812 * @throws IllegalArgumentException If they specified key is not valid
7813 *
7814 * @see #setTag(Object)
7815 * @see #getTag(int)
7816 */
7817 public void setTag(int key, final Object tag) {
7818 // If the package id is 0x00 or 0x01, it's either an undefined package
7819 // or a framework id
7820 if ((key >>> 24) < 2) {
7821 throw new IllegalArgumentException("The key must be an application-specific "
7822 + "resource id.");
7823 }
7824
7825 setTagInternal(this, key, tag);
7826 }
7827
7828 /**
7829 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
7830 * framework id.
7831 *
7832 * @hide
7833 */
7834 public void setTagInternal(int key, Object tag) {
7835 if ((key >>> 24) != 0x1) {
7836 throw new IllegalArgumentException("The key must be a framework-specific "
7837 + "resource id.");
7838 }
7839
Romain Guy8506ab42009-06-11 17:35:47 -07007840 setTagInternal(this, key, tag);
Romain Guyd90a3312009-05-06 14:54:28 -07007841 }
7842
7843 private static void setTagInternal(View view, int key, Object tag) {
7844 SparseArray<Object> tags = null;
7845 synchronized (sTagsLock) {
7846 if (sTags == null) {
7847 sTags = new WeakHashMap<View, SparseArray<Object>>();
7848 } else {
7849 tags = sTags.get(view);
7850 }
7851 }
7852
7853 if (tags == null) {
7854 tags = new SparseArray<Object>(2);
7855 synchronized (sTagsLock) {
7856 sTags.put(view, tags);
7857 }
7858 }
7859
7860 tags.put(key, tag);
7861 }
7862
7863 /**
Romain Guy13922e02009-05-12 17:56:14 -07007864 * @param consistency The type of consistency. See ViewDebug for more information.
7865 *
7866 * @hide
7867 */
7868 protected boolean dispatchConsistencyCheck(int consistency) {
7869 return onConsistencyCheck(consistency);
7870 }
7871
7872 /**
7873 * Method that subclasses should implement to check their consistency. The type of
7874 * consistency check is indicated by the bit field passed as a parameter.
Romain Guy8506ab42009-06-11 17:35:47 -07007875 *
Romain Guy13922e02009-05-12 17:56:14 -07007876 * @param consistency The type of consistency. See ViewDebug for more information.
7877 *
7878 * @throws IllegalStateException if the view is in an inconsistent state.
7879 *
7880 * @hide
7881 */
7882 protected boolean onConsistencyCheck(int consistency) {
7883 boolean result = true;
7884
7885 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
7886 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
7887
7888 if (checkLayout) {
7889 if (getParent() == null) {
7890 result = false;
7891 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
7892 "View " + this + " does not have a parent.");
7893 }
7894
7895 if (mAttachInfo == null) {
7896 result = false;
7897 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
7898 "View " + this + " is not attached to a window.");
7899 }
7900 }
7901
7902 if (checkDrawing) {
7903 // Do not check the DIRTY/DRAWN flags because views can call invalidate()
7904 // from their draw() method
7905
7906 if ((mPrivateFlags & DRAWN) != DRAWN &&
7907 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
7908 result = false;
7909 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
7910 "View " + this + " was invalidated but its drawing cache is valid.");
7911 }
7912 }
7913
7914 return result;
7915 }
7916
7917 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007918 * Prints information about this view in the log output, with the tag
7919 * {@link #VIEW_LOG_TAG}.
7920 *
7921 * @hide
7922 */
7923 public void debug() {
7924 debug(0);
7925 }
7926
7927 /**
7928 * Prints information about this view in the log output, with the tag
7929 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
7930 * indentation defined by the <code>depth</code>.
7931 *
7932 * @param depth the indentation level
7933 *
7934 * @hide
7935 */
7936 protected void debug(int depth) {
7937 String output = debugIndent(depth - 1);
7938
7939 output += "+ " + this;
7940 int id = getId();
7941 if (id != -1) {
7942 output += " (id=" + id + ")";
7943 }
7944 Object tag = getTag();
7945 if (tag != null) {
7946 output += " (tag=" + tag + ")";
7947 }
7948 Log.d(VIEW_LOG_TAG, output);
7949
7950 if ((mPrivateFlags & FOCUSED) != 0) {
7951 output = debugIndent(depth) + " FOCUSED";
7952 Log.d(VIEW_LOG_TAG, output);
7953 }
7954
7955 output = debugIndent(depth);
7956 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
7957 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
7958 + "} ";
7959 Log.d(VIEW_LOG_TAG, output);
7960
7961 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
7962 || mPaddingBottom != 0) {
7963 output = debugIndent(depth);
7964 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
7965 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
7966 Log.d(VIEW_LOG_TAG, output);
7967 }
7968
7969 output = debugIndent(depth);
7970 output += "mMeasureWidth=" + mMeasuredWidth +
7971 " mMeasureHeight=" + mMeasuredHeight;
7972 Log.d(VIEW_LOG_TAG, output);
7973
7974 output = debugIndent(depth);
7975 if (mLayoutParams == null) {
7976 output += "BAD! no layout params";
7977 } else {
7978 output = mLayoutParams.debug(output);
7979 }
7980 Log.d(VIEW_LOG_TAG, output);
7981
7982 output = debugIndent(depth);
7983 output += "flags={";
7984 output += View.printFlags(mViewFlags);
7985 output += "}";
7986 Log.d(VIEW_LOG_TAG, output);
7987
7988 output = debugIndent(depth);
7989 output += "privateFlags={";
7990 output += View.printPrivateFlags(mPrivateFlags);
7991 output += "}";
7992 Log.d(VIEW_LOG_TAG, output);
7993 }
7994
7995 /**
7996 * Creates an string of whitespaces used for indentation.
7997 *
7998 * @param depth the indentation level
7999 * @return a String containing (depth * 2 + 3) * 2 white spaces
8000 *
8001 * @hide
8002 */
8003 protected static String debugIndent(int depth) {
8004 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
8005 for (int i = 0; i < (depth * 2) + 3; i++) {
8006 spaces.append(' ').append(' ');
8007 }
8008 return spaces.toString();
8009 }
8010
8011 /**
8012 * <p>Return the offset of the widget's text baseline from the widget's top
8013 * boundary. If this widget does not support baseline alignment, this
8014 * method returns -1. </p>
8015 *
8016 * @return the offset of the baseline within the widget's bounds or -1
8017 * if baseline alignment is not supported
8018 */
8019 @ViewDebug.ExportedProperty
8020 public int getBaseline() {
8021 return -1;
8022 }
8023
8024 /**
8025 * Call this when something has changed which has invalidated the
8026 * layout of this view. This will schedule a layout pass of the view
8027 * tree.
8028 */
8029 public void requestLayout() {
8030 if (ViewDebug.TRACE_HIERARCHY) {
8031 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
8032 }
8033
8034 mPrivateFlags |= FORCE_LAYOUT;
8035
8036 if (mParent != null && !mParent.isLayoutRequested()) {
8037 mParent.requestLayout();
8038 }
8039 }
8040
8041 /**
8042 * Forces this view to be laid out during the next layout pass.
8043 * This method does not call requestLayout() or forceLayout()
8044 * on the parent.
8045 */
8046 public void forceLayout() {
8047 mPrivateFlags |= FORCE_LAYOUT;
8048 }
8049
8050 /**
8051 * <p>
8052 * This is called to find out how big a view should be. The parent
8053 * supplies constraint information in the width and height parameters.
8054 * </p>
8055 *
8056 * <p>
8057 * The actual mesurement work of a view is performed in
8058 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
8059 * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
8060 * </p>
8061 *
8062 *
8063 * @param widthMeasureSpec Horizontal space requirements as imposed by the
8064 * parent
8065 * @param heightMeasureSpec Vertical space requirements as imposed by the
8066 * parent
8067 *
8068 * @see #onMeasure(int, int)
8069 */
8070 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
8071 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
8072 widthMeasureSpec != mOldWidthMeasureSpec ||
8073 heightMeasureSpec != mOldHeightMeasureSpec) {
8074
8075 // first clears the measured dimension flag
8076 mPrivateFlags &= ~MEASURED_DIMENSION_SET;
8077
8078 if (ViewDebug.TRACE_HIERARCHY) {
8079 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
8080 }
8081
8082 // measure ourselves, this should set the measured dimension flag back
8083 onMeasure(widthMeasureSpec, heightMeasureSpec);
8084
8085 // flag not set, setMeasuredDimension() was not invoked, we raise
8086 // an exception to warn the developer
8087 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
8088 throw new IllegalStateException("onMeasure() did not set the"
8089 + " measured dimension by calling"
8090 + " setMeasuredDimension()");
8091 }
8092
8093 mPrivateFlags |= LAYOUT_REQUIRED;
8094 }
8095
8096 mOldWidthMeasureSpec = widthMeasureSpec;
8097 mOldHeightMeasureSpec = heightMeasureSpec;
8098 }
8099
8100 /**
8101 * <p>
8102 * Measure the view and its content to determine the measured width and the
8103 * measured height. This method is invoked by {@link #measure(int, int)} and
8104 * should be overriden by subclasses to provide accurate and efficient
8105 * measurement of their contents.
8106 * </p>
8107 *
8108 * <p>
8109 * <strong>CONTRACT:</strong> When overriding this method, you
8110 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
8111 * measured width and height of this view. Failure to do so will trigger an
8112 * <code>IllegalStateException</code>, thrown by
8113 * {@link #measure(int, int)}. Calling the superclass'
8114 * {@link #onMeasure(int, int)} is a valid use.
8115 * </p>
8116 *
8117 * <p>
8118 * The base class implementation of measure defaults to the background size,
8119 * unless a larger size is allowed by the MeasureSpec. Subclasses should
8120 * override {@link #onMeasure(int, int)} to provide better measurements of
8121 * their content.
8122 * </p>
8123 *
8124 * <p>
8125 * If this method is overridden, it is the subclass's responsibility to make
8126 * sure the measured height and width are at least the view's minimum height
8127 * and width ({@link #getSuggestedMinimumHeight()} and
8128 * {@link #getSuggestedMinimumWidth()}).
8129 * </p>
8130 *
8131 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
8132 * The requirements are encoded with
8133 * {@link android.view.View.MeasureSpec}.
8134 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
8135 * The requirements are encoded with
8136 * {@link android.view.View.MeasureSpec}.
8137 *
8138 * @see #getMeasuredWidth()
8139 * @see #getMeasuredHeight()
8140 * @see #setMeasuredDimension(int, int)
8141 * @see #getSuggestedMinimumHeight()
8142 * @see #getSuggestedMinimumWidth()
8143 * @see android.view.View.MeasureSpec#getMode(int)
8144 * @see android.view.View.MeasureSpec#getSize(int)
8145 */
8146 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
8147 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
8148 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
8149 }
8150
8151 /**
8152 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
8153 * measured width and measured height. Failing to do so will trigger an
8154 * exception at measurement time.</p>
8155 *
8156 * @param measuredWidth the measured width of this view
8157 * @param measuredHeight the measured height of this view
8158 */
8159 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
8160 mMeasuredWidth = measuredWidth;
8161 mMeasuredHeight = measuredHeight;
8162
8163 mPrivateFlags |= MEASURED_DIMENSION_SET;
8164 }
8165
8166 /**
8167 * Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
8168 * Will take the desired size, unless a different size is imposed by the constraints.
8169 *
8170 * @param size How big the view wants to be
8171 * @param measureSpec Constraints imposed by the parent
8172 * @return The size this view should be.
8173 */
8174 public static int resolveSize(int size, int measureSpec) {
8175 int result = size;
8176 int specMode = MeasureSpec.getMode(measureSpec);
8177 int specSize = MeasureSpec.getSize(measureSpec);
8178 switch (specMode) {
8179 case MeasureSpec.UNSPECIFIED:
8180 result = size;
8181 break;
8182 case MeasureSpec.AT_MOST:
8183 result = Math.min(size, specSize);
8184 break;
8185 case MeasureSpec.EXACTLY:
8186 result = specSize;
8187 break;
8188 }
8189 return result;
8190 }
8191
8192 /**
8193 * Utility to return a default size. Uses the supplied size if the
8194 * MeasureSpec imposed no contraints. Will get larger if allowed
8195 * by the MeasureSpec.
8196 *
8197 * @param size Default size for this view
8198 * @param measureSpec Constraints imposed by the parent
8199 * @return The size this view should be.
8200 */
8201 public static int getDefaultSize(int size, int measureSpec) {
8202 int result = size;
8203 int specMode = MeasureSpec.getMode(measureSpec);
8204 int specSize = MeasureSpec.getSize(measureSpec);
8205
8206 switch (specMode) {
8207 case MeasureSpec.UNSPECIFIED:
8208 result = size;
8209 break;
8210 case MeasureSpec.AT_MOST:
8211 case MeasureSpec.EXACTLY:
8212 result = specSize;
8213 break;
8214 }
8215 return result;
8216 }
8217
8218 /**
8219 * Returns the suggested minimum height that the view should use. This
8220 * returns the maximum of the view's minimum height
8221 * and the background's minimum height
8222 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
8223 * <p>
8224 * When being used in {@link #onMeasure(int, int)}, the caller should still
8225 * ensure the returned height is within the requirements of the parent.
8226 *
8227 * @return The suggested minimum height of the view.
8228 */
8229 protected int getSuggestedMinimumHeight() {
8230 int suggestedMinHeight = mMinHeight;
8231
8232 if (mBGDrawable != null) {
8233 final int bgMinHeight = mBGDrawable.getMinimumHeight();
8234 if (suggestedMinHeight < bgMinHeight) {
8235 suggestedMinHeight = bgMinHeight;
8236 }
8237 }
8238
8239 return suggestedMinHeight;
8240 }
8241
8242 /**
8243 * Returns the suggested minimum width that the view should use. This
8244 * returns the maximum of the view's minimum width)
8245 * and the background's minimum width
8246 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
8247 * <p>
8248 * When being used in {@link #onMeasure(int, int)}, the caller should still
8249 * ensure the returned width is within the requirements of the parent.
8250 *
8251 * @return The suggested minimum width of the view.
8252 */
8253 protected int getSuggestedMinimumWidth() {
8254 int suggestedMinWidth = mMinWidth;
8255
8256 if (mBGDrawable != null) {
8257 final int bgMinWidth = mBGDrawable.getMinimumWidth();
8258 if (suggestedMinWidth < bgMinWidth) {
8259 suggestedMinWidth = bgMinWidth;
8260 }
8261 }
8262
8263 return suggestedMinWidth;
8264 }
8265
8266 /**
8267 * Sets the minimum height of the view. It is not guaranteed the view will
8268 * be able to achieve this minimum height (for example, if its parent layout
8269 * constrains it with less available height).
8270 *
8271 * @param minHeight The minimum height the view will try to be.
8272 */
8273 public void setMinimumHeight(int minHeight) {
8274 mMinHeight = minHeight;
8275 }
8276
8277 /**
8278 * Sets the minimum width of the view. It is not guaranteed the view will
8279 * be able to achieve this minimum width (for example, if its parent layout
8280 * constrains it with less available width).
8281 *
8282 * @param minWidth The minimum width the view will try to be.
8283 */
8284 public void setMinimumWidth(int minWidth) {
8285 mMinWidth = minWidth;
8286 }
8287
8288 /**
8289 * Get the animation currently associated with this view.
8290 *
8291 * @return The animation that is currently playing or
8292 * scheduled to play for this view.
8293 */
8294 public Animation getAnimation() {
8295 return mCurrentAnimation;
8296 }
8297
8298 /**
8299 * Start the specified animation now.
8300 *
8301 * @param animation the animation to start now
8302 */
8303 public void startAnimation(Animation animation) {
8304 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
8305 setAnimation(animation);
8306 invalidate();
8307 }
8308
8309 /**
8310 * Cancels any animations for this view.
8311 */
8312 public void clearAnimation() {
Romain Guy305a2eb2010-02-09 11:30:44 -08008313 if (mCurrentAnimation != null) {
Romain Guyb4a107d2010-02-09 18:50:08 -08008314 mCurrentAnimation.detach();
Romain Guy305a2eb2010-02-09 11:30:44 -08008315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008316 mCurrentAnimation = null;
8317 }
8318
8319 /**
8320 * Sets the next animation to play for this view.
8321 * If you want the animation to play immediately, use
8322 * startAnimation. This method provides allows fine-grained
8323 * control over the start time and invalidation, but you
8324 * must make sure that 1) the animation has a start time set, and
8325 * 2) the view will be invalidated when the animation is supposed to
8326 * start.
8327 *
8328 * @param animation The next animation, or null.
8329 */
8330 public void setAnimation(Animation animation) {
8331 mCurrentAnimation = animation;
8332 if (animation != null) {
8333 animation.reset();
8334 }
8335 }
8336
8337 /**
8338 * Invoked by a parent ViewGroup to notify the start of the animation
8339 * currently associated with this view. If you override this method,
8340 * always call super.onAnimationStart();
8341 *
8342 * @see #setAnimation(android.view.animation.Animation)
8343 * @see #getAnimation()
8344 */
8345 protected void onAnimationStart() {
8346 mPrivateFlags |= ANIMATION_STARTED;
8347 }
8348
8349 /**
8350 * Invoked by a parent ViewGroup to notify the end of the animation
8351 * currently associated with this view. If you override this method,
8352 * always call super.onAnimationEnd();
8353 *
8354 * @see #setAnimation(android.view.animation.Animation)
8355 * @see #getAnimation()
8356 */
8357 protected void onAnimationEnd() {
8358 mPrivateFlags &= ~ANIMATION_STARTED;
8359 }
8360
8361 /**
8362 * Invoked if there is a Transform that involves alpha. Subclass that can
8363 * draw themselves with the specified alpha should return true, and then
8364 * respect that alpha when their onDraw() is called. If this returns false
8365 * then the view may be redirected to draw into an offscreen buffer to
8366 * fulfill the request, which will look fine, but may be slower than if the
8367 * subclass handles it internally. The default implementation returns false.
8368 *
8369 * @param alpha The alpha (0..255) to apply to the view's drawing
8370 * @return true if the view can draw with the specified alpha.
8371 */
8372 protected boolean onSetAlpha(int alpha) {
8373 return false;
8374 }
8375
8376 /**
8377 * This is used by the RootView to perform an optimization when
8378 * the view hierarchy contains one or several SurfaceView.
8379 * SurfaceView is always considered transparent, but its children are not,
8380 * therefore all View objects remove themselves from the global transparent
8381 * region (passed as a parameter to this function).
8382 *
8383 * @param region The transparent region for this ViewRoot (window).
8384 *
8385 * @return Returns true if the effective visibility of the view at this
8386 * point is opaque, regardless of the transparent region; returns false
8387 * if it is possible for underlying windows to be seen behind the view.
8388 *
8389 * {@hide}
8390 */
8391 public boolean gatherTransparentRegion(Region region) {
8392 final AttachInfo attachInfo = mAttachInfo;
8393 if (region != null && attachInfo != null) {
8394 final int pflags = mPrivateFlags;
8395 if ((pflags & SKIP_DRAW) == 0) {
8396 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
8397 // remove it from the transparent region.
8398 final int[] location = attachInfo.mTransparentLocation;
8399 getLocationInWindow(location);
8400 region.op(location[0], location[1], location[0] + mRight - mLeft,
8401 location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
8402 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
8403 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
8404 // exists, so we remove the background drawable's non-transparent
8405 // parts from this transparent region.
8406 applyDrawableToTransparentRegion(mBGDrawable, region);
8407 }
8408 }
8409 return true;
8410 }
8411
8412 /**
8413 * Play a sound effect for this view.
8414 *
8415 * <p>The framework will play sound effects for some built in actions, such as
8416 * clicking, but you may wish to play these effects in your widget,
8417 * for instance, for internal navigation.
8418 *
8419 * <p>The sound effect will only be played if sound effects are enabled by the user, and
8420 * {@link #isSoundEffectsEnabled()} is true.
8421 *
8422 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
8423 */
8424 public void playSoundEffect(int soundConstant) {
8425 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
8426 return;
8427 }
8428 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
8429 }
8430
8431 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008432 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07008433 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008434 * <p>Provide haptic feedback to the user for this view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008435 *
8436 * <p>The framework will provide haptic feedback for some built in actions,
8437 * such as long presses, but you may wish to provide feedback for your
8438 * own widget.
8439 *
8440 * <p>The feedback will only be performed if
8441 * {@link #isHapticFeedbackEnabled()} is true.
8442 *
8443 * @param feedbackConstant One of the constants defined in
8444 * {@link HapticFeedbackConstants}
8445 */
8446 public boolean performHapticFeedback(int feedbackConstant) {
8447 return performHapticFeedback(feedbackConstant, 0);
8448 }
8449
8450 /**
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008451 * BZZZTT!!1!
Romain Guy8506ab42009-06-11 17:35:47 -07008452 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07008453 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008454 *
8455 * @param feedbackConstant One of the constants defined in
8456 * {@link HapticFeedbackConstants}
8457 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
8458 */
8459 public boolean performHapticFeedback(int feedbackConstant, int flags) {
8460 if (mAttachInfo == null) {
8461 return false;
8462 }
8463 if ((flags&HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
8464 && !isHapticFeedbackEnabled()) {
8465 return false;
8466 }
8467 return mAttachInfo.mRootCallbacks.performHapticFeedback(
8468 feedbackConstant,
8469 (flags&HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
8470 }
8471
8472 /**
Dianne Hackbornffa42482009-09-23 22:20:11 -07008473 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
8474 * it is ever exposed at all.
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -07008475 * @hide
Dianne Hackbornffa42482009-09-23 22:20:11 -07008476 */
8477 public void onCloseSystemDialogs(String reason) {
8478 }
8479
8480 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 * Given a Drawable whose bounds have been set to draw into this view,
8482 * update a Region being computed for {@link #gatherTransparentRegion} so
8483 * that any non-transparent parts of the Drawable are removed from the
8484 * given transparent region.
8485 *
8486 * @param dr The Drawable whose transparency is to be applied to the region.
8487 * @param region A Region holding the current transparency information,
8488 * where any parts of the region that are set are considered to be
8489 * transparent. On return, this region will be modified to have the
8490 * transparency information reduced by the corresponding parts of the
8491 * Drawable that are not transparent.
8492 * {@hide}
8493 */
8494 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
8495 if (DBG) {
8496 Log.i("View", "Getting transparent region for: " + this);
8497 }
8498 final Region r = dr.getTransparentRegion();
8499 final Rect db = dr.getBounds();
8500 final AttachInfo attachInfo = mAttachInfo;
8501 if (r != null && attachInfo != null) {
8502 final int w = getRight()-getLeft();
8503 final int h = getBottom()-getTop();
8504 if (db.left > 0) {
8505 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
8506 r.op(0, 0, db.left, h, Region.Op.UNION);
8507 }
8508 if (db.right < w) {
8509 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
8510 r.op(db.right, 0, w, h, Region.Op.UNION);
8511 }
8512 if (db.top > 0) {
8513 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
8514 r.op(0, 0, w, db.top, Region.Op.UNION);
8515 }
8516 if (db.bottom < h) {
8517 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
8518 r.op(0, db.bottom, w, h, Region.Op.UNION);
8519 }
8520 final int[] location = attachInfo.mTransparentLocation;
8521 getLocationInWindow(location);
8522 r.translate(location[0], location[1]);
8523 region.op(r, Region.Op.INTERSECT);
8524 } else {
8525 region.op(db, Region.Op.DIFFERENCE);
8526 }
8527 }
8528
Adam Powelle14579b2009-12-16 18:39:52 -08008529 private void postCheckForLongClick(int delayOffset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 mHasPerformedLongPress = false;
8531
8532 if (mPendingCheckForLongPress == null) {
8533 mPendingCheckForLongPress = new CheckForLongPress();
8534 }
8535 mPendingCheckForLongPress.rememberWindowAttachCount();
Adam Powelle14579b2009-12-16 18:39:52 -08008536 postDelayed(mPendingCheckForLongPress,
8537 ViewConfiguration.getLongPressTimeout() - delayOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008538 }
8539
8540 private static int[] stateSetUnion(final int[] stateSet1,
8541 final int[] stateSet2) {
8542 final int stateSet1Length = stateSet1.length;
8543 final int stateSet2Length = stateSet2.length;
8544 final int[] newSet = new int[stateSet1Length + stateSet2Length];
8545 int k = 0;
8546 int i = 0;
8547 int j = 0;
8548 // This is a merge of the two input state sets and assumes that the
8549 // input sets are sorted by the order imposed by ViewDrawableStates.
8550 for (int viewState : R.styleable.ViewDrawableStates) {
8551 if (i < stateSet1Length && stateSet1[i] == viewState) {
8552 newSet[k++] = viewState;
8553 i++;
8554 } else if (j < stateSet2Length && stateSet2[j] == viewState) {
8555 newSet[k++] = viewState;
8556 j++;
8557 }
8558 if (k > 1) {
8559 assert(newSet[k - 1] > newSet[k - 2]);
8560 }
8561 }
8562 return newSet;
8563 }
8564
8565 /**
8566 * Inflate a view from an XML resource. This convenience method wraps the {@link
8567 * LayoutInflater} class, which provides a full range of options for view inflation.
8568 *
8569 * @param context The Context object for your activity or application.
8570 * @param resource The resource ID to inflate
8571 * @param root A view group that will be the parent. Used to properly inflate the
8572 * layout_* parameters.
8573 * @see LayoutInflater
8574 */
8575 public static View inflate(Context context, int resource, ViewGroup root) {
8576 LayoutInflater factory = LayoutInflater.from(context);
8577 return factory.inflate(resource, root);
8578 }
Adam Powell0b8bb422010-02-08 14:30:45 -08008579
8580 /**
8581 * Scroll the view with standard behavior for scrolling beyond the normal
8582 * content boundaries. Views that call this method should override
Adam Powell4886d402010-02-12 11:32:47 -08008583 * {@link #onOverscrolled(int, int, boolean, boolean)} to respond to the
8584 * results of an overscroll operation.
Adam Powell0b8bb422010-02-08 14:30:45 -08008585 *
8586 * Views can use this method to handle any touch or fling-based scrolling.
8587 *
8588 * @param deltaX Change in X in pixels
8589 * @param deltaY Change in Y in pixels
8590 * @param scrollX Current X scroll value in pixels before applying deltaX
8591 * @param scrollY Current Y scroll value in pixels before applying deltaY
8592 * @param scrollRangeX Maximum content scroll range along the X axis
8593 * @param scrollRangeY Maximum content scroll range along the Y axis
8594 * @param maxOverscrollX Number of pixels to overscroll by in either direction
8595 * along the X axis.
8596 * @param maxOverscrollY Number of pixels to overscroll by in either direction
8597 * along the Y axis.
8598 * @return true if scrolling was clamped to an overscroll boundary along either
8599 * axis, false otherwise.
8600 */
8601 protected boolean overscrollBy(int deltaX, int deltaY,
8602 int scrollX, int scrollY,
8603 int scrollRangeX, int scrollRangeY,
8604 int maxOverscrollX, int maxOverscrollY) {
Adam Powellc9fbaab2010-02-16 17:16:19 -08008605 final int overscrollMode = mOverscrollMode;
8606 final boolean canScrollHorizontal =
8607 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
8608 final boolean canScrollVertical =
8609 computeVerticalScrollRange() > computeVerticalScrollExtent();
8610 final boolean overscrollHorizontal = overscrollMode == OVERSCROLL_ALWAYS ||
8611 (overscrollMode == OVERSCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
8612 final boolean overscrollVertical = overscrollMode == OVERSCROLL_ALWAYS ||
8613 (overscrollMode == OVERSCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
Adam Powell0b8bb422010-02-08 14:30:45 -08008614
Adam Powellc9fbaab2010-02-16 17:16:19 -08008615 int newScrollX = scrollX + deltaX;
8616 if (overscrollHorizontal) {
8617 // Scale the scroll amount if we're in the dropoff zone
8618 final int dropoffX = maxOverscrollX / 2;
8619 final int dropoffLeft = -dropoffX;
8620 final int dropoffRight = dropoffX + scrollRangeX;
8621 if ((scrollX < dropoffLeft && deltaX < 0) ||
8622 (scrollX > dropoffRight && deltaX > 0)) {
8623 newScrollX = scrollX + deltaX / 2;
8624 } else {
8625 if (newScrollX > dropoffRight && deltaX > 0) {
8626 int extra = newScrollX - dropoffRight;
8627 newScrollX = dropoffRight + extra / 2;
8628 } else if (newScrollX < dropoffLeft && deltaX < 0) {
8629 int extra = newScrollX - dropoffLeft;
8630 newScrollX = dropoffLeft + extra / 2;
8631 }
Adam Powell0b8bb422010-02-08 14:30:45 -08008632 }
Adam Powellc9fbaab2010-02-16 17:16:19 -08008633 } else {
8634 maxOverscrollX = 0;
Adam Powell0b8bb422010-02-08 14:30:45 -08008635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008636
Adam Powellc9fbaab2010-02-16 17:16:19 -08008637 int newScrollY = scrollY + deltaY;
8638 if (overscrollVertical) {
8639 final int dropoffY = maxOverscrollY / 2;
8640 final int dropoffTop = -dropoffY;
8641 final int dropoffBottom = dropoffY + scrollRangeY;
8642 if ((scrollY < dropoffTop && deltaY < 0) ||
8643 (scrollY > dropoffBottom && deltaY > 0)) {
8644 newScrollY = scrollY + deltaY / 2;
8645 } else {
8646 if (newScrollY > dropoffBottom && deltaY > 0) {
8647 int extra = newScrollY - dropoffBottom;
8648 newScrollY = dropoffBottom + extra / 2;
8649 } else if (newScrollY < dropoffTop && deltaY < 0) {
8650 int extra = newScrollY - dropoffTop;
8651 newScrollY = dropoffTop + extra / 2;
8652 }
8653 }
8654 } else {
8655 maxOverscrollY = 0;
8656 }
8657
Adam Powell0b8bb422010-02-08 14:30:45 -08008658 // Clamp values if at the limits and record
8659 final int left = -maxOverscrollX;
8660 final int right = maxOverscrollX + scrollRangeX;
8661 final int top = -maxOverscrollY;
8662 final int bottom = maxOverscrollY + scrollRangeY;
8663
8664 boolean clampedX = false;
8665 if (newScrollX > right) {
8666 newScrollX = right;
8667 clampedX = true;
8668 } else if (newScrollX < left) {
8669 newScrollX = left;
8670 clampedX = true;
8671 }
8672
8673 boolean clampedY = false;
8674 if (newScrollY > bottom) {
8675 newScrollY = bottom;
8676 clampedY = true;
8677 } else if (newScrollY < top) {
8678 newScrollY = top;
8679 clampedY = true;
8680 }
8681
8682 // Bump the device with some haptic feedback if we're at the edge
8683 // and didn't start there.
Adam Powellc9fbaab2010-02-16 17:16:19 -08008684 if ((overscrollHorizontal && clampedX && scrollX != left && scrollX != right) ||
8685 (overscrollVertical && clampedY && scrollY != top && scrollY != bottom)) {
Adam Powell0b8bb422010-02-08 14:30:45 -08008686 performHapticFeedback(HapticFeedbackConstants.SCROLL_BARRIER);
8687 }
8688
8689 onOverscrolled(newScrollX, newScrollY, clampedX, clampedY);
8690
8691 return clampedX || clampedY;
8692 }
8693
8694 /**
8695 * Called by {@link #overscrollBy(int, int, int, int, int, int, int, int)} to
8696 * respond to the results of an overscroll operation.
8697 *
8698 * @param scrollX New X scroll value in pixels
8699 * @param scrollY New Y scroll value in pixels
8700 * @param clampedX True if scrollX was clamped to an overscroll boundary
8701 * @param clampedY True if scrollY was clamped to an overscroll boundary
8702 */
8703 protected void onOverscrolled(int scrollX, int scrollY,
8704 boolean clampedX, boolean clampedY) {
8705 // Intentionally empty.
8706 }
8707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008708 /**
8709 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
8710 * Each MeasureSpec represents a requirement for either the width or the height.
8711 * A MeasureSpec is comprised of a size and a mode. There are three possible
8712 * modes:
8713 * <dl>
8714 * <dt>UNSPECIFIED</dt>
8715 * <dd>
8716 * The parent has not imposed any constraint on the child. It can be whatever size
8717 * it wants.
8718 * </dd>
8719 *
8720 * <dt>EXACTLY</dt>
8721 * <dd>
8722 * The parent has determined an exact size for the child. The child is going to be
8723 * given those bounds regardless of how big it wants to be.
8724 * </dd>
8725 *
8726 * <dt>AT_MOST</dt>
8727 * <dd>
8728 * The child can be as large as it wants up to the specified size.
8729 * </dd>
8730 * </dl>
8731 *
8732 * MeasureSpecs are implemented as ints to reduce object allocation. This class
8733 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
8734 */
8735 public static class MeasureSpec {
8736 private static final int MODE_SHIFT = 30;
8737 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
8738
8739 /**
8740 * Measure specification mode: The parent has not imposed any constraint
8741 * on the child. It can be whatever size it wants.
8742 */
8743 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
8744
8745 /**
8746 * Measure specification mode: The parent has determined an exact size
8747 * for the child. The child is going to be given those bounds regardless
8748 * of how big it wants to be.
8749 */
8750 public static final int EXACTLY = 1 << MODE_SHIFT;
8751
8752 /**
8753 * Measure specification mode: The child can be as large as it wants up
8754 * to the specified size.
8755 */
8756 public static final int AT_MOST = 2 << MODE_SHIFT;
8757
8758 /**
8759 * Creates a measure specification based on the supplied size and mode.
8760 *
8761 * The mode must always be one of the following:
8762 * <ul>
8763 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
8764 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
8765 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
8766 * </ul>
8767 *
8768 * @param size the size of the measure specification
8769 * @param mode the mode of the measure specification
8770 * @return the measure specification based on size and mode
8771 */
8772 public static int makeMeasureSpec(int size, int mode) {
8773 return size + mode;
8774 }
8775
8776 /**
8777 * Extracts the mode from the supplied measure specification.
8778 *
8779 * @param measureSpec the measure specification to extract the mode from
8780 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
8781 * {@link android.view.View.MeasureSpec#AT_MOST} or
8782 * {@link android.view.View.MeasureSpec#EXACTLY}
8783 */
8784 public static int getMode(int measureSpec) {
8785 return (measureSpec & MODE_MASK);
8786 }
8787
8788 /**
8789 * Extracts the size from the supplied measure specification.
8790 *
8791 * @param measureSpec the measure specification to extract the size from
8792 * @return the size in pixels defined in the supplied measure specification
8793 */
8794 public static int getSize(int measureSpec) {
8795 return (measureSpec & ~MODE_MASK);
8796 }
8797
8798 /**
8799 * Returns a String representation of the specified measure
8800 * specification.
8801 *
8802 * @param measureSpec the measure specification to convert to a String
8803 * @return a String with the following format: "MeasureSpec: MODE SIZE"
8804 */
8805 public static String toString(int measureSpec) {
8806 int mode = getMode(measureSpec);
8807 int size = getSize(measureSpec);
8808
8809 StringBuilder sb = new StringBuilder("MeasureSpec: ");
8810
8811 if (mode == UNSPECIFIED)
8812 sb.append("UNSPECIFIED ");
8813 else if (mode == EXACTLY)
8814 sb.append("EXACTLY ");
8815 else if (mode == AT_MOST)
8816 sb.append("AT_MOST ");
8817 else
8818 sb.append(mode).append(" ");
8819
8820 sb.append(size);
8821 return sb.toString();
8822 }
8823 }
8824
8825 class CheckForLongPress implements Runnable {
8826
8827 private int mOriginalWindowAttachCount;
8828
8829 public void run() {
The Android Open Source Project10592532009-03-18 17:39:46 -07008830 if (isPressed() && (mParent != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008831 && mOriginalWindowAttachCount == mWindowAttachCount) {
8832 if (performLongClick()) {
8833 mHasPerformedLongPress = true;
8834 }
8835 }
8836 }
8837
8838 public void rememberWindowAttachCount() {
8839 mOriginalWindowAttachCount = mWindowAttachCount;
8840 }
8841 }
Adam Powelle14579b2009-12-16 18:39:52 -08008842
8843 private final class CheckForTap implements Runnable {
8844 public void run() {
8845 mPrivateFlags &= ~PREPRESSED;
8846 mPrivateFlags |= PRESSED;
8847 refreshDrawableState();
8848 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
8849 postCheckForLongClick(ViewConfiguration.getTapTimeout());
8850 }
8851 }
8852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853
8854 /**
8855 * Interface definition for a callback to be invoked when a key event is
8856 * dispatched to this view. The callback will be invoked before the key
8857 * event is given to the view.
8858 */
8859 public interface OnKeyListener {
8860 /**
8861 * Called when a key is dispatched to a view. This allows listeners to
8862 * get a chance to respond before the target view.
8863 *
8864 * @param v The view the key has been dispatched to.
8865 * @param keyCode The code for the physical key that was pressed
8866 * @param event The KeyEvent object containing full information about
8867 * the event.
8868 * @return True if the listener has consumed the event, false otherwise.
8869 */
8870 boolean onKey(View v, int keyCode, KeyEvent event);
8871 }
8872
8873 /**
8874 * Interface definition for a callback to be invoked when a touch event is
8875 * dispatched to this view. The callback will be invoked before the touch
8876 * event is given to the view.
8877 */
8878 public interface OnTouchListener {
8879 /**
8880 * Called when a touch event is dispatched to a view. This allows listeners to
8881 * get a chance to respond before the target view.
8882 *
8883 * @param v The view the touch event has been dispatched to.
8884 * @param event The MotionEvent object containing full information about
8885 * the event.
8886 * @return True if the listener has consumed the event, false otherwise.
8887 */
8888 boolean onTouch(View v, MotionEvent event);
8889 }
8890
8891 /**
8892 * Interface definition for a callback to be invoked when a view has been clicked and held.
8893 */
8894 public interface OnLongClickListener {
8895 /**
8896 * Called when a view has been clicked and held.
8897 *
8898 * @param v The view that was clicked and held.
8899 *
8900 * return True if the callback consumed the long click, false otherwise
8901 */
8902 boolean onLongClick(View v);
8903 }
8904
8905 /**
8906 * Interface definition for a callback to be invoked when the focus state of
8907 * a view changed.
8908 */
8909 public interface OnFocusChangeListener {
8910 /**
8911 * Called when the focus state of a view has changed.
8912 *
8913 * @param v The view whose state has changed.
8914 * @param hasFocus The new focus state of v.
8915 */
8916 void onFocusChange(View v, boolean hasFocus);
8917 }
8918
8919 /**
8920 * Interface definition for a callback to be invoked when a view is clicked.
8921 */
8922 public interface OnClickListener {
8923 /**
8924 * Called when a view has been clicked.
8925 *
8926 * @param v The view that was clicked.
8927 */
8928 void onClick(View v);
8929 }
8930
8931 /**
8932 * Interface definition for a callback to be invoked when the context menu
8933 * for this view is being built.
8934 */
8935 public interface OnCreateContextMenuListener {
8936 /**
8937 * Called when the context menu for this view is being built. It is not
8938 * safe to hold onto the menu after this method returns.
8939 *
8940 * @param menu The context menu that is being built
8941 * @param v The view for which the context menu is being built
8942 * @param menuInfo Extra information about the item for which the
8943 * context menu should be shown. This information will vary
8944 * depending on the class of v.
8945 */
8946 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
8947 }
8948
8949 private final class UnsetPressedState implements Runnable {
8950 public void run() {
8951 setPressed(false);
8952 }
8953 }
8954
8955 /**
8956 * Base class for derived classes that want to save and restore their own
8957 * state in {@link android.view.View#onSaveInstanceState()}.
8958 */
8959 public static class BaseSavedState extends AbsSavedState {
8960 /**
8961 * Constructor used when reading from a parcel. Reads the state of the superclass.
8962 *
8963 * @param source
8964 */
8965 public BaseSavedState(Parcel source) {
8966 super(source);
8967 }
8968
8969 /**
8970 * Constructor called by derived classes when creating their SavedState objects
8971 *
8972 * @param superState The state of the superclass of this view
8973 */
8974 public BaseSavedState(Parcelable superState) {
8975 super(superState);
8976 }
8977
8978 public static final Parcelable.Creator<BaseSavedState> CREATOR =
8979 new Parcelable.Creator<BaseSavedState>() {
8980 public BaseSavedState createFromParcel(Parcel in) {
8981 return new BaseSavedState(in);
8982 }
8983
8984 public BaseSavedState[] newArray(int size) {
8985 return new BaseSavedState[size];
8986 }
8987 };
8988 }
8989
8990 /**
8991 * A set of information given to a view when it is attached to its parent
8992 * window.
8993 */
8994 static class AttachInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008995 interface Callbacks {
8996 void playSoundEffect(int effectId);
8997 boolean performHapticFeedback(int effectId, boolean always);
8998 }
8999
9000 /**
9001 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
9002 * to a Handler. This class contains the target (View) to invalidate and
9003 * the coordinates of the dirty rectangle.
9004 *
9005 * For performance purposes, this class also implements a pool of up to
9006 * POOL_LIMIT objects that get reused. This reduces memory allocations
9007 * whenever possible.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009008 */
Romain Guyd928d682009-03-31 17:52:16 -07009009 static class InvalidateInfo implements Poolable<InvalidateInfo> {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009010 private static final int POOL_LIMIT = 10;
Romain Guy2e9bbce2009-04-01 10:40:10 -07009011 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
9012 Pools.finitePool(new PoolableManager<InvalidateInfo>() {
Romain Guyd928d682009-03-31 17:52:16 -07009013 public InvalidateInfo newInstance() {
9014 return new InvalidateInfo();
9015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009016
Romain Guyd928d682009-03-31 17:52:16 -07009017 public void onAcquired(InvalidateInfo element) {
9018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009019
Romain Guyd928d682009-03-31 17:52:16 -07009020 public void onReleased(InvalidateInfo element) {
9021 }
9022 }, POOL_LIMIT)
9023 );
9024
9025 private InvalidateInfo mNext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009026
9027 View target;
9028
9029 int left;
9030 int top;
9031 int right;
9032 int bottom;
9033
Romain Guyd928d682009-03-31 17:52:16 -07009034 public void setNextPoolable(InvalidateInfo element) {
9035 mNext = element;
9036 }
9037
9038 public InvalidateInfo getNextPoolable() {
9039 return mNext;
9040 }
9041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009042 static InvalidateInfo acquire() {
Romain Guyd928d682009-03-31 17:52:16 -07009043 return sPool.acquire();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009044 }
9045
9046 void release() {
Romain Guyd928d682009-03-31 17:52:16 -07009047 sPool.release(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009048 }
9049 }
9050
9051 final IWindowSession mSession;
9052
9053 final IWindow mWindow;
9054
9055 final IBinder mWindowToken;
9056
9057 final Callbacks mRootCallbacks;
9058
9059 /**
9060 * The top view of the hierarchy.
9061 */
9062 View mRootView;
Romain Guy8506ab42009-06-11 17:35:47 -07009063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009064 IBinder mPanelParentWindowToken;
9065 Surface mSurface;
9066
9067 /**
Romain Guy8506ab42009-06-11 17:35:47 -07009068 * Scale factor used by the compatibility mode
9069 */
9070 float mApplicationScale;
9071
9072 /**
9073 * Indicates whether the application is in compatibility mode
9074 */
9075 boolean mScalingRequired;
9076
9077 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078 * Left position of this view's window
9079 */
9080 int mWindowLeft;
9081
9082 /**
9083 * Top position of this view's window
9084 */
9085 int mWindowTop;
9086
9087 /**
Romain Guy35b38ce2009-10-07 13:38:55 -07009088 * Indicates whether the window is translucent/transparent
9089 */
9090 boolean mTranslucentWindow;
9091
9092 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009093 * For windows that are full-screen but using insets to layout inside
9094 * of the screen decorations, these are the current insets for the
9095 * content of the window.
9096 */
9097 final Rect mContentInsets = new Rect();
9098
9099 /**
9100 * For windows that are full-screen but using insets to layout inside
9101 * of the screen decorations, these are the current insets for the
9102 * actual visible parts of the window.
9103 */
9104 final Rect mVisibleInsets = new Rect();
9105
9106 /**
9107 * The internal insets given by this window. This value is
9108 * supplied by the client (through
9109 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
9110 * be given to the window manager when changed to be used in laying
9111 * out windows behind it.
9112 */
9113 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
9114 = new ViewTreeObserver.InternalInsetsInfo();
9115
9116 /**
9117 * All views in the window's hierarchy that serve as scroll containers,
9118 * used to determine if the window can be resized or must be panned
9119 * to adjust for a soft input area.
9120 */
9121 final ArrayList<View> mScrollContainers = new ArrayList<View>();
9122
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07009123 final KeyEvent.DispatcherState mKeyDispatchState
9124 = new KeyEvent.DispatcherState();
9125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009126 /**
9127 * Indicates whether the view's window currently has the focus.
9128 */
9129 boolean mHasWindowFocus;
9130
9131 /**
9132 * The current visibility of the window.
9133 */
9134 int mWindowVisibility;
9135
9136 /**
9137 * Indicates the time at which drawing started to occur.
9138 */
9139 long mDrawingTime;
9140
9141 /**
Romain Guy5bcdff42009-05-14 21:27:18 -07009142 * Indicates whether or not ignoring the DIRTY_MASK flags.
9143 */
9144 boolean mIgnoreDirtyState;
9145
9146 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009147 * Indicates whether the view's window is currently in touch mode.
9148 */
9149 boolean mInTouchMode;
9150
9151 /**
9152 * Indicates that ViewRoot should trigger a global layout change
9153 * the next time it performs a traversal
9154 */
9155 boolean mRecomputeGlobalAttributes;
9156
9157 /**
9158 * Set to true when attributes (like mKeepScreenOn) need to be
9159 * recomputed.
9160 */
9161 boolean mAttributesChanged;
9162
9163 /**
9164 * Set during a traveral if any views want to keep the screen on.
9165 */
9166 boolean mKeepScreenOn;
9167
9168 /**
9169 * Set if the visibility of any views has changed.
9170 */
9171 boolean mViewVisibilityChanged;
9172
9173 /**
9174 * Set to true if a view has been scrolled.
9175 */
9176 boolean mViewScrollChanged;
9177
9178 /**
9179 * Global to the view hierarchy used as a temporary for dealing with
9180 * x/y points in the transparent region computations.
9181 */
9182 final int[] mTransparentLocation = new int[2];
9183
9184 /**
9185 * Global to the view hierarchy used as a temporary for dealing with
9186 * x/y points in the ViewGroup.invalidateChild implementation.
9187 */
9188 final int[] mInvalidateChildLocation = new int[2];
9189
9190 /**
9191 * The view tree observer used to dispatch global events like
9192 * layout, pre-draw, touch mode change, etc.
9193 */
9194 final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
9195
9196 /**
9197 * A Canvas used by the view hierarchy to perform bitmap caching.
9198 */
9199 Canvas mCanvas;
9200
9201 /**
9202 * A Handler supplied by a view's {@link android.view.ViewRoot}. This
9203 * handler can be used to pump events in the UI events queue.
9204 */
9205 final Handler mHandler;
9206
9207 /**
9208 * Identifier for messages requesting the view to be invalidated.
9209 * Such messages should be sent to {@link #mHandler}.
9210 */
9211 static final int INVALIDATE_MSG = 0x1;
9212
9213 /**
9214 * Identifier for messages requesting the view to invalidate a region.
9215 * Such messages should be sent to {@link #mHandler}.
9216 */
9217 static final int INVALIDATE_RECT_MSG = 0x2;
9218
9219 /**
9220 * Temporary for use in computing invalidate rectangles while
9221 * calling up the hierarchy.
9222 */
9223 final Rect mTmpInvalRect = new Rect();
svetoslavganov75986cf2009-05-14 22:28:01 -07009224
9225 /**
9226 * Temporary list for use in collecting focusable descendents of a view.
9227 */
9228 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
9229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009230 /**
9231 * Creates a new set of attachment information with the specified
9232 * events handler and thread.
9233 *
9234 * @param handler the events handler the view must use
9235 */
9236 AttachInfo(IWindowSession session, IWindow window,
9237 Handler handler, Callbacks effectPlayer) {
9238 mSession = session;
9239 mWindow = window;
9240 mWindowToken = window.asBinder();
9241 mHandler = handler;
9242 mRootCallbacks = effectPlayer;
9243 }
9244 }
9245
9246 /**
9247 * <p>ScrollabilityCache holds various fields used by a View when scrolling
9248 * is supported. This avoids keeping too many unused fields in most
9249 * instances of View.</p>
9250 */
Mike Cleronf116bf82009-09-27 19:14:12 -07009251 private static class ScrollabilityCache implements Runnable {
9252
9253 /**
9254 * Scrollbars are not visible
9255 */
9256 public static final int OFF = 0;
9257
9258 /**
9259 * Scrollbars are visible
9260 */
9261 public static final int ON = 1;
9262
9263 /**
9264 * Scrollbars are fading away
9265 */
9266 public static final int FADING = 2;
9267
9268 public boolean fadeScrollBars;
9269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009270 public int fadingEdgeLength;
Mike Cleronf116bf82009-09-27 19:14:12 -07009271 public int scrollBarDefaultDelayBeforeFade;
9272 public int scrollBarFadeDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009273
9274 public int scrollBarSize;
9275 public ScrollBarDrawable scrollBar;
Mike Cleronf116bf82009-09-27 19:14:12 -07009276 public float[] interpolatorValues;
9277 public View host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009278
9279 public final Paint paint;
9280 public final Matrix matrix;
9281 public Shader shader;
9282
Mike Cleronf116bf82009-09-27 19:14:12 -07009283 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
9284
9285 private final float[] mOpaque = {255.0f};
9286 private final float[] mTransparent = {0.0f};
9287
9288 /**
9289 * When fading should start. This time moves into the future every time
9290 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
9291 */
9292 public long fadeStartTime;
9293
9294
9295 /**
9296 * The current state of the scrollbars: ON, OFF, or FADING
9297 */
9298 public int state = OFF;
9299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009300 private int mLastColor;
9301
Mike Cleronf116bf82009-09-27 19:14:12 -07009302 public ScrollabilityCache(ViewConfiguration configuration, View host) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
9304 scrollBarSize = configuration.getScaledScrollBarSize();
Romain Guy35b38ce2009-10-07 13:38:55 -07009305 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
9306 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009307
9308 paint = new Paint();
9309 matrix = new Matrix();
9310 // use use a height of 1, and then wack the matrix each time we
9311 // actually use it.
9312 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -07009313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009314 paint.setShader(shader);
9315 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
Mike Cleronf116bf82009-09-27 19:14:12 -07009316 this.host = host;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 }
Romain Guy8506ab42009-06-11 17:35:47 -07009318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009319 public void setFadeColor(int color) {
9320 if (color != 0 && color != mLastColor) {
9321 mLastColor = color;
9322 color |= 0xFF000000;
Romain Guy8506ab42009-06-11 17:35:47 -07009323
Romain Guye55e1a72009-08-27 10:42:26 -07009324 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
9325 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
Romain Guy8506ab42009-06-11 17:35:47 -07009326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009327 paint.setShader(shader);
9328 // Restore the default transfer mode (src_over)
9329 paint.setXfermode(null);
9330 }
9331 }
Mike Cleronf116bf82009-09-27 19:14:12 -07009332
9333 public void run() {
Mike Cleron3ecd58c2009-09-28 11:39:02 -07009334 long now = AnimationUtils.currentAnimationTimeMillis();
Mike Cleronf116bf82009-09-27 19:14:12 -07009335 if (now >= fadeStartTime) {
9336
9337 // the animation fades the scrollbars out by changing
9338 // the opacity (alpha) from fully opaque to fully
9339 // transparent
9340 int nextFrame = (int) now;
9341 int framesCount = 0;
9342
9343 Interpolator interpolator = scrollBarInterpolator;
9344
9345 // Start opaque
9346 interpolator.setKeyFrame(framesCount++, nextFrame, mOpaque);
9347
9348 // End transparent
9349 nextFrame += scrollBarFadeDuration;
9350 interpolator.setKeyFrame(framesCount, nextFrame, mTransparent);
9351
9352 state = FADING;
9353
9354 // Kick off the fade animation
9355 host.invalidate();
9356 }
9357 }
9358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009359 }
9360}