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